From 2240d4effebe99c755db5315d13b658c31a17ee1 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 12 Nov 2026 01:40:42 +0700 Subject: [PATCH 001/160] chore(release): reconcile 0.16.0-beta.2 into main (#9422) * docs(changelog): describe 0.16.0-beta.2 Folds the nine user-facing changes merged since beta.1 into the series entry and renames its heading. Highlights are unchanged. * chore(release): cut 0.16.0-beta.2 --- CHANGELOG.md | 11 ++++- CHANGELOG.zh-CN.md | 11 ++++- package-lock.json | 56 ++++++++++++------------ package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 ++-- packages/client/package.json | 6 +-- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 ++--- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++--- packages/website/package.json | 2 +- plugins/package.json | 2 +- 16 files changed, 75 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a66fde2adf..f2112e386a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 0.16.0-beta.1 - 2026-11-10 +## 0.16.0-beta.2 - 2026-11-11 - **Background tasks:** Paseo now shows the background tasks an agent is running, such as shells and monitors, above the composer, with a Stop button for each. Works with Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162) by [@fxlelouarn](https://github.com/fxlelouarn)) - **Plugin sidebar views:** A plugin can replace the sidebar's content with its own layout of workspaces, agents, projects and terminals across every connected host. Pick the view per device under Settings → Sidebar; Paseo's sidebar header and footer stay in place. ([#8906](https://github.com/getpaseo/paseo/pull/8906)) @@ -30,6 +30,8 @@ - Changed the slash command menu to show loading and error states with Retry, and to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905)) - Changed the workspace header and tabs to switch to compact controls when Explorer or a split pane narrows the workspace ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao)) - Changed sending a message to a Pi agent whose process has exited to fail immediately with an instruction to reload the agent ([#8718](https://github.com/getpaseo/paseo/pull/8718)) +- Changed Rename workspace in the sidebar on desktop and wide web layouts to edit the title in place instead of opening a dialog ([#9280](https://github.com/getpaseo/paseo/pull/9280)) +- Changed What's new and the website changelog to show a release's highlights first, with the full list behind Show all changes ([#9281](https://github.com/getpaseo/paseo/pull/9281)) ### Fixed @@ -37,6 +39,7 @@ - Fixed chats with short collapsed turns opening with empty space until you scrolled ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083)) - Fixed Collapse turns hiding an earlier reply inside a later turn's summary line after an idle Claude, Codex or OpenCode agent was resumed ([#9098](https://github.com/getpaseo/paseo/pull/9098)) - Fixed the missing space between a prompt and the reply or collapsed-turn summary line below it ([#9009](https://github.com/getpaseo/paseo/pull/9009)) +- Fixed a long user message showing without its fade and Show more for one frame when a chat opened ([#9302](https://github.com/getpaseo/paseo/pull/9302)) - Fixed Markdown tables showing as literal pipes when written directly below a paragraph with no blank line ([#8485](https://github.com/getpaseo/paseo/pull/8485) by [@ragokan](https://github.com/ragokan), [@suk-6](https://github.com/suk-6), [@thsrite](https://github.com/thsrite)) - Fixed linked badge images that share a line with text rendering as full-width blocks on web and desktop ([#8530](https://github.com/getpaseo/paseo/pull/8530)) - Fixed View diagram opening fullscreen instead of returning to the inline Mermaid diagram after View source ([#8932](https://github.com/getpaseo/paseo/pull/8932) by [@luoph](https://github.com/luoph)) @@ -48,6 +51,7 @@ - Fixed Add host sending you to Settings from the sidebar and New workspace ([#8512](https://github.com/getpaseo/paseo/pull/8512)) - Fixed a failed agent's red dot and Failed grouping staying in the sidebar after opening the agent or choosing Mark as read ([#8831](https://github.com/getpaseo/paseo/pull/8831)) - Fixed a workspace's unread indicator staying on after it was cleared while the agent's runtime was closed ([#9087](https://github.com/getpaseo/paseo/pull/9087)) +- Fixed unarchiving a workspace not restoring the agents that were archived with it ([#9210](https://github.com/getpaseo/paseo/pull/9210)) - Fixed the context window popover closing by itself whenever the chat scrolled during a streaming reply ([#8742](https://github.com/getpaseo/paseo/pull/8742) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed the sidebar usage summary updating only when Usage was opened ([#7806](https://github.com/getpaseo/paseo/pull/7806) by [@ragokan](https://github.com/ragokan)) - Fixed tooltips and menus above their trigger briefly covering it on Android when their content grew after opening ([#9247](https://github.com/getpaseo/paseo/pull/9247)) @@ -73,11 +77,13 @@ - Fixed Codex "Apply file changes" approvals showing no file name or diff before you accept ([#8585](https://github.com/getpaseo/paseo/pull/8585) by [@ragokan](https://github.com/ragokan)) - Fixed the timeline showing only the first file's diff when Codex edits several files in one patch ([#8613](https://github.com/getpaseo/paseo/pull/8613) by [@ragokan](https://github.com/ragokan)) - Fixed Codex session discovery and startup intermittently failing with a SQLite initialization error when several Codex operations start at once ([#9008](https://github.com/getpaseo/paseo/pull/9008) by [@colonelpanic8](https://github.com/colonelpanic8), [@michaelmwu](https://github.com/michaelmwu)) +- Fixed Codex reconnect attempts and warnings not appearing in the timeline ([#9370](https://github.com/getpaseo/paseo/pull/9370) by [@whatamelon](https://github.com/whatamelon)) - Fixed OpenCode conversations that were mid-turn during a daemon restart showing idle and ignoring Stop ([#8698](https://github.com/getpaseo/paseo/pull/8698)) - Fixed OpenCode being told you declined a tool call when you sent a message while its approval was pending ([#8477](https://github.com/getpaseo/paseo/pull/8477)) - Fixed reopened Pi conversations missing the messages from before a context compaction ([#8523](https://github.com/getpaseo/paseo/pull/8523)) - Fixed archived Pi chats failing to open with `spawn pi ENOENT` after their working folder was removed ([#8442](https://github.com/getpaseo/paseo/pull/8442) by [@DAnaeto](https://github.com/DAnaeto)) - Fixed reading an archived Pi chat leaving a Pi process running when idle runtime cleanup is disabled ([#8554](https://github.com/getpaseo/paseo/pull/8554) by [@rylwin](https://github.com/rylwin)) +- Fixed resumed pi-subagents runs missing from the Subagents track ([#9261](https://github.com/getpaseo/paseo/pull/9261) by [@xxachangxx](https://github.com/xxachangxx)) - Fixed a prompt sent to an ACP agent whose process has exited staying in running forever instead of failing with an error ([#8406](https://github.com/getpaseo/paseo/pull/8406) by [@DAnaeto](https://github.com/DAnaeto)) - Fixed an ACP agent staying stuck on "waiting for permission" after it abandoned an approval request and ended its turn ([#8548](https://github.com/getpaseo/paseo/pull/8548) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed changing the mode of an ACP agent failing with `invalid_params` after the agent sends a config update ([#8912](https://github.com/getpaseo/paseo/pull/8912) by [@a-sh](https://github.com/a-sh)) @@ -109,10 +115,13 @@ ### Plugins - Added plugin subscriptions, which stream live events from the daemon to a plugin's panels, and binary (`Uint8Array`) payloads for plugin RPCs and events ([#8527](https://github.com/getpaseo/paseo/pull/8527)) +- Added an agent's background task count (`backgroundWork.count`) and `background` flag to plugin agent snapshots, and a `background` flag to agent hooks ([#9362](https://github.com/getpaseo/paseo/pull/9362)) - Changed Settings → Plugins to open a plugin's settings from a cog button, with a tab per settings screen ([#8675](https://github.com/getpaseo/paseo/pull/8675)) - Added an upward chevron to plugin composer pills that open a menu or popover ([#8673](https://github.com/getpaseo/paseo/pull/8673)) - Changed daemon startup to launch configured plugins concurrently instead of one after another ([#8427](https://github.com/getpaseo/paseo/pull/8427) by [@DAnaeto](https://github.com/DAnaeto)) - Fixed registry plugin installs failing with "npm artifact changed since review" when the host's npm uses a registry mirror ([#8756](https://github.com/getpaseo/paseo/pull/8756) by [@tlipoca9](https://github.com/tlipoca9)) +- Fixed a plugin the daemon terminated for an invalid message staying listed with no exit reported ([#9285](https://github.com/getpaseo/paseo/pull/9285) by [@Brandon168](https://github.com/Brandon168)) +- Fixed ACP provider plugins dropping the token usage an agent reports in its prompt response ([#9396](https://github.com/getpaseo/paseo/pull/9396) by [@Myasuka](https://github.com/Myasuka)) - Fixed the published `@getpaseo/*` npm packages declaring no license; they now declare Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816) by [@mdlawson](https://github.com/mdlawson), [@ragokan](https://github.com/ragokan)) - Fixed forking from an earlier reply failing with "This checkpoint changed after it was created" after a plugin updated one of its timeline cards ([#8746](https://github.com/getpaseo/paseo/pull/8746) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) - Fixed Collapse turns leaving a turn open, or folding to an earlier reply, when a plugin renders the final reply ([#8811](https://github.com/getpaseo/paseo/pull/8811) by [@geoqiao](https://github.com/geoqiao)) diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index fd91d002ab..a3f7fbfa3f 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,6 +1,6 @@ # Changelog -## 0.16.0-beta.1 - 2026-11-10 +## 0.16.0-beta.2 - 2026-11-11 - **后台任务**:Paseo 现在会在 Composer 上方显示 Agent 正在运行的后台任务,例如 shell 和监视器,每项都带“停止”按钮。支持 Claude Code、Codex 和 OpenCode v2。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162),贡献者:[@fxlelouarn](https://github.com/fxlelouarn)) - **插件侧边栏视图**:插件可以用自己的布局替换侧边栏内容,展示所有已连接主机上的工作区、Agent、项目和终端。在“设置 → 侧边栏”中为每台设备选择视图;Paseo 的侧边栏页眉和页脚保持不变。 ([#8906](https://github.com/getpaseo/paseo/pull/8906)) @@ -30,6 +30,8 @@ - 斜杠命令菜单现在显示加载和错误状态并提供“重试”,且不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905)) - 文件浏览器(Explorer)或分屏使工作区变窄时,工作区页眉和标签页改用紧凑控件 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao)) - 向进程已退出的 Pi Agent 发送消息时立即失败,并提示重新加载该 Agent ([#8718](https://github.com/getpaseo/paseo/pull/8718)) +- 在桌面端和宽屏网页布局中,侧边栏的“重命名 workspace”改为在原处编辑标题,不再打开对话框 ([#9280](https://github.com/getpaseo/paseo/pull/9280)) +- “更新内容”和网站更新日志改为先显示每个版本的亮点,完整列表收在“显示全部变更”之后 ([#9281](https://github.com/getpaseo/paseo/pull/9281)) ### 修复 @@ -37,6 +39,7 @@ - 修复包含较短折叠轮次的聊天打开时留有空白、需滚动后才填满的问题 ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083)) - 修复空闲的 Claude、Codex 或 OpenCode Agent 恢复后,“折叠轮次”把较早的回复藏进后一轮摘要行的问题 ([#9098](https://github.com/getpaseo/paseo/pull/9098)) - 修复提示词与其下方的回复或折叠轮次摘要行之间缺少间距的问题 ([#9009](https://github.com/getpaseo/paseo/pull/9009)) +- 修复聊天打开时,较长的用户消息有一帧不显示渐隐效果和“展开”的问题 ([#9302](https://github.com/getpaseo/paseo/pull/9302)) - 修复紧跟在段落之后、中间没有空行的 Markdown 表格显示为原始竖线的问题 ([#8485](https://github.com/getpaseo/paseo/pull/8485),贡献者:[@ragokan](https://github.com/ragokan)、[@suk-6](https://github.com/suk-6)、[@thsrite](https://github.com/thsrite)) - 修复网页版和桌面端中与文字同行的带链接徽章图片被渲染成整行宽度的问题 ([#8530](https://github.com/getpaseo/paseo/pull/8530)) - 修复“查看源码”后点击“查看图表”会打开全屏、而不是回到内联 Mermaid 图表的问题 ([#8932](https://github.com/getpaseo/paseo/pull/8932),贡献者:[@luoph](https://github.com/luoph)) @@ -48,6 +51,7 @@ - 修复从侧边栏和“新建工作区”点击“添加主机”会跳转到“设置”的问题 ([#8512](https://github.com/getpaseo/paseo/pull/8512)) - 修复打开失败的 Agent 或选择 Mark as read 后,其红点和“失败”分组仍留在侧边栏的问题 ([#8831](https://github.com/getpaseo/paseo/pull/8831)) - 修复在 Agent 运行时已关闭的情况下清除未读后,工作区的未读指示仍然亮着的问题 ([#9087](https://github.com/getpaseo/paseo/pull/9087)) +- 修复取消归档工作区时未恢复随之归档的 Agent 的问题 ([#9210](https://github.com/getpaseo/paseo/pull/9210)) - 修复流式回复期间聊天一滚动上下文窗口浮层就自行关闭的问题 ([#8742](https://github.com/getpaseo/paseo/pull/8742),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复侧边栏用量摘要只在打开“使用情况”时才更新的问题 ([#7806](https://github.com/getpaseo/paseo/pull/7806),贡献者:[@ragokan](https://github.com/ragokan)) - 修复 Android 上位于触发元素上方的提示和菜单在打开后内容变多时短暂盖住触发元素的问题 ([#9247](https://github.com/getpaseo/paseo/pull/9247)) @@ -73,11 +77,13 @@ - 修复 Codex 的“Apply file changes”审批在你接受之前不显示文件名和 diff 的问题 ([#8585](https://github.com/getpaseo/paseo/pull/8585),贡献者:[@ragokan](https://github.com/ragokan)) - 修复 Codex 在一个补丁中编辑多个文件时,时间线只显示第一个文件的 diff 的问题 ([#8613](https://github.com/getpaseo/paseo/pull/8613),贡献者:[@ragokan](https://github.com/ragokan)) - 修复多个 Codex 操作同时启动时,Codex 会话发现和启动偶发 SQLite 初始化错误的问题 ([#9008](https://github.com/getpaseo/paseo/pull/9008),贡献者:[@colonelpanic8](https://github.com/colonelpanic8)、[@michaelmwu](https://github.com/michaelmwu)) +- 修复 Codex 的重连尝试和警告未显示在时间线中的问题 ([#9370](https://github.com/getpaseo/paseo/pull/9370),贡献者:[@whatamelon](https://github.com/whatamelon)) - 修复 daemon 重启时正处于轮次中的 OpenCode 对话显示为空闲并忽略“停止”的问题 ([#8698](https://github.com/getpaseo/paseo/pull/8698)) - 修复审批待处理期间你发送消息时,OpenCode 被告知你拒绝了工具调用的问题 ([#8477](https://github.com/getpaseo/paseo/pull/8477)) - 修复重新打开的 Pi 对话缺少上下文压缩之前的消息的问题 ([#8523](https://github.com/getpaseo/paseo/pull/8523)) - 修复工作文件夹被移除后,已归档的 Pi 聊天因 `spawn pi ENOENT` 无法打开的问题 ([#8442](https://github.com/getpaseo/paseo/pull/8442),贡献者:[@DAnaeto](https://github.com/DAnaeto)) - 修复关闭空闲运行时清理的情况下,读取已归档的 Pi 聊天会遗留一个 Pi 进程的问题 ([#8554](https://github.com/getpaseo/paseo/pull/8554),贡献者:[@rylwin](https://github.com/rylwin)) +- 修复恢复的 pi-subagents 运行未出现在 Subagent 栏中的问题 ([#9261](https://github.com/getpaseo/paseo/pull/9261),贡献者:[@xxachangxx](https://github.com/xxachangxx)) - 修复向进程已退出的 ACP Agent 发送提示词后一直停留在运行中、而不是报错失败的问题 ([#8406](https://github.com/getpaseo/paseo/pull/8406),贡献者:[@DAnaeto](https://github.com/DAnaeto)) - 修复 ACP Agent 放弃审批请求并结束轮次后一直卡在“waiting for permission”的问题 ([#8548](https://github.com/getpaseo/paseo/pull/8548),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复 ACP Agent 发送配置更新后,更改其模式因 `invalid_params` 失败的问题 ([#8912](https://github.com/getpaseo/paseo/pull/8912),贡献者:[@a-sh](https://github.com/a-sh)) @@ -109,10 +115,13 @@ ### 插件 - 新增插件订阅,可将 daemon 的实时事件流式推送到插件面板;插件 RPC 和事件支持二进制(`Uint8Array`)负载 ([#8527](https://github.com/getpaseo/paseo/pull/8527)) +- 插件的 Agent 快照新增后台任务数量(`backgroundWork.count`)和 `background` 标记,Agent 钩子新增 `background` 标记 ([#9362](https://github.com/getpaseo/paseo/pull/9362)) - “设置 → 插件”改为通过齿轮按钮打开插件设置,每个设置页面对应一个标签页 ([#8675](https://github.com/getpaseo/paseo/pull/8675)) - 为会打开菜单或浮层的插件 Composer 胶囊按钮新增向上的箭头 ([#8673](https://github.com/getpaseo/paseo/pull/8673)) - daemon 启动时改为并发启动已配置的插件,不再逐个启动 ([#8427](https://github.com/getpaseo/paseo/pull/8427),贡献者:[@DAnaeto](https://github.com/DAnaeto)) - 修复主机的 npm 使用镜像源时,从插件库安装插件因“npm artifact changed since review”失败的问题 ([#8756](https://github.com/getpaseo/paseo/pull/8756),贡献者:[@tlipoca9](https://github.com/tlipoca9)) +- 修复 daemon 因无效消息终止插件后,该插件仍留在列表中且未报告退出的问题 ([#9285](https://github.com/getpaseo/paseo/pull/9285),贡献者:[@Brandon168](https://github.com/Brandon168)) +- 修复 ACP Provider 插件丢弃 Agent 在提示词响应中报告的 token 用量的问题 ([#9396](https://github.com/getpaseo/paseo/pull/9396),贡献者:[@Myasuka](https://github.com/Myasuka)) - 修复已发布的 `@getpaseo/*` npm 包未声明许可证的问题;现在声明为 Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816),贡献者:[@mdlawson](https://github.com/mdlawson)、[@ragokan](https://github.com/ragokan)) - 修复插件更新了自己的某张时间线卡片后,从较早的回复分叉因“This checkpoint changed after it was created”失败的问题 ([#8746](https://github.com/getpaseo/paseo/pull/8746),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) - 修复由插件渲染最终回复时,“折叠轮次”让轮次保持展开或折叠到较早回复的问题 ([#8811](https://github.com/getpaseo/paseo/pull/8811),贡献者:[@geoqiao](https://github.com/geoqiao)) diff --git a/package-lock.json b/package-lock.json index 4205cb17ac..fcfe3e0eed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37468,7 +37468,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39637,13 +39637,13 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/server": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/server": "0.16.0-beta.2", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -39890,11 +39890,11 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/relay": "0.16.0-beta.1", + "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/relay": "0.16.0-beta.2", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -39906,7 +39906,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40149,7 +40149,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40195,7 +40195,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "@codemirror/language": "6.12.4", @@ -40225,7 +40225,7 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", @@ -40233,8 +40233,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40244,8 +40244,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40267,7 +40267,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "semver": "^7.8.5", @@ -40295,7 +40295,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "@noble/ciphers": "^2.4.0", @@ -40517,17 +40517,17 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/highlight": "0.16.0-beta.1", - "@getpaseo/plugin": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/relay": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/highlight": "0.16.0-beta.2", + "@getpaseo/plugin": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/relay": "0.16.0-beta.2", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41474,7 +41474,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43084,7 +43084,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index e6d7a0466b..3723a8f4ad 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index 35c5859c03..62f1f65ba4 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index 572d8aab98..915581ad32 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Paseo CLI - control your AI coding agents from the command line", "license": "Apache-2.0", "bin": { @@ -29,9 +29,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/server": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/server": "0.16.0-beta.2", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index c244deb6db..862157ccab 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Paseo client SDK package", "license": "Apache-2.0", "files": [ @@ -49,8 +49,8 @@ "measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts" }, "dependencies": { - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/relay": "0.16.0-beta.1", + "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/relay": "0.16.0-beta.2", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 6e1133d317..20c36da260 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index fb6aa1b517..85a6a9313e 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 26a21299c2..67ad30a5ca 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "license": "Apache-2.0", "files": [ "dist", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 4d3f76849f..97644d8303 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Paseo plugin SDK package", "license": "Apache-2.0", "files": [ @@ -78,8 +78,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -89,8 +89,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 02a7d75321..4c3738ba21 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Paseo shared protocol schemas and wire types", "license": "Apache-2.0", "files": [ diff --git a/packages/relay/package.json b/packages/relay/package.json index f1f8c3588c..1c8bdf3d6e 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Paseo relay for bridging daemon and client connections", "license": "Apache-2.0", "files": [ diff --git a/packages/server/package.json b/packages/server/package.json index fa14593632..a73beba2fd 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "description": "Paseo backend server", "license": "Apache-2.0", "files": [ @@ -109,11 +109,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0-beta.1", - "@getpaseo/highlight": "0.16.0-beta.1", - "@getpaseo/plugin": "0.16.0-beta.1", - "@getpaseo/protocol": "0.16.0-beta.1", - "@getpaseo/relay": "0.16.0-beta.1", + "@getpaseo/client": "0.16.0-beta.2", + "@getpaseo/highlight": "0.16.0-beta.2", + "@getpaseo/plugin": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/relay": "0.16.0-beta.2", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 93e801ed2d..01b96c2cd1 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index b160396c83..c31af5c7e7 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0-beta.1", + "version": "0.16.0-beta.2", "private": true, "type": "module", "scripts": { From 68818067f2a55c5655dc43f380a143fe4cb7ebb6 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:49:19 +0000 Subject: [PATCH 002/160] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 71db8df5f5..22080158c6 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-vG7v6uq2ADtOILEuRq9q3wTDUENAhRBbzI7UGBsWOqo= +sha256-e6BNeOJvy1uyDe/XW9hdr7NBgJ+t9tlNum5oLNefREI= From 9e607a3aa337737edcd32f3fb39117049cf7cd66 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:09:19 +0000 Subject: [PATCH 003/160] fix(app): restore physical arrow keys in Android terminals (#9407) * fix(app): send hardware arrow keys to the terminal on Android TextInput.onKeyPress is built from the IME input connection, so physical arrows never reach it and fell through to the hidden input as caret movement. The hardware module now claims arrows while the terminal input (nativeID) has focus, and the input forwards them to the PTY with their modifiers. * test(app): guard Android terminal hardware arrow delivery Exercise physical arrow ownership through a real Android window and editable, including repeats, modifiers and ordinary text-field editing. The terminal case fails on main because Left moves the hidden caret; the following typed character is then discarded as a replacement. Co-authored-by: moevis --------- Co-authored-by: moevis Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- docs/android.md | 9 +++ docs/keyboard-shortcuts.md | 5 ++ .../android/build.gradle | 3 + .../src/androidTest/AndroidManifest.xml | 6 ++ .../sh/paseo/keyboard/TerminalArrowTest.kt | 81 +++++++++++++++++++ .../keyboard/PaseoHardwareKeyboardModule.kt | 26 ++++-- .../terminal-emulator-native-grid.native.tsx | 9 +-- packages/app/src/keyboard/index.ts | 2 + .../terminal-input.native.test.ts | 31 +++---- .../native-renderer/terminal-input.native.tsx | 40 ++++++++- .../native-renderer/terminal-key-events.ts | 33 +++++--- 11 files changed, 199 insertions(+), 46 deletions(-) create mode 100644 packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/AndroidManifest.xml create mode 100644 packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/java/sh/paseo/keyboard/TerminalArrowTest.kt diff --git a/docs/android.md b/docs/android.md index 8b6201ae91..e913f6c7a7 100644 --- a/docs/android.md +++ b/docs/android.md @@ -112,6 +112,15 @@ need an artifact. `android:clear` removes the generated Android project. Run `npm run test:android --workspace=@getpaseo/app` explicitly with a local Android toolchain to prebuild Android and run native module unit tests. Ordinary CI does not prebuild Android or run these tests. +With an emulator or device connected, run the hardware keyboard's window-dispatch regression tests +from `packages/app/android`: + +```bash +./gradlew :paseo-hardware-keyboard:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false +``` + +These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing. + ### Diagnostic logs without ADB In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all diff --git a/docs/keyboard-shortcuts.md b/docs/keyboard-shortcuts.md index 2c1045eb54..dd93f03b4a 100644 --- a/docs/keyboard-shortcuts.md +++ b/docs/keyboard-shortcuts.md @@ -85,6 +85,11 @@ Escape interrupts an agent only in the message input or an unclaimed surface. A focused terminal excludes that binding. The source leaves terminal Escape alone; terminal Escape/Ctrl forwarding is a separate feature. +Terminal arrows never pass through the shortcut pipeline. The Android hardware +module claims them while the terminal's hidden input (`nativeID`) owns the focus. +`TextInput.onKeyPress` only sees IME keys, and an arrow that falls through moves +the hidden caret and desyncs the next text change, so the pipeline cannot own them. + ## Keys shared with text editing A binding on a key the platform already uses for editing, such as Cmd/Ctrl+Z for diff --git a/packages/app/modules/paseo-hardware-keyboard/android/build.gradle b/packages/app/modules/paseo-hardware-keyboard/android/build.gradle index 62031857e0..4ec4e613e2 100644 --- a/packages/app/modules/paseo-hardware-keyboard/android/build.gradle +++ b/packages/app/modules/paseo-hardware-keyboard/android/build.gradle @@ -8,9 +8,12 @@ android { defaultConfig { versionCode 1 versionName '0.1.0' + testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' } } dependencies { implementation 'com.facebook.react:react-android' testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test:runner:1.6.2' + androidTestImplementation 'androidx.test.ext:junit:1.2.1' } diff --git a/packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/AndroidManifest.xml b/packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000000..16f134baf7 --- /dev/null +++ b/packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/AndroidManifest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/java/sh/paseo/keyboard/TerminalArrowTest.kt b/packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/java/sh/paseo/keyboard/TerminalArrowTest.kt new file mode 100644 index 0000000000..8684a30521 --- /dev/null +++ b/packages/app/modules/paseo-hardware-keyboard/android/src/androidTest/java/sh/paseo/keyboard/TerminalArrowTest.kt @@ -0,0 +1,81 @@ +package sh.paseo.keyboard + +import android.app.Activity +import android.content.Intent +import android.view.KeyEvent +import android.widget.EditText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** Exercises the real Android window and editable that receive physical keys. */ +@RunWith(AndroidJUnit4::class) +class TerminalArrowTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private var activity: Activity? = null + + @After fun finish() { + instrumentation.runOnMainSync { + activity?.let { + HardwareKeyboard.release(it.window) + it.finish() + } + } + } + + @Test fun physicalArrowsDoNotMoveTheTerminalInputCaret() { + withInput(terminal = true) { input, host -> + for (code in listOf(KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN)) { + for (modifiers in listOf(0, KeyEvent.META_SHIFT_ON, KeyEvent.META_ALT_ON, KeyEvent.META_CTRL_ON)) { + input.setSelection(3) + for (repeat in 0..2) { + assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_DOWN, code, repeat, modifiers))) + assertEquals("Physical arrows must leave the hidden input caret at the end", 3, input.selectionStart) + } + assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_UP, code, 0, modifiers))) + } + } + host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_X)) + host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_X)) + assertEquals("abcx", input.text.toString()) + } + } + + @Test fun physicalArrowsStillEditOtherTextFields() { + withInput(terminal = false) { input, host -> + host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)) + host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)) + assertEquals(2, input.selectionStart) + host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_X)) + host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_X)) + assertEquals("abxc", input.text.toString()) + } + } + + private fun withInput(terminal: Boolean, check: (EditText, Activity) -> Unit) { + val host = instrumentation.startActivitySync( + Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + activity = host + lateinit var input: EditText + instrumentation.runOnMainSync { + input = EditText(host) + if (terminal) input.setTag(com.facebook.react.R.id.view_tag_native_id, "paseo-terminal-input") + host.setContentView(input) + input.setText("abc") + input.requestFocus() + input.setSelection(3) + HardwareKeyboard.observe(host.window) + } + instrumentation.waitForIdleSync() + instrumentation.runOnMainSync { + assertSame("The editable must own window focus before keys are dispatched", input, host.window.currentFocus) + check(input, host) + } + } +} diff --git a/packages/app/modules/paseo-hardware-keyboard/android/src/main/java/sh/paseo/keyboard/PaseoHardwareKeyboardModule.kt b/packages/app/modules/paseo-hardware-keyboard/android/src/main/java/sh/paseo/keyboard/PaseoHardwareKeyboardModule.kt index f8b5fd7d31..c0aa92ad4e 100644 --- a/packages/app/modules/paseo-hardware-keyboard/android/src/main/java/sh/paseo/keyboard/PaseoHardwareKeyboardModule.kt +++ b/packages/app/modules/paseo-hardware-keyboard/android/src/main/java/sh/paseo/keyboard/PaseoHardwareKeyboardModule.kt @@ -10,18 +10,24 @@ import android.view.KeyEvent import android.view.Window import android.widget.EditText import android.view.inputmethod.BaseInputConnection +import com.facebook.react.R import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.bridge.ReactContext import com.facebook.react.interfaces.ExtraWindowEventListener import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition +// Matched against the hidden terminal input's `nativeID` +// (TERMINAL_INPUT_NATIVE_ID in terminal-input.native.tsx). +private const val TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input" + internal object HardwareKeyboard { var module: PaseoHardwareKeyboardModule? = null @Volatile var overlayKeys: Set = emptySet() private val windows = mutableMapOf() val dispatcher = WindowKeyDispatcher() private val consumedPresses = mutableSetOf() + private val terminalArrowCodes = setOf("ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight") fun observe(window: Window) { if (windows.containsKey(window)) return @@ -38,7 +44,7 @@ internal object HardwareKeyboard { consumedPresses.clear() } - fun dispatch(event: KeyEvent, composing: Boolean): Boolean { + fun dispatch(event: KeyEvent, composing: Boolean, terminalFocused: Boolean): Boolean { if (event.flags and KeyEvent.FLAG_SOFT_KEYBOARD != 0) return false if (event.action != KeyEvent.ACTION_DOWN && event.action != KeyEvent.ACTION_UP) return false val code = code(event.keyCode) @@ -64,8 +70,12 @@ internal object HardwareKeyboard { )) if (event.action == KeyEvent.ACTION_UP) return consumedPresses.remove(event.keyCode) val overlayOwnsKey = key != "Dead" && key in overlayKeys && !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed && !composing - if (overlayOwnsKey) consumedPresses.add(event.keyCode) - return overlayOwnsKey + // Without this the hidden input consumes the arrows as caret movement and + // its next text change stops being a plain append. Modifiers stay + // forwarded: Alt/Shift+arrow are terminal editing keys. + val terminalOwnsKey = terminalFocused && !composing && code in terminalArrowCodes + if (overlayOwnsKey || terminalOwnsKey) consumedPresses.add(event.keyCode) + return overlayOwnsKey || terminalOwnsKey } private fun code(keyCode: Int): String = when (keyCode) { @@ -107,9 +117,15 @@ internal object HardwareKeyboard { private class KeyboardWindowCallback(private val window: Window, val previous: Window.Callback) : Window.Callback by previous { override fun dispatchKeyEvent(event: KeyEvent): Boolean { - val editable = (window.currentFocus as? EditText)?.text + val focus = window.currentFocus + val editable = (focus as? EditText)?.text val composing = editable != null && BaseInputConnection.getComposingSpanStart(editable) >= 0 - return HardwareKeyboard.dispatcher.dispatch(event, { HardwareKeyboard.dispatch(event, composing) }, { previous.dispatchKeyEvent(event) }) + val terminalFocused = focus?.getTag(R.id.view_tag_native_id) == TERMINAL_INPUT_NATIVE_ID + return HardwareKeyboard.dispatcher.dispatch( + event, + { HardwareKeyboard.dispatch(event, composing, terminalFocused) }, + { previous.dispatchKeyEvent(event) }, + ) } } diff --git a/packages/app/src/components/terminal-emulator-native-grid.native.tsx b/packages/app/src/components/terminal-emulator-native-grid.native.tsx index ad71316f3c..e76905b327 100644 --- a/packages/app/src/components/terminal-emulator-native-grid.native.tsx +++ b/packages/app/src/components/terminal-emulator-native-grid.native.tsx @@ -51,10 +51,7 @@ import { TERMINAL_SELECTION_GRIP_SIZE, } from "../terminal/native-renderer/terminal-selection-controller"; import { resolveNativeTerminalMountAction } from "../terminal/native-renderer/terminal-mount-policy"; -import { - forwardNativeTerminalKey, - type NativeTerminalKey, -} from "../terminal/native-renderer/terminal-key-events"; +import { type NativeTerminalKeyEvent } from "../terminal/native-renderer/terminal-key-events"; import { TerminalInput, type TerminalInputHandle, @@ -511,9 +508,9 @@ function NativeTerminalEmulator({ ); const handleNativeTerminalKey = useCallback( - (key: NativeTerminalKey) => { + (event: NativeTerminalKeyEvent) => { claimActiveTerminalSizeForAction("key"); - forwardNativeTerminalKey({ key, onTerminalKey: callbacksRef.current.onTerminalKey }); + callbacksRef.current.onTerminalKey?.(event); }, [claimActiveTerminalSizeForAction], ); diff --git a/packages/app/src/keyboard/index.ts b/packages/app/src/keyboard/index.ts index c8836c8e08..7659ba333b 100644 --- a/packages/app/src/keyboard/index.ts +++ b/packages/app/src/keyboard/index.ts @@ -8,6 +8,8 @@ export { subscribeOverlays, } from "./internal/overlay-dispatch"; export { useKeyboardFocusSurface } from "./internal/use-focus-surface"; +export { subscribeHardwareKeyboard } from "./internal/sources/hardware"; +export type { HardwareKeyboardEvent } from "./internal/sources/hardware"; export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions"; export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser"; export { useHardwareKeyboardPresent } from "./availability"; diff --git a/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts b/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts index 01d3e398d5..1b92045fdb 100644 --- a/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts +++ b/packages/app/src/terminal/native-renderer/terminal-input.native.test.ts @@ -6,7 +6,7 @@ import { TERMINAL_INPUT_CONTEXT_MENU_HIDDEN, TERMINAL_INPUT_HITBOX_SIZE, } from "./terminal-input.native"; -import { forwardNativeTerminalKey, type NativeTerminalKeyEvent } from "./terminal-key-events"; +import { createNativeTerminalKeyEvent, resolveHardwareTerminalKey } from "./terminal-key-events"; describe("native terminal typed input", () => { function inputData(change: { data: string; shouldClear: boolean }): string { @@ -149,25 +149,18 @@ describe("native terminal typed input", () => { }); }); - it("forwards native arrow key events to the terminal key path", () => { - const events: NativeTerminalKeyEvent[] = []; - - forwardNativeTerminalKey({ - key: "ArrowUp", - onTerminalKey: (event) => { - events.push(event); - }, + it("identifies hardware arrows by code and keeps their modifiers", () => { + // UIKit leaves `key` as a sentinel for Left/Right, so the code leads. + expect(resolveHardwareTerminalKey({ key: "\uF702", code: "ArrowLeft" })).toBe("ArrowLeft"); + expect(resolveHardwareTerminalKey({ key: "ArrowUp", code: "" })).toBe("ArrowUp"); + expect(resolveHardwareTerminalKey({ key: "a", code: "KeyA" })).toBeNull(); + expect(createNativeTerminalKeyEvent("ArrowDown", { shift: true, alt: true })).toEqual({ + key: "ArrowDown", + ctrl: false, + shift: true, + alt: true, + meta: false, }); - - expect(events).toEqual([ - { - key: "ArrowUp", - ctrl: false, - shift: false, - alt: false, - meta: false, - }, - ]); }); it("keeps the hidden input from owning terminal long-press selection", () => { diff --git a/packages/app/src/terminal/native-renderer/terminal-input.native.tsx b/packages/app/src/terminal/native-renderer/terminal-input.native.tsx index 4eea8a1da3..7ca7020cb0 100644 --- a/packages/app/src/terminal/native-renderer/terminal-input.native.tsx +++ b/packages/app/src/terminal/native-renderer/terminal-input.native.tsx @@ -1,5 +1,6 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react"; import { + Platform, StyleSheet, type NativeSyntheticEvent, type StyleProp, @@ -10,10 +11,19 @@ import { EditingTextInput as TextInput, type EditingTextInputHandle, } from "@/components/ui/text-input"; -import { resolveNativeTerminalKey, type NativeTerminalKey } from "./terminal-key-events"; +import { hasActiveOverlay, subscribeHardwareKeyboard } from "@/keyboard"; +import { + createNativeTerminalKeyEvent, + resolveHardwareTerminalKey, + resolveNativeTerminalKey, + type NativeTerminalKey, + type NativeTerminalKeyEvent, +} from "./terminal-key-events"; export const TERMINAL_INPUT_CONTEXT_MENU_HIDDEN = true; export const TERMINAL_INPUT_HITBOX_SIZE = 1; +/** Matched by the Android hardware keyboard module to claim arrow keys for this input. */ +export const TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"; export interface TerminalTextInputChange { data: string; @@ -39,7 +49,7 @@ interface TerminalInputProps { isKeyboardVisible: boolean; onFocus?: () => void; onInput?: (data: string) => void; - onTerminalKey?: (key: NativeTerminalKey) => void; + onTerminalKey?: (event: NativeTerminalKeyEvent) => void; style?: StyleProp; } @@ -187,6 +197,8 @@ export const TerminalInput = forwardRef const inputRef = useRef(null); const isFocusedRef = useRef(false); const pendingFocusFrameRef = useRef(null); + const onTerminalKeyRef = useRef(onTerminalKey); + onTerminalKeyRef.current = onTerminalKey; const inputState = useMemo(() => createTerminalTextInputState(), []); const inputStyle = useMemo(() => [styles.input, style], [style]); @@ -250,6 +262,27 @@ export const TerminalInput = forwardRef useEffect(() => clearPendingFocus, [clearPendingFocus]); + useEffect(() => { + // Physical arrows arrive through the native key stream, never through + // TextInput.onKeyPress (RN builds that event from the IME connection). + // The native module claims them for this input so the hidden buffer + // cannot move its caret, then re-emits them here for the PTY. + if (Platform.OS !== "android") return; + return subscribeHardwareKeyboard((event) => { + if (!isFocusedRef.current || event.phase !== "down" || event.isComposing) return; + if (hasActiveOverlay()) return; + const key = resolveHardwareTerminalKey(event); + if (!key) return; + onTerminalKeyRef.current?.({ + key, + ctrl: event.ctrlKey, + shift: event.shiftKey, + alt: event.altKey, + meta: event.metaKey, + }); + }); + }, []); + useImperativeHandle( ref, () => ({ @@ -293,7 +326,7 @@ export const TerminalInput = forwardRef (event: NativeSyntheticEvent) => { const change = inputState.receiveKeyPress(event.nativeEvent.key); if (change.key) { - onTerminalKey?.(change.key); + onTerminalKey?.(createNativeTerminalKeyEvent(change.key)); } if (change.data.length > 0) { onInput?.(change.data); @@ -321,6 +354,7 @@ export const TerminalInput = forwardRef blurOnSubmit={false} importantForAutofill="no" multiline={true} + nativeID={TERMINAL_INPUT_NATIVE_ID} onChangeText={handleChangeText} onBlur={handleBlur} onFocus={handleFocus} diff --git a/packages/app/src/terminal/native-renderer/terminal-key-events.ts b/packages/app/src/terminal/native-renderer/terminal-key-events.ts index 35b0a54f72..8d6aa8d44b 100644 --- a/packages/app/src/terminal/native-renderer/terminal-key-events.ts +++ b/packages/app/src/terminal/native-renderer/terminal-key-events.ts @@ -22,19 +22,26 @@ export function resolveNativeTerminalKey(key: string): NativeTerminalKey | null } } -export function createNativeTerminalKeyEvent(key: NativeTerminalKey): NativeTerminalKeyEvent { - return { - key, - ctrl: false, - shift: false, - alt: false, - meta: false, - }; +/** + * Physical keyboards report the DOM `code`. UIKit leaves `key` as a sentinel + * for Left/Right, so the code is the only reliable identifier there. + */ +export function resolveHardwareTerminalKey(input: { + key?: string; + code?: string; +}): NativeTerminalKey | null { + return resolveNativeTerminalKey(input.code ?? "") ?? resolveNativeTerminalKey(input.key ?? ""); } -export function forwardNativeTerminalKey(input: { - key: NativeTerminalKey; - onTerminalKey?: NativeTerminalKeyHandler; -}): void { - input.onTerminalKey?.(createNativeTerminalKeyEvent(input.key)); +export function createNativeTerminalKeyEvent( + key: NativeTerminalKey, + modifiers: { ctrl?: boolean; shift?: boolean; alt?: boolean; meta?: boolean } = {}, +): NativeTerminalKeyEvent { + return { + key, + ctrl: modifiers.ctrl ?? false, + shift: modifiers.shift ?? false, + alt: modifiers.alt ?? false, + meta: modifiers.meta ?? false, + }; } From aa7cabb455decaa6ad21fe4d1ea8fd0d6007bdb4 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:08:41 +0000 Subject: [PATCH 004/160] test(app): cover composer recall in one journey (#9409) Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../app/e2e/browser/composer-recall.spec.ts | 76 +++++++++---------- 1 file changed, 37 insertions(+), 39 deletions(-) diff --git a/packages/app/e2e/browser/composer-recall.spec.ts b/packages/app/e2e/browser/composer-recall.spec.ts index a58a8ff59e..4923d8e80c 100644 --- a/packages/app/e2e/browser/composer-recall.spec.ts +++ b/packages/app/e2e/browser/composer-recall.spec.ts @@ -6,6 +6,7 @@ import { fillComposerDraft, typeIntoFocusedComposer, } from "../support/helpers/composer"; +import { expectVisibleAgentSurfacesIdle } from "../support/helpers/agent-stream"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; function userMessages(page: Page) { @@ -29,7 +30,9 @@ async function pressInComposer(page: Page, key: string) { } test.describe("Composer recall", () => { - test("Up and Down walk sent messages from an empty composer", async ({ page }) => { + test("recalls, edits, and sends messages while keeping slash autocomplete usable", async ({ + page, + }) => { const session = await seedMockAgentWorkspace({ repoPrefix: "composer-recall-", title: "Composer recall", @@ -37,49 +40,44 @@ test.describe("Composer recall", () => { try { await openAgentRoute(page, session); await expectComposerVisible(page); - await sendAndWaitForMessage(page, "fix the auth bug", 1); - await sendAndWaitForMessage(page, "add tests", 2); + await test.step("walk sent history, edit a recalled draft, and send it", async () => { + await sendAndWaitForMessage(page, "fix the auth bug", 1); + await sendAndWaitForMessage(page, "add tests", 2); - await pressInComposer(page, "ArrowUp"); - await expectComposerDraft(page, "add tests"); - await pressInComposer(page, "ArrowUp"); - await expectComposerDraft(page, "fix the auth bug"); - await pressInComposer(page, "ArrowDown"); - await expectComposerDraft(page, "add tests"); - await pressInComposer(page, "ArrowDown"); - await expectComposerDraft(page, ""); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "add tests"); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "fix the auth bug"); + await pressInComposer(page, "ArrowDown"); + await expectComposerDraft(page, "add tests"); + await pressInComposer(page, "ArrowDown"); + await expectComposerDraft(page, ""); - await pressInComposer(page, "ArrowUp"); - await typeIntoFocusedComposer(page, " for login"); - await expectComposerDraft(page, "add tests for login"); - await pressInComposer(page, "ArrowUp"); - await expectComposerDraft(page, "add tests for login"); + await pressInComposer(page, "ArrowUp"); + await typeIntoFocusedComposer(page, " for login"); + await expectComposerDraft(page, "add tests for login"); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "add tests for login"); - await sendDraftWhenReady(page); - await expect(userMessages(page)).toHaveCount(3, { timeout: 30_000 }); - await expect(userMessages(page).last()).toContainText("add tests for login"); - } finally { - await session.cleanup(); - } - }); + await sendDraftWhenReady(page); + await expect(userMessages(page)).toHaveCount(3, { timeout: 30_000 }); + await expect(userMessages(page).last()).toContainText("add tests for login"); + }); + await test.step("recall a slash message without opening its picker, then edit it", async () => { + await expectComposerDraft(page, ""); + const reply = await session.client.waitForFinish(session.agentId, 15_000); + expect(reply.status).toBe("idle"); + await expectVisibleAgentSurfacesIdle(page); + await sendAndWaitForMessage(page, "/tdd", 4); - test("a recalled slash message does not open the command picker", async ({ page }) => { - const session = await seedMockAgentWorkspace({ - repoPrefix: "composer-recall-slash-", - title: "Composer recall slash", - }); - try { - await openAgentRoute(page, session); - await expectComposerVisible(page); - await sendAndWaitForMessage(page, "/tdd", 1); + const popover = page.getByTestId("composer-autocomplete-popover").filter({ visible: true }); + await pressInComposer(page, "ArrowUp"); + await expectComposerDraft(page, "/tdd"); + await expect(popover).toHaveCount(0); - const popover = page.getByTestId("composer-autocomplete-popover").filter({ visible: true }); - await pressInComposer(page, "ArrowUp"); - await expectComposerDraft(page, "/tdd"); - await expect(popover).toHaveCount(0); - - await typeIntoFocusedComposer(page, "x"); - await expect(popover.first()).toBeVisible({ timeout: 30_000 }); + await typeIntoFocusedComposer(page, "x"); + await expect(popover.first()).toBeVisible({ timeout: 30_000 }); + }); } finally { await session.cleanup(); } From 4df5307eaab6b22d06fe54a45c68211b3413f45c Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:14:46 +0000 Subject: [PATCH 005/160] fix: keep failed ACP tools valid in conversation history (#9467) Co-authored-by: Tianyu Yang --- .../src/server/acp-internal/connection.ts | 4 +- packages/plugin/src/server/acp.test.ts | 67 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index 6c8ac31b71..570d3cd4ca 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -1527,7 +1527,9 @@ function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem { name: snapshot.name ?? snapshot.title, detail, }; - if (status === "failed") return { ...base, status, error: snapshot.output }; + if (status === "failed") { + return { ...base, status, error: snapshot.output ?? { message: "Tool failed" } }; + } return { ...base, status, error: null }; } diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index b022e0a5ef..ee96f3eb08 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -9,6 +9,7 @@ import { } from "@agentclientprotocol/sdk"; import type { ProviderConnection, ProviderEvent, ProviderInput } from "./provider.js"; import { afterEach, describe, expect, it } from "vitest"; +import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages"; import { runAcpProvider, type AcpStreamMessage } from "./acp.js"; const temporaryDirectories: string[] = []; @@ -890,6 +891,72 @@ lines.on("line", (line) => { }, ); + it.each([ + { status: "failed", output: undefined, error: { message: "Tool failed" } }, + { status: "failed", output: null, error: { message: "Tool failed" } }, + { + status: "failed", + output: { message: "File not found" }, + error: { message: "File not found" }, + }, + { status: "failed", output: "Permission denied", error: "Permission denied" }, + { status: "completed", output: null, error: null }, + ] as const)( + "keeps a $status ACP tool with output $output valid on the history wire", + async ({ status, output, error }) => { + const harness = connectorHarness({ + promptUpdates: () => [ + { + sessionUpdate: "tool_call", + toolCallId: "read-1", + title: "Read file", + kind: "read", + status: "in_progress", + }, + { sessionUpdate: "tool_call_update", toolCallId: "read-1", status, rawOutput: output }, + ], + }); + const registration = runAcpProvider({ + id: "tool-history-acp", + label: "Tool history ACP", + connector: harness.connector, + }); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send(openInput()); + await waitForEvent(events, (event) => event.type === "session.ready"); + await connection.send({ + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "first", + delivery: "auto", + input: { type: "message", content: [{ type: "text", text: "Read a file" }] }, + }, + }); + await waitForEvent( + events, + (event) => event.type === "session.turn" && event.state === "completed", + ); + const rows = events.flatMap((event) => + event.type === "timeline.item" && event.item.id === "read-1" ? [event.item] : [], + ); + expect(rows).toHaveLength(2); + for (const row of rows) { + expect(AgentTimelineItemPayloadSchema.safeParse(row).success).toBe(true); + } + expect(rows.at(-1)).toMatchObject({ type: "tool_call", status, error }); + } finally { + await connection.close(); + } + }, + ); + it("serializes configuration mutations", async () => { let releaseMutation: (() => void) | null = null; const configOptions = [ From 065c487a908171d83ce6ff48c623aea2107b9cad Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:04:52 +0000 Subject: [PATCH 006/160] fix(server): keep workspace scripts when paseo.json checks are slow (#9477) * fix(server): answer workspace listings from the last paseo.json snapshot Every workspace listing and update builds a descriptor per workspace, and each descriptor read that workspace's paseo.json through a stat inside the daemon-wide two-slot pool, with a 5 s timeout that counted the queue wait. With many workspaces and a few clients listing, the last workspaces timed out, dropped their scripts, and the timed-out reads still ran, so other requests waited minutes. The projection path now answers from the last snapshot and re-checks it behind the caller once it is 2 s old (a clock stepped backwards counts as stale). Edits, worktree setup and metadata prompts keep the fresh read. The snapshot cap rises to 1024 roots so a listing over more roots than the cap does not evict the next root it needs. * fix(server): check paseo.json on every listing, answer the last config only when the check is late Answering listings from the snapshot showed the previous scripts on the first listing after an external edit to paseo.json, such as a branch switch or an agent editing the file, and nothing re-sent the update once the background check saw the change. A file that stopped being admissible also kept its old scripts indefinitely. Listings and script status now check paseo.json as before. When the check does not finish within the 5 s budget, they answer the last config read for that root instead of no scripts. Edits and execution keep failing on a late check. Co-authored-by: Phieu Dinh * fix(server): keep the saved paseo.json as the last known config after an in-app save Saving through the project config editor dropped the snapshot, so a late check on the next listing showed no scripts for that workspace. The save now records the config it wrote. * fix(server): record the saved paseo.json without another filesystem read Re-reading the file after the rename made a completed save wait on an unbudgeted read. The save now records the config and file stats it already has. --------- Co-authored-by: Phieu Dinh Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../server/script-status-projection.test.ts | 81 ++++++++++++++++++- .../src/server/script-status-projection.ts | 5 +- .../server/src/utils/paseo-config-file.ts | 65 ++++++++++++--- 3 files changed, 139 insertions(+), 12 deletions(-) diff --git a/packages/server/src/server/script-status-projection.test.ts b/packages/server/src/server/script-status-projection.test.ts index b6ef6e18f5..7032ba0d5c 100644 --- a/packages/server/src/server/script-status-projection.test.ts +++ b/packages/server/src/server/script-status-projection.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { tmpdir } from "node:os"; @@ -13,6 +13,7 @@ import { WorkspaceScriptPayloadSchema } from "@getpaseo/protocol/messages"; import type { ScriptHealthState } from "./script-health-monitor.js"; import { WorkspaceScriptRuntimeStore } from "./workspace-script-runtime-store.js"; import { readPaseoConfig } from "../utils/worktree.js"; +import { readPaseoConfigForEdit, writePaseoConfigForEdit } from "../utils/paseo-config-file.js"; import type { PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; import { createTestLogger } from "../test-utils/test-logger.js"; @@ -471,6 +472,84 @@ describe("script-status-projection", () => { } }); + it("keeps every workspace's scripts when a listing's paseo.json checks do not finish in time", async () => { + // More workspaces than the daemon kept snapshots for before, each with a config it has read. + const tempDir = realpathSync(mkdtempSync(path.join(tmpdir(), "script-projection-many-"))); + const workspaces = Array.from({ length: 300 }, (_, index) => { + const directory = path.join(tempDir, `workspace-${index}`); + mkdirSync(directory); + writeFileSync( + path.join(directory, "paseo.json"), + JSON.stringify({ scripts: { api: { type: "service", command: "npm run dev" } } }), + ); + return directory; + }); + const logger = createTestLogger(); + try { + await Promise.all( + workspaces.map((directory) => readPaseoConfigForProjection(directory, logger)), + ); + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const listing = Promise.all( + workspaces.map((directory) => readPaseoConfigForProjection(directory, logger)), + ); + // The filesystem has not answered any check when the 5 s budget runs out. + vi.advanceTimersByTime(5_000); + const configs = await listing; + + expect(configs.filter((config) => config?.scripts?.api === undefined)).toEqual([]); + } finally { + vi.useRealTimers(); + rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it("keeps the saved scripts when the first check after an in-app save is late", async () => { + const workspace = createWorkspaceRepo({ + paseoConfig: { scripts: { api: { type: "service", command: "npm run dev" } } }, + }); + const logger = createTestLogger(); + try { + const current = await readPaseoConfigForEdit(workspace.repoDir); + if (!current.ok) throw new Error("expected a readable paseo.json"); + const saved = await writePaseoConfigForEdit({ + repoRoot: workspace.repoDir, + config: { scripts: { web: { type: "service", command: "npm run web" } } }, + expectedRevision: current.revision, + }); + expect(saved.ok).toBe(true); + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const listing = readPaseoConfigForProjection(workspace.repoDir, logger); + vi.advanceTimersByTime(5_000); + + expect(Object.keys((await listing)?.scripts ?? {})).toEqual(["web"]); + } finally { + vi.useRealTimers(); + workspace.cleanup(); + } + }); + + it("shows an external paseo.json edit on the next listing", async () => { + const workspace = createWorkspaceRepo({ + paseoConfig: { scripts: { api: { type: "service", command: "npm run dev" } } }, + }); + try { + await readPaseoConfigForProjection(workspace.repoDir, createTestLogger()); + writeFileSync( + path.join(workspace.repoDir, "paseo.json"), + JSON.stringify({ scripts: { web: { type: "service", command: "npm run web" } } }), + ); + + const config = await readPaseoConfigForProjection(workspace.repoDir, createTestLogger()); + + expect(Object.keys(config?.scripts ?? {})).toEqual(["web"]); + } finally { + workspace.cleanup(); + } + }); + it("buildWorkspaceScriptPayloads given paseoConfig=null still surfaces orphaned runtime scripts", async () => { const workspaceId = "workspace-null-config"; const workspace = createWorkspaceRepo(); diff --git a/packages/server/src/server/script-status-projection.ts b/packages/server/src/server/script-status-projection.ts index a66f5fb073..25922ee2bc 100644 --- a/packages/server/src/server/script-status-projection.ts +++ b/packages/server/src/server/script-status-projection.ts @@ -5,7 +5,8 @@ import type { WorkspaceScriptPayload, } from "@getpaseo/protocol/messages"; import type { PaseoConfig } from "@getpaseo/protocol/paseo-config-schema"; -import { getScriptConfigs, isServiceScript, readPaseoConfig } from "../utils/worktree.js"; +import { readPaseoConfigOrLastKnown } from "../utils/paseo-config-file.js"; +import { getScriptConfigs, isServiceScript } from "../utils/worktree.js"; import { deriveProjectSlug } from "./workspace-git-metadata.js"; import type { ScriptHealthEntry, ScriptHealthState } from "./script-health-monitor.js"; import type { @@ -37,7 +38,7 @@ export async function readPaseoConfigForProjection( workspaceDirectory: string, logger: Logger, ): Promise { - const result = await readPaseoConfig(workspaceDirectory); + const result = await readPaseoConfigOrLastKnown(workspaceDirectory); if (result.ok) { return result.config; } diff --git a/packages/server/src/utils/paseo-config-file.ts b/packages/server/src/utils/paseo-config-file.ts index b8152c4f22..909c7d3dad 100644 --- a/packages/server/src/utils/paseo-config-file.ts +++ b/packages/server/src/utils/paseo-config-file.ts @@ -114,6 +114,12 @@ interface Snapshot { runtime: ReadPaseoConfigResult; } +// How long a caller waits for the filesystem, including time queued behind other roots. +const READ_BUDGET_MS = 5_000; +// Above the roots a busy daemon lists: a listing that visits more roots than this evicts the next one it needs. +const MAX_SNAPSHOTS = 1_024; +const UNAVAILABLE = Symbol("project config unavailable"); + /** Owns config admission, snapshots and daemon read/modify/write ordering for every consumer. */ class ProjectConfigOwner { // A stalled mount retains its slot until the OS returns; never consume the whole fs pool. @@ -166,17 +172,39 @@ class ProjectConfigOwner { this.snapshots.delete(root); this.snapshots.set(root, snapshot); // Worktrees come and go; retain only a bounded set of reusable snapshots. - if (this.snapshots.size > 256) this.snapshots.delete(this.snapshots.keys().next().value!); + if (this.snapshots.size > MAX_SNAPSHOTS) + this.snapshots.delete(this.snapshots.keys().next().value!); return snapshot; } async read(repoRoot: string): Promise { + const checked = await this.check(resolve(repoRoot)); + if (checked === UNAVAILABLE) throw new Error("Project config unavailable"); + return checked; + } + + /** A check the filesystem does not answer in time answers the last config read for that root. */ + async readOrLastKnown(repoRoot: string): Promise { const root = resolve(repoRoot); - return withTimeout( - this.serialized(root, "read", () => this.load(root)), - 5_000, - "Project config unavailable", - ); + const checked = await this.check(root); + if (checked !== UNAVAILABLE) return checked; + const known = this.snapshots.get(root); + if (!known) throw new Error("Project config unavailable"); + return known; + } + + private async check(root: string): Promise { + let budget: ReturnType | undefined; + try { + return await Promise.race([ + this.serialized(root, "read", () => this.load(root)), + new Promise((settle) => { + budget = setTimeout(settle, READ_BUDGET_MS, UNAVAILABLE); + }), + ]); + } finally { + clearTimeout(budget); + } } private async load(root: string): Promise { @@ -242,7 +270,7 @@ class ProjectConfigOwner { async write(input: WritePaseoConfigForEditInput): Promise { const root = resolve(input.repoRoot); return this.serialized(root, "write", async () => { - const { edit: parsed } = await validateConfig(input.config); + const { edit: parsed, runtime } = await validateConfig(input.config); if (!parsed.success) return { ok: false, error: { code: "invalid_project_config" } }; const content = `${JSON.stringify(parsed.data, null, 2)}\n`; if (Buffer.byteLength(content) > MAX_PASEO_CONFIG_BYTES) { @@ -251,7 +279,8 @@ class ProjectConfigOwner { const tempPath = join(root, `.${PASEO_CONFIG_FILE_NAME}.${process.pid}.${randomUUID()}.tmp`); try { await writeFile(tempPath, content, { flag: "wx" }); - const savedRevision = revision(await stat(tempPath)); + const savedStats = await stat(tempPath); + const savedRevision = revision(savedStats); const currentStats = await inspect(root); if (currentStats) admit(currentStats); const currentRevision = currentStats ? revision(currentStats) : null; @@ -261,7 +290,13 @@ class ProjectConfigOwner { // Serialized against daemon edits. External writers still have the existing // optimistic stat/rename race; revision tokens remain mtime + size. await rename(tempPath, resolvePaseoConfigPath(root)); - this.snapshots.delete(root); + // Remember what was saved without another read, so a late check right after the save + // still has a config to show. A rename that changes ctime only costs the next check a reload. + this.remember(root, { + fingerprint: fingerprint(savedStats), + edit: { ok: true, config: parsed.data, revision: savedRevision }, + runtime: { ok: true, config: runtime }, + }); return { ok: true, config: parsed.data, revision: savedRevision }; } catch { return { ok: false, error: { code: "write_failed" } }; @@ -289,6 +324,18 @@ export async function readPaseoConfig(repoRoot: string): Promise { + try { + return (await projectConfig.readOrLastKnown(repoRoot)).runtime; + } catch (error) { + return { ok: false, configPath: resolvePaseoConfigPath(repoRoot), error }; + } +} + export async function readPaseoConfigForEdit( repoRoot: string, ): Promise { From 525ee7f22264bb2132a92ba056ab0a39f18ff46a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:11:35 +0000 Subject: [PATCH 007/160] fix(app): keep Mermaid chart axes from overlapping and clipping (#9483) * fix(app): render Mermaid diagrams in an unscaled offscreen staging container * fix(app): keep gantt charts at a fixed width in the Mermaid staging container Rendering into the oversized staging container gave gantt charts its 16384px width, because Mermaid sizes a gantt chart from the element it renders in. The host then fit that width into the message column and the chart drew a few pixels tall. Give gantt charts the 1200px width Mermaid uses when there is no container width, so they report the same size whatever frame the host gives the runtime. Co-authored-by: FluidXin <266379324+FluidXin@users.noreply.github.com> * fix(app): keep gantt charts as wide as the Mermaid frame Pinning gantt charts to 1200px shrank them on iOS and Android, where the measuring frame is as wide as the message column and gantt charts used to fill it. Use the frame's own width instead, which is what Mermaid read from the page before rendering moved into the staging container. Co-authored-by: FluidXin <266379324+FluidXin@users.noreply.github.com> --------- Co-authored-by: FluidXin <266379324+FluidXin@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../markdown/fence/mermaid/build-runtime.mjs | 15 +++ .../markdown/fence/mermaid/runtime/entry.ts | 13 ++- .../fence/mermaid/runtime/html.gen.ts | 2 +- .../mermaid/runtime/runtime.browser.test.ts | 105 +++++++++++++++++- 4 files changed, 132 insertions(+), 3 deletions(-) diff --git a/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs b/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs index 6ed821ceac..26ffd2489a 100644 --- a/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs +++ b/packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs @@ -63,10 +63,25 @@ const html = ` #diagram svg { display: block; } + /* Keep Mermaid's temporary render container unscaled when the host mounts this frame + at 0x0 or 240x240 before the diagram's own dimensions are known. */ + #staging-clip { + position: fixed; + width: 0; + height: 0; + overflow: hidden; + visibility: hidden; + pointer-events: none; + } + #staging { + width: 16384px; + height: 16384px; + }
+ `; diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts index 25d7db5e3e..a7d00d59e6 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/entry.ts @@ -40,6 +40,9 @@ function initializeMermaid(colorScheme: "light" | "dark"): void { ], flowchart: { htmlLabels: false }, class: { htmlLabels: false }, + // A gantt chart takes the width of the element it renders in, which is the oversized staging + // container. Keep it as wide as this frame, which on native is the message column. + gantt: { useWidth: document.body.clientWidth }, }); } @@ -97,7 +100,15 @@ function measureDiagram(host: HTMLElement, svg: SVGSVGElement | null): DiagramSi async function render(message: MermaidRuntimeRenderMessage): Promise { try { initializeMermaid(message.colorScheme); - const { svg } = await mermaid.render(`paseo-mermaid-${message.revision}`, message.source); + const staging = document.getElementById("staging"); + if (!staging) { + throw new Error("Missing Mermaid staging container"); + } + const { svg } = await mermaid.render( + `paseo-mermaid-${message.revision}`, + message.source, + staging, + ); if (message.revision !== latestRevision) { return; } diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts index 608ab27869..082c07321d 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/html.gen.ts @@ -1,4 +1,4 @@ // Generated by packages/app/src/components/markdown/fence/mermaid/build-runtime.mjs. // Do not edit by hand. -export const mermaidRuntimeHtml = "\n\n \n \n \n \n \n \n \n
\n \n \n"; +export const mermaidRuntimeHtml = "\n\n \n \n \n \n \n \n \n
\n
\n \n \n"; diff --git a/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts b/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts index 7ffbbc79db..a9727900ff 100644 --- a/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts +++ b/packages/app/src/components/markdown/fence/mermaid/runtime/runtime.browser.test.ts @@ -29,9 +29,15 @@ function waitForRuntimeMessage( }); } -async function mountRuntime(size?: { width: number; height: number }): Promise { +async function mountRuntime( + size?: { width: number; height: number }, + options?: { allowSameOrigin?: boolean }, +): Promise { const frame = document.createElement("iframe"); frame.sandbox.add("allow-scripts"); + if (options?.allowSameOrigin) { + frame.sandbox.add("allow-same-origin"); + } if (size) { frame.style.width = `${size.width}px`; frame.style.height = `${size.height}px`; @@ -112,6 +118,103 @@ describe("Mermaid sandbox runtime", () => { expect(renderedSize(narrow)).toEqual(renderedSize(wide)); }); + /** + * MermaidFenceHost renders the first revision inside a 240x240 measuring frame (or 0x0 before + * ResizeObserver settles), then resizes the frame to the reported diagram size without + * re-rendering. Diagrams such as xychart-beta set `width="100%"` and `viewBox="0 0 700 500"` + * before measuring axis text with `getBoundingClientRect()`, so rendering directly in a narrow + * frame shrinks measured glyph boxes and leaves the Y-axis title colliding with tick labels and + * X-axis labels clipped at the bottom edge. + */ + it("preserves unscaled SVG layout when rendered inside a narrow or zero-sized frame", async () => { + const source = [ + "xychart-beta", + ' title "Throughput by Stage (req/s)"', + ' x-axis ["v1-base", "v2-parse", "v3-batch", "v4-cache", "v5-simd", "v6-final"]', + ' y-axis "Throughput (req/s)" 92.5 --> 93.6', + " bar [92.7, 92.8, 93.1, 93.2, 93.3, 93.5]", + ].join("\n"); + const zeroFrame = await mountRuntime({ height: 0, width: 0 }, { allowSameOrigin: true }); + const measuringFrame = await mountRuntime( + { height: 240, width: 240 }, + { allowSameOrigin: true }, + ); + const fullFrame = await mountRuntime({ height: 500, width: 700 }, { allowSameOrigin: true }); + + await render(zeroFrame, { revision: 1, source }); + await render(measuringFrame, { revision: 1, source }); + await render(fullFrame, { revision: 1, source }); + + for (const frame of [zeroFrame, measuringFrame]) { + frame.style.width = "700px"; + frame.style.height = "500px"; + const doc = frame.contentDocument; + if (!doc) { + throw new Error("Expected inspectable runtime document"); + } + const svgRect = doc.querySelector("#diagram svg")?.getBoundingClientRect(); + const yTitleRect = doc.querySelector(".left-axis .title text")?.getBoundingClientRect(); + const yLabels = Array.from(doc.querySelectorAll(".left-axis .label text")); + const xLabels = Array.from(doc.querySelectorAll(".bottom-axis .label text")); + expect(svgRect).not.toBeUndefined(); + expect(yTitleRect).not.toBeUndefined(); + expect(yLabels.length).toBeGreaterThan(0); + expect(xLabels.length).toBeGreaterThan(0); + + for (const label of yLabels) { + expect(yTitleRect!.right).toBeLessThan(label.getBoundingClientRect().left); + } + for (const label of xLabels) { + expect(label.getBoundingClientRect().bottom).toBeLessThanOrEqual(svgRect!.bottom); + } + } + + function axisOrigin(frame: HTMLIFrameElement): { leftAxisX: number; bottomAxisY: number } { + const doc = frame.contentDocument; + const leftPath = doc?.querySelector(".left-axis .axisl-line path")?.getAttribute("d") ?? ""; + const bottomPath = + doc?.querySelector(".bottom-axis .axis-line path")?.getAttribute("d") ?? ""; + const leftMatch = leftPath.match(/^M\s+([\d.]+),/); + const bottomMatch = bottomPath.match(/^M\s+[\d.]+,([\d.]+)/); + if (!leftMatch || !bottomMatch) { + throw new Error(`Unexpected axis paths: ${leftPath} | ${bottomPath}`); + } + return { + leftAxisX: Number.parseFloat(leftMatch[1]), + bottomAxisY: Number.parseFloat(bottomMatch[1]), + }; + } + + const fullOrigin = axisOrigin(fullFrame); + for (const candidate of [measuringFrame, zeroFrame]) { + const origin = axisOrigin(candidate); + expect(origin.leftAxisX).toBeCloseTo(fullOrigin.leftAxisX, 3); + expect(origin.bottomAxisY).toBeCloseTo(fullOrigin.bottomAxisY, 3); + } + }); + + /** + * A gantt chart takes the width of the element Mermaid renders it in. Rendering inside the large + * offscreen container must keep it as wide as the frame, which on native is the message column. + */ + it("renders a gantt chart as wide as the frame the host gives it", async () => { + const source = [ + "gantt", + " title Release plan", + " dateFormat YYYY-MM-DD", + " section Build", + " Design :a1, 2024-01-01, 10d", + " Implement :after a1, 20d", + ].join("\n"); + const widths = []; + for (const width of [240, 350, 900]) { + const frame = await mountRuntime({ height: 240, width }); + widths.push(renderedSize(await render(frame, { revision: 1, source })).width); + } + + expect(widths).toEqual([240, 350, 900]); + }); + it("coalesces queued input and never reports an obsolete result", async () => { const frame = await mountRuntime(); const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`; From b5c25e5c1055f55bab71af5c3c362c1d8af52bd1 Mon Sep 17 00:00:00 2001 From: Don Phillips Date: Thu, 12 Nov 2026 09:56:32 -0800 Subject: [PATCH 008/160] fix(opencode): discover V2 tools from bound session catalogs (#9426) Fetch tool definitions for the bound session instead of the global manifest so plugin-contributed tools can be registered and invoked. Preserve global discovery for legacy callers and existing session filtering and execution authorization. Cover session-only tool discovery, invocation, child inheritance, disabled and unrelated sessions, unbinding, and plugin reload. --- docs/providers.md | 2 +- .../agent/providers/opencode/bridge.test.ts | 151 ++++++++++++++++++ .../server/agent/providers/opencode/bridge.ts | 15 +- .../opencode/v2/shared-bridge-plugin.mjs | 5 +- .../opencode/v2/shared-bridge.test.ts | 3 +- 5 files changed, 170 insertions(+), 6 deletions(-) diff --git a/docs/providers.md b/docs/providers.md index fe3d58446a..a0b9d2f4f7 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -160,7 +160,7 @@ Use OpenCode v2 execution events to trigger turn completion, with active-state a V2.0.4 also removed the activation endpoint that gated a cold location, and a cold location registers its config-derived commands, skills, and providers asynchronously. Wait until `plugin.list` returns a populated inventory before reading the catalog or commands; an empty inventory means the location is still warming. Fail when the readiness deadline expires, including when an inventory request stalls. -Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool. +Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. V2 discovers definitions from each bound session's catalog: plugin-contributed tools can be absent from the global manifest, and an allowlist cannot register a missing definition. Registration is location-wide, so session filtering and caller-scoped execution must remain in place. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool. An agent with custom environment variables or user-configured MCP servers gets a dedicated OpenCode server. V2 supports session environment, but its MCP configuration remains location-scoped, so separate servers still prevent one agent from changing another agent's MCP setup. Configure custom MCP with `mcp.add`; do not follow it with `mcp.connect`, which only toggles config-backed servers. diff --git a/packages/server/src/server/agent/providers/opencode/bridge.test.ts b/packages/server/src/server/agent/providers/opencode/bridge.test.ts index aa7acb830c..45ce16be2b 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.test.ts @@ -77,6 +77,157 @@ function readPluginOptions(env: Record): { } describe("OpenCodeBridge", () => { + test("discovers only the requested session's catalog and retains global discovery", async () => { + const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-discovery-")); + temporaryDirectories.push(paseoHome); + const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() }); + const catalog = createCatalog(); + bridge.setManifestCatalog(catalog); + await bridge.start(); + const unbind = bridge.bindSession({ sessionId: "bound", env: {}, tools: catalog }); + bridge.bindSession({ sessionId: "disabled", env: {} }); + try { + const { baseUrl, token } = bridge.sharedV2Connection(); + async function discover(query: string) { + const response = await fetch(`${baseUrl}/_internal/opencode/tools${query}`, { + headers: { Authorization: `Bearer ${token}` }, + }); + return { status: response.status, body: await response.json() }; + } + const expected = { + status: 200, + body: { + tools: [ + { + name: "echo_context", + title: "Echo context", + description: "Returns the supplied value.", + inputSchema: serializePaseoToolInputParameters(catalog.getTool("echo_context")!), + }, + ], + }, + }; + expect(await discover("")).toEqual(expected); + expect(await discover("?sessionID=bound")).toEqual(expected); + expect(await discover("?sessionID=disabled")).toEqual({ status: 200, body: { tools: [] } }); + const missing = { + status: 404, + body: { error: "OpenCode session is not bound to a Paseo agent" }, + }; + expect(await discover("?sessionID=unknown")).toEqual(missing); + expect(await discover("?sessionID=")).toEqual(missing); + unbind(); + expect(await discover("?sessionID=bound")).toEqual(missing); + } finally { + await bridge.close(); + } + }); + + test("registers and executes session-only tools without exposing them to other sessions", async () => { + const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-session-tools-")); + temporaryDirectories.push(paseoHome); + const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() }); + const builtin = createCatalog(); + const pluginTool = { + name: "plugin_action", + description: "Run a session-specific plugin action.", + inputSchema: { value: z.string() }, + }; + const tools = new Map([...builtin.tools, [pluginTool.name, pluginTool] as const]); + const calls: unknown[] = []; + const author: PaseoToolCatalog = { + tools, + getTool: (name) => tools.get(name), + executeTool: async (name, input, context) => { + if (name !== pluginTool.name) return builtin.executeTool(name, input, context); + calls.push(input); + return { content: [{ type: "text", text: "Plugin action complete" }] }; + }, + }; + bridge.setManifestCatalog(builtin); + await bridge.start(); + bridge.bindSession({ sessionId: "author/one", env: {}, tools: author }); + bridge.bindSession({ sessionId: "other", env: {}, tools: builtin }); + bridge.bindSession({ sessionId: "disabled", env: {} }); + try { + const registered = new Map(); + const hooks: Array<(input: V2TestContext) => Promise> = []; + const dispose = await setupBoundV2Plugin( + bridge, + { + tool: { + transform: async (transform) => { + transform({ + add: (tool) => { + registered.set(tool.name, tool); + }, + }); + return { dispose: async () => undefined }; + }, + }, + session: { + context: async () => [], + get: async ({ sessionID }) => ({ + parentID: sessionID === "child" ? "author/one" : undefined, + }), + hook: async (_name, hook) => { + hooks.push(hook); + return { dispose: async () => undefined }; + }, + }, + }, + ["author/one", "other", "disabled"], + ); + try { + expect([...registered.keys()]).toEqual([ + "paseo_structured_output", + "paseo_echo_context", + `paseo_${pluginTool.name}`, + ]); + const submit = registered.get(`paseo_${pluginTool.name}`)!; + expect(submit.input).toEqual(serializePaseoToolInputParameters(pluginTool)); + const visibleTools = [ + ["author/one", ["paseo_echo_context", `paseo_${pluginTool.name}`, "native"]], + ["child", ["paseo_echo_context", `paseo_${pluginTool.name}`, "native"]], + ["other", ["paseo_echo_context", "native"]], + ["disabled", ["native"]], + ["unrelated", ["native"]], + ] as const; + for (const [sessionID, expected] of visibleTools) { + const input = { + sessionID, + tools: Object.fromEntries([...registered.keys(), "native"].map((name) => [name, {}])), + }; + for (const hook of hooks) await hook(input); + expect(Object.keys(input.tools)).toEqual(expected); + } + await expect( + submit.execute({ value: "revision" }, { sessionID: "author/one" }), + ).resolves.toMatchObject({ content: [{ type: "text", text: "Plugin action complete" }] }); + await expect( + submit.execute({ value: "child revision" }, { sessionID: "child" }), + ).resolves.toMatchObject({ content: [{ type: "text", text: "Plugin action complete" }] }); + await expect(submit.execute({}, { sessionID: "other" })).rejects.toThrow( + "Paseo tool not found", + ); + await expect(submit.execute({}, { sessionID: "disabled" })).rejects.toThrow( + "Paseo tools are disabled", + ); + await expect(submit.execute({}, { sessionID: "unrelated" })).rejects.toThrow("not bound"); + expect(calls).toEqual([{ value: "revision" }, { value: "child revision" }]); + await expect( + registered + .get("paseo_echo_context")! + .execute({ value: "builtin" }, { sessionID: "other" }), + ).resolves.toMatchObject({ content: [{ type: "text", text: "builtin" }] }); + } finally { + await dispose(); + } + } finally { + await bridge.close(); + } + }); + test("advertises agent-scoped schemas that execute through both bridge plugins", async () => { const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-manifest-")); temporaryDirectories.push(paseoHome); diff --git a/packages/server/src/server/agent/providers/opencode/bridge.ts b/packages/server/src/server/agent/providers/opencode/bridge.ts index 87ee07798b..3b04ecb6cf 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge.ts @@ -166,7 +166,9 @@ export class OpenCodeBridge { } const url = new URL(request.url ?? "/", this.requireBaseUrl()); if (request.method === "GET" && url.pathname === `${INTERNAL_PREFIX}/tools`) { - sendJson(response, 200, { tools: this.serializeManifest() }); + sendJson(response, 200, { + tools: this.serializeManifest(url.searchParams.get("sessionID")), + }); return; } @@ -228,8 +230,15 @@ export class OpenCodeBridge { } } - private serializeManifest(): Array> { - const catalog = this.manifestCatalog; + private serializeManifest(sessionId: string | null): Array> { + let catalog: Pick | null | undefined = this.manifestCatalog; + if (sessionId !== null) { + const binding = this.sessions.get(sessionId); + if (!binding) { + throw new OpenCodeBridgeClientError(404, "OpenCode session is not bound to a Paseo agent"); + } + catalog = binding.tools; + } if (!catalog) return []; return [...catalog.tools.values()].map((tool) => { const definition: Record = { diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs index 4be98bfba9..1eaaad53af 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs @@ -38,7 +38,10 @@ export async function registerSharedBridge(context) { return null; } async function install(binding) { - const manifest = await request(binding, "/tools"); + const manifest = await request( + binding, + `/tools?sessionID=${encodeURIComponent(binding.sessionID)}`, + ); for (const definition of manifest.tools) await installDefinition(definition); } async function installDefinition(definition) { diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts index c560fa6558..385b6daff7 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts @@ -27,7 +27,8 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions" const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() }); const tool = { name: "echo", description: "echo", inputSchema: { value: z.string() } }; const tools = new Map([[tool.name, tool]]); - bridge.setManifestCatalog({ tools }); + // Session-only tools must survive plugin reload without a global definition. + bridge.setManifestCatalog({ tools: new Map() }); await bridge.start(); const unbind = bridge.bindSession({ sessionId: "paseo", From d426088c3f78cdfb332812ab8eeb85cef343743a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:04:24 +0000 Subject: [PATCH 009/160] Stop agent updates re-rendering the workspace screen, favicon, and command center (#9497) * Stop hidden surfaces rebuilding the agent directory on every update The favicon is mounted at the root of every web and Electron session, and it derived the whole aggregated agent list to answer three questions: is any agent running, does any want attention, does any need input. The aggregated list allocates a projection per agent, deep-compares it, sorts the whole host and rebuilds its identity cache, and useAggregatedAgents re-ran all of that on every agent update on any host. The dock badge did the same for workspaces: it materialised every workspace status and deep-compared the array for a number. Both now read a scalar selector: selectFaviconStatus walks the agent maps and returns one of three strings, and selectMacDockBadgeCount counts actionable workspaces without building a list. A store write that leaves those values alone no longer re-renders the root component. useAggregatedAgents also treated `demand` as "hold the directory subscription" but still subscribed to every host's agent map, so the closed command center (useAggregatedAgents({ demand: open })) rebuilt the full list on every update too. With demand false the hook now returns a stable empty result and stays off the maps. Measured on the many-agent-tabs harness (5 tabs, 20 s windows, agent_update churn from a background host): the root favicon component rendered 1554 times in 20 s before this change and 1 time after. * Complete the host runtime mock in the favicon test * Keep the profiling harness out of the fix The harness scans every process environment to find the daemon. Whether Paseo carries a renderer CPU harness, and how it samples processes, is a separate decision from the rendering fix. Co-Authored-By: Claude Opus 5.5 * Stop re-rendering the workspace screen on unrelated agent updates useOpenAgentTabLabels subscribed the workspace screen to the host's whole agent map. Every agent update on the host replaces that map, so each update re-rendered the open workspace screen, its split panes and tab menus. Subscribe only to the agents that have open tabs. Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * Test render isolation through pure selectors and the browser Replace the JSDOM hook tests and module mocks with pure selector tests and a browser test that updates an agent in another workspace and checks the open workspace screen does not re-render. Memoize the favicon and dock badge selectors on the session maps they read, so unrelated store writes skip the scan, and pass directory demand as an object. Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../workspace-unrelated-agent-update.spec.ts | 56 ++++++++++++++ .../app/src/hooks/use-aggregated-agents.ts | 30 ++++++-- .../app/src/hooks/use-directory-demand.ts | 18 +++++ packages/app/src/hooks/use-favicon-status.ts | 53 ++++++------- .../src/stores/session-store-hooks/index.ts | 16 +--- .../session-store-hooks/selectors.test.ts | 31 -------- .../stores/session-store-hooks/selectors.ts | 14 ---- .../app/src/subagents/open-tab-labels.test.ts | 54 ++++++++++++- packages/app/src/subagents/open-tab-labels.ts | 21 +++++ .../subagents/use-open-agent-tab-labels.ts | 30 +++++--- .../app/src/utils/desktop-badge-state.test.ts | 76 ++++++++++++++++--- packages/app/src/utils/desktop-badge-state.ts | 35 ++++++++- packages/app/src/utils/favicon-status.test.ts | 71 +++++++++++++++++ packages/app/src/utils/favicon-status.ts | 40 ++++++++++ .../app/src/utils/memoize-on-session-maps.ts | 31 ++++++++ 15 files changed, 449 insertions(+), 127 deletions(-) create mode 100644 packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts create mode 100644 packages/app/src/utils/favicon-status.test.ts create mode 100644 packages/app/src/utils/favicon-status.ts create mode 100644 packages/app/src/utils/memoize-on-session-maps.ts diff --git a/packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts b/packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts new file mode 100644 index 0000000000..8d283191c2 --- /dev/null +++ b/packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts @@ -0,0 +1,56 @@ +import { test, expect } from "../support/fixtures"; +import { openAgentRoute } from "../support/helpers/mock-agent"; +import { + readReactRenders, + recordReactRenders, + resetReactRenders, +} from "../support/helpers/react-renders"; +import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client"; + +async function createMockAgent(workspace: SeededWorkspace, title: string): Promise { + const agent = await workspace.client.createAgent({ + provider: "mock", + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title, + modeId: "load-test", + model: "e2e-fast-stream", + }); + return agent.id; +} + +test.describe("Updates to agents in other workspaces", () => { + let open: SeededWorkspace; + let other: SeededWorkspace; + + test.afterEach(async () => { + await open?.cleanup(); + await other?.cleanup(); + }); + + test("do not re-render the open workspace screen", async ({ page }) => { + open = await seedWorkspace({ repoPrefix: "unrelated-update-open-", title: "Open" }); + other = await seedWorkspace({ repoPrefix: "unrelated-update-other-", title: "Other" }); + const openAgentId = await createMockAgent(open, "Open agent"); + const otherAgentId = await createMockAgent(other, "Other agent"); + + await recordReactRenders(page); + await openAgentRoute(page, { workspaceId: open.workspaceId, agentId: openAgentId }); + await expect( + page.getByTestId(`workspace-tab-agent_${openAgentId}`).filter({ visible: true }).first(), + ).toBeVisible({ timeout: 60_000 }); + await page.waitForTimeout(2_000); + await resetReactRenders(page); + + await other.client.sendAgentMessage(otherAgentId, "update"); + await other.client.waitForFinish(otherAgentId, 60_000); + // The favicon follows every agent on the host, so it renders when the other agent runs and + // settles. That confirms the updates reached this page. + await expect + .poll(async () => (await readReactRenders(page)).FaviconStatusSync ?? 0) + .toBeGreaterThan(0); + + const renders = await readReactRenders(page); + expect(renders.WorkspaceScreenContent ?? 0).toBe(0); + }); +}); diff --git a/packages/app/src/hooks/use-aggregated-agents.ts b/packages/app/src/hooks/use-aggregated-agents.ts index 910caf1d64..ffce971ca6 100644 --- a/packages/app/src/hooks/use-aggregated-agents.ts +++ b/packages/app/src/hooks/use-aggregated-agents.ts @@ -1,10 +1,11 @@ -import { useMemo, useCallback, useEffect, useRef, useSyncExternalStore } from "react"; +import { useMemo, useCallback, useRef, useSyncExternalStore } from "react"; import equal from "fast-deep-equal"; import { useShallow } from "zustand/shallow"; import { useSessionStore } from "@/stores/session-store"; import type { AgentDirectoryEntry } from "@/types/agent-directory"; import type { Agent } from "@/stores/session-store"; import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime"; +import { useAllDirectoryDemand } from "./use-directory-demand"; export interface AggregatedAgent extends AgentDirectoryEntry { serverId: string; @@ -19,6 +20,9 @@ export interface AggregatedAgentsResult { refreshAll: () => void; } +const NO_AGENT_MAPS: Record | undefined> = Object.freeze({}); +const NO_AGENTS: AggregatedAgent[] = []; + export function useAggregatedAgents(options?: { includeArchived?: boolean; demand?: boolean; @@ -28,19 +32,21 @@ export function useAggregatedAgents(options?: { const includeArchived = options?.includeArchived ?? false; const demand = options?.demand ?? true; const serverIds = useMemo(() => daemons.map((daemon) => daemon.serverId), [daemons]); - useEffect(() => { - if (!demand) return; - const releases = serverIds.map((serverId) => runtime.acquireDirectoryDemand(serverId)); - return () => releases.forEach((release) => release()); - }, [demand, runtime, serverIds]); + useAllDirectoryDemand({ serverIds, enabled: demand }); const runtimeVersion = useSyncExternalStore( (onStoreChange) => runtime.subscribeAll(onStoreChange), () => runtime.getVersion(), () => runtime.getVersion(), ); + // The caller has said it does not need the directory, so stay off the agent maps entirely: + // every map change otherwise re-renders this hook and rebuilds the whole list for a surface + // that is not on screen (the command center while it is closed). const sessionAgents = useSessionStore( useShallow((state) => { + if (!demand) { + return NO_AGENT_MAPS; + } const result: Record | undefined> = {}; for (const [serverId, session] of Object.entries(state.sessions)) { result[serverId] = session.agents; @@ -64,6 +70,16 @@ export function useAggregatedAgents(options?: { const result = useMemo(() => { // runtimeVersion is referenced so the memo recomputes when runtime state changes. void runtimeVersion; + if (!demand) { + prevAgentsRef.current = new Map(); + prevSortedRef.current = NO_AGENTS; + return { + agents: NO_AGENTS, + isLoading: false, + isInitialLoad: false, + isRevalidating: false, + }; + } const allAgents: AggregatedAgent[] = []; const serverLabelById = new Map( daemons.map((daemon) => [daemon.serverId, daemon.label] as const), @@ -158,7 +174,7 @@ export function useAggregatedAgents(options?: { isInitialLoad, isRevalidating, }; - }, [daemons, includeArchived, runtime, runtimeVersion, sessionAgents]); + }, [daemons, demand, includeArchived, runtime, runtimeVersion, sessionAgents]); return { ...result, diff --git a/packages/app/src/hooks/use-directory-demand.ts b/packages/app/src/hooks/use-directory-demand.ts index f4d2953ab0..b9e8ccb9a2 100644 --- a/packages/app/src/hooks/use-directory-demand.ts +++ b/packages/app/src/hooks/use-directory-demand.ts @@ -14,3 +14,21 @@ export function useDirectoryDemand(serverId: string | null | undefined): void { return getHostRuntimeStore().acquireDirectoryDemand(serverId); }, [serverId]); } + +/** + * Holds directory demand for several hosts at once, so a caller that needs the whole fleet + * (the favicon, the aggregated agent list) does not have to subscribe to every agent map to + * keep the directories loading. + */ +export function useAllDirectoryDemand(input: { + serverIds: readonly string[]; + enabled: boolean; +}): void { + const { serverIds, enabled } = input; + useEffect(() => { + if (!enabled) return; + const runtime = getHostRuntimeStore(); + const releases = serverIds.map((serverId) => runtime.acquireDirectoryDemand(serverId)); + return () => releases.forEach((release) => release()); + }, [enabled, serverIds]); +} diff --git a/packages/app/src/hooks/use-favicon-status.ts b/packages/app/src/hooks/use-favicon-status.ts index 5fcce9a24c..4686b10ff8 100644 --- a/packages/app/src/hooks/use-favicon-status.ts +++ b/packages/app/src/hooks/use-favicon-status.ts @@ -1,12 +1,13 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { getIsElectronRuntimeMac } from "@/constants/layout"; -import { useAggregatedAgents } from "./use-aggregated-agents"; +import { useAllDirectoryDemand } from "./use-directory-demand"; import { getDesktopHost } from "@/desktop/host"; -import { useWorkspaceStatusesForBadges } from "@/stores/session-store-hooks"; -import { deriveMacDockBadgeCountFromWorkspaceStatuses } from "@/utils/desktop-badge-state"; +import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state"; +import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status"; import { isNative } from "@/constants/platform"; +import { useSessionStore } from "@/stores/session-store"; +import { useHosts } from "@/runtime/host-runtime"; -type FaviconStatus = "none" | "running" | "attention"; type ColorScheme = "dark" | "light"; /* eslint-disable @typescript-eslint/no-require-imports */ @@ -24,21 +25,6 @@ const FAVICON_IMAGES: Record["agents"], -): FaviconStatus { - const hasRunning = agents.some((agent) => agent.status === "running"); - if (hasRunning) { - return "running"; - } - const hasAttention = agents.some((agent) => agent.requiresAttention); - const hasNeedsInput = agents.some((agent) => (agent.pendingPermissionCount ?? 0) > 0); - if (hasAttention || hasNeedsInput) { - return "attention"; - } - return "none"; -} - function getFaviconUri(status: FaviconStatus, colorScheme: ColorScheme): string { const image = FAVICON_IMAGES[colorScheme][status]; if (typeof image === "object" && "uri" in image) { @@ -94,8 +80,15 @@ async function updateMacDockBadge(count?: number) { } export function useFaviconStatus() { - const { agents } = useAggregatedAgents({ demand: !isNative }); - const workspaceStatuses = useWorkspaceStatusesForBadges(); + const daemons = useHosts(); + const serverIds = useMemo(() => daemons.map((daemon) => daemon.serverId), [daemons]); + // The favicon reads the whole fleet, so it has to keep every host's directory loading even + // though it no longer subscribes to the agent maps. + useAllDirectoryDemand({ serverIds, enabled: !isNative }); + const selectFaviconStatus = useMemo(createFaviconStatusSelector, []); + const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []); + const status = useSessionStore(selectFaviconStatus); + const dockBadgeCount = useSessionStore(selectMacDockBadgeCount); const [colorScheme, setColorScheme] = useState(getSystemColorScheme); const lastDockBadgeCountRef = useRef(undefined); @@ -112,17 +105,15 @@ export function useFaviconStatus() { return () => mediaQuery.removeEventListener("change", handler); }, []); - // Update favicon when agents or color scheme changes useEffect(() => { if (isNative) return; - - const status = deriveFaviconStatus(agents); updateFavicon(status, colorScheme); + }, [status, colorScheme]); - const dockBadgeCount = deriveMacDockBadgeCountFromWorkspaceStatuses(workspaceStatuses); - if (dockBadgeCount !== lastDockBadgeCountRef.current) { - lastDockBadgeCountRef.current = dockBadgeCount; - void updateMacDockBadge(dockBadgeCount); - } - }, [agents, colorScheme, workspaceStatuses]); + useEffect(() => { + if (isNative) return; + if (dockBadgeCount === lastDockBadgeCountRef.current) return; + lastDockBadgeCountRef.current = dockBadgeCount; + void updateMacDockBadge(dockBadgeCount); + }, [dockBadgeCount]); } diff --git a/packages/app/src/stores/session-store-hooks/index.ts b/packages/app/src/stores/session-store-hooks/index.ts index d6d4a188c1..e2cc20454f 100644 --- a/packages/app/src/stores/session-store-hooks/index.ts +++ b/packages/app/src/stores/session-store-hooks/index.ts @@ -17,22 +17,16 @@ import { selectWorkspaceExists, selectWorkspaceFields, selectWorkspaceKeys, - selectWorkspaceStatusesForBadges, workspaceEqualityFns, type WorkspaceStructure, } from "./selectors"; import { useSessionStore, type WorkspaceDescriptor } from "../session-store"; -import type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; // These are the ONLY supported ways to read workspaces from the session store. // Do not write raw `useSessionStore` selectors that return the workspaces Map, a session object, // or the sessions dict — it breaks re-render isolation. -export type { - DesktopBadgeWorkspaceStatus, - WorkspaceStructure, - WorkspaceStructureProject, -} from "./selectors"; +export type { WorkspaceStructure, WorkspaceStructureProject } from "./selectors"; export function useWorkspace( serverId: string | null, @@ -163,11 +157,3 @@ export function useHasWorkspaces(serverId: string | null): boolean { workspaceEqualityFns.identity, ); } - -export function useWorkspaceStatusesForBadges(): DesktopBadgeWorkspaceStatus[] { - return useStoreWithEqualityFn( - useSessionStore, - (state) => selectWorkspaceStatusesForBadges(state), - workspaceEqualityFns.deep, - ); -} diff --git a/packages/app/src/stores/session-store-hooks/selectors.test.ts b/packages/app/src/stores/session-store-hooks/selectors.test.ts index 95cc1ba498..68caaf2294 100644 --- a/packages/app/src/stores/session-store-hooks/selectors.test.ts +++ b/packages/app/src/stores/session-store-hooks/selectors.test.ts @@ -14,7 +14,6 @@ import { selectWorkspaceDirectory, selectWorkspaceFields, selectWorkspaceKeys, - selectWorkspaceStatusesForBadges, selectWorkspaceStructureProjects, workspaceEqualityFns, type SidebarOrderSnapshot, @@ -589,36 +588,6 @@ describe("selectHasWorkspaces", () => { }); }); -describe("selectWorkspaceStatusesForBadges", () => { - it("tracks status changes without changing for no-ops or unrelated descriptor updates", () => { - const workspaceA = createWorkspace({ id: "workspace-a", status: "done" }); - const workspaceB = createWorkspace({ id: "workspace-b", status: "attention" }); - initializeWorkspaces([workspaceA, workspaceB]); - - const tracked = trackSelector( - useSessionStore, - (state) => selectWorkspaceStatusesForBadges(state), - workspaceEqualityFns.deep, - ); - const before = tracked.current; - expect(before).toEqual(["done", "attention"]); - - useSessionStore - .getState() - .mergeWorkspaces(SERVER_ID, [{ ...workspaceA, scripts: [...workspaceA.scripts] }]); - expect(tracked.current).toBe(before); - - useSessionStore.getState().mergeWorkspaces(SERVER_ID, [{ ...workspaceB, name: "Renamed" }]); - expect(tracked.current).toBe(before); - - useSessionStore.getState().mergeWorkspaces(SERVER_ID, [{ ...workspaceA, status: "failed" }]); - expect(tracked.current).not.toBe(before); - expect(tracked.current).toEqual(["failed", "attention"]); - - tracked.stop(); - }); -}); - it("a prompt changes only its project's structure and output preserves both project identities", () => { const a = { ...createWorkspace({ id: "a", projectId: "p" }), createdAt: new Date("2026-01-01") }; const b = { ...createWorkspace({ id: "b", projectId: "p" }), createdAt: new Date("2026-02-01") }; diff --git a/packages/app/src/stores/session-store-hooks/selectors.ts b/packages/app/src/stores/session-store-hooks/selectors.ts index 85169b6f4a..832ae54ca2 100644 --- a/packages/app/src/stores/session-store-hooks/selectors.ts +++ b/packages/app/src/stores/session-store-hooks/selectors.ts @@ -5,11 +5,9 @@ import { type WorkspaceStructure, type WorkspaceStructureProject, } from "@/projects/workspace-structure"; -import type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity"; import type { ProjectDescriptor, WorkspaceDescriptor } from "../session-store"; -export type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; export type { WorkspaceStructure, WorkspaceStructureProject } from "@/projects/workspace-structure"; export interface SessionsSnapshot { @@ -321,15 +319,3 @@ export function selectHasWorkspaces(state: SessionsSnapshot, serverId: string | } return (state.sessions[serverId]?.workspaces?.size ?? 0) > 0; } - -export function selectWorkspaceStatusesForBadges( - state: SessionsSnapshot, -): DesktopBadgeWorkspaceStatus[] { - const statuses: DesktopBadgeWorkspaceStatus[] = []; - for (const session of Object.values(state.sessions)) { - for (const workspace of session.workspaces.values()) { - statuses.push(workspace.status); - } - } - return statuses; -} diff --git a/packages/app/src/subagents/open-tab-labels.test.ts b/packages/app/src/subagents/open-tab-labels.test.ts index 61874cd058..9cab01f11b 100644 --- a/packages/app/src/subagents/open-tab-labels.test.ts +++ b/packages/app/src/subagents/open-tab-labels.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from "vitest"; import type { Agent } from "@/stores/session-store"; import type { WorkspaceTab } from "@/workspace-tabs/model"; -import { getAgentTabsNeedingOpenLabel } from "./open-tab-labels"; +import { shallow } from "zustand/shallow"; +import { getAgentTabsNeedingOpenLabel, selectOpenTabAgents } from "./open-tab-labels"; const label = "paseo.open-agent-tab.client-1"; @@ -51,3 +52,54 @@ describe("getAgentTabsNeedingOpenLabel", () => { ).toEqual([]); }); }); + +describe("selectOpenTabAgents", () => { + function stateWith(agents: Agent[]) { + return { + sessions: { + srv: { agents: new Map(agents.map((entry) => [entry.id, entry])), agentDetails: new Map() }, + }, + }; + } + + it("stays equal when only an agent without an open tab changes", () => { + const open = agent({ id: "open" }); + const before = selectOpenTabAgents(stateWith([open, agent({ id: "elsewhere" })]), { + serverId: "srv", + agentIds: ["open"], + }); + const after = selectOpenTabAgents(stateWith([open, agent({ id: "elsewhere" })]), { + serverId: "srv", + agentIds: ["open"], + }); + + expect(shallow(before, after)).toBe(true); + }); + + it("changes when an agent with an open tab changes", () => { + const elsewhere = agent({ id: "elsewhere" }); + const before = selectOpenTabAgents(stateWith([agent({ id: "open" }), elsewhere]), { + serverId: "srv", + agentIds: ["open"], + }); + const after = selectOpenTabAgents(stateWith([agent({ id: "open" }), elsewhere]), { + serverId: "srv", + agentIds: ["open"], + }); + + expect(shallow(before, after)).toBe(false); + }); + + it("falls back to agent details and returns null for unknown agents", () => { + const detail = agent({ id: "detail" }); + const state = { + sessions: { + srv: { agents: new Map(), agentDetails: new Map([["detail", detail]]) }, + }, + }; + + expect( + selectOpenTabAgents(state, { serverId: "srv", agentIds: ["detail", "missing"] }), + ).toEqual([detail, null]); + }); +}); diff --git a/packages/app/src/subagents/open-tab-labels.ts b/packages/app/src/subagents/open-tab-labels.ts index ca7d8e63dc..df855a6df5 100644 --- a/packages/app/src/subagents/open-tab-labels.ts +++ b/packages/app/src/subagents/open-tab-labels.ts @@ -23,3 +23,24 @@ export function getAgentTabsNeedingOpenLabel(input: { } return [...agentIds]; } + +interface OpenTabAgentSource { + sessions: Record< + string, + { agents: ReadonlyMap; agentDetails: ReadonlyMap } | undefined + >; +} + +/** + * The agents behind the given open tabs, in tab order. Compared element by element, this changes + * only when one of those agents changes, not on updates to other agents on the host. + */ +export function selectOpenTabAgents( + state: OpenTabAgentSource, + input: { serverId: string; agentIds: readonly string[] }, +): (Agent | null)[] { + const session = state.sessions[input.serverId]; + return input.agentIds.map( + (agentId) => session?.agents.get(agentId) ?? session?.agentDetails.get(agentId) ?? null, + ); +} diff --git a/packages/app/src/subagents/use-open-agent-tab-labels.ts b/packages/app/src/subagents/use-open-agent-tab-labels.ts index ea02fd1b16..7570d65465 100644 --- a/packages/app/src/subagents/use-open-agent-tab-labels.ts +++ b/packages/app/src/subagents/use-open-agent-tab-labels.ts @@ -1,10 +1,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { getOpenAgentTabLabel } from "@getpaseo/protocol/agent-labels"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { useShallow } from "zustand/shallow"; import { useSessionStore } from "@/stores/session-store"; import { getOrCreateClientId } from "@/utils/client-id"; import type { WorkspaceTab } from "@/workspace-tabs/model"; -import { getAgentTabsNeedingOpenLabel } from "./open-tab-labels"; +import { getAgentTabsNeedingOpenLabel, selectOpenTabAgents } from "./open-tab-labels"; function increment(value: number): number { return value + 1; @@ -16,9 +17,16 @@ export function useOpenAgentTabLabels(input: { tabs: WorkspaceTab[]; enabled: boolean; }): void { - const agents = useSessionStore((state) => state.sessions[input.serverId]?.agents ?? null); - const agentDetails = useSessionStore( - (state) => state.sessions[input.serverId]?.agentDetails ?? null, + const openAgentIds = useMemo( + () => input.tabs.flatMap((tab) => (tab.target.kind === "agent" ? [tab.target.agentId] : [])), + [input.tabs], + ); + // Only the agents with open tabs can need a label. Subscribing to the whole agent map would + // re-render the workspace screen on every update to any agent on the host. + const openAgents = useSessionStore( + useShallow((state) => + selectOpenTabAgents(state, { serverId: input.serverId, agentIds: openAgentIds }), + ), ); const pendingAgentIdsRef = useRef(new Set()); const retryTimerRef = useRef | null>(null); @@ -39,15 +47,13 @@ export function useOpenAgentTabLabels(input: { return; } - const openAgentIds = new Set( - input.tabs.flatMap((tab) => (tab.target.kind === "agent" ? [tab.target.agentId] : [])), - ); + const agentsById = new Map(openAgentIds.map((agentId, index) => [agentId, openAgents[index]])); for (const agentId of pendingAgentIdsRef.current) { - if (!openAgentIds.has(agentId)) { + if (!agentsById.has(agentId)) { pendingAgentIdsRef.current.delete(agentId); } } - if (openAgentIds.size === 0) { + if (agentsById.size === 0) { return; } @@ -57,7 +63,7 @@ export function useOpenAgentTabLabels(input: { const label = getOpenAgentTabLabel(clientId); const agentIds = getAgentTabsNeedingOpenLabel({ tabs: input.tabs, - getAgent: (agentId) => agents?.get(agentId) ?? agentDetails?.get(agentId), + getAgent: (agentId) => agentsById.get(agentId), label, pendingAgentIds: pendingAgentIdsRef.current, }); @@ -82,5 +88,5 @@ export function useOpenAgentTabLabels(input: { console.warn("[OpenAgentTabLabels] Failed to resolve client ID", { error }); } })(); - }, [agentDetails, agents, input.client, input.enabled, input.tabs, retryVersion]); + }, [input.client, input.enabled, input.tabs, openAgentIds, openAgents, retryVersion]); } diff --git a/packages/app/src/utils/desktop-badge-state.test.ts b/packages/app/src/utils/desktop-badge-state.test.ts index 9bcdd39bc4..69c747bcfe 100644 --- a/packages/app/src/utils/desktop-badge-state.test.ts +++ b/packages/app/src/utils/desktop-badge-state.test.ts @@ -1,9 +1,39 @@ import { describe, expect, it } from "vitest"; +import type { WorkspaceDescriptor } from "@/stores/session-store"; import { - deriveMacDockBadgeCountFromWorkspaceStatuses, + createMacDockBadgeCountSelector, isWorkspaceActionableForDesktopBadge, + selectMacDockBadgeCount, } from "./desktop-badge-state"; +function workspace(id: string, status: WorkspaceDescriptor["status"]): WorkspaceDescriptor { + return { + createdAt: null, + lastUserMessageAt: null, + id, + projectId: "project-1", + projectDisplayName: "Project 1", + projectRootPath: "/repo", + workspaceDirectory: "/repo", + projectKind: "git", + workspaceKind: "local_checkout", + name: id, + status, + archivingAt: null, + statusEnteredAt: null, + diffStat: null, + scripts: [], + }; +} + +function stateWith(...workspaces: WorkspaceDescriptor[]) { + return { + sessions: { + srv_a: { workspaces: new Map(workspaces.map((entry) => [entry.id, entry])) }, + }, + }; +} + describe("desktop-badge-state", () => { it("treats attention-requiring workspace statuses as actionable", () => { expect(isWorkspaceActionableForDesktopBadge("attention")).toBe(true); @@ -17,18 +47,40 @@ describe("desktop-badge-state", () => { }); it("returns undefined when no visible workspaces need attention", () => { - expect(deriveMacDockBadgeCountFromWorkspaceStatuses(["done", "running"])).toBeUndefined(); + expect( + selectMacDockBadgeCount(stateWith(workspace("a", "done"), workspace("b", "running"))), + ).toBeUndefined(); }); - it("counts only actionable visible workspaces", () => { - expect( - deriveMacDockBadgeCountFromWorkspaceStatuses([ - "done", - "attention", - "running", - "needs_input", - "failed", - ]), - ).toBe(3); + it("counts only actionable visible workspaces across every host", () => { + const state = { + sessions: { + srv_a: { + workspaces: new Map([ + ["a", workspace("a", "done")], + ["b", workspace("b", "attention")], + ]), + }, + srv_b: { + workspaces: new Map([ + ["c", workspace("c", "running")], + ["d", workspace("d", "needs_input")], + ["e", workspace("e", "failed")], + ]), + }, + }, + }; + expect(selectMacDockBadgeCount(state)).toBe(3); + }); + + it("recounts only when a workspace map is replaced", () => { + const select = createMacDockBadgeCountSelector(); + const state = stateWith(workspace("a", "attention")); + expect(select(state)).toBe(1); + + state.sessions.srv_a.workspaces.set("b", workspace("b", "failed")); + expect(select({ sessions: { ...state.sessions } })).toBe(1); + + expect(select(stateWith(workspace("a", "attention"), workspace("b", "failed")))).toBe(2); }); }); diff --git a/packages/app/src/utils/desktop-badge-state.ts b/packages/app/src/utils/desktop-badge-state.ts index 00a2a78328..94cf025b50 100644 --- a/packages/app/src/utils/desktop-badge-state.ts +++ b/packages/app/src/utils/desktop-badge-state.ts @@ -1,14 +1,41 @@ import type { WorkspaceDescriptor } from "@/stores/session-store"; +import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; export type DesktopBadgeWorkspaceStatus = WorkspaceDescriptor["status"]; +interface WorkspaceStatusSession { + workspaces: ReadonlyMap; +} + +interface WorkspaceStatusSource { + sessions: Record; +} + export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspaceStatus): boolean { return status === "attention" || status === "needs_input" || status === "failed"; } -export function deriveMacDockBadgeCountFromWorkspaceStatuses( - statuses: readonly DesktopBadgeWorkspaceStatus[], -): number | undefined { - const actionableCount = statuses.filter(isWorkspaceActionableForDesktopBadge).length; +/** + * The macOS dock badge only needs a count, so count here instead of materialising every + * workspace status and comparing the whole list on every store write. + */ +export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined { + let actionableCount = 0; + for (const session of Object.values(state.sessions)) { + if (!session) continue; + for (const workspace of session.workspaces.values()) { + if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1; + } + } return actionableCount > 0 ? actionableCount : undefined; } + +/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */ +export function createMacDockBadgeCountSelector(): ( + state: WorkspaceStatusSource, +) => number | undefined { + return memoizeOnSessionMaps( + (session) => session.workspaces, + selectMacDockBadgeCount, + ); +} diff --git a/packages/app/src/utils/favicon-status.test.ts b/packages/app/src/utils/favicon-status.test.ts new file mode 100644 index 0000000000..6bb6a71d8e --- /dev/null +++ b/packages/app/src/utils/favicon-status.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import type { Agent } from "@/stores/session-store"; +import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status"; + +function agent(input: Partial & { id: string }): Agent { + return { + status: "idle", + background: false, + archivedAt: null, + requiresAttention: false, + pendingPermissions: [], + ...input, + } as Agent; +} + +function stateWith(...agents: Agent[]) { + return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } }; +} + +describe("deriveFaviconStatus", () => { + it("is running when any visible agent runs", () => { + expect( + deriveFaviconStatus( + stateWith( + agent({ id: "a", requiresAttention: true }), + agent({ id: "b", status: "running" }), + ), + ), + ).toBe("running"); + }); + + it("needs attention for attention or pending permissions", () => { + expect(deriveFaviconStatus(stateWith(agent({ id: "a", requiresAttention: true })))).toBe( + "attention", + ); + expect( + deriveFaviconStatus( + stateWith(agent({ id: "a", pendingPermissions: [{}] as Agent["pendingPermissions"] })), + ), + ).toBe("attention"); + }); + + it("ignores background and archived agents", () => { + expect( + deriveFaviconStatus( + stateWith( + agent({ id: "a", status: "running", background: true }), + agent({ id: "b", requiresAttention: true, archivedAt: new Date() }), + ), + ), + ).toBe("none"); + }); +}); + +describe("createFaviconStatusSelector", () => { + it("reuses its result while the agent maps are unchanged", () => { + const select = createFaviconStatusSelector(); + const state = stateWith(agent({ id: "a", status: "running" })); + expect(select(state)).toBe("running"); + + // Same agent map, mutated behind the store's back: the selector must not rescan. + state.sessions.srv.agents.set("a", agent({ id: "a" })); + expect(select({ sessions: { ...state.sessions } })).toBe("running"); + }); + + it("rescans when an agent map is replaced", () => { + const select = createFaviconStatusSelector(); + expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running"); + expect(select(stateWith(agent({ id: "a" })))).toBe("none"); + }); +}); diff --git a/packages/app/src/utils/favicon-status.ts b/packages/app/src/utils/favicon-status.ts new file mode 100644 index 0000000000..62d1630ab7 --- /dev/null +++ b/packages/app/src/utils/favicon-status.ts @@ -0,0 +1,40 @@ +import type { Agent } from "@/stores/session-store"; +import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; + +export type FaviconStatus = "none" | "running" | "attention"; + +interface FaviconAgentSession { + agents: ReadonlyMap; +} + +interface FaviconAgentSource { + sessions: Record; +} + +/** + * The favicon is the only always-mounted consumer of the whole agent directory, so derive its + * three states here instead of building the aggregated agent list: the list allocates a + * projection per agent, deep-compares it and sorts every agent on the host on each update. + */ +export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus { + let hasAttention = false; + let hasNeedsInput = false; + for (const session of Object.values(state.sessions)) { + if (!session) continue; + for (const agent of session.agents.values()) { + if (agent.background || agent.archivedAt) continue; + if (agent.status === "running") return "running"; + if (agent.requiresAttention) hasAttention = true; + if (agent.pendingPermissions.length > 0) hasNeedsInput = true; + } + } + return hasAttention || hasNeedsInput ? "attention" : "none"; +} + +/** A session-store selector for the favicon status that rescans only when an agent map changes. */ +export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus { + return memoizeOnSessionMaps( + (session) => session.agents, + deriveFaviconStatus, + ); +} diff --git a/packages/app/src/utils/memoize-on-session-maps.ts b/packages/app/src/utils/memoize-on-session-maps.ts new file mode 100644 index 0000000000..ed621ee1c4 --- /dev/null +++ b/packages/app/src/utils/memoize-on-session-maps.ts @@ -0,0 +1,31 @@ +interface SessionsSource { + sessions: Record; +} + +/** + * Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has + * changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost + * a reference check per host instead of a walk over every entry. + */ +export function memoizeOnSessionMaps, TResult>( + pickMap: (session: TSession) => unknown, + derive: (state: TState) => TResult, +): (state: TState) => TResult { + let previousMaps: unknown[] | null = null; + let previousResult: TResult; + return (state) => { + const maps = Object.values(state.sessions).map((session) => + session ? pickMap(session) : undefined, + ); + if ( + previousMaps && + previousMaps.length === maps.length && + previousMaps.every((map, index) => map === maps[index]) + ) { + return previousResult; + } + previousMaps = maps; + previousResult = derive(state); + return previousResult; + }; +} From 21709812bb3dbb3191f9d5cda2f342b628eb4071 Mon Sep 17 00:00:00 2001 From: Rock Date: Thu, 12 Nov 2026 13:02:10 -0800 Subject: [PATCH 010/160] fix(codex): retry an oversized history page with smaller pages (#9432) thread/items/list asks for 100 items a page. On image-heavy threads a page can exceed the app-server's line cap, and the history stopped at the first such page with a "too large to load" warning, dropping every later item even when each one fits. The reader now halves the page and retries the same cursor, and shows the warning only when a single item cannot fit. Co-authored-by: Claude Opus 5.5 --- .../providers/codex/thread-history.test.ts | 11 ++++++-- .../agent/providers/codex/thread-history.ts | 27 ++++++++++++++----- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/packages/server/src/server/agent/providers/codex/thread-history.test.ts b/packages/server/src/server/agent/providers/codex/thread-history.test.ts index 3feb737aa8..3f0e35801a 100644 --- a/packages/server/src/server/agent/providers/codex/thread-history.test.ts +++ b/packages/server/src/server/agent/providers/codex/thread-history.test.ts @@ -147,7 +147,7 @@ describe("Codex thread history", () => { appServer.assertNoErrors(); }); - test("a page too big to send shows a warning row and stops loading", async () => { + test("a page too big to send retries smaller pages, then warns at the item that cannot fit", async () => { const answers = Array.from({ length: 120 }, (_, index) => agentItem(`agent-${index}`, `Answer ${index}`), ); @@ -163,11 +163,12 @@ describe("Codex thread history", () => { ); const loaded = [ { type: "user_message", text: "One", messageId: "user-1" }, - ...answers.slice(0, 99).map((answer) => ({ + ...answers.map((answer) => ({ type: "assistant_message", text: answer.text, messageId: answer.id, })), + { type: "user_message", text: "Two", messageId: "user-2" }, { type: "notification", level: "warning", @@ -176,6 +177,12 @@ describe("Codex thread history", () => { ]; try { expect(timelineItems(await readHistory(session))).toEqual(loaded); + // Each oversized page retries the same cursor at half the size until it fits. + expect( + historyRequests(appServer) + .filter((request) => request.method === "thread/items/list") + .map((request) => (request.params as { limit: number }).limit), + ).toEqual([100, 100, 50, 25, 12, 12, 6, 6, 3, 3, 1, 1]); // The oversized reply failed only its own request; the session still answers. expect(timelineItems(await readHistory(session))).toEqual(loaded); } finally { diff --git a/packages/server/src/server/agent/providers/codex/thread-history.ts b/packages/server/src/server/agent/providers/codex/thread-history.ts index bf7461deb6..557d92150b 100644 --- a/packages/server/src/server/agent/providers/codex/thread-history.ts +++ b/packages/server/src/server/agent/providers/codex/thread-history.ts @@ -124,15 +124,28 @@ async function* readPaginatedHistory( ): AsyncGenerator { const seenCursors = new Set(); let cursor: string | undefined; + let limit = PAGE_SIZE; for (;;) { - const page = CodexItemsPageSchema.parse( - await requestHistory( - client, - "thread/items/list", - { threadId, limit: PAGE_SIZE, sortDirection: "asc", cursor }, + let response: unknown; + try { + response = await client.request("thread/items/list", { + threadId, + limit, + sortDirection: "asc", + cursor, + }); + } catch (error) { + if (!(error instanceof CodexAppServerResponseTooLargeError)) throw error; + // Image-heavy items can push a full page past the line cap; retry the same cursor smaller. + if (limit > 1) { + limit = Math.max(1, Math.floor(limit / 2)); + continue; + } + throw new CodexThreadHistoryTooLargeError( "The rest of this Codex thread's history is too large to load.", - ), - ); + ); + } + const page = CodexItemsPageSchema.parse(response); for (const row of page.data) { yield { item: row.item, From fd9aebd622a50aea9089b431629dc2018c6ee64b Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:49:05 +0000 Subject: [PATCH 011/160] fix(app): close a bottom sheet hidden before it finished opening (#9519) A sheet hidden right after it was presented, such as the context usage sheet when a plugin focuses the composer, could stay open. The dismiss reached the sheet before it had measured its layout, and the library drops a close it cannot position yet. The sheet then finished opening, and the visibility tracker took that as presented while its owner wanted it hidden. The tracker now dismisses again when a sheet reports an open position while its owner wants it hidden. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../visibility-tracker.test.ts | 12 ++++++++++++ .../visibility-tracker.ts | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.test.ts b/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.test.ts index 5205fb2486..ae2cb5c7ae 100644 --- a/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.test.ts +++ b/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.test.ts @@ -88,6 +88,18 @@ describe("bottom sheet visibility tracker", () => { expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }]); }); + it("dismisses again when a sheet hidden while opening finishes opening anyway", () => { + const { sheet, tracker } = setup(); + tracker.attachController(sheet); + tracker.syncDesired({ visible: true }); + + // The owner hides the sheet before its open animation reports in; the sheet still lands open. + tracker.syncDesired({ visible: false }); + tracker.handleSheetIndexChange(0); + + expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }, { type: "dismiss" }]); + }); + it("waits to present until the sheet controller becomes available", () => { const { sheet, tracker } = setup(); tracker.syncDesired({ visible: true }); diff --git a/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.ts b/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.ts index 167ed2ebe6..bf867d0432 100644 --- a/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.ts +++ b/packages/app/src/components/ui/isolated-bottom-sheet-modal/visibility-tracker.ts @@ -120,6 +120,11 @@ export function createBottomSheetVisibilityTracker(opts: { if (phase === "presenting" || phase === "dismissing") { setPhase("presented"); } + // A dismiss sent before the sheet measured its layout is dropped, and the sheet still + // finishes opening. The owner wants it hidden, so it goes again. + if (!visible && isEnabled !== false) { + dismiss(); + } return; } if (phase === "presenting" || phase === "presented") { From cc16ac6ac495734774e75b09bf4a0c80bb7f7439 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:52:13 +0000 Subject: [PATCH 012/160] fix(app): keep line breaks when copying a selection that crosses part of a code block (#9515) * Preserve partial code blocks in assistant selection copy * test(app): cover partial code copies in the real assistant selection journey Copying from a paragraph into part of a highlighted code block, or from partway through a block out to the next paragraph, now has browser journey coverage. On main both copies join the code lines into one line and drop the fence. Co-authored-by: Michael Wu Co-Authored-By: Claude Opus 5.5 * fix(app): keep indented code lines inside a copied list item Copying a list item that holds a code block indented only the code lines that start with a non-space character, so an indented line fell outside the item and broke the fence. Indent every non-empty line of the item. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Michael Wu Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../browser/assistant-selection-copy.spec.ts | 37 ++++++++++++-- .../content.browser.test.ts | 50 +++++++++++++++++++ .../assistant-selection-copy/content.web.ts | 11 +++- 3 files changed, 94 insertions(+), 4 deletions(-) diff --git a/packages/app/e2e/browser/assistant-selection-copy.spec.ts b/packages/app/e2e/browser/assistant-selection-copy.spec.ts index 81f89290c7..0703ff1341 100644 --- a/packages/app/e2e/browser/assistant-selection-copy.spec.ts +++ b/packages/app/e2e/browser/assistant-selection-copy.spec.ts @@ -644,6 +644,22 @@ test("copying an assistant selection preserves Markdown structure and links", as '```typescript\nconst answer = "yes";\n return answer;\n```\n\nAfter code.', ); + // Crossing into part of the block keeps the selected code lines as a fenced block. + await selectAssistantAcrossCodeLines(page, "not a generated link.", "return"); + await copySelection(page); + + expect((await readRichClipboard(page)).plainText).toBe( + 'not a generated link.\n\n```typescript\nconst answer = "yes";\n return\n```', + ); + + // So does starting partway through the block and leaving it. + await selectAssistantAcrossCodeLines(page, "answer", "After code."); + await copySelection(page); + + expect((await readRichClipboard(page)).plainText).toBe( + '```typescript\nanswer = "yes";\n return answer;\n```\n\nAfter code.', + ); + // Selecting a whole line runs off its end into the newline node. A trailing // newline auto-executes the line when it is pasted into a terminal. await selectAssistantAcrossCodeLines(page, "const", " "); @@ -729,13 +745,25 @@ test.describe("on a touch-capable desktop browser", () => { // The pan accepts touch only, and a mouse drag must still extend the browser's selection. test.use({ hasTouch: true }); - test("a mouse drag selects across assistant paragraphs", async ({ page }) => { + test("a mouse drag selects across assistant list, quote, and code blocks", async ({ page }) => { const agent = await seedMockAgentWorkspace({ repoPrefix: "assistant-selection-drag-", title: "Assistant selection drag", - initialPrompt: "Render three paragraphs.", + initialPrompt: "Render structured text.", featureValues: { - mockAssistantResponse: "First paragraph.\n\nSecond paragraph.\n\nThird paragraph.", + mockAssistantResponse: [ + "First paragraph.", + "", + "- List item.", + "", + "> Quote text.", + "", + "```ts", + "const answer = 1;", + "```", + "", + "Third paragraph.", + ].join("\n"), }, }); @@ -760,6 +788,9 @@ test.describe("on a touch-capable desktop browser", () => { const selected = await page.evaluate(() => window.getSelection()?.toString() ?? ""); expect(selected).toContain("First paragraph."); + expect(selected).toContain("List item."); + expect(selected).toContain("Quote text."); + expect(selected).toContain("const answer = 1;"); expect(selected).toContain("Third paragraph."); } finally { await agent.cleanup(); diff --git a/packages/app/src/assistant-selection-copy/content.browser.test.ts b/packages/app/src/assistant-selection-copy/content.browser.test.ts index 5c4fcfb331..f4e240c690 100644 --- a/packages/app/src/assistant-selection-copy/content.browser.test.ts +++ b/packages/app/src/assistant-selection-copy/content.browser.test.ts @@ -759,6 +759,56 @@ describe("assistant selection copy inside highlighted code", () => { "```typescript\nconst answer = 1;\n if (answer) {\n doThing();\n```\n\nAfter the block.", ); }); + + it("keeps line breaks when a quote selection ends partway through code", () => { + const message = mountHighlighted(); + const quote = document.createElement("div"); + quote.setAttribute("data-paseo-markdown-tag", "blockquote"); + quote.textContent = "Quoted context"; + message.querySelector('[data-paseo-markdown-tag="pre"]')!.before(quote); + + const content = copyBetween( + [tokenText(message, "Quoted context"), 0], + [tokenText(message, " (answer)"), 9], + ); + + expect(content?.plainText).toBe( + "> Quoted context\n\n```typescript\nconst answer = 1;\n if (answer)\n```", + ); + }); + + it("keeps indented code lines inside their list item", () => { + const host = document.createElement("div"); + host.innerHTML = [ + '
', + '
', + '
', + '
1.
', + '
Item text
', + highlightedCodeBlock("typescript"), + "
", + ].join(""); + document.body.append(host); + + const content = copyBetween([tokenText(host, "1."), 0], [tokenText(host, " (answer)"), 9]); + + expect(content?.plainText).toBe( + "1. Item text\n\n ```typescript\n const answer = 1;\n if (answer)\n ```", + ); + }); + + it("keeps line breaks when a selection starts partway through code", () => { + const message = mountHighlighted(); + + const content = copyBetween( + [tokenText(message, " answer"), 1], + [tokenText(message, "After the block."), "After the block.".length], + ); + + expect(content?.plainText).toBe( + "```typescript\nanswer = 1;\n if (answer) {\n doThing();\n```\n\nAfter the block.", + ); + }); }); describe("semantic library output", () => { diff --git a/packages/app/src/assistant-selection-copy/content.web.ts b/packages/app/src/assistant-selection-copy/content.web.ts index 250d60d761..58a2a8fd85 100644 --- a/packages/app/src/assistant-selection-copy/content.web.ts +++ b/packages/app/src/assistant-selection-copy/content.web.ts @@ -81,7 +81,8 @@ turndown.addRule("compactListItem", { const item = content .replace(/^\n+/, "") .replace(/\n+$/, "\n") - .replace(/\n(?=\S)/g, "\n "); + // Every non-empty line, so indented code lines stay inside the item. + .replace(/\n(?=[^\n])/g, "\n "); const parent = node.parentElement; if (parent?.nodeName !== "OL") { return `${options.bulletListMarker} ${item}\n`; @@ -359,6 +360,9 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean if (tag === "p" || tag === "img" || isTableStructure(tag)) { return true; } + if (isCrossBoundaryCodeElement(range, element, tag)) { + return true; + } const isSelectableSemantic = tag !== null && tag !== "li" && tag !== "ol" && tag !== "ul"; if ( (isSelectableSemantic || element.tagName === "A") && @@ -386,6 +390,11 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean return hasSelectedAllContents(range, element, tag === "li"); } +function isCrossBoundaryCodeElement(range: Range, element: Element, tag: string | null): boolean { + const isCode = tag === "pre" || (tag === "code" && Boolean(element.closest(CODE_BLOCK_SELECTOR))); + return isCode && !selectionStaysInsideElement(range, element); +} + function selectionStaysInsideElement(range: Range, element: Element): boolean { return ( range.startContainer !== element && From 536846eb60b935e77ae450724814c4cc9edf4c6e Mon Sep 17 00:00:00 2001 From: LiebeLee <27326628+LiebeLee@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:02:23 +0800 Subject: [PATCH 013/160] fix(omp): persist the resumed session identity when importing (#8854) OMP import listings return a session file path, and the import helper stored that path as both sessionId and nativeHandle. Records then carried a path in sessionId while runtimeInfo carried the real id, which breaks identity-based lookups and makes a later import of the same file look unrelated. Prefer the resumed session's own describePersistence() identity and keep the listed handle as nativeHandle, merging metadata so provider-specific fields survive. --- docs/providers.md | 9 +++ .../agent/provider-session-import.test.ts | 67 +++++++++++++++++++ .../server/agent/provider-session-import.ts | 22 +++++- 3 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 packages/server/src/server/agent/provider-session-import.test.ts diff --git a/docs/providers.md b/docs/providers.md index a0b9d2f4f7..6d9ea2a6ac 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -150,6 +150,15 @@ Pi import discovery reads Pi's persisted JSONL session files because Pi RPC does OMP is a first-class built-in provider, disabled by default. Its launch contract, typed runtime, agent/session behavior, history, permissions, imports, and test fake live under `providers/omp/`; only the provider-neutral JSONL child-process transport is shared with Pi. It launches `omp --mode rpc-ui`, uses OMP's `get_available_commands` RPC for slash-command discovery, bridges OMP `rpc-ui` approval dialogs into Paseo permissions, and imports terminal-started sessions from `~/.omp/agent/sessions` when enabled. +OMP rewind is a branch, not an edit: `branch` writes a new session file whose header names the +previous file as `parentSession` and leaves that previous file untouched. A rewind chain therefore +adds one file to `~/.omp/agent/sessions` per step, and `omp --resume` lists all of them. The +previous file also keeps whatever head it had recorded, which can be an older branch than the one +the user last saw. Treat the provider session file selected by OMP as the authority; do not assume +the newest file or the newest message wins. Import listings hand back a file path, so persist the +resumed session's own identity (`sessionId`) with that path as `nativeHandle`, not the listed +handle as both. + OMP supports native Paseo host tools. The adapter registers the full caller-scoped Paseo tool catalog directly with OMP, matching providers such as Claude that expose the full catalog through MCP. Serialize every OMP host definition with `loadMode: "essential"` so `create_agent`, `send_agent_prompt`, `wait_for_agent`, and related tools remain direct calls; omitting the field makes OMP mount non-built-in names under `xd://` instead. OMP's provider-managed task subagents are surfaced as Paseo subagents through `child_session` imports; the parent keeps the subagents track while the child runtime stays owned by OMP. Custom OMP profiles should extend `omp`; other Pi-compatible forks can still extend `pi`, override `command`, and set `params.sessionDir` to their JSONL session directory. Pi RPC extension UI dialog requests (`select`, `input`, `editor`, `confirm`) are bridged into Paseo question permissions and answered with `extension_ui_response`. Pi extensions such as `ask_user` may chain dialogs: for example, a `select` can be followed by an optional-comment `input`. When an `ask_user` tool call declares `allowComment: true`, Paseo presents the selection and optional comment as one question permission, answers Pi's initial `select` immediately, then auto-answers the follow-up optional `input` with the comment the user already supplied (or an empty string). Preserve placeholders and optional/skip semantics for standalone optional inputs so the app can still distinguish "skip this optional input" from "cancel the whole dialog." Fire-and-forget extension UI requests such as notifications are intentionally ignored by the provider adapter unless Paseo grows first-class UI for them. diff --git a/packages/server/src/server/agent/provider-session-import.test.ts b/packages/server/src/server/agent/provider-session-import.test.ts new file mode 100644 index 0000000000..b9f7073ebc --- /dev/null +++ b/packages/server/src/server/agent/provider-session-import.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; +import type { + AgentPersistenceHandle, + AgentSession, + AgentSessionConfig, + ImportProviderSessionContext, +} from "./agent-sdk-types.js"; +import { importSessionFromPersistence } from "./provider-session-import.js"; + +const SESSION_FILE = "/Users/dev/.omp/agent/sessions/project/2026-01-01_session-id.jsonl"; +const SESSION_ID = "session-id"; + +function config(cwd: string): AgentSessionConfig { + return { provider: "omp", cwd }; +} + +function context(cwd: string): ImportProviderSessionContext { + return { config: config(cwd), storedConfig: config(cwd) }; +} + +function fakeSession(described: AgentPersistenceHandle | null): AgentSession { + return { + async *streamHistory() {}, + describePersistence: () => described, + } as unknown as AgentSession; +} + +describe("importSessionFromPersistence", () => { + it("persists the resumed session identity instead of the listed file handle", async () => { + const cwd = "/Users/dev/code/project"; + const imported = await importSessionFromPersistence({ + provider: "omp", + request: { providerHandleId: SESSION_FILE, cwd }, + context: context(cwd), + resumeSession: async () => + fakeSession({ + provider: "omp", + sessionId: SESSION_ID, + nativeHandle: SESSION_FILE, + metadata: { cwd, model: "resumed-model" }, + }), + }); + + expect(imported.persistence).toMatchObject({ + provider: "omp", + sessionId: SESSION_ID, + nativeHandle: SESSION_FILE, + metadata: { cwd, provider: "omp", model: "resumed-model" }, + }); + }); + + it("keeps the requested handle when the provider describes no identity", async () => { + const cwd = "/Users/dev/code/project"; + const imported = await importSessionFromPersistence({ + provider: "omp", + request: { providerHandleId: SESSION_FILE, cwd }, + context: context(cwd), + resumeSession: async () => fakeSession(null), + }); + + expect(imported.persistence).toMatchObject({ + provider: "omp", + sessionId: SESSION_FILE, + nativeHandle: SESSION_FILE, + }); + }); +}); diff --git a/packages/server/src/server/agent/provider-session-import.ts b/packages/server/src/server/agent/provider-session-import.ts index b09a5ab874..c75cd2d70d 100644 --- a/packages/server/src/server/agent/provider-session-import.ts +++ b/packages/server/src/server/agent/provider-session-import.ts @@ -38,12 +38,32 @@ export async function importSessionFromPersistence(input: { return { session, config: storedConfig, - persistence, + persistence: canonicalImportPersistence(persistence, session), timeline: history.timeline, providerSubagentEvents: history.providerSubagentEvents, }; } +/** + * Import handles identify a session by whatever the provider lists, which is not + * always the session id: OMP lists session files. Persist the resumed session's own + * identity instead, so records, dedupe and resume all agree, while the provider's + * native handle still resolves the session. + */ +function canonicalImportPersistence( + requested: AgentPersistenceHandle, + session: ImportedProviderSession["session"], +): AgentPersistenceHandle { + const described = session.describePersistence(); + if (!described?.sessionId) return requested; + return { + ...described, + provider: requested.provider, + nativeHandle: described.nativeHandle ?? requested.nativeHandle, + metadata: { ...requested.metadata, ...described.metadata }, + }; +} + function buildImportPersistenceHandle( provider: AgentProvider, input: ImportProviderSessionInput, From 9eccb4722b8bc189d073bb9b4d4b9690741d4c53 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:00:22 +0000 Subject: [PATCH 014/160] Model picker profile buttons respond to taps on Android tablets (#9526) * fix(app): keep the model picker's profile action tappable on Android On Android tablets the model list scrolls inside an independent viewport whose native scroll gesture cancels a plain Pressable's touches. Rows use the gesture-aware pressable; the profile + and the Profiles pencil were left as plain Pressables. Route both through the same gesture path. * test(app): cover the tablet model row's profile action on Android Adds an agent-device journey that taps a model row's `+` in the New workspace picker on an Android tablet and waits for the seeded profile form. It fails on main, where the tap is swallowed, and passes with the gesture-aware profile action. Co-authored-by: moevis Co-Authored-By: Claude Opus 5.5 * test(app): make the tablet profile journey follow the documented setup The journey now starts from a remembered model like its sibling, so it runs after model-tablet.android.ad, and asserts that closing the profile form leaves the remembered model selected, so a tap on `+` that also selected the row fails it. Co-authored-by: moevis Co-Authored-By: Claude Opus 5.5 * test(app): keep the no-profiles requirement for the tablet profile journey With a saved profile the picker opens on its root view, which has no Back, so the journey needs a host with no agent profiles. Co-authored-by: moevis Co-Authored-By: Claude Opus 5.5 * fix(app): hide the model row's profile action through its style IconActionButton took a pointerEvents prop that only its web branch applied, so a native caller hiding the action would get an invisible button that still took taps. The hidden style now carries pointerEvents: "none", which every pressable branch already applies, and the prop is gone. The web journey checks the plus ignores taps until its row is hovered. Co-authored-by: moevis Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: moevis Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/app/e2e/mobile/modal-sheet/README.md | 14 +++ .../model-tablet-profile.android.ad | 22 +++++ .../app/e2e/support/helpers/agent-profiles.ts | 10 ++- packages/app/src/components/model-browser.tsx | 89 +++++++++++++------ 4 files changed, 107 insertions(+), 28 deletions(-) create mode 100644 packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad diff --git a/packages/app/e2e/mobile/modal-sheet/README.md b/packages/app/e2e/mobile/modal-sheet/README.md index 8a59b16883..17a96a01bc 100644 --- a/packages/app/e2e/mobile/modal-sheet/README.md +++ b/packages/app/e2e/mobile/modal-sheet/README.md @@ -85,6 +85,20 @@ agent-device test packages/app/e2e/mobile/modal-sheet/model-tablet.android.ad \ --artifacts-dir /tmp/paseo-model-tablet-qa ``` +`model-tablet-profile.android.ad` taps the `+` of a model row in New workspace, asserts the seeded +profile form opens, and asserts that closing the form leaves the remembered model selected. Run it +on the same tablet setup, after `model-tablet.android.ad` or with `MODEL_LABEL` remembered, against a +host with no agent profiles: with a profile saved, the picker opens on its root view, which has no +Back. Set `PROFILE_MODEL_ID` to a different model on the provider's first page: + +```sh +agent-device test packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad \ + --serial "$ANDROID_SERIAL" --metro-port "$MODEL_QA_METRO_PORT" \ + --env FORM_URL="paseo://new?serverId=${SHEET_QA_SERVER_ID}" \ + --env PROVIDER_ID=codex --env MODEL_LABEL="$MODEL_QA_MODEL_LABEL" \ + --env PROFILE_MODEL_ID="$MODEL_QA_PROFILE_MODEL_ID" +``` + The existing-agent journey needs the sidebar pinned so its composer stays narrow. Start each run with no modal open; a failed provider tap leaves its modal open, so dismiss it before the next run. These host-dependent journeys remain outside the default mobile suite, alongside the compact sheet journeys above. diff --git a/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad b/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad new file mode 100644 index 0000000000..1b84493ed6 --- /dev/null +++ b/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad @@ -0,0 +1,22 @@ +# Connected host with MODEL_LABEL selected and no agent profiles, 1600x2560 at density 320. See README.md. +# FORM_URL=paseo://new?serverId=; PROFILE_MODEL_ID is another catalog model with no profile. +context platform=android timeout=60000 retries=0 +env APP_ID=sh.paseo.debug +env PROVIDER_ID=codex + +open "${APP_ID}" "${FORM_URL}" +wait "label=\"Workspace project\"" 20000 +press "id=\"combined-model-selector\"" +wait "id=\"combobox-desktop-container\"" 10000 +# A remembered model opens its provider's list. Return to the provider page first. +press "label=\"Back\"" +wait "id=\"model-provider-${PROVIDER_ID}\"" 10000 +press "id=\"model-provider-${PROVIDER_ID}\"" +wait "id=\"compact-model-list\"" 3000 +# The row's profile action sits inside Android's independent scroll viewport. +press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\"" +wait "text=\"Add agent profile\"" 5000 +# Closing the form keeps the remembered model: the tap did not also select the row. +back +wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000 +close diff --git a/packages/app/e2e/support/helpers/agent-profiles.ts b/packages/app/e2e/support/helpers/agent-profiles.ts index a538d256c0..d2430e7f6d 100644 --- a/packages/app/e2e/support/helpers/agent-profiles.ts +++ b/packages/app/e2e/support/helpers/agent-profiles.ts @@ -505,10 +505,14 @@ export async function expectCreateProfileFromModelRow( page: Page, input: { provider: string; modelId: string; modelLabel: string }, ): Promise { + const action = pickerViewport(page).getByTestId( + `model-create-profile-${input.provider}-${input.modelId}`, + ); + // Until its row is hovered the plus is invisible, so a tap on its spot reaches the row. + await expect(action).toHaveCSS("pointer-events", "none"); await modelRow(page, input).hover(); - await pickerViewport(page) - .getByTestId(`model-create-profile-${input.provider}-${input.modelId}`) - .click(); + await expect(action).toHaveCSS("pointer-events", "auto"); + await action.click(); const modal = editModal(page); await expect(modal).toBeVisible({ timeout: 30_000 }); await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue( diff --git a/packages/app/src/components/model-browser.tsx b/packages/app/src/components/model-browser.tsx index 82edd1458d..509e7a23b0 100644 --- a/packages/app/src/components/model-browser.tsx +++ b/packages/app/src/components/model-browser.tsx @@ -106,29 +106,76 @@ function ProviderSettingsAction({ ); } -function AgentProfilesEditAction({ onPress }: { onPress: () => void }) { - const { t } = useTranslation(); +/** + * An icon button that explains itself in a tooltip on desktop hover. Tooltips + * never open on mobile, so native renders the shared gesture-aware pressable + * instead of a plain Pressable: inside the model list's independent scroll + * viewport (Android, wide windows) the native scroll gesture cancels a plain + * Pressable's touches and the button would never fire. + */ +function IconActionButton({ + accessibilityLabel, + testID, + onPress, + style, + children, +}: { + accessibilityLabel: string; + testID: string; + onPress: () => void; + style?: + | StyleProp + | ((state: PressableStateCallbackType & { hovered?: boolean }) => StyleProp); + children: React.ReactNode; +}) { + if (isNative) { + return ( + + {children} + + ); + } return ( - + {children} - {t("modelSelector.editProfilesLabel")} + {accessibilityLabel} ); } +function AgentProfilesEditAction({ onPress }: { onPress: () => void }) { + const { t } = useTranslation(); + return ( + + + + ); +} + const IndependentScrollGestureContext = createContext | null>( null, ); @@ -637,24 +684,14 @@ function ModelRowProfileAction({ [visible], ); return ( - - - - {children} - - - - {label} - - + + {children} + ); } @@ -1690,8 +1727,10 @@ const styles = StyleSheet.create((theme) => ({ rowIconButtonPressed: { backgroundColor: theme.colors.surface1, }, + // Hidden in style so every pressable branch that applies the style also stops taking taps. profileActionHidden: { opacity: 0, + pointerEvents: "none", }, emptyState: { padding: theme.spacing[4], From 7c35ad90b91b07ed469b1e29dc70cc17f78a90e7 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:05:34 +0000 Subject: [PATCH 015/160] Start an edited agent draft after its first start failed (#9534) * test(app): reproduce edited draft retries after a failed agent start Resubmitting an agent draft after its start failed reuses the draft ID as the creation key with different inputs, and the daemon rejects it with agent_request_key_conflict (or workspace_request_key_conflict from New workspace). Co-Authored-By: Claude Opus 5.5 * fix(app): start an edited agent draft after its first start failed The draft sent its draft ID as the creation key on every submit. After a failed start the daemon keeps that key's request, so resubmitting an edited draft was rejected with agent_request_key_conflict. The key now names the draft's exact request: a retry resumes it, an edit starts a new one. A retry after New workspace's agent failed to start creates the agent in the workspace that is already ready, instead of replaying workspace provisioning with a different agent. Co-authored-by: michaelmwu <421504+michaelmwu@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: michaelmwu <421504+michaelmwu@users.noreply.github.com> --- .../e2e/browser/creation-idempotency.spec.ts | 38 ++++++++++++++- packages/app/e2e/support/helpers/creation.ts | 7 ++- .../src/composer/draft/creation-key.test.ts | 30 ++++++++++++ .../app/src/composer/draft/creation-key.ts | 29 ++++++++++++ .../app/src/composer/draft/workspace-tab.tsx | 10 ++-- .../app/src/screens/new-workspace-screen.tsx | 18 ++----- .../new-workspace/retry-agent-request.test.ts | 47 ------------------- .../new-workspace/retry-agent-request.ts | 28 ----------- .../workspace-draft-submission-store.test.ts | 24 ---------- .../workspace-draft-submission-store.ts | 11 +---- 10 files changed, 114 insertions(+), 128 deletions(-) create mode 100644 packages/app/src/composer/draft/creation-key.test.ts create mode 100644 packages/app/src/composer/draft/creation-key.ts delete mode 100644 packages/app/src/screens/new-workspace/retry-agent-request.test.ts delete mode 100644 packages/app/src/screens/new-workspace/retry-agent-request.ts diff --git a/packages/app/e2e/browser/creation-idempotency.spec.ts b/packages/app/e2e/browser/creation-idempotency.spec.ts index 7658addf72..8de9f40fbb 100644 --- a/packages/app/e2e/browser/creation-idempotency.spec.ts +++ b/packages/app/e2e/browser/creation-idempotency.spec.ts @@ -127,8 +127,42 @@ for (const scenario of [ await creation.submitPrompt("Retry this workspace and agent together."); await creation.expectAgentCount(1); }); + + test(`an edited prompt after failed agent initialization starts the agent in its workspace${scenario.suffix}`, async ({ + creation, + startup, + page, + }) => { + await creation.openWorkspaceForm("local"); + await creation.submitPrompt("Start the original task.", "Create"); + await creation.expectAgentStillStarting(); + await startup.fail(); + await creation.expectStartupFailure(); + await creation.expectOneCreatedWorkspace(); + await scenario.prepare(creation); + await creation.submitPrompt("Start the edited task."); + await creation.expectPromptVisible("Start the edited task."); + await creation.expectOneCreatedWorkspace(); + await creation.expectAgentCount(1); + await expect(page.getByText(/request_key_conflict/)).toHaveCount(0); + }); } +test("an edited agent draft starts after its first start failed", async ({ + creation, + startup, + page, +}) => { + await creation.openAgentDraft(); + await startup.fail(); + await creation.submitPrompt("Start the original task."); + await creation.expectStartupFailure(); + await creation.submitPrompt("Start the edited task."); + await creation.expectPromptVisible("Start the edited task."); + await creation.expectAgentCount(1); + await expect(page.getByText(/request_key_conflict/)).toHaveCount(0); +}); + for (const entry of [ { name: "agent draft", @@ -159,7 +193,9 @@ for (const entry of [ await entry.settled(creation); await creation.expectCreatedAgentError(); await creation.expectPromptBeforeError(prompt); - await page.screenshot({ path: testInfo.outputPath("created-agent-prompt-error.png") }); + await page.screenshot({ + path: testInfo.outputPath("created-agent-prompt-error.png"), + }); await creation.reloadAgent(); await creation.expectPromptBeforeError(prompt); await creation.submitPrompt("emit 1 coalesced agent stream updates for a corrected prompt."); diff --git a/packages/app/e2e/support/helpers/creation.ts b/packages/app/e2e/support/helpers/creation.ts index 1c3d5dda89..0de6d6672a 100644 --- a/packages/app/e2e/support/helpers/creation.ts +++ b/packages/app/e2e/support/helpers/creation.ts @@ -142,6 +142,8 @@ export async function createCreationScenario(page: Page) { const requests = await observeCreationRequests(page); const project = await seedWorkspace({ repoPrefix: "creation-idempotency-" }); let workspaceId = project.workspaceId; + // Workspaces the scenario opens itself to evict the deck; they are not creations under test. + const evictionWorkspaceIds = new Set(); return { cleanup: project.cleanup, async openWorkspaceForm(isolation: "local" | "worktree") { @@ -232,7 +234,9 @@ export async function createCreationScenario(page: Page) { await requests.settled(); const workspaces = (await project.client.fetchWorkspaces()).entries.filter( (workspace) => - workspace.projectId === project.projectId && workspace.id !== project.workspaceId, + workspace.projectId === project.projectId && + workspace.id !== project.workspaceId && + !evictionWorkspaceIds.has(workspace.id), ); expect(workspaces).toHaveLength(1); workspaceId = workspaces[0]!.id; @@ -276,6 +280,7 @@ export async function createCreationScenario(page: Page) { source: { kind: "directory", path: project.repoPath }, }); if (!result.workspace) throw new Error(result.error ?? "Failed to seed eviction workspace"); + evictionWorkspaceIds.add(result.workspace.id); await switchWorkspaceViaSidebar({ page, serverId: getServerId(), diff --git a/packages/app/src/composer/draft/creation-key.test.ts b/packages/app/src/composer/draft/creation-key.test.ts new file mode 100644 index 0000000000..b32480ba39 --- /dev/null +++ b/packages/app/src/composer/draft/creation-key.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { draftCreationKey } from "./creation-key"; + +const request = { + config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, + workspaceId: "workspace-1", + initialPrompt: "Start the original task.", + clientMessageId: "draft-1:initial-message", +}; + +describe("draftCreationKey", () => { + it("keeps the key for a retry of the same request, whatever its key order", () => { + const reordered = { + clientMessageId: request.clientMessageId, + initialPrompt: request.initialPrompt, + workspaceId: request.workspaceId, + config: { model: "gpt-6", cwd: "/repo", provider: "codex" }, + }; + expect(draftCreationKey("draft-1", reordered)).toBe(draftCreationKey("draft-1", request)); + }); + + it.each([ + { name: "prompt", edited: { ...request, initialPrompt: "Start the edited task." } }, + { name: "model", edited: { ...request, config: { ...request.config, model: "gpt-6-mini" } } }, + ])("gives an edited $name a new key on the same draft", ({ edited }) => { + const key = draftCreationKey("draft-1", edited); + expect(key).not.toBe(draftCreationKey("draft-1", request)); + expect(key.startsWith("draft-1:")).toBe(true); + }); +}); diff --git a/packages/app/src/composer/draft/creation-key.ts b/packages/app/src/composer/draft/creation-key.ts new file mode 100644 index 0000000000..556086756e --- /dev/null +++ b/packages/app/src/composer/draft/creation-key.ts @@ -0,0 +1,29 @@ +/** + * The creation key for a draft's request. The daemon keeps one request per key, so retrying the + * same draft resumes its creation, while an edited draft is a new request with its own key. + */ +export function draftCreationKey(draftId: string, request: object): string { + return `${draftId}:${hash(canonicalJson(request))}`; +} + +function canonicalJson(value: unknown): string { + return JSON.stringify(value, (_key, entry: unknown) => + entry && typeof entry === "object" && !Array.isArray(entry) + ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))) + : entry, + ); +} + +// 53-bit cyrb53: distinguishes the edits of one draft without WebCrypto, which needs HTTPS. +function hash(text: string): string { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let index = 0; index < text.length; index += 1) { + const code = text.charCodeAt(index); + h1 = Math.imul(h1 ^ code, 2654435761); + h2 = Math.imul(h2 ^ code, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36); +} diff --git a/packages/app/src/composer/draft/workspace-tab.tsx b/packages/app/src/composer/draft/workspace-tab.tsx index 0815603e55..12f392397f 100644 --- a/packages/app/src/composer/draft/workspace-tab.tsx +++ b/packages/app/src/composer/draft/workspace-tab.tsx @@ -47,6 +47,7 @@ import { } from "@/workspace-tabs/model"; import { openWorkspaceChanges } from "@/workspace-tabs/open-supporting-view"; import { useSettings } from "@/hooks/use-settings"; +import { draftCreationKey } from "@/composer/draft/creation-key"; interface AutoSubmitConfig { provider: string; @@ -164,8 +165,7 @@ async function submitDraftCreateRequest(input: { const attachmentsArray = Array.isArray(attachments) ? attachments : undefined; const imagesData = await encodeImages(images); - const options = { - idempotencyKey: input.draftId, + const request = { config, workspaceId, initialPrompt: text, @@ -174,8 +174,10 @@ async function submitDraftCreateRequest(input: { ...(imagesData && imagesData.length > 0 ? { images: imagesData } : {}), ...(attachmentsArray && attachmentsArray.length > 0 ? { attachments: attachmentsArray } : {}), }; - const creation = useWorkspaceDraftSubmissionStore.getState().creationByDraftId[input.draftId]; - const result = creation ? await creation.retry(options) : await client.createAgent(options); + const result = await client.createAgent({ + ...request, + idempotencyKey: draftCreationKey(input.draftId, request), + }); return { agentId: result.id, diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index bab4df8f01..ccf49c9b4a 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -1,8 +1,5 @@ import { useAddHost } from "@/hosts/add-host"; -import type { - CreateAgentRequestOptions, - CreateWorkspaceRequestOptions, -} from "@getpaseo/client/internal/daemon-client"; +import type { CreateWorkspaceRequestOptions } from "@getpaseo/client/internal/daemon-client"; import type { AgentSnapshotPayload, CreationSnapshot } from "@getpaseo/protocol/messages"; import { encodeImages } from "@/utils/encode-images"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; @@ -126,7 +123,6 @@ import { } from "./workspace/terminals/state"; import { captureWorkspaceDraftCleanup } from "./new-workspace/background-handoff"; import { useNewWorkspaceScreenPresence } from "./new-workspace/screen-presence"; -import { retriedAgentRequest } from "./new-workspace/retry-agent-request"; function useIsNewWorkspaceDraftHandoffActive(input: { draftId: string | undefined; @@ -243,7 +239,6 @@ interface SubmitDraftInput { clearConsumedDraft: () => void; agentCreation?: { result: Promise; - retry: (input: CreateAgentRequestOptions) => Promise; }; serverId: string; draftKey: string; @@ -471,13 +466,13 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise => { + const execute = async (): Promise => { const { agent } = await ensureWorkspace({ cwd, prompt: text, attachments: workspaceNamingAttachments, withInitialAgent: true, - agent: requestedAgent, + agent: initialAgent, onEvent: (snapshot) => { if (!snapshot.workspace || navigated) return; navigated = true; @@ -516,11 +511,8 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise execute()), - retry: (request: CreateAgentRequestOptions) => - execute(retriedAgentRequest(initialAgent, request, cwd)), - }; + // A retry after a failed agent start belongs to the ready workspace's draft, not to this creation. + const agentCreation = { result: Promise.resolve().then(() => execute()) }; await agentCreation.result; if (outcome === "background") clearConsumedDraft(); return outcome; diff --git a/packages/app/src/screens/new-workspace/retry-agent-request.test.ts b/packages/app/src/screens/new-workspace/retry-agent-request.test.ts deleted file mode 100644 index 248a044a3c..0000000000 --- a/packages/app/src/screens/new-workspace/retry-agent-request.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { retriedAgentRequest, type WorkspaceAgentRequest } from "./retry-agent-request"; - -const initial: WorkspaceAgentRequest = { - config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, - metadata: { "issues.key": "PAS-1" }, - initialPrompt: "first try", - clientMessageId: "draft_1:initial-message", -}; - -describe("retriedAgentRequest", () => { - it("creates with the metadata the draft resubmitted", () => { - const retried = retriedAgentRequest( - initial, - { - config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, - initialPrompt: "second try", - metadata: { "issues.key": "PAS-2" }, - }, - "/repo", - ); - expect(retried.metadata).toEqual({ "issues.key": "PAS-2" }); - expect(retried.initialPrompt).toBe("second try"); - expect(retried.clientMessageId).toBe("draft_1:initial-message"); - }); - - it("creates with no metadata once the draft cleared it", () => { - const retried = retriedAgentRequest( - initial, - { config: { provider: "codex", cwd: "/repo", model: "gpt-6" }, initialPrompt: "second try" }, - "/repo", - ); - expect("metadata" in retried).toBe(false); - }); - - it("keeps the first attempt's directory over the resubmitted config", () => { - const retried = retriedAgentRequest( - initial, - { - config: { provider: "codex", cwd: "/elsewhere", model: "gpt-6-mini" }, - initialPrompt: "second try", - }, - "/repo", - ); - expect(retried.config).toEqual({ provider: "codex", cwd: "/repo", model: "gpt-6-mini" }); - }); -}); diff --git a/packages/app/src/screens/new-workspace/retry-agent-request.ts b/packages/app/src/screens/new-workspace/retry-agent-request.ts deleted file mode 100644 index 4a7efa02cf..0000000000 --- a/packages/app/src/screens/new-workspace/retry-agent-request.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { - CreateAgentRequestOptions, - CreateWorkspaceRequestOptions, -} from "@getpaseo/client/internal/daemon-client"; - -export type WorkspaceAgentRequest = NonNullable; - -/** - * The agent a retried creation asks for: everything the draft resubmitted (config, prompt, - * images, attachments and metadata, cleared included) on the first attempt's identity, so a - * retry creates what the composer shows now, not what it showed when creation first failed. - */ -export function retriedAgentRequest( - initial: WorkspaceAgentRequest, - request: CreateAgentRequestOptions, - cwd: string, -): WorkspaceAgentRequest { - const { metadata: _replaced, ...identity } = initial; - return { - ...identity, - config: { ...request.config!, cwd }, - initialPrompt: request.initialPrompt ?? "", - clientMessageId: initial.clientMessageId, - images: request.images, - attachments: request.attachments, - ...(request.metadata ? { metadata: request.metadata } : {}), - }; -} diff --git a/packages/app/src/stores/workspace-draft-submission-store.test.ts b/packages/app/src/stores/workspace-draft-submission-store.test.ts index 73e1a40899..317b605767 100644 --- a/packages/app/src/stores/workspace-draft-submission-store.test.ts +++ b/packages/app/src/stores/workspace-draft-submission-store.test.ts @@ -45,27 +45,3 @@ test("the production app consumes a draft once and leaves other drafts pending", expect(store.getState().consumePending(submission)).toBeNull(); expect(Object.keys(store.getState().pendingByDraftId)).toEqual(["draft-2"]); }); - -test("consuming draft presentation retains its running creation through remount and retry", () => { - const store = loadProductionStore(); - const result = new Promise(() => {}); - const creation = { result, retry: () => result }; - const submission = { - serverId: "server", - workspaceId: "workspace", - draftId: "draft-one", - text: "hello", - attachments: [], - cwd: "/repo", - provider: "codex", - clientMessageId: "message", - timestamp: 1, - agentCreation: creation, - }; - store.getState().setPending(submission); - store.getState().consumePending(submission); - expect(store.getState().pendingByDraftId[submission.draftId]).toBeUndefined(); - expect(store.getState().creationByDraftId[submission.draftId]).toBe(creation); - store.getState().clearDraftSetup({ draftId: submission.draftId }); - expect(store.getState().creationByDraftId[submission.draftId]).toBeUndefined(); -}); diff --git a/packages/app/src/stores/workspace-draft-submission-store.ts b/packages/app/src/stores/workspace-draft-submission-store.ts index 4a7d3ceaf3..b3eb086d46 100644 --- a/packages/app/src/stores/workspace-draft-submission-store.ts +++ b/packages/app/src/stores/workspace-draft-submission-store.ts @@ -1,4 +1,3 @@ -import type { CreateAgentRequestOptions } from "@getpaseo/client/internal/daemon-client"; import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; import { create } from "zustand"; import type { ComposerAttachment } from "@/attachments/types"; @@ -9,7 +8,6 @@ export interface PendingWorkspaceDraftSubmission { /** Already-running creation. Mounting the draft only observes its result. */ agentCreation?: { result: Promise; - retry: (input: CreateAgentRequestOptions) => Promise; }; serverId: string; workspaceId: string; @@ -35,7 +33,6 @@ export interface PendingWorkspaceDraftSetup { interface WorkspaceDraftSubmissionState { pendingByDraftId: Record; setupByDraftId: Record; - creationByDraftId: Record>; setPending: (submission: PendingWorkspaceDraftSubmission) => void; setDraftSetup: (input: { draftId: string; @@ -69,12 +66,8 @@ export const useWorkspaceDraftSubmissionStore = create ({ pendingByDraftId: {}, setupByDraftId: {}, - creationByDraftId: {}, setPending: (submission) => set((state) => ({ - creationByDraftId: submission.agentCreation - ? { ...state.creationByDraftId, [submission.draftId]: submission.agentCreation } - : state.creationByDraftId, pendingByDraftId: { ...state.pendingByDraftId, [submission.draftId]: submission, @@ -94,10 +87,8 @@ export const useWorkspaceDraftSubmissionStore = create { - const creationByDraftId = { ...state.creationByDraftId }; - delete creationByDraftId[normalizedDraftId]; const { [normalizedDraftId]: _removed, ...setupByDraftId } = state.setupByDraftId; - return { setupByDraftId, creationByDraftId }; + return { setupByDraftId }; }); }, consumePending: (input) => { From 7980ad008bb1bc7e4b395100ff96a9d771ddc8b8 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:01:35 +0000 Subject: [PATCH 016/160] Keep keystrokes typed while a terminal restores its screen (#9533) * fix(app): keep keystrokes typed while a terminal restores its screen When a terminal re-attaches, for example after the host reconnects, the browser terminal replays the screen snapshot and ignores everything xterm emits until the replay is parsed, so replies to queries in the restored output don't reach the shell. That also threw away what the user typed during the replay: the first characters typed right after a reconnect were lost. xterm emits both through the same callback. Replies only come out of parsing a write, so data emitted while a keyboard, input or paste event is dispatching on the terminal is the user's, and it now goes through. * fix(app): keep pastes suppressed while a terminal restores its screen Until the replayed snapshot restores bracketed paste mode, a multi-line paste would reach the shell unbracketed and run line by line. Pastes during a replay are dropped as before; only typed input goes through. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../terminal-emulator-runtime.browser.test.ts | 37 +++++++++++++++++++ .../runtime/terminal-emulator-runtime.ts | 29 ++++++++++++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts index bf044237b0..a875ae5a3a 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.browser.test.ts @@ -115,6 +115,26 @@ interface CreateTerminalHostInput { isMac?: boolean; } +/** Text typed into xterm's textarea, as the browser reports a typed character. */ +function typeText(mounted: MountedTerminal, text: string): void { + mounted.host + .querySelector(".xterm-helper-textarea") + ?.dispatchEvent( + new InputEvent("input", { data: text, inputType: "insertText", bubbles: true }), + ); +} + +/** A native paste of plain text into xterm's textarea. */ +function pasteText(mounted: MountedTerminal, text: string): void { + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", text); + mounted.host + .querySelector(".xterm-helper-textarea") + ?.dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); +} + function createTerminalHost(input: CreateTerminalHostInput): MountedTerminal { const root = document.createElement("div"); root.style.width = `${input.width}px`; @@ -824,6 +844,23 @@ describe("incremental replay lifecycle", () => { expect(mounted.inputs[0]?.startsWith("\x1b]4;1;rgb:")).toBe(true); }); + it("keeps what the user types, but not pastes, while a replay is still parsing", async () => { + const mounted = createTerminalHost({ width: 720, height: 360 }); + await waitFor({ predicate: () => mounted.sizes.length > 0 }); + mounted.runtime.replay({ type: "begin" }); + mounted.runtime.replay({ type: "data", data: terminalOutput("\x1b]4;1;?\x07restored") }); + mounted.runtime.replay({ type: "end" }); + + typeText(mounted, "a"); + pasteText(mounted, "echo one\necho two\n"); + typeText(mounted, "f"); + await new Promise((resolve) => + mounted.runtime.write({ data: terminalOutput("live"), onCommitted: resolve }), + ); + + expect(mounted.inputs).toEqual(["a", "f"]); + }); + it("measures emoji clusters with the daemon's grapheme widths and copies them intact", async () => { const mounted = createTerminalHost({ width: 720, height: 360 }); const text = "A😀B❤️C👋🏽D👨‍👩‍👧E"; diff --git a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts index ae74a4945f..3aaf1e1393 100644 --- a/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts +++ b/packages/app/src/terminal/runtime/terminal-emulator-runtime.ts @@ -124,6 +124,7 @@ interface TerminalEmulatorRuntimeDisposables { clearFitTimeouts: () => void; removeFontListeners: () => void; removeFilePasteListener: () => void; + removeUserInputListeners: () => void; restoreDocumentStyles: () => void; restoreViewportStyles: () => void; disposeFitAddon: () => void; @@ -157,6 +158,10 @@ const isAppleHandheld = const FIT_TIMEOUT_DELAYS_MS = [0, 16, 48, 120, 250, 500, 1_000, 2_000]; const OUTPUT_OPERATION_TIMEOUT_MS = 5_000; const EMPTY_TERMINAL_OUTPUT = new Uint8Array(0); +// DOM events xterm turns into typed data on its textarea. Pastes stay suppressed during a +// replay: until the snapshot restores bracketed paste mode, a multi-line paste would run +// line by line in the shell. +const USER_INPUT_EVENT_TYPES = ["keydown", "keypress", "input"] as const; const RESET_TERMINAL_OUTPUT = new Uint8Array([0x1b, 0x63]); const terminalOutputEncoder = new TextEncoder(); @@ -313,6 +318,8 @@ export class TerminalEmulatorRuntime { private hasUngatedWrites = false; private readonly inputModeDecoder = new TextDecoder(); private suppressInput = false; + // The latest user input event the host saw; its eventPhase is NONE once dispatch ends. + private userInputEvent: Event | null = null; private readonly inputModeTracker = new TerminalInputModeTracker(); private lastInputModeState: TerminalInputModeState = this.inputModeTracker.getState(); private themeBackgroundElements: HTMLElement[] = []; @@ -739,8 +746,17 @@ export class TerminalEmulatorRuntime { fitAndEmitResize({ forceRefresh: true, shouldClaim: false }); + // xterm reports what the user types and the replies it generates while parsing + // through the same onData. Replies only come out of parsing a write, never while a + // user input event is dispatching, so typing survives a replay that suppresses them. + const recordUserInputEvent = (event: Event): void => { + this.userInputEvent = event; + }; + for (const type of USER_INPUT_EVENT_TYPES) { + input.host.addEventListener(type, recordUserInputEvent, true); + } const inputDisposable = terminal.onData((data) => { - if (this.suppressInput) { + if (this.suppressInput && !this.isDispatchingUserInput()) { return; } this.callbacks.onInput?.(data); @@ -844,6 +860,12 @@ export class TerminalEmulatorRuntime { removeFilePasteListener: () => { input.host.removeEventListener("paste", filePasteHandler, true); }, + removeUserInputListeners: () => { + for (const type of USER_INPUT_EVENT_TYPES) { + input.host.removeEventListener(type, recordUserInputEvent, true); + } + this.userInputEvent = null; + }, restoreDocumentStyles, restoreViewportStyles, disposeFitAddon: () => { @@ -873,6 +895,7 @@ export class TerminalEmulatorRuntime { disposables.clearFitTimeouts(); disposables.removeFontListeners(); disposables.removeFilePasteListener(); + disposables.removeUserInputListeners(); disposables.disposeFitAddon(); disposables.disposeWebglAddon(); disposables.disposeTerminal(); @@ -913,6 +936,10 @@ export class TerminalEmulatorRuntime { this.terminal?.paste(text); } + private isDispatchingUserInput(): boolean { + return (this.userInputEvent?.eventPhase ?? Event.NONE) !== Event.NONE; + } + private pasteClipboard(terminal: Pick): void { const text = this.clipboard.readText().catch(() => ""); const onFilePaste = this.callbacks.onFilePaste; From aead84bf0fa4e5bc6b457427bcafbec3acd95749 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:09:32 +0000 Subject: [PATCH 017/160] Interrupting sends no longer fail with "already has an active run" (#9537) * Interrupting sends no longer fail with "already has an active run" Two sends that interrupt the same running agent raced: the first left the foreground lane after cancelling and before reserving its new run, so the second send's cancel ran in that gap, saw the agent still marked running, and tracked a phantom run that made the first send's start throw. Replacements now queue per agent in arrival order, and each cancels and reserves its run inside one foreground mutation. A replacement that finds a run still starting waits for it outside the lane, so Stop still reaches it. Co-authored-by: Michael Wu <421504+michaelmwu@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * Interrupting sends still recover an agent whose turn never starts A replacement now waits for a starting run only up to the rescue timeout, then cancels it the way main did, so sending another message still unsticks an agent whose provider never acknowledges a start. Co-Authored-By: Claude Opus 5.5 * A queued replacement acts on the agent as it is when it gets the lane Resolve the managed agent inside the foreground mutation instead of before queueing, so a session reload while the send waits cannot leave it writing state to, or checking steer ownership against, the old agent. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Michael Wu <421504+michaelmwu@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/agent-manager.test.ts | 104 ++++++++++++++ .../server/src/server/agent/agent-manager.ts | 130 ++++++++++++------ 2 files changed, 193 insertions(+), 41 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 1491aaa6e7..0590bae58c 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -1529,6 +1529,110 @@ test("does not replace a newer foreground turn after unavailable steer fallback } }); +test("concurrent interrupting sends each start their own turn in order", async () => { + const session = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); + const { manager, agentId, workdir } = await startAndSteerThroughManager(session, "interrupt"); + try { + const prompts = ["first interrupt", "second interrupt", "third interrupt"]; + await Promise.all( + prompts.map((prompt) => + startAgentRun(manager, agentId, prompt, logger, { + replaceRunning: true, + activeTurnBehavior: "interrupt", + runOptions: { clientMessageId: prompt }, + }), + ), + ); + await manager.waitForAgentRunStart(agentId); + expect(session.startPrompts.slice(-3)).toEqual(prompts); + expect(manager.getAgent(agentId)?.activeForegroundTurnId).toBe( + `active-turn-${session.startCount}`, + ); + } finally { + await manager.closeAgent(agentId); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("Stop can cancel startup while an interrupting send waits behind it", async () => { + const entered = deferred(); + const release = deferred(); + class SlowStartSession extends SteeringTestSession { + starting = false; + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt === "slow startup") { + this.starting = true; + entered.resolve(); + await release.promise; + this.starting = false; + } + return super.startTurn(prompt); + } + override async interrupt(): Promise { + if (this.starting) release.resolve(); + await super.interrupt(); + } + } + const session = new SlowStartSession({ provider: "codex", cwd: process.cwd() }); + const { manager, agentId, workdir } = await startAndSteerThroughManager(session, "interrupt"); + try { + await startAgentRun(manager, agentId, "slow startup", logger, { replaceRunning: true }); + await entered.promise; + const replacement = startAgentRun(manager, agentId, "queued replacement", logger, { + replaceRunning: true, + }); + void replacement.catch(() => undefined); + const stop = manager.cancelAgentRun(agentId); + await vi.waitFor(() => expect(session.interruptCount).toBe(3), { timeout: 1000 }); + await stop; + await replacement; + await manager.waitForAgentRunStart(agentId); + expect(session.startPrompts.slice(-2)).toEqual(["slow startup", "queued replacement"]); + } finally { + release.resolve(); + await manager.closeAgent(agentId); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("an interrupting send replaces a turn whose start never finishes", async () => { + class StalledStartSession extends SteeringTestSession { + override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { + if (prompt === "stalled start") { + this.startPrompts.push(prompt); + return new Promise(() => {}); + } + return super.startTurn(prompt); + } + } + const session = new StalledStartSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stalled-start-")); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ + clients: { codex: client }, + logger, + rescueTimeouts: { interruptSessionMs: 10 }, + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + await startAgentRun(manager, agent.id, "stalled start", logger, { replaceRunning: true }); + await startAgentRun(manager, agent.id, "recovery", logger, { + replaceRunning: true, + activeTurnBehavior: "interrupt", + }); + expect(session.startPrompts).toEqual(["stalled start", "recovery"]); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("steers a tracked autonomous turn without creating a replacement run", async () => { const session = new SteeringTestSession({ provider: "claude", cwd: process.cwd() }); const workdir = mkdtempSync(join(tmpdir(), "agent-manager-autonomous-steer-")); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index b2570ff97e..4f17103938 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -844,6 +844,7 @@ export class AgentManager { private readonly sessionEventTails = new Map>(); private readonly steerEventBarriers = new Map(); private readonly foregroundMutationTails = new Map>(); + private readonly replacementMutationTails = new Map>(); private readonly runs = new AgentRunState(); private readonly subscribers = new Set(); private readonly idFactory: () => string; @@ -2112,6 +2113,7 @@ export class AgentManager { agent.inFlightPermissionResponses.size === 0 && (this.collectingRuntimes.has(agent.id) || !this.lifecycleMutationTails.has(agent.id)) && !this.foregroundMutationTails.has(agent.id) && + !this.replacementMutationTails.has(agent.id) && !this.sessionEventTails.has(agent.id) && !this.providerSubagents.list(agent.id).some((child) => child.status === "running") ); @@ -3414,31 +3416,8 @@ export class AgentManager { prompt: AgentPromptInput, options?: AgentRunOptions, ): Promise> { - const snapshot = this.requireAgent(agentId); - if ( - snapshot.lifecycle !== "running" && - !snapshot.activeForegroundTurnId && - !this.runs.hasRun(agentId) - ) { - return this.streamAgent(agentId, prompt, options); - } - - const agent = this.requireSessionAgent(agentId); - agent.pendingReplacement = true; - agent.lifecycle = "running"; - this.touchUpdatedAt(agent); - this.emitState(agent); - - try { - await this.cancelAgentRunBefore(agentId, "replace"); - return this.streamAgent(agentId, prompt, options); - } catch (error) { - const latest = this.agents.get(agentId); - if (latest) { - latest.pendingReplacement = false; - } - throw error; - } + this.requireSessionAgent(agentId); + return this.replaceRunInForegroundLane(agentId, prompt, options); } async steerAgentRun( @@ -3562,18 +3541,26 @@ export class AgentManager { } private async runForegroundMutation(agentId: string, operation: () => Promise): Promise { - const previous = this.foregroundMutationTails.get(agentId) ?? Promise.resolve(); + return this.runQueuedMutation(this.foregroundMutationTails, agentId, operation); + } + + private async runQueuedMutation( + tails: Map>, + agentId: string, + operation: () => Promise, + ): Promise { + const previous = tails.get(agentId) ?? Promise.resolve(); const run = previous.catch(() => undefined).then(operation); const tail = run.then( () => undefined, () => undefined, ); - this.foregroundMutationTails.set(agentId, tail); + tails.set(agentId, tail); try { return await run; } finally { - if (this.foregroundMutationTails.get(agentId) === tail) { - this.foregroundMutationTails.delete(agentId); + if (tails.get(agentId) === tail) { + tails.delete(agentId); } } } @@ -3585,20 +3572,81 @@ export class AgentManager { options?: AgentRunOptions, ): Promise> { this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId); - agent.pendingReplacement = true; - agent.lifecycle = "running"; - this.touchUpdatedAt(agent); - this.emitState(agent); + return this.replaceRunInForegroundLane(agent.id, prompt, options, (live) => + this.assertSteerAdmissionOwnsTurn(live, expectedTurnId), + ); + } - try { - await this.cancelAgentRunBefore(agent.id, "replace"); - return this.streamAgent(agent.id, prompt, options); - } catch (error) { - const latest = this.agents.get(agent.id); - if (latest) { - latest.pendingReplacement = false; + /** + * Cancels the current run and reserves its replacement in one foreground mutation, so a + * concurrent replacement or Stop cannot land between the cancel and the new run's start. + */ + private async replaceRunInForegroundLane( + agentId: string, + prompt: AgentPromptInput, + options: AgentRunOptions | undefined, + assertAdmission?: (agent: ActiveManagedAgent) => void, + ): Promise> { + // Replacements queue in arrival order; each one holds the foreground lane only while + // it cancels and reserves, so Stop is never stuck behind a replacement that is waiting. + return this.runQueuedMutation(this.replacementMutationTails, agentId, () => + this.replaceRunWhenAdmitted(agentId, prompt, options, assertAdmission), + ); + } + + private async replaceRunWhenAdmitted( + agentId: string, + prompt: AgentPromptInput, + options: AgentRunOptions | undefined, + assertAdmission?: (agent: ActiveManagedAgent) => void, + ): Promise> { + let stalledStart: PendingForegroundRun | null = null; + for (;;) { + const admission = await this.runForegroundMutation(agentId, async () => { + // Resolve the agent inside the lane: a reload while this send waited replaces it. + const agent = this.requireSessionAgent(agentId); + // A run that is still starting has no turn to interrupt yet. Canceling it would drop + // its prompt, so wait for it outside the lane, where Stop can still reach it. A start + // that outlasts the rescue timeout is canceled like any other run. + const starting = this.runs.getPendingRun(agent.id); + if (starting && starting.start.status !== "started" && starting !== stalledStart) { + return { status: "starting" as const, run: starting }; + } + assertAdmission?.(agent); + if (!this.hasInFlightRun(agent.id)) { + return { + status: "reserved" as const, + iterator: this.streamAgent(agent.id, prompt, options), + }; + } + agent.pendingReplacement = true; + agent.lifecycle = "running"; + this.touchUpdatedAt(agent); + this.emitState(agent); + try { + const result = await this.cancelAgentRunNow(agent.id); + if (result.status === "refused") { + throw new AgentRunCancellationError(agent.id, "replace"); + } + return { + status: "reserved" as const, + iterator: this.streamAgent(agent.id, prompt, options), + }; + } catch (error) { + agent.pendingReplacement = false; + throw error; + } + }); + if (admission.status === "reserved") { + return admission.iterator; + } + const started = await this.waitWithTimeout({ + operation: Promise.race([admission.run.turnStartedPromise, admission.run.settledPromise]), + timeoutMs: this.rescueTimeouts.interruptSessionMs, + }); + if (started === "timed_out") { + stalledStart = admission.run; } - throw error; } } From 1aba2a5f23672f0e2b0a605d35d2201bbd0be2c1 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:42:48 +0000 Subject: [PATCH 018/160] Measure composer pills after the compact layout replaces them (#9546) Resizing to a compact width mounts a new composer, so boundingBox() on a pill could resolve the wide layout's element and return null once it unmounted. Wait for the compact header, then poll each pill's width. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- packages/app/e2e/browser/composer-diff-stat.spec.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/app/e2e/browser/composer-diff-stat.spec.ts b/packages/app/e2e/browser/composer-diff-stat.spec.ts index 5dd2b8ae1d..d197dfa448 100644 --- a/packages/app/e2e/browser/composer-diff-stat.spec.ts +++ b/packages/app/e2e/browser/composer-diff-stat.spec.ts @@ -3,7 +3,7 @@ import { writeFile } from "node:fs/promises"; import path from "node:path"; import { expect, test, type Page } from "../support/fixtures"; import { seedSubagent } from "../support/helpers/subagents"; -import { submitMessage } from "../support/helpers/composer"; +import { expectWorkspaceHeaderVisible, submitMessage } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; import { gateNextAgentMessage } from "../support/helpers/agent-message-gate"; import { @@ -918,11 +918,12 @@ test.describe("touch composer tracks", () => { [tasks, subagents, changes].map(async (pill) => (await pill.boundingBox())!.width), ); await page.setViewportSize({ width: 200, height: 844 }); - const narrowWidths = await Promise.all( - [tasks, subagents, changes].map(async (pill) => (await pill.boundingBox())!.width), - ); - for (const [index, width] of wideWidths.entries()) - expect(narrowWidths[index]).toBeGreaterThanOrEqual(width - 1); + // The compact layout mounts a new composer, so measure only after it replaces the wide one. + await expectWorkspaceHeaderVisible(page); + for (const [index, pill] of [tasks, subagents, changes].entries()) + await expect + .poll(async () => (await pill.boundingBox())?.width ?? 0) + .toBeGreaterThanOrEqual(wideWidths[index] - 1); const track = page.getByTestId("composer-track-scroll"); expect(await track.evaluate((node) => node.scrollWidth)).toBeGreaterThan( await track.evaluate((node) => node.clientWidth), From e532a243279b3a782688adc20cfae2643afb87ac Mon Sep 17 00:00:00 2001 From: Orcun Simsek Date: Fri, 13 Nov 2026 06:57:45 +0300 Subject: [PATCH 019/160] fix(server): start cross-host children in their caller's mode (#9512) When an agent creates a child on another connected host without passing settings.modeId, the destination cannot see the caller, so the child fell back to the provider default instead of inheriting the caller's mode the way a same-host child does. A bypass caller's remote child then asked for approval on every tool call. Resolve the mode on the sending host before routing, as background already is: an omitted mode with a same-provider caller forwards the caller's current mode. Explicit modes still win, and cross-provider or caller-less creates still leave the mode to the destination. Co-authored-by: Orcun Simsek <1612171+ortschun@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../agent/host-operations/index.test.ts | 52 +++++++++++++++++-- .../src/server/agent/host-operations/index.ts | 15 +++--- .../server/connected-hosts/hosts.e2e.test.ts | 51 ++++++++++++++++++ 3 files changed, 107 insertions(+), 11 deletions(-) diff --git a/packages/server/src/server/agent/host-operations/index.test.ts b/packages/server/src/server/agent/host-operations/index.test.ts index fbd492e881..bc54209e60 100644 --- a/packages/server/src/server/agent/host-operations/index.test.ts +++ b/packages/server/src/server/agent/host-operations/index.test.ts @@ -107,11 +107,17 @@ async function olderHost() { return { client, socket }; } -function resolverFor(client: DaemonClient, callerBackground: boolean) { +interface Caller { + background: boolean; + provider: string; + currentModeId: string | null; +} + +function resolverFor(client: DaemonClient, caller: Caller | null) { return createHostResolver({ serverId: "origin", - callerAgentId: "caller", - caller: () => ({ background: callerBackground }), + callerAgentId: caller ? "caller" : undefined, + caller: () => caller, local: {} as HostOperations, hosts: () => ({ directory: async () => ({ self: { serverId: "origin", label: "Origin" }, hosts: [] }), @@ -120,6 +126,12 @@ function resolverFor(client: DaemonClient, callerBackground: boolean) { }); } +const visibleCodexCaller: Caller = { + background: false, + provider: "codex", + currentModeId: "full-access", +}; + const createArgs = { workspaceId: workspace.id, provider: "codex/gpt-5.4", @@ -129,7 +141,7 @@ const createArgs = { test("a visible caller still creates agents on a host without background agents", async () => { const { client, socket } = await olderHost(); - const creating = resolverFor(client, false).use("srv_older", (host) => + const creating = resolverFor(client, visibleCodexCaller).use("srv_older", (host) => host.createAgent(createArgs, {} as never), ); creating.catch(() => {}); @@ -143,7 +155,37 @@ test("a background caller's remote child asks the host to update instead of turn const { client, socket } = await olderHost(); await expect( - resolverFor(client, true).use("srv_older", (host) => host.createAgent(createArgs, {} as never)), + resolverFor(client, { ...visibleCodexCaller, background: true }).use("srv_older", (host) => + host.createAgent(createArgs, {} as never), + ), ).rejects.toThrow("Update the host to use background agents."); expect(socket.requests.map((request) => request.type)).not.toContain("create_agent_request"); }); + +async function forwardedMode(caller: Caller | null, args: Record = createArgs) { + const { client, socket } = await olderHost(); + const creating = resolverFor(client, caller).use("srv_older", (host) => + host.createAgent(args, {} as never), + ); + creating.catch(() => {}); + const request = (await socket.createRequest()) as { config: { modeId?: string } }; + return request.config.modeId; +} + +test("a remote child of the same provider starts in its caller's mode", async () => { + expect(await forwardedMode(visibleCodexCaller)).toBe("full-access"); +}); + +test("an explicit mode wins over the caller's mode on a remote host", async () => { + expect( + await forwardedMode(visibleCodexCaller, { ...createArgs, settings: { modeId: "auto" } }), + ).toBe("auto"); +}); + +test("a remote child of another provider leaves its mode to the host", async () => { + expect(await forwardedMode({ ...visibleCodexCaller, provider: "claude" })).toBeUndefined(); +}); + +test("a remote create without a caller agent leaves its mode to the host", async () => { + expect(await forwardedMode(null)).toBeUndefined(); +}); diff --git a/packages/server/src/server/agent/host-operations/index.ts b/packages/server/src/server/agent/host-operations/index.ts index f6ae774375..961ba10f88 100644 --- a/packages/server/src/server/agent/host-operations/index.ts +++ b/packages/server/src/server/agent/host-operations/index.ts @@ -203,8 +203,8 @@ export function createHostResolver(input: { local: HostOperations; hosts: () => ToolHosts; callerAgentId?: string; - /** The destination can't see the caller, so its background defaults resolve before routing. */ - caller: () => BackgroundCaller | null; + /** The destination can't see the caller, so its background and mode defaults resolve before routing. */ + caller: () => (BackgroundCaller & { provider: string; currentModeId: string | null }) | null; lockedCwd?: string; }) { return { @@ -222,6 +222,11 @@ export function createHostResolver(input: { async createAgent(args) { const parsed = remoteCreate.parse(args); const { provider, model } = resolveRequiredProviderModel(parsed.provider); + const caller = input.caller(); + // Same-provider children inherit the caller's mode, as they would on the same host. + const modeId = + parsed.settings?.modeId ?? + (caller?.provider === provider ? (caller.currentModeId ?? undefined) : undefined); const workspace = await client.findWorkspace(parsed.workspaceId); if (!workspace) throw new Error(`Workspace ${parsed.workspaceId} not found`); const labels = { @@ -236,15 +241,13 @@ export function createHostResolver(input: { model, cwd: workspace.workspaceDirectory, title: parsed.title, - modeId: parsed.settings?.modeId, + modeId, thinkingOptionId: parsed.settings?.thinkingOptionId, featureValues: parsed.settings?.features, }, workspaceId: parsed.workspaceId, // Older hosts reject any background with a workspaceId, so a visible create omits it. - ...(inheritAgentBackground(parsed.background, input.caller()) - ? { background: true } - : {}), + ...(inheritAgentBackground(parsed.background, caller) ? { background: true } : {}), labels, initialPrompt: parsed.initialPrompt, idempotencyKey: parsed.idempotencyKey, diff --git a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts index 5b618f0670..5caf88217d 100644 --- a/packages/server/src/server/connected-hosts/hosts.e2e.test.ts +++ b/packages/server/src/server/connected-hosts/hosts.e2e.test.ts @@ -2127,6 +2127,57 @@ test( }, ); +test( + "a remote child without a mode starts in its same-provider caller's mode", + { timeout: 30000 }, + async () => { + const a = await daemon({ mcpEnabled: true }); + const b = await daemon(); + const origin = await api(a); + const destination = await api(b); + await origin.paseo.hosts.add({ connection: `127.0.0.1:${b.port}` }); + const directory = await online(origin.paseo); + const workspace = await origin.paseo.workspaces.create({ + source: { kind: "directory", path: a.staticDir }, + }); + const remoteWorkspace = await destination.paseo.workspaces.create({ + source: { kind: "directory", path: b.staticDir }, + }); + const parent = await workspace.agents.create({ + config: { provider: "claude/claude-test", modeId: "bypassPermissions" }, + title: "Mode parent", + }); + const mcp = new Client({ name: "mode-parent", version: "1" }); + cleanup.push(() => mcp.close()); + await mcp.connect( + new StreamableHTTPClientTransport( + new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`), + ), + ); + const remoteMode = async (provider: string, settings?: { modeId: string }) => { + const response = await mcp.callTool({ + name: "create_agent", + arguments: { + serverId: directory.hosts[0]!.serverId, + workspaceId: remoteWorkspace.id, + provider, + title: "Mode child", + initialPrompt: "Report your mode", + settings, + }, + }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + const childId = (response.structuredContent as { agentId: string }).agentId; + return (await destination.client.fetchAgent(childId))?.agent.currentModeId; + }; + + expect(await remoteMode("claude/claude-test")).toBe("bypassPermissions"); + expect(await remoteMode("claude/claude-test", { modeId: "default" })).toBe("default"); + // Another provider's modes are unknown here, so the destination applies its own default. + expect(await remoteMode("codex/gpt-5.4")).toBeNull(); + }, +); + test( "remote finish observation survives a permission checkpoint until resumed completion", { timeout: 30000 }, From 7791dcee3b97abe96f6662513937815bf368d6a0 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 11:20:12 +0700 Subject: [PATCH 020/160] Docs: document the public iOS TestFlight beta on the Updates page (#9553) * Document the public iOS TestFlight beta and how to get betas on every platform * Show the TestFlight beta on the download page's Beta view --- docs/release.md | 3 ++- packages/website/src/downloads.tsx | 1 + .../website/src/routes/{-$locale}/download.tsx | 15 +++++++++------ public-docs/updates.md | 15 ++++++++------- public-docs/updates.zh-CN.md | 15 ++++++++------- 5 files changed, 28 insertions(+), 21 deletions(-) diff --git a/docs/release.md b/docs/release.md index 869aab78ec..5da108be41 100644 --- a/docs/release.md +++ b/docs/release.md @@ -248,6 +248,7 @@ npm run release:promote # Promote X.Y.Z-beta.N to stable X.Y.Z - Beta tags are published GitHub prereleases like `v0.1.41-beta.1` - Betas publish npm packages with `--tag beta`, so `npm install @getpaseo/cli@beta` opts in while plain `npm install @getpaseo/cli` stays on `latest` +- The user-facing beta instructions, including the public TestFlight join link for the `Paseo Beta` group, live in `public-docs/updates.md` and its `zh-CN` pair. Update them when a beta path is added or removed. - Betas publish desktop assets and APKs for testing. They also build iOS, upload it to TestFlight, add it to the `Paseo Beta` external group, and submit it for Beta App Review. They do not submit mobile builds to the production stores. - `release:promote` creates a fresh stable tag like `v0.1.41`; the final release never reuses the beta tag - Desktop assets now come from the Electron package at `packages/desktop` @@ -488,7 +489,7 @@ The GitHub Release body is populated automatically by the `Release Notes Sync` w - The website download page defaults to GitHub's latest published **stable** release. - A published beta prerelease is offered behind the Stable/Beta switch on `/download` (`?channel=beta`), never as the default. The switch only appears while the newest prerelease leads stable on its core version, so promoting `X.Y.Z-beta.N` to `X.Y.Z` retires the beta channel from the page until the next beta line opens. -- Homebrew, the Play Store, the App Store, and `app.paseo.sh` have no beta. The Beta view drops those rows, and the whole Web section, rather than showing an inert "stable only" placeholder. When a surface gains a beta path — say a public TestFlight link — add its row back in `packages/website/src/routes/download.tsx`. +- Homebrew, the Play Store, and `app.paseo.sh` have no beta. The Beta view drops those rows, and the whole Web section, rather than showing an inert "stable only" placeholder. The iOS row swaps the App Store pill for the public TestFlight link (`testFlightBetaUrl` in `packages/website/src/downloads.tsx`). When another surface gains a beta path, add its row back in `packages/website/src/routes/{-$locale}/download.tsx`. - The default download target only moves when you publish the final stable release tag like `v0.1.41`. - The public `/changelog` page renders `CHANGELOG.md` as-is, so the in-flight `-beta.N` entry shows there once it lands on `main` — that's intended, it's where beta users check what's coming. Only the **default download target** stays pinned to the latest stable; the download links read GitHub's releases API, not the changelog, so a `-beta.N` heading on top never affects them. - The download page's "What's new" link deep-links the **minor group** anchor (`/changelog#release-0.3`), not the exact entry: the beta entry is renamed on each beta and on promotion, so the minor group remains the durable target. A version with no entry in the bundled changelog — a tag whose changelog commit hasn't redeployed the site yet — links the plain `/changelog` instead of a dead anchor. diff --git a/packages/website/src/downloads.tsx b/packages/website/src/downloads.tsx index a97b18c991..3ca73f6364 100644 --- a/packages/website/src/downloads.tsx +++ b/packages/website/src/downloads.tsx @@ -50,6 +50,7 @@ export function thanksPageHref(fileUrl: string, locale: Locale): string { } export const appStoreUrl = "https://apps.apple.com/app/paseo-pocket-engineer/id6758887924"; +export const testFlightBetaUrl = "https://testflight.apple.com/join/Y5HpSQjJ"; export const playStoreUrl = "https://play.google.com/store/apps/details?id=sh.paseo"; export const webAppUrl = "https://app.paseo.sh"; diff --git a/packages/website/src/routes/{-$locale}/download.tsx b/packages/website/src/routes/{-$locale}/download.tsx index de071302e5..6d4697bd1e 100644 --- a/packages/website/src/routes/{-$locale}/download.tsx +++ b/packages/website/src/routes/{-$locale}/download.tsx @@ -10,6 +10,7 @@ import { downloadUrls, appStoreUrl, playStoreUrl, + testFlightBetaUrl, thanksPageHref, webAppUrl, AppleIcon, @@ -159,13 +160,15 @@ function Download() { - {!onBeta && ( - - + + + {onBeta ? ( + + ) : ( - - - )} + )} + + diff --git a/public-docs/updates.md b/public-docs/updates.md index e5a11eee29..84b9d7acae 100644 --- a/public-docs/updates.md +++ b/public-docs/updates.md @@ -52,19 +52,20 @@ Betas are the best way to get fixes and features early. If you hit a bug, report ### How to join the beta channel -In the desktop app: +| Platform | How to get betas | +| -------------- | ------------------------------------------------------------------------------------------------------------- | +| iOS and iPadOS | Join the [Paseo TestFlight beta](https://testflight.apple.com/join/Y5HpSQjJ). | +| Android | Download the APK from a prerelease on the [GitHub releases page](https://github.com/getpaseo/paseo/releases). | +| Desktop | Open **Settings → About** and select **Beta** under **Release channel**. | +| CLI | Run `npm install -g @getpaseo/cli@beta`. Plain `npm install -g @getpaseo/cli` stays on stable. | -1. Open **Settings** -2. Go to **About** -3. Under **Release channel**, select **Beta** - -The app will check for beta updates from then on. +The desktop app checks for beta updates from the moment you select **Beta**. ## App stores Desktop releases and the CLI are usually available first. App Store and Play Store releases can lag behind because they go through review. -There is no beta channel in the app stores right now — only stable builds are submitted. If you want early Android builds, download the APK from the [GitHub releases page](https://github.com/getpaseo/paseo/releases). +The App Store and Play Store listings carry stable builds only. On iOS, the [TestFlight beta](https://testflight.apple.com/join/Y5HpSQjJ) is the beta channel. Every beta is uploaded to it after Apple's beta review, and stable releases are uploaded to it as well, so TestFlight testers stay on the latest build. On Android there is no Play Store beta, so install beta APKs from GitHub. ## What to do if something breaks diff --git a/public-docs/updates.zh-CN.md b/public-docs/updates.zh-CN.md index b83e520db1..90b4526934 100644 --- a/public-docs/updates.zh-CN.md +++ b/public-docs/updates.zh-CN.md @@ -50,19 +50,20 @@ v0.1.92-beta.3 ### 如何加入测试版渠道 {#how-to-join-the-beta-channel} -在桌面应用中: +| 平台 | 获取测试版的方式 | +| ------------- | ------------------------------------------------------------------------------------------------ | +| iOS 和 iPadOS | 加入 [Paseo TestFlight 测试版](https://testflight.apple.com/join/Y5HpSQjJ)。 | +| Android | 从 [GitHub releases 页面](https://github.com/getpaseo/paseo/releases)的预发布版本下载 APK。 | +| 桌面端 | 打开 **设置 → 关于**,在 **发布通道** 下选择 **Beta**。 | +| CLI | 运行 `npm install -g @getpaseo/cli@beta`。直接运行 `npm install -g @getpaseo/cli` 仍使用稳定版。 | -1. 打开 **设置** -2. 进入 **关于** -3. 在 **发布通道** 下选择 **Beta** - -之后应用就会检查测试版更新。 +在桌面应用中选择 **Beta** 后,应用就会检查测试版更新。 ## 应用商店 {#app-stores} 桌面端版本和 CLI 通常最先提供。App Store 和 Play Store 的版本需要经过审核,可能会滞后。 -应用商店目前没有测试版渠道,只提交稳定版构建。如果你想提前使用 Android 构建,请从 [GitHub releases 页面](https://github.com/getpaseo/paseo/releases)下载 APK。 +App Store 和 Play Store 的商店页面只提供稳定版构建。在 iOS 上,[TestFlight 测试版](https://testflight.apple.com/join/Y5HpSQjJ)就是测试版渠道。每个测试版都会在通过 Apple 的测试版审核后上传到 TestFlight,稳定版也会上传到那里,所以 TestFlight 测试者始终使用最新构建。Android 没有 Play Store 测试版,请从 GitHub 安装测试版 APK。 ## 出现问题怎么办 {#what-to-do-if-something-breaks} From c558af91ebac263abb94666b09bea60f20c8e8fa Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:13:38 +0700 Subject: [PATCH 021/160] fix(usage): show Copilot premium request quota (#8489) The usage source discarded quota snapshots, leaving the card with only a plan and reset date. Publish finite premium usage through the existing window interface and retain its remaining request count. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Ryan Swift --- .../copilot-usage-source/server/usage.test.ts | 87 +++++++++++++++++++ plugins/copilot-usage-source/server/usage.ts | 39 ++++++++- 2 files changed, 125 insertions(+), 1 deletion(-) diff --git a/plugins/copilot-usage-source/server/usage.test.ts b/plugins/copilot-usage-source/server/usage.test.ts index 8333f28828..def2a2d0c2 100644 --- a/plugins/copilot-usage-source/server/usage.test.ts +++ b/plugins/copilot-usage-source/server/usage.test.ts @@ -171,3 +171,90 @@ it.each([401, 403])("reports an existing login rejected with HTTP %i", async (st else process.env["COPILOT_TOKEN"] = previous; } }); + +it.each([ + { remaining: 1500, percentRemaining: 100, usedPct: 0 }, + { remaining: 1125, percentRemaining: 75, usedPct: 25 }, + { remaining: 0, percentRemaining: 0, usedPct: 100 }, +])( + "reports premium quota with $remaining requests remaining", + async ({ remaining, percentRemaining, usedPct }) => { + const report = await fetchPremiumQuota({ + entitlement: 1500, + remaining, + percent_remaining: percentRemaining, + unlimited: false, + }); + expect(report).toMatchObject({ + status: "available", + planLabel: "individual", + windows: [ + { + id: "premium_interactions", + label: "Premium requests", + usedPct, + remainingPct: percentRemaining, + resetsAt: "2026-12-01T00:00:00.000Z", + }, + ], + details: expect.arrayContaining([ + { + id: "premium_remaining", + label: "Premium requests remaining", + value: `${remaining} / 1500`, + }, + ]), + }); + }, +); + +it.each([ + undefined, + null, + { unlimited: true, percent_remaining: 100, remaining: 1500, entitlement: 1500 }, +])( + "does not invent a finite quota for absent or unlimited premium snapshots (%j)", + async (premium) => { + const report = await fetchPremiumQuota(premium); + expect(report).toMatchObject({ + status: "available", + windows: [], + details: [{ id: "reset", label: "Quota reset", value: "2026-12-01" }], + }); + }, +); + +it("reports a percentage without inventing missing counts and falls back to the legacy reset", async () => { + const report = await fetchPremiumQuota({ percent_remaining: 60, unlimited: false }, null); + expect(report).toMatchObject({ + status: "available", + windows: [{ usedPct: 40, remainingPct: 60, resetsAt: "2026-12-01" }], + details: [{ id: "reset", label: "Quota reset", value: "2026-12-01" }], + }); +}); + +async function fetchPremiumQuota( + premium: unknown, + utcReset: string | null = "2026-12-01T00:00:00.000Z", +) { + const { writeFile } = await import("node:fs/promises"); + const directory = mkdtempSync(join(tmpdir(), "copilot-premium-")); + const locator = join(directory, "hosts.yml"); + try { + await writeFile(locator, "github.com:\n oauth_token: fixture-copilot\n"); + return await fetchUsage({ store: "file", locator }, async () => + jsonResponse({ + copilot_plan: "individual", + quota_reset_date: "2026-12-01", + quota_reset_date_utc: utcReset, + quota_snapshots: { + premium_interactions: premium, + chat: { unlimited: true, percent_remaining: 100 }, + completions: { unlimited: true, percent_remaining: 100 }, + }, + }), + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/plugins/copilot-usage-source/server/usage.ts b/plugins/copilot-usage-source/server/usage.ts index 78ae61bc9f..b7159c6970 100644 --- a/plugins/copilot-usage-source/server/usage.ts +++ b/plugins/copilot-usage-source/server/usage.ts @@ -5,6 +5,8 @@ import { join } from "node:path"; import { z } from "zod"; import { unavailable, + windowFromUsedPct, + type UsageWindow, type UsageAccount, type UsageReport, type UsageDetail, @@ -18,6 +20,19 @@ const ApiOptionalStringSchema = z.preprocess( const CopilotUsageResponseSchema = z.object({ copilot_plan: ApiOptionalStringSchema, quota_reset_date: ApiOptionalStringSchema, + quota_reset_date_utc: ApiOptionalStringSchema, + quota_snapshots: z + .object({ + premium_interactions: z + .object({ + entitlement: z.number().nonnegative().nullish(), + remaining: z.number().nonnegative().nullish(), + percent_remaining: z.number().min(0).max(100).nullish(), + unlimited: z.boolean().optional(), + }) + .nullish(), + }) + .nullish(), }); async function readToken(input: UsageInput): Promise { @@ -72,10 +87,32 @@ export async function fetchUsage( ? [{ id: "reset", label: "Quota reset", value: resp.quota_reset_date }] : []; + const windows: UsageWindow[] = []; + const premium = resp.quota_snapshots?.premium_interactions; + if (premium && !premium.unlimited) { + if (premium.percent_remaining != null) { + windows.push( + windowFromUsedPct({ + id: "premium_interactions", + label: "Premium requests", + utilizationPct: 100 - premium.percent_remaining, + resetsAt: resp.quota_reset_date_utc || resp.quota_reset_date, + }), + ); + } + if (premium.remaining != null && premium.entitlement != null) { + details.push({ + id: "premium_remaining", + label: "Premium requests remaining", + value: `${premium.remaining} / ${premium.entitlement}`, + }); + } + } + return { status: "available", planLabel: resp.copilot_plan || undefined, - windows: [], + windows, balances: [], details, }; From b6952995be1ac5dad6a24d4baaf4332396e710c4 Mon Sep 17 00:00:00 2001 From: Jack Tomaszewski Date: Fri, 13 Nov 2026 06:40:17 +0100 Subject: [PATCH 022/160] feat(app): use Cmd+Shift+[ / ] for previous/next tab on macOS desktop (#7692) * feat(app): use Cmd+Shift+[ / ] for previous/next tab on macOS desktop Co-Authored-By: Claude Opus 5.5 * fix(app): drop Alt+Shift tab navigation on macOS desktop Co-Authored-By: Claude Opus 5.5 * test(app): cover previous/next tab shortcuts on web and macOS desktop Co-Authored-By: Claude Opus 5.5 * fix(app): adopt desktopBindings condition for tab navigation shortcuts Main renamed the binding condition `desktop` to `desktopBindings` and the test context `isDesktop` to `usesDesktopBindings` (#8625). Rebase the Cmd+Shift+[ / ] tab shortcuts onto that vocabulary. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Mohamed Boudra --- .../workspace-tab-relative-navigation.spec.ts | 32 +++++++++ .../src/keyboard/keyboard-shortcuts.test.ts | 30 ++++++++ .../app/src/keyboard/keyboard-shortcuts.ts | 54 ++++++++++++++- .../workspace-tab-relative-navigation.spec.ts | 68 +++++++++++++++++++ 4 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 packages/app/e2e/browser/workspace-tab-relative-navigation.spec.ts create mode 100644 packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts diff --git a/packages/app/e2e/browser/workspace-tab-relative-navigation.spec.ts b/packages/app/e2e/browser/workspace-tab-relative-navigation.spec.ts new file mode 100644 index 0000000000..a44503c89d --- /dev/null +++ b/packages/app/e2e/browser/workspace-tab-relative-navigation.spec.ts @@ -0,0 +1,32 @@ +import { expect, test } from "../support/fixtures"; +import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs"; + +// The browser owns Cmd+Shift+brackets for its own tabs, so web keeps +// Alt+Shift+brackets on every OS. Desktop bindings live in the desktop suite. +test("web switches to the previous and next tab with Alt+Shift+[ and ]", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "tab-relative-web-" }); + try { + await gotoWorkspace(page, workspace.workspaceId); + await waitForWorkspaceTabsVisible(page); + const terminalTabs = page + .locator('[data-testid^="workspace-tab-terminal_"]') + .filter({ visible: true }); + await clickNewTerminal(page); + await expect(terminalTabs).toHaveCount(1, { timeout: 30_000 }); + await clickNewTerminal(page); + await expect(terminalTabs).toHaveCount(2, { timeout: 30_000 }); + const first = terminalTabs.nth(0); + const second = terminalTabs.nth(1); + await expect(second).toHaveAttribute("aria-selected", "true"); + + await page.keyboard.press("Alt+Shift+BracketLeft"); + await expect(first).toHaveAttribute("aria-selected", "true"); + + await page.keyboard.press("Alt+Shift+BracketRight"); + await expect(second).toHaveAttribute("aria-selected", "true"); + } finally { + await workspace.cleanup(); + } +}); diff --git a/packages/app/src/keyboard/keyboard-shortcuts.test.ts b/packages/app/src/keyboard/keyboard-shortcuts.test.ts index 9eddf4b5b5..03066dedd7 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.test.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.test.ts @@ -226,6 +226,20 @@ describe("keyboard-shortcuts", () => { action: "workspace.tab.navigate.relative", payload: { delta: 1 }, }, + { + name: "matches tab relative navigation on macOS desktop via Cmd+Shift+[", + event: { key: "{", code: "BracketLeft", metaKey: true, shiftKey: true }, + context: { isMac: true, usesDesktopBindings: true }, + action: "workspace.tab.navigate.relative", + payload: { delta: -1 }, + }, + { + name: "matches tab relative navigation on macOS desktop via Cmd+Shift+]", + event: { key: "}", code: "BracketRight", metaKey: true, shiftKey: true }, + context: { isMac: true, usesDesktopBindings: true }, + action: "workspace.tab.navigate.relative", + payload: { delta: 1 }, + }, { name: "matches Mod+T to open new tab", event: { key: "t", code: "KeyT", metaKey: true }, @@ -479,6 +493,11 @@ describe("keyboard-shortcuts", () => { event: { key: "w", code: "KeyW", ctrlKey: true }, context: { isMac: false, usesDesktopBindings: true, focusScope: "terminal" }, }, + { + name: "does not switch tabs with Alt+Shift+] on mac desktop (Cmd+Shift+] only)", + event: { key: "’", code: "BracketRight", altKey: true, shiftKey: true }, + context: { isMac: true, usesDesktopBindings: true }, + }, { name: "does not match Ctrl+T on mac (Cmd only)", event: { key: "t", code: "KeyT", ctrlKey: true }, @@ -1306,6 +1325,17 @@ describe("unassigned shortcuts", () => { expect(getBindingIdForAction("workspace-tab-new", desktopNonMac)).toBe(TAB_NEW_BINDING); }); + it("advertises Cmd+Shift+brackets for tab navigation on macOS desktop", () => { + const desktopMac = { isMac: true, usesDesktopBindings: true }; + + expect(getDefaultKeysForAction("workspace-tab-prev", desktopMac)).toEqual([ + ["mod", "shift", "["], + ]); + expect(getDefaultKeysForAction("workspace-tab-next", desktopMac)).toEqual([ + ["mod", "shift", "]"], + ]); + }); + it("still lists the default keys when nothing is overridden", () => { const sections = buildKeyboardShortcutHelpSections(desktopNonMac); diff --git a/packages/app/src/keyboard/keyboard-shortcuts.ts b/packages/app/src/keyboard/keyboard-shortcuts.ts index d6db467da3..ef929903c6 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.ts @@ -715,11 +715,37 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ }, // --- Tab relative navigation --- + // macOS desktop uses Cmd+Shift+brackets; the browser owns those keys, so + // macOS web keeps Alt+Shift alongside every non-mac platform. + { + id: "workspace-tab-navigate-relative-cmd-shift-left-mac", + action: "workspace.tab.navigate.relative", + combo: "Cmd+Shift+[", + when: { mac: true, desktopBindings: true, commandCenter: false }, + payload: { type: "delta", delta: -1 }, + help: { + id: "workspace-tab-prev", + section: "tabs-panes", + label: "Previous tab", + }, + }, + { + id: "workspace-tab-navigate-relative-cmd-shift-right-mac", + action: "workspace.tab.navigate.relative", + combo: "Cmd+Shift+]", + when: { mac: true, desktopBindings: true, commandCenter: false }, + payload: { type: "delta", delta: 1 }, + help: { + id: "workspace-tab-next", + section: "tabs-panes", + label: "Next tab", + }, + }, { id: "workspace-tab-navigate-relative-alt-shift-left", action: "workspace.tab.navigate.relative", combo: "Alt+Shift+[", - when: { commandCenter: false }, + when: { mac: false, commandCenter: false }, payload: { type: "delta", delta: -1 }, help: { id: "workspace-tab-prev", @@ -731,7 +757,31 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [ id: "workspace-tab-navigate-relative-alt-shift-right", action: "workspace.tab.navigate.relative", combo: "Alt+Shift+]", - when: { commandCenter: false }, + when: { mac: false, commandCenter: false }, + payload: { type: "delta", delta: 1 }, + help: { + id: "workspace-tab-next", + section: "tabs-panes", + label: "Next tab", + }, + }, + { + id: "workspace-tab-navigate-relative-alt-shift-left-mac-web", + action: "workspace.tab.navigate.relative", + combo: "Alt+Shift+[", + when: { mac: true, desktopBindings: false, commandCenter: false }, + payload: { type: "delta", delta: -1 }, + help: { + id: "workspace-tab-prev", + section: "tabs-panes", + label: "Previous tab", + }, + }, + { + id: "workspace-tab-navigate-relative-alt-shift-right-mac-web", + action: "workspace.tab.navigate.relative", + combo: "Alt+Shift+]", + when: { mac: true, desktopBindings: false, commandCenter: false }, payload: { type: "delta", delta: 1 }, help: { id: "workspace-tab-next", diff --git a/packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts b/packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts new file mode 100644 index 0000000000..033e99009e --- /dev/null +++ b/packages/desktop/e2e/workspace-tab-relative-navigation.spec.ts @@ -0,0 +1,68 @@ +import type { Page } from "@playwright/test"; +import { test, expect } from "../../app/e2e/support/fixtures"; +import { clickNewTerminal, gotoWorkspace } from "../../app/e2e/support/helpers/launcher"; +import { seedWorkspace } from "../../app/e2e/support/helpers/seed-client"; +import { waitForWorkspaceTabsVisible } from "../../app/e2e/support/helpers/workspace-tabs"; + +// macOS desktop switches tabs with Cmd+Shift+brackets, like other Mac apps. +// Web keeps Alt+Shift (the browser owns Cmd+Shift+brackets) and is covered in +// the app browser suite. Windows/Linux desktop can't be emulated here: shortcut +// OS detection falls back to the host user agent for non-darwin bridges. + +async function installMacDesktopBridge(page: Page): Promise { + await page.addInitScript(() => { + window.paseoDesktop = { + platform: "darwin", + events: { on: () => () => {} }, + invoke: async (command: string) => { + if (command === "get_desktop_settings") { + return { + releaseChannel: "stable", + daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true }, + }; + } + return null; + }, + }; + }); +} + +const terminalTabs = (page: Page) => + page.locator('[data-testid^="workspace-tab-terminal_"]').filter({ visible: true }); + +async function openTwoTerminalTabs(page: Page) { + await waitForWorkspaceTabsVisible(page); + await clickNewTerminal(page); + await expect(terminalTabs(page)).toHaveCount(1, { timeout: 30_000 }); + await clickNewTerminal(page); + await expect(terminalTabs(page)).toHaveCount(2, { timeout: 30_000 }); + const first = terminalTabs(page).nth(0); + const second = terminalTabs(page).nth(1); + await expect(second).toHaveAttribute("aria-selected", "true"); + return { first, second }; +} + +test.describe("Previous/next tab shortcuts on desktop", () => { + test("macOS desktop switches tabs with Cmd+Shift+[ and ], not Alt+Shift", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "tab-relative-mac-desktop-" }); + try { + await installMacDesktopBridge(page); + await gotoWorkspace(page, workspace.workspaceId); + const { first, second } = await openTwoTerminalTabs(page); + + await page.keyboard.press("Meta+Shift+BracketLeft"); + await expect(first).toHaveAttribute("aria-selected", "true"); + + await page.keyboard.press("Meta+Shift+BracketRight"); + await expect(second).toHaveAttribute("aria-selected", "true"); + + // Alt+Shift is the web and Windows/Linux binding and must not fire here. + // Had it moved to the first tab, Cmd+Shift+[ would wrap back to the second. + await page.keyboard.press("Alt+Shift+BracketLeft"); + await page.keyboard.press("Meta+Shift+BracketLeft"); + await expect(first).toHaveAttribute("aria-selected", "true"); + } finally { + await workspace.cleanup(); + } + }); +}); From 8b3b2a9ea33e530d4d6f2c1294c2e290c92e69b1 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 13:09:38 +0700 Subject: [PATCH 023/160] Stop re-sending unchanged Changes snapshots to apps older than 0.16 (#9562) * fix(server): stop re-sending unchanged Changes snapshots to pre-0.16 apps The shared diff engine commits a revision for every observed input change: ignored-file writes, same-content saves, mtime touches, index rewrites, and ref moves that only change the resolved SHAs. Binary-stream clients absorb those cheaply by reusing unchanged file objects. The legacy adapter turned each revision into a full JSON snapshot, so old apps were re-sent the whole diff (5 MB+ on large checkouts) whenever the repository was touched. The adapter now sends a snapshot only when it differs from the last one it sent to that subscriber, as 0.15 did. The check lives here, not in the engine, because the JSON snapshot drops the resolved SHAs: a commit that moves HEAD in All mode is a real revision for new clients and a no-op for old ones. * test(server): wait for the revision end before asserting no legacy push --- .../src/server/checkout-diff-manager.test.ts | 79 +++++++++++++++++++ .../src/server/checkout-diff-manager.ts | 6 ++ 2 files changed, 85 insertions(+) diff --git a/packages/server/src/server/checkout-diff-manager.test.ts b/packages/server/src/server/checkout-diff-manager.test.ts index da2947c24d..e1f0e25a33 100644 --- a/packages/server/src/server/checkout-diff-manager.test.ts +++ b/packages/server/src/server/checkout-diff-manager.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { tmpdir } from "node:os"; import pino from "pino"; import { expect, test } from "vitest"; +import { DiffOpcode } from "@getpaseo/protocol/binary-frames/index"; import { CheckoutDiffManager, type CheckoutDiffSnapshotPayload } from "./checkout-diff-manager.js"; import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; import { createFileObserver } from "./file-observer/index.js"; @@ -137,6 +138,84 @@ test("cancelling a legacy subscriber during a shared revision does not revive it }); }, 30_000); +test("legacy subscribers are not re-sent a snapshot that did not change", async () => { + await withCheckout(async ({ cwd, manager }) => { + await writeFile(join(cwd, ".gitignore"), "*.log\n"); + await writeFile(join(cwd, "x.ts"), "const value = 1;\n"); + let revisions = 0; + const modern = await manager.streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + if (frame.opcode === DiffOpcode.End) revisions++; + }, + ); + await modern.start(); + const updates: CheckoutDiffSnapshotPayload[] = []; + const legacy = await manager.subscribe({ cwd, compare: { mode: "uncommitted" } }, (snapshot) => + updates.push(snapshot), + ); + try { + expect(legacy.initial.files.map((file) => file.path)).toEqual([".gitignore", "x.ts"]); + await waitForSubscriberCount(manager, 2); + const before = revisions; + await writeFile(join(cwd, "app.log"), "ignored\n"); + await writeFile(join(cwd, "README"), "base\n"); + await writeFile(join(cwd, "x.ts"), "const value = 1;\n"); + await manager.scheduleRefreshForCwd(cwd); + await expect.poll(() => revisions, { timeout: 10_000 }).toBeGreaterThan(before); + expect(updates).toHaveLength(0); + await writeFile(join(cwd, "x.ts"), "const value = 2;\n"); + await expect.poll(() => updates.length, { timeout: 10_000 }).toBe(1); + expect(updates[0].files[1].hunks[0].lines).toContainEqual( + expect.objectContaining({ type: "add", content: "const value = 2;" }), + ); + } finally { + await legacy.unsubscribe(); + await modern.release(); + } + }); +}, 30_000); + +test("legacy All subscribers are not re-sent the snapshot when a commit only moves HEAD", async () => { + await withCheckout(async ({ cwd, manager, git }) => { + git("checkout", "-b", "feature"); + await writeFile(join(cwd, "x.ts"), "const value = 1;\n"); + const endedHeads: string[] = []; + let beganHead = ""; + const modern = await manager.streams.subscribe( + { + cwd, + base: { kind: "rev", rev: "main" }, + checkoutBase: { compare: { mode: "all", baseRef: "main" }, paseoHome: cwd }, + head: { kind: "worktree" }, + mergeBase: true, + }, + async (frame) => { + if (frame.opcode === DiffOpcode.Begin) beganHead = frame.headSha; + if (frame.opcode === DiffOpcode.End) endedHeads.push(beganHead); + }, + ); + await modern.start(); + const updates: CheckoutDiffSnapshotPayload[] = []; + const legacy = await manager.subscribe( + { cwd, compare: { mode: "all", baseRef: "main" } }, + (snapshot) => updates.push(snapshot), + ); + try { + expect(legacy.initial.files.map((file) => file.path)).toEqual(["x.ts"]); + await waitForSubscriberCount(manager, 2); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "feature"); + const head = git("rev-parse", "HEAD"); + await expect.poll(() => endedHeads.at(-1), { timeout: 10_000 }).toBe(head); + expect(updates).toHaveLength(0); + } finally { + await legacy.unsubscribe(); + await modern.release(); + } + }); +}, 30_000); + async function waitForSubscriberCount(manager: CheckoutDiffManager, count: number): Promise { await expect .poll(() => manager.getMetrics().checkoutDiffSubscriptionCount, { timeout: 10_000 }) diff --git a/packages/server/src/server/checkout-diff-manager.ts b/packages/server/src/server/checkout-diff-manager.ts index 921934e70e..6eb83de4e8 100644 --- a/packages/server/src/server/checkout-diff-manager.ts +++ b/packages/server/src/server/checkout-diff-manager.ts @@ -73,6 +73,7 @@ export class CheckoutDiffManager { resolveInitial = resolve; }); let delivered = false; + let deliveredFingerprint = ""; let pending: DiffBegin | null = null; let files = new Map(); let bodies = new Map(); @@ -114,6 +115,11 @@ export class CheckoutDiffManager { payload = legacySnapshot(cwd, [...next.values()]); } pending = null; + // The engine commits a revision per observed input change, including ones that only move the + // resolved SHAs this snapshot omits. Old clients get a snapshot only when it differs. + const fingerprint = JSON.stringify(payload); + if (fingerprint === deliveredFingerprint) return; + deliveredFingerprint = fingerprint; if (delivered) listener(payload); else { delivered = true; From 70aeb7b45b3c73f934b652327f766af0ba80bb8f Mon Sep 17 00:00:00 2001 From: Papa Goose <7808846+papag00se@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:29 -0800 Subject: [PATCH 024/160] fix(pi,omp): treat null optional tool arguments as omitted (#9506) Models commonly send null for optional tool arguments, such as read offset/limit (captured in #7011) and bash timeout. Pi and OMP treat null as omitted, but the Paseo mappers rejected it, so these calls fell back to unknown tool cards that show raw JSON input and output instead of Read/Shell cards. --- .../agent/providers/omp/tool-call-detail.ts | 3 ++- .../agent/providers/pi/tool-call-mapper.ts | 3 ++- .../agent/providers/tool-call-args.test.ts | 18 ++++++++++++++++++ .../server/agent/providers/tool-call-args.ts | 9 +++++++++ 4 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 packages/server/src/server/agent/providers/tool-call-args.test.ts create mode 100644 packages/server/src/server/agent/providers/tool-call-args.ts diff --git a/packages/server/src/server/agent/providers/omp/tool-call-detail.ts b/packages/server/src/server/agent/providers/omp/tool-call-detail.ts index cece7f0398..296d2c5de3 100644 --- a/packages/server/src/server/agent/providers/omp/tool-call-detail.ts +++ b/packages/server/src/server/agent/providers/omp/tool-call-detail.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import type { ToolCallDetail } from "../../agent-sdk-types.js"; +import { omitNullArgs } from "../tool-call-args.js"; interface BashToolInput { command: string; @@ -324,7 +325,7 @@ export function parseToolArgs(toolName: string, rawArgs: unknown): OmpTrackedToo } const schema = SIMPLE_TOOL_SCHEMAS[toolName as SimpleToolKind]; if (schema) { - const parsed = schema.safeParse(rawArgs); + const parsed = schema.safeParse(omitNullArgs(rawArgs)); if (parsed.success) { return { kind: toolName as SimpleToolKind, diff --git a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts index 8fbba690b8..9360667f8b 100644 --- a/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts +++ b/packages/server/src/server/agent/providers/pi/tool-call-mapper.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import type { ToolCallDetail } from "../../agent-sdk-types.js"; import type { ProviderImageOutput } from "../provider-image-output.js"; +import { omitNullArgs } from "../tool-call-args.js"; interface BashToolInput { command: string; @@ -331,7 +332,7 @@ export function parseToolArgs(toolName: string, rawArgs: unknown): PiTrackedTool } const schema = SIMPLE_TOOL_SCHEMAS[toolName as SimpleToolKind]; if (schema) { - const parsed = schema.safeParse(rawArgs); + const parsed = schema.safeParse(omitNullArgs(rawArgs)); if (parsed.success) { return { kind: toolName as SimpleToolKind, toolName, args: parsed.data } as PiTrackedToolCall; } diff --git a/packages/server/src/server/agent/providers/tool-call-args.test.ts b/packages/server/src/server/agent/providers/tool-call-args.test.ts new file mode 100644 index 0000000000..87b38a0329 --- /dev/null +++ b/packages/server/src/server/agent/providers/tool-call-args.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from "vitest"; + +import { parseToolArgs as parseOmpToolArgs } from "./omp/tool-call-detail.js"; +import { parseToolArgs as parsePiToolArgs } from "./pi/tool-call-mapper.js"; + +// Models send `null` for optional arguments (captured in #7011: read offset/limit), which the +// runtimes treat as omitted. Rejecting them turned every such call into an unknown card. +describe.each([ + ["Pi", parsePiToolArgs], + ["OMP", parseOmpToolArgs], +])("%s tool args with null optional values", (_provider, parseToolArgs) => { + test.each([ + ["read", { path: "./preview.png", offset: null, limit: null }, { path: "./preview.png" }], + ["bash", { command: "ls", timeout: null }, { command: "ls" }], + ])("parses %s as its own tool kind", (toolName, rawArgs, args) => { + expect(parseToolArgs(toolName, rawArgs)).toEqual({ kind: toolName, toolName, args }); + }); +}); diff --git a/packages/server/src/server/agent/providers/tool-call-args.ts b/packages/server/src/server/agent/providers/tool-call-args.ts new file mode 100644 index 0000000000..baf9d2d3bb --- /dev/null +++ b/packages/server/src/server/agent/providers/tool-call-args.ts @@ -0,0 +1,9 @@ +// Models routinely send `null` for optional tool arguments (e.g. read offset/limit); the +// runtimes treat that as omitted, so the mappers must too or the call degrades to an +// unknown card that carries the raw result. +export function omitNullArgs(rawArgs: unknown): unknown { + if (!rawArgs || typeof rawArgs !== "object" || Array.isArray(rawArgs)) { + return rawArgs; + } + return Object.fromEntries(Object.entries(rawArgs).filter(([, value]) => value !== null)); +} From 8dc979ec2f350118b2332414be2570bb8381f289 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 14:12:01 +0700 Subject: [PATCH 025/160] Shift+Tab in the iPad composer no longer inserts a tab (#9561) * Shift+Tab in the iPad composer no longer inserts a tab On iPad with a hardware keyboard, Shift+Tab in the composer cycled the agent mode and the composer also inserted a tab. The native window reports presses to JavaScript after the text control has handled them, so the shortcut pipeline cannot prevent the default. The hardware keyboard source now claims, up front, the Shift and Option shortcuts whose binding is active in the current focus scope, and recomputes the claims when the focus surface or command center changes. iOS registers them as key commands so the text control never sees them. The window still emits the press, so the shortcut runs once. Closes #9468 * Claim every step of a rebound chord shortcut A binding rebound to a chord such as Mod+J Shift+Tab only claimed its first step, so finishing the chord in the iPad composer still typed a tab. * Claim only the first step of a chord shortcut Claiming every step of a chord held keys like Shift+A for as long as the chord's binding was active, so the composer could no longer type a capital A. A later step is a shortcut only while its chord is in progress. * Expect no Option claims now that iPad tab switching uses Cmd+Shift Main moved tab switching on Apple platforms with desktop bindings to Cmd+Shift+[ / ], which text controls do not type, so the default claims are only Shift+Tab while the composer is focused. --- docs/keyboard-shortcuts.md | 13 +- .../ios/PaseoHardwareKeyboardModule.swift | 63 ++++++++- .../src/keyboard/internal/focus-surfaces.ts | 18 ++- .../src/keyboard/internal/sources/contract.ts | 2 + .../internal/sources/electron-browser.test.ts | 8 +- .../internal/sources/hardware.android.ts | 5 +- .../keyboard/internal/sources/hardware.ios.ts | 6 +- .../src/keyboard/internal/sources/hardware.ts | 7 + .../src/keyboard/internal/sources/index.ts | 24 ++-- .../keyboard/internal/sources/index.web.ts | 3 +- .../src/keyboard/internal/sources/native.ts | 105 +++++++++++---- .../keyboard/native-shortcuts.browser.test.ts | 1 + .../app/src/keyboard/native-shortcuts.test.ts | 123 +++++++++++++++--- packages/app/src/keyboard/use-shortcuts.ts | 6 +- .../app/src/lib/overlay-root.browser.test.tsx | 1 + 15 files changed, 325 insertions(+), 60 deletions(-) diff --git a/docs/keyboard-shortcuts.md b/docs/keyboard-shortcuts.md index dd93f03b4a..21d0152d4b 100644 --- a/docs/keyboard-shortcuts.md +++ b/docs/keyboard-shortcuts.md @@ -20,9 +20,16 @@ settings the native composer does not implement. ## Native sources -Use the iOS window press stream for hardware keys. `UIKeyCommand` only takes keys -that must bypass the focused text control: composer Return and the top overlay's -Enter and arrows. Keep the stream as the sole shortcut emitter: a command-owned +Use the iOS window press stream for hardware keys. The stream reaches JavaScript +after the focused text control has already handled the press, so the pipeline's +`preventDefault` cannot stop a key from typing. A key the text control would type +must be claimed up front. `UIKeyCommand` takes only those keys: composer Return, the +top overlay's Enter and arrows, and the Shift or Option shortcuts whose binding is +active in the current focus scope, such as Shift+Tab in the composer. +`sources/native.ts` computes the claims from the published bindings and recomputes +them when the focus scope changes. Cmd and Ctrl combos are never claimed, because +text controls do not type them. Android takes no claims: a focused `EditText` +types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned press is still observed by the window. The source spike used an iPad Pro 11-inch (M4) simulator on iOS 18.6 with a diff --git a/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift b/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift index 446e1d98c4..b6d463742e 100644 --- a/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift +++ b/packages/app/modules/paseo-hardware-keyboard/ios/PaseoHardwareKeyboardModule.swift @@ -8,6 +8,7 @@ private let hardwareShortcutEventName = "onHardwareKeyboardShortcut" private weak var activeModule: PaseoHardwareKeyboardModule? private var isHardwareSubmitEnabled = false private var overlayKeys: Set = [] +private var claimedShortcuts: [ClaimedShortcut] = [] /// UIKit spells non-character keys as sentinel input strings rather than as the /// character they would type. JS sends the DOM `code` and the mapping lives @@ -19,6 +20,42 @@ private let namedKeyInputs: [String: String] = [ "Enter": "\r", ] +/// A shortcut the window takes from the focused text control: Shift+Tab would +/// otherwise insert a tab, and Option+Shift+[ would type a quote. +private struct ClaimedShortcut { + let input: String + let modifierFlags: UIKeyModifierFlags +} + +struct ClaimedShortcutRecord: Record { + @Field var code: String = "" + @Field var shift: Bool = false + @Field var alt: Bool = false +} + +private let claimableKeyInputs: [String: String] = [ + "Tab": "\t", "Space": " ", "Enter": "\r", "Escape": UIKeyCommand.inputEscape, + "ArrowUp": UIKeyCommand.inputUpArrow, "ArrowDown": UIKeyCommand.inputDownArrow, + "ArrowLeft": UIKeyCommand.inputLeftArrow, "ArrowRight": UIKeyCommand.inputRightArrow, + "Minus": "-", "Equal": "=", "BracketLeft": "[", "BracketRight": "]", "Backslash": "\\", + "Semicolon": ";", "Quote": "'", "Backquote": "`", "Comma": ",", "Period": ".", "Slash": "/", +] + +/// UIKit matches a key command against the unmodified character, so +/// Option+Shift+[ is registered as "[" with both modifier flags. +private func claimedShortcut(_ record: ClaimedShortcutRecord) -> ClaimedShortcut? { + let code = record.code + let input: String? + if code.count == 4 && code.hasPrefix("Key") { input = code.suffix(1).lowercased() } + else if code.count == 6 && code.hasPrefix("Digit") { input = String(code.suffix(1)) } + else { input = claimableKeyInputs[code] } + guard let input else { return nil } + var modifierFlags: UIKeyModifierFlags = [] + if record.shift { modifierFlags.insert(.shift) } + if record.alt { modifierFlags.insert(.alternate) } + return ClaimedShortcut(input: input, modifierFlags: modifierFlags) +} + /// Whether the first responder is mid-IME-composition. /// /// A committing key has to stay out of the way while a CJK candidate is being @@ -62,6 +99,14 @@ public class PaseoHardwareKeyboardModule: Module { } } + Function("setClaimedShortcuts") { (shortcuts: [ClaimedShortcutRecord]) in + let claimed = shortcuts.compactMap(claimedShortcut) + DispatchQueue.main.async { + claimedShortcuts = claimed + UIMenuSystem.main.setNeedsRebuild() + } + } + OnDestroy { self.keyboardObservers.forEach(NotificationCenter.default.removeObserver) self.keyboardObservers = [] @@ -69,6 +114,7 @@ public class PaseoHardwareKeyboardModule: Module { activeModule = nil isHardwareSubmitEnabled = false overlayKeys = [] + claimedShortcuts = [] } } } @@ -139,7 +185,10 @@ public final class PaseoHardwareKeyboardWindow: UIWindow { { commands.append(makeSubmitCommand()) } - if !isComposingText() { commands.append(contentsOf: overlayKeys.compactMap(makeShortcutCommand)) } + if !isComposingText() { + commands.append(contentsOf: overlayKeys.compactMap(makeShortcutCommand)) + commands.append(contentsOf: claimedShortcuts.map(makeClaimedCommand)) + } return commands } @@ -172,6 +221,18 @@ public final class PaseoHardwareKeyboardWindow: UIWindow { return command } + /// The window's press stream still emits the shortcut; the command only keeps + /// the key away from the text control. + private func makeClaimedCommand(_ shortcut: ClaimedShortcut) -> UIKeyCommand { + let command = UIKeyCommand( + input: shortcut.input, + modifierFlags: shortcut.modifierFlags, + action: #selector(handleHardwareKeyboardShortcut(_:)) + ) + if #available(iOS 15.0, *) { command.wantsPriorityOverSystemBehavior = true } + return command + } + @objc private func handleHardwareKeyboardSubmit(_ sender: UIKeyCommand) { guard canSubmitCurrentTextInput() else { diff --git a/packages/app/src/keyboard/internal/focus-surfaces.ts b/packages/app/src/keyboard/internal/focus-surfaces.ts index 5bdeb6fa0d..e13526176e 100644 --- a/packages/app/src/keyboard/internal/focus-surfaces.ts +++ b/packages/app/src/keyboard/internal/focus-surfaces.ts @@ -4,20 +4,32 @@ export type KeyboardFocusSurface = "message-input" | "terminal"; export function createKeyboardFocusScope(hasEditableFocus: () => boolean = () => false) { const surfaces = new Map(); + const listeners = new Set<() => void>(); + const notify = () => { + for (const listener of listeners) listener(); + }; return { declare(surface: KeyboardFocusSurface) { const token = Symbol(surface); surfaces.set(token, surface); + notify(); return () => { - surfaces.delete(token); + if (surfaces.delete(token)) notify(); }; }, - resolve(commandCenterOpen: boolean): KeyboardFocusScope { + /** Pass `editableFocused` to resolve for a text control that is not a declared surface. */ + resolve(commandCenterOpen: boolean, editableFocused = hasEditableFocus()): KeyboardFocusScope { if (commandCenterOpen) return "command-center"; - let focused: KeyboardFocusScope = hasEditableFocus() ? "editable" : "other"; + let focused: KeyboardFocusScope = editableFocused ? "editable" : "other"; for (const surface of surfaces.values()) focused = surface; return focused; }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, }; } export const focusSurfaces = createKeyboardFocusScope(hasFocusedTextInput); diff --git a/packages/app/src/keyboard/internal/sources/contract.ts b/packages/app/src/keyboard/internal/sources/contract.ts index 886dbc3548..69de22f09e 100644 --- a/packages/app/src/keyboard/internal/sources/contract.ts +++ b/packages/app/src/keyboard/internal/sources/contract.ts @@ -10,6 +10,7 @@ export interface KeyboardSourceHandlers { keyUp(event: KeyboardInputEvent): void; blur(): void; commandCenterOpen(): boolean; + subscribeCommandCenter(listener: () => void): () => void; } export function nativeKeyboardInput( event: KeyboardInputEvent, @@ -23,5 +24,6 @@ export interface KeyboardPolicyInput { bindings: readonly ParsedShortcutBinding[]; chordState?: ChordState; isMac: boolean; + usesDesktopBindings: boolean; enabled: boolean; } diff --git a/packages/app/src/keyboard/internal/sources/electron-browser.test.ts b/packages/app/src/keyboard/internal/sources/electron-browser.test.ts index abcc98b7fd..8ac3ac9949 100644 --- a/packages/app/src/keyboard/internal/sources/electron-browser.test.ts +++ b/packages/app/src/keyboard/internal/sources/electron-browser.test.ts @@ -366,7 +366,13 @@ describe("Electron guest source through shared resolution", () => { }, captureFocusRestore: (id) => restored.push(id), }, - { keyDown: pipeline.keyDown, keyUp() {}, blur() {}, commandCenterOpen: () => false }, + { + keyDown: pipeline.keyDown, + keyUp() {}, + blur() {}, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }, ); receive({ browserId: "tab-1", diff --git a/packages/app/src/keyboard/internal/sources/hardware.android.ts b/packages/app/src/keyboard/internal/sources/hardware.android.ts index cfe7a15cb9..b0e0d41155 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.android.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.android.ts @@ -1,5 +1,5 @@ import { requireNativeModule } from "expo-modules-core"; -import type { HardwareKeyboardEvent } from "./hardware"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeyboardModule { getHardwareKeyboardPresent(): boolean; addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void }; @@ -19,6 +19,9 @@ export function subscribeHardwareKeyboard( export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void { module.setOverlayKeys(keys); } +// A focused Android EditText types nothing for Tab, Shift+Tab or Alt+Shift+[, +// so there is no character to take from it. +export function setHardwareKeyboardClaimedShortcuts(_shortcuts: readonly ClaimedShortcut[]): void {} export function getHardwareKeyboardPresent(): boolean { return module.getHardwareKeyboardPresent(); diff --git a/packages/app/src/keyboard/internal/sources/hardware.ios.ts b/packages/app/src/keyboard/internal/sources/hardware.ios.ts index cfe7a15cb9..2745b51ba9 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.ios.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.ios.ts @@ -1,9 +1,10 @@ import { requireNativeModule } from "expo-modules-core"; -import type { HardwareKeyboardEvent } from "./hardware"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeyboardModule { getHardwareKeyboardPresent(): boolean; addListener(event: "onHardwareKeyboardPresenceChanged", handler: () => void): { remove(): void }; setOverlayKeys(keys: readonly string[]): void; + setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; addListener( event: "onHardwareKeyboardShortcut", handler: (event: HardwareKeyboardEvent) => void, @@ -19,6 +20,9 @@ export function subscribeHardwareKeyboard( export function setHardwareKeyboardOverlayKeys(keys: readonly string[]): void { module.setOverlayKeys(keys); } +export function setHardwareKeyboardClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void { + module.setClaimedShortcuts(shortcuts); +} export function getHardwareKeyboardPresent(): boolean { return module.getHardwareKeyboardPresent(); diff --git a/packages/app/src/keyboard/internal/sources/hardware.ts b/packages/app/src/keyboard/internal/sources/hardware.ts index c6631886d1..33afb7eabb 100644 --- a/packages/app/src/keyboard/internal/sources/hardware.ts +++ b/packages/app/src/keyboard/internal/sources/hardware.ts @@ -3,12 +3,19 @@ export interface HardwareKeyboardEvent extends KeyboardShortcutInput { isComposing: boolean; phase: "down" | "up"; } +/** A shortcut the native window takes from the focused text control, by DOM `code`. */ +export interface ClaimedShortcut { + code: string; + shift: boolean; + alt: boolean; +} export function subscribeHardwareKeyboard( _handler: (event: HardwareKeyboardEvent) => void, ): () => void { return () => {}; } export function setHardwareKeyboardOverlayKeys(_keys: readonly string[]): void {} +export function setHardwareKeyboardClaimedShortcuts(_shortcuts: readonly ClaimedShortcut[]): void {} export function getHardwareKeyboardPresent(): boolean { return false; diff --git a/packages/app/src/keyboard/internal/sources/index.ts b/packages/app/src/keyboard/internal/sources/index.ts index 5d886b979a..570251a083 100644 --- a/packages/app/src/keyboard/internal/sources/index.ts +++ b/packages/app/src/keyboard/internal/sources/index.ts @@ -1,11 +1,19 @@ -import type { KeyboardSourceHandlers } from "./contract"; -import { setHardwareKeyboardOverlayKeys, subscribeHardwareKeyboard } from "./hardware"; -import { attachHardwareKeyboardSource } from "./native"; +import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract"; +import { + setHardwareKeyboardClaimedShortcuts, + setHardwareKeyboardOverlayKeys, + subscribeHardwareKeyboard, +} from "./hardware"; +import { createHardwareKeyboardSource } from "./native"; +const hardwareKeyboard = createHardwareKeyboardSource({ + subscribe: subscribeHardwareKeyboard, + setOverlayKeys: setHardwareKeyboardOverlayKeys, + setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts, +}); export function attachKeyboardSources(handlers: KeyboardSourceHandlers): () => void { - return attachHardwareKeyboardSource( - { subscribe: subscribeHardwareKeyboard, setOverlayKeys: setHardwareKeyboardOverlayKeys }, - handlers, - ); + return hardwareKeyboard.attach(handlers); } -export function publishKeyboardPolicy(_input: import("./contract").KeyboardPolicyInput): void {} +export function publishKeyboardPolicy(input: KeyboardPolicyInput): void { + hardwareKeyboard.publishPolicy(input); +} diff --git a/packages/app/src/keyboard/internal/sources/index.web.ts b/packages/app/src/keyboard/internal/sources/index.web.ts index da6023be5b..e915c38180 100644 --- a/packages/app/src/keyboard/internal/sources/index.web.ts +++ b/packages/app/src/keyboard/internal/sources/index.web.ts @@ -1,4 +1,3 @@ -import { usesDesktopBindings } from "../conventions"; import { getDesktopHost } from "@/desktop/host"; import { getResidentBrowserWebview } from "@/desktop/browser/resident-webviews"; import { setCommandCenterFocusRestoreElement } from "@/utils/command-center-focus-restore"; @@ -26,7 +25,7 @@ export function attachKeyboardSources(handlers: KeyboardSourceHandlers): () => v } export function publishKeyboardPolicy(input: import("./contract").KeyboardPolicyInput): void { const policy = input.enabled - ? buildBrowserKeyboardPolicy({ ...input, usesDesktopBindings: usesDesktopBindings }) + ? buildBrowserKeyboardPolicy(input) : { menuPrefixes: [], prefixes: [] }; void getDesktopHost()?.browser?.setShortcutPolicy?.(policy); } diff --git a/packages/app/src/keyboard/internal/sources/native.ts b/packages/app/src/keyboard/internal/sources/native.ts index 995e9df491..9d76abe0a6 100644 --- a/packages/app/src/keyboard/internal/sources/native.ts +++ b/packages/app/src/keyboard/internal/sources/native.ts @@ -1,31 +1,92 @@ +import { matchesKeyboardShortcutContext } from "../../keyboard-shortcuts"; import { focusSurfaces } from "../focus-surfaces"; import { overlays } from "../overlays"; -import { nativeKeyboardInput, type KeyboardSourceHandlers } from "./contract"; -import type { HardwareKeyboardEvent } from "./hardware"; +import { + nativeKeyboardInput, + type KeyboardPolicyInput, + type KeyboardSourceHandlers, +} from "./contract"; +import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware"; interface HardwareKeySource { subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void; setOverlayKeys(keys: readonly string[]): void; + setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void; } -export function attachHardwareKeyboardSource( - source: HardwareKeySource, - handlers: KeyboardSourceHandlers, -): () => void { - const updateKeys = () => source.setOverlayKeys(overlays.getKeys()); - updateKeys(); - const unsubscribeOverlays = overlays.subscribe(updateKeys); - const unsubscribeHardware = source.subscribe((input) => { - const event = { ...input, preventDefault() {}, stopPropagation() {} }; - if (input.phase === "up") { - handlers.keyUp(event); - return; + +const DIGIT_CODES = Array.from({ length: 9 }, (_, index) => `Digit${index + 1}`); + +/** + * The shortcuts a focused text control would otherwise type or act on. + * + * The native window observes every press but cannot wait for the pipeline to + * decide, so it has to claim these keys up front: without a claim, Shift+Tab + * cycles the agent mode and the composer also inserts a tab. Cmd and Ctrl + * combos do not type, and the platform's own editing combos stay with the text + * control through `editable: false`. Unmodified keys belong to overlays and the + * composer's Return. + */ +function claimedShortcuts( + policy: KeyboardPolicyInput | null, + commandCenterOpen: boolean, +): ClaimedShortcut[] { + if (!policy?.enabled) return []; + const context = { + isMac: policy.isMac, + usesDesktopBindings: policy.usesDesktopBindings, + commandCenterOpen, + focusScope: focusSurfaces.resolve(commandCenterOpen, true), + }; + const claimed = new Map(); + for (const binding of policy.bindings) { + const combo = binding.parsedChord[0]; + if (!combo || binding.preventDefault === false) continue; + if (combo.meta || combo.ctrl || combo.mod || !(combo.shift || combo.alt)) continue; + if (!matchesKeyboardShortcutContext(binding.when, context)) continue; + const shift = combo.shift === true; + const alt = combo.alt === true; + for (const code of combo.code === "Digit" ? DIGIT_CODES : [combo.code]) { + claimed.set(`${code}:${shift}:${alt}`, { code, shift, alt }); } - handlers.keyDown( - nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), - ); - }); - return () => { - unsubscribeHardware(); - unsubscribeOverlays(); - source.setOverlayKeys([]); + } + return [...claimed.values()]; +} + +export function createHardwareKeyboardSource(source: HardwareKeySource) { + let policy: KeyboardPolicyInput | null = null; + let updateClaims = () => {}; + return { + publishPolicy(next: KeyboardPolicyInput) { + policy = next; + updateClaims(); + }, + attach(handlers: KeyboardSourceHandlers): () => void { + const updateKeys = () => source.setOverlayKeys(overlays.getKeys()); + updateClaims = () => + source.setClaimedShortcuts(claimedShortcuts(policy, handlers.commandCenterOpen())); + updateKeys(); + updateClaims(); + const unsubscribeOverlays = overlays.subscribe(updateKeys); + const unsubscribeFocus = focusSurfaces.subscribe(() => updateClaims()); + const unsubscribeCommandCenter = handlers.subscribeCommandCenter(() => updateClaims()); + const unsubscribeHardware = source.subscribe((input) => { + const event = { ...input, preventDefault() {}, stopPropagation() {} }; + if (input.phase === "up") { + handlers.keyUp(event); + return; + } + handlers.keyDown( + nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())), + ); + }); + return () => { + unsubscribeHardware(); + unsubscribeFocus(); + unsubscribeCommandCenter(); + unsubscribeOverlays(); + updateClaims = () => {}; + source.setOverlayKeys([]); + source.setClaimedShortcuts([]); + }; + }, }; } diff --git a/packages/app/src/keyboard/native-shortcuts.browser.test.ts b/packages/app/src/keyboard/native-shortcuts.browser.test.ts index 004eb912b2..22bd6e16ad 100644 --- a/packages/app/src/keyboard/native-shortcuts.browser.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.browser.test.ts @@ -25,6 +25,7 @@ describe("DOM source adapter", () => { keyUp() {}, blur() {}, commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, }); const event = new KeyboardEvent("keydown", { key: "j", diff --git a/packages/app/src/keyboard/native-shortcuts.test.ts b/packages/app/src/keyboard/native-shortcuts.test.ts index e155fa2ba1..d4c4edc24f 100644 --- a/packages/app/src/keyboard/native-shortcuts.test.ts +++ b/packages/app/src/keyboard/native-shortcuts.test.ts @@ -130,7 +130,7 @@ describe("hardware source adapter", () => { it.each([true, false])( "delivers hardware down/up and declared focus with mac=%s", async (isMac) => { - const { attachHardwareKeyboardSource } = await import("./internal/sources/native"); + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); const { focusSurfaces } = await import("./internal/focus-surfaces"); const actions: string[] = []; const releases: string[] = []; @@ -148,23 +148,22 @@ describe("hardware source adapter", () => { }, overlays: createOverlayRegistry(), }); - const detach = attachHardwareKeyboardSource( - { - subscribe(handler) { - events.add(handler); - return () => { - events.delete(handler); - }; - }, - setOverlayKeys() {}, + const detach = createHardwareKeyboardSource({ + subscribe(handler) { + events.add(handler); + return () => { + events.delete(handler); + }; }, - { - keyDown: pipeline.keyDown, - keyUp: (event) => releases.push(event.key), - blur() {}, - commandCenterOpen: () => false, - }, - ); + setOverlayKeys() {}, + setClaimedShortcuts() {}, + }).attach({ + keyDown: pipeline.keyDown, + keyUp: (event) => releases.push(event.key), + blur() {}, + commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, + }); const down = { ...keyboardEvent("k", "KeyK", isMac), isComposing: false, @@ -180,4 +179,94 @@ describe("hardware source adapter", () => { expect(events.size).toBe(0); }, ); + + it("claims the Shift and Option shortcuts a focused text control would otherwise type", async () => { + const { createHardwareKeyboardSource } = await import("./internal/sources/native"); + const { focusSurfaces } = await import("./internal/focus-surfaces"); + let claimed: string[] = []; + const source = createHardwareKeyboardSource({ + subscribe: () => () => {}, + setOverlayKeys() {}, + setClaimedShortcuts(shortcuts) { + claimed = shortcuts + .map(({ code, shift, alt }) => [alt && "Alt", shift && "Shift", code]) + .map((parts) => parts.filter(Boolean).join("+")) + .sort(); + }, + }); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + let commandCenterOpen = false; + const commandCenterListeners = new Set<() => void>(); + const detach = source.attach({ + keyDown() {}, + keyUp() {}, + blur() {}, + commandCenterOpen: () => commandCenterOpen, + subscribeCommandCenter(listener) { + commandCenterListeners.add(listener); + return () => commandCenterListeners.delete(listener); + }, + }); + const setCommandCenterOpen = (open: boolean) => { + commandCenterOpen = open; + for (const listener of commandCenterListeners) listener(); + }; + // iPad tab switching uses Cmd+Shift+[ / ], which no text control types. + expect(claimed).toEqual([]); + + const releaseComposer = focusSurfaces.declare("message-input"); + expect(claimed).toEqual(["Shift+Tab"]); + setCommandCenterOpen(true); + expect(claimed).toEqual([]); + setCommandCenterOpen(false); + expect(claimed).toEqual(["Shift+Tab"]); + releaseComposer(); + expect(claimed).toEqual([]); + + source.publishPolicy({ + bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Alt+M" }), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + const releaseRebound = focusSurfaces.declare("message-input"); + expect(claimed).toEqual(["Alt+KeyM"]); + releaseRebound(); + + // A chord's later step is only a shortcut while the chord is in progress; + // claiming it always would stop the composer typing a capital A. + source.publishPolicy({ + bindings: buildEffectiveBindings({ "message-input-mode-cycle-shift-tab": "Mod+J Shift+A" }), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + const releaseChord = focusSurfaces.declare("message-input"); + expect(claimed).toEqual([]); + releaseChord(); + + const releaseFinal = focusSurfaces.declare("message-input"); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: false, + }); + expect(claimed).toEqual([]); + source.publishPolicy({ + bindings: buildEffectiveBindings({}), + isMac: true, + usesDesktopBindings: true, + enabled: true, + }); + expect(claimed).toEqual(["Shift+Tab"]); + detach(); + expect(claimed).toEqual([]); + releaseFinal(); + }); }); diff --git a/packages/app/src/keyboard/use-shortcuts.ts b/packages/app/src/keyboard/use-shortcuts.ts index b762d8dfcf..73e06f2ea1 100644 --- a/packages/app/src/keyboard/use-shortcuts.ts +++ b/packages/app/src/keyboard/use-shortcuts.ts @@ -62,7 +62,7 @@ export function useKeyboardShortcuts({ const keyboardWorkspaceSelectionRef = useRef(null); const publishBrowserShortcutPolicy = useCallback( (chordState?: ChordState) => { - publishKeyboardPolicy({ bindings, chordState, isMac, enabled }); + publishKeyboardPolicy({ bindings, chordState, isMac, usesDesktopBindings, enabled }); }, [bindings, enabled, isMac], ); @@ -265,6 +265,10 @@ export function useKeyboardShortcuts({ keyUp: handleKeyUp, blur: resetModifiers, commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen, + subscribeCommandCenter: (listener) => + useKeyboardShortcutsStore.subscribe((state, previous) => { + if (state.commandCenterOpen !== previous.commandCenterOpen) listener(); + }), }); return () => { detach(); diff --git a/packages/app/src/lib/overlay-root.browser.test.tsx b/packages/app/src/lib/overlay-root.browser.test.tsx index 7f0d5115ac..299c036fc9 100644 --- a/packages/app/src/lib/overlay-root.browser.test.tsx +++ b/packages/app/src/lib/overlay-root.browser.test.tsx @@ -134,6 +134,7 @@ describe("DOM source through the shared resolver", () => { keyUp() {}, blur() {}, commandCenterOpen: () => false, + subscribeCommandCenter: () => () => {}, }); const event = new KeyboardEvent("keydown", { key: "j", From af6ca46ae3e7d209b2aca0c23bf9ba1fc1a8eb28 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 15:22:53 +0700 Subject: [PATCH 026/160] fix(plugin)!: drop the always-empty timeline from agent.turn.after (#9573) agent.turn.after no longer declares timeline; plugins read the turn with timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }) filtered by event.turnId. Plugins built against the old SDK keep receiving timeline: [] behind COMPAT(pluginTurnTimeline). Closes #9315 Co-authored-by: Jacek Tomaszewski --- packages/client/src/index.ts | 5 +++++ packages/plugin/src/boundaries.test.ts | 12 +++++++++++- packages/plugin/src/server/lifecycle.ts | 10 +++++----- .../src/server/agent/agent-manager.test.ts | 1 - .../src/server/plugins/lifecycle.e2e.test.ts | 11 +++++++++-- .../server/plugins/lifecycle.real.e2e.test.ts | 16 ++++++++++++---- .../server/src/server/plugins/lifecycle/index.ts | 3 --- packages/server/src/server/plugins/runtime.ts | 10 +++++++++- .../lifecycle-actions/index.server.ts | 5 +++-- public-docs/plugins/hooks.md | 12 +++++------- public-docs/plugins/hooks.zh-CN.md | 11 +++++------ public-docs/plugins/migration.md | 16 ++++++++++++++++ public-docs/plugins/migration.zh-CN.md | 15 +++++++++++++++ public-docs/sdk/reference.md | 2 +- public-docs/sdk/reference.zh-CN.md | 2 +- 15 files changed, 97 insertions(+), 34 deletions(-) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 7f1c5fd14f..1a056de459 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -306,6 +306,11 @@ export interface PaseoAgentTimelineRefetchOptions { cursor?: FetchAgentTimelineCursor; limit?: number; projection?: FetchAgentTimelineProjection; + /** + * Extends a `tail` or `before` page back to the start of the oldest turn it touches, so + * `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. + */ + wholeTurns?: boolean; requestId?: string; } diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 7b78940ba4..8b8cae6630 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -393,6 +393,7 @@ describe("lifecycle hook SDK types", () => { expect( typeErrors(` import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server"; + import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; export default function contribute(server: PluginServerContext) { server.addHook("worktree.create.before", async ({ request }) => { if (request.kind === "checkout-branch") { @@ -426,8 +427,17 @@ describe("lifecycle hook SDK types", () => { const { metadata, ...withoutMetadata } = request; return withoutMetadata; }); - server.addHook("agent.turn.after", async ({ agent, outcome, timeline }, { paseo, signal }) => { + server.addHook("agent.turn.after", async (event, { paseo, signal }) => { + const { agent, outcome } = event; const kind: "completed" | "failed" | "canceled" = outcome.kind; + // @ts-expect-error Turn payloads carry no history; read it from the agent's timeline. + event.timeline; + const turn = await paseo.agents + .ref(agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const items: readonly AgentTimelineItem[] = turn.entries + .filter((entry) => entry.turnId === event.turnId) + .map(({ item }) => item); // @ts-expect-error Notification payloads have no creation request. outcome.request; }); diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index a048d93706..f1ee1a9790 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -2,7 +2,6 @@ import type { AgentToolDefinition } from "./agent-tools.js"; import type { AgentPermissionRequest, AgentPermissionResponse, - AgentTimelineItem, AgentSessionConfig, JsonValue, } from "@getpaseo/protocol/agent-types"; @@ -104,12 +103,13 @@ export interface PluginHookEvents { "agent.turn.after": { agent: PluginHookAgent; turnId: string | null; - outcome: PluginTurnOutcome; /** - * @deprecated Always empty. Fetch history on demand with - * context.paseo.agents.ref(agent.id).timeline.refetch({ direction: "tail", limit: 20 }). + * The payload carries no history. Read the turn with + * `paseo.agents.ref(agent.id).timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })` + * and keep the entries whose `turnId` equals this `turnId`. The result is empty when a newer turn + * started before the read, or when `turnId` is `null`. */ - timeline: readonly AgentTimelineItem[]; + outcome: PluginTurnOutcome; }; "agent.permission.before": { agent: PluginHookAgent; request: AgentPermissionRequest }; "agent.permission.after": { diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 0590bae58c..700ee87c45 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -13334,7 +13334,6 @@ test.each([ }, turnId: "hook-turn", outcome, - timeline: [], }, }, ]); diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index 92fb21443e..d08089ad3d 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -163,8 +163,14 @@ export default function contribute(server) { server.addHook("agent.turn.before", async (event) => { console.log(JSON.stringify({ hook: "agent.turn.before", event })); }); - server.addHook("agent.turn.after", async (event) => { - console.log(JSON.stringify({ hook: "agent.turn.after", event })); + server.addHook("agent.turn.after", async (event, context) => { + const page = await context.paseo.agents + .ref(event.agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries + .filter((entry) => entry.turnId === event.turnId) + .map(({ item }) => item.type); + console.log(JSON.stringify({ hook: "agent.turn.after", event, turn })); }); server.addHook("agent.permission.before", async (event, context) => { console.log(JSON.stringify({ hook: "agent.permission.before", event })); @@ -220,6 +226,7 @@ export default function contribute(server) { { hook: "agent.turn.after", event: { outcome: { kind: "completed" }, timeline: [] }, + turn: ["user_message", "tool_call"], }, { hook: "agent.turn.before", event: { agent: { id: agent.id } } }, ]); diff --git a/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts index 40de1215d8..5223e547ec 100644 --- a/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.real.e2e.test.ts @@ -157,8 +157,7 @@ test.skipIf(process.platform !== "linux")( "This is a hook integration test. Reply exactly: out of credits. If the next user message is Try again., reply exactly RETRY_OK instead. Do not use tools.", ); await waitForTurns(client, agent.id, 2); - const retryTurns = await endedTurns(client, agent.id); - expect(assistantText(retryTurns[1].data.timeline)).toBe("RETRY_OK"); + expect(await latestReplyText(client, agent.id)).toBe("RETRY_OK"); proof.followup = "RETRY_OK"; await client.sendMessage( @@ -207,8 +206,7 @@ test.skipIf(process.platform !== "linux")( const envPermission = await waitForPermission(client, agent.id, envCommand); await client.respondToPermission(agent.id, envPermission, { behavior: "allow" }); await waitForTurns(client, agent.id, 5); - const envTurns = await endedTurns(client, agent.id); - expect(assistantText(envTurns[4].data.timeline)).toBe("created|opened"); + expect(await latestReplyText(client, agent.id)).toBe("created|opened"); proof.environmentOutput = "created|opened"; await client.refreshAgent(agent.id); @@ -332,6 +330,16 @@ test.skipIf(process.platform !== "linux")( 600_000, ); +// Turn hooks carry no history; read the reply the way plugins do. +async function latestReplyText(client: DaemonClient, agentId: string): Promise { + const page = await client.fetchAgentTimeline(agentId, { + direction: "tail", + limit: 1, + wholeTurns: true, + }); + return assistantText(page.entries.map((entry) => entry.item)); +} + function assistantText(timeline: readonly AgentTimelineItem[]): string { let text = ""; for (const item of timeline) { diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 5e552c0111..b291bf3723 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -195,21 +195,18 @@ export function publishAgentStream( lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, - timeline: [], outcome: { kind: "completed" }, }); } else if (event.type === "turn_failed") { lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, - timeline: [], outcome: { kind: "failed", error: { message: event.error, code: event.code } }, }); } else if (event.type === "turn_canceled") { lifecycle.emit("agent.turn.after", { agent, turnId: event.turnId ?? null, - timeline: [], outcome: { kind: "canceled", reason: event.reason }, }); } else if (event.type === "permission_requested") { diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index f8fe8a91b5..fad1b78bd0 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -564,7 +564,7 @@ export class PluginRuntime { type: "hook", requestId: randomUUID(), name, - input: event, + input: wireEvent(name, event), }) .then(() => undefined) .catch((error) => { @@ -1482,3 +1482,11 @@ function readConnectionId(value: unknown): string | null { const connectionId = Reflect.get(value, "connectionId"); return typeof connectionId === "string" ? connectionId : null; } + +// COMPAT(pluginTurnTimeline): added in v0.16.0-beta.3; plugins built before the field left the SDK type read `timeline`; remove after 2027-05-31 +function wireEvent( + name: Name, + event: PluginHookEvents[Name], +): PluginHookEvents[Name] { + return name === "agent.turn.after" ? { ...event, timeline: [] } : event; +} diff --git a/plugin-examples/lifecycle-actions/index.server.ts b/plugin-examples/lifecycle-actions/index.server.ts index 906cd2d565..a89c7aa82f 100644 --- a/plugin-examples/lifecycle-actions/index.server.ts +++ b/plugin-examples/lifecycle-actions/index.server.ts @@ -23,8 +23,9 @@ export default function contribute(server: PluginServerContext) { return; } const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); + const page = await agent.timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries.filter((entry) => entry.turnId === event.turnId); + const text = latestOutputText(turn.map(({ item }) => item)); if (/out of credits/i.test(text)) { console.log("Sending a follow-up after out of credits", event.agent.id); await agent.send("Try again."); diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index c93da33e04..29be2ce0de 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -62,7 +62,7 @@ Paseo only sees the returned promise, so detached work gets no error reporting a | `agent.close.after` | no | `{ agent }` | | | `agent.archive.after` | no | `{ agent, archivedAt }` | | | `agent.turn.before` | no | `{ agent, turnId }` | | -| `agent.turn.after` | no | `{ agent, turnId, outcome, timeline }` | | +| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | | `agent.permission.before` | no | `{ agent, request }` | | | `agent.permission.after` | no | `{ agent, requestId, resolution }` | | @@ -525,7 +525,7 @@ server.addHook("agent.turn.before", async ({ agent, turnId }) => { ## agent.turn.after -A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome, timeline }`. `outcome.kind` is `completed`, `failed`, or `canceled`. `timeline` is deprecated and always empty; fetch history through the SDK as below. +A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome }`. `outcome.kind` is `completed`, `failed`, or `canceled`. The payload carries no history. Read the turn from the agent's timeline: `refetch({ direction: "tail", limit: 1, wholeTurns: true })` returns the latest turn whole, as below. Keep the entries whose `turnId` equals `event.turnId`, because a turn that starts before your read, such as a follow-up another plugin sent, replaces this one as the latest. The filtered list is empty in that case, and when `event.turnId` is `null`. Plugins built against an older SDK that read `event.timeline` get an empty array. ### Send a follow-up when a turn ends @@ -545,8 +545,9 @@ export default function contribute(server: PluginServerContext) { } const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); + const page = await agent.timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries.filter((entry) => entry.turnId === event.turnId); + const text = latestOutputText(turn.map(({ item }) => item)); if (/out of credits/i.test(text)) { await agent.send("Try again."); } @@ -562,9 +563,6 @@ Turn ends: "out of credits" → a new turn starts ``` -The handler fetches only the last 20 timeline items. Output before that page is not inspected. -Use `cursor` and `direction` to page further when your plugin needs more history. - This sends a new message with the existing SDK. Persistent matches keep sending follow-ups; add limits or delays in your plugin when needed. Attachments and tool effects are not replayed. diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index d78bccd6d2..af6c66bd7b 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -60,7 +60,7 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 | `agent.close.after` | 否 | `{ agent }` | | | `agent.archive.after` | 否 | `{ agent, archivedAt }` | | | `agent.turn.before` | 否 | `{ agent, turnId }` | | -| `agent.turn.after` | 否 | `{ agent, turnId, outcome, timeline }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | | `agent.permission.before` | 否 | `{ agent, request }` | | | `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | @@ -514,7 +514,7 @@ server.addHook("agent.turn.before", async ({ agent, turnId }) => { ## agent.turn.after {#agentturnafter} -实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome, timeline }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。`timeline` 已弃用且始终为空;请按下面的示例通过 SDK 获取历史。 +实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。载荷不含历史。请从 Agent 的时间线读取本轮:`refetch({ direction: "tail", limit: 1, wholeTurns: true })` 会完整返回最近一轮,见下面的示例。只保留 `turnId` 等于 `event.turnId` 的条目:如果在读取前已有新一轮开始(例如另一个插件发送的后续消息),最近一轮就不再是本轮。此时过滤后的列表为空;`event.turnId` 为 `null` 时也为空。基于旧版 SDK 构建、仍读取 `event.timeline` 的插件只会拿到空数组。 ### 在轮次结束时发送后续消息 {#send-a-follow-up-when-a-turn-ends} @@ -531,8 +531,9 @@ export default function contribute(server: PluginServerContext) { } const agent = context.paseo.agents.ref(event.agent.id); - const page = await agent.timeline.refetch({ direction: "tail", limit: 20 }); - const text = latestOutputText(page.entries.map(({ item }) => item)); + const page = await agent.timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); + const turn = page.entries.filter((entry) => entry.turnId === event.turnId); + const text = latestOutputText(turn.map(({ item }) => item)); if (/out of credits/i.test(text)) { await agent.send("Try again."); } @@ -548,8 +549,6 @@ Turn ends: "out of credits" → a new turn starts ``` -该处理函数只获取最近 20 条时间线条目,不检查这一页之前的输出。插件需要更多历史时,请用 `cursor` 和 `direction` 继续翻页。 - 这会用现有的 SDK 发送一条新消息。持续匹配会不断发送后续消息;需要时请在插件中添加次数限制或延迟。附件和工具的效果不会被重放。 ## agent.permission.before {#agentpermissionbefore} diff --git a/public-docs/plugins/migration.md b/public-docs/plugins/migration.md index 836a8e57b6..a2cd723ff5 100644 --- a/public-docs/plugins/migration.md +++ b/public-docs/plugins/migration.md @@ -207,6 +207,22 @@ setting `id` as an option key and each `value` as that option, and sends changes | `ProviderSetting` type | `ProviderOptionControl` | | `agent.create.before` `config.featureValues` | `config.providerOptions`; a returned `featureValues` edit is still applied | +### Turn history in v0.16 + +`agent.turn.after` has sent an empty `timeline` since v0.13, and the SDK type no longer declares it. +A plugin that reads `event.timeline` now fails typecheck. Read the turn from the agent instead: + +```ts +const turn = await context.paseo.agents + .ref(event.agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); +const items = turn.entries.filter((entry) => entry.turnId === event.turnId).map(({ item }) => item); +``` + +The filter drops entries from a turn that started after this one ended, such as a follow-up another plugin sent. The list is empty when such a turn has already started, or when `event.turnId` is `null`. + +Plugins built against an older SDK keep receiving `timeline: []` until removal after 2027-05-31. + ## 5. Recognize half-migration errors | Compiler or load error | Meaning and fix | diff --git a/public-docs/plugins/migration.zh-CN.md b/public-docs/plugins/migration.zh-CN.md index 216f2437b9..df74652d4b 100644 --- a/public-docs/plugins/migration.zh-CN.md +++ b/public-docs/plugins/migration.zh-CN.md @@ -170,6 +170,21 @@ Provider 插件只有一个配置记录 `providerOptions`,并用控件描述 | `ProviderSetting` 类型 | `ProviderOptionControl` | | `agent.create.before` 的 `config.featureValues` | `config.providerOptions`;返回的 `featureValues` 修改仍会被应用 | +### v0.16 中的轮次历史 {#turn-history-in-v016} + +自 v0.13 起,`agent.turn.after` 发送的 `timeline` 始终为空,SDK 类型也不再声明它。读取 `event.timeline` 的插件现在无法通过类型检查。请改为从 Agent 读取本轮: + +```ts +const turn = await context.paseo.agents + .ref(event.agent.id) + .timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true }); +const items = turn.entries.filter((entry) => entry.turnId === event.turnId).map(({ item }) => item); +``` + +过滤会去掉本轮结束后才开始的新一轮的条目,例如另一个插件发送的后续消息。如果这样的新一轮已经开始,或 `event.turnId` 为 `null`,列表为空。 + +基于旧版 SDK 构建的插件在 2027-05-31 之后移除兼容层之前仍会收到 `timeline: []`。 + ## 5. 识别只迁移了一半的错误 {#5-recognize-half-migration-errors} | 编译器或加载错误 | 含义与修复方法 | diff --git a/public-docs/sdk/reference.md b/public-docs/sdk/reference.md index 5a095b2c2a..4db6277f85 100644 --- a/public-docs/sdk/reference.md +++ b/public-docs/sdk/reference.md @@ -118,7 +118,7 @@ workspace the call creates is background too. With a `parent` and no value, the ### Timeline handle -`agent.timeline.refetch(options?)` fetches a page. Options are `direction`, `cursor`, `limit`, `projection`, and `requestId`. +`agent.timeline.refetch(options?)` fetches a page. Options are `direction`, `cursor`, `limit`, `projection`, `wholeTurns`, and `requestId`. `wholeTurns: true` extends a `tail` or `before` page back to the start of the oldest turn it reaches, so `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. It requires `features.wholeTurnTimeline`; older hosts ignore it and return a page of `limit` items. `agent.timeline.subscribe(handler)` establishes network demand for this agent and restores it after reconnect. Its unsubscribe function releases that demand; await `unsubscribe.ready` for initial daemon acknowledgement before starting work. Delivery is live-only. Reconnect emits a local `subscription_restored` event; request missed history explicitly with `refetch()`. A live replacement invalidates the previous epoch. See the callback shapes, paging and failure behavior in [timeline events](./events.md#follow-timeline-events). diff --git a/public-docs/sdk/reference.zh-CN.md b/public-docs/sdk/reference.zh-CN.md index 5879e9cab9..87166ff76f 100644 --- a/public-docs/sdk/reference.zh-CN.md +++ b/public-docs/sdk/reference.zh-CN.md @@ -114,7 +114,7 @@ nav: API 参考 ### 时间线句柄 {#timeline-handle} -`agent.timeline.refetch(options?)` 获取一页时间线。选项有 `direction`、`cursor`、`limit`、`projection` 和 `requestId`。 +`agent.timeline.refetch(options?)` 获取一页时间线。选项有 `direction`、`cursor`、`limit`、`projection`、`wholeTurns` 和 `requestId`。`wholeTurns: true` 会把 `tail` 或 `before` 页向前扩展到它所触及的最早一轮的开头,因此 `{ direction: "tail", limit: 1, wholeTurns: true }` 返回最近一轮。它需要 `features.wholeTurnTimeline`;旧版主机会忽略它,返回 `limit` 条记录。 `agent.timeline.subscribe(handler)` 为该 Agent 建立网络订阅需求,并在重连后恢复它。它返回的取消订阅函数会释放这项需求;开始工作之前,请 await `unsubscribe.ready` 以等待 daemon 的初始确认。投递只包含实时内容。重连时会发出一个本地的 `subscription_restored` 事件;错过的历史请用 `refetch()` 显式请求。实时的替换会使之前的 epoch 失效。回调的形状、分页和失败行为见[时间线事件](./events.md#follow-timeline-events)。 From a30b784eb2c1022ab70856b4c77e20bb8fb10183 Mon Sep 17 00:00:00 2001 From: Jack Tomaszewski Date: Fri, 13 Nov 2026 11:12:39 +0100 Subject: [PATCH 027/160] feat(plugins): let plugins add items to sidebar workspace rows (#7645) Plugins can register workspace-row badge render slots, control them from a separated Show menu group, and use the shared WorkspaceRowBadge UI. Co-authored-by: Jacek Tomaszewski --- docs/plugins.md | 15 ++ .../plugin-workspace-row-badges.spec.ts | 148 ++++++++++++++++++ .../sidebar/display-preferences/menu.tsx | 46 +++++- .../sidebar/display-preferences/model.ts | 37 +++++ .../sidebar/sidebar-workspace-row-content.tsx | 1 + .../sidebar/workspace-meta-row/index.tsx | 16 +- .../app/src/hooks/use-settings/storage.ts | 4 + .../app/src/plugins/buttons/model.test.ts | 1 + .../command-center/contributions.test.ts | 1 + .../src/plugins/composer-items/model.test.ts | 1 + .../src/plugins/composer-items/source.test.ts | 1 + packages/app/src/plugins/evaluate.test.ts | 41 +++++ packages/app/src/plugins/evaluate.ts | 21 +++ .../plugins/installation-provider.test.tsx | 1 + packages/app/src/plugins/item-host.tsx | 2 +- packages/app/src/plugins/react-native/ui.ts | 1 + packages/app/src/plugins/registry.ts | 1 + .../app/src/plugins/sidebar-groups.test.ts | 1 + .../src/plugins/surface-contribution.test.ts | 1 + packages/app/src/plugins/theme.test.ts | 1 + .../app/src/plugins/timeline/model.test.ts | 1 + .../app/src/plugins/timeline/view.test.tsx | 1 + packages/app/src/plugins/types.ts | 5 + .../workspace-panels/resolution.test.ts | 1 + .../workspace-row-badge-items/index.tsx | 96 ++++++++++++ .../plugins/workspace-row-badge-items/kit.tsx | 93 +++++++++++ .../workspace-row-badge-items/model.test.ts | 44 ++++++ .../workspace-row-badge-items/model.ts | 45 ++++++ packages/plugin/src/client/contracts.ts | 19 +++ packages/plugin/src/client/index.ts | 2 + packages/plugin/src/client/ui.ts | 13 ++ .../workspace-row-badges/README.md | 9 ++ .../workspace-row-badges/index.client.tsx | 29 ++++ .../workspace-row-badges/paseo-plugin.json | 1 + public-docs/plugins/migration.md | 49 +++--- public-docs/plugins/migration.zh-CN.md | 47 +++--- public-docs/plugins/reference.md | 54 +++++++ public-docs/plugins/reference.zh-CN.md | 45 ++++++ 38 files changed, 843 insertions(+), 52 deletions(-) create mode 100644 packages/app/e2e/browser/plugin-workspace-row-badges.spec.ts create mode 100644 packages/app/src/plugins/workspace-row-badge-items/index.tsx create mode 100644 packages/app/src/plugins/workspace-row-badge-items/kit.tsx create mode 100644 packages/app/src/plugins/workspace-row-badge-items/model.test.ts create mode 100644 packages/app/src/plugins/workspace-row-badge-items/model.ts create mode 100644 plugin-examples/workspace-row-badges/README.md create mode 100644 plugin-examples/workspace-row-badges/index.client.tsx create mode 100644 plugin-examples/workspace-row-badges/paseo-plugin.json diff --git a/docs/plugins.md b/docs/plugins.md index d64e7ed150..d6c2228d69 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -624,6 +624,21 @@ one section's order from built-ins, plugin groups, and the section's preference remembers under its own key. It shares header ids and the `plugin::` settings key with new-API items. +## Contribute workspace row badge items + +The [public reference](../public-docs/plugins/reference.md#workspace-row-badge-items) owns the author API. +The host lives in `packages/app/src/plugins/workspace-row-badge-items/`; `WorkspaceMetaRow` draws a host's +items after its own. + +- Plugin items render with no wrapper view. The meta line spaces children with `gap`, so an empty + wrapper would leave a gap on rows the plugin has nothing to say about. That is also why + the row adds no separator around plugin items; a plugin renders its slot. +- A row only renders items from plugins on its own host. The Show menu coalesces items across hosts + by `/`, the key in the `sidebarPluginRowBadgeItems` setting, and places them in + their own group below a separator. A missing key is visible. +- Previews (Settings > Host appearance) pass no `workspace` to `WorkspaceMetaRow`, so plugin items + stay off them. + ## Contribute file panels Client `addFilePanel` registrations become the body of a file tab. The tab stats the file, picks a diff --git a/packages/app/e2e/browser/plugin-workspace-row-badges.spec.ts b/packages/app/e2e/browser/plugin-workspace-row-badges.spec.ts new file mode 100644 index 0000000000..164c931248 --- /dev/null +++ b/packages/app/e2e/browser/plugin-workspace-row-badges.spec.ts @@ -0,0 +1,148 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Page } from "@playwright/test"; +import { expect, test } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace"; +import { pluginRequirements } from "../support/helpers/plugin-fixture"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { + closeSidebarDisplayPreferences, + openMobileAgentSidebar, + openSidebarDisplayPage, +} from "../support/helpers/sidebar"; + +const PLUGIN_ID = "row-badges-e2e"; +const TITLE = "Badge host workspace"; + +const PLUGIN_SOURCE = `import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; + +function Review() { + return ; +} + +function Docs() { + return ; +} + +function IconOnly() { + return ; +} + +function EmptyLabel() { + return ; +} + +function Quiet() { + return null; +} + +function Broken() { + throw new Error("badge failed"); +} + +export default function contribute(client) { + client.addWorkspaceRowBadgeItem({ id: "review", title: "Review state", icon: "Eye", Component: Review }); + client.addWorkspaceRowBadgeItem({ id: "docs", title: "Docs state", icon: "BookOpen", Component: Docs }); + client.addWorkspaceRowBadgeItem({ id: "icon", title: "Icon state", icon: "Star", Component: IconOnly }); + client.addWorkspaceRowBadgeItem({ id: "empty", title: "Empty label state", icon: "Circle", Component: EmptyLabel }); + client.addWorkspaceRowBadgeItem({ id: "quiet", title: "Quiet state", icon: "Moon", Component: Quiet }); + client.addWorkspaceRowBadgeItem({ id: "broken", title: "Broken state", icon: "Bug", Component: Broken }); + return () => {}; +} +`; + +// The meta line the badges draw on. Each item sits in one wrapper of its own, so the line is two up. +const LABELS = { review: "In review", docs: "Docs" } as const; + +function badgeLine(page: Page, itemId: keyof typeof LABELS) { + return badge(page, itemId).locator("xpath=../.."); +} + +function badge(page: Page, itemId: keyof typeof LABELS) { + return page.getByLabel(LABELS[itemId], { exact: true }).locator("visible=true"); +} + +async function toggleShowItem(page: Page, label: string, touch: boolean) { + await openSidebarDisplayPage(page, "sidebar-display-show"); + await page.getByRole("menuitem", { name: label, exact: true }).click(); + if (touch) { + await page + .getByRole("button", { name: "Bottom sheet backdrop", exact: true }) + .click({ position: { x: 5, y: 5 } }); + } else { + await closeSidebarDisplayPreferences(page); + } +} + +test("a plugin badge shows on workspace rows, hides quietly, and follows its Show toggle", async ({ + page, +}, info) => { + test.setTimeout(120_000); + const workspace = await seedWorkspace({ repoPrefix: "row-badges-", title: TITLE }); + const client = await connectNewWorkspaceDaemonClient({ ownProjects: false }); + const config = await client.getDaemonConfig(); + const directory = await mkdtemp(path.join(tmpdir(), "paseo-row-badges-")); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }), + ); + await writeFile(path.join(directory, "index.client.tsx"), PLUGIN_SOURCE); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + + await page.setViewportSize({ width: 1280, height: 900 }); + await gotoAppShell(page); + + await test.step("the badge draws on the row; a null item and a throwing item draw nothing", async () => { + await expect(badge(page, "review")).toBeVisible(); + await expect(badge(page, "review")).toContainText("In review"); + // The null and throwing items after them draw nothing, and the line adds nothing of its own. + await expect(badgeLine(page, "review")).toHaveText("In reviewDocs"); + // An icon-only badge is named by its item's title. + await expect( + page.getByLabel("Icon state", { exact: true }).locator("visible=true"), + ).toBeVisible(); + await expect( + page.getByLabel("Empty label state", { exact: true }).locator("visible=true"), + ).toBeVisible(); + await expect(page.getByText(TITLE).first()).toBeVisible(); + await page.screenshot({ path: info.outputPath("wide.png") }); + }); + + await test.step("every item has a Show toggle, and switching one off removes only that badge", async () => { + await openSidebarDisplayPage(page, "sidebar-display-show"); + for (const label of ["Review state", "Quiet state", "Broken state", "Docs state"]) { + await expect(page.getByRole("menuitem", { name: label, exact: true })).toBeVisible(); + } + await expect(page.getByTestId("sidebar-plugin-row-badge-items-separator")).toBeVisible(); + await page.screenshot({ path: info.outputPath("show-menu.png") }); + await page.getByRole("menuitem", { name: "Review state", exact: true }).click(); + await closeSidebarDisplayPreferences(page); + await expect(badge(page, "review")).toHaveCount(0); + // The first badge is gone, so the next one leads the line without a "·". + await expect(badgeLine(page, "docs")).toHaveText("Docs"); + await toggleShowItem(page, "Review state", false); + await expect(badge(page, "review")).toBeVisible(); + }); + + await test.step("the badge draws on a compact layout", async () => { + await page.setViewportSize({ width: 390, height: 844 }); + await openMobileAgentSidebar(page); + await expect(badge(page, "review")).toBeVisible(); + await page.screenshot({ path: info.outputPath("compact.png") }); + await toggleShowItem(page, "Review state", true); + await expect(badge(page, "review")).toHaveCount(0); + await toggleShowItem(page, "Review state", true); + await expect(badge(page, "review")).toBeVisible(); + }); + } finally { + await client.removePlugin(PLUGIN_ID).catch(() => undefined); + await client.patchDaemonConfig({ pluginsEnabled: config.config.pluginsEnabled }); + await client.close(); + await rm(directory, { recursive: true, force: true }); + await workspace.cleanup(); + } +}); diff --git a/packages/app/src/components/sidebar/display-preferences/menu.tsx b/packages/app/src/components/sidebar/display-preferences/menu.tsx index d6483a5519..93a31c3c0d 100644 --- a/packages/app/src/components/sidebar/display-preferences/menu.tsx +++ b/packages/app/src/components/sidebar/display-preferences/menu.tsx @@ -58,6 +58,8 @@ import { SIDEBAR_ROW_ITEMS, type SidebarRowItem } from "./row-items"; import { useWorkspaceLabelProjection } from "@/workspace-labels"; import { WorkspaceLabelDot } from "@/workspace-labels/swatch"; import { WorkspaceLabelManagerModal } from "@/workspace-labels/manager-modal"; +import { PluginIconView } from "@/plugins/icons"; +import type { PluginWorkspaceRowBadgeItemGroup } from "@/plugins/workspace-row-badge-items"; const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); @@ -65,6 +67,7 @@ const ThemedSettings2 = withUnistyles(Settings2); /** CI's mark: the subject of the checks row, and the shape the icon-only option leaves behind. */ const ThemedCircleCheck = withUnistyles(CircleCheck); const ThemedCircle = withUnistyles(Circle); +const ThemedPluginIconView = withUnistyles(PluginIconView); /** Fits the item's 16pt leading slot with a hair of room, matching the trailing check. */ const OPTION_ICON_SIZE = 14; @@ -607,9 +610,9 @@ function OptionList({ } /** - * Two groups, split by the separator. Above it, what a row may say about a workspace — each one - * independent. Below it, the one thing the slot to the right of the title holds, so picking the - * one already showing empties the slot and gives the width back to the title. + * Three groups: Paseo's own row items, plugin badge items, then the one thing the slot to the + * right of the title holds. Picking the trailing choice already showing empties the slot and + * gives the width back to the title. * * CI is the one item above the separator with three answers rather than two, so it opens a page * instead of ticking, and it goes last: a row that navigates does not belong in the middle of a @@ -632,6 +635,12 @@ function ShowPage({ preferences }: { preferences: Preferences }): ReactElement { /> ))} + {preferences.pluginRowBadgeItems.length > 0 ? ( + + ) : null} + {preferences.pluginRowBadgeItems.map((item) => ( + + ))} {TRAILING_CHOICES.map((choice) => ( preferences.togglePluginRowBadgeItem(item.key), + [item.key, preferences], + ); + const leading = useMemo( + () => ( + + ), + [item.icon], + ); + return ( + + {item.title} + + ); +} + /** * No value on the row, only the chevron. The three answers are all long enough that the value * fills the row and stops reading as an answer sitting at the right edge — it turns into a second diff --git a/packages/app/src/components/sidebar/display-preferences/model.ts b/packages/app/src/components/sidebar/display-preferences/model.ts index a2ef3212e0..565d0d9fd1 100644 --- a/packages/app/src/components/sidebar/display-preferences/model.ts +++ b/packages/app/src/components/sidebar/display-preferences/model.ts @@ -10,6 +10,12 @@ import { type SidebarGroupMode, type SidebarLabelFilter, } from "@/stores/sidebar-view-store"; +import { useInstalledPlugins } from "@/plugins/registry"; +import { + groupPluginWorkspaceRowBadgeItems, + isWorkspaceRowBadgeItemVisible, + type PluginWorkspaceRowBadgeItemGroup, +} from "@/plugins/workspace-row-badge-items"; import { DEFAULT_SIDEBAR_CHECKS_DISPLAY, type SidebarChecksDisplay } from "./checks-display"; import { DEFAULT_SIDEBAR_ROW_ITEMS, type SidebarRowItem, type SidebarRowItems } from "./row-items"; @@ -27,6 +33,10 @@ export interface SidebarDisplayPreferences { setTitleSource: (source: WorkspaceTitleSource) => void; rowItems: SidebarRowItems; toggleRowItem: (item: SidebarRowItem) => void; + /** Workspace row badge items contributed by installed plugins, one per plugin item across hosts. */ + pluginRowBadgeItems: readonly PluginWorkspaceRowBadgeItemGroup[]; + isPluginRowBadgeItemVisible: (key: string) => boolean; + togglePluginRowBadgeItem: (key: string) => void; checksDisplay: SidebarChecksDisplay; setChecksDisplay: (display: SidebarChecksDisplay) => void; trailing: SidebarWorkspaceTrailing; @@ -75,9 +85,30 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences { sidebarWorkspaceTrailing, sidebarRowItems, sidebarChecksDisplay, + sidebarPluginRowBadgeItems, }, updateSettings, } = useAppSettings(); + const installedPlugins = useInstalledPlugins(); + const pluginRowBadgeItems = useMemo( + () => groupPluginWorkspaceRowBadgeItems(installedPlugins), + [installedPlugins], + ); + const isPluginRowBadgeItemVisible = useCallback( + (key: string) => isWorkspaceRowBadgeItemVisible(sidebarPluginRowBadgeItems, key), + [sidebarPluginRowBadgeItems], + ); + const togglePluginRowBadgeItem = useCallback( + (key: string) => { + void updateSettings({ + sidebarPluginRowBadgeItems: { + ...sidebarPluginRowBadgeItems, + [key]: !isWorkspaceRowBadgeItemVisible(sidebarPluginRowBadgeItems, key), + }, + }); + }, + [updateSettings, sidebarPluginRowBadgeItems], + ); const setTitleSource = useCallback( (source: WorkspaceTitleSource) => { @@ -123,6 +154,9 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences { setTitleSource, rowItems: sidebarRowItems, toggleRowItem, + pluginRowBadgeItems, + isPluginRowBadgeItemVisible, + togglePluginRowBadgeItem, checksDisplay: sidebarChecksDisplay, setChecksDisplay, trailing: sidebarWorkspaceTrailing, @@ -148,6 +182,9 @@ export function useSidebarDisplayPreferences(): SidebarDisplayPreferences { setTitleSource, sidebarRowItems, toggleRowItem, + pluginRowBadgeItems, + isPluginRowBadgeItemVisible, + togglePluginRowBadgeItem, sidebarChecksDisplay, setChecksDisplay, sidebarWorkspaceTrailing, diff --git a/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx b/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx index 710ac03e1b..aef10abe48 100644 --- a/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx +++ b/packages/app/src/components/sidebar/sidebar-workspace-row-content.tsx @@ -186,6 +186,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte prHint={workspace.prHint} serviceSummary={serviceSummary} labels={labels} + workspace={workspace} /> diff --git a/packages/app/src/components/sidebar/workspace-meta-row/index.tsx b/packages/app/src/components/sidebar/workspace-meta-row/index.tsx index d539fcf064..f475b6fa08 100644 --- a/packages/app/src/components/sidebar/workspace-meta-row/index.tsx +++ b/packages/app/src/components/sidebar/workspace-meta-row/index.tsx @@ -16,6 +16,10 @@ import { openExternalUrl } from "@/utils/open-external-url"; import { useSidebarMetaPreferences } from "@/components/sidebar/display-preferences/model"; import type { Theme } from "@/styles/theme"; import { PullRequestStateIcon } from "@/git/pull-request-state-icon"; +import { + PluginWorkspaceRowBadgeItems, + usePluginWorkspaceRowBadgeItems, +} from "@/plugins/workspace-row-badge-items"; import { CheckIndicator } from "./check-indicator"; import type { CheckSummary, CheckSummaryState } from "./check-summary"; import { selectMetaRowItems, type MetaRowItem } from "./meta-items"; @@ -59,6 +63,9 @@ const dangerMapping = (theme: Theme) => ({ color: theme.colors.statusDanger }); * state has its own colors — a label is a name a person chose, so it carries its own identity * color on a tint instead (see `WorkspaceLabelChip`). It sits last so the reported facts are * read first, and it stays the same height as the rest of the line. + * + * Plugin items follow everything the row knows itself. A plugin renders its slot as it likes: + * the row adds no separator, since only the plugin knows whether it has anything to say. */ export function WorkspaceMetaRow({ currentBranch, @@ -67,6 +74,7 @@ export function WorkspaceMetaRow({ prHint, serviceSummary, labels = EMPTY_LABELS, + workspace = null, }: { currentBranch: string | null; projectName: string | null; @@ -74,6 +82,8 @@ export function WorkspaceMetaRow({ prHint: PrHint | null; serviceSummary: WorkspaceServiceSummary | null; labels?: readonly WorkspaceLabelDefinition[]; + /** The real workspace behind the row; previews leave it out and get no plugin items. */ + workspace?: { serverId: string; workspaceId: string } | null; }) { const { rowItems, checksDisplay } = useSidebarMetaPreferences(); const items = selectMetaRowItems({ @@ -86,8 +96,9 @@ export function WorkspaceMetaRow({ visible: rowItems, checksDisplay, }); + const pluginItems = usePluginWorkspaceRowBadgeItems(workspace?.serverId ?? null); - if (items.length === 0) return null; + if (items.length === 0 && (!workspace || pluginItems.length === 0)) return null; return ( @@ -97,6 +108,9 @@ export function WorkspaceMetaRow({ ))} + {workspace ? ( + + ) : null} ); } diff --git a/packages/app/src/hooks/use-settings/storage.ts b/packages/app/src/hooks/use-settings/storage.ts index 424536ac69..f04b7b6d94 100644 --- a/packages/app/src/hooks/use-settings/storage.ts +++ b/packages/app/src/hooks/use-settings/storage.ts @@ -96,6 +96,8 @@ export interface AppSettings { sidebarWorkspaceTrailing: SidebarWorkspaceTrailing; sidebarRowItems: SidebarRowItems; sidebarChecksDisplay: SidebarChecksDisplay; + /** Plugin workspace row badge items by `/`; a missing key shows. */ + sidebarPluginRowBadgeItems: Record; /** Top-level sidebar rows in display order; empty means the default order, all visible. */ sidebarNavItems: SidebarNavPreference[]; /** Sidebar footer items in display order; empty means the default order, all visible. */ @@ -156,6 +158,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = { sidebarWorkspaceTrailing: "timestamp", sidebarRowItems: DEFAULT_SIDEBAR_ROW_ITEMS, sidebarChecksDisplay: DEFAULT_SIDEBAR_CHECKS_DISPLAY, + sidebarPluginRowBadgeItems: {}, sidebarNavItems: [], sidebarFooterItems: [], usage: DEFAULT_USAGE_PREFERENCES, @@ -253,6 +256,7 @@ const StoredAppSettingsSchema = z .enum(["iconAndText", "icon", "none"]) .optional() .catch(DEFAULT_SIDEBAR_CHECKS_DISPLAY), + sidebarPluginRowBadgeItems: z.record(z.string(), z.boolean()).catch({}), sidebarNavItems: z.array(z.object({ key: z.string(), visible: z.boolean() })).catch([]), sidebarFooterItems: z.array(z.object({ key: z.string(), visible: z.boolean() })).catch([]), usage: UsagePreferencesSchema, diff --git a/packages/app/src/plugins/buttons/model.test.ts b/packages/app/src/plugins/buttons/model.test.ts index ac3aba7672..543ae781ad 100644 --- a/packages/app/src/plugins/buttons/model.test.ts +++ b/packages/app/src/plugins/buttons/model.test.ts @@ -26,6 +26,7 @@ function installation(): InstalledPlugin { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/command-center/contributions.test.ts b/packages/app/src/plugins/command-center/contributions.test.ts index c821bebd83..6d96520660 100644 --- a/packages/app/src/plugins/command-center/contributions.test.ts +++ b/packages/app/src/plugins/command-center/contributions.test.ts @@ -105,6 +105,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/composer-items/model.test.ts b/packages/app/src/plugins/composer-items/model.test.ts index 234e06ed90..ecd5799c81 100644 --- a/packages/app/src/plugins/composer-items/model.test.ts +++ b/packages/app/src/plugins/composer-items/model.test.ts @@ -37,6 +37,7 @@ function installed(): InstalledPlugin { filePanels: [], composerItems: [], newWorkspaceItems: [], + workspaceRowBadgeItems: [], workspacePanels: [], commandCenterItems: [], clientSlashCommands: [], diff --git a/packages/app/src/plugins/composer-items/source.test.ts b/packages/app/src/plugins/composer-items/source.test.ts index a9be4012d0..cf9204fa8e 100644 --- a/packages/app/src/plugins/composer-items/source.test.ts +++ b/packages/app/src/plugins/composer-items/source.test.ts @@ -47,6 +47,7 @@ function plugin(): InstalledPlugin { filePanels: [], composerItems: [], newWorkspaceItems: [], + workspaceRowBadgeItems: [], workspacePanels: [], commandCenterItems: [], clientSlashCommands: [], diff --git a/packages/app/src/plugins/evaluate.test.ts b/packages/app/src/plugins/evaluate.test.ts index 69ede1feed..7aea3be565 100644 --- a/packages/app/src/plugins/evaluate.test.ts +++ b/packages/app/src/plugins/evaluate.test.ts @@ -101,6 +101,7 @@ describe("evaluatePluginClientBundle", () => { plugin.addSettingsScreen({ id: "display", title: "Display", icon: "Settings", Component }), plugin.addSidebarHeaderItem({ id: "main", title: "Main", Component }), plugin.addSidebarFooterItem({ id: "status", title: "Status", Component }), + plugin.addWorkspaceRowBadgeItem({ id: "status", title: "Status", icon: "Blocks", Component }), plugin.addWorkspacePanel({ id: "panel", title: "Panel", icon: "Blocks", context: "workspace", Component }), plugin.addCommandCenterItem({ id: "command", title: "Command", icon: "Blocks", context: "global", onSelect() {} }), plugin.addSlashCommand({ name: "review", description: "Review", argumentHint: "", context: "workspace", onSubmit() {} }), @@ -132,6 +133,7 @@ describe("evaluatePluginClientBundle", () => { plugin.settingsScreens, plugin.sidebarItems.header, plugin.sidebarItems.footer, + plugin.workspaceRowBadgeItems, plugin.workspacePanels, plugin.commandCenterItems, plugin.clientSlashCommands, @@ -152,6 +154,7 @@ describe("evaluatePluginClientBundle", () => { plugin.settingsScreens, plugin.sidebarItems.header, plugin.sidebarItems.footer, + plugin.workspaceRowBadgeItems, plugin.workspacePanels, plugin.commandCenterItems, plugin.clientSlashCommands, @@ -282,6 +285,44 @@ describe("evaluatePluginClientBundle", () => { ).toThrow("Sidebar item main has no title"); }); + it("collects workspace row badge items and rejects duplicate and malformed ones", () => { + const plugin = evaluatePluginClientBundle( + "example", + bundle(` + function Item() { return null; } + plugin.addWorkspaceRowBadgeItem({ id: "status", title: " Status ", icon: "Blocks", Component: Item }); + `), + ); + expect( + plugin.workspaceRowBadgeItems.map(({ id, title, icon }) => ({ id, title, icon })), + ).toEqual([{ id: "status", title: "Status", icon: "Blocks" }]); + + const row = (fields: string) => + bundle(`function Item() { return null; } plugin.addWorkspaceRowBadgeItem({ ${fields} });`); + expect(() => + evaluatePluginClientBundle( + "example", + bundle(` + function Item() { return null; } + plugin.addWorkspaceRowBadgeItem({ id: "status", title: "One", icon: "Blocks", Component: Item }); + plugin.addWorkspaceRowBadgeItem({ id: "status", title: "Two", icon: "Blocks", Component: Item }); + `), + ), + ).toThrow("Duplicate workspace row badge item: status"); + expect(() => + evaluatePluginClientBundle( + "example", + row(`id: "status", title: " ", icon: "Blocks", Component: Item`), + ), + ).toThrow("Workspace row badge item status has no title"); + expect(() => + evaluatePluginClientBundle( + "example", + row(`id: "status", title: "Status", icon: "Blocks", Component: "Item"`), + ), + ).toThrow("Workspace row badge item status is not a component"); + }); + it("expands the addSurface and addSidebarItem aliases to a screen and a legacy header item", () => { const plugin = evaluatePluginClientBundle( "example", diff --git a/packages/app/src/plugins/evaluate.ts b/packages/app/src/plugins/evaluate.ts index f3e89122dd..db31415ecb 100644 --- a/packages/app/src/plugins/evaluate.ts +++ b/packages/app/src/plugins/evaluate.ts @@ -37,6 +37,7 @@ import type { PluginScreenContribution, PluginSidebarItemContribution, PluginWorkspacePanelContribution, + PluginWorkspaceRowBadgeItemContribution, } from "./types"; import type { ComponentType } from "react"; import { parsePluginIcon, parseSerializablePluginIcon } from "./icons"; @@ -133,6 +134,7 @@ export function runPluginClientBundle( sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], @@ -151,6 +153,7 @@ export function runPluginClientBundle( header: new Set(), footer: new Set(), }; + const workspaceRowItemIds = new Set(); const filePanelIds = new Set(); const composerItemIds = new Set(); const newWorkspaceItemIds = new Set(); @@ -323,6 +326,23 @@ export function runPluginClientBundle( addSidebarFooterItem(contribution: PluginSidebarItemContribution) { return addSidebarItem("footer", contribution); }, + addWorkspaceRowBadgeItem(contribution: PluginWorkspaceRowBadgeItemContribution) { + const itemId = requireId(contribution.id, "workspace row badge item id"); + if (workspaceRowItemIds.has(itemId)) + throw new Error(`Duplicate workspace row badge item: ${itemId}`); + const title = normalizePluginText(contribution.title); + if (!title) throw new Error(`Workspace row badge item ${itemId} has no title`); + const icon = parsePluginIcon(`Workspace row badge item ${itemId}`, contribution.icon); + if (!isComponentType(contribution.Component)) { + throw new Error(`Workspace row badge item ${itemId} is not a component`); + } + workspaceRowItemIds.add(itemId); + return register( + collector.workspaceRowBadgeItems, + { id: itemId, title, icon, Component: contribution.Component }, + () => workspaceRowItemIds.delete(itemId), + ); + }, // COMPAT(pluginSidebarAliases): added in v0.11.0, remove after 2027-03-29 // Titled by its id; a legacy item pointing at it lends the header its own title instead. addSurface(surfaceId: string, Component: ComponentType) { @@ -634,6 +654,7 @@ export function runPluginClientBundle( sidebarViews: collector.sidebarViews, sidebarItems: collector.sidebarItems, legacySidebarItems: collector.legacySidebarItems, + workspaceRowBadgeItems: collector.workspaceRowBadgeItems, filePanels: collector.filePanels, composerItems: collector.composerItems, newWorkspaceItems: collector.newWorkspaceItems, diff --git a/packages/app/src/plugins/installation-provider.test.tsx b/packages/app/src/plugins/installation-provider.test.tsx index b4f7735e86..9248221704 100644 --- a/packages/app/src/plugins/installation-provider.test.tsx +++ b/packages/app/src/plugins/installation-provider.test.tsx @@ -46,6 +46,7 @@ function installation(invoked: string[]): InstalledPlugin { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/item-host.tsx b/packages/app/src/plugins/item-host.tsx index 2df4198e7a..3083aa1595 100644 --- a/packages/app/src/plugins/item-host.tsx +++ b/packages/app/src/plugins/item-host.tsx @@ -14,7 +14,7 @@ import type { InstalledPlugin } from "./types"; /** `withUnistyles` mapping that hands a host the plugin theme. */ export const pluginThemeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) }); -function renderNothing() { +export function renderNothing() { return null; } diff --git a/packages/app/src/plugins/react-native/ui.ts b/packages/app/src/plugins/react-native/ui.ts index 8b7d17216d..b5ae3c77b0 100644 --- a/packages/app/src/plugins/react-native/ui.ts +++ b/packages/app/src/plugins/react-native/ui.ts @@ -11,6 +11,7 @@ export { export { ExternalLink } from "@/components/ui/external-link"; export { SidebarRow, SidebarSeparator } from "@/plugins/sidebar-items/kit"; +export { WorkspaceRowBadge } from "@/plugins/workspace-row-badge-items/kit"; export { DocumentFrame } from "@/file-panels/document-frame"; diff --git a/packages/app/src/plugins/registry.ts b/packages/app/src/plugins/registry.ts index 042050ed3a..c291681601 100644 --- a/packages/app/src/plugins/registry.ts +++ b/packages/app/src/plugins/registry.ts @@ -125,6 +125,7 @@ export class PluginRegistry { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/sidebar-groups.test.ts b/packages/app/src/plugins/sidebar-groups.test.ts index 635f3d8eac..f0a9104e9f 100644 --- a/packages/app/src/plugins/sidebar-groups.test.ts +++ b/packages/app/src/plugins/sidebar-groups.test.ts @@ -37,6 +37,7 @@ function installed( footer: [{ id: "status", title: "Status", Component: () => null }], }, legacySidebarItems, + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/surface-contribution.test.ts b/packages/app/src/plugins/surface-contribution.test.ts index 8af246cf81..9d5a9a4a22 100644 --- a/packages/app/src/plugins/surface-contribution.test.ts +++ b/packages/app/src/plugins/surface-contribution.test.ts @@ -51,6 +51,7 @@ function installation( surfaces: surfaces.map((id) => ({ id, title: id, Component: () => null })), sidebarViews: [], sidebarItems: { header: [], footer: [] }, + workspaceRowBadgeItems: [], legacySidebarItems: sidebarItems.map((item) => ({ ...item, title: item.id, diff --git a/packages/app/src/plugins/theme.test.ts b/packages/app/src/plugins/theme.test.ts index aeb7872a2e..b8c3567e78 100644 --- a/packages/app/src/plugins/theme.test.ts +++ b/packages/app/src/plugins/theme.test.ts @@ -64,6 +64,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/timeline/model.test.ts b/packages/app/src/plugins/timeline/model.test.ts index 957bd18686..e30e3b40b2 100644 --- a/packages/app/src/plugins/timeline/model.test.ts +++ b/packages/app/src/plugins/timeline/model.test.ts @@ -27,6 +27,7 @@ function plugin(input: { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/timeline/view.test.tsx b/packages/app/src/plugins/timeline/view.test.tsx index 7d96747279..57e371eadc 100644 --- a/packages/app/src/plugins/timeline/view.test.tsx +++ b/packages/app/src/plugins/timeline/view.test.tsx @@ -34,6 +34,7 @@ vi.mock("../client-runtime", () => ({ })); vi.mock("../icons", () => ({ Icon: () => null, + PluginIconView: () => null, pluginIconComponent: () => () => null, })); diff --git a/packages/app/src/plugins/types.ts b/packages/app/src/plugins/types.ts index 497df5c59c..2ca1e4cf01 100644 --- a/packages/app/src/plugins/types.ts +++ b/packages/app/src/plugins/types.ts @@ -17,6 +17,7 @@ import type { PluginSidebarContribution as SDKPluginSidebarContribution, PluginSidebarViewContribution, PluginSidebarItemContribution as SDKPluginSidebarItemContribution, + PluginWorkspaceRowBadgeItemContribution as SDKPluginWorkspaceRowBadgeItemContribution, PluginScreenContribution as SDKPluginScreenContribution, PluginSettingsScreenContribution as SDKPluginSettingsScreenContribution, PluginTimelineRendererContribution, @@ -33,6 +34,8 @@ type PluginClientSlashCommandContribution = SDKPluginClientSlashCommandContribut type PluginComposerPillContribution = SDKPluginComposerPillContribution; type PluginSidebarContribution = SDKPluginSidebarContribution; type PluginSidebarItemContribution = SDKPluginSidebarItemContribution; +type PluginWorkspaceRowBadgeItemContribution = + SDKPluginWorkspaceRowBadgeItemContribution; type PluginScreenContribution = SDKPluginScreenContribution; type PluginSettingsScreenContribution = SDKPluginSettingsScreenContribution; type WorkspacePanelInput = SDKPluginWorkspacePanelContribution; @@ -56,6 +59,7 @@ export interface EvaluatedPlugin { // COMPAT(pluginSidebarAliases): added in v0.11.0, remove after 2027-03-29 /** `addSidebarItem` registrations, so `/plugin//sidebar/` routes keep resolving. */ legacySidebarItems: PluginSidebarContribution[]; + workspaceRowBadgeItems: PluginWorkspaceRowBadgeItemContribution[]; filePanels: PluginFilePanelContribution[]; composerItems: PluginComposerItemContribution[]; newWorkspaceItems: PluginNewWorkspaceItemContribution[]; @@ -95,6 +99,7 @@ export type { PluginComposerPillContribution, PluginSidebarContribution, PluginSidebarItemContribution, + PluginWorkspaceRowBadgeItemContribution, PluginScreenContribution, PluginSettingsScreenContribution, PluginThemeContribution, diff --git a/packages/app/src/plugins/workspace-panels/resolution.test.ts b/packages/app/src/plugins/workspace-panels/resolution.test.ts index 6ceb95f1a1..4a8f7c0112 100644 --- a/packages/app/src/plugins/workspace-panels/resolution.test.ts +++ b/packages/app/src/plugins/workspace-panels/resolution.test.ts @@ -24,6 +24,7 @@ function installed(): InstalledPlugin { sidebarViews: [], sidebarItems: { header: [], footer: [] }, legacySidebarItems: [], + workspaceRowBadgeItems: [], filePanels: [], composerItems: [], newWorkspaceItems: [], diff --git a/packages/app/src/plugins/workspace-row-badge-items/index.tsx b/packages/app/src/plugins/workspace-row-badge-items/index.tsx new file mode 100644 index 0000000000..00f70416c5 --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/index.tsx @@ -0,0 +1,96 @@ +import type { PluginTheme } from "@getpaseo/plugin"; +import type { PluginWorkspaceRowBadgeItemProps } from "@getpaseo/plugin/client"; +import { useMemo } from "react"; +import { withUnistyles } from "react-native-unistyles"; +import { useAppSettings } from "@/hooks/use-settings"; +import { useInstalledPlugins } from "../registry"; +import { pluginThemeMapping, renderNothing, usePluginItemHost } from "../item-host"; +import { PluginEnvironmentProvider } from "../popover"; +import { SurfaceErrorBoundary } from "../surface-error-boundary"; +import type { InstalledPlugin, PluginWorkspaceRowBadgeItemContribution } from "../types"; +import { isWorkspaceRowBadgeItemVisible, workspaceRowBadgeItemKey } from "./model"; + +import { WorkspaceRowBadgeTitleContext } from "./kit"; + +export { WorkspaceRowBadge } from "./kit"; +export { + groupPluginWorkspaceRowBadgeItems, + isWorkspaceRowBadgeItemVisible, + type PluginWorkspaceRowBadgeItemGroup, +} from "./model"; + +interface RowBadgeItemTarget { + plugin: InstalledPlugin; + item: PluginWorkspaceRowBadgeItemContribution; +} + +/** The visible plugin row items installed on this workspace's host. */ +export function usePluginWorkspaceRowBadgeItems(serverId: string | null): RowBadgeItemTarget[] { + const installed = useInstalledPlugins(); + const { + settings: { sidebarPluginRowBadgeItems }, + } = useAppSettings(); + return useMemo( + () => + installed + .filter((plugin) => plugin.serverId === serverId) + .flatMap((plugin) => plugin.workspaceRowBadgeItems.map((item) => ({ plugin, item }))) + .filter(({ plugin, item }) => + isWorkspaceRowBadgeItemVisible( + sidebarPluginRowBadgeItems, + workspaceRowBadgeItemKey(plugin.id, item.id), + ), + ), + [installed, serverId, sidebarPluginRowBadgeItems], + ); +} + +/** + * Plugin items on a workspace's meta line, after the row's own. No wrapper views: an item that + * renders nothing must leave no gap behind it on the line. + */ +export function PluginWorkspaceRowBadgeItems({ + targets, + workspaceId, +}: { + targets: readonly RowBadgeItemTarget[]; + workspaceId: string; +}) { + return targets.map((target) => ( + + )); +} + +function RowBadgeItemHost({ + target: { plugin, item }, + workspaceId, + theme, +}: { + target: RowBadgeItemTarget; + workspaceId: string; + theme: PluginTheme; +}) { + const { environment, props: hostProps } = usePluginItemHost(plugin, theme); + const props = useMemo( + () => ({ ...hostProps, workspaceId }), + [hostProps, workspaceId], + ); + const title = plugin.i18n.resolve(item.title, plugin.locale); + const Item = item.Component; + return ( + + + + + + + + ); +} + +const ThemedRowBadgeItemHost = withUnistyles(RowBadgeItemHost); diff --git a/packages/app/src/plugins/workspace-row-badge-items/kit.tsx b/packages/app/src/plugins/workspace-row-badge-items/kit.tsx new file mode 100644 index 0000000000..eaa3733b5d --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/kit.tsx @@ -0,0 +1,93 @@ +import type { WorkspaceRowBadgeProps, WorkspaceRowBadgeTone } from "@getpaseo/plugin/client/ui"; +import { createContext, useContext, useMemo } from "react"; +import { Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { HOST_BADGE_ICON_SIZE } from "@/hosts/host-badge"; +import type { Theme } from "@/styles/theme"; +import { parsePluginIcon, PluginIconView } from "../icons"; + +/** The item's title, the accessible name of a badge that has neither a label nor its own. */ +export const WorkspaceRowBadgeTitleContext = createContext(undefined); + +const ThemedPluginIconView = withUnistyles(PluginIconView); + +function toneColor(theme: Theme, tone: WorkspaceRowBadgeTone): string { + if (tone === "success") return theme.colors.statusSuccess; + if (tone === "warning") return theme.colors.statusWarning; + if (tone === "danger") return theme.colors.statusDanger; + if (tone === "info") return theme.colors.statusDotRunning; + return theme.colors.foregroundMuted; +} + +const TONE_MAPPINGS: Record { color: string }> = { + muted: (theme) => ({ color: toneColor(theme, "muted") }), + success: (theme) => ({ color: toneColor(theme, "success") }), + warning: (theme) => ({ color: toneColor(theme, "warning") }), + danger: (theme) => ({ color: toneColor(theme, "danger") }), + info: (theme) => ({ color: toneColor(theme, "info") }), +}; + +/** + * A plugin's badge on the line under a workspace title, drawn like the row's own peers: one glyph + * at the line's size and a short word, in the color of the state it reports. The plugin owns the + * slot, so the badge draws no separator. + */ +export function WorkspaceRowBadge({ + icon, + label, + tone = "muted", + accessibilityLabel, +}: WorkspaceRowBadgeProps) { + const itemTitle = useContext(WorkspaceRowBadgeTitleContext); + // Parsed at render, not registration, so an invalid icon throws to the item's boundary. + const parsedIcon = useMemo( + () => (icon === undefined ? null : parsePluginIcon("Workspace row badge", icon)), + [icon], + ); + if (!parsedIcon && !label) return null; + return ( + + {parsedIcon ? ( + + ) : null} + {label ? ( + + {label} + + ) : null} + + ); +} + +// Read inside render, never into a module-scope table — see docs/unistyles.md. +function textToneStyle(tone: WorkspaceRowBadgeTone) { + if (tone === "success") return styles.success; + if (tone === "warning") return styles.warning; + if (tone === "danger") return styles.danger; + if (tone === "info") return styles.info; + return styles.muted; +} + +const styles = StyleSheet.create((theme) => ({ + item: { + flexDirection: "row", + alignItems: "center", + gap: 3, + minWidth: 0, + flexShrink: 1, + }, + text: { + fontSize: theme.fontSize.sm, + lineHeight: 16, + flexShrink: 1, + }, + muted: { color: toneColor(theme, "muted") }, + success: { color: toneColor(theme, "success") }, + warning: { color: toneColor(theme, "warning") }, + danger: { color: toneColor(theme, "danger") }, + info: { color: toneColor(theme, "info") }, +})); diff --git a/packages/app/src/plugins/workspace-row-badge-items/model.test.ts b/packages/app/src/plugins/workspace-row-badge-items/model.test.ts new file mode 100644 index 0000000000..8bcad76426 --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/model.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import type { InstalledPlugin } from "../types"; +import { groupPluginWorkspaceRowBadgeItems, isWorkspaceRowBadgeItemVisible } from "./model"; + +function Item() { + return null; +} + +function installed(id: string, serverId: string, itemIds: string[]): InstalledPlugin { + return { + id, + serverId, + locale: "en", + i18n: { resolve: (text: string) => text }, + workspaceRowBadgeItems: itemIds.map((itemId) => ({ + id: itemId, + title: `${id} ${itemId}`, + icon: "Gauge", + Component: Item, + })), + } as unknown as InstalledPlugin; +} + +describe("groupPluginWorkspaceRowBadgeItems", () => { + it("lists each plugin item once across hosts, in install order", () => { + const groups = groupPluginWorkspaceRowBadgeItems([ + installed("status", "host-a", ["state"]), + installed("asks", "host-a", ["open"]), + installed("status", "host-b", ["state"]), + ]); + expect(groups.map(({ key, title }) => ({ key, title }))).toEqual([ + { key: "status/state", title: "status state" }, + { key: "asks/open", title: "asks open" }, + ]); + }); +}); + +describe("isWorkspaceRowBadgeItemVisible", () => { + it("shows items until they are switched off", () => { + expect(isWorkspaceRowBadgeItemVisible({}, "status/state")).toBe(true); + expect(isWorkspaceRowBadgeItemVisible({ "status/state": true }, "status/state")).toBe(true); + expect(isWorkspaceRowBadgeItemVisible({ "status/state": false }, "status/state")).toBe(false); + }); +}); diff --git a/packages/app/src/plugins/workspace-row-badge-items/model.ts b/packages/app/src/plugins/workspace-row-badge-items/model.ts new file mode 100644 index 0000000000..6f937b3d5d --- /dev/null +++ b/packages/app/src/plugins/workspace-row-badge-items/model.ts @@ -0,0 +1,45 @@ +import type { PluginIcon } from "@getpaseo/plugin/client"; +import type { InstalledPlugin } from "../types"; + +/** One workspace row badge item, coalesced across every host that contributes it. */ +export interface PluginWorkspaceRowBadgeItemGroup { + /** `/`: the key its Show toggle is stored under. */ + key: string; + pluginId: string; + itemId: string; + title: string; + icon: PluginIcon; +} + +export function workspaceRowBadgeItemKey(pluginId: string, itemId: string): string { + return `${pluginId}/${itemId}`; +} + +/** An item missing from the stored record has never been toggled, so it shows. */ +export function isWorkspaceRowBadgeItemVisible( + visibility: Readonly>, + key: string, +): boolean { + return visibility[key] !== false; +} + +/** Distinct items in install order, for the Show menu. Each host's copy draws on its own rows. */ +export function groupPluginWorkspaceRowBadgeItems( + plugins: readonly InstalledPlugin[], +): PluginWorkspaceRowBadgeItemGroup[] { + const groups = new Map(); + for (const plugin of plugins) { + for (const item of plugin.workspaceRowBadgeItems) { + const key = workspaceRowBadgeItemKey(plugin.id, item.id); + if (groups.has(key)) continue; + groups.set(key, { + key, + pluginId: plugin.id, + itemId: item.id, + title: plugin.i18n.resolve(item.title, plugin.locale), + icon: item.icon, + }); + } + } + return [...groups.values()]; +} diff --git a/packages/plugin/src/client/contracts.ts b/packages/plugin/src/client/contracts.ts index 1949e5506e..72dc1f954d 100644 --- a/packages/plugin/src/client/contracts.ts +++ b/packages/plugin/src/client/contracts.ts @@ -121,6 +121,22 @@ export interface PluginSidebarViewContribution Component: ComponentType; } +export interface PluginWorkspaceRowBadgeItemProps extends PluginHostProps { + workspaceId: string; +} + +/** + * Part of the line under a workspace's title in the sidebar, on every workspace of the plugin's host. + * Render `WorkspaceRowBadge`, or nothing when there is nothing to say about this workspace. + */ +export interface PluginWorkspaceRowBadgeItemContribution { + id: string; + /** The item's toggle in the sidebar's Show menu. */ + title: Text; + icon: PluginIcon; + Component: ComponentType; +} + /** * A Lucide icon name, inline SVG markup, or a component. Components receive the surface's size * and color; buttons widen the props with their host and target context. @@ -214,6 +230,9 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl addSidebarHeaderItem(contribution: PluginSidebarItemContribution): PluginCleanup; addSidebarFooterItem(contribution: PluginSidebarItemContribution): PluginCleanup; addAgentPanel(contribution: PluginAgentPanelContribution): PluginCleanup; + addWorkspaceRowBadgeItem( + contribution: PluginWorkspaceRowBadgeItemContribution, + ): PluginCleanup; addWorkspacePanel(contribution: PluginWorkspacePanelContribution): PluginCleanup; addCommandCenterItem( contribution: PluginCommandCenterItemContribution, diff --git a/packages/plugin/src/client/index.ts b/packages/plugin/src/client/index.ts index 0597e56afe..9f99fcfb70 100644 --- a/packages/plugin/src/client/index.ts +++ b/packages/plugin/src/client/index.ts @@ -18,6 +18,8 @@ export type { PluginSidebarViewProps, PluginSidebarViewContribution, PluginSidebarItemContribution, + PluginWorkspaceRowBadgeItemProps, + PluginWorkspaceRowBadgeItemContribution, PluginIcon, PluginPanelLocation, PluginOpenPanelOptions, diff --git a/packages/plugin/src/client/ui.ts b/packages/plugin/src/client/ui.ts index 30ad3e178a..f72880b027 100644 --- a/packages/plugin/src/client/ui.ts +++ b/packages/plugin/src/client/ui.ts @@ -173,6 +173,19 @@ export declare const SidebarRow: ComponentType; /** A line between groups of rows. Render it from a sidebar item's `Component`. */ export declare const SidebarSeparator: ComponentType; +export type WorkspaceRowBadgeTone = "muted" | "success" | "warning" | "danger" | "info"; +export interface WorkspaceRowBadgeProps { + /** A Lucide icon name, inline SVG, or a component. */ + icon?: SidebarIcon; + label?: string; + /** Default "muted". */ + tone?: WorkspaceRowBadgeTone; + /** Defaults to `label`, then the item's `title`. */ + accessibilityLabel?: string; +} +/** One item on a sidebar workspace row's meta line. Render it from a workspace row badge item's `Component`. */ +export declare const WorkspaceRowBadge: ComponentType; + /** Paseo's loading state. Fills the panel; the panel decides when to show it. */ export declare const Loading: ComponentType; diff --git a/plugin-examples/workspace-row-badges/README.md b/plugin-examples/workspace-row-badges/README.md new file mode 100644 index 0000000000..0973457e9f --- /dev/null +++ b/plugin-examples/workspace-row-badges/README.md @@ -0,0 +1,9 @@ +# Workspace row badges + +Install this directory as a plugin. Any workspace that needs input or has failed shows a badge on +the line under its title in the sidebar. Workspaces in any other state show nothing. + +The component reads its own data with `useWorkspace(workspaceId, selector)` and returns `null` when +it has nothing to say. **Show → Workspace attention** in the sidebar's display preferences toggles it. + +See the [reference](../../public-docs/plugins/reference.md#workspace-row-badge-items). diff --git a/plugin-examples/workspace-row-badges/index.client.tsx b/plugin-examples/workspace-row-badges/index.client.tsx new file mode 100644 index 0000000000..9aa371229f --- /dev/null +++ b/plugin-examples/workspace-row-badges/index.client.tsx @@ -0,0 +1,29 @@ +import { useWorkspace } from "@getpaseo/plugin/client"; +import type { + PluginClientContext, + PluginWorkspaceRowBadgeItemProps, +} from "@getpaseo/plugin/client"; +import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; + +function WorkspaceAttention({ workspaceId }: PluginWorkspaceRowBadgeItemProps) { + const status = useWorkspace(workspaceId, (workspace) => workspace.status); + if (status === "needs_input") { + return ; + } + if (status === "failed") { + return ; + } + return null; +} + +export default function contribute(client: PluginClientContext) { + // Apps older than this API do not have the method, and requirements.paseo cannot exclude them. + if (!client.addWorkspaceRowBadgeItem) return () => {}; + client.addWorkspaceRowBadgeItem({ + id: "attention", + title: "Workspace attention", + icon: "CircleAlert", + Component: WorkspaceAttention, + }); + return () => {}; +} diff --git a/plugin-examples/workspace-row-badges/paseo-plugin.json b/plugin-examples/workspace-row-badges/paseo-plugin.json new file mode 100644 index 0000000000..3c824820fb --- /dev/null +++ b/plugin-examples/workspace-row-badges/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "workspace-row-badges", "requirements": { "paseo": ">=0.16.0" } } diff --git a/public-docs/plugins/migration.md b/public-docs/plugins/migration.md index a2cd723ff5..6021e193f5 100644 --- a/public-docs/plugins/migration.md +++ b/public-docs/plugins/migration.md @@ -67,30 +67,31 @@ is a compile error. Use this table as the complete registration checklist. -| Old registration and location | New registration and location | -| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| `plugin.handle(contract, handler)` in the old root entry | `server.handle(contract, handler)` in `index.server.ts` | -| `plugin.addSurface(id, Component)` in the old root entry | `client.addScreen({ id, title, Component })` in `index.client.tsx` | -| `plugin.addSidebarItem({ id, title, icon, surface })` in the old root entry | `client.addSidebarHeaderItem({ id, title, Component })` in `index.client.tsx`; see [sidebar items](reference#sidebar-items) | -| New sidebar footer contribution | `client.addSidebarFooterItem({ id, title, Component })` in `index.client.tsx` | -| New sidebar replacement view | `client.addSidebarView({ id, title, Component })` in `index.client.tsx`; see [sidebar views](sidebar-views) | -| New file panel contribution | `client.addFilePanel(panel)` in `index.client.tsx` | -| `plugin.addWorkspacePanel(panel)` in the old root entry | `client.addWorkspacePanel(panel)` in `index.client.tsx` | -| Agent panel with `context: "agent"` | `client.addAgentPanel(panel)` in `index.client.tsx`; omit `context` | -| `plugin.addCommandCenterItem(item)` in the old root entry | `client.addCommandCenterItem(item)` in `index.client.tsx` | -| `plugin.addClientSlashCommand(command)` in the old root entry | `client.addSlashCommand(command)` in `index.client.tsx` | -| `plugin.addClientSide(fn)` in the old root entry | Delete the wrapper and move the body of `fn` into the default client entry function | -| `client.addComposerPill(pill)` inside the old client callback | `client.addComposerPill(pill)` inside `index.client.tsx` or an imported `client/` function | -| New composer item contribution | `client.addComposerItem(item)` in `index.client.tsx`; see [composer items](reference#composer-items) | -| New New workspace item contribution | `client.addNewWorkspaceItem(item)` in `index.client.tsx`; see [New workspace items](reference#new-workspace-items) | -| New header contribution | `client.addHeaderButton({ id, workspaceId, button })` | -| `plugin.addAttachmentSource(source)` in the old root entry | `client.addAttachmentSource(source)` in `index.client.tsx` | -| New settings screen contribution | `client.addSettingsScreen(screen)` in `index.client.tsx`; see [settings screens](reference#settings-screens) | -| `plugin.addTheme(theme)` in the old root entry | `client.addTheme(theme)` in `index.client.tsx` | -| `plugin.addTimelineTransformer(transformer)` in the old root entry | `client.addTimelineTransformer(transformer)` in `index.client.tsx` | -| `plugin.addTimelineRenderer(renderer)` in the old root entry | `client.addTimelineRenderer(renderer)` in `index.client.tsx` | -| `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` in shared files | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | -| `ZodOutput` handler parameter types | `RpcInput` from `@getpaseo/plugin`; `RpcOutput` for return types | +| Old registration and location | New registration and location | +| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `plugin.handle(contract, handler)` in the old root entry | `server.handle(contract, handler)` in `index.server.ts` | +| `plugin.addSurface(id, Component)` in the old root entry | `client.addScreen({ id, title, Component })` in `index.client.tsx` | +| `plugin.addSidebarItem({ id, title, icon, surface })` in the old root entry | `client.addSidebarHeaderItem({ id, title, Component })` in `index.client.tsx`; see [sidebar items](reference#sidebar-items) | +| New sidebar footer contribution | `client.addSidebarFooterItem({ id, title, Component })` in `index.client.tsx` | +| New sidebar replacement view | `client.addSidebarView({ id, title, Component })` in `index.client.tsx`; see [sidebar views](sidebar-views) | +| New badge on sidebar workspace rows | `client.addWorkspaceRowBadgeItem({ id, title, icon, Component })` in `index.client.tsx`; see [workspace row badge items](reference#workspace-row-badge-items) | +| New file panel contribution | `client.addFilePanel(panel)` in `index.client.tsx` | +| `plugin.addWorkspacePanel(panel)` in the old root entry | `client.addWorkspacePanel(panel)` in `index.client.tsx` | +| Agent panel with `context: "agent"` | `client.addAgentPanel(panel)` in `index.client.tsx`; omit `context` | +| `plugin.addCommandCenterItem(item)` in the old root entry | `client.addCommandCenterItem(item)` in `index.client.tsx` | +| `plugin.addClientSlashCommand(command)` in the old root entry | `client.addSlashCommand(command)` in `index.client.tsx` | +| `plugin.addClientSide(fn)` in the old root entry | Delete the wrapper and move the body of `fn` into the default client entry function | +| `client.addComposerPill(pill)` inside the old client callback | `client.addComposerPill(pill)` inside `index.client.tsx` or an imported `client/` function | +| New composer item contribution | `client.addComposerItem(item)` in `index.client.tsx`; see [composer items](reference#composer-items) | +| New New workspace item contribution | `client.addNewWorkspaceItem(item)` in `index.client.tsx`; see [New workspace items](reference#new-workspace-items) | +| New header contribution | `client.addHeaderButton({ id, workspaceId, button })` | +| `plugin.addAttachmentSource(source)` in the old root entry | `client.addAttachmentSource(source)` in `index.client.tsx` | +| New settings screen contribution | `client.addSettingsScreen(screen)` in `index.client.tsx`; see [settings screens](reference#settings-screens) | +| `plugin.addTheme(theme)` in the old root entry | `client.addTheme(theme)` in `index.client.tsx` | +| `plugin.addTimelineTransformer(transformer)` in the old root entry | `client.addTimelineTransformer(transformer)` in `index.client.tsx` | +| `plugin.addTimelineRenderer(renderer)` in the old root entry | `client.addTimelineRenderer(renderer)` in `index.client.tsx` | +| `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` in shared files | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | +| `ZodOutput` handler parameter types | `RpcInput` from `@getpaseo/plugin`; `RpcOutput` for return types | Register the screen that replaces an `addSidebarItem` under that item's `id` to keep saved links working. A `/plugin//sidebar/` link, and the older `/plugin//`, opens the diff --git a/public-docs/plugins/migration.zh-CN.md b/public-docs/plugins/migration.zh-CN.md index df74652d4b..9ca601600c 100644 --- a/public-docs/plugins/migration.zh-CN.md +++ b/public-docs/plugins/migration.zh-CN.md @@ -60,29 +60,30 @@ my-plugin/ 把下表作为完整的注册检查清单。 -| 旧的注册及位置 | 新的注册及位置 | -| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| 旧根入口中的 `plugin.handle(contract, handler)` | `index.server.ts` 中的 `server.handle(contract, handler)` | -| 旧根入口中的 `plugin.addSurface(id, Component)` | `index.client.tsx` 中的 `client.addScreen({ id, title, Component })` | -| 旧根入口中的 `plugin.addSidebarItem({ id, title, icon, surface })` | `index.client.tsx` 中的 `client.addSidebarHeaderItem({ id, title, Component })`;见[侧边栏项](reference#sidebar-items) | -| 新的侧边栏底部贡献 | `index.client.tsx` 中的 `client.addSidebarFooterItem({ id, title, Component })` | -| 新的文件面板贡献 | `index.client.tsx` 中的 `client.addFilePanel(panel)` | -| 旧根入口中的 `plugin.addWorkspacePanel(panel)` | `index.client.tsx` 中的 `client.addWorkspacePanel(panel)` | -| 带有 `context: "agent"` 的 Agent 面板 | `index.client.tsx` 中的 `client.addAgentPanel(panel)`;省略 `context` | -| 旧根入口中的 `plugin.addCommandCenterItem(item)` | `index.client.tsx` 中的 `client.addCommandCenterItem(item)` | -| 旧根入口中的 `plugin.addClientSlashCommand(command)` | `index.client.tsx` 中的 `client.addSlashCommand(command)` | -| 旧根入口中的 `plugin.addClientSide(fn)` | 删除这层包装,把 `fn` 的函数体移入默认的客户端入口函数 | -| 旧客户端回调中的 `client.addComposerPill(pill)` | `index.client.tsx` 或被导入的 `client/` 函数中的 `client.addComposerPill(pill)` | -| 新的编辑器项贡献 | `index.client.tsx` 中的 `client.addComposerItem(item)`;见[编辑器项](reference#composer-items) | -| 新的“新建工作区”项贡献 | `index.client.tsx` 中的 `client.addNewWorkspaceItem(item)`;见[新建工作区项](reference#new-workspace-items) | -| 新的标题栏贡献 | `client.addHeaderButton({ id, workspaceId, button })` | -| 旧根入口中的 `plugin.addAttachmentSource(source)` | `index.client.tsx` 中的 `client.addAttachmentSource(source)` | -| 新的设置界面贡献 | `index.client.tsx` 中的 `client.addSettingsScreen(screen)`;见[设置界面](reference#settings-screens) | -| 旧根入口中的 `plugin.addTheme(theme)` | `index.client.tsx` 中的 `client.addTheme(theme)` | -| 旧根入口中的 `plugin.addTimelineTransformer(transformer)` | `index.client.tsx` 中的 `client.addTimelineTransformer(transformer)` | -| 旧根入口中的 `plugin.addTimelineRenderer(renderer)` | `index.client.tsx` 中的 `client.addTimelineRenderer(renderer)` | -| shared 文件中的 `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | -| 处理函数参数类型 `ZodOutput` | 来自 `@getpaseo/plugin` 的 `RpcInput`;返回类型使用 `RpcOutput` | +| 旧的注册及位置 | 新的注册及位置 | +| --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| 旧根入口中的 `plugin.handle(contract, handler)` | `index.server.ts` 中的 `server.handle(contract, handler)` | +| 旧根入口中的 `plugin.addSurface(id, Component)` | `index.client.tsx` 中的 `client.addScreen({ id, title, Component })` | +| 旧根入口中的 `plugin.addSidebarItem({ id, title, icon, surface })` | `index.client.tsx` 中的 `client.addSidebarHeaderItem({ id, title, Component })`;见[侧边栏项](reference#sidebar-items) | +| 新的侧边栏底部贡献 | `index.client.tsx` 中的 `client.addSidebarFooterItem({ id, title, Component })` | +| 新的工作区行徽章贡献 | `index.client.tsx` 中的 `client.addWorkspaceRowBadgeItem({ id, title, icon, Component })`;见[工作区行徽章项](reference#workspace-row-badge-items) | +| 新的文件面板贡献 | `index.client.tsx` 中的 `client.addFilePanel(panel)` | +| 旧根入口中的 `plugin.addWorkspacePanel(panel)` | `index.client.tsx` 中的 `client.addWorkspacePanel(panel)` | +| 带有 `context: "agent"` 的 Agent 面板 | `index.client.tsx` 中的 `client.addAgentPanel(panel)`;省略 `context` | +| 旧根入口中的 `plugin.addCommandCenterItem(item)` | `index.client.tsx` 中的 `client.addCommandCenterItem(item)` | +| 旧根入口中的 `plugin.addClientSlashCommand(command)` | `index.client.tsx` 中的 `client.addSlashCommand(command)` | +| 旧根入口中的 `plugin.addClientSide(fn)` | 删除这层包装,把 `fn` 的函数体移入默认的客户端入口函数 | +| 旧客户端回调中的 `client.addComposerPill(pill)` | `index.client.tsx` 或被导入的 `client/` 函数中的 `client.addComposerPill(pill)` | +| 新的编辑器项贡献 | `index.client.tsx` 中的 `client.addComposerItem(item)`;见[编辑器项](reference#composer-items) | +| 新的“新建工作区”项贡献 | `index.client.tsx` 中的 `client.addNewWorkspaceItem(item)`;见[新建工作区项](reference#new-workspace-items) | +| 新的标题栏贡献 | `client.addHeaderButton({ id, workspaceId, button })` | +| 旧根入口中的 `plugin.addAttachmentSource(source)` | `index.client.tsx` 中的 `client.addAttachmentSource(source)` | +| 新的设置界面贡献 | `index.client.tsx` 中的 `client.addSettingsScreen(screen)`;见[设置界面](reference#settings-screens) | +| 旧根入口中的 `plugin.addTheme(theme)` | `index.client.tsx` 中的 `client.addTheme(theme)` | +| 旧根入口中的 `plugin.addTimelineTransformer(transformer)` | `index.client.tsx` 中的 `client.addTimelineTransformer(transformer)` | +| 旧根入口中的 `plugin.addTimelineRenderer(renderer)` | `index.client.tsx` 中的 `client.addTimelineRenderer(renderer)` | +| shared 文件中的 `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin/server"` | `import { defineRpc, defineAttachmentSource } from "@getpaseo/plugin"` | +| 处理函数参数类型 `ZodOutput` | 来自 `@getpaseo/plugin` 的 `RpcInput`;返回类型使用 `RpcOutput` | 用原 `addSidebarItem` 项的 `id` 注册替代它的界面,这样已保存的链接仍然有效。`/plugin//sidebar/` 链接以及更早的 `/plugin//` 链接,会打开具有该 `id` 的 `addSidebarItem`,否则打开具有该 `id` 的界面。 diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index cdd847ba7f..2fc43da606 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -854,6 +854,60 @@ function hideAlerts() { } ``` +### Workspace row badge items + +`addWorkspaceRowBadgeItem({ id, title, icon, Component })` adds an item to the line under each workspace +title in the sidebar, after the row's own items (host, pull request, checks, services, labels). +`title` and `icon` label the item's toggle in the sidebar's **Show** menu, in a separate plugin group +below a separator. Items start visible. + +`Component` renders once per workspace row on the plugin's host and receives +`PluginWorkspaceRowBadgeItemProps`: `theme`, `host`, `layout`, and `workspaceId`. Render +`WorkspaceRowBadge` from `@getpaseo/plugin/client/ui`, or `null` when there is nothing to say about +the workspace: + +| Prop | Meaning | +| -------------------- | ------------------------------------------------------------------------------ | +| `icon` | Optional. Any [icon](#icons) form, drawn at the line's glyph size. | +| `label` | Optional. A short word. A badge with neither `icon` nor `label` draws nothing. | +| `tone` | `"muted"` (default), `"success"`, `"warning"`, `"danger"`, or `"info"`. | +| `accessibilityLabel` | Defaults to `label`, then the item's `title`. | + +The line adds no separator around your badges, and returning `null` leaves no gap. Render as many +badges as you like. Every row +renders the component, so share one query across rows instead of fetching per workspace: the +plugin's React Query client is shared by all of its components on a host. + +```tsx +import type { PluginWorkspaceRowBadgeItemProps } from "@getpaseo/plugin/client"; +import { useRpc } from "@getpaseo/plugin/client"; +import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; +import { useQuery } from "@tanstack/react-query"; + +function ReviewState({ workspaceId }: PluginWorkspaceRowBadgeItemProps) { + const list = useRpc(reviewStates); + const { data } = useQuery({ + queryKey: ["review-states"], + queryFn: () => list({}), + refetchInterval: 5000, + }); + const state = data?.[workspaceId]; + if (!state) return null; + return ; +} + +client.addWorkspaceRowBadgeItem({ + id: "review", + title: "Review", + icon: "Eye", + Component: ReviewState, +}); +``` + +Apps older than this API have no `addWorkspaceRowBadgeItem`; check for it before calling. + +See the [workspace row badges example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/workspace-row-badges). + ## Host UI Import Paseo-owned UI from `@getpaseo/plugin/client/ui` in client code. This example diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 7ab38e8587..4ee3a6c793 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -705,6 +705,51 @@ function hideAlerts() { } ``` +### 工作区行徽章项 {#workspace-row-badge-items} + +`addWorkspaceRowBadgeItem({ id, title, icon, Component })` 在侧边栏每个工作区标题下方的那一行中添加一项,位于该行自带的各项(主机、拉取请求、检查、服务、标签)之后。`title` 和 `icon` 用于标注该项在侧边栏 **Show** 菜单中的开关,插件开关位于分隔线下方的独立分组中。各项默认可见。 + +`Component` 为插件所在主机上的每个工作区行渲染一次,并接收 `PluginWorkspaceRowBadgeItemProps`:`theme`、`host`、`layout` 和 `workspaceId`。渲染 `@getpaseo/plugin/client/ui` 中的 `WorkspaceRowBadge`;工作区没有需要说明的内容时返回 `null`: + +| 属性 | 含义 | +| -------------------- | --------------------------------------------------------------------- | +| `icon` | 可选。任意[图标](#icons)形式,以该行的图标尺寸绘制。 | +| `label` | 可选。一个简短的词。既没有 `icon` 也没有 `label` 的徽章不绘制。 | +| `tone` | `"muted"`(默认)、`"success"`、`"warning"`、`"danger"` 或 `"info"`。 | +| `accessibilityLabel` | 默认为 `label`,其次是该项的 `title`。 | + +该行不会在你的徽章周围添加分隔符,返回 `null` 不会留下空隙。可以渲染任意数量的徽章。每一行都会渲染该组件,所以请在各行之间共享一次查询,而不是为每个工作区单独获取:插件的 React Query 客户端由它在某台主机上的所有组件共享。 + +```tsx +import type { PluginWorkspaceRowBadgeItemProps } from "@getpaseo/plugin/client"; +import { useRpc } from "@getpaseo/plugin/client"; +import { WorkspaceRowBadge } from "@getpaseo/plugin/client/ui"; +import { useQuery } from "@tanstack/react-query"; + +function ReviewState({ workspaceId }: PluginWorkspaceRowBadgeItemProps) { + const list = useRpc(reviewStates); + const { data } = useQuery({ + queryKey: ["review-states"], + queryFn: () => list({}), + refetchInterval: 5000, + }); + const state = data?.[workspaceId]; + if (!state) return null; + return ; +} + +client.addWorkspaceRowBadgeItem({ + id: "review", + title: "Review", + icon: "Eye", + Component: ReviewState, +}); +``` + +早于此 API 的应用没有 `addWorkspaceRowBadgeItem`;调用前请先检查它是否存在。 + +参见[工作区行徽章示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/workspace-row-badges)。 + ## 宿主 UI {#host-ui} 在客户端代码中从 `@getpaseo/plugin/client/ui` 导入由 Paseo 提供的 UI。下面的示例会打开一个受控的弹窗、渲染一个宿主图标,并用 toast 确认操作: From ec520979242ecbc2f99337d708c32dc3297443a4 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 19:59:28 +0700 Subject: [PATCH 028/160] fix(usage): keep failed usage visible in sidebar (#9594) Retain the last successful percentages in the sidebar after a failed refresh, with a red warning that opens the existing error detail. Share snapshot selection between cards, default pins, and summary rendering so the surfaces no longer disagree about retained usage. --- packages/app/e2e/browser/usage-modal.spec.ts | 24 ++++++++- packages/app/src/usage/model.ts | 53 ++++++++++++++------ packages/app/src/usage/pinned.test.ts | 28 ++++++++++- packages/app/src/usage/pinned.ts | 18 +++++-- packages/app/src/usage/preferences.ts | 7 +-- packages/app/src/usage/sidebar-item.tsx | 44 +++++++++++++--- 6 files changed, 142 insertions(+), 32 deletions(-) diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 6835e01bcb..cdf21e56d6 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -25,6 +25,7 @@ import { } from "../support/helpers/usage-login"; import { claudeAndCodexReports, + closeUsage, expectPinnedUsage, openCompactSidebar, openUsageFromIcon, @@ -79,12 +80,17 @@ function twoHoursAgo(): string { } /** Set PASEO_QA_SCREENSHOT_DIR to keep a QA screenshot. */ -async function qaScreenshot(page: Page, name: string) { +async function qaScreenshot(page: Page, name: string, target: "page" | "summary" = "page") { const directory = process.env.PASEO_QA_SCREENSHOT_DIR; if (!directory) return; await page.waitForTimeout(600); await page.addStyleTag({ content: ".__expo_fast_refresh { display: none !important; }" }); - await page.screenshot({ path: path.join(directory, `${name}.png`) }); + const file = path.join(directory, `${name}.png`); + if (target === "summary") { + await usageItem(page).screenshot({ path: file }); + return; + } + await page.screenshot({ path: file }); } function hostFilter(page: Page) { @@ -628,6 +634,15 @@ for (const compact of [false, true]) { await refreshLoginUsage(page); await expectRetainedLoginUsage(page, "Claude: Rate limited"); await expectLoginUsageFreshness(page, "Last updated 1h ago", compact); + await expectPinnedUsage(page, ["42% Weekly"]); + await expect(usageItem(page).getByTestId("sidebar-usage-error")).toBeVisible(); + await expect(usageItem(page)).toHaveAccessibleName(/Unable to refresh usage/); + await qaScreenshot(page, `usage-error-detail-${compact ? "compact" : "desktop"}`); + await closeUsage(page); + await qaScreenshot(page, `usage-error-summary-${compact ? "compact" : "desktop"}`, "summary"); + await openUsageFromItem(page); + await expectRetainedLoginUsage(page, "Claude: Rate limited"); + await refreshLoginUsage(page); await expectRetainedLoginUsage(page, "Claude: Rate limited"); await expectLoginUsageFreshness(page, "Last updated 1h ago", compact); @@ -639,6 +654,8 @@ for (const compact of [false, true]) { await refreshLoginUsage(page); await expectRetainedLoginUsage(page, "Claude: No active quota"); await expectLoginUsageFreshness(page, "Last updated 1h ago", compact); + await expectPinnedUsage(page, ["42% Weekly"]); + await expect(usageItem(page).getByTestId("sidebar-usage-error")).toHaveCount(0); await fixture.setReport({ status: "available", @@ -647,6 +664,9 @@ for (const compact of [false, true]) { await page.clock.setFixedTime(new Date(Date.now() + 150_000)); await refreshLoginUsage(page); await expectLoginUsageOnly(page, "43% used"); + await expectPinnedUsage(page, ["43% Weekly"]); + await expect(usageItem(page).getByTestId("sidebar-usage-error")).toHaveCount(0); + await expect(usageItem(page)).not.toHaveAccessibleName(/Unable to refresh usage/); await advanceUsageClock(page, 60_000); await expect(page.getByText("42% used", { exact: true })).toHaveCount(0); await expectLoginUsageFreshness(page, "Updated 2m ago", compact); diff --git a/packages/app/src/usage/model.ts b/packages/app/src/usage/model.ts index bbe183dcd0..ac2cf62db2 100644 --- a/packages/app/src/usage/model.ts +++ b/packages/app/src/usage/model.ts @@ -2,7 +2,13 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; import { usageCopy } from "./copy"; import type { UsageDisplayAs } from "./preferences"; -import type { UsageReport, UsageReportEntry, UsageView, UsageWindow } from "./types"; +import type { + AvailableUsageReport, + UsageReport, + UsageReportEntry, + UsageView, + UsageWindow, +} from "./types"; export function usedPercent(window: UsageWindow): number | null { if (window.usedPct != null) return window.usedPct; @@ -205,13 +211,34 @@ export function resolveUsageModalHostId(choice: UsageHostChoice): string | null return picked?.serverId ?? resolveUsageHostId(choice) ?? connected[0]?.serverId ?? null; } +export interface UsageSnapshot { + report: AvailableUsageReport; + successfulAt: string; + retained: boolean; +} + +/** The latest successful values and their freshness, independent of the latest attempt's outcome. */ +export function resolveUsageSnapshot(entry: UsageReportEntry): UsageSnapshot | null { + if (entry.report.status === "available") { + // COMPAT(usageSuccessfulAt): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. + // Old daemons expose only attempt time for available reports, never for failures. + return { + report: entry.report, + successfulAt: entry.successfulAt ?? entry.fetchedAt, + retained: false, + }; + } + // COMPAT(usageLastSuccessful): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. + // Older daemons cannot provide history; a failed attempt is never a successful update. + const retained = entry.lastSuccessful; + if (!retained) return null; + return { report: retained.report, successfulAt: retained.fetchedAt, retained: true }; +} + /** Current outcome owns messages; only a successful poll owns values and freshness. */ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) { const available = entry.report.status === "available"; - // COMPAT(usageLastSuccessful): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. - // Older daemons cannot provide history; a failed attempt is never a successful update. - const snapshot = available ? null : (entry.lastSuccessful ?? null); - const content = entry.report.status === "available" ? entry.report : (snapshot?.report ?? null); + const snapshot = resolveUsageSnapshot(entry); const messages: string[] = []; if (!available) { if (entry.loginErrors) @@ -224,16 +251,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) { else messages.push(usageProblemText(entry.report, t)); } return { - windows: content?.windows ?? [], - balances: content?.balances ?? [], - details: content?.details ?? [], - planLabel: content?.planLabel ?? null, - // COMPAT(usageSuccessfulAt): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0. - // Old daemons expose only attempt time for available reports, never for failures. - successfulAt: available - ? (entry.successfulAt ?? entry.fetchedAt) - : (snapshot?.fetchedAt ?? null), - retained: snapshot !== null, + windows: snapshot?.report.windows ?? [], + balances: snapshot?.report.balances ?? [], + details: snapshot?.report.details ?? [], + planLabel: snapshot?.report.planLabel ?? null, + successfulAt: snapshot?.successfulAt ?? null, + retained: snapshot?.retained ?? false, messages, }; } diff --git a/packages/app/src/usage/pinned.test.ts b/packages/app/src/usage/pinned.test.ts index 410b81575f..f16f001d47 100644 --- a/packages/app/src/usage/pinned.test.ts +++ b/packages/app/src/usage/pinned.test.ts @@ -139,6 +139,7 @@ describe("resolvePinnedUsage", () => { expect(sources[0]).toEqual({ key: "claude:default", icon: "", + hasError: false, windows: [ { key: "claude:default/five-hour", @@ -257,7 +258,7 @@ describe("resolvePinnedUsage", () => { }); }); -it("keeps unavailable and error reports out of the sidebar summary even with retained data", () => { +it("shows retained windows and marks errored sources in the sidebar summary", () => { if (claude.report.status !== "available" || codex.report.status !== "available") throw new Error("fixtures must be available"); const expired: UsageReportEntry = { @@ -273,7 +274,30 @@ it("keeps unavailable and error reports out of the sidebar summary even with ret lastSuccessful: { fetchedAt: codex.fetchedAt, report: codex.report }, report: { status: "error", error: "Store deleted" }, }; - expect(resolvePinnedUsage([expired, failed], preferences(null))).toEqual([]); + const expected = [ + { key: "claude:default", hasError: false, windows: ["31%"] }, + { key: "codex:default", hasError: true, windows: ["12%"] }, + ]; + const summarize = (pins: UsagePreferences["pins"]) => + resolvePinnedUsage([expired, failed], preferences(pins)).map((source) => ({ + key: source.key, + hasError: source.hasError, + windows: source.windows.map((window) => window.percentText), + })); + + expect(summarize(null)).toEqual(expected); + expect( + summarize([ + { sourceId: "claude", windowId: "five-hour" }, + { sourceId: "codex", windowId: "weekly" }, + ]), + ).toEqual(expected); + expect( + resolvePinnedUsage( + [{ ...failed, lastSuccessful: undefined }], + preferences([{ sourceId: "codex", windowId: "weekly" }]), + ), + ).toEqual([]); }); it("localizes pinned labels and meanings while preserving custom window names", async () => { diff --git a/packages/app/src/usage/pinned.ts b/packages/app/src/usage/pinned.ts index 21fd4cf06c..acce210a7c 100644 --- a/packages/app/src/usage/pinned.ts +++ b/packages/app/src/usage/pinned.ts @@ -1,7 +1,7 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; import { formatPct, formatDisplayPct, formatProviderUsageLabel } from "./format"; -import { displayPercent } from "./model"; +import { displayPercent, resolveUsageSnapshot } from "./model"; import { effectiveUsagePins, type UsagePreferences } from "./preferences"; import { windowTone } from "./tone"; import type { UsageReportEntry, UsageTone } from "./types"; @@ -23,6 +23,8 @@ export interface PinnedUsageWindow { export interface PinnedUsageSource { key: string; icon: string | null; + /** The displayed values are retained from before a failed refresh. */ + hasError: boolean; windows: PinnedUsageWindow[]; } @@ -74,8 +76,9 @@ export function resolvePinnedUsage( ): PinnedUsageSource[] { const pins = effectiveUsagePins(preferences, reports); return groupBySource(reports).flatMap((entry) => { - if (entry.report.status !== "available") return []; - const windows = entry.report.windows + const snapshot = resolveUsageSnapshot(entry); + if (!snapshot) return []; + const windows = snapshot.report.windows .filter( (window) => displayPercent(window, preferences.displayAs) !== null && @@ -94,6 +97,13 @@ export function resolvePinnedUsage( }; }); if (windows.length === 0) return []; - return [{ key: entry.id, icon: entry.icon ?? null, windows }]; + return [ + { + key: entry.id, + icon: entry.icon ?? null, + hasError: entry.report.status === "error", + windows, + }, + ]; }); } diff --git a/packages/app/src/usage/preferences.ts b/packages/app/src/usage/preferences.ts index e082870af6..b9c5c6fde9 100644 --- a/packages/app/src/usage/preferences.ts +++ b/packages/app/src/usage/preferences.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { displayPercent } from "./model"; +import { displayPercent, resolveUsageSnapshot } from "./model"; import type { UsageReportEntry } from "./types"; /** Whether percentages read as the share used or the share left. */ @@ -55,8 +55,9 @@ export function effectiveUsagePins( if (preferences.pins !== null) return preferences.pins; const pins: UsagePin[] = []; for (const entry of reports) { - if (entry.report.status !== "available") continue; - const withPercent = entry.report.windows.filter( + const snapshot = resolveUsageSnapshot(entry); + if (!snapshot) continue; + const withPercent = snapshot.report.windows.filter( (window) => displayPercent(window, preferences.displayAs) !== null, ); const marked = withPercent.filter((window) => window.summary); diff --git a/packages/app/src/usage/sidebar-item.tsx b/packages/app/src/usage/sidebar-item.tsx index bd4dfeb65e..a35202b369 100644 --- a/packages/app/src/usage/sidebar-item.tsx +++ b/packages/app/src/usage/sidebar-item.tsx @@ -8,6 +8,7 @@ import { type ReactNode, } from "react"; import { useTranslation } from "react-i18next"; +import { TriangleAlert } from "lucide-react-native"; import { Pressable, Text, @@ -15,7 +16,8 @@ import { type LayoutChangeEvent, type PressableStateCallbackType, } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import type { Theme } from "@/styles/theme"; import { useRetainedPanelActive } from "@/components/retained-panel"; import { useAppVisible } from "@/hooks/use-app-visible"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; @@ -35,6 +37,9 @@ import { } from "./pinned"; import { UsageModal } from "./usage-modal"; +const ThemedTriangleAlert = withUnistyles(TriangleAlert); +const errorIconColor = (theme: Theme) => ({ color: theme.colors.statusDanger }); + /** Each summary window with data on the usage host, under its source; empty while none has. */ export function useUsageSummary(): readonly PinnedUsageSource[] { const { t } = useTranslation(); @@ -60,7 +65,14 @@ export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSou const label = t(builtinSidebarNavLabelKey("usage")); const openUsage = useOpenSidebarUsage(); if (sources.length === 0) return null; - return ; + return ( + + ); } const OpenSidebarUsageContext = createContext<(() => void) | null>(null); @@ -95,9 +107,15 @@ export function useOpenSidebarUsage(): () => void { return openUsage; } -function pinnedUsageLabel(label: string, sources: readonly PinnedUsageSource[]): string { +function pinnedUsageLabel( + label: string, + sources: readonly PinnedUsageSource[], + errorLabel: string, +): string { const windows = sources.flatMap((source) => source.windows); - return `${label}: ${windows.map((window) => window.label).join(", ")}`; + const summary = windows.map((window) => window.label).join(", "); + const error = sources.some((source) => source.hasError) ? `, ${errorLabel}` : ""; + return `${label}: ${summary}${error}`; } function triggerStyle({ hovered }: PressableStateCallbackType & { hovered?: boolean }) { @@ -116,10 +134,12 @@ function layoutWidth(event: LayoutChangeEvent): number { function PinnedUsageTrigger({ label, sources, + errorLabel, onPress, }: { label: string; sources: readonly PinnedUsageSource[]; + errorLabel: string; onPress: () => void; }) { const [available, setAvailable] = useState(null); @@ -144,7 +164,7 @@ function PinnedUsageTrigger({ @@ -185,10 +205,17 @@ function PinnedUsageLine({ return sources.map((source, sourceIndex) => ( + {source.hasError ? ( + + ) : null} {source.windows.map((window, windowIndex) => { const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap; @@ -251,6 +278,11 @@ const styles = StyleSheet.create((theme) => ({ flexDirection: "row", alignItems: "center", }, + source: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1], + }, sourceGap: { marginLeft: theme.spacing[3], }, From cf9eaa8d29820c385dd733165cd57e44fa1773e8 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 19:59:42 +0700 Subject: [PATCH 029/160] Forge links use the daemon-resolved host and parent repository (#9576) * fix(forge): build web links from the host and repository the daemon resolves The app built forge links by parsing the origin remote itself, so an SSH config alias (git@github.com-work:...) produced https://github.com-work/... and a fork checkout sent #123 to the fork instead of the repository that owns the numbers. The daemon now publishes `forgeWeb` { host, referenceRepository? } on the workspace descriptor and on checkout status, and the app builds every forge URL from it. The host is the ssh -G resolved cloud host. referenceRepository is the fork's parent, read through an optional ForgeService.getReferenceRepository (GitHub, GitLab, Gitea family). Branch and file links stay on the origin repository because a feature branch usually exists only on the fork. Old daemons omit the field and the app derives links from the remote as before (tagged COMPAT(forgeWeb)). * fix(forge): keep the published web location tied to its remote and retry failed parent lookups - A web location resolved for one origin remote is no longer published after `git remote set-url`; it returns when the next forge refresh resolves the new remote. - The GitHub parent lookup rejects on a gh failure instead of returning null, so a network error is retried rather than cached as "this repository has no parent". - The pull request status poll retries a due lookup, so an idle workspace recovers without waiting for a forced refresh. - Workspace snapshot fixtures now expect `forgeWeb` for github.com remotes. * fix(forge): look up a fork's parent once per remote, on any checkout - A successful parent lookup is kept for the life of the remote instead of being repeated by every forced refresh (each push, fetch and branch switch). - The lookup no longer waits on the pull request status's auth state, which is "no_remote" on a detached HEAD; a failed or signed-out lookup is retried on the next forced refresh or poll. * fix(forge): resolve the new remote's web location when origin changes `git remote set-url` reaches the daemon as a git-only refresh, which stopped publishing the old remote's forgeWeb but never resolved the new one, so links fell back to parsing the remote. A git refresh that finds the remote changed since the last forge refresh now runs a forced forge refresh, which also probes a newly seen SSH alias. * fix(forge): keep the alias-resolved host when a failed parent lookup is retried The poll's retry resolved the forge with the synchronous resolver, which reports the raw SSH alias as the host. A lookup that settled on retry then published and kept `github.com-work` as the web host. The retry now uses the async resolver, like the forge refresh, so the host means the same thing on both paths. * fix(forge): treat a Gitea or GitLab API error body as a failed parent lookup `tea api` exits 0 on HTTP errors, so an error body parsed as a repository without a parent and was cached as "not a fork". The repository schemas now require the repository's own name, so an error body rejects and the lookup is retried. The shorthand provider also keys its context on the forgeWeb strings, so unrelated workspace updates no longer re-render every Markdown message. * fix(forge): keep the parent lookup off the workspace refresh path * fix(forge): keep a parent answer that lands during a refresh * test(forge): make the parent lookup tests Windows-safe * fix(forge): drain the background parent lookup on dispose * test(forge): retry temp cleanup after the poll lookup on Windows --- docs/forge-providers.md | 32 + .../app/src/git/forge-shorthand/index.tsx | 17 +- .../src/git/forge-shorthand/shorthand.test.ts | 11 + .../app/src/git/forge-shorthand/shorthand.ts | 7 +- packages/app/src/git/forge-url.test.ts | 78 +++ packages/app/src/git/forge-url.ts | 52 +- .../src/runtime/replica-cache/index.test.ts | 15 + .../app/src/runtime/replica-cache/index.ts | 3 + .../screens/workspace/workspace-screen.tsx | 6 +- packages/app/src/stores/session-store.ts | 2 + .../workspace/open-in-editor/planner.test.ts | 49 ++ .../src/workspace/open-in-editor/planner.ts | 6 + packages/protocol/src/git-remote.ts | 20 + packages/protocol/src/messages.ts | 19 + .../protocol/src/messages.workspaces.test.ts | 9 + .../server/checkout/status-projection.test.ts | 41 +- .../src/server/checkout/status-projection.ts | 2 + packages/server/src/server/forge-web.ts | 79 +++ packages/server/src/server/session.ts | 1 + .../src/server/session.workspaces.test.ts | 39 ++ ...it-service.observation.integration.test.ts | 554 ++++++++++++++++++ .../workspace-git-service.primitive.test.ts | 10 +- .../src/server/workspace-git-service.test.ts | 2 + .../src/server/workspace-git-service.ts | 131 ++++- packages/server/src/services/forge-service.ts | 7 + .../server/src/services/gitea-service.test.ts | 35 ++ packages/server/src/services/gitea-service.ts | 21 + .../src/services/github-service.test.ts | 59 ++ .../server/src/services/github-service.ts | 87 ++- .../src/services/gitlab-service.test.ts | 32 + .../server/src/services/gitlab-service.ts | 24 + 31 files changed, 1403 insertions(+), 47 deletions(-) create mode 100644 packages/server/src/server/forge-web.ts diff --git a/docs/forge-providers.md b/docs/forge-providers.md index 2d31eaef2f..62c91611f8 100644 --- a/docs/forge-providers.md +++ b/docs/forge-providers.md @@ -113,6 +113,38 @@ host that is either a known cloud host or one the CLI is already authenticated to. Adapter probes must not make anonymous HTTP requests to remote-derived hosts, and adapters must not route credentials to an unauthenticated host. +### Web links: `forgeWeb` + +The daemon publishes `forgeWeb` on the workspace descriptor and on +`checkout_status_response`. The app builds every forge URL from it instead of +parsing `origin` itself. + +- `host` is the browsable host: an `ssh -G` alias such as `github.com-work` and + a cloud SSH host such as `ssh.github.com` resolve to the cloud host; self-hosted + hosts pass through. +- `referenceRepository` is the repository that owns issue and change-request + numbers: the parent when `origin` is a fork. `#123` links there; `owner/repo#123` + keeps the repository you wrote. +- Branch and file links stay on the `origin` repository. A feature branch usually + exists only on the fork. + +An adapter opts into `referenceRepository` with the optional +`ForgeService.getReferenceRepository`. GitHub reads `parent` from `gh repo view`, +GitLab reads `forked_from_project` from `glab api`, and the Gitea family reads +`parent` from `tea api`. The lookup always names the `origin` repository +explicitly, so it does not depend on `gh`'s default-repository choice, and it +rejects on any CLI failure. `packages/server/src/server/forge-web.ts` keeps a +successful answer for as long as the remote stays the same. The first snapshot +publishes `{ host }` immediately and the reference repository follows in a later +update, so a slow or signed-out forge CLI never holds back the checkout's git +state or pull request status. A failed lookup (signed out, network down) leaves +links on `origin` and is retried by the next refresh or pull request status poll +once a minute has passed. + +Daemons older than v0.16.0 omit the field; the app then derives the host from the +remote and links `#N` to `origin`. That fallback is tagged `COMPAT(forgeWeb)` in +`packages/app/src/git/forge-url.ts`. + ## App Each app forge splits into two modules so pure logic never imports the client diff --git a/packages/app/src/git/forge-shorthand/index.tsx b/packages/app/src/git/forge-shorthand/index.tsx index 5e40874c0a..81bbcbf12e 100644 --- a/packages/app/src/git/forge-shorthand/index.tsx +++ b/packages/app/src/git/forge-shorthand/index.tsx @@ -1,3 +1,4 @@ +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import { createContext, useCallback, useContext, useMemo, type ReactNode } from "react"; import { createForgeShorthand, type ForgeShorthand } from "./shorthand"; @@ -9,13 +10,27 @@ const ForgeShorthandContext = createContext(null); export function ForgeShorthandProvider({ forge, remoteUrl, + forgeWeb, children, }: { forge: string | null | undefined; remoteUrl: string | null | undefined; + forgeWeb: ForgeWeb | null | undefined; children: ReactNode; }) { - const value = useMemo(() => createForgeShorthand({ forge, remoteUrl }), [forge, remoteUrl]); + // Keyed on the strings: the descriptor hands over a new `forgeWeb` object whenever any + // other workspace field changes, and a new context value re-renders every Markdown message. + const webHost = forgeWeb?.host; + const referenceRepository = forgeWeb?.referenceRepository; + const value = useMemo( + () => + createForgeShorthand({ + forge, + remoteUrl, + forgeWeb: webHost ? { host: webHost, referenceRepository } : null, + }), + [forge, remoteUrl, webHost, referenceRepository], + ); return {children}; } diff --git a/packages/app/src/git/forge-shorthand/shorthand.test.ts b/packages/app/src/git/forge-shorthand/shorthand.test.ts index 7da4ea1014..f135bbd48a 100644 --- a/packages/app/src/git/forge-shorthand/shorthand.test.ts +++ b/packages/app/src/git/forge-shorthand/shorthand.test.ts @@ -22,6 +22,17 @@ describe("createForgeShorthand", () => { expect(gitlab.resolve("g/sub/q#3")).toBe("https://gitlab.com/g/sub/q/-/issues/3"); }); + it("links numbers to the repository the daemon says owns them, but keeps explicit references", () => { + const fork = createForgeShorthand({ + forge: "github", + remoteUrl: "git@github.com-work:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + })!; + + expect(fork.resolve("#123")).toBe("https://github.com/main-owner/repo/issues/123"); + expect(fork.resolve("acme/tools#4")).toBe("https://github.com/acme/tools/issues/4"); + }); + it("only recognizes the sigils the forge declares", () => { expect(matches(github, "see #1 and !2")).toEqual(["#1"]); expect(github.resolve("!2")).toBeNull(); diff --git a/packages/app/src/git/forge-shorthand/shorthand.ts b/packages/app/src/git/forge-shorthand/shorthand.ts index 84a97bfb29..0b4af83174 100644 --- a/packages/app/src/git/forge-shorthand/shorthand.ts +++ b/packages/app/src/git/forge-shorthand/shorthand.ts @@ -1,3 +1,4 @@ +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import type { ForgeReferenceSigil } from "@/git/client-forge-module"; import { forgeFromRemoteUrl } from "@/git/forge"; import { getClientForgeLogicModule } from "@/git/forges"; @@ -26,12 +27,15 @@ const REFERENCE = new RegExp(String.raw`^(?:(${REPO}))?([#!])(${NUMBER})$`); export function createForgeShorthand(input: { forge: string | null | undefined; remoteUrl: string | null | undefined; + forgeWeb?: ForgeWeb | null; }): ForgeShorthand | null { const remoteUrl = input.remoteUrl; const forge = input.forge || forgeFromRemoteUrl(remoteUrl); if (!forge || !remoteUrl) return null; const sigils = forgeSigils(forge).filter( - (sigil) => buildForgeReferenceUrl(forge, { remoteUrl, sigil, number: 1 }) !== null, + (sigil) => + buildForgeReferenceUrl(forge, { remoteUrl, forgeWeb: input.forgeWeb, sigil, number: 1 }) !== + null, ); if (sigils.length === 0) return null; return { @@ -41,6 +45,7 @@ export function createForgeShorthand(input: { if (!match) return null; return buildForgeReferenceUrl(forge, { remoteUrl, + forgeWeb: input.forgeWeb, repo: match[1] ?? null, sigil: match[2] as ForgeReferenceSigil, number: Number(match[3]), diff --git a/packages/app/src/git/forge-url.test.ts b/packages/app/src/git/forge-url.test.ts index e0deca00ff..c9efa7b9b0 100644 --- a/packages/app/src/git/forge-url.test.ts +++ b/packages/app/src/git/forge-url.test.ts @@ -326,3 +326,81 @@ describe("hasForgeWebUrls", () => { expect(hasForgeWebUrls("bitbucket")).toBe(false); }); }); + +describe("links resolved by the daemon (forgeWeb)", () => { + const sshAliasRemote = "git@github.com-work:acme/repo.git"; + + it("links #N on the web host the daemon resolved for an SSH config alias", () => { + expect( + buildForgeReferenceUrl("github", { + remoteUrl: sshAliasRemote, + forgeWeb: { host: "github.com" }, + sigil: "#", + number: 1, + }), + ).toBe("https://github.com/acme/repo/issues/1"); + }); + + it("opens the branch and a file on the resolved web host for an SSH config alias", () => { + const forgeWeb = { host: "github.com" }; + expect( + buildForgeBranchTreeUrl("github", { remoteUrl: sshAliasRemote, forgeWeb, branch: "main" }), + ).toBe("https://github.com/acme/repo/tree/main"); + expect( + buildForgeBlobUrl("github", { + remoteUrl: sshAliasRemote, + forgeWeb, + branch: "main", + path: "src/index.ts", + }), + ).toBe("https://github.com/acme/repo/blob/main/src/index.ts"); + }); + + it("links #N to the repository that owns the numbers, such as a fork's parent", () => { + expect( + buildForgeReferenceUrl("github", { + remoteUrl: "git@github.com:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + sigil: "#", + number: 123, + }), + ).toBe("https://github.com/main-owner/repo/issues/123"); + }); + + it("keeps an explicit owner/repo#N reference on the named repository", () => { + expect( + buildForgeReferenceUrl("github", { + remoteUrl: "git@github.com:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + repo: "other/tools", + sigil: "#", + number: 7, + }), + ).toBe("https://github.com/other/tools/issues/7"); + }); + + it("keeps the branch and file links on the origin repository for a fork", () => { + const input = { + remoteUrl: "git@github.com:fork-owner/repo.git", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + branch: "feature/only-on-fork", + }; + expect(buildForgeBranchTreeUrl("github", input)).toBe( + "https://github.com/fork-owner/repo/tree/feature/only-on-fork", + ); + expect(buildForgeBlobUrl("github", { ...input, path: "a.ts" })).toBe( + "https://github.com/fork-owner/repo/blob/feature/only-on-fork/a.ts", + ); + }); + + it("keeps the scheme and port of a self-hosted http remote", () => { + expect( + buildForgeReferenceUrl("gitea", { + remoteUrl: "http://forge.test:3000/team/repo.git", + forgeWeb: { host: "forge.test", referenceRepository: "upstream/repo" }, + sigil: "#", + number: 12, + }), + ).toBe("http://forge.test:3000/upstream/repo/issues/12"); + }); +}); diff --git a/packages/app/src/git/forge-url.ts b/packages/app/src/git/forge-url.ts index 4fd86950e9..b56ed5d7d9 100644 --- a/packages/app/src/git/forge-url.ts +++ b/packages/app/src/git/forge-url.ts @@ -6,17 +6,23 @@ * format); an unknown forge has no grammar and yields null, so the action is * simply absent rather than wrong. * - * URL grammar lives on each client forge module. The repo identity and host - * both ride the manifest's `cloudHosts` only to canonicalize a cloud SSH alias - * (e.g. ssh.github.com -> github.com); a self-hosted host is used as-is. + * URL grammar lives on each client forge module. The daemon resolves the web + * host (SSH config aliases, cloud SSH hosts) and the repository that owns + * issue and change-request numbers (a fork's parent) and publishes them as + * `forgeWeb`; branch and file links stay on the origin repository. */ -import { getForgeDefinition } from "@getpaseo/protocol/forge-manifest"; -import { normalizeHost, parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; +import { + forgeWebHost, + isForgeCloudHost, + parseGitRemoteLocation, +} from "@getpaseo/protocol/git-remote"; +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import type { ForgeReferenceSigil } from "@/git/client-forge-module"; import { getClientForgeLogicModule } from "@/git/forges"; export interface ForgeBlobUrlInput { remoteUrl: string | null | undefined; + forgeWeb?: ForgeWeb | null; branch: string | null | undefined; path: string | null | undefined; lineStart?: number; @@ -25,12 +31,17 @@ export interface ForgeBlobUrlInput { export interface ForgeBranchTreeUrlInput { remoteUrl: string | null | undefined; + forgeWeb?: ForgeWeb | null; branch: string | null | undefined; } export interface ForgeReferenceUrlInput { remoteUrl: string | null | undefined; - /** Repository path of a cross-repository reference; the remote's repository when absent. */ + forgeWeb?: ForgeWeb | null; + /** + * Repository path of a cross-repository reference; the repository that owns + * issue numbers (`forgeWeb.referenceRepository`, else the remote's) when absent. + */ repo?: string | null; sigil: ForgeReferenceSigil; number: number; @@ -62,13 +73,6 @@ interface ForgeWebLocation { repo: string; } -/** - * Web host + repo path from a remote. The host is the remote's host, except a - * cloud SSH alias (a non-first entry in the forge's `cloudHosts`, e.g. - * ssh.github.com) is canonicalized to the forge's web host (`cloudHosts[0]`). - * Self-hosted hosts are returned untouched. The repo path supports nested - * groups (e.g. GitLab subgroups) since it is the full remote path. - */ function isValidRepoPath(path: string): boolean { const segments = path.split("/").filter((segment) => segment.length > 0); if (segments.length === 0) { @@ -77,9 +81,17 @@ function isValidRepoPath(path: string): boolean { return !segments.includes(".."); } +/** + * Web location of the origin repository. The host is the daemon's + * `forgeWeb.host`. A daemon without `forgeWeb` publishes none, so the remote's + * own host is used, with a cloud SSH alias mapped to the forge's web host. + * The repo path supports nested groups (e.g. GitLab subgroups) since it is + * the full remote path. + */ function resolveForgeWebLocation( forge: string, remoteUrl: string | null | undefined, + forgeWeb: ForgeWeb | null | undefined, ): ForgeWebLocation | null { if (!remoteUrl) { return null; @@ -88,9 +100,9 @@ function resolveForgeWebLocation( if (!location || !isValidRepoPath(location.path)) { return null; } - const cloudHosts = (getForgeDefinition(forge)?.cloudHosts ?? []).map(normalizeHost); - const isCloudHost = cloudHosts.includes(location.host); - const webHost = isCloudHost ? cloudHosts[0] : location.host; + // COMPAT(forgeWeb): added in v0.16.0, remove the remote-derived host after 2027-06-01 once daemon floor >= v0.16.0. + const webHost = forgeWeb?.host ?? forgeWebHost(forge, location.host); + const isCloudHost = isForgeCloudHost(forge, location.host); // Carry a non-default port only for a self-hosted http(s) origin (e.g. // `:60443`): the web UI shares that origin. An SSH/scp remote's port is not the // web port, and a canonicalized cloud host always serves on the default port. @@ -139,7 +151,7 @@ export function buildForgeBranchTreeUrl( input: ForgeBranchTreeUrlInput, ): string | null { const grammar = getClientForgeLogicModule(forge)?.urlGrammar; - const location = resolveForgeWebLocation(forge, input.remoteUrl); + const location = resolveForgeWebLocation(forge, input.remoteUrl, input.forgeWeb); const branch = input.branch?.trim(); if (!grammar || !location || !branch || branch === "HEAD") { return null; @@ -149,7 +161,7 @@ export function buildForgeBranchTreeUrl( export function buildForgeBlobUrl(forge: string, input: ForgeBlobUrlInput): string | null { const grammar = getClientForgeLogicModule(forge)?.urlGrammar; - const location = resolveForgeWebLocation(forge, input.remoteUrl); + const location = resolveForgeWebLocation(forge, input.remoteUrl, input.forgeWeb); const branch = input.branch?.trim(); const filePath = normalizeBlobPath(input.path); if (!grammar || !location || !branch || branch === "HEAD" || !filePath) { @@ -175,8 +187,8 @@ export function buildForgeReferenceUrl( const referencePath = getClientForgeLogicModule(forge)?.urlGrammar?.referencePaths?.find( (path) => path.sigil === input.sigil, ); - const location = resolveForgeWebLocation(forge, input.remoteUrl); - const repo = input.repo ?? location?.repo; + const location = resolveForgeWebLocation(forge, input.remoteUrl, input.forgeWeb); + const repo = input.repo ?? input.forgeWeb?.referenceRepository ?? location?.repo; if ( !referencePath || !location || diff --git a/packages/app/src/runtime/replica-cache/index.test.ts b/packages/app/src/runtime/replica-cache/index.test.ts index a55bf51e04..f0187e8319 100644 --- a/packages/app/src/runtime/replica-cache/index.test.ts +++ b/packages/app/src/runtime/replica-cache/index.test.ts @@ -354,6 +354,21 @@ describe("ReplicaCache", () => { ); }); + it("preserves where the workspace's forge is on the web across cache reopen", async () => { + const storage = new MemoryStorage(); + const writer = createCache(storage); + const baseline = directory({ workspaces: { generation: "g", afterSeq: 8 } }); + const forgeWeb = { host: "github.com", referenceRepository: "main-owner/repo" }; + const workspace = normalizeWorkspaceDescriptor({ ...workspacePayload(), forgeWeb }); + baseline.workspaces.set(workspace.id, workspace); + commitDirectory(writer, SERVER_ID, baseline); + await writer.flush(); + + const restored = await createCache(storage).readDirectory(SERVER_ID); + + expect(restored.workspaces.get(workspace.id)?.forgeWeb).toEqual(forgeWeb); + }); + it("preserves workspace sorting timestamps across cache reopen", async () => { const storage = new MemoryStorage(); const writer = createCache(storage); diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index e9304513b9..efe2e10639 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { AgentStatusSchema, AgentTimelineItemPayloadSchema, + ForgeWebSchema, WorkspaceGitHubRuntimePayloadSchema, } from "@getpaseo/protocol/messages"; import { AgentProviderSchema } from "@getpaseo/protocol/provider-manifest"; @@ -335,6 +336,7 @@ const StoredWorkspaceSchema = z.strictObject({ gitRuntime: WorkspaceGitRuntimeSchema, githubRuntime: WorkspaceGitHubRuntimePayloadSchema, forge: z.string().optional(), + forgeWeb: ForgeWebSchema.optional(), }); const StoredProjectSchema = z.strictObject({ @@ -768,6 +770,7 @@ function serializeWorkspace(workspace: WorkspaceDescriptor): StoredWorkspace { gitRuntime: workspace.gitRuntime, githubRuntime: workspace.githubRuntime, forge: workspace.forge, + forgeWeb: workspace.forgeWeb, }; } diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 185a1dbac3..0c30fb5bfc 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -3919,7 +3919,11 @@ function WorkspaceMarkdownLinks({ }: AssistantFileLinkResolverProviderProps & { workspace: WorkspaceDescriptor | null | undefined }) { return ( - + {children} diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index 625c3d8c2f..72ed4af90e 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -140,6 +140,7 @@ export interface WorkspaceDescriptor { gitRuntime?: WorkspaceDescriptorPayload["gitRuntime"]; githubRuntime?: WorkspaceDescriptorPayload["githubRuntime"]; forge?: WorkspaceDescriptorPayload["forge"]; + forgeWeb?: WorkspaceDescriptorPayload["forgeWeb"]; project?: ProjectPlacementPayload; } @@ -185,6 +186,7 @@ export function normalizeWorkspaceDescriptor( gitRuntime: payload.gitRuntime, githubRuntime: payload.githubRuntime, forge: payload.forge, + forgeWeb: payload.forgeWeb, project: payload.project, }; } diff --git a/packages/app/src/workspace/open-in-editor/planner.test.ts b/packages/app/src/workspace/open-in-editor/planner.test.ts index d97e54c22c..694816593c 100644 --- a/packages/app/src/workspace/open-in-editor/planner.test.ts +++ b/packages/app/src/workspace/open-in-editor/planner.test.ts @@ -184,6 +184,55 @@ describe("planWorkspaceOpenTargets", () => { ]); }); + it("opens the branch and the active file on the web host the daemon resolved for an SSH alias", () => { + const aliasStatus = { + isGit: true, + remoteUrl: "git@github.com-work:acme/repo.git", + currentBranch: "feature/x", + forgeWeb: { host: "github.com" }, + }; + const open = (activeFile?: { path: string }) => + planWorkspaceOpenTargets({ + workspaceDirectory: "/repo", + activeFile, + desktopTargets: [], + canUseDesktopBridge: false, + isLocalExecution: false, + checkoutStatus: aliasStatus, + forge: "github", + }).map((target) => (target.source === "forge" ? target.url : null)); + + expect(open()).toEqual(["https://github.com/acme/repo/tree/feature/x"]); + expect(open({ path: "src/app.ts" })).toEqual([ + "https://github.com/acme/repo/blob/feature/x/src/app.ts", + ]); + }); + + it("keeps the branch and file on the origin repository of a fork", () => { + const forkStatus = { + isGit: true, + remoteUrl: "git@github.com:fork-owner/repo.git", + currentBranch: "feature/only-on-fork", + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }; + const forgeUrls = (activeFile: { path: string } | undefined) => + planWorkspaceOpenTargets({ + workspaceDirectory: "/repo", + activeFile, + desktopTargets: [], + canUseDesktopBridge: false, + isLocalExecution: false, + checkoutStatus: forkStatus, + forge: "github", + }).flatMap((target) => (target.source === "forge" ? [target.url] : [])); + const urls = [...forgeUrls(undefined), ...forgeUrls({ path: "src/app.ts" })]; + + expect(urls).toEqual([ + "https://github.com/fork-owner/repo/tree/feature/only-on-fork", + "https://github.com/fork-owner/repo/blob/feature/only-on-fork/src/app.ts", + ]); + }); + it("infers the forge from the remote URL when the forge input is null", () => { const targets = planWorkspaceOpenTargets({ workspaceDirectory: "/repo", diff --git a/packages/app/src/workspace/open-in-editor/planner.ts b/packages/app/src/workspace/open-in-editor/planner.ts index 08cd23ffef..d4b98a1697 100644 --- a/packages/app/src/workspace/open-in-editor/planner.ts +++ b/packages/app/src/workspace/open-in-editor/planner.ts @@ -1,3 +1,4 @@ +import type { ForgeWeb } from "@getpaseo/protocol/messages"; import { type Forge, forgeFromRemoteUrl, getForgePresentation } from "@/git/forge"; import type { DesktopOpenTarget, OpenDesktopTargetInput } from "@/workspace/desktop-open-targets"; import { @@ -9,6 +10,7 @@ import { interface CheckoutStatusForOpenTarget { isGit: boolean; remoteUrl?: string | null; + forgeWeb?: ForgeWeb | null; currentBranch?: string | null; } @@ -118,6 +120,7 @@ function buildForgeWebUrl( forge: Forge, input: { remoteUrl: string | null | undefined; + forgeWeb: ForgeWeb | null | undefined; branch: string | null | undefined; path: string | null; lineStart?: number; @@ -129,6 +132,7 @@ function buildForgeWebUrl( return ( presentation.buildBlobUrl?.({ remoteUrl: input.remoteUrl, + forgeWeb: input.forgeWeb, branch: input.branch, path: input.path, lineStart: input.lineStart, @@ -139,6 +143,7 @@ function buildForgeWebUrl( return ( presentation.buildBranchTreeUrl?.({ remoteUrl: input.remoteUrl, + forgeWeb: input.forgeWeb, branch: input.branch, }) ?? null ); @@ -159,6 +164,7 @@ function planForgeOpenTarget(input: { } const url = buildForgeWebUrl(forge, { remoteUrl: input.checkoutStatus.remoteUrl, + forgeWeb: input.checkoutStatus.forgeWeb, branch: input.checkoutStatus.currentBranch, path: input.resolvedFile?.relativePath ?? null, lineStart: input.activeFile?.lineStart, diff --git a/packages/protocol/src/git-remote.ts b/packages/protocol/src/git-remote.ts index 56f1363a96..1ba5b7fd9d 100644 --- a/packages/protocol/src/git-remote.ts +++ b/packages/protocol/src/git-remote.ts @@ -108,6 +108,26 @@ export function normalizeHost(host: string): string { return host.trim().replace(/\.+$/u, "").toLowerCase(); } +/** Whether `host` is one of the forge's public cloud hosts, SSH aliases included. */ +export function isForgeCloudHost(forge: string, host: string): boolean { + const cloudHosts = (getForgeDefinition(forge)?.cloudHosts ?? []).map(normalizeHost); + return cloudHosts.includes(normalizeHost(host)); +} + +/** + * Web host for a remote host of `forge`. A cloud SSH alias (a non-first entry + * in the forge's `cloudHosts`, e.g. ssh.github.com) maps to the forge's web + * host (`cloudHosts[0]`); any other host, self-hosted included, is returned + * as is. + */ +export function forgeWebHost(forge: string, host: string): string { + const normalized = normalizeHost(host); + if (!isForgeCloudHost(forge, normalized)) { + return normalized; + } + return normalizeHost(getForgeDefinition(forge)?.cloudHosts?.[0] ?? normalized); +} + function normalizeRemotePath(path: string): string | null { let normalized = path.trim().replace(/^\/+|\/+$/gu, ""); if (normalized.endsWith(".git")) normalized = normalized.slice(0, -4); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 271d3bab9e..ab903ac898 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -4328,6 +4328,22 @@ export const WorkspaceScriptPayloadSchema = z.object({ terminalId: z.string().nullable().optional().default(null), }); +/** + * Where a workspace's forge is on the web, resolved by the daemon so every + * client builds the same links. + */ +export const ForgeWebSchema = z.object({ + /** Web host of the forge: the SSH config alias resolved, cloud SSH hosts mapped to their web host. */ + host: z.string(), + /** + * Repository path that owns issue and change-request numbers when it is not + * the origin repository, such as a fork's parent. Absent: the origin repository. + */ + referenceRepository: z.string().optional(), +}); + +export type ForgeWeb = z.infer; + const WorkspaceGitRuntimePayloadSchema = z .object({ currentBranch: z.string().nullable().optional(), @@ -4464,6 +4480,8 @@ export const WorkspaceDescriptorPayloadSchema = z // until 2027-01-17; remove the consumer fallback once the supported daemon // floor is >= v0.2.0. forge: z.string().optional(), + // Absent from daemons older than v0.16.0; clients then derive links from the origin remote. + forgeWeb: ForgeWebSchema.optional(), project: ProjectPlacementPayloadSchema.optional(), // COMPAT(directorySync): sequence of this latest directory projection. syncSeq: z.number().int().positive().optional(), @@ -5697,6 +5715,7 @@ const CheckoutStatusCommonSchema = z.object({ // upstream branch name is not necessarily currentBranch, so composing one is wrong. // aheadOfOrigin/behindOfOrigin are measured against exactly this ref. upstreamRef: z.string().nullable().optional(), + forgeWeb: ForgeWebSchema.optional(), }); const CheckoutStatusNotGitSchema = CheckoutStatusCommonSchema.extend({ diff --git a/packages/protocol/src/messages.workspaces.test.ts b/packages/protocol/src/messages.workspaces.test.ts index 8a5bd13224..c056f68733 100644 --- a/packages/protocol/src/messages.workspaces.test.ts +++ b/packages/protocol/src/messages.workspaces.test.ts @@ -1251,6 +1251,15 @@ describe("workspace message schemas", () => { expect( WorkspaceDescriptorPayloadSchema.parse({ ...baseWorkspace, forge: "gitlab" }).forge, ).toBe("gitlab"); + + // forgeWeb is optional: an old daemon omits it, a new daemon's value round-trips. + expect(WorkspaceDescriptorPayloadSchema.parse(baseWorkspace).forgeWeb).toBeUndefined(); + expect( + WorkspaceDescriptorPayloadSchema.parse({ + ...baseWorkspace, + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }).forgeWeb, + ).toEqual({ host: "github.com", referenceRepository: "main-owner/repo" }); }); test("workspace.create.request rejects old flat backing shape and accepts new source envelope", () => { diff --git a/packages/server/src/server/checkout/status-projection.test.ts b/packages/server/src/server/checkout/status-projection.test.ts index 5a5ac1558b..336138bd67 100644 --- a/packages/server/src/server/checkout/status-projection.test.ts +++ b/packages/server/src/server/checkout/status-projection.test.ts @@ -1,13 +1,52 @@ import { describe, expect, test } from "vitest"; -import { CheckoutPrStatusSchema } from "@getpaseo/protocol/messages"; +import { CheckoutPrStatusSchema, CheckoutStatusResponseSchema } from "@getpaseo/protocol/messages"; import type { WorkspaceGitRuntimeSnapshot } from "../workspace-git-service.js"; import { buildCheckoutPrStatusPayloadFromSnapshot, + buildCheckoutStatusPayloadFromSnapshot, normalizeCheckoutPrStatusPayload, } from "./status-projection.js"; describe("checkout status projection", () => { + test("publishes where the forge is on the web with the checkout status", () => { + const snapshot: WorkspaceGitRuntimeSnapshot = { + cwd: "/repo", + git: { + isGit: true, + repoRoot: "/repo", + mainRepoRoot: null, + currentBranch: "main", + remoteUrl: "git@github.com-work:fork-owner/repo.git", + isPaseoOwnedWorktree: false, + isDirty: false, + baseRef: "main", + aheadBehind: null, + upstreamRef: null, + aheadOfOrigin: null, + behindOfOrigin: null, + hasRemote: true, + diffStat: null, + }, + forge: { featuresEnabled: true, authState: "authenticated", pullRequest: null, error: null }, + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }; + + const payload = buildCheckoutStatusPayloadFromSnapshot({ + cwd: "/repo", + requestId: "req-1", + snapshot, + }); + + expect(payload.forgeWeb).toEqual({ + host: "github.com", + referenceRepository: "main-owner/repo", + }); + expect( + CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload, + ).toMatchObject({ forgeWeb: payload.forgeWeb }); + }); + test("includes repository identity fields on the PR status wire payload", () => { const payload = normalizeCheckoutPrStatusPayload( { diff --git a/packages/server/src/server/checkout/status-projection.ts b/packages/server/src/server/checkout/status-projection.ts index 93242cb941..00f9ce05c5 100644 --- a/packages/server/src/server/checkout/status-projection.ts +++ b/packages/server/src/server/checkout/status-projection.ts @@ -69,6 +69,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({ behindOfOrigin: snapshot.git.behindOfOrigin ?? null, hasRemote: snapshot.git.hasRemote, remoteUrl: snapshot.git.remoteUrl, + ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), isPaseoOwnedWorktree: true, error: null, requestId, @@ -91,6 +92,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({ behindOfOrigin: snapshot.git.behindOfOrigin ?? null, hasRemote: snapshot.git.hasRemote, remoteUrl: snapshot.git.remoteUrl, + ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), isPaseoOwnedWorktree: false, error: null, requestId, diff --git a/packages/server/src/server/forge-web.ts b/packages/server/src/server/forge-web.ts new file mode 100644 index 0000000000..08aa3f3a0a --- /dev/null +++ b/packages/server/src/server/forge-web.ts @@ -0,0 +1,79 @@ +import { forgeWebHost } from "@getpaseo/protocol/git-remote"; +import type { ForgeWeb } from "@getpaseo/protocol/messages"; +import type { ForgeResolution } from "../services/forge-resolver.js"; + +// A failed reference-repository lookup (signed out, network down, rate limit) is retried after this long. +const REFERENCE_REPOSITORY_RETRY_MS = 60_000; + +/** + * Web location of a workspace's forge, remembered per origin remote. The host + * comes from the forge resolution; the reference repository needs the forge, so + * it is looked up once per remote, and again only after a failed lookup, once + * the retry delay has passed. + */ +export interface ForgeWebEntry { + remoteUrl: string; + remoteKey: string; + forgeWeb: ForgeWeb; + retryAtMs: number | null; +} + +/** + * The web location available without the forge lookup: a settled answer for this + * remote, or the host alone while its reference repository is due. Publish this + * with the snapshot immediately; a slow or signed-out forge CLI must not hold + * back the workspace's git state or pull request status. + */ +export function forgeWebForResolution(input: { + remoteUrl: string; + resolution: ForgeResolution; + previous: ForgeWebEntry | null; + nowMs: number; +}): ForgeWebEntry { + const remoteKey = `${input.resolution.forge}\0${input.remoteUrl}`; + const previous = input.previous?.remoteKey === remoteKey ? input.previous : null; + // A settled lookup stands for as long as the remote does, and a failed one keeps its retry + // time, however often forced refreshes (every push, fetch and branch switch) ask. + if (previous) { + return previous; + } + return { + remoteUrl: input.remoteUrl, + remoteKey, + forgeWeb: { host: forgeWebHost(input.resolution.forge, input.resolution.host) }, + // A lookup that has never run is due now; one that failed keeps its own retry time. + retryAtMs: input.resolution.service.getReferenceRepository ? input.nowMs : null, + }; +} + +/** + * Enriches an entry with the repository that owns issue and change-request + * numbers. The links still work without it, so a failed lookup is retried later + * rather than surfaced. + */ +export async function resolveForgeWebReference(input: { + cwd: string; + resolution: ForgeResolution; + entry: ForgeWebEntry; + nowMs: number; +}): Promise { + const host = input.entry.forgeWeb.host; + const lookup = input.resolution.service.getReferenceRepository; + if (!lookup) { + return input.entry.retryAtMs === null ? input.entry : { ...input.entry, retryAtMs: null }; + } + try { + const referenceRepository = await lookup.call(input.resolution.service, { cwd: input.cwd }); + return { + ...input.entry, + forgeWeb: referenceRepository ? { host, referenceRepository } : { host }, + retryAtMs: null, + }; + } catch { + return { + ...input.entry, + forgeWeb: { host }, + retryAtMs: input.nowMs + REFERENCE_REPOSITORY_RETRY_MS, + }; + } +} diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 2192c699ad..d6567da4ca 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -6184,6 +6184,7 @@ export class Session { // resolves to "github") so the sidebar/hover-card brand mark matches the // status projection without a second resolve. forge: snapshot.forge.forge, + forgeWeb: snapshot.forgeWeb, }; } diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index b3ededb352..f14a6e94dc 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -6619,6 +6619,45 @@ test("lists Git runtime for a checkout explicitly owned by a non-Git project", a }); }); +test("lists where the workspace's forge is on the web so every client builds the same links", async () => { + const session = createSessionForWorkspaceTests(); + const project = createPersistedProjectRecord({ + projectId: "proj-forge-web", + rootPath: REPO_CWD, + kind: "git", + displayName: "repo", + createdAt: "2026-03-01T12:00:00.000Z", + updatedAt: "2026-03-01T12:00:00.000Z", + }); + const workspace = createPersistedWorkspaceRecord({ + workspaceId: "ws-forge-web", + projectId: project.projectId, + cwd: REPO_CWD, + kind: "local_checkout", + displayName: "main", + createdAt: "2026-03-01T12:00:00.000Z", + updatedAt: "2026-03-01T12:00:00.000Z", + }); + session.listAgentPayloads = async () => []; + session.projectRegistry.list = async () => [project]; + session.workspaceRegistry.listAll = session.workspaceRegistry.listActive = async () => [ + workspace, + ]; + session.workspaceRuntimeStore.get = () => ({ + ...createWorkspaceRuntimeSnapshot(REPO_CWD), + forgeWeb: { host: "github.com", referenceRepository: "main-owner/repo" }, + }); + + const [descriptor] = ( + await session.buildWorkspaceDescriptorMap({ includeGitData: true }) + ).values(); + + expect(descriptor?.forgeWeb).toEqual({ + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}); + test("buildWorkspaceDescriptorMap computes statusEnteredAt from runtime agent fields", async () => { const setupSession = () => { const session = createSessionForWorkspaceTests(); diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index 8480d0604d..70b483e1a1 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -17,6 +17,7 @@ import { type CheckoutSnapshotFacts, type CheckoutStatusGit, } from "../utils/checkout-git.js"; +import { createGitHubService, GitHubCommandError } from "../services/github-service.js"; import { createFileObserver } from "./file-observer/index.js"; import { WorkspaceGitServiceImpl } from "./workspace-git-service.js"; import type { FileChange, FileObserver, SubscribeToFileChanges } from "./file-observer/index.js"; @@ -1019,3 +1020,556 @@ test("a branch switch made before the Git metadata watcher starts still reaches ) .toBe("feature"); }, 30_000); + +function createCheckoutWithOrigin(origin: string): string { + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-forge-web-"))); + const repo = path.join(root, "repo"); + mkdirSync(repo); + const git = (...args: string[]) => + execFileSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: repo, stdio: "pipe" }); + git("init", "-b", "main"); + git("config", "user.email", "test@example.com"); + git("config", "user.name", "Test"); + writeFileSync(path.join(repo, "README.md"), "base\n"); + git("add", "."); + git("commit", "-m", "base"); + git("remote", "add", "origin", origin); + cleanup.push(async () => + rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }), + ); + return repo; +} + +// The GitHub adapter runs for real; only the `gh` binary it spawns is scripted. +function createGitHubWithRepositoryView(repositoryView: object) { + return createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view") { + return { stdout: JSON.stringify(repositoryView), stderr: "" }; + } + return { stdout: "", stderr: "" }; + }, + }); +} + +async function snapshotOf( + repo: string, + deps: ConstructorParameters[0]["deps"], +) { + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps, + }); + cleanup.push(() => service.dispose()); + return { + service, + snapshot: await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }), + }; +} + +async function expectForgeWebEventually( + service: WorkspaceGitServiceImpl, + repo: string, + expected: { host: string; referenceRepository?: string }, +) { + await expect + .poll(async () => (await service.getSnapshot(repo, { includeForge: false })).forgeWeb, { + timeout: 10_000, + }) + .toEqual(expected); +} + +test("an SSH config alias remote publishes the web host the alias resolves to", async () => { + const repo = createCheckoutWithOrigin("git@github.com-work:acme/repo.git"); + + const { snapshot } = await snapshotOf(repo, { + resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), + forgeOverrides: { github: createGitHubWithRepositoryView({}) }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); +}); + +test("a cloud SSH host publishes the forge's web host", async () => { + const repo = createCheckoutWithOrigin("ssh://git@ssh.github.com/acme/repo.git"); + + const { snapshot } = await snapshotOf(repo, { + forgeOverrides: { github: createGitHubWithRepositoryView({}) }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); +}); + +test("a fork checkout publishes its parent as the repository that owns issue and pull request numbers", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + + const { service, snapshot } = await snapshotOf(repo, { + forgeOverrides: { + github: createGitHubWithRepositoryView({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + }, + }); + + // The host is available with the first snapshot; the parent follows in a background update. + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}); + +test("a plain remote publishes no separate reference repository", async () => { + const repo = createCheckoutWithOrigin("https://github.com/acme/repo.git"); + + const { service, snapshot } = await snapshotOf(repo, { + forgeOverrides: { + github: createGitHubWithRepositoryView({ owner: { login: "acme" }, name: "repo" }), + }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); + await expectForgeWebEventually(service, repo, { host: "github.com" }); +}); + +test("a remote on no forge publishes no web location", async () => { + const repo = createCheckoutWithOrigin("git@bitbucket.org:acme/repo.git"); + + const { snapshot } = await snapshotOf(repo, { resolveSshHostname: async () => null }); + + expect(snapshot.forgeWeb).toBeUndefined(); +}); + +test("changing the origin remote publishes the new remote's web location, not the previous one", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view") { + const isFork = args[2] === "fork-owner/repo"; + return { + stdout: JSON.stringify( + isFork + ? { + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + } + : { owner: { login: "acme" }, name: "other" }, + ), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + const before = await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + + execFileSync("git", ["remote", "set-url", "origin", "git@github.com-work:acme/other.git"], { + cwd: repo, + }); + // The refresh a `.git/config` change schedules does not ask for forge data. + const after = await service.getSnapshot(repo, { + force: true, + includeForge: false, + reason: "forge-web-test", + }); + + expect(after.git.remoteUrl).toBe("git@github.com-work:acme/other.git"); + expect(after.forgeWeb).toEqual({ host: "github.com" }); + expect(before.forgeWeb).toEqual({ host: "github.com" }); +}, 30_000); + +test("a failed parent lookup is retried by the pull request status poll, keeping the host an SSH alias resolves to", async () => { + const repo = createCheckoutWithOrigin("git@github.com-work:fork-owner/repo.git"); + let nowMs = Date.parse("2026-01-01T00:00:00Z"); + let ghAnswers = false; + let lookups = 0; + let pollStatus: ((status: null) => void) | undefined; + const github = createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + // The reference lookup names the origin repository; the PR status load asks for the cwd repo. + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookups += 1; + if (!ghAnswers) { + throw new GitHubCommandError({ + args, + cwd: repo, + exitCode: 1, + stderr: "error connecting to api.github.com", + }); + } + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + now: () => new Date(nowMs), + resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), + forgeOverrides: { + // The adapter is real; only the poll is driven by the test instead of a timer. + github: Object.assign(Object.create(github), { + retainCurrentPullRequestStatusPoll: (options: { onStatus?: (status: null) => void }) => { + pollStatus = options.onStatus; + return { unsubscribe: () => {} }; + }, + }), + }, + }, + }); + const subscription = service.registerWorkspace({ cwd: repo }, () => {}); + cleanup.push(async () => { + subscription.unsubscribe(); + await service.dispose(); + }); + + const failed = await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + expect(failed.forgeWeb).toEqual({ host: "github.com" }); + await expect.poll(() => pollStatus, { timeout: 10_000 }).toBeDefined(); + await expect.poll(() => lookups, { timeout: 10_000 }).toBe(1); + // Let the failed lookup record its retry time before advancing the clock. + await new Promise((resolve) => setTimeout(resolve, 0)); + + ghAnswers = true; + nowMs += 61_000; + pollStatus?.(null); + + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + const forced = await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + expect(forced.forgeWeb).toEqual({ host: "github.com", referenceRepository: "main-owner/repo" }); +}, 30_000); + +test("a successful parent lookup is reused across forced refreshes of the same remote", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + let repositoryViews = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view") { + // The parent lookup is the one that names the origin repository. + if (args[2] === "fork-owner/repo") repositoryViews += 1; + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + expect(repositoryViews).toBe(1); +}); + +test("a fork checked out at a detached HEAD still publishes its parent", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + execFileSync("git", ["checkout", "--detach"], { cwd: repo, stdio: "pipe" }); + + const { service, snapshot } = await snapshotOf(repo, { + forgeOverrides: { + github: createGitHubWithRepositoryView({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + }, + }); + + expect(snapshot.forgeWeb).toEqual({ host: "github.com" }); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}); + +test("a parent lookup that finishes during a refresh keeps its answer", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + const lookupStarted = Promise.withResolvers(); + const releaseLookup = Promise.withResolvers(); + const statusLoadStarted = Promise.withResolvers(); + const releaseStatusLoad = Promise.withResolvers(); + let holdNextStatusLoad = false; + let repositoryViews = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "auth" && args[1] === "status" && holdNextStatusLoad) { + holdNextStatusLoad = false; + statusLoadStarted.resolve(); + await releaseStatusLoad.promise; + } + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + repositoryViews += 1; + if (repositoryViews === 1) { + lookupStarted.resolve(); + await releaseLookup.promise; + } + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await lookupStarted.promise; + + holdNextStatusLoad = true; + const second = service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await statusLoadStarted.promise; + + // The first refresh's lookup finishes while the second refresh is still loading the PR status. + releaseLookup.resolve(); + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); + releaseStatusLoad.resolve(); + + const snapshot = await second; + expect(snapshot.forgeWeb).toEqual({ + host: "github.com", + referenceRepository: "main-owner/repo", + }); + expect(repositoryViews).toBe(1); +}, 30_000); + +test("disposal waits for a background parent lookup", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + const lookupStarted = Promise.withResolvers(); + const releaseLookup = Promise.withResolvers(); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookupStarted.resolve(); + await releaseLookup.promise; + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + + try { + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await lookupStarted.promise; + + let disposed = false; + const disposal = service.dispose().then(() => { + disposed = true; + return undefined; + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(disposed).toBe(false); + + releaseLookup.resolve(); + await disposal; + expect(disposed).toBe(true); + } finally { + releaseLookup.resolve(); + await service.dispose(); + } +}, 30_000); + +test("the first snapshot publishes git state and pull request status without waiting for the parent lookup", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + writeFileSync(path.join(repo, "changed.txt"), "dirty\n"); + const lookupStarted = Promise.withResolvers(); + const releaseLookup = Promise.withResolvers(); + const pullRequestStatusLoaded = Promise.withResolvers(); + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookupStarted.resolve(); + await releaseLookup.promise; + return { + stdout: JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }), + stderr: "", + }; + } + if (args[0] === "pr" && args[1] === "view") { + pullRequestStatusLoaded.resolve(); + return { + stdout: JSON.stringify({ + number: 42, + url: "https://github.com/fork-owner/repo/pull/42", + title: "Already known pull request", + state: "OPEN", + baseRefName: "main", + headRefName: "main", + mergedAt: null, + }), + stderr: "", + }; + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + let snapshot: Awaited> | null = null; + const pending = service + .getSnapshot(repo, { force: true, reason: "forge-web-test" }) + .then((value) => { + snapshot = value; + return value; + }); + + await pullRequestStatusLoaded.promise; + // The forge lookup is still held here; the snapshot must not wait for it. + await expect.poll(() => snapshot !== null, { timeout: 5_000 }).toBe(true); + expect(snapshot).not.toBeNull(); + expect(snapshot!.git.currentBranch).toBe("main"); + expect(snapshot!.git.isDirty).toBe(true); + expect(snapshot!.forge.pullRequest?.number).toBe(42); + expect(snapshot!.forgeWeb).toEqual({ host: "github.com" }); + + await lookupStarted.promise; + releaseLookup.resolve(); + await pending; + await expectForgeWebEventually(service, repo, { + host: "github.com", + referenceRepository: "main-owner/repo", + }); +}, 30_000); + +test("a failed parent lookup is not repeated by forced refreshes before the retry delay", async () => { + const repo = createCheckoutWithOrigin("git@github.com:fork-owner/repo.git"); + let lookups = 0; + const service = new WorkspaceGitServiceImpl({ + logger: pino({ enabled: false }), + paseoHome: path.join(path.dirname(repo), "home"), + deps: { + forgeOverrides: { + github: createGitHubService({ + resolveGhPath: async () => "gh", + resolveRepoHost: async () => null, + runner: async (args) => { + if (args[0] === "repo" && args[1] === "view" && args[2] === "fork-owner/repo") { + lookups += 1; + throw new GitHubCommandError({ + args, + cwd: repo, + exitCode: 1, + stderr: "error connecting to api.github.com", + }); + } + return { stdout: "", stderr: "" }; + }, + }), + }, + }, + }); + cleanup.push(() => service.dispose()); + + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await expect.poll(() => lookups, { timeout: 10_000 }).toBe(1); + // Let the failed lookup record its retry time. + await new Promise((resolve) => setTimeout(resolve, 0)); + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + await service.getSnapshot(repo, { force: true, reason: "forge-web-test" }); + + expect(lookups).toBe(1); +}, 30_000); diff --git a/packages/server/src/server/workspace-git-service.primitive.test.ts b/packages/server/src/server/workspace-git-service.primitive.test.ts index f9d4af8a9d..7502c0ba30 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -264,6 +264,8 @@ function createSnapshot(cwd: string, overrides?: SnapshotOverrides): WorkspaceGi pullRequest: resolveSnapshotPullRequest(base, overrides), error: resolveSnapshotError(base, overrides), }, + // Every remote these fixtures use is on github.com. + ...(forge ? { forgeWeb: { host: "github.com" } } : {}), }; } @@ -704,8 +706,9 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => { refreshStatus.resolve(createCheckoutStatus(REPO_CWD, { currentBranch: "feature" })); await refresh; - expect(await service.getSnapshot(REPO_CWD)).toEqual( - createSnapshot(REPO_CWD, { + // A branch change resets the PR status but not where the same remote lives on the web. + expect(await service.getSnapshot(REPO_CWD)).toEqual({ + ...createSnapshot(REPO_CWD, { git: { currentBranch: "feature", diffStat: { additions: 4, deletions: 2 }, @@ -716,7 +719,8 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => { error: null, }, }), - ); + forgeWeb: { host: "github.com" }, + }); expect(getCheckoutStatus).toHaveBeenCalledTimes(2); expect(getCheckoutShortstat).toHaveBeenCalledTimes(2); diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index 9d91610cd8..d2cc4e0484 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -93,6 +93,8 @@ function createSnapshot( pullRequest: resolveSnapshotPullRequest(base, overrides), error: resolveSnapshotError(base, overrides), }, + // Every remote these fixtures use is on github.com. + ...(forgeName ? { forgeWeb: { host: "github.com" } } : {}), }; } diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index c086fa41be..60c868f1b3 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -5,7 +5,7 @@ import { LRUCache } from "lru-cache"; import { CheckoutDiffCache } from "./checkout-diff-cache.js"; import pLimit from "p-limit"; import type pino from "pino"; -import type { ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; +import type { ForgeWeb, ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; import type { CheckoutContext } from "../utils/checkout-git.js"; import { @@ -71,6 +71,12 @@ import { type SubscribeToFileChanges, createFileObserver, } from "./file-observer/index.js"; +import { + forgeWebForResolution, + resolveForgeWebReference, + type ForgeWebEntry, +} from "./forge-web.js"; +import type { SshHostnameResolver } from "../utils/ssh-hostname.js"; import { checkoutLiteFromGitSnapshot } from "./workspace-registry-model.js"; import { createWatcherLivenessCanary } from "./watcher-liveness-canary.js"; @@ -200,6 +206,8 @@ export interface WorkspaceGitRuntimeSnapshot { } | null; error: { message: string } | null; }; + /** Absent when the remote resolves to no forge. */ + forgeWeb?: ForgeWeb; } export interface WorkspaceGitService { @@ -406,6 +414,8 @@ interface WorkspaceGitServiceDependencies { * fakes. Any forge not listed here is built (and cached once) by the registry. */ forgeOverrides?: Record; + /** Resolves an SSH config alias to its HostName; defaults to `ssh -G`. */ + resolveSshHostname?: SshHostnameResolver; resolveAbsoluteGitDir: (cwd: string) => Promise; hasOriginRemote: (cwd: string) => Promise; runGitFetch: ( @@ -459,6 +469,11 @@ interface WorkspaceGitTarget { latestGitLoadedAtMs: number | null; latestForge: WorkspaceGitRuntimeSnapshot["forge"] | null; latestForgeLoadedAtMs: number | null; + latestForgeWeb: ForgeWebEntry | null; + /** The entry whose reference repository is being looked up, so one remote costs one call. */ + forgeWebLookupEntry: ForgeWebEntry | null; + /** The remote the forge snapshot was last refreshed for; null until the first forge refresh. */ + forgeRefreshedForRemote: { remoteUrl: string | null } | null; latestSnapshot: WorkspaceGitRuntimeSnapshot | null; latestSnapshotLoadedAtMs: number | null; latestFacts: CheckoutSnapshotFacts | null; @@ -647,6 +662,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private disposed = false; private disposePromise: Promise | null = null; private readonly pendingRefreshes = new Set>(); + private readonly pendingForgeWebLookups = new Set>(); private readonly snapshotUpdatedListeners = new Set(); private readonly workspaceTargets = new Map(); private readonly repoTargets = new Map(); @@ -691,6 +707,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { ); this.forgeResolver = createForgeResolver({ createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge), + resolveSshHostname: this.deps.resolveSshHostname, }); } @@ -1140,11 +1157,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { this.workingTreeWatchAliases.clear(); this.snapshotUpdatedListeners.clear(); // Unsubscribing can remove a target while its Git command still owns the cwd. - // Stop admission first, then drain those refreshes before releasing the service. - this.disposePromise = Promise.all([ - this.fileObserver.close(), - Promise.allSettled(this.pendingRefreshes), - ]).then(() => undefined); + // Stop admission first, then drain those refreshes and the parent lookups they start. + this.disposePromise = (async () => { + await Promise.all([this.fileObserver.close(), Promise.allSettled(this.pendingRefreshes)]); + await Promise.allSettled(this.pendingForgeWebLookups); + })(); return this.disposePromise; } @@ -1301,6 +1318,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { latestGit: null, latestGitLoadedAtMs: null, latestForge: null, + latestForgeWeb: null, + forgeWebLookupEntry: null, + forgeRefreshedForRemote: null, latestForgeLoadedAtMs: null, latestSnapshot: null, latestSnapshotLoadedAtMs: null, @@ -3568,6 +3588,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } if (request.includeForge) { await this.refreshForgeSnapshot(target, request, facts, runRefreshGitCommand); + } else if (this.hasRemoteChangedSinceForgeRefresh(target)) { + // `git remote set-url` reaches here as a git-only refresh. The forge, its host and the + // fork's parent all belong to the old remote, so resolve the new one now. + await this.refreshForgeSnapshot( + target, + { ...request, includeForge: true, force: true }, + facts, + runRefreshGitCommand, + ); } const snapshot = this.combineSnapshot(target); @@ -3669,6 +3698,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const loadedAtMs = this.deps.now().getTime(); target.latestGitLoadedAtMs = loadedAtMs; target.latestForge = buildForgeUnavailableSnapshot(); + target.latestForgeWeb = null; target.latestForgeLoadedAtMs = target.latestGitLoadedAtMs; return facts; } @@ -3713,6 +3743,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { return facts; } + private hasRemoteChangedSinceForgeRefresh(target: WorkspaceGitTarget): boolean { + const refreshedFor = target.forgeRefreshedForRemote; + return ( + refreshedFor !== null && + target.latestGit?.isGit === true && + refreshedFor.remoteUrl !== target.latestGit.remoteUrl + ); + } + private async refreshForgeSnapshot( target: WorkspaceGitTarget, request: WorkspaceGitRefreshRequest, @@ -3720,13 +3759,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { runRefreshGitCommand: RunGitCommand, ): Promise { const remoteUrl = target.latestGit?.remoteUrl ?? null; + target.forgeRefreshedForRemote = { remoteUrl }; const resolution = await this.forgeResolver.resolveFromRemoteUrlAsync(remoteUrl); // Every forge gates on the resolver alone: a cloud host matches synchronously // and a self-hosted/Enterprise host is recognized by the adapter probe (which // this async resolution populates), so GitHub Enterprise is no longer gated // out by a cloud-only identity check. - if (!resolution) { + if (!resolution || !remoteUrl) { target.latestForge = buildUnresolvedRemoteForgeSnapshot(remoteUrl); + target.latestForgeWeb = null; target.latestForgeLoadedAtMs = this.deps.now().getTime(); return; } @@ -3749,7 +3790,16 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { // Carry the resolved forge (probe-aware) so the wire projection labels // self-managed GitLab hosts correctly instead of falling back to "github". target.latestForge = { ...forgeSnapshot, forge: resolution.forge }; + // Publish the host with the snapshot; the parent lookup finishes in the background. Read the + // previous entry after the wait: a lookup for the old entry may have completed meanwhile. + target.latestForgeWeb = forgeWebForResolution({ + remoteUrl, + resolution, + previous: target.latestForgeWeb, + nowMs: this.deps.now().getTime(), + }); target.latestForgeLoadedAtMs = this.deps.now().getTime(); + this.queueForgeWebReferenceLookup(target); } private combineSnapshot(target: WorkspaceGitTarget): WorkspaceGitRuntimeSnapshot { @@ -3761,6 +3811,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { cwd: target.cwd, git: target.latestGit, forge: target.latestForge ?? buildForgeUnavailableSnapshot(), + // Only the remote it was resolved for: after `git remote set-url` the old host and + // parent are wrong until the next forge refresh resolves the new remote. + ...(target.latestForgeWeb?.remoteUrl === target.latestGit.remoteUrl + ? { forgeWeb: target.latestForgeWeb.forgeWeb } + : {}), }; } @@ -3800,6 +3855,68 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { this.rememberSnapshot(target, this.combineSnapshot(target), { forceEmit: false, }); + this.queueForgeWebReferenceLookup(target); + } + + private queueForgeWebReferenceLookup(target: WorkspaceGitTarget): void { + const lookup = this.resolveForgeWebReferenceIfDue(target) + .catch((error) => { + if (!this.disposed) { + this.logger.warn( + { err: error, cwd: target.cwd }, + "Failed to resolve the forge reference repository", + ); + } + }) + .finally(() => { + this.pendingForgeWebLookups.delete(lookup); + }); + this.pendingForgeWebLookups.add(lookup); + } + + // The status poll is the only periodic work an idle workspace has, so it also + // retries a parent lookup that failed or ran before the forge CLI was signed in. + private async resolveForgeWebReferenceIfDue(target: WorkspaceGitTarget): Promise { + const entry = target.latestForgeWeb; + const remoteUrl = target.latestGit?.remoteUrl ?? null; + const nowMs = this.deps.now().getTime(); + if ( + !entry || + !remoteUrl || + entry.remoteUrl !== remoteUrl || + entry.retryAtMs === null || + nowMs < entry.retryAtMs || + target.forgeWebLookupEntry === entry + ) { + return; + } + target.forgeWebLookupEntry = entry; + try { + // The async resolver, like the forge refresh: only it reports the `ssh -G` host for an alias. + const resolution = await this.forgeResolver.resolveFromRemoteUrlAsync(remoteUrl); + if (!resolution) { + return; + } + const next = await resolveForgeWebReference({ + cwd: target.cwd, + resolution, + entry, + nowMs, + }); + if (target.closed || this.workspaceTargets.get(target.cwd) !== target) { + return; + } + // The origin can change while the lookup runs; the old remote's answer is not ours to publish. + if (target.latestForgeWeb !== entry || target.latestGit?.remoteUrl !== entry.remoteUrl) { + return; + } + target.latestForgeWeb = next; + this.rememberSnapshot(target, this.combineSnapshot(target), { forceEmit: false }); + } finally { + if (target.forgeWebLookupEntry === entry) { + target.forgeWebLookupEntry = null; + } + } } private rememberSnapshot( diff --git a/packages/server/src/services/forge-service.ts b/packages/server/src/services/forge-service.ts index d676304f79..fbf7f6522d 100644 --- a/packages/server/src/services/forge-service.ts +++ b/packages/server/src/services/forge-service.ts @@ -467,6 +467,13 @@ export interface ForgeService { * Others reject a cross-repo checkout that carries no refs. */ supportsCrossRepoCheckoutWithoutRefs?: boolean; + /** + * Repository path that owns the issue and change-request numbers of the + * checkout's origin repository when that is a different repository, such as a + * fork's parent. Null when the origin owns its numbers. Adapters whose forge + * has no fork model omit it. + */ + getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise; getCurrentPullRequestStatus( options: { cwd: string; diff --git a/packages/server/src/services/gitea-service.test.ts b/packages/server/src/services/gitea-service.test.ts index 44d263791f..174e870839 100644 --- a/packages/server/src/services/gitea-service.test.ts +++ b/packages/server/src/services/gitea-service.test.ts @@ -429,6 +429,41 @@ function giteaMergeStatus( }; } +describe("createGiteaService getReferenceRepository", () => { + it("names the repository a fork was forked from, asking about the origin repository explicitly", async () => { + const { service, calls } = makeService(() => + ok( + JSON.stringify({ + full_name: "example-user/sample-repo", + fork: true, + parent: { full_name: "upstream-org/sample-repo" }, + }), + ), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBe( + "upstream-org/sample-repo", + ); + expect(calls).toEqual([["api", "repos/example-user/sample-repo"]]); + }); + + it("rejects when tea api answers with an error body, since tea exits 0 on HTTP errors", async () => { + const { service } = makeService(() => + ok(JSON.stringify({ message: "user does not exist [uid: 0, name: ]" })), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).rejects.toThrow(); + }); + + it("is null for a repository that is not a fork", async () => { + const { service } = makeService(() => + ok(JSON.stringify({ full_name: "example-user/sample-repo", fork: false, parent: null })), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBeNull(); + }); +}); + describe("createGiteaService", () => { it("maps a tea pr list item to the neutral current PR status by head branch", async () => { const { service, calls } = makeService((args) => { diff --git a/packages/server/src/services/gitea-service.ts b/packages/server/src/services/gitea-service.ts index ef1df9f888..f1148c655e 100644 --- a/packages/server/src/services/gitea-service.ts +++ b/packages/server/src/services/gitea-service.ts @@ -247,6 +247,14 @@ const GiteaPullRequestApiSchema = z }) .passthrough(); +// `full_name` is required so an HTTP error body, which `tea api` returns with exit code 0, fails the parse. +const GiteaRepositoryApiSchema = z + .object({ + full_name: z.string(), + parent: z.object({ full_name: z.string().optional() }).nullable().optional(), + }) + .passthrough(); + const GiteaCurrentPullRequestApiSchema = z .object({ number: z.number(), @@ -2007,6 +2015,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For } }, + async getReferenceRepository(input): Promise { + const repo = await resolveCurrentRepoIdentity(input.cwd); + if (!repo) { + return null; + } + const repository = await runJson( + ["api", `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`], + { cwd: input.cwd }, + GiteaRepositoryApiSchema, + ); + return repository.parent?.full_name ?? null; + }, + getCurrentPullRequestStatus(input): Promise { return loadCurrentPullRequestStatus({ cwd: input.cwd, diff --git a/packages/server/src/services/github-service.test.ts b/packages/server/src/services/github-service.test.ts index 0b97f551bb..02aa8d4993 100644 --- a/packages/server/src/services/github-service.test.ts +++ b/packages/server/src/services/github-service.test.ts @@ -528,6 +528,65 @@ describe("ForgeService", () => { vi.useFakeTimers(); }); + describe("getReferenceRepository", () => { + const forkView = JSON.stringify({ + owner: { login: "fork-owner" }, + name: "repo", + parent: { owner: { login: "main-owner" }, name: "repo" }, + }); + + it("names the parent of a fork checkout, asking about the origin repository explicitly", async () => { + const runner = createRunner([forkView]); + const service = createGitHubService({ + runner: runner.runner, + resolveRepoHost: async () => null, + resolveOriginRepository: async () => "fork-owner/repo", + }); + + await expect(service.getReferenceRepository?.({ cwd: "/tmp/repo" })).resolves.toBe( + "main-owner/repo", + ); + expect(runner.calls).toHaveLength(1); + expect(runner.calls[0].args).toEqual([ + "repo", + "view", + "fork-owner/repo", + "--json", + "owner,name,parent", + ]); + }); + + it("rejects when gh cannot answer, so a failed lookup is not mistaken for a repository without a parent", async () => { + const service = createGitHubService({ + runner: async () => { + throw new GitHubCommandError({ + args: ["repo", "view"], + cwd: "/tmp/repo", + exitCode: 1, + stderr: "error connecting to api.github.com", + }); + }, + resolveRepoHost: async () => null, + resolveOriginRepository: async () => "fork-owner/repo", + }); + + await expect(service.getReferenceRepository?.({ cwd: "/tmp/repo" })).rejects.toBeInstanceOf( + GitHubCommandError, + ); + }); + + it("is null for a repository that is not a fork", async () => { + const runner = createRunner([JSON.stringify({ owner: { login: "acme" }, name: "repo" })]); + const service = createGitHubService({ + runner: runner.runner, + resolveRepoHost: async () => null, + resolveOriginRepository: async () => "acme/repo", + }); + + await expect(service.getReferenceRepository?.({ cwd: "/tmp/repo" })).resolves.toBeNull(); + }); + }); + afterEach(() => { vi.useRealTimers(); }); diff --git a/packages/server/src/services/github-service.ts b/packages/server/src/services/github-service.ts index 04731b63d2..189d53de5b 100644 --- a/packages/server/src/services/github-service.ts +++ b/packages/server/src/services/github-service.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { isGitHubHost, + parseGitHubRemoteIdentity, parseGitHubRemoteUrl, parseGitRemoteLocation, } from "@getpaseo/protocol/git-remote"; @@ -959,6 +960,11 @@ interface GitHubServiceDependencies { * per invocation. */ resolveRepoSlug: (cwd: string) => Promise; + /** + * owner/name of the origin remote on any host: an SSH alias or Enterprise + * host included, which `resolveRepoSlug` leaves to `gh`. + */ + resolveOriginRepository: (cwd: string) => Promise; } export interface GitHubCommandRunnerOptions { @@ -1050,6 +1056,7 @@ interface CreateGitHubServiceOptions { now?: () => number; resolveRepoHost?: (cwd: string) => Promise; resolveRepoSlug?: (cwd: string) => Promise; + resolveOriginRepository?: (cwd: string) => Promise; } type PullRequestCheckRunNode = z.infer; @@ -1132,6 +1139,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G now: options.now ?? Date.now, resolveRepoHost: options.resolveRepoHost ?? resolveGitHubEnterpriseHost, resolveRepoSlug: options.resolveRepoSlug ?? resolveGitHubSlugFromOrigin, + resolveOriginRepository: options.resolveOriginRepository ?? resolveOriginRepositoryPath, }; // A resolved enterprise host is cached permanently; a null resolution (no // host, or the auth probe said no) expires so `gh auth login --hostname` @@ -2543,6 +2551,26 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return { success: true }; }, + getReferenceRepository(input) { + return cached({ + cwd: input.cwd, + method: "getReferenceRepository", + args: {}, + readOptions: input, + load: async () => { + const repo = await deps.resolveOriginRepository(input.cwd); + if (!repo) { + return null; + } + // A failed lookup must reject: "no parent" is cached as a final answer. + const view = await readGitHubRepoView({ cwd: input.cwd, repo, run }); + const parentOwner = view.parent?.owner?.login; + const parentName = view.parent?.name; + return parentOwner && parentName ? `${parentOwner}/${parentName}` : null; + }, + }); + }, + isAuthenticated(input) { return cached({ cwd: input.cwd, @@ -3224,20 +3252,53 @@ async function resolveGitHubSlugFromOrigin(cwd: string): Promise return parseGitHubRemoteUrl(stdout.trim())?.repo ?? null; } -async function getGitHubRepoView(options: { - cwd: string; - run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; -}): Promise | null> { - const args = ["repo", "view", "--json", "owner,name,parent"]; +async function resolveOriginRepositoryPath(cwd: string): Promise { + let stdout: string; try { - const stdout = await options.run(args, { - cwd: options.cwd, - }); - return parseGitHubJsonOutput(stdout, GitHubRepoViewSchema, { - args, - cwd: options.cwd, - emptyFallback: "{}", - }); + ({ stdout } = await runGitCommand(["config", "--get", "remote.origin.url"], { + cwd, + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, + timeout: GIT_ORIGIN_URL_READ_TIMEOUT_MS, + })); + } catch { + return null; + } + const location = parseGitRemoteLocation(stdout.trim()); + return location ? (parseGitHubRemoteIdentity(location.path)?.repo ?? null) : null; +} + +interface GitHubRepoViewOptions { + cwd: string; + /** owner/name to ask about; `gh` picks the default repository for the directory when absent. */ + repo?: string; + run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; +} + +async function readGitHubRepoView( + options: GitHubRepoViewOptions, +): Promise> { + const args = [ + "repo", + "view", + ...(options.repo ? [options.repo] : []), + "--json", + "owner,name,parent", + ]; + const stdout = await options.run(args, { + cwd: options.cwd, + }); + return parseGitHubJsonOutput(stdout, GitHubRepoViewSchema, { + args, + cwd: options.cwd, + emptyFallback: "{}", + }); +} + +async function getGitHubRepoView( + options: GitHubRepoViewOptions, +): Promise | null> { + try { + return await readGitHubRepoView(options); } catch (error) { // A missing CLI or an auth failure must surface as its typed class so the // caller reports the real problem; only a genuine "not a resolvable repo" diff --git a/packages/server/src/services/gitlab-service.test.ts b/packages/server/src/services/gitlab-service.test.ts index 81e8bc966d..2e6df284c9 100644 --- a/packages/server/src/services/gitlab-service.test.ts +++ b/packages/server/src/services/gitlab-service.test.ts @@ -260,6 +260,38 @@ const DISCUSSIONS = [ }, ]; +describe("createGitLabService getReferenceRepository", () => { + it("names the project a fork was forked from, asking about the origin project explicitly", async () => { + const { service, calls } = makeService(() => + ok( + JSON.stringify({ + path_with_namespace: "example-group/example-project", + forked_from_project: { path_with_namespace: "upstream-group/sub/example-project" }, + }), + ), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBe( + "upstream-group/sub/example-project", + ); + expect(calls).toEqual([["api", "projects/example-group%2Fexample-project"]]); + }); + + it("rejects when glab api answers with an error body", async () => { + const { service } = makeService(() => ok(JSON.stringify({ message: "404 Project Not Found" }))); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).rejects.toThrow(); + }); + + it("is null for a project that is not a fork", async () => { + const { service } = makeService(() => + ok(JSON.stringify({ path_with_namespace: "example-group/example-project" })), + ); + + await expect(service.getReferenceRepository?.({ cwd: "/repo" })).resolves.toBeNull(); + }); +}); + describe("createGitLabService", () => { it("maps a glab merge request view to the neutral current PR status", async () => { const { service, calls } = makeService((args) => diff --git a/packages/server/src/services/gitlab-service.ts b/packages/server/src/services/gitlab-service.ts index 4fde7173f9..3e0111a439 100644 --- a/packages/server/src/services/gitlab-service.ts +++ b/packages/server/src/services/gitlab-service.ts @@ -249,6 +249,16 @@ const GitLabApprovalsSchema = z }) .passthrough(); +const GitLabProjectSchema = z + .object({ + path_with_namespace: z.string(), + forked_from_project: z + .object({ path_with_namespace: z.string().optional() }) + .nullable() + .optional(), + }) + .passthrough(); + type GitLabMergeRequest = z.infer; type GitLabIssue = z.infer; type GitLabNote = z.infer; @@ -1151,6 +1161,20 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F } }, + async getReferenceRepository(input): Promise { + const remoteUrl = await resolveRemoteUrl(input.cwd); + const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null; + if (!projectPath) { + return null; + } + const project = await runJson( + ["api", `projects/${encodeURIComponent(projectPath)}`], + { cwd: input.cwd }, + GitLabProjectSchema, + ); + return project.forked_from_project?.path_with_namespace ?? null; + }, + async getCurrentPullRequestStatus(input): Promise { try { const mr = await resolveCurrentMergeRequest(input.cwd, input.headRef, input.headSha); From d13438ba50ed74c0d9057370b5f5c781aee0f687 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 13 Nov 2026 19:59:48 +0700 Subject: [PATCH 030/160] fix(diff): identify worktree files by content, not stat metadata (#9584) * fix(diff): identify worktree files by content Stat-only identity changes re-sent unchanged diff bodies after a touch or git add. Worktree tracked and untracked files now share one content identity built from the comparison-side blob, working-tree content, and Git interpretation. Stat metadata no longer forces body delivery, while real content changes still change the identity. Closes #9563 * fix(diff): align untracked patches and comparison modes Read untracked bodies with --no-textconv so they follow the same patch rules as tracked bodies. Include the comparison-side mode in worktree identity so a base file type change cannot keep stale hunks. Use object parameters for the identity inputs. --- packages/server/src/server/diff/git.ts | 147 +++++++++--- packages/server/src/server/diff/inputs.ts | 22 +- .../src/server/diff/subscriptions.test.ts | 216 ++++++++++++++++++ 3 files changed, 344 insertions(+), 41 deletions(-) diff --git a/packages/server/src/server/diff/git.ts b/packages/server/src/server/diff/git.ts index c58c1de181..74e0f84057 100644 --- a/packages/server/src/server/diff/git.ts +++ b/packages/server/src/server/diff/git.ts @@ -12,7 +12,6 @@ import { type CheckoutDiffCompare, } from "../../utils/checkout-git.js"; import { lstat, readFile, readlink } from "node:fs/promises"; -import type { BigIntStats } from "node:fs"; import { resolve } from "node:path"; import type { DiffEndpoint, DiffSubscribeRequest } from "@getpaseo/protocol/messages"; import type { DiffEntry, DiffBody } from "@getpaseo/protocol/binary-frames/index"; @@ -27,6 +26,16 @@ export interface ListedFile { identity: string; source: { kind: "tracked" } | { kind: "untracked"; size: number }; } +interface WorktreeInput { + /** Comparison-side mode, or null when the file is added/untracked on this side. */ + oldMode: string | null; + /** Comparison-side blob, or null when the file is added/untracked on this side. */ + oldBlob: string | null; + /** A regular file whose bytes readGitInputs blob-hashes. */ + hashed: boolean; + /** Content Git cannot read as a regular file, such as a symlink target or submodule state. */ + literal: string | null; +} interface ResolvedComparison { baseSha: string; headSha: string; @@ -195,20 +204,47 @@ async function readComparisonList( ...(privateIndex ? { GIT_INDEX_FILE: privateIndex.indexFile } : {}), }, }; - const { files, worktreeFiles, interpretationPaths } = await readTrackedFiles( - compare, - args, - options, - ); - if (compare.head.kind === "worktree") files.push(...(await listUntrackedFiles(options))); + const tracked = await readTrackedFiles(compare, args, options); + const files = tracked.files; + const worktreeInputs = tracked.worktreeInputs; + if (compare.head.kind === "worktree") { + const untracked = await listUntrackedFiles(options); + files.push(...untracked.files); + for (const [path, input] of untracked.worktreeInputs) worktreeInputs.set(path, input); + } files.sort((a, b) => a.entry.path.localeCompare(b.entry.path)); - for (const file of files) interpretationPaths.add(file.entry.path); - const gitInputs = await readGitInputs([...interpretationPaths].sort(), worktreeFiles, options); - for (const file of files) + for (const file of files) tracked.interpretationPaths.add(file.entry.path); + const hashedPaths = new Set( + [...worktreeInputs].filter(([, input]) => input.hashed).map(([path]) => path), + ); + const literalContent = new Map( + [...worktreeInputs].flatMap(([path, input]) => + input.literal === null ? [] : [[path, input.literal] as const], + ), + ); + const gitInputs = await readGitInputs({ + paths: [...tracked.interpretationPaths].sort(), + hashedPaths, + options, + literalContent, + }); + for (const file of files) { + if (compare.head.kind === "worktree") { + const input = worktreeInputs.get(file.entry.path); + if (!input) throw new Error(`Missing worktree identity for ${file.entry.path}`); + file.identity = JSON.stringify([ + input.oldMode, + input.oldBlob, + gitInputs.identities.get(file.entry.path) ?? null, + gitInputs.identities.get(file.entry.oldPath ?? file.entry.path) ?? null, + ]); + continue; + } file.identity += JSON.stringify([ gitInputs.identities.get(file.entry.path), gitInputs.identities.get(file.entry.oldPath ?? file.entry.path), ]); + } const metrics = { highlightCalls: 0 }; const patches = new Patches(args, options, files); const sources = new HighlightSources({ @@ -237,7 +273,15 @@ async function readComparisonList( const result = file.source.kind === "untracked" ? await runGitCommand( - ["diff", "--no-index", ...GIT_PATCH_FORMAT_ARGS, "--", "/dev/null", file.entry.path], + [ + "diff", + "--no-index", + "--no-textconv", + ...GIT_PATCH_FORMAT_ARGS, + "--", + "/dev/null", + file.entry.path, + ], { ...options, acceptExitCodes: [0, 1], @@ -293,7 +337,11 @@ async function readTrackedFiles( compare: Compare, args: string[], options: GitCommandOptions, -): Promise<{ files: ListedFile[]; worktreeFiles: Set; interpretationPaths: Set }> { +): Promise<{ + files: ListedFile[]; + worktreeInputs: Map; + interpretationPaths: Set; +}> { const [raw, stat] = await Promise.all([ runGitCommand([...args.filter((arg) => arg !== "-w"), "--raw", "--no-abbrev", "-z"], options), runGitCommand([...args, "--numstat", "-z"], options), @@ -303,7 +351,7 @@ async function readTrackedFiles( const stats = parseStats(stat.stdout); const fields = raw.stdout.split("\0"); const files: ListedFile[] = []; - const worktreeFiles = new Set(); + const worktreeInputs = new Map(); const interpretationPaths = new Set(); for (let index = 0; index < fields.length - 1; index++) { const header = fields[index].split(" "); @@ -325,10 +373,25 @@ async function readTrackedFiles( else if (code === "D") change = "deleted"; else if (oldPath !== null) change = "renamed"; let identity = header.join(" "); - if (compare.head.kind === "worktree" && code !== "D") { - const worktree = await readWorktreeIdentity(path, header, options); - identity += `:${worktree.identity}`; - if (worktree.regular && !counts.binary) worktreeFiles.add(path); + if (compare.head.kind === "worktree") { + const input: WorktreeInput = { + oldMode: code === "A" ? null : header[0], + oldBlob: code === "A" ? null : absentBlob(header[2]), + hashed: false, + literal: null, + }; + if (code !== "D") { + const worktree = await readWorktreeContent({ + path, + header, + text: !counts.binary, + options, + }); + input.hashed = worktree.hashed; + input.literal = worktree.literal; + } + worktreeInputs.set(path, input); + identity = ""; } files.push({ @@ -345,24 +408,32 @@ async function readTrackedFiles( source: { kind: "tracked" }, }); } - return { files, worktreeFiles, interpretationPaths }; + return { files, worktreeInputs, interpretationPaths }; } -async function readWorktreeIdentity( - path: string, - header: string[], - options: GitCommandOptions, -): Promise<{ identity: string; regular: boolean }> { - const value = await lstat(resolve(options.cwd, path), { bigint: true }); - let identity = fileStatIdentity(value); +async function readWorktreeContent({ + path, + header, + text, + options, +}: { + path: string; + header: string[]; + text: boolean; + options: GitCommandOptions; +}): Promise<{ hashed: boolean; literal: string | null }> { + const absolutePath = resolve(options.cwd, path); + const value = await lstat(absolutePath, { bigint: true }); + if (value.isSymbolicLink()) + return { hashed: false, literal: `symlink:${await readlink(absolutePath)}` }; if (value.isDirectory() && (header[0] === ":160000" || header[1] === "160000")) { const submodule = await runGitCommand( ["status", "--porcelain=v2", "--branch", "--untracked-files=normal"], - { cwd: resolve(options.cwd, path), envOverlay: { GIT_OPTIONAL_LOCKS: "0" } }, + { cwd: absolutePath, envOverlay: { GIT_OPTIONAL_LOCKS: "0" } }, ); - identity += `:${submodule.stdout}`; + return { hashed: false, literal: `submodule:${submodule.stdout}` }; } - return { identity, regular: value.isFile() }; + return { hashed: value.isFile() && text, literal: null }; } function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] { @@ -385,9 +456,12 @@ async function readUntrackedText( return readFile(path); } -async function listUntrackedFiles(options: GitCommandOptions): Promise { +async function listUntrackedFiles( + options: GitCommandOptions, +): Promise<{ files: ListedFile[]; worktreeInputs: Map }> { const cwd = options.cwd; const files: ListedFile[] = []; + const worktreeInputs = new Map(); const untracked = await runGitCommand( ["ls-files", "--others", "--exclude-standard", "-z"], options, @@ -408,6 +482,12 @@ async function listUntrackedFiles(options: GitCommandOptions): Promise, - options: GitCommandOptions, -) { - const regular = paths.filter((path) => worktreeFiles.has(path)); +interface ReadGitInputsOptions { + paths: string[]; + hashedPaths: ReadonlySet; + options: GitCommandOptions; + literalContent?: ReadonlyMap; +} + +export async function readGitInputs({ + paths, + hashedPaths, + options, + literalContent = new Map(), +}: ReadGitInputsOptions) { + const regular = paths.filter((path) => hashedPaths.has(path)); const [interpretation, blobs] = await Promise.all([ readInterpretation(paths, options), regular.length @@ -34,7 +42,7 @@ export async function readGitInputs( fingerprint([ interpretation.config, interpretation.attributes.get(path) ?? [], - blobByPath.get(path) ?? null, + blobByPath.get(path) ?? literalContent.get(path) ?? null, ]), ]), ); diff --git a/packages/server/src/server/diff/subscriptions.test.ts b/packages/server/src/server/diff/subscriptions.test.ts index 6f792a3311..3fb0ca9509 100644 --- a/packages/server/src/server/diff/subscriptions.test.ts +++ b/packages/server/src/server/diff/subscriptions.test.ts @@ -530,6 +530,222 @@ test("submodule commits invalidate cached worktree gitlink bodies", async () => } }); +test("stat-only changes reuse cached bodies and send no body frames", async () => { + const { utimes } = await import("node:fs/promises"); + const cwd = await mkdtemp(join(tmpdir(), "diff-stat-only-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + const path = join(cwd, "file.txt"); + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, "README"), "base\n"); + await writeFile(path, "base\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(path, "changed\n"); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + expect( + frames.flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])), + ).toContainEqual(expect.objectContaining({ path: "file.txt" })); + frames.length = 0; + for (let index = 0; index < 3; index++) { + const ended = frames.filter((frame) => frame.opcode === DiffOpcode.End).length; + const timestamp = new Date(Date.now() + 1000 * (index + 1)); + await utimes(path, timestamp, timestamp); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.filter((frame) => frame.opcode === DiffOpcode.End).length, { + timeout: 5000, + }) + .toBeGreaterThanOrEqual(ended + 1); + await new Promise((resolve) => setTimeout(resolve, 300)); + } + expect(frames.filter((frame) => frame.opcode === DiffOpcode.Bodies)).toHaveLength(0); + const beginnings = frames.filter((frame) => frame.opcode === DiffOpcode.Begin); + expect(beginnings.length).toBeGreaterThanOrEqual(3); + for (const begin of beginnings) { + expect(begin.entries.find((entry) => entry.path === "file.txt")?.body).toBe(false); + } + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } +}); + +test("staging unchanged worktree content reuses its cached body", async () => { + const cwd = await mkdtemp(join(tmpdir(), "diff-staging-only-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, "README"), "base\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(join(cwd, "staged.ts"), "export const staged = true;\n"); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + expect( + frames.flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])), + ).toContainEqual(expect.objectContaining({ path: "staged.ts" })); + frames.length = 0; + git("add", "-A"); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + expect(frames.filter((frame) => frame.opcode === DiffOpcode.Bodies)).toHaveLength(0); + expect(frames.find((frame) => frame.opcode === DiffOpcode.Begin)).toMatchObject({ + entries: [{ path: "staged.ts", change: "added", body: false }], + }); + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } +}); + +test.skipIf(process.platform === "win32")( + "untracked bodies use the same patch conversion as tracked files", + async () => { + const cwd = await mkdtemp(join(tmpdir(), "diff-textconv-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(join(cwd, ".gitattributes"), "*.dat diff=upper\n"); + git("config", "diff.upper.textconv", "sed s/hello/HELLO/"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(join(cwd, "x.dat"), "hello\n"); + const subscription = await streams.subscribe( + { cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } }, + async (frame) => { + frames.push(frame); + }, + ); + await subscription.start(); + const initial = frames + .flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])) + .find((file) => file.path === "x.dat"); + expect(initial?.hunks.flatMap((hunk) => hunk.lines)).toContainEqual({ + type: "add", + content: "hello", + }); + frames.length = 0; + git("add", "x.dat"); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + expect(frames.filter((frame) => frame.opcode === DiffOpcode.Bodies)).toHaveLength(0); + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } + }, +); + +test.skipIf(process.platform === "win32")( + "comparison-side file type changes refresh cached bodies", + async () => { + const { symlink } = await import("node:fs/promises"); + const cwd = await mkdtemp(join(tmpdir(), "diff-base-mode-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const streams = new DiffSubscriptions({ + async requestWorkingTreeWatch(root) { + return { repoRoot: root, unsubscribe: async () => {} }; + }, + }); + const frames: DiffFrame[] = []; + const path = join(cwd, "x"); + try { + git("init", "-b", "main"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.com"); + await writeFile(path, "target"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "regular"); + git("branch", "compare"); + await rm(path); + await symlink("target", path); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "symlink"); + const moved = git("rev-parse", "HEAD"); + await rm(path); + await writeFile(path, "target\n"); + const compare = { + cwd, + base: { kind: "rev" as const, rev: "refs/heads/compare" }, + head: { kind: "worktree" as const }, + }; + const subscription = await streams.subscribe(compare, async (frame) => { + frames.push(frame); + }); + await subscription.start(); + expect( + frames.flatMap((frame) => (frame.opcode === DiffOpcode.Bodies ? frame.files : [])), + ).toContainEqual(expect.objectContaining({ path: "x" })); + frames.length = 0; + git("update-ref", "refs/heads/compare", moved); + await streams.invalidateForCwd(cwd); + await expect + .poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 }) + .toBe(true); + const bodies = frames.flatMap((frame) => + frame.opcode === DiffOpcode.Bodies ? frame.files : [], + ); + expect(bodies).toContainEqual(expect.objectContaining({ path: "x" })); + const { listComparison } = await import("./git.js"); + const fresh = await listComparison(compare); + try { + const record = await fresh.read(fresh.files[0]); + if (record.kind !== "ready") throw new Error("Expected readable type change"); + expect(bodies).toContainEqual(record.body); + } finally { + await fresh.close(); + } + await subscription.release(); + } finally { + await streams.close(); + await rm(cwd, { recursive: true, force: true }); + } + }, +); + test.each([true, false])( "tracked=%s timestamp-preserving replacements refresh cached bodies", async (tracked) => { From 85ce1aa828c2278149fc3e942a2fc935ed52dacc Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 10:33:50 +0700 Subject: [PATCH 031/160] fix(app): preserve settings scroll through appearance changes (#9605) Preserve settings scroll and form edits across appearance changes while refreshing numeric typography at text and input leaves. Normalize displayed font sizes explicitly after commits. Closes #9600 Closes #6931 Closes #6915 Co-authored-by: Josh --- docs/unistyles.md | 2 +- packages/app/e2e/browser/changes-pane.spec.ts | 4 - .../e2e/browser/settings-navigation.spec.ts | 34 ++++- packages/app/e2e/support/helpers/settings.ts | 124 ++++++++++++++++++ packages/app/src/app/_layout.tsx | 3 + packages/app/src/appearance/text.tsx | 3 + packages/app/src/appearance/text.web.tsx | 12 ++ packages/app/src/appearance/theme-picker.tsx | 3 +- .../app/src/components/page-layout/index.tsx | 3 +- .../settings/headings/settings-section.tsx | 3 +- packages/app/src/components/ui/button.tsx | 3 +- .../src/components/ui/dropdown-trigger.tsx | 3 +- packages/app/src/screens/settings-screen.tsx | 10 +- .../appearance/appearance-preview.tsx | 3 +- .../appearance/appearance-section.tsx | 32 +++-- .../settings/providers-section.test.tsx | 35 +---- 16 files changed, 212 insertions(+), 65 deletions(-) create mode 100644 packages/app/src/appearance/text.tsx create mode 100644 packages/app/src/appearance/text.web.tsx diff --git a/docs/unistyles.md b/docs/unistyles.md index 6be82f70b0..98049998ff 100644 --- a/docs/unistyles.md +++ b/docs/unistyles.md @@ -346,7 +346,7 @@ Gotchas: - **Narrow the discriminated union before spreading.** `updateTheme`'s updater returns the theme union; spreading the union widens `colorScheme` to `"light" | "dark"`, which is assignable to neither concrete member. Branch on `t.colorScheme` so each branch spreads a single narrowed theme type (no `as`). - **`lineHeight.diff` is the code/diff line-height axis** — it is coupled to the code-font-size control (≈ `codeFontSize * 1.5`). Do NOT use it for prose. Markdown body line-height scales with content size (`Math.round(theme.fontSize.content * 1.4)`); routing prose through `lineHeight.diff` clips text at small code sizes. - **High-churn draft values** (live-while-typing in the appearance preview) bypass the theme: apply them as inline styles marked with `inlineUnistylesStyle` so per-keystroke values don't grow the `#unistyles-web` CSS registry. -- **Web numeric appearance tokens need a render; native tracked styles update in place.** On web, string tokens such as colors become CSS variables, but numeric tokens (font sizes, line heights) are baked into generated classes. `AppearanceStyleBoundary` remounts web shell chrome and explorer content to refresh those classes. Native sidebars and explorer hosts stay outside appearance keys: their gesture refs outlive detached dependents until Gesture Handler's passive cleanup, so remounting a related gesture can query an unmounted view. Their tracked native styles and existing themed leaf props update without replacing the gesture hosts or draggable lists. Parsed PR markdown uses its own `withUnistyles` style mapping. +- **Web numeric appearance tokens need a render; native tracked styles update in place.** On web, string tokens such as colors become CSS variables, but numeric tokens (font sizes, line heights) are baked into generated classes. `AppearanceStyleBoundary` remounts web shell chrome and explorer content to refresh those classes. Settings retains its screen and form; `AppearanceText` refreshes numeric text styles at the leaf, and its font fields use `withUnistyles` to refresh input styles without replacing the inputs. Native sidebars and explorer hosts stay outside appearance keys: their gesture refs outlive detached dependents until Gesture Handler's passive cleanup, so remounting a related gesture can query an unmounted view. Their tracked native styles and existing themed leaf props update without replacing the gesture hosts or draggable lists. Parsed PR markdown uses its own `withUnistyles` style mapping. - **Appearance keys belong below native lifetime owners.** `ThemedStack` wraps screen content through `screenLayout`, preserving navigator identity; nested navigators are listed in `nestedNavigatorScreens` and own their own screen boundaries. The remaining shell surfaces retain their appearance refresh separately from native panel hosts. A key above a native stack can detach its screen container inside a FragmentManager transaction during settings hydration. Keep both navigators and retained panel gesture hosts outside those keys. `applyAppearance` patches the active theme before inactive registry entries so subscribers receive the committed values in the same update. Do not add local appearance keys or a boundary above a navigator. - **Dynamic font tokens stay widened.** `fontFamily`, `fontSize`, and `lineHeight` on `commonTheme` are annotated `string`/`number` (not narrowed by `as const`) so the updater's return assigns; the platform default stacks live in `DEFAULT_UI_FONT_STACK` / `DEFAULT_MONO_FONT_STACK`. diff --git a/packages/app/e2e/browser/changes-pane.spec.ts b/packages/app/e2e/browser/changes-pane.spec.ts index 8bc76e2a37..3ce36b15e4 100644 --- a/packages/app/e2e/browser/changes-pane.spec.ts +++ b/packages/app/e2e/browser/changes-pane.spec.ts @@ -2297,13 +2297,9 @@ async function changeCodeTypographyFromSettings( await page.getByTestId("sidebar-settings").click(); await expect(page).toHaveURL(new RegExp(`${buildSettingsSectionRoute("general")}|/settings$`)); await page.getByRole("button", { name: "Appearance" }).click(); - // A committed font change remounts the screen (AppearanceStyleBoundary), and the new form starts - // from the stored size. Edit the size only in the remounted form, or the remount drops it. const sizeField = page.getByLabel("Code font size"); - await sizeField.evaluate((field) => field.setAttribute("data-e2e-before-font-family", "")); await page.getByLabel("Code font family").fill(typography.fontFamily); await page.getByLabel("Code font family").press("Enter"); - await expect(page.locator("[data-e2e-before-font-family]")).toHaveCount(0); await sizeField.fill(String(typography.fontSize)); await page.getByLabel("Code font size").press("Enter"); await expect(page.getByLabel("Code font family")).toHaveValue(typography.fontFamily); diff --git a/packages/app/e2e/browser/settings-navigation.spec.ts b/packages/app/e2e/browser/settings-navigation.spec.ts index 5b019139f2..e46962d618 100644 --- a/packages/app/e2e/browser/settings-navigation.spec.ts +++ b/packages/app/e2e/browser/settings-navigation.spec.ts @@ -14,12 +14,17 @@ import { revealSettingsSidebarSection, expectSettingsSidebarScrollSettled, scrollSettingsSidebarUp, - changeSettingsInterfaceFontSize, selectSettingsHostSectionsRapidly, expectSettingsSidebarScrollOffset, scrollSettingsDetailDown, expectSettingsDetailScrollOffset, openSettingsSection, + changeSettingsSyntaxTheme, + revealSettingsSyntaxTheme, + expectSettingsSyntaxColorChanged, + changeSettingsTypography, + normalizeSettingsFontSizes, + changeSettingsInterfaceFontSizeKeepingSidebarPosition, expectSettingsHeader, openAddHostFlow, selectHostConnectionType, @@ -84,13 +89,32 @@ test.describe("Settings sidebar scroll position", () => { await expectSettingsSidebarScrollOffset(page, 0); }); - test("keeps the sidebar position through interface font changes", async ({ page }) => { + test("updates appearance without losing the detail scroll or form edits", async ({ page }) => { await gotoAppShell(page); await openSettings(page); await openSettingsSection(page, "appearance"); - const offset = await scrollSettingsSidebarToEnd(page); - await changeSettingsInterfaceFontSize(page, 20); - await expectSettingsSidebarScrollOffset(page, offset); + const { offset, keywordColor } = await revealSettingsSyntaxTheme(page); + await changeSettingsSyntaxTheme(page, "Dracula"); + await expectSettingsDetailScrollOffset(page, offset); + await expectSettingsSyntaxColorChanged(page, keywordColor); + await changeSettingsTypography(page); + }); + + test("shows normalized font sizes after committing out-of-range and empty values", async ({ + page, + }) => { + await gotoAppShell(page); + await openSettings(page); + await openSettingsSection(page, "appearance"); + await normalizeSettingsFontSizes(page); + }); + + test("keeps the sidebar context through interface font changes", async ({ page }) => { + await gotoAppShell(page); + await openSettings(page); + await openSettingsSection(page, "appearance"); + await scrollSettingsSidebarToEnd(page); + const offset = await changeSettingsInterfaceFontSizeKeepingSidebarPosition(page, 20); await openSettingsHostSection(page, getServerId(), "providers"); await expectSettingsSidebarScrollOffset(page, offset); }); diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index 796d0b45f5..d877484ee5 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -106,6 +106,33 @@ export async function changeSettingsInterfaceFontSize(page: Page, size: number): await input.fill(String(size)); await input.press("Tab"); await expect(input).toHaveValue(String(size)); + await expect( + page.getByRole("navigation", { name: "Settings" }).getByText("Appearance", { exact: true }), + ).toHaveCSS("font-size", `${size}px`); +} + +export async function changeSettingsInterfaceFontSizeKeepingSidebarPosition( + page: Page, + size: number, +): Promise { + const navigation = page.getByRole("navigation", { name: "Settings" }); + const anchor = navigation.getByRole("button", { name: "About", exact: true }); + const before = await anchor.evaluate((node) => ({ + top: node.getBoundingClientRect().top, + height: node.getBoundingClientRect().height, + })); + await changeSettingsInterfaceFontSize(page, size); + // Larger fonts reflow rows. Preserve the visible destination, rather than its old pixel offset. + await expect + .poll(() => + anchor.evaluate((node, top) => Math.abs(node.getBoundingClientRect().top - top), before.top), + ) + .toBeLessThan(before.height); + const offset = await page + .getByTestId("settings-sidebar-scroll-body") + .evaluate((node) => node.scrollTop); + expect(offset).toBeGreaterThan(0); + return offset; } export async function scrollSettingsSidebarToEnd(page: Page): Promise { @@ -613,3 +640,100 @@ export async function expectRestartRecoveryPrompt(page: Page, prompt: string) { await sheet.getByRole("button", { name: "Cancel", exact: true }).click(); await expect(sheet).toHaveCount(0); } + +export async function revealSettingsSyntaxTheme(page: Page) { + await page.getByLabel(/Highlight theme:/).scrollIntoViewIfNeeded(); + const offset = await page + .getByTestId("settings-detail-scroll-body") + .evaluate((node) => node.scrollTop); + expect(offset).toBeGreaterThan(0); + const keywordColor = await page + .getByRole("img", { name: "Live preview of content typography, syntax theme, and code font" }) + .getByText("export", { exact: true }) + .first() + .evaluate((node) => getComputedStyle(node).color); + return { offset, keywordColor }; +} + +export async function changeSettingsSyntaxTheme(page: Page, theme: string): Promise { + await page.getByLabel(/Highlight theme:/).click(); + await page.getByRole("menuitem", { name: theme, exact: true }).click(); + await expect(page.getByLabel(`Highlight theme: ${theme}`, { exact: true })).toBeVisible(); +} + +export async function expectSettingsSyntaxColorChanged( + page: Page, + previousColor: string, +): Promise { + await expect( + page + .getByRole("img", { name: "Live preview of content typography, syntax theme, and code font" }) + .getByText("export", { exact: true }) + .first(), + ).not.toHaveCSS("color", previousColor); +} + +export async function changeSettingsTypography(page: Page): Promise { + const input = page.getByRole("textbox", { name: "Interface font size", exact: true }); + await input.fill("18"); + await input.press("Enter"); + await expect(input).toHaveValue("18"); + await expect(input).toHaveCSS("font-size", "18px"); + await expect(page.getByText("Code size", { exact: true })).toHaveCSS("font-size", "18px"); + const navigation = page.getByRole("navigation", { name: "Settings" }); + await expect(navigation.getByText("Appearance", { exact: true })).toHaveCSS("font-size", "18px"); + await expect(navigation.getByText("Providers", { exact: true })).toHaveCSS("font-size", "18px"); + await expect(page.getByText("Dracula", { exact: true })).toHaveCSS("font-size", "18px"); + const familyInput = page.getByRole("textbox", { name: "Code font family", exact: true }); + await familyInput.fill("Courier New, Courier, monospace"); + await familyInput.press("Enter"); + const codeInput = page.getByRole("textbox", { name: "Code font size", exact: true }); + await codeInput.fill("16"); + await codeInput.press("Enter"); + await expect(codeInput).toHaveValue("16"); + const preview = page.getByRole("img", { + name: "Live preview of content typography, syntax theme, and code font", + }); + await expect(preview.getByText("export", { exact: true }).first()).toHaveCSS("font-size", "16px"); + await expect(preview.getByText("export", { exact: true }).first()).toHaveCSS( + "line-height", + "24px", + ); + await expect(preview.getByText("export", { exact: true }).first()).toHaveCSS( + "font-family", + /Courier/, + ); + const contentInput = page.getByRole("textbox", { name: "Content font size", exact: true }); + await contentInput.fill("20"); + await contentInput.press("Enter"); + await expect(preview.getByText("Readable content and code preview", { exact: true })).toHaveCSS( + "font-size", + "20px", + ); +} + +export async function normalizeSettingsFontSizes(page: Page): Promise { + for (const [name, minimum, maximum] of [ + ["Interface font size", "10", "21"], + ["Content font size", "10", "21"], + ["Code font size", "9", "22"], + ] as const) { + const input = page.getByRole("textbox", { name, exact: true }); + await input.fill("999"); + await input.press("Enter"); + await expect(input).toHaveValue(maximum); + // Clamp again when the saved value is already at the maximum. + await input.fill("999"); + await input.press("Tab"); + await expect(input).toHaveValue(maximum); + await input.fill(""); + await input.press("Enter"); + await expect(input).toHaveValue(maximum); + await input.fill("1"); + await input.press("Enter"); + await expect(input).toHaveValue(minimum); + await input.fill("1"); + await input.press("Tab"); + await expect(input).toHaveValue(minimum); + } +} diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index b4ca122f77..8577eb97ea 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -864,6 +864,8 @@ const ROOT_STACK_SCREEN_OPTIONS = { animation: "none" as const, }; const ROOT_STACK_NESTED_NAVIGATOR_SCREENS = ["h/[serverId]"] as const; +// Settings owns reactive typography leaves; its scroll and form state survive appearance edits. +const ROOT_STACK_SCREEN_OWNED_APPEARANCE = ["settings/[section]"] as const; function RootStack() { const storeReady = useStoreReady(); @@ -871,6 +873,7 @@ function RootStack() { diff --git a/packages/app/src/appearance/text.tsx b/packages/app/src/appearance/text.tsx new file mode 100644 index 0000000000..ab1508dc70 --- /dev/null +++ b/packages/app/src/appearance/text.tsx @@ -0,0 +1,3 @@ +import { Text } from "react-native"; + +export { Text as AppearanceText }; diff --git a/packages/app/src/appearance/text.web.tsx b/packages/app/src/appearance/text.web.tsx new file mode 100644 index 0000000000..1ba56de360 --- /dev/null +++ b/packages/app/src/appearance/text.web.tsx @@ -0,0 +1,12 @@ +import { Text as NativeText } from "react-native"; +import { withUnistyles } from "react-native-unistyles"; +import type { Theme } from "@/styles/theme"; + +// Web numeric tokens are baked into classes. Subscribe this leaf so withUnistyles +// resolves its style prop again without replacing the surrounding form or scroll view. +function typographyChanges(theme: Theme) { + void theme.fontSize; + return {}; +} + +export const AppearanceText = withUnistyles(NativeText, typographyChanges); diff --git a/packages/app/src/appearance/theme-picker.tsx b/packages/app/src/appearance/theme-picker.tsx index cb2ebf5983..cd68bd27a0 100644 --- a/packages/app/src/appearance/theme-picker.tsx +++ b/packages/app/src/appearance/theme-picker.tsx @@ -1,6 +1,7 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useCallback, useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Text, View, type PressableStateCallbackType } from "react-native"; +import { View, type PressableStateCallbackType } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { PressHighlight } from "@/components/ui/press-highlight"; import { DEFAULT_THEME_PREFERENCE, useAppSettings, type AppSettings } from "@/hooks/use-settings"; diff --git a/packages/app/src/components/page-layout/index.tsx b/packages/app/src/components/page-layout/index.tsx index 4f3bb57af4..44280ec3e8 100644 --- a/packages/app/src/components/page-layout/index.tsx +++ b/packages/app/src/components/page-layout/index.tsx @@ -1,5 +1,6 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useMemo, type ReactNode } from "react"; -import { Platform, ScrollView, Text, View } from "react-native"; +import { Platform, ScrollView, View } from "react-native"; import { KeyboardAwareScrollView } from "react-native-keyboard-controller"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { StyleSheet } from "react-native-unistyles"; diff --git a/packages/app/src/components/settings/headings/settings-section.tsx b/packages/app/src/components/settings/headings/settings-section.tsx index c0460ae15a..d651a47825 100644 --- a/packages/app/src/components/settings/headings/settings-section.tsx +++ b/packages/app/src/components/settings/headings/settings-section.tsx @@ -1,5 +1,6 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useMemo, type ReactNode } from "react"; -import { Text, View, type StyleProp, type ViewStyle } from "react-native"; +import { View, type StyleProp, type ViewStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link"; import { SettingsInfoTip } from "./settings-info-tip"; diff --git a/packages/app/src/components/ui/button.tsx b/packages/app/src/components/ui/button.tsx index 55e4808b8e..03f56c3db1 100644 --- a/packages/app/src/components/ui/button.tsx +++ b/packages/app/src/components/ui/button.tsx @@ -1,3 +1,4 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { useContainedControlSize } from "@/components/ui/control-size"; import { @@ -10,7 +11,7 @@ import { type ReactElement, type ReactNode, } from "react"; -import { Pressable, Text, View } from "react-native"; +import { Pressable, View } from "react-native"; import type { PressableProps, PressableStateCallbackType, diff --git a/packages/app/src/components/ui/dropdown-trigger.tsx b/packages/app/src/components/ui/dropdown-trigger.tsx index 7504bbece4..1552c62a29 100644 --- a/packages/app/src/components/ui/dropdown-trigger.tsx +++ b/packages/app/src/components/ui/dropdown-trigger.tsx @@ -1,5 +1,6 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useCallback, useMemo, type ReactElement, type ReactNode } from "react"; -import { Text, View } from "react-native"; +import { View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { ChevronDown } from "lucide-react-native"; import { diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 9c8b230e4c..abd19f5a1b 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -1,15 +1,9 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useHardwareKeyboardPresent } from "@/keyboard"; import { useAddHost } from "@/hosts/add-host"; import { useCallback, useMemo, useRef, useState } from "react"; import type { ComponentType, ReactNode } from "react"; -import { - Alert, - Pressable, - ScrollView, - Text, - View, - type PressableStateCallbackType, -} from "react-native"; +import { Alert, Pressable, ScrollView, View, type PressableStateCallbackType } from "react-native"; import { useRouter } from "expo-router"; import { useFocusEffect } from "expo-router/react-navigation"; import { useSafeAreaInsets } from "react-native-safe-area-context"; diff --git a/packages/app/src/screens/settings/appearance/appearance-preview.tsx b/packages/app/src/screens/settings/appearance/appearance-preview.tsx index 01699b6cb0..feb571c62f 100644 --- a/packages/app/src/screens/settings/appearance/appearance-preview.tsx +++ b/packages/app/src/screens/settings/appearance/appearance-preview.tsx @@ -1,6 +1,7 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { Text, View, type TextStyle } from "react-native"; +import { View, type TextStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import type { HighlightToken } from "@getpaseo/highlight"; import { isWeb } from "@/constants/platform"; diff --git a/packages/app/src/screens/settings/appearance/appearance-section.tsx b/packages/app/src/screens/settings/appearance/appearance-section.tsx index f42475dc48..9ff6adccad 100644 --- a/packages/app/src/screens/settings/appearance/appearance-section.tsx +++ b/packages/app/src/screens/settings/appearance/appearance-section.tsx @@ -1,8 +1,9 @@ +import { AppearanceText as Text } from "@/appearance/text"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { TFunction } from "i18next"; import { useTranslation } from "react-i18next"; -import { Text, View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; +import { View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { SYNTAX_THEME_OPTIONS, type SyntaxThemeId, @@ -13,10 +14,7 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; import { SettingsSection } from "@/components/settings/headings/settings-section"; import { ThemePicker } from "@/appearance/theme-picker"; import { Button } from "@/components/ui/button"; -import { - EditingTextInput as TextInput, - type EditingTextInputHandle, -} from "@/components/ui/text-input"; +import { EditingTextInput, type EditingTextInputHandle } from "@/components/ui/text-input"; import { MAX_CODE_FONT_SIZE, MAX_CONTENT_FONT_SIZE, @@ -36,6 +34,12 @@ import { isNative } from "@/constants/platform"; import { settingsStyles } from "@/styles/settings"; import { AppearancePreview } from "./appearance-preview"; +// Subscribe the input leaf to numeric theme changes without resetting its editing state. +const TextInput = withUnistyles(EditingTextInput, (theme) => { + void theme.fontSize; + return {}; +}); + // Platform default stacks can be the bare native tokens ("normal"/"monospace"); // those read as a bug, so show a human label in the placeholder instead. const BARE_DEFAULT_STACKS: ReadonlySet = new Set(["normal", "monospace"]); @@ -124,7 +128,7 @@ interface FontSizeRowProps { draft: string; withBorder?: boolean; onChangeDraft: (value: string) => void; - onCommit: () => void; + onCommit: () => string; } function FontSizeRow({ @@ -136,6 +140,12 @@ function FontSizeRow({ onChangeDraft, onCommit, }: FontSizeRowProps) { + const inputRef = useRef(null); + const handleCommit = useCallback(() => { + const committed = onCommit(); + inputRef.current?.replaceText(committed); + }, [onCommit]); + return ( @@ -144,10 +154,11 @@ function FontSizeRow({ { @@ -402,6 +414,7 @@ export function AppearanceSection() { if (next !== settings.codeFontSize) { void updateSettings({ codeFontSize: next }); } + return String(next); }, [codeSizeDraft, settings.codeFontSize, updateSettings]); const commitContentSize = useCallback(() => { @@ -414,6 +427,7 @@ export function AppearanceSection() { if (next !== settings.contentFontSize) { void updateSettings({ contentFontSize: next }); } + return String(next); }, [contentSizeDraft, settings.contentFontSize, updateSettings]); // Live-while-typing: the in-progress drafts drive the preview without diff --git a/packages/app/src/screens/settings/providers-section.test.tsx b/packages/app/src/screens/settings/providers-section.test.tsx index 86c55be4e8..3e55134520 100644 --- a/packages/app/src/screens/settings/providers-section.test.tsx +++ b/packages/app/src/screens/settings/providers-section.test.tsx @@ -8,29 +8,8 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types"; import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; import { ToastApiProvider } from "@/contexts/toast-api-context"; -const { theme, snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted( +const { snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted( () => ({ - theme: { - spacing: { 1: 4, "1.5": 6, 2: 8, 3: 12, 4: 16, 6: 24 }, - iconSize: { sm: 14, md: 20 }, - fontSize: { xs: 11, sm: 13, base: 15 }, - fontWeight: { normal: "400" }, - borderRadius: { lg: 8 }, - opacity: { 50: 0.5 }, - colors: { - surface1: "#111", - surface2: "#222", - surface3: "#333", - foreground: "#fff", - foregroundMuted: "#aaa", - border: "#555", - accent: "#0a84ff", - statusSuccess: "#00ff00", - statusWarning: "#ff9500", - statusDanger: "#ff0000", - palette: { red: { 300: "#ff6b6b" }, white: "#fff" }, - }, - }, snapshotState: { entries: undefined as ProviderSnapshotEntry[] | undefined, isLoading: false, @@ -44,8 +23,8 @@ const { theme, snapshotState, configState, patchConfigMock, openProviderSettings }), ); -vi.mock("react-native", () => ({ - Platform: { OS: "web" }, +vi.mock("react-native", async (importOriginal) => ({ + ...(await importOriginal()), View: ({ children, testID }: { children?: React.ReactNode; testID?: string }) => React.createElement("div", { "data-testid": testID }, children), Text: ({ children }: { children?: React.ReactNode }) => @@ -87,14 +66,6 @@ vi.mock("react-native", () => ({ ActivityIndicator: () => React.createElement("span", { "data-testid": "activity-indicator" }), })); -vi.mock("react-native-unistyles", () => ({ - StyleSheet: { - create: (factory: unknown) => - typeof factory === "function" ? (factory as (t: typeof theme) => unknown)(theme) : factory, - }, - useUnistyles: () => ({ theme, rt: { breakpoint: "md" } }), -})); - vi.mock("lucide-react-native", () => { const icon = (name: string) => () => React.createElement("span", { "data-icon": name }); return { From 2a9395e2d1f7808e478ca4a0b323bf05c33aa45a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 10:35:43 +0700 Subject: [PATCH 032/160] Light plugin themes and Pure Black keep their selected and hovered rows readable (#9579) * fix(app): derive theme states and plugin fills so light and Pure Black themes stay readable Hover, selected, the neutral fill and tertiary text were colors a theme picked by eye, and plugin palettes filled them by borrowing `ring` and `border`. A light plugin theme got a dark selected row under dark text, Pure Black's hover barely separated from its surface, and light terminal ANSI white was white on white. States are now fixed WCAG-contrast steps from the surface they sit on, toward the foreground, derived in styles/derive-colors.ts. Plugin themes derive their neutral fill and tertiary text instead of aliasing `ring` and `border`, and may set an optional `sidebar` color. The web focus outline follows the theme's `ring`, and light terminal white and bright white are derived to read on the background. Tokens with no consumers are removed. Existing plugin themes change look with no author action, and the composer placeholder uses foregroundMuted like every other placeholder. Co-authored-by: Nathan Green <342098+nathansgreen@users.noreply.github.com> * fix(app): accept alpha hex in plugin theme colors when deriving The plugin schema accepts #rgba and #rrggbbaa, but contrast derivation parsed only opaque hex and threw, which would crash rendering for such a theme. Derivation now reads those colors as the opaque color they sit on. * fix(app): keep derived plugin fills and tertiary text readable on low-contrast palettes A fixed contrast step for the neutral fill left text on message bubbles, secondary buttons and badges at 2.6:1 on a dark palette whose body text is 4.75:1, and the fixed fade made Solarized Light tertiary text 1.92:1. The fill step is now bounded by the text it carries and tertiary text has a floor. The plugin reference states the minimum Paseo version for sidebar and that the terminal white is derived on light themes only. * fix(app): keep the derived neutral fill visible when a theme's own text is quiet Bounding the fill by text contrast could reach a step of 1 or less on a palette whose body text is under about 3:1, returning the page background itself. The step now has a minimum. * docs(app): state the trade-off between the neutral fill step and text contrast Below about 3.8:1 body text the fill keeps its minimum step and text on it falls under 3:1. The comment now says so and a test pins both outcomes. * fix(app): leave the light terminal's ANSI white as it was ANSI white is both text and a cell background, so no single palette value is readable in both roles; making it readable as text broke black text on white cells. That needs a contrast rule in the terminal renderer, so light white and bright white return to their previous values and the derivation and its test floors are removed. * feat(plugins): make derived theme colors overridable Sidebar passive text was derived against the page even though timestamps render on hover and selected surfaces. Derive it against the resolved state surface and let contributed themes override each derived semantic role explicitly. --------- Co-authored-by: Nathan Green <342098+nathansgreen@users.noreply.github.com> --- docs/design.md | 2 + .../browser/appearance-theme-picker.spec.ts | 4 +- packages/app/e2e/browser/plugin-theme.spec.ts | 103 ++++++++ packages/app/public/index.html | 6 +- .../src/components/sidebar-workspace-list.tsx | 6 +- .../sidebar/sidebar-status-list.tsx | 6 +- .../sidebar/sidebar-workspace-row-content.tsx | 1 + .../sidebar/workspace-meta-row/index.tsx | 17 +- .../sidebar/workspace-trailing/index.tsx | 25 +- packages/app/src/composer/input/input.tsx | 2 +- packages/app/src/plugins/theme.test.ts | 148 +++++++++++- packages/app/src/plugins/themes/index.ts | 60 ++++- .../settings/host-appearance-section.tsx | 1 + packages/app/src/styles/derive-colors.ts | 90 +++++++ .../app/src/styles/theme-contrast.test.ts | 219 ++++++++++++++++++ packages/app/src/styles/theme.test.ts | 33 +-- packages/app/src/styles/theme.ts | 59 +++-- packages/app/src/utils/color.test.ts | 49 +++- packages/app/src/utils/color.ts | 64 +++++ packages/plugin/src/contracts.ts | 6 + plugin-examples/catppuccin/index.client.ts | 6 + plugin-examples/catppuccin/paseo-plugin.json | 2 +- public-docs/plugins/reference.md | 39 +++- public-docs/plugins/reference.zh-CN.md | 36 ++- 24 files changed, 893 insertions(+), 91 deletions(-) create mode 100644 packages/app/src/styles/derive-colors.ts create mode 100644 packages/app/src/styles/theme-contrast.test.ts diff --git a/docs/design.md b/docs/design.md index f86565e97e..23e6661a63 100644 --- a/docs/design.md +++ b/docs/design.md @@ -44,6 +44,8 @@ Foreground is for the thing being acted on: row titles, section headings, the se `foregroundExtraMuted` is reserved for passive chrome that must sit behind muted text, such as an always-visible window control. Use the solid token instead of lowering SVG opacity; per-path opacity makes overlapping icon strokes render unevenly. Interactive hover and pressed states return to `foreground`. +A theme states places and identity; `packages/app/src/styles/derive-colors.ts` derives their relationships. Sidebar hover and selected fills step from the sidebar toward the foreground. For plugin themes, passive text on those states derives against the actual state surface; page tertiary text is a separate relationship. Explicit plugin semantic overrides take precedence over derived defaults. Built-in themes retain their chosen passive text. `packages/app/src/styles/theme-contrast.test.ts` checks the built-in and representative plugin palettes against contrast floors. + Accent is the one CTA per surface. A ` ); } else { diff --git a/packages/app/src/panels/file-panel.tsx b/packages/app/src/panels/file-panel.tsx index d26bd3271d..a57059fc31 100644 --- a/packages/app/src/panels/file-panel.tsx +++ b/packages/app/src/panels/file-panel.tsx @@ -43,6 +43,7 @@ function FilePanel() { return ( Date: Sat, 14 Nov 2026 13:26:36 +0700 Subject: [PATCH 037/160] fix(app): keep cached workspace commands available during refresh (#9642) Branch status updates reset draft command queries and discarded usable catalogs. Invalidate them instead and share the session freshness policy so drafts refresh in the background. --- .../app/src/agent-commands/cache/index.ts | 10 ++--- packages/app/src/agent-commands/query.test.ts | 39 +++++++++++++++++-- packages/app/src/agent-commands/use-query.ts | 7 ++-- .../app/src/git/checkout-status-cache.test.ts | 6 ++- packages/app/src/git/checkout-status-cache.ts | 4 +- 5 files changed, 49 insertions(+), 17 deletions(-) diff --git a/packages/app/src/agent-commands/cache/index.ts b/packages/app/src/agent-commands/cache/index.ts index baee276a47..2505f0ac8d 100644 --- a/packages/app/src/agent-commands/cache/index.ts +++ b/packages/app/src/agent-commands/cache/index.ts @@ -5,7 +5,7 @@ import equal from "fast-deep-equal"; import { normalizeWorkspacePath } from "@/utils/workspace-identity"; export const AGENT_COMMANDS_QUERY_ROOT = "agentCommands"; -export const sessionCommandQueryPolicy = { +export const agentCommandQueryPolicy = { staleTime: 600_000, gcTime: 1_800_000, refetchOnMount: true, @@ -102,14 +102,12 @@ export function draftAgentCommandsQueryKey(input: { ] as const; } -// Draft commands include project skills read from the checkout. When the checkout moves to -// another branch the cached list describes files that are gone, so it is dropped rather than -// shown while a refetch runs. -export function resetDraftAgentCommandsForCheckout( +// Refresh checkout skills after branch changes while keeping the previous catalog usable. +export function invalidateDraftAgentCommandsForCheckout( queryClient: QueryClient, input: { serverId: string; cwd: string }, ): Promise { - return queryClient.resetQueries({ queryKey: draftAgentCommandsCheckoutScope(input) }); + return queryClient.invalidateQueries({ queryKey: draftAgentCommandsCheckoutScope(input) }); } export function agentCommandsQueryKey(input: { diff --git a/packages/app/src/agent-commands/query.test.ts b/packages/app/src/agent-commands/query.test.ts index 33b55b4464..dafa354aad 100644 --- a/packages/app/src/agent-commands/query.test.ts +++ b/packages/app/src/agent-commands/query.test.ts @@ -2,12 +2,13 @@ import { describe, expect, it } from "vitest"; import { QueryClient, QueryObserver } from "@tanstack/react-query"; import { fetchQueryOptions } from "@/data/query"; import { + invalidateDraftAgentCommandsForCheckout, agentCommandsQueryKey, agentCommandsQueryRoot, draftAgentCommandsQueryKey, normalizeAgentCommandsCwd, sessionAgentCommandsQueryKey, - sessionCommandQueryPolicy, + agentCommandQueryPolicy, } from "./cache"; it("reuses fresh commands and keeps stale commands during a shared refresh and failure", async () => { @@ -20,8 +21,8 @@ it("reuses fresh commands and keeps stale commands during a shared refresh and f resolveRefresh = resolve; }); const options = fetchQueryOptions({ - ...sessionCommandQueryPolicy, - staleTimeMs: sessionCommandQueryPolicy.staleTime, + ...agentCommandQueryPolicy, + staleTimeMs: agentCommandQueryPolicy.staleTime, dataShape: "value", queryKey: key, retry: false, @@ -124,3 +125,35 @@ describe("agent command query keys", () => { expect(agentCommandsQueryRoot("server-1")).toEqual(["agentCommands", "server-1"]); }); }); + +it("retains draft commands while checkout invalidation refreshes the catalog", async () => { + const client = new QueryClient(); + const key = draftAgentCommandsQueryKey({ + serverId: "s", + draftConfig: { provider: "codex", cwd: "/repo" }, + }); + client.setQueryData(key, ["old"]); + let finish: (commands: string[]) => void = () => {}; + const refresh = new Promise((resolve) => { + finish = resolve; + }); + const observer = new QueryObserver( + client, + fetchQueryOptions({ + queryKey: key, + dataShape: "value", + immutableWhen: () => true, + queryFn: () => refresh, + }), + ); + const unsubscribe = observer.subscribe(() => {}); + const updating = invalidateDraftAgentCommandsForCheckout(client, { serverId: "s", cwd: "/repo" }); + expect(observer.getCurrentResult().data).toEqual(["old"]); + expect(observer.getCurrentResult().isPending).toBe(false); + expect(observer.getCurrentResult().isFetching).toBe(true); + finish(["new"]); + await updating; + expect(observer.getCurrentResult().data).toEqual(["new"]); + unsubscribe(); + client.clear(); +}); diff --git a/packages/app/src/agent-commands/use-query.ts b/packages/app/src/agent-commands/use-query.ts index 61a869d092..74f7704867 100644 --- a/packages/app/src/agent-commands/use-query.ts +++ b/packages/app/src/agent-commands/use-query.ts @@ -9,7 +9,7 @@ import { useShallow } from "zustand/shallow"; import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; import { agentCommandsQueryKey, - sessionCommandQueryPolicy, + agentCommandQueryPolicy, type AgentCommandsDraftConfig, } from "./cache"; @@ -92,9 +92,8 @@ export function useAgentCommandsQuery({ agentCommandProvider: draftConfig?.provider ?? provider, agentCommandCwd: draftConfig?.cwd ?? cwd, }, - ...(draftConfig - ? { immutableWhen: () => true as const } - : { ...sessionCommandQueryPolicy, staleTimeMs: sessionCommandQueryPolicy.staleTime }), + ...agentCommandQueryPolicy, + staleTimeMs: agentCommandQueryPolicy.staleTime, subscribed: queryEnabled, retry: 3, retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 5000), diff --git a/packages/app/src/git/checkout-status-cache.test.ts b/packages/app/src/git/checkout-status-cache.test.ts index bbfeb6d758..661b26226a 100644 --- a/packages/app/src/git/checkout-status-cache.test.ts +++ b/packages/app/src/git/checkout-status-cache.test.ts @@ -196,7 +196,7 @@ describe("applyCheckoutStatusUpdateFromEvent", () => { ).toBe(false); }); - it("drops the checkout's cached draft slash commands when its branch changes", () => { + it("marks draft slash commands stale without clearing them when the branch changes", () => { const queryClient = createQueryClient(); queryClient.setQueryData( checkoutStatusQueryKey(serverId, cwd), @@ -219,7 +219,9 @@ describe("applyCheckoutStatusUpdateFromEvent", () => { message: checkoutStatusUpdate(checkoutStatus({ currentBranch: "main" })), }); - expect(queryClient.getQueryData(thisCheckout)).toBeUndefined(); + expect(queryClient.getQueryData(thisCheckout)).toEqual([{ name: "build-paseo" }]); + expect(queryClient.getQueryState(thisCheckout)?.isInvalidated).toBe(true); + expect(queryClient.getQueryState(otherCheckout)?.isInvalidated).toBe(false); expect(queryClient.getQueryData(otherCheckout)).toEqual([{ name: "build-paseo" }]); }); diff --git a/packages/app/src/git/checkout-status-cache.ts b/packages/app/src/git/checkout-status-cache.ts index 7a20e98fa2..42e7fcd6c9 100644 --- a/packages/app/src/git/checkout-status-cache.ts +++ b/packages/app/src/git/checkout-status-cache.ts @@ -8,7 +8,7 @@ import { invalidatePrPaneTimelineForCheckout, } from "@/git/query-keys"; import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status"; -import { resetDraftAgentCommandsForCheckout } from "@/agent-commands/cache"; +import { invalidateDraftAgentCommandsForCheckout } from "@/agent-commands/cache"; export type CheckoutStatusPayload = CheckoutStatusResponse["payload"]; export type { CheckoutPrStatusPayload } from "@/git/pr-status"; @@ -66,7 +66,7 @@ export function applyCheckoutStatusUpdateFromEvent({ ); queryClient.setQueryData(checkoutStatusQueryKey(serverId, payload.cwd), cachePayload); if (previousStatus?.currentBranch !== payload.currentBranch) { - void resetDraftAgentCommandsForCheckout(queryClient, { serverId, cwd: payload.cwd }); + void invalidateDraftAgentCommandsForCheckout(queryClient, { serverId, cwd: payload.cwd }); } void queryClient.invalidateQueries({ queryKey: checkoutCommitsQueryKey(serverId, payload.cwd), From caae991a0f81fe95bd3edad7d21f1bc4b88a1add Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 13:26:56 +0700 Subject: [PATCH 038/160] Keep sidebar toasts and bottom scrolling stable (#9639) * fix(app): keep sidebar toast dismissal and bottom scrolling stable Keep the positioned toast surface mounted through its native exit so its bottom anchor cannot collapse beneath the fading card. Reserve scrollable space below the final sidebar row without changing the scroll range when a toast appears. * fix(app): preserve toast safety across themes and sidebar groups Keep animated positioning in static React Native styles, extend the permanent scroll clearance to status grouping, and bound recording analysis to the requested frames. * fix(app): preserve the toast surface when content changes Replacing upload and reconnect status toasts must update the existing surface. A per-toast key retained the old surface during its exit, duplicating messages and breaking continuity. --- .../sidebar-system-insets/toast-dismissal.mjs | 83 +++++++++++++++++++ .../src/components/sidebar-workspace-list.tsx | 4 +- .../sidebar/sidebar-status-list.tsx | 3 +- .../app/src/components/toast-host.test.tsx | 28 +++++++ packages/app/src/components/toast-host.tsx | 69 +++++++-------- 5 files changed, 152 insertions(+), 35 deletions(-) create mode 100644 packages/app/e2e/mobile/sidebar-system-insets/toast-dismissal.mjs diff --git a/packages/app/e2e/mobile/sidebar-system-insets/toast-dismissal.mjs b/packages/app/e2e/mobile/sidebar-system-insets/toast-dismissal.mjs new file mode 100644 index 0000000000..bc7914cdfb --- /dev/null +++ b/packages/app/e2e/mobile/sidebar-system-insets/toast-dismissal.mjs @@ -0,0 +1,83 @@ +// Record a sidebar toast through timeout on the 2560×1600 Android tablet. +// Pass a vertical sample line through the card's plain interior, away from text, +// icons, and Android's clipboard preview, plus the visible-to-dismissed interval: +// node .../toast-dismissal.mjs recording.mp4 sample-x start-seconds end-seconds +// This checks actual native frames; a browser layout test misses this regression. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; + +const [, , recording, sampleX, start, end] = process.argv; +assert(recording && sampleX && start && end, "Pass recording, sample x, start and end seconds"); +const { frames } = JSON.parse( + execFileSync( + "ffprobe", + [ + "-v", + "error", + "-select_streams", + "v", + "-show_entries", + "frame=best_effort_timestamp_time", + "-of", + "json", + recording, + ], + { encoding: "utf8" }, + ), +); +const selectedFrames = frames + .map((frame, index) => ({ time: Number(frame.best_effort_timestamp_time), index })) + .filter(({ time }) => time >= Number(start) && time <= Number(end)); +assert(selectedFrames.length > 2, "Capture at least three frames in the supplied interval"); +const firstFrame = selectedFrames[0].index; +const endFrame = selectedFrames.at(-1).index + 1; +const bytesPerFrame = 800; +// Bound both output and buffer to the requested frames, even for a long recording. +const pixels = execFileSync( + "ffmpeg", + [ + "-v", + "fatal", + "-i", + recording, + "-vf", + `trim=start_frame=${firstFrame}:end_frame=${endFrame},crop=2:400:${Number(sampleX)}:1100,format=gray`, + "-fps_mode", + "passthrough", + "-f", + "rawvideo", + "-", + ], + { maxBuffer: selectedFrames.length * bytesPerFrame + 1024 }, +); +assert.equal( + pixels.length, + selectedFrames.length * bytesPerFrame, + "Every selected frame must be decoded", +); +const positions = []; +let disappeared = false; +for (const [index, { time }] of selectedFrames.entries()) { + const column = pixels.subarray(index * bytesPerFrame, (index + 1) * bytesPerFrame); + const runs = []; + let run = []; + for (let y = 0; y < 400; y++) { + if (column[y * 2] > 250) run.push(y); + else { + if (run.length > 40) runs.push(run); + run = []; + } + } + if (run.length > 40) runs.push(run); + runs.sort((a, b) => b.length - a.length); + if (runs.length) { + const card = runs[0]; + positions.push({ time, centre: 1100 + (card[0] + card.at(-1)) / 2 }); + } else if (positions.length) disappeared = true; +} +assert(positions.length > 2, "Capture at least three visible card frames"); +assert(disappeared, "Recording must include the card disappearing"); +const centres = positions.map(({ centre }) => centre); +const shift = Math.max(...centres) - Math.min(...centres); +console.log(JSON.stringify({ positions, maximumShiftPixels: shift }, null, 2)); +assert(shift <= 2, `Toast moved ${shift}px during dismissal`); diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index bf6a060931..4c4c1575fd 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -2592,7 +2592,9 @@ const styles = StyleSheet.create((theme) => ({ // Optical inset: aligns the visible Pinned/Workspaces glyph edge with the // Schedules icon across the divider; their layout boxes have different insets. paddingTop: 2, - paddingBottom: theme.spacing[4], + // Keep the last row scrollable above the sidebar toast, including a wrapped Undo row. + // This space stays present across toast changes so the scroll range never jumps. + paddingBottom: theme.spacing[24], }, projectListContainer: { width: "100%", diff --git a/packages/app/src/components/sidebar/sidebar-status-list.tsx b/packages/app/src/components/sidebar/sidebar-status-list.tsx index ecbf367d9c..b271157d03 100644 --- a/packages/app/src/components/sidebar/sidebar-status-list.tsx +++ b/packages/app/src/components/sidebar/sidebar-status-list.tsx @@ -1101,7 +1101,8 @@ const styles = StyleSheet.create((theme) => ({ paddingHorizontal: theme.spacing[2], // Keep status mode's Pinned/Workspaces boundary identical to project mode. paddingTop: 2, - paddingBottom: theme.spacing[4], + // Match project grouping: permanent room to scroll the final row above sidebar toasts. + paddingBottom: theme.spacing[24], }, pinnedSection: { marginBottom: theme.spacing[1], diff --git a/packages/app/src/components/toast-host.test.tsx b/packages/app/src/components/toast-host.test.tsx index 32f1bfb8a7..f72cf29813 100644 --- a/packages/app/src/components/toast-host.test.tsx +++ b/packages/app/src/components/toast-host.test.tsx @@ -32,4 +32,32 @@ describe("useToastHost", () => { act(() => dismissUploading()); expect(result.current.toast?.content).toBe("Image uploaded"); }); + + it("ends each toast's undo opportunity once, including replacement", () => { + const { result } = renderHook(() => useToastHost()); + const dismissed: string[] = []; + let dismissFirst = () => {}; + let dismissSecond = () => {}; + act(() => { + dismissFirst = result.current.api.show("First archive", { + onDismiss: () => dismissed.push("first"), + }); + }); + act(() => { + dismissSecond = result.current.api.show("Second archive", { + onDismiss: () => dismissed.push("second"), + }); + }); + expect(dismissed).toEqual(["first"]); + act(() => dismissFirst()); + expect(result.current.toast?.content).toBe("Second archive"); + expect(dismissed).toEqual(["first"]); + act(() => { + dismissSecond(); + dismissSecond(); + result.current.dismiss(); + }); + expect(result.current.toast).toBeNull(); + expect(dismissed).toEqual(["first", "second"]); + }); }); diff --git a/packages/app/src/components/toast-host.tsx b/packages/app/src/components/toast-host.tsx index 7be8273a79..bb9a04707d 100644 --- a/packages/app/src/components/toast-host.tsx +++ b/packages/app/src/components/toast-host.tsx @@ -8,7 +8,7 @@ import { Platform, StyleSheet as NativeStyleSheet, Text, ToastAndroid, View } fr import Animated, { FadeIn, FadeOut } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import type { Theme } from "@/styles/theme"; +import { SPACING, type Theme } from "@/styles/theme"; import { useTranslation } from "react-i18next"; import { useIsCompactFormFactor } from "@/constants/layout"; import { isWeb } from "@/constants/platform"; @@ -212,10 +212,18 @@ export function ToastViewport({ const topOffset = placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance; - const content = ( - - {toast ? ( - - - - ) : null} + + + - - ); + + ) : null; if (placement === "app-shell" && isWeb && typeof document !== "undefined") { return createPortal(content, getOverlayRoot()); @@ -294,26 +298,25 @@ function ToastCard({ } const animatedStyles = NativeStyleSheet.create({ + container: { + position: "absolute", + left: SPACING[4], + right: SPACING[4], + zIndex: OVERLAY_Z.toast, + alignItems: "center", + }, + sidebarContainer: { + position: "absolute", + left: SPACING[2], + right: SPACING[2], + bottom: SPACING[2], + zIndex: OVERLAY_Z.toast, + alignItems: "center", + }, surface: { alignSelf: "center", maxWidth: "100%" }, }); const styles = StyleSheet.create((theme) => ({ - container: (placement: Exclude, topOffset: number) => ({ - position: "absolute", - left: theme.spacing[4], - right: theme.spacing[4], - top: topOffset + (placement === "app-shell" ? theme.spacing[2] : theme.spacing[3]), - zIndex: OVERLAY_Z.toast, - alignItems: "center", - }), - sidebarContainer: { - position: "absolute", - left: theme.spacing[2], - right: theme.spacing[2], - bottom: theme.spacing[2], - zIndex: OVERLAY_Z.toast, - alignItems: "center", - }, widthBoundary: { width: "92%", maxWidth: TOAST_MAX_WIDTH, From 93d21e561232551930a22390433a15ef9f5acdb6 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 13:27:02 +0700 Subject: [PATCH 039/160] Preserve the mobile sidebar when returning from Settings (#9641) * fix(app): preserve mobile sidebar continuity through Settings Retain the sidebar for the Settings visit so Back resumes the original navigation surface without a new drawer animation. Native screen appearance owns the handoff because pathname and layout updates precede presentation. * fix(app): keep settings navigation imports lightweight Keep the Settings visit state accessible without loading native presentation hooks, and exercise continuity with a scrolled list and complete paint capture. --- docs/mobile-panels.md | 17 +++- .../e2e/browser/settings-navigation.spec.ts | 89 ++++++++++++++++++ packages/app/e2e/support/helpers/settings.ts | 92 +++++++++++++++++++ packages/app/src/app/_layout.tsx | 64 +++++++++++-- packages/app/src/components/left-sidebar.tsx | 24 ++--- packages/app/src/mobile-panels/model.test.ts | 19 ++++ packages/app/src/mobile-panels/model.ts | 14 ++- packages/app/src/mobile-panels/provider.tsx | 15 ++- packages/app/src/mobile-panels/selection.ts | 7 +- .../app/src/navigation/settings-navigation.ts | 35 ++++++- .../navigation/settings-presentation/index.ts | 46 +++++++++- .../settings-presentation/model.test.ts | 36 ++++++++ .../navigation/settings-presentation/model.ts | 47 +++++++++- .../settings-presentation/session/index.ts | 6 ++ packages/app/src/screens/settings-screen.tsx | 10 +- .../index.ts | 6 +- .../navigation.test.ts | 10 ++ .../navigation.ts | 8 +- packages/app/src/stores/panel-store/index.ts | 9 +- .../app/src/stores/panel-store/state.test.ts | 24 +++++ packages/app/src/stores/panel-store/state.ts | 10 +- 21 files changed, 531 insertions(+), 57 deletions(-) create mode 100644 packages/app/src/navigation/settings-presentation/session/index.ts diff --git a/docs/mobile-panels.md b/docs/mobile-panels.md index 21849788d2..a45e209097 100644 --- a/docs/mobile-panels.md +++ b/docs/mobile-panels.md @@ -27,9 +27,17 @@ interface MobilePanelSelection { Every semantic target change increments `revision`. Repeating the current target is idempotent. Compact panel selection is not persisted; a cold start begins at `agent`. -Only an overlay sidebar holds `agent-list`, and only a compact layout holds `file-explorer`. App -chrome publishes the layout (compact or wide, and the left sidebar presentation `overlay`, `dock`, or -`hidden`) to `panel-store`, which drops any target the layout does not present. A stale +An overlay sidebar holds `agent-list`, and only a compact layout holds `file-explorer`. +A compact Settings visit entered from the sidebar suspends it: the host stays mounted and +laid out on native. Its target and scroll position survive until return to the originating +workspace. Route changes and `onLayout` both precede native screen appearance, so the sidebar +stays visible until Settings emits the native navigator's `transitionEnd`. Web uses layout. +Input and activity stop during the handoff. Widening or leaving for another destination discards +the return. Commands issued while suspended settle immediately behind Settings, so explicit +agent navigation does not reveal a closing sidebar animation. + +App chrome publishes the layout (compact or wide, and the left sidebar presentation `overlay`, +`dock`, `hidden`, or `suspended`) to `panel-store`, which drops any target the layout does not present. A stale `agent-list` would reopen the overlay on the next collapse; a stale `file-explorer` after widening would block the navigation swipe, which begins only from `agent`. @@ -120,7 +128,8 @@ definition, no longer eligible to begin. the overlay host fills the window. - The overlay's backdrop covers the whole window; safe-area padding applies to the sidebar and workspace content only. It closes by swiping back, tapping the backdrop, or picking a destination: - every sidebar destination closes the overlay before it navigates. + workspace destinations close the overlay before navigating. Settings suspends the compact + sidebar for the duration of its visit instead. - Animated panel nodes use React Native static styles plus inline theme values. Do not attach Unistyles-generated styles to those nodes; Unistyles and Reanimated patching the same Fabric node has caused native crashes. diff --git a/packages/app/e2e/browser/settings-navigation.spec.ts b/packages/app/e2e/browser/settings-navigation.spec.ts index e46962d618..054a913188 100644 --- a/packages/app/e2e/browser/settings-navigation.spec.ts +++ b/packages/app/e2e/browser/settings-navigation.spec.ts @@ -1,3 +1,4 @@ +import { writeFile } from "node:fs/promises"; import { test, expect } from "../support/fixtures"; import { buildHostWorkspaceRoute, @@ -6,10 +7,16 @@ import { buildSettingsRoute, buildSettingsSectionRoute, } from "@/utils/host-routes"; +import { openCompactSidebar } from "../support/helpers/usage-sidebar-item"; import { gotoAppShell, openSettings } from "../support/helpers/app"; import { getE2EDaemonPort } from "../support/helpers/daemon-port"; import { closeCompactSettings, + captureCompactSidebarReturn, + openSettingsFromCompactSidebar, + captureCompactSidebarContext, + expectCompactSidebarOpen, + closeCompactSidebar, scrollSettingsSidebarToEnd, revealSettingsSidebarSection, expectSettingsSidebarScrollSettled, @@ -374,6 +381,87 @@ test.describe("Settings sidebar navigation", () => { test.describe("Settings — compact master-detail", () => { test.use({ viewport: { width: 390, height: 844 } }); + test("returning from Settings preserves the open sidebar from the first paint", async ({ + page, + withWorkspace, + }, testInfo) => { + const workspace = await withWorkspace({ prefix: "settings-sidebar-continuity-" }); + for (let i = 0; i < 12; i++) await withWorkspace({ prefix: "settings-sidebar-scroll-" }); + await openWorkspace(page, workspace); + await openCompactSidebar(page); + await expectCompactSidebarOpen(page); + const expectContextPreserved = await captureCompactSidebarContext(page); + const openingFrames = await captureCompactSidebarReturn(page, () => + openSettingsFromCompactSidebar(page), + ); + await writeFile( + testInfo.outputPath("sidebar-opening-frames.json"), + JSON.stringify(openingFrames, null, 2), + ); + expect(openingFrames.some((frame) => frame.settingsVisible)).toBe(true); + expect(openingFrames.every((frame) => frame.sidebarVisible || frame.settingsVisible)).toBe( + true, + ); + await openSettingsSection(page, "appearance"); + await goBackInSettings(page); + const frames = await captureCompactSidebarReturn(page, () => closeCompactSettings(page)); + await writeFile( + testInfo.outputPath("sidebar-return-frames.json"), + JSON.stringify(frames, null, 2), + ); + await testInfo.attach("sidebar-return-frames", { + body: JSON.stringify(frames, null, 2), + contentType: "application/json", + }); + const workspaceFrames = frames.filter((frame) => !frame.pathname.startsWith("/settings")); + expect(workspaceFrames.length).toBeGreaterThan(0); + expect(workspaceFrames.every((frame) => frame.sidebarVisible)).toBe(true); + const firstX = workspaceFrames[0]!.closeX; + expect( + workspaceFrames.every((frame) => Math.abs((frame.closeX ?? Infinity) - firstX!) < 1), + ).toBe(true); + await expectCompactSidebarOpen(page); + await expectContextPreserved(); + await openSettingsFromCompactSidebar(page); + const backFrames = await captureCompactSidebarReturn(page, async () => { + await page.goBack(); + }); + await writeFile( + testInfo.outputPath("browser-back-frames.json"), + JSON.stringify(backFrames, null, 2), + ); + await testInfo.attach("browser-back-frames", { + body: JSON.stringify(backFrames, null, 2), + contentType: "application/json", + }); + const backWorkspaceFrames = backFrames.filter( + (frame) => !frame.pathname.startsWith("/settings"), + ); + expect(backWorkspaceFrames.length).toBeGreaterThan(0); + expect(backWorkspaceFrames.every((frame) => frame.sidebarVisible)).toBe(true); + await expectCompactSidebarOpen(page); + await closeCompactSidebar(page); + }); + + test("widening during Settings discards the mobile sidebar return", async ({ + page, + withWorkspace, + }) => { + const workspace = await withWorkspace({ prefix: "settings-sidebar-resize-" }); + await openWorkspace(page, workspace); + await openCompactSettings(page, buildHostWorkspaceRoute(getServerId(), workspace.workspaceId)); + await page.setViewportSize({ width: 1000, height: 844 }); + await expect(page.getByTestId("settings-detail-pane")).toBeVisible(); + await page.setViewportSize({ width: 390, height: 844 }); + await goBackInSettings(page); + await expectCompactSettingsList(page); + await closeCompactSettings(page); + await expect(page.getByRole("button", { name: "Close sidebar", exact: true })).toBeHidden(); + await expect( + page.getByRole("button", { name: "Open menu", exact: true }).first(), + ).toBeInViewport(); + }); + test("the compact tab switcher reopens after Settings hides its workspace", async ({ page }) => { const workspace = await seedMockAgentWorkspace({ repoPrefix: "settings-tab-switcher-", @@ -401,6 +489,7 @@ test.describe("Settings — compact master-detail", () => { await expect(newAgent).toHaveCount(0); await closeCompactSettings(page); + await closeCompactSidebar(page); await expect(switcher).toBeVisible(); await expect(newAgent).toHaveCount(0); await switcher.click(); diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index d877484ee5..ee5aae1f42 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -737,3 +737,95 @@ export async function normalizeSettingsFontSizes(page: Page): Promise { await expect(input).toHaveValue(minimum); } } + +/** Sample actual paints, including the first workspace frame after Settings. */ +export async function captureCompactSidebarReturn(page: Page, returnAction: () => Promise) { + await page.evaluate(() => { + const capture = { + frames: [] as { + time: number; + pathname: string; + sidebarVisible: boolean; + settingsVisible: boolean; + closeX: number | null; + }[], + stopped: false, + }; + Object.assign(window, { __sidebarFrameCapture: capture }); + const start = performance.now(); + function sample() { + if (capture.stopped) return; + const close = document.querySelector('[data-testid="sidebar-close"]'); + capture.frames.push({ + time: performance.now() - start, + pathname: location.pathname, + settingsVisible: + document + .querySelector('[data-testid="settings-sidebar"]') + ?.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) ?? false, + sidebarVisible: + (close?.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) ?? false) && + close!.getBoundingClientRect().x >= 0 && + close!.getBoundingClientRect().right <= innerWidth, + closeX: close?.getBoundingClientRect().x ?? null, + }); + requestAnimationFrame(sample); + } + requestAnimationFrame(sample); + }); + await returnAction(); + return page.evaluate(async () => { + const capture = ( + window as typeof window & { + __sidebarFrameCapture: { + frames: { + time: number; + pathname: string; + sidebarVisible: boolean; + settingsVisible: boolean; + closeX: number | null; + }[]; + stopped: boolean; + }; + } + ).__sidebarFrameCapture; + await new Promise((resolve) => setTimeout(resolve, 1500)); + capture.stopped = true; + return capture.frames; + }); +} + +export async function captureCompactSidebarContext(page: Page) { + const sidebar = await page.getByTestId("sidebar-project-workspace-list-scroll").elementHandle(); + if (!sidebar) throw new Error("Open sidebar has no workspace list"); + await expect + .poll(() => sidebar.evaluate((el) => el.scrollHeight - el.clientHeight)) + .toBeGreaterThan(0); + const offset = await sidebar.evaluate((el) => { + el.scrollTop = el.scrollHeight; + return el.scrollTop; + }); + expect(offset).toBeGreaterThan(0); + return async () => { + expect(await sidebar.evaluate((el) => el.isConnected)).toBe(true); + expect(await sidebar.evaluate((el) => el.scrollTop)).toBe(offset); + await sidebar.dispose(); + }; +} + +export async function expectCompactSidebarOpen(page: Page) { + await expect(page.getByRole("button", { name: "Close sidebar", exact: true })).toBeInViewport(); +} + +export async function closeCompactSidebar(page: Page) { + await page.getByRole("button", { name: "Close sidebar", exact: true }).click(); + await expect( + page.getByRole("button", { name: "Open menu", exact: true }).first(), + ).toBeInViewport(); +} + +export async function openSettingsFromCompactSidebar(page: Page) { + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await expectAppRoute(page, buildSettingsRoute()); + await expectCompactSettingsList(page); +} diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index 8577eb97ea..787e0c20e4 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -87,7 +87,10 @@ import { type StartupBlocker, } from "@/navigation/host-runtime-bootstrap"; import { registerWorkspaceRouteNavigationRef } from "@/navigation/workspace-route-navigation"; -import { useSettingsRouteEntry } from "@/navigation/settings-presentation"; +import { + useSettingsRouteEntry, + useSettingsSidebarPresentation, +} from "@/navigation/settings-presentation"; import { ThemedStack } from "@/navigation/themed-stack"; import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon"; import { AgentNavigationListener } from "@/desktop/agent-navigation"; @@ -473,12 +476,16 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon viewportWidth, }), }); - const sidebarPresentation = resolveLeftSidebarPresentation({ - chromeEnabled, - isCompactLayout, - isFocusModeEnabled: isWorkspaceFocusModeEnabled, - desktopSidebarVisible, - }); + const { presentation: sidebarPresentation, visible: sidebarVisible } = + useSettingsSidebarPresentation({ + visible: chromeEnabled, + presentation: resolveLeftSidebarPresentation({ + chromeEnabled, + isCompactLayout, + isFocusModeEnabled: isWorkspaceFocusModeEnabled, + desktopSidebarVisible, + }), + }); const applyPanelLayout = usePanelStore((state) => state.applyPanelLayout); // Publishes the layout to the store, which owns the panel targets each layout allows. useLayoutEffect(() => { @@ -546,7 +553,11 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon - {isCompactLayout ? themedSidebarChrome : null} + {isCompactLayout ? ( + + {themedSidebarChrome} + + ) : null} @@ -584,6 +595,34 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon ); } +// Keep native scroll ranges and gesture hosts intact while Settings covers the sidebar. +function CompactSidebarHost({ + visible, + interactive, + children, +}: { + visible: boolean; + interactive: boolean; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + function AppContainerLifetime({ children, sidebarGesturesEnabled, @@ -614,14 +653,18 @@ function SidebarChrome({ const isCompactLayout = useIsCompactFormFactor(); const isMobileActive = useIsMobilePanelActive("agent-list"); const overlay = presentation === "overlay"; - const active = resolveSidebarActivity(presentation !== "hidden", overlay, isMobileActive); + const active = resolveSidebarActivity( + presentation !== "hidden" && presentation !== "suspended", + overlay, + isMobileActive, + ); const hardwareKeyboardPresent = useHardwareKeyboardPresent(); return ( - {mounted ? ( + {mounted || presentation === "suspended" ? ( ) : null} @@ -1007,6 +1050,7 @@ export default function RootLayout() { } const layoutStyles = StyleSheet.create((theme) => ({ + compactSidebarHost: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }, surfaceFill: { flex: 1, backgroundColor: theme.colors.surface0, diff --git a/packages/app/src/components/left-sidebar.tsx b/packages/app/src/components/left-sidebar.tsx index ba40ab41fd..38b01fd334 100644 --- a/packages/app/src/components/left-sidebar.tsx +++ b/packages/app/src/components/left-sidebar.tsx @@ -1,6 +1,5 @@ import { SidebarViewSlot } from "@/plugins/sidebar-view"; import { useAddHost } from "@/hosts/add-host"; -import { router } from "expo-router"; import { CircleGauge, FolderPlus, @@ -85,8 +84,9 @@ import { useOwnsWindowChromeCorner, WindowChromeSafeArea } from "@/utils/desktop import { useCloseAgentListGesture } from "@/mobile-panels/gestures"; import { useLeftPanelWidth } from "@/mobile-panels/provider"; import { MobilePanelOverlay } from "@/mobile-panels/presentation"; -import { buildSettingsRoute } from "@/utils/host-routes"; -import { openHostOverview } from "@/navigation/settings-navigation"; +import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; +import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store"; +import { openSettingsFromSidebar } from "@/navigation/settings-navigation"; import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage"; import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton"; import { SidebarCalloutSlot } from "./sidebar-callout-slot"; @@ -157,6 +157,7 @@ export const LeftSidebar = memo(function LeftSidebar({ const { t } = useTranslation(); const insets = useSafeAreaInsets(); const isCompactLayout = useIsCompactFormFactor(); + const activeWorkspace = useActiveWorkspaceSelection(); const showMobileAgent = usePanelStore((state) => state.showMobileAgent); const { @@ -193,25 +194,26 @@ export const LeftSidebar = memo(function LeftSidebar({ const openProjectPicker = useOpenAddProject(); const { open: openImportSession, sheet: importSessionSheet } = useImportSession(); - // Each destination closes the navigation overlay first. Closing is idempotent, so a docked - // sidebar runs the same handler. + // Workspace destinations close the overlay; Settings retains it for the return journey. const handleOpenProject = useCallback(() => { void openProjectPicker(); }, [openProjectPicker]); const handleSettings = useCallback(() => { - showMobileAgent(); - router.push(buildSettingsRoute()); - }, [showMobileAgent]); + openSettingsFromSidebar({ workspace: activeWorkspace, isCompact: isCompactLayout }); + }, [activeWorkspace, isCompactLayout]); const handleAddHost = useAddHost(); const handleOpenHostSettings = useCallback( (serverId: string) => { - showMobileAgent(); - openHostOverview(serverId); + openSettingsFromSidebar({ + workspace: activeWorkspace, + isCompact: isCompactLayout, + route: buildSettingsHostSectionRoute(serverId, "host"), + }); }, - [showMobileAgent], + [activeWorkspace, isCompactLayout], ); const labels = useMemo( diff --git a/packages/app/src/mobile-panels/model.test.ts b/packages/app/src/mobile-panels/model.test.ts index ca4ef04a8a..a77c9684bc 100644 --- a/packages/app/src/mobile-panels/model.test.ts +++ b/packages/app/src/mobile-panels/model.test.ts @@ -305,3 +305,22 @@ describe("mobile panel ownership", () => { }); }); }); + +it("lands an explicit destination while the sidebar is suspended without a slide", () => { + const state = createMobilePanelMotionState({ target: "agent-list", revision: 1 }); + const result = transitionMobilePanel(state, { + type: "command", + selection: { target: "agent", revision: 2 }, + immediate: true, + }); + expect(result).toEqual({ + immediateTarget: "agent", + state: { + target: "agent", + revision: 2, + gesture: null, + motionTarget: "agent", + settledTarget: "agent", + }, + }); +}); diff --git a/packages/app/src/mobile-panels/model.ts b/packages/app/src/mobile-panels/model.ts index 363bcfc450..9b59eea3c6 100644 --- a/packages/app/src/mobile-panels/model.ts +++ b/packages/app/src/mobile-panels/model.ts @@ -17,6 +17,7 @@ export interface MobilePanelCommit { export interface MobilePanelTransition { animationTarget?: MobilePanelView; + immediateTarget?: MobilePanelView; commit?: MobilePanelCommit; state: MobilePanelMotionState; } @@ -48,7 +49,7 @@ function settleMobilePanelAtPosition( } export type MobilePanelEvent = - | { type: "command"; selection: MobilePanelSelection } + | { type: "command"; selection: MobilePanelSelection; immediate?: boolean } | { type: "gesture.begin"; origin: MobilePanelView } | { type: "gesture.finish"; @@ -78,6 +79,17 @@ export function transitionMobilePanel( if (event.selection.revision <= state.revision) { return { state }; } + if (event.immediate) { + return { + immediateTarget: event.selection.target, + state: { + ...event.selection, + gesture: null, + motionTarget: event.selection.target, + settledTarget: event.selection.target, + }, + }; + } // An interrupted drag left the position between anchors, so it moves back even when the // target is unchanged. Without a drag, the command adopts motion already heading there. const continuesCurrentMotion = !state.gesture && state.motionTarget === event.selection.target; diff --git a/packages/app/src/mobile-panels/provider.tsx b/packages/app/src/mobile-panels/provider.tsx index 77c00558ce..8fdf4ab5dc 100644 --- a/packages/app/src/mobile-panels/provider.tsx +++ b/packages/app/src/mobile-panels/provider.tsx @@ -157,6 +157,11 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) { const animateTransition = useCallback( (transition: MobilePanelTransition) => { "worklet"; + if (transition.immediateTarget) { + cancelAnimation(position); + position.value = getMobilePanelAnchor(transition.immediateTarget); + return; + } if (!transition.animationTarget) { return; } @@ -170,25 +175,27 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) { ); const applySelection = useCallback( - (selection: MobilePanelSelection) => { + (selection: MobilePanelSelection, immediate: boolean) => { "worklet"; const currentState = motionState.value; const transition = transitionMobilePanel(currentState, { type: "command", selection, + immediate, }); if (transition.state === currentState) { return; } motionState.value = transition.state; animateTransition(transition); + if (immediate) scheduleOnRN(publishActivePanel, selection.target, selection.revision); }, - [animateTransition, motionState], + [animateTransition, motionState, publishActivePanel], ); useEffect(() => { - return subscribeMobilePanelSelection((selection) => { - scheduleOnUI(applySelection, selection); + return subscribeMobilePanelSelection((selection, immediate) => { + scheduleOnUI(applySelection, selection, immediate); }); }, [applySelection]); diff --git a/packages/app/src/mobile-panels/selection.ts b/packages/app/src/mobile-panels/selection.ts index f47d9e737c..2ee7769b37 100644 --- a/packages/app/src/mobile-panels/selection.ts +++ b/packages/app/src/mobile-panels/selection.ts @@ -2,13 +2,14 @@ import { usePanelStore, type MobilePanelSelection } from "@/stores/panel-store"; /** Observe panel commands, including layout commands published before subscription. */ export function subscribeMobilePanelSelection( - onSelection: (selection: MobilePanelSelection) => void, + onSelection: (selection: MobilePanelSelection, immediate: boolean) => void, ) { const unsubscribe = usePanelStore.subscribe((state, previousState) => { if (state.mobilePanel !== previousState.mobilePanel) { - onSelection(state.mobilePanel); + onSelection(state.mobilePanel, state.layout.leftSidebar === "suspended"); } }); - onSelection(usePanelStore.getState().mobilePanel); + const state = usePanelStore.getState(); + onSelection(state.mobilePanel, state.layout.leftSidebar === "suspended"); return unsubscribe; } diff --git a/packages/app/src/navigation/settings-navigation.ts b/packages/app/src/navigation/settings-navigation.ts index 123b23077a..889eb093fc 100644 --- a/packages/app/src/navigation/settings-navigation.ts +++ b/packages/app/src/navigation/settings-navigation.ts @@ -1,5 +1,8 @@ import { router, type Href } from "expo-router"; -import { navigateToLastWorkspace } from "@/stores/navigation-active-workspace-store"; +import { + navigateToWorkspace, + navigateToLastWorkspace, +} from "@/stores/navigation-active-workspace-store"; import { buildOpenProjectRoute, buildProjectSettingsRoute, @@ -10,6 +13,27 @@ import { type SettingsSectionSlug, } from "@/utils/host-routes"; +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; +import { usePanelStore } from "@/stores/panel-store"; +import { + beginSettingsSidebarVisit, + getSettingsSidebarReturn, +} from "@/navigation/settings-presentation/session"; + +export function openSettingsFromSidebar(input: { + workspace: ActiveWorkspaceSelection | null; + isCompact: boolean; + route?: Href; +}): void { + const panels = usePanelStore.getState(); + if (input.isCompact && input.workspace && panels.mobilePanel.target === "agent-list") { + beginSettingsSidebarVisit(input.workspace); + } else { + panels.showMobileAgent(); + } + router.push(input.route ?? buildSettingsRoute()); +} + export type SettingsView = | { kind: "plugin"; serverId: string; pluginId: string; screenId: string } | { kind: "root" } @@ -27,6 +51,15 @@ export function openProjectSettings(serverId: string, projectId: string): void { export function returnFromSettings(view: SettingsView): void { if (view.kind === "root") { + const destination = getSettingsSidebarReturn(); + if (destination && usePanelStore.getState().mobilePanel.target === "agent-list") { + navigateToWorkspace({ + serverId: destination.serverId, + workspaceId: destination.workspaceId, + surface: "sidebar", + }); + return; + } if (!navigateToLastWorkspace()) { router.replace(buildOpenProjectRoute()); } diff --git a/packages/app/src/navigation/settings-presentation/index.ts b/packages/app/src/navigation/settings-presentation/index.ts index cdf86b0d19..62dbb30223 100644 --- a/packages/app/src/navigation/settings-presentation/index.ts +++ b/packages/app/src/navigation/settings-presentation/index.ts @@ -1,19 +1,24 @@ +import { useIsCompactFormFactor } from "@/constants/layout"; +import { usePanelStore, type LeftSidebarPresentation } from "@/stores/panel-store"; import { useCallback, useLayoutEffect, useRef } from "react"; import { ScrollView, type NativeScrollEvent, type NativeSyntheticEvent } from "react-native"; import { usePathname, useRootNavigationState } from "expo-router"; +import { useIsFocused, type ParamListBase } from "expo-router/react-navigation"; +import { useNavigation } from "expo-router"; +import type { NativeStackNavigationProp } from "expo-router/native-stack"; +import { isWeb } from "@/constants/platform"; import { useStore } from "zustand"; import { useIsLastWorkspaceSelectionHydrated, useLastWorkspaceSelection, } from "@/stores/navigation-active-workspace-store"; -import { createSettingsPresentation } from "./model"; - -const selection = createSettingsPresentation(); +import { settingsPresentation as selection } from "./session"; // Mount once above the sibling Settings routes so replacements and Back share // one visit, and leaving Settings gives the next workspace entry a fresh default. export function useSettingsRouteEntry(): void { const pathname = usePathname(); + const isCompact = useIsCompactFormFactor(); const navigationState = useRootNavigationState(); const routeKey = navigationState?.routes[navigationState.index]?.key; const workspace = useLastWorkspaceSelection(); @@ -21,15 +26,46 @@ export function useSettingsRouteEntry(): void { const workspaceServerId = workspace?.serverId ?? null; useLayoutEffect(() => { if (isWorkspaceHydrated && routeKey) { - selection.enterRoute({ key: routeKey, pathname }, workspaceServerId); + if (!isCompact) selection.clearSidebarReturn(); + if (selection.enterRoute({ key: routeKey, pathname }, workspaceServerId)) { + usePanelStore.getState().showMobileAgent(); + } } - }, [pathname, routeKey, workspaceServerId, isWorkspaceHydrated]); + }, [pathname, routeKey, workspaceServerId, isWorkspaceHydrated, isCompact]); } export function useSettingsHostSelection(): string | null { return useStore(selection.store, (state) => state.selectedServerId); } +export function useSettingsSidebarPresentation(input: { + presentation: LeftSidebarPresentation; + visible: boolean; +}): { presentation: LeftSidebarPresentation; visible: boolean } { + const origin = useStore(selection.store, (state) => state.sidebarReturn); + const pathname = usePathname(); + const compact = useIsCompactFormFactor(); + if (compact && origin && (pathname === "/settings" || pathname.startsWith("/settings/"))) { + return { presentation: "suspended", visible: origin.phase === "opening" }; + } + return input; +} + +// Native layout precedes screen appearance; only the navigator can finish that handoff. +export function useSettingsContentPresented() { + const focused = useIsFocused(); + const navigation = useNavigation>(); + useLayoutEffect(() => { + if (isWeb) return; + return navigation.addListener("transitionEnd", ({ data }) => { + if (!data.closing) selection.presentContent(); + }); + }, [navigation]); + return useCallback(() => { + if (isWeb && focused) selection.presentContent(); + }, [focused]); +} + export const selectSettingsHost = selection.selectHost; // Sibling routes remount the wide sidebar. Only the current mount owns its diff --git a/packages/app/src/navigation/settings-presentation/model.test.ts b/packages/app/src/navigation/settings-presentation/model.test.ts index a8970b17b4..73188bb39e 100644 --- a/packages/app/src/navigation/settings-presentation/model.test.ts +++ b/packages/app/src/navigation/settings-presentation/model.test.ts @@ -130,3 +130,39 @@ describe("Settings sidebar presentation", () => { expect(settings.attachSidebar().offset).toBe(0); }); }); + +describe("Settings sidebar return", () => { + it("retains the origin through nested Settings and consumes it on return", () => { + const settings = createSettingsPresentation(); + const origin = { serverId: "host", workspaceId: "workspace" }; + settings.beginSidebarVisit(origin); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + settings.enterRoute({ key: "appearance", pathname: "/settings/appearance" }, "host"); + expect(settings.store.getState().sidebarReturn).toEqual({ ...origin, phase: "opening" }); + settings.presentContent(); + expect(settings.store.getState().sidebarReturn).toEqual({ ...origin, phase: "covered" }); + expect( + settings.enterRoute({ key: "workspace", pathname: "/h/host/workspace/workspace" }, "host"), + ).toBe(false); + expect(settings.store.getState().sidebarReturn).toBeNull(); + }); + + it("discards the sidebar when returning to a different workspace", () => { + const settings = createSettingsPresentation(); + settings.beginSidebarVisit({ serverId: "host", workspaceId: "workspace" }); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + expect(settings.enterRoute({ key: "other", pathname: "/h/host/workspace/other" }, "host")).toBe( + true, + ); + expect(settings.store.getState().sidebarReturn).toBeNull(); + }); + + it("does not carry sidebar returns into another visit or a wide layout", () => { + const settings = createSettingsPresentation(); + settings.beginSidebarVisit({ serverId: "host", workspaceId: "workspace" }); + settings.clearSidebarReturn(); + settings.enterRoute({ key: "root", pathname: "/settings" }, "host"); + expect(settings.store.getState().sidebarReturn).toBeNull(); + expect(createSettingsPresentation().store.getState().sidebarReturn).toBeNull(); + }); +}); diff --git a/packages/app/src/navigation/settings-presentation/model.ts b/packages/app/src/navigation/settings-presentation/model.ts index 2a88e9d82b..c6784a11cf 100644 --- a/packages/app/src/navigation/settings-presentation/model.ts +++ b/packages/app/src/navigation/settings-presentation/model.ts @@ -1,3 +1,5 @@ +import type { ActiveWorkspaceSelection } from "@/stores/last-workspace-selection"; +import { parseHostWorkspaceRouteFromPathname } from "@/utils/host-routes"; import { createStore } from "zustand/vanilla"; interface SettingsRouteEntry { @@ -7,15 +9,34 @@ interface SettingsRouteEntry { interface SettingsSelectionState { selectedServerId: string | null; + sidebarReturn: (ActiveWorkspaceSelection & { phase: "opening" | "covered" }) | null; } export function createSettingsPresentation() { - const store = createStore(() => ({ selectedServerId: null })); + const store = createStore(() => ({ + selectedServerId: null, + sidebarReturn: null, + })); const enteredRoutes = new Map(); let inSettings = false; let sidebarOffset = 0; let sidebarOwner: object | null = null; + function beginSidebarVisit(workspace: ActiveWorkspaceSelection) { + store.setState({ sidebarReturn: { ...workspace, phase: "opening" } }); + } + + function presentContent() { + const origin = store.getState().sidebarReturn; + if (origin?.phase === "opening") { + store.setState({ sidebarReturn: { ...origin, phase: "covered" } }); + } + } + + function clearSidebarReturn() { + if (store.getState().sidebarReturn) store.setState({ sidebarReturn: null }); + } + function attachSidebar() { const owner = {}; sidebarOwner = owner; @@ -35,17 +56,24 @@ export function createSettingsPresentation() { function enterRoute( { key, pathname }: SettingsRouteEntry, workspaceServerId: string | null, - ): void { + ): boolean { const isSettings = pathname === "/settings" || pathname.startsWith("/settings/"); if (!isSettings) { + const origin = store.getState().sidebarReturn; + const destination = parseHostWorkspaceRouteFromPathname(pathname); + const discardSidebar = + origin !== null && + (origin.serverId !== destination?.serverId || + origin.workspaceId !== destination?.workspaceId); + clearSidebarReturn(); sidebarOffset = 0; sidebarOwner = null; inSettings = false; enteredRoutes.clear(); - return; + return discardSidebar; } // A retained route returning through Back must not replay its old host intent. - if (enteredRoutes.get(key) === pathname) return; + if (enteredRoutes.get(key) === pathname) return false; const isNewVisit = !inSettings; inSettings = true; enteredRoutes.set(key, pathname); @@ -56,11 +84,20 @@ export function createSettingsPresentation() { } else if (isNewVisit) { store.setState({ selectedServerId: workspaceServerId }); } + return false; } function selectHost(serverId: string): void { store.setState({ selectedServerId: serverId }); } - return { store, enterRoute, selectHost, attachSidebar }; + return { + store, + enterRoute, + selectHost, + attachSidebar, + beginSidebarVisit, + clearSidebarReturn, + presentContent, + }; } diff --git a/packages/app/src/navigation/settings-presentation/session/index.ts b/packages/app/src/navigation/settings-presentation/session/index.ts new file mode 100644 index 0000000000..519539966e --- /dev/null +++ b/packages/app/src/navigation/settings-presentation/session/index.ts @@ -0,0 +1,6 @@ +import { createSettingsPresentation } from "../model"; + +/** @package */ +export const settingsPresentation = createSettingsPresentation(); +export const beginSettingsSidebarVisit = settingsPresentation.beginSidebarVisit; +export const getSettingsSidebarReturn = () => settingsPresentation.store.getState().sidebarReturn; diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index abd19f5a1b..1d98e8e288 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -1,3 +1,4 @@ +import { useSettingsContentPresented } from "@/navigation/settings-presentation"; import { AppearanceText as Text } from "@/appearance/text"; import { useHardwareKeyboardPresent } from "@/keyboard"; import { useAddHost } from "@/hosts/add-host"; @@ -1118,6 +1119,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { const appVersion = resolveAppVersion(); const appVersionText = formatVersionWithPrefix(appVersion); const isCompactLayout = useIsCompactFormFactor(); + const onContentLayout = useSettingsContentPresented(); const insets = useSafeAreaInsets(); const insetBottomStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]); const hosts = useHosts(); @@ -1341,7 +1343,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { if (settingsLoading) { return ( - + {t("settings.loading")} ); @@ -1350,7 +1352,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // Mobile root: full-screen sidebar-as-list. if (isCompactLayout && view.kind === "root") { return ( - + + {content} @@ -1382,7 +1384,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // region + traffic-light padding; detail pane renders whatever header the // selected section provides. return ( - + { + revealWorkspace: (workspaceKey, surface) => { useWorkspaceLayoutStore.getState().focusWorkspace(workspaceKey); - usePanelStore.getState().showMobileAgent(); + const panels = usePanelStore.getState(); + if (surface === "sidebar") panels.showMobileAgentList(); + else panels.showMobileAgent(); }, getSessionWorkspaces: (serverId) => useSessionStore.getState().sessions[serverId]?.workspaces, isWorkspaceLayoutHydrated: () => useWorkspaceLayoutStore.persist.hasHydrated(), diff --git a/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts b/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts index 5dbc292524..db68e05602 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/navigation.test.ts @@ -77,6 +77,16 @@ describe("workspace navigation", () => { expect(revealed).toEqual([null]); }); + it("returns to the sidebar without revealing workspace content first", () => { + const surfaces: (string | undefined)[] = []; + const { deps, navigations } = createFakeDeps({ + revealWorkspace: (_workspaceKey, surface) => surfaces.push(surface), + }); + navigateToWorkspace({ serverId: "server", workspaceId: "workspace", surface: "sidebar" }, deps); + expect(surfaces).toEqual(["sidebar"]); + expect(navigations).toEqual(["/h/server/workspace/workspace"]); + }); + it("reveals an explicit target after opening instead of forcing center", () => { const workspace = { id: "workspace" } as WorkspaceDescriptor; const { deps, revealed } = createFakeDeps({ diff --git a/packages/app/src/stores/navigation-active-workspace-store/navigation.ts b/packages/app/src/stores/navigation-active-workspace-store/navigation.ts index bbc55701d6..ed73b7ed2d 100644 --- a/packages/app/src/stores/navigation-active-workspace-store/navigation.ts +++ b/packages/app/src/stores/navigation-active-workspace-store/navigation.ts @@ -23,6 +23,7 @@ export interface NavigateToWorkspaceInput { serverId: string; workspaceId: string; target?: WorkspaceTabTarget; + surface?: "sidebar"; pin?: boolean; placement?: WorkspaceTabPlacement; asTab?: boolean; @@ -35,7 +36,7 @@ export interface NavigateToWorkspaceDeps extends PrepareWorkspaceTabDeps { rememberLastWorkspace: (selection: ActiveWorkspaceSelection) => void; navigateToRoute: (route: string) => void; revealTab: (workspaceKey: string, tabId: string | null) => void; - revealWorkspace: (workspaceKey: string) => void; + revealWorkspace: (workspaceKey: string, surface?: "sidebar") => void; } export interface NavigateToLastWorkspaceDeps extends NavigateToWorkspaceDeps { @@ -100,7 +101,10 @@ export function navigateToWorkspace( if (input.target) { prepareWorkspaceTab({ ...input, target: input.target }, { openTab }); } else { - deps.revealWorkspace(`${input.serverId}:${resolvedWorkspaceId ?? input.workspaceId}`); + deps.revealWorkspace( + `${input.serverId}:${resolvedWorkspaceId ?? input.workspaceId}`, + input.surface, + ); } const route = buildHostWorkspaceRoute(input.serverId, input.workspaceId); diff --git a/packages/app/src/stores/panel-store/index.ts b/packages/app/src/stores/panel-store/index.ts index 660f2d1b62..8673030fdc 100644 --- a/packages/app/src/stores/panel-store/index.ts +++ b/packages/app/src/stores/panel-store/index.ts @@ -52,6 +52,7 @@ export type ExpandedPathsUpdate = string[] | ((currentPaths: string[]) => string export interface PanelState { // Mobile: React's durable target plus the generation that owns it. mobilePanel: MobilePanelSelection; + layout: PanelLayout; // Desktop: independent sidebar toggles desktop: DesktopSidebarState; @@ -120,6 +121,7 @@ export const usePanelStore = create()( (set) => ({ // Mobile always starts at agent view mobilePanel: { target: "agent", revision: 0 }, + layout: { isCompact: false, leftSidebar: "hidden" }, // Desktop defaults based on platform desktop: { @@ -215,7 +217,12 @@ export const usePanelStore = create()( applyPanelLayout: (layout) => set((state) => { const mobilePanel = reconcileMobilePanel(state.mobilePanel, layout); - return mobilePanel === state.mobilePanel ? state : { mobilePanel }; + const layoutUnchanged = + state.layout.isCompact === layout.isCompact && + state.layout.leftSidebar === layout.leftSidebar; + return mobilePanel === state.mobilePanel && layoutUnchanged + ? state + : { mobilePanel, layout }; }), setExpandedPathsForWorkspace: (workspaceKey, paths) => diff --git a/packages/app/src/stores/panel-store/state.test.ts b/packages/app/src/stores/panel-store/state.test.ts index 317d4fd9a8..b9613ab020 100644 --- a/packages/app/src/stores/panel-store/state.test.ts +++ b/packages/app/src/stores/panel-store/state.test.ts @@ -171,6 +171,30 @@ describe("panel-store wide navigation overlay", () => { expect(usePanelStore.getState().mobilePanel.target).toBe("agent"); }); + it("retains the sidebar through a suspended layout without publishing motion", () => { + const panels = usePanelStore.getState(); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "overlay" }); + panels.showMobileAgentList(); + const selection = usePanelStore.getState().mobilePanel; + panels.applyPanelLayout({ isCompact: true, leftSidebar: "suspended" }); + expect(usePanelStore.getState().mobilePanel).toBe(selection); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "overlay" }); + expect(usePanelStore.getState().mobilePanel).toBe(selection); + }); + + it("publishes an immediate destination when navigation closes a suspended sidebar", () => { + const panels = usePanelStore.getState(); + panels.showMobileAgentList(); + panels.applyPanelLayout({ isCompact: true, leftSidebar: "suspended" }); + const commands: boolean[] = []; + const unsubscribe = subscribeMobilePanelSelection((_selection, immediate) => + commands.push(immediate), + ); + panels.showMobileAgent(); + unsubscribe(); + expect(commands).toEqual([true, true]); + }); + it("drops the overlay target once the sidebar is no longer presented as an overlay", () => { usePanelStore.getState().showMobileAgentList(); usePanelStore.getState().applyPanelLayout({ isCompact: false, leftSidebar: "overlay" }); diff --git a/packages/app/src/stores/panel-store/state.ts b/packages/app/src/stores/panel-store/state.ts index a9971fa458..5e9cc2119d 100644 --- a/packages/app/src/stores/panel-store/state.ts +++ b/packages/app/src/stores/panel-store/state.ts @@ -26,8 +26,8 @@ export interface PanelLayoutInput { isCompact: boolean; } -/** How app chrome presents the left sidebar: over the workspace, beside it, or not at all. */ -export type LeftSidebarPresentation = "overlay" | "dock" | "hidden"; +/** Sidebar presentation; suspended retains an overlay while Settings covers it. */ +export type LeftSidebarPresentation = "overlay" | "dock" | "hidden" | "suspended"; /** The panels app chrome presents, which decide the mobile panel targets that can stay selected. */ export interface PanelLayout extends PanelLayoutInput { @@ -77,7 +77,7 @@ export function setMobilePanelTarget( } /** - * Only an overlay sidebar shows the `agent-list` target. A docked or hidden sidebar drops it, so + * Only an overlay or suspended sidebar holds `agent-list`. A docked or hidden sidebar drops it, so * a stale target cannot resurface the overlay on the next collapse. Always invalidate in-flight * gestures, even when an opening swipe has not committed `agent-list` yet. */ @@ -98,7 +98,9 @@ export function reconcileMobilePanel( layout: PanelLayout, ): MobilePanelSelection { const sidebarReconciled = - layout.leftSidebar === "overlay" ? selection : dropOverlayAgentList(selection); + layout.leftSidebar === "overlay" || layout.leftSidebar === "suspended" + ? selection + : dropOverlayAgentList(selection); if (!layout.isCompact && sidebarReconciled.target === "file-explorer") { return setMobilePanelTarget(sidebarReconciled, "agent"); } From a6a37b568d7cc8a84c91c5822b21319414a13db5 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 13:44:33 +0700 Subject: [PATCH 040/160] fix(app): correct composer glyph and placeholder tones (#9608) * fix(app): mute labelled toolbar glyphs to match their labels Touch-sized composer glyphs rested at foreground while the label beside them used foregroundMuted. Use the existing label/icon glyph roles: a labelled glyph takes the muted tone, while an icon-only glyph keeps the foreground header-icon treatment from #8909. * test(app): keep toolbar tone coverage in the browser journey The component-level probe asserted the color prop handed to a stub icon in JSDOM, which the testing rules forbid. The real-browser journey already checks the rendered stroke and label colors for both glyph roles. * test(app): expect the muted tone for a labelled toolbar glyph The composer layout test still asserted the old foreground tone for the label role. * fix(app): quiet the composer placeholder to extra muted The empty composer painted its placeholder with surface4, a surface token, instead of a text tone. Use foregroundExtraMuted so it sits below foregroundMuted and above the background, and document the composer-specific exception. * test(app): clean up a composer tone fixture when setup fails The helper now releases the seeded agent and repository if navigation or the readiness check throws before the test owns cleanup. --- docs/design.md | 8 +- .../e2e/browser/composer-toolbar-tone.spec.ts | 131 ++++++++++++++++++ .../support/helpers/composer-toolbar-tone.ts | 55 ++++++++ .../components/ui/control-geometry.test.ts | 11 +- .../app/src/components/ui/control-geometry.ts | 9 +- .../composer/agent-controls/layout.test.ts | 2 +- packages/app/src/composer/input/input.tsx | 2 +- 7 files changed, 207 insertions(+), 11 deletions(-) create mode 100644 packages/app/e2e/browser/composer-toolbar-tone.spec.ts create mode 100644 packages/app/e2e/support/helpers/composer-toolbar-tone.ts diff --git a/docs/design.md b/docs/design.md index 662e714a36..57b3a7c9e1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -40,9 +40,9 @@ Weight has three tiers, applied by role: The rule, condensed: text that _names_ a surface or a group is `medium`. Text that lives _inside_ a surface or a group is `normal`. Top-of-screen titles are ``, which is lighter still. -Foreground is for the thing being acted on: row titles, section headings, the selected sidebar item. `foregroundMuted` is for context: hints, descriptions, secondary metadata, idle sidebar items, placeholders, status text. +Foreground is for the thing being acted on: row titles, section headings, the selected sidebar item. `foregroundMuted` is for context: hints, descriptions, secondary metadata, idle sidebar items, placeholders, status text. The composer's empty placeholder is quieter; it uses `foregroundExtraMuted`. -`foregroundExtraMuted` is reserved for passive chrome that must sit behind muted text, such as an always-visible window control. Use the solid token instead of lowering SVG opacity; per-path opacity makes overlapping icon strokes render unevenly. Interactive hover and pressed states return to `foreground`. +`foregroundExtraMuted` is reserved for passive chrome that must sit behind muted text, such as an always-visible window control, and for the composer's empty placeholder. Use the solid token instead of lowering SVG opacity; per-path opacity makes overlapping icon strokes render unevenly. Interactive hover and pressed states return to `foreground`. A theme states places and identity; `packages/app/src/styles/derive-colors.ts` derives their relationships. Sidebar hover and selected fills step from the sidebar toward the foreground. For plugin themes, passive text on those states derives against the actual state surface; page tertiary text is a separate relationship. Explicit plugin semantic overrides take precedence over derived defaults. Built-in themes retain their chosen passive text. `packages/app/src/styles/theme-contrast.test.ts` checks the built-in and representative plugin palettes against contrast floors. @@ -72,7 +72,7 @@ the sidebar. Apply it as `backgroundColor`; setting `opacity` on the control als Controls come in two sizes, defined once in `control-geometry.ts`. The default is the right size almost everywhere — pages, dialogs, forms, settings rows, the setup flow — so don't pass a size. It is 32px tall where a pointer drives it and 44px where controls are touch-sized, so every touch control meets the iOS HIG's 44pt hit region. `sm` is 28px pointer and 32px touch, with `fontSize.sm` labels, and is for tight chrome only: toolbars, nested settings rows, dense inline row actions. A `size="sm"` on an ordinary page or dialog is wrong, and so is choosing a size from `useIsCompactFormFactor()`. -Dense toolbar rows, such as the composer's, are the exception to the 44pt control. Touch-sized the row is 44pt tall and each control is a 36pt circle (`TOOLBAR_DISC_SIZE`): send and stop fill it, and every other control's pressed highlight fills it, so every highlight is the same fully rounded shape. Labelled pickers are 36pt pills. A control lays out at its full highlight (`toolbarSlot`, `toolbarContentSlot`) with no gap between controls (`TOOLBAR_CONTROL_GAP`), so neighbouring highlights touch and never overlap. Toolbar glyphs match the header icons: 20pt, the app's 1.5px stroke, resting at `foreground` (`toolbarGlyphsFor`). The context ring is 18pt with a 2px stroke (`TOOLBAR_RINGS`): a circle fills its box where an outline glyph does not, and a thin circle reads lighter than a glyph at the same stroke. A disc's solid glyph, such as the stop square, stays at the `md` size (`TOOLBAR_DISC_GLYPH_SIZES`). Pointer-sized toolbars keep 28px controls, a 4px gap, and a 16pt muted glyph that brightens on hover. +Dense toolbar rows, such as the composer's, are the exception to the 44pt control. Touch-sized the row is 44pt tall and each control is a 36pt circle (`TOOLBAR_DISC_SIZE`): send and stop fill it, and every other control's pressed highlight fills it, so every highlight is the same fully rounded shape. Labelled pickers are 36pt pills. A control lays out at its full highlight (`toolbarSlot`, `toolbarContentSlot`) with no gap between controls (`TOOLBAR_CONTROL_GAP`), so neighbouring highlights touch and never overlap. Touch-sized toolbar glyphs are 20pt at the app's 1.5px stroke. An icon-only control's glyph matches the header icons and rests at `foreground`; a glyph beside a label rests at `foregroundMuted` so the two read as one quiet unit (`toolbarGlyphsFor`). The context ring is 18pt with a 2px stroke (`TOOLBAR_RINGS`): a circle fills its box where an outline glyph does not, and a thin circle reads lighter than a glyph at the same stroke. A disc's solid glyph, such as the stop square, stays at the `md` size (`TOOLBAR_DISC_GLYPH_SIZES`). Pointer-sized toolbars keep 28px controls, a 4px gap, and a 16pt muted glyph that brightens on hover. In the composer, the first glyph's ink starts on the text column's edge, and the trailing control is always a disc, so the row does not shift as it changes between voice mode, send and stop. The disc nests into the corner, as far from the right edge as from the bottom, and touch-sized the composer's corner radius is concentric with it (`packages/app/src/composer/input/toolbar-rails.ts`). Touch-sized the disc keeps a 6pt clearance from its neighbour, because it is always painted and a pressed neighbour would merge with it. The attach button sits 2pt closer to the picker than its highlight would put it: the plus is all thin arms, so the full gap reads wide. That offset is set by eye. @@ -269,7 +269,7 @@ New status pills use ``. Identity, shortcut, and interactive link b - A "Settings" CTA on a detail page. Detail pages are settings; settings is reached from the sidebar, the host entry, or a row's kebab menu. - The word "checkout" in UI strings or identifiers. The term is "workspace". - New color tokens or hardcoded hex outside the palette. The identity color table is the documented exception (§13), not a license. -- Placeholder text dimmed beyond `foregroundMuted`. No extra opacity, no italics, no ghost-text. +- Placeholder text dimmed beyond `foregroundMuted`, except the composer's empty placeholder, which uses `foregroundExtraMuted`. No extra opacity, no italics, no ghost-text. - `onPointerEnter` and `onPointerLeave`. They do not fire on native iOS. Hover uses Pressable's `onHoverIn`/`onHoverOut` gated with `isHovered || isCompact || isNative`. - Raw DOM APIs without an `isWeb` guard. - Spacing values outside the scale. `padding: 20` and `gap: 10` are wrong. diff --git a/packages/app/e2e/browser/composer-toolbar-tone.spec.ts b/packages/app/e2e/browser/composer-toolbar-tone.spec.ts new file mode 100644 index 0000000000..6d4b0a704f --- /dev/null +++ b/packages/app/e2e/browser/composer-toolbar-tone.spec.ts @@ -0,0 +1,131 @@ +import { expect, test } from "../support/fixtures"; +import { composerLocator, expectComposerVisible } from "../support/helpers/composer"; +import { + composerControl, + expectGlyphMatchesLabel, + expectIconOnlyGlyph, + readComposerControlTone, + readComposerPlaceholderTone, + readComposerTextTone, +} from "../support/helpers/composer-toolbar-tone"; +import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; + +const THINKING = "agent-thinking-selector"; +const MODE = "mode-control"; +const ATTACH = "message-input-attach-button"; +const COMBINED_MODEL = "combined-model-selector"; + +async function openSeededComposer( + page: import("@playwright/test").Page, + repoPrefix: string, + readyTestId = MODE, +) { + const agent = await seedMockAgentWorkspace({ + repoPrefix, + title: "Toolbar tone", + model: "ten-second-stream", + }); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + await expect(composerControl(page, readyTestId)).toBeVisible({ timeout: 30_000 }); + return agent; + } catch (error) { + await agent.cleanup(); + throw error; + } +} + +test.describe("Composer toolbar glyph tone", () => { + test.describe.configure({ timeout: 180_000 }); + + test.describe("on a touch screen", () => { + test.use({ hasTouch: true, viewport: { width: 1024, height: 1366 } }); + + test("a glyph beside its label matches the label while an icon-only glyph stays foreground", async ({ + page, + }) => { + const agent = await openSeededComposer(page, "composer-tone-touch-"); + try { + const thinking = await readComposerControlTone(composerControl(page, THINKING)); + const mode = await readComposerControlTone(composerControl(page, MODE)); + const attach = await readComposerControlTone(composerControl(page, ATTACH)); + + expectGlyphMatchesLabel(thinking, "thinking"); + expectGlyphMatchesLabel(mode, "mode"); + expectIconOnlyGlyph(attach, "attach"); + expect(attach.glyph, "an icon-only glyph is brighter than a labelled glyph").not.toBe( + thinking.label, + ); + } finally { + await agent.cleanup(); + } + }); + }); + + test.describe("on a compact non-touch window", () => { + test.use({ hasTouch: false, viewport: { width: 590, height: 844 } }); + + test("the icon-only thinking glyph stays foreground and the labelled mode glyph matches its label", async ({ + page, + }) => { + const agent = await openSeededComposer(page, "composer-tone-compact-"); + try { + const thinking = await readComposerControlTone(composerControl(page, THINKING)); + const mode = await readComposerControlTone(composerControl(page, MODE)); + const attach = await readComposerControlTone(composerControl(page, ATTACH)); + + expectIconOnlyGlyph(thinking, "thinking"); + expectGlyphMatchesLabel(mode, "mode"); + expectIconOnlyGlyph(attach, "attach"); + expect(thinking.glyph, "the icon-only glyphs share one tone").toBe(attach.glyph); + expect(thinking.glyph, "an icon-only glyph is brighter than a labelled glyph").not.toBe( + mode.label, + ); + } finally { + await agent.cleanup(); + } + }); + }); + + test.describe("on a folded compact non-touch window", () => { + test.use({ hasTouch: false, viewport: { width: 480, height: 844 } }); + + test("the empty composer placeholder is quieter than its labels", async ({ page }) => { + const agent = await openSeededComposer(page, "composer-tone-placeholder-", COMBINED_MODEL); + try { + const placeholder = await readComposerPlaceholderTone(composerLocator(page)); + const extraMuted = await readComposerTextTone( + composerControl(page, "combined-model-selector-thinking-label"), + ); + const muted = await readComposerTextTone( + composerControl(page, "combined-model-selector-model-label"), + ); + + expect(placeholder, "the composer paints a placeholder").not.toBeNull(); + expect(extraMuted, "the folded thinking label paints the extra-muted tone").not.toBeNull(); + expect(placeholder, "the placeholder uses the extra-muted tone").toBe(extraMuted); + expect(placeholder, "the placeholder is quieter than a labelled glyph").not.toBe(muted); + } finally { + await agent.cleanup(); + } + }); + }); + + test.describe("with a wide pointer", () => { + test.use({ hasTouch: false, viewport: { width: 1280, height: 800 } }); + + test("a labelled glyph stays muted and matches its label", async ({ page }) => { + const agent = await openSeededComposer(page, "composer-tone-pointer-"); + try { + const thinking = await readComposerControlTone(composerControl(page, THINKING)); + const mode = await readComposerControlTone(composerControl(page, MODE)); + + expectGlyphMatchesLabel(thinking, "thinking"); + expectGlyphMatchesLabel(mode, "mode"); + } finally { + await agent.cleanup(); + } + }); + }); +}); diff --git a/packages/app/e2e/support/helpers/composer-toolbar-tone.ts b/packages/app/e2e/support/helpers/composer-toolbar-tone.ts new file mode 100644 index 0000000000..e64caf7a43 --- /dev/null +++ b/packages/app/e2e/support/helpers/composer-toolbar-tone.ts @@ -0,0 +1,55 @@ +import { expect, type Locator, type Page } from "@playwright/test"; + +/** The tones a composer toolbar control paints: its glyph's stroke and its label's text color. */ +export interface ComposerControlTone { + /** The visible glyph's stroke, or null when the control paints no glyph. */ + glyph: string | null; + /** The visible label's color, or null when the control is icon-only. */ + label: string | null; +} + +export function composerControl(page: Page, testId: string): Locator { + return page.getByTestId(testId).filter({ visible: true }).first(); +} + +/** + * Reads the colors the control actually paints. The toolbar glyph and its label are separate + * nodes, so this is the only way to tell whether they match. + */ +export async function readComposerControlTone(control: Locator): Promise { + return control.evaluate((element) => { + const visible = (node: Element) => node.getClientRects().length > 0; + const glyph = Array.from(element.querySelectorAll("svg")).find(visible); + const label = Array.from(element.querySelectorAll("*")) + .filter(visible) + .find((node) => + [...node.childNodes].some( + (child) => child.nodeType === Node.TEXT_NODE && child.textContent?.trim(), + ), + ); + return { + glyph: glyph ? getComputedStyle(glyph).stroke : null, + label: label ? getComputedStyle(label).color : null, + }; + }); +} + +export function expectGlyphMatchesLabel(tone: ComposerControlTone, name: string): void { + expect(tone.label, `${name} paints a label`).not.toBeNull(); + expect(tone.glyph, `${name}'s glyph matches its label`).toBe(tone.label); +} + +export function expectIconOnlyGlyph(tone: ComposerControlTone, name: string): void { + expect(tone.label, `${name} is icon-only`).toBeNull(); + expect(tone.glyph, `${name} paints a glyph`).not.toBeNull(); +} + +/** The color the browser paints in a text input's placeholder. */ +export async function readComposerPlaceholderTone(input: Locator): Promise { + return input.evaluate((element) => getComputedStyle(element, "::placeholder").color); +} + +/** The color the browser paints for a text node. */ +export async function readComposerTextTone(text: Locator): Promise { + return text.evaluate((element) => getComputedStyle(element).color); +} diff --git a/packages/app/src/components/ui/control-geometry.test.ts b/packages/app/src/components/ui/control-geometry.test.ts index 2e3352397c..58086cf212 100644 --- a/packages/app/src/components/ui/control-geometry.test.ts +++ b/packages/app/src/components/ui/control-geometry.test.ts @@ -144,11 +144,20 @@ describe("toolbar glyphs and spacing", () => { expect(toolbarGlyphsFor("touch").label).toEqual({ size: 20, strokeWidth: 1.5, - tone: "foreground", + tone: "muted", }); expect(TOOLBAR_GLYPH_SIZES.label).toEqual({ xs: 20, md: 16 }); }); + it("mutes a touch glyph paired with a label while keeping an icon-only touch glyph foreground", () => { + const { icon, label } = toolbarGlyphsFor("touch"); + const colors = { foreground: "#fafafa", foregroundMuted: "#a1a5a4" }; + const palette = { colors } as unknown as Theme; + + expect(toolbarGlyphColor(palette, label.tone)).toBe(colors.foregroundMuted); + expect(toolbarGlyphColor(palette, icon.tone)).toBe(colors.foreground); + }); + it("sizes the touch context ring to the toolbar glyph's ink and keeps the pointer ring", () => { expect(TOOLBAR_RINGS).toEqual({ touch: { size: 18, strokeWidth: 2 }, diff --git a/packages/app/src/components/ui/control-geometry.ts b/packages/app/src/components/ui/control-geometry.ts index f8d3132e38..bec7819b7f 100644 --- a/packages/app/src/components/ui/control-geometry.ts +++ b/packages/app/src/components/ui/control-geometry.ts @@ -132,9 +132,10 @@ export function iconSizeFor(size: IconSize): SizingValue { } /** - * The glyph a toolbar control paints. Touch-sized every toolbar glyph matches the header icons: - * 20pt at the app's 1.5px stroke, resting at `foreground`. Pointer-sized it is the `md` glyph at - * the same stroke and rests muted until hovered. + * The glyph a toolbar control paints. Touch-sized every toolbar glyph is 20pt at the app's 1.5px + * stroke. An icon-only control's glyph matches the header icons and rests at `foreground`; a glyph + * paired with a label rests muted so the control reads as one quiet unit with its label. + * Pointer-sized it is the `md` glyph at the same stroke and rests muted until hovered. */ export type ToolbarGlyphTone = "foreground" | "muted"; @@ -160,7 +161,7 @@ const POINTER_TOOLBAR_GLYPH: ToolbarGlyph = { const TOOLBAR_GLYPHS: Record = { touch: { icon: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "foreground" }, - label: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "foreground" }, + label: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "muted" }, }, pointer: { icon: POINTER_TOOLBAR_GLYPH, label: POINTER_TOOLBAR_GLYPH }, }; diff --git a/packages/app/src/composer/agent-controls/layout.test.ts b/packages/app/src/composer/agent-controls/layout.test.ts index 75dc07451d..4a985f1849 100644 --- a/packages/app/src/composer/agent-controls/layout.test.ts +++ b/packages/app/src/composer/agent-controls/layout.test.ts @@ -251,7 +251,7 @@ describe("composer control layout", () => { controlSize: 36, glyphs: { icon: { size: 20, strokeWidth: 1.5, tone: "foreground" }, - label: { size: 20, strokeWidth: 1.5, tone: "foreground" }, + label: { size: 20, strokeWidth: 1.5, tone: "muted" }, }, controlGap: 0, labelPadding: 8, diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 6c7ddd7d86..b0ed623304 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -97,7 +97,7 @@ import { } from "@/components/ui/text-input"; const ComposerTextInput = withUnistyles(EditingTextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, + placeholderTextColor: theme.colors.foregroundExtraMuted, })); import { resolveSendTooltipLabel, From d30aa16bebb180740267178a97baae87a504ca4f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:10:41 +0000 Subject: [PATCH 041/160] Retrying a message that failed before reaching the provider delivers it (#9580) * fix(server): let a message rejected before dispatch be retried A send_agent_message_request with a messageId wrote its pending receipt before loading the agent, setting its mode, and starting the run. When one of those steps failed, nothing reached the provider, yet every retry with the same messageId reported agent_request_outcome_unknown. The pending receipt is now written at the dispatch boundary: the send awaits beforeDispatch after the agent is loaded and its mode is set, just before the prompt is handed to a run. A failure before that point leaves no receipt, so the retry submits the message once. Failures after it stay ambiguous, as before. Closes #9297 Co-authored-by: tmad4000 <1430007+tmad4000@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * test(server): lock that a send failing after dispatch is never resubmitted Scope the docs/hub.md retry sentence to direct sends: agent-sourced sends still write their receipt before queueing. Co-Authored-By: Claude Opus 5.5 * docs(hub): scope the retry promise to failures before the run starts Co-Authored-By: Claude Opus 5.5 * docs(hub): name run startup as the ambiguous boundary Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: tmad4000 <1430007+tmad4000@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- docs/hub.md | 4 ++ .../server/src/server/agent/agent-prompt.ts | 3 ++ .../hub/execution-session.websocket.test.ts | 40 +++++++++++++++++++ .../hub/test-utils/relationship-harness.ts | 10 +++++ .../src/server/message-receipts/index.test.ts | 17 ++++---- .../src/server/message-receipts/index.ts | 15 ++++--- packages/server/src/server/session.ts | 10 +++-- .../server/test-utils/fake-agent-client.ts | 7 ++++ .../src/server/test-utils/session-stubs.ts | 2 +- 9 files changed, 90 insertions(+), 18 deletions(-) diff --git a/docs/hub.md b/docs/hub.md index b4df317e76..1fbe6b92d5 100644 --- a/docs/hub.md +++ b/docs/hub.md @@ -61,6 +61,10 @@ The daemon journals the assigned agent ID before creation. Concurrent retries sh and a retry after a lost acknowledgement or restart returns the durable agent without creating a workspace or starting a turn. Deleting that agent does not make its old creation key reusable. Confirmed message delivery is also journaled, so retrying its message ID does not submit it again. +A direct send (one without `sourceAgentId`) rejected before its prompt is handed to a run, for +example because the agent could not be loaded or the requested mode could not be set, leaves no +receipt, so retrying its message ID submits it. A failure during or after run startup is treated +as an unfinished delivery. An unfinished delivery after restart reports `agent_request_outcome_unknown`: a provider can have accepted a prompt before the daemon recorded success, so automatic resubmission could duplicate work. Inspect the agent before choosing a new message ID. Receipts contain identity and request diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index dde5c02bbd..d178c72f6c 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -210,6 +210,8 @@ export async function unarchiveAgentState( } export interface SendPromptToAgentParams { + /** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */ + beforeDispatch?: () => Promise; onDispatch?: StartAgentRunOptions["onDispatch"]; agentManager: AgentManager; agentStorage: AgentStorage; @@ -357,6 +359,7 @@ export async function sendPreparedPromptToAgent( await params.agentManager.setAgentMode(params.agentId, params.sessionMode); } + await params.beforeDispatch?.(); return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, { replaceRunning: true, onDispatch: params.onDispatch, diff --git a/packages/server/src/server/hub/execution-session.websocket.test.ts b/packages/server/src/server/hub/execution-session.websocket.test.ts index 266c55e196..7cc2db0480 100644 --- a/packages/server/src/server/hub/execution-session.websocket.test.ts +++ b/packages/server/src/server/hub/execution-session.websocket.test.ts @@ -182,6 +182,46 @@ test("ordinary Hub create and message retries do not duplicate agents or prompts ).toMatchObject({ payload: { accepted: false } }); }); +test("Hub retries a message whose send failed before reaching the provider", async () => { + const hub = await launchRelationship(); + const agentId = await hub.createUnrelatedLocalAgent(); + const message = { + type: "send_agent_message_request", + agentId, + messageId: "mode-change-failed", + text: "retry me", + sessionMode: "full-access", + }; + hub.failNextProviderModeChange(); + expect(await hub.requestOrdinary({ ...message, requestId: "first-attempt" })).toMatchObject({ + payload: { accepted: false, error: expect.stringContaining("mode change failure") }, + }); + expect(hub.providerPromptTexts().filter((text) => text === "retry me")).toHaveLength(0); + + expect(await hub.requestOrdinary({ ...message, requestId: "retry" })).toMatchObject({ + payload: { accepted: true, error: null }, + }); + expect(hub.providerPromptTexts().filter((text) => text === "retry me")).toHaveLength(1); +}); + +test("Hub never resubmits a message whose send failed after reaching the provider", async () => { + const hub = await launchRelationship(); + const agentId = await hub.createUnrelatedLocalAgent(); + const message = { + type: "send_agent_message_request", + agentId, + messageId: "turn-start-failed", + text: "do not repeat me", + }; + hub.failProviderPromptStart("do not repeat me"); + await hub.requestOrdinary({ ...message, requestId: "first-attempt" }); + + expect(await hub.requestOrdinary({ ...message, requestId: "retry" })).toMatchObject({ + payload: { accepted: false, error: "agent_request_outcome_unknown" }, + }); + expect(hub.providerPromptTexts().filter((text) => text === "do not repeat me")).toHaveLength(0); +}); + test("ordinary Hub requests survive daemon restart and restore an archived workspace", async () => { const hub = await launchRelationship(); const create = { diff --git a/packages/server/src/server/hub/test-utils/relationship-harness.ts b/packages/server/src/server/hub/test-utils/relationship-harness.ts index a0c02bbb12..f2e0e4dff6 100644 --- a/packages/server/src/server/hub/test-utils/relationship-harness.ts +++ b/packages/server/src/server/hub/test-utils/relationship-harness.ts @@ -458,6 +458,7 @@ export class HubRelationshipHarness { private readonly claimedCliSockets = new Set(); private readonly promptsToFail = new Set(); private failNextSessionClose = false; + private failNextModeChange = false; private observedEnrollments = 0; private observedSockets = 0; private readonly codex: ControlledAgentClient; @@ -474,6 +475,11 @@ export class HubRelationshipHarness { this.failNextSessionClose = false; throw new Error("Requested provider session close failure"); }, + beforeSetMode: async () => { + if (!this.failNextModeChange) return; + this.failNextModeChange = false; + throw new Error("Requested provider mode change failure"); + }, onStartTurn: (prompt) => { const promptText = typeof prompt === "string" ? prompt : JSON.stringify(prompt); if (this.promptsToFail.delete(promptText)) { @@ -674,6 +680,10 @@ export class HubRelationshipHarness { this.promptsToFail.add(prompt); } + failNextProviderModeChange(): void { + this.failNextModeChange = true; + } + failNextProviderSessionClose(): void { this.failNextSessionClose = true; } diff --git a/packages/server/src/server/message-receipts/index.test.ts b/packages/server/src/server/message-receipts/index.test.ts index 10c1615a6a..f77ced4d6e 100644 --- a/packages/server/src/server/message-receipts/index.test.ts +++ b/packages/server/src/server/message-receipts/index.test.ts @@ -23,7 +23,8 @@ test("message retries survive reconstruction without submitting twice", async () agentId: "agent", messageId: "arrival", request: { text: "hello" }, - send: async () => { + send: async (beforeDispatch: () => Promise) => { + await beforeDispatch(); deliveries++; }, }; @@ -41,7 +42,8 @@ test("ambiguous provider delivery is never blindly replayed after restart", asyn agentId: "agent", messageId: "arrival", request: {}, - send: async () => { + send: async (beforeDispatch: () => Promise) => { + await beforeDispatch(); deliveries++; throw new Error("connection lost"); }, @@ -53,7 +55,7 @@ test("ambiguous provider delivery is never blindly replayed after restart", asyn expect(deliveries).toBe(1); }); -test("failed local message preparation does not leave an ambiguous receipt", async () => { +test("a send that fails before beforeDispatch can be retried with the same message", async () => { const { requests, directory } = await fixture(); let available = false; let sends = 0; @@ -61,14 +63,13 @@ test("failed local message preparation does not leave an ambiguous receipt", asy agentId: "agent", messageId: "message", request: {}, - prepare: async () => { - if (!available) throw new Error("load failed"); - }, - send: async () => { + send: async (beforeDispatch: () => Promise) => { + if (!available) throw new Error("mode change failed"); + await beforeDispatch(); sends++; }, }; - await expect(requests.send(input)).rejects.toThrow("load failed"); + await expect(requests.send(input)).rejects.toThrow("mode change failed"); available = true; await new MessageReceipts(directory).send(input); available = false; diff --git a/packages/server/src/server/message-receipts/index.ts b/packages/server/src/server/message-receipts/index.ts index 6103160b12..f76d1381ec 100644 --- a/packages/server/src/server/message-receipts/index.ts +++ b/packages/server/src/server/message-receipts/index.ts @@ -13,8 +13,11 @@ interface SendMessageInput { agentId: string; messageId: string; request: unknown; - send: () => Promise; - prepare?: () => Promise; + /** + * Delivers the message. It awaits `beforeDispatch` immediately before the provider can receive + * the message; a failure before that call proves nothing was submitted and leaves no receipt. + */ + send: (beforeDispatch: () => Promise) => Promise; } /** Owns message delivery receipts; creation is owned by CreationService. */ @@ -48,10 +51,12 @@ export class MessageReceipts { // A provider may have accepted the message before its receipt was committed. throw new Error("agent_request_outcome_unknown"); } - await input.prepare?.(); const receipt = { fingerprint, agentId: input.agentId }; - await writeJsonFileAtomic(file, { ...receipt, state: "pending" }); - await input.send(); + let pending: Promise | null = null; + await input.send(() => { + pending ??= writeJsonFileAtomic(file, { ...receipt, state: "pending" }); + return pending; + }); await writeJsonFileAtomic(file, { ...receipt, state: "completed" }); } } diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index d6567da4ca..ae19cdc0d4 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -8918,8 +8918,9 @@ export class Session { queued = acceptAdmission; }); let deliveryStatus: "queued" | undefined; - const send = async () => { + const send = async (beforeDispatch: () => Promise) => { if (msg.sourceAgentId) { + await beforeDispatch(); const receipt = this.agentMessages.enqueue({ recipientId: agentId, messageId: msg.messageId, @@ -8950,6 +8951,7 @@ export class Session { activeTurnBehavior: msg.activeTurnBehavior ?? "interrupt", sessionMode: msg.sessionMode, clearPendingPermissions: true, + beforeDispatch, logger: this.sessionLogger, }); if (result.disposition === "turn_started") { @@ -8972,12 +8974,12 @@ export class Session { activeTurnBehavior: msg.activeTurnBehavior ?? (msg.sourceAgentId ? "steer" : "interrupt"), }, - prepare: async () => { + send: async (beforeDispatch) => { if (!msg.sourceAgentId) await this.prepareAgentMessage(agentId, msg.text); + await send(beforeDispatch); }, - send, }) - : send(); + : send(async () => {}); void sent.catch((error) => { if (deliveryStatus === "queued") { this.handleAgentRunError(agentId, error, "Failed to dispatch queued agent message"); diff --git a/packages/server/src/server/test-utils/fake-agent-client.ts b/packages/server/src/server/test-utils/fake-agent-client.ts index a7a237b9de..1be2a405e8 100644 --- a/packages/server/src/server/test-utils/fake-agent-client.ts +++ b/packages/server/src/server/test-utils/fake-agent-client.ts @@ -84,6 +84,7 @@ interface FakeAgentSessionOptions { beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; steerActiveTurn?: AgentSession["steerActiveTurn"]; onInterrupt?: () => void; + beforeSetMode?: (modeId: string) => Promise; historyEvents?: readonly AgentStreamEvent[]; } @@ -95,6 +96,7 @@ export interface TestAgentClientOptions { beforeTurnComplete?: (prompt: AgentPromptInput) => Promise; steerActiveTurn?: AgentSession["steerActiveTurn"]; onInterrupt?: () => void; + beforeSetMode?: (modeId: string) => Promise; supportsMcpServers?: boolean; historyEvents?: readonly AgentStreamEvent[]; } @@ -369,6 +371,7 @@ class FakeAgentSession implements AgentSession { readonly steerActiveTurn: AgentSession["steerActiveTurn"]; private readonly onInterrupt: (() => void) | undefined; + private readonly beforeSetMode: ((modeId: string) => Promise) | undefined; private readonly closeSession: (() => Promise) | undefined; private readonly onStartTurn: TestAgentClientOptions["onStartTurn"]; private readonly beforeTurnComplete: ((prompt: AgentPromptInput) => Promise) | undefined; @@ -385,6 +388,7 @@ class FakeAgentSession implements AgentSession { this.memoryMarker = options.memoryMarker ?? null; this.steerActiveTurn = options.steerActiveTurn; this.onInterrupt = options.onInterrupt; + this.beforeSetMode = options.beforeSetMode; this.closeSession = options.closeSession; this.onStartTurn = options.onStartTurn; this.beforeTurnComplete = options.beforeTurnComplete; @@ -891,6 +895,7 @@ class FakeAgentSession implements AgentSession { } async setMode(modeId: string): Promise { + await this.beforeSetMode?.(modeId); this.config.modeId = modeId; } @@ -1264,6 +1269,7 @@ class FakeAgentClient implements AgentClient { beforeTurnComplete: this.options.beforeTurnComplete, steerActiveTurn: this.options.steerActiveTurn, onInterrupt: this.options.onInterrupt, + beforeSetMode: this.options.beforeSetMode, historyEvents: this.options.historyEvents, }); } @@ -1294,6 +1300,7 @@ class FakeAgentClient implements AgentClient { beforeTurnComplete: this.options.beforeTurnComplete, steerActiveTurn: this.options.steerActiveTurn, onInterrupt: this.options.onInterrupt, + beforeSetMode: this.options.beforeSetMode, historyEvents: this.options.historyEvents, }); } diff --git a/packages/server/src/server/test-utils/session-stubs.ts b/packages/server/src/server/test-utils/session-stubs.ts index 0c156ae5d9..7546da1427 100644 --- a/packages/server/src/server/test-utils/session-stubs.ts +++ b/packages/server/src/server/test-utils/session-stubs.ts @@ -306,7 +306,7 @@ export function createProviderSnapshotManagerStub(): { export function createMessageReceiptsStub(): SessionOptions["messageReceipts"] { return { - send: (input) => input.send(), + send: (input) => input.send(async () => {}), }; } From d11239fd95df403234e5a87f517294941f6d01b4 Mon Sep 17 00:00:00 2001 From: ese111 <79190824+ese111@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:04:58 +0900 Subject: [PATCH 042/160] fix(plugin): accept all review attachment mode (#9590) --- packages/plugin/src/server/provider.test.ts | 66 +++++++++++++++++++++ packages/plugin/src/server/provider.ts | 4 +- 2 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 packages/plugin/src/server/provider.test.ts diff --git a/packages/plugin/src/server/provider.test.ts b/packages/plugin/src/server/provider.test.ts new file mode 100644 index 0000000000..7020c9a526 --- /dev/null +++ b/packages/plugin/src/server/provider.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; +import { ProviderInputSchema, type ProviderInput } from "./provider.js"; + +type ReviewMode = "uncommitted" | "base" | "all"; +type Delivery = "auto" | "steer"; + +const contextLine = { + oldLineNumber: null, + newLineNumber: 12, + type: "add", + content: "const value = 1;", +} as const; + +function reviewPrompt(mode: ReviewMode, delivery: Delivery): ProviderInput { + return { + type: "session.prompt", + sessionId: "session-1", + prompt: { + clientMessageId: "message-1", + delivery, + input: { + type: "message", + content: [ + { + type: "review", + mimeType: "application/paseo-review", + cwd: "/workspace", + mode, + baseRef: "main", + comments: [ + { + filePath: "src/index.ts", + side: "new", + lineNumber: 12, + body: "Please review this change.", + context: { + hunkHeader: "@@ -10,2 +10,3 @@", + targetLine: contextLine, + lines: [{ ...contextLine, type: "context", oldLineNumber: 11 }, contextLine], + }, + }, + ], + }, + ], + }, + }, + }; +} + +describe("Provider review attachments", () => { + it.each(["uncommitted", "base", "all"] as const)( + "preserves mode %s on an ordinary prompt", + (mode) => { + const input = reviewPrompt(mode, "auto"); + expect(ProviderInputSchema.parse(input)).toEqual(input); + }, + ); + + it.each(["uncommitted", "base", "all"] as const)( + "preserves mode %s on a steering prompt", + (mode) => { + const input = reviewPrompt(mode, "steer"); + expect(ProviderInputSchema.parse(input)).toEqual(input); + }, + ); +}); diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index 5b9511f1f7..b928f5d168 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -213,7 +213,7 @@ interface ProviderReviewAttachment { type: "review"; mimeType: "application/paseo-review"; cwd: string; - mode: "uncommitted" | "base"; + mode: "uncommitted" | "base" | "all"; baseRef?: string | null; comments: Array<{ filePath: string; @@ -881,7 +881,7 @@ const providerContentSchema: z.ZodType = z.union([ type: z.literal("review"), mimeType: z.literal("application/paseo-review"), cwd: z.string(), - mode: z.enum(["uncommitted", "base"]), + mode: z.enum(["uncommitted", "base", "all"]), baseRef: z.string().nullable().optional(), comments: z.array( z From 2fa0e4b169ee1d0daddd80dc167e67bf65f0ee2a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:32:44 +0000 Subject: [PATCH 043/160] fix(app): load older history when an upward wheel lands at the start (#9570) A wheel listener can run before or after the browser applies the scroll it causes. When the reader had already stopped following output and the last notch landed exactly at the history start, the listener saw the pre-scroll position, did not re-arm history-start pagination, and no older page was requested. The upward scroll now re-arms loading itself. The turn-collapse journey hung on this race until its 120s timeout; the older-history page wait now fails with a message after the expect timeout. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../support/helpers/agent-timeline-gate.ts | 19 --------- .../support/helpers/timeline-pagination.ts | 6 ++- .../strategy-web.browser.test.tsx | 40 ++++++++++++++++++- .../app/src/agent-stream/strategy-web.tsx | 23 ++++++++--- 4 files changed, 61 insertions(+), 27 deletions(-) diff --git a/packages/app/e2e/support/helpers/agent-timeline-gate.ts b/packages/app/e2e/support/helpers/agent-timeline-gate.ts index 89a1d8c364..3c979bf51d 100644 --- a/packages/app/e2e/support/helpers/agent-timeline-gate.ts +++ b/packages/app/e2e/support/helpers/agent-timeline-gate.ts @@ -21,7 +21,6 @@ export interface OlderTimelinePagesGate { getRepeatedEntryCount(): number; getOwnedEntryCountContaining(text: string): number; releasePage(pageNumber: number): void; - waitForRequestCount(count: number): Promise; } export interface DaemonHydrationGate { @@ -371,15 +370,6 @@ export async function holdAgentOlderTimelinePages( const ownedEntries = new Map(); const releasedPages = new Set(); const delayedForwards = new Map void>>(); - const requestWaiters = new Map void>>(); - - const resolveRequestWaiters = () => { - for (const [count, resolvers] of requestWaiters) { - if (requestCount < count) continue; - requestWaiters.delete(count); - for (const resolve of resolvers) resolve(); - } - }; const routePattern = daemonPort === undefined ? daemonWsRoutePattern() : wsRoutePatternForPort(String(daemonPort)); @@ -393,7 +383,6 @@ export async function holdAgentOlderTimelinePages( sessionMessage.direction === "before" ) { requestCount += 1; - resolveRequestWaiters(); } server.send(message); }); @@ -439,14 +428,6 @@ export async function holdAgentOlderTimelinePages( for (const forward of delayedForwards.get(pageNumber) ?? []) forward(); delayedForwards.delete(pageNumber); }, - waitForRequestCount(count) { - if (requestCount >= count) return Promise.resolve(); - return new Promise((resolve) => { - const resolvers = requestWaiters.get(count) ?? []; - resolvers.push(resolve); - requestWaiters.set(count, resolvers); - }); - }, }; } diff --git a/packages/app/e2e/support/helpers/timeline-pagination.ts b/packages/app/e2e/support/helpers/timeline-pagination.ts index ed69897e4e..802ec2a29b 100644 --- a/packages/app/e2e/support/helpers/timeline-pagination.ts +++ b/packages/app/e2e/support/helpers/timeline-pagination.ts @@ -427,7 +427,11 @@ export async function holdOlderHistoryPages( const loader = page.getByTestId("load-older-history-spinner"); return { async expectRequestedPages(count) { - await gate.waitForRequestCount(count); + await expect + .poll(() => gate.getRequestCount(), { + message: `older history requests ${count} page(s)`, + }) + .toBeGreaterThanOrEqual(count); expect(gate.getRequestCount()).toBe(count); }, async expectSettledWithRequestedPages(count) { diff --git a/packages/app/src/agent-stream/strategy-web.browser.test.tsx b/packages/app/src/agent-stream/strategy-web.browser.test.tsx index 12127ea630..a9cc44a849 100644 --- a/packages/app/src/agent-stream/strategy-web.browser.test.tsx +++ b/packages/app/src/agent-stream/strategy-web.browser.test.tsx @@ -49,7 +49,12 @@ afterEach(() => { host.remove(); }); -function mountTimeline(historyMounted: StreamItem[]) { +type OlderHistoryInput = Pick< + StreamRenderInput, + "onNearHistoryStart" | "hasOlderHistory" | "olderHistoryProgressKey" +>; + +function mountTimeline(historyMounted: StreamItem[], olderHistory?: OlderHistoryInput) { const strategy = createWebStreamStrategy({ isMobileBreakpoint: true }); const viewportRef = React.createRef(); const input: StreamRenderInput = { @@ -76,6 +81,7 @@ function mountTimeline(historyMounted: StreamItem[]) { baseListContentContainerStyle: null, forwardListContentContainerStyle: null, contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH, + ...olderHistory, }; const render = (segments: Partial) => root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } })); @@ -100,6 +106,11 @@ function mountTimeline(historyMounted: StreamItem[]) { scrollTo: (top: number) => { scrollContainer.scrollTop = top; }, + // A wheel listener runs before the browser applies the scroll the wheel causes. + wheelUpTo: (top: number) => { + scrollContainer.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1000 })); + scrollContainer.scrollTop = top; + }, distanceFromEnd: () => scrollContainer.scrollHeight - scrollContainer.clientHeight - scrollContainer.scrollTop, // Resize observers and the hold's settle run on animation frames. @@ -208,3 +219,30 @@ describe("web disclosure hold", () => { expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1); }); }); + +describe("web history start", () => { + it("loads older history when an upward wheel lands at the start after the reader stopped following", async () => { + let olderHistoryLoads = 0; + const history = [1, 2, 3, 4, 5, 6].map((index) => row(index)); + const timeline = mountTimeline(history, { + hasOlderHistory: true, + olderHistoryProgressKey: "epoch:1", + onNearHistoryStart: async () => { + olderHistoryLoads += 1; + return true; + }, + }); + await timeline.settle(); + // Opening a row at the bottom stops following output without any scroll. + timeline.hold("message-5", () => + timeline.render({ historyMounted: [...history.slice(0, 5), row(7, 200), history[5]!] }), + ); + await timeline.settle(); + expect(olderHistoryLoads).toBe(0); + + timeline.wheelUpTo(0); + await timeline.settle(); + + expect(olderHistoryLoads).toBe(1); + }); +}); diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index c47e0720f4..896b53b3f6 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -605,6 +605,15 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool window.performance.now() + UPWARD_INPUT_EVIDENCE_TIMEOUT_MS; }, []); + const hasUpwardInputEvidence = useCallback(() => { + const mouseGesture = mouseScrollGestureRef.current; + return ( + mouseGesture?.kind === "scrollbar" || + (mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) || + window.performance.now() < upwardInputEvidenceUntilRef.current + ); + }, []); + useLayoutEffect(() => { if (isActive) { return; @@ -791,16 +800,16 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - USER_SCROLL_DELTA_EPSILON; const scrolledDown = currentScrollTop > lastKnownScrollTopRef.current + USER_SCROLL_DELTA_EPSILON; - const mouseGesture = mouseScrollGestureRef.current; - const hasUpwardInputEvidence = - mouseGesture?.kind === "scrollbar" || - (mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) || - window.performance.now() < upwardInputEvidenceUntilRef.current; + const userScrolledUp = scrolledUp && hasUpwardInputEvidence(); if (!followOutputRef.current && isAtBottom && scrolledDown && !isJumpSettling()) { setFollowOutput(true); - } else if (followOutputRef.current && scrolledUp && hasUpwardInputEvidence) { + } else if (followOutputRef.current && userScrolledUp) { stopFollowingOutputFromUserIntent(); + } else if (userScrolledUp) { + // Wheel listeners can run before or after the browser applies the scroll, so the + // upward scroll itself re-arms loading when it reaches the start. + rearmHistoryStartFromUserIntent(); } lastKnownScrollTopRef.current = currentScrollTop; @@ -811,8 +820,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool evaluateHistoryStart(); }, [ evaluateHistoryStart, + hasUpwardInputEvidence, isJumpSettling, readingAnchor, + rearmHistoryStartFromUserIntent, stopFollowingOutputFromUserIntent, updateScrollMetrics, ]); From 7deb338d4c5509cbc92dcad1d48b2cf35f199c27 Mon Sep 17 00:00:00 2001 From: hankyo <36651040+tkfka1@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:00:45 +0900 Subject: [PATCH 044/160] fix(opencode): re-probe a v1 runtime when the provider is refreshed (#9593) Updating OpenCode from 1.x to 2.x while the daemon runs left it on the v1 client: the version probe result was cached for the client's lifetime and the binary update does not change provider config, so the client was never rebuilt. Once the old v1 server exited, every request failed with "Request is not supported by this version of OpenCode Server (Server responded with text/html)". Refresh and Reload did not recover; only a daemon restart did. A forced catalog refresh now drops a cached v1 selection so the next call re-probes the binary. A v2 selection owns live sessions and stays. A guard keeps an overlapping forced refresh from discarding the selection the first one made. Fixes #9583 Co-authored-by: Claude Opus 5.5 --- .../providers/opencode/runtime-client.test.ts | 105 ++++++++++++++++++ .../providers/opencode/runtime-client.ts | 10 ++ 2 files changed, 115 insertions(+) diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts index 910a68cfef..fbccc0cbf3 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.test.ts @@ -113,6 +113,111 @@ test.each([ } }); +test("re-probes a v1 runtime on a forced refresh after OpenCode is updated to v2", async () => { + const { mkdtemp, writeFile, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const root = await mkdtemp(join(tmpdir(), "opencode-version-upgrade-")); + const script = join(root, "version.cjs"); + const client = new OpenCodeRuntimeClient(createTestLogger(), { + command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, + }); + const controlLabel = async () => + (await client.listControls({ provider: "opencode", cwd: root })).controls[0]?.label; + try { + await writeFile(script, 'console.log("1.14.46")'); + expect(await controlLabel()).toBe("Auto Accept"); + await writeFile(script, 'console.log("opencode v2.0.10")'); + expect(await controlLabel()).toBe("Auto Accept"); + + // The fake binary cannot serve, so the refresh fails on the v2 startup path it switched to. + await expect(client.fetchCatalog({ scope: "global", force: true })).rejects.toThrow( + "OpenCode v2 server exited during startup", + ); + + expect(await controlLabel()).toBe("Auto-accept"); + } finally { + await client.shutdown(); + await rm(root, { recursive: true, force: true }); + } +}); + +async function createCountingVersionBinary(prefix: string) { + const { mkdtemp, writeFile, readFile, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { OpenCodeRuntimeClient } = await import("./runtime-client.js"); + const { createTestLogger } = await import("../../../../test-utils/test-logger.js"); + const root = await mkdtemp(join(tmpdir(), prefix)); + const script = join(root, "version.cjs"); + const probes = join(root, "probes"); + await writeFile(probes, ""); + const client = new OpenCodeRuntimeClient(createTestLogger(), { + command: { mode: "replace", argv: [process.execPath, script] }, + env: { XDG_STATE_HOME: root }, + }); + return { + client, + root, + report: (version: string) => + writeFile( + script, + `if (process.argv.includes("--version")) require("node:fs").appendFileSync(${JSON.stringify(probes)}, "x"); console.log(${JSON.stringify(version)})`, + ), + probeCount: async () => (await readFile(probes, "utf8")).length, + controlLabel: async () => + (await client.listControls({ provider: "opencode", cwd: root })).controls[0]?.label, + dispose: async () => { + await client.shutdown(); + await rm(root, { recursive: true, force: true }); + }, + }; +} + +test("keeps a v2 runtime on a forced refresh without probing the binary again", async () => { + const binary = await createCountingVersionBinary("opencode-v2-refresh-"); + try { + await binary.report("opencode v2.0.10"); + expect(await binary.controlLabel()).toBe("Auto-accept"); + expect(await binary.probeCount()).toBe(1); + + await expect(binary.client.fetchCatalog({ scope: "global", force: true })).rejects.toThrow( + "OpenCode v2 server exited during startup", + ); + + expect(await binary.probeCount()).toBe(1); + expect(await binary.controlLabel()).toBe("Auto-accept"); + } finally { + await binary.dispose(); + } +}); + +test.each([0, 1, 2, 3, 4, 5, 6, 8])( + "probes once when a second forced refresh starts %i microtasks after the first", + async (ticks) => { + const binary = await createCountingVersionBinary("opencode-concurrent-refresh-"); + try { + await binary.report("1.14.46"); + expect(await binary.controlLabel()).toBe("Auto Accept"); + await binary.report("opencode v2.0.10"); + + const first = binary.client.fetchCatalog({ scope: "global", force: true }); + for (let tick = 0; tick < ticks; tick++) await Promise.resolve(); + const second = binary.client.fetchCatalog({ scope: "global", force: true }); + const results = await Promise.allSettled([first, second]); + + expect(results.map((result) => result.status)).toEqual(["rejected", "rejected"]); + expect(await binary.probeCount()).toBe(2); + expect(await binary.controlLabel()).toBe("Auto-accept"); + } finally { + await binary.dispose(); + } + }, +); + test("appends a first notice after old history and records a changed major version", async () => { const { withOpenCodeRuntimeNotice } = await import("./runtime-notice.js"); const { V2Harness } = await import("./test-utils/v2-harness.js"); diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.ts index 6e65c7637e..d10bb9953d 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.ts @@ -155,8 +155,18 @@ export class OpenCodeRuntimeClient implements AgentClient { return client === this.legacy ? session : withOpenCodeRuntimeNotice(session, 2, handle); } async fetchCatalog(options: FetchCatalogOptions, context?: ProviderRefreshContext) { + if (options.force) await this.reprobeLegacySelection(); return (await this.client()).fetchCatalog(options, context); } + // Updating the binary does not change provider config, so the client survives it. A forced + // refresh re-probes a v1 pick so a 1.x to 2.x update takes effect without a daemon restart. + // A v2 pick owns live sessions and stays. + private async reprobeLegacySelection() { + const current = this.selected; + if (!current) return; + const client = await current.catch(() => null); + if (client === this.legacy && this.selected === current) this.selected = null; + } async listCommands(config: AgentSessionConfig) { return (await this.client()).listCommands(config); } From 1bd94ac2b0305d14bb24acef2f09c00dc70969ee Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 18:03:46 +0700 Subject: [PATCH 045/160] Collapsing Activity in the PR pane gives the checks the space, and the separator above it resizes (#9656) * fix(app): let the PR pane's Activity section collapse and resize The PR pane was one ScrollView. Checks sat in a nested list capped at 268px, and the line above Activity was a plain 1px View. Collapsing Activity only hid its body, so the checks stayed boxed with empty space below, and nothing could be dragged. The pane now splits like the Changes pane's docked Commits section. The overview (header and checks) scrolls in its own region. While Activity is open, a ResizeHandle between the two sets the overview's share. While it is collapsed, the Activity row docks to the bottom and the overview fills the rest. * fix(app): keep the PR pane separator under the finger above the home indicator The split measured the pane including its bottom safe-area padding, but the overview's percentage height resolves against the box inside that padding. On a phone with a home indicator the two heights differ, so a drag jumped at the start and then lagged the finger (a 250px drag moved the separator 212px on Android). The split is now measured inside the padding, so the drag and the layout use the same height. * fix(app): keep focus on the PR pane's Activity header when it toggles The header moved between two parents as Activity opened and closed, so React remounted the row and keyboard focus fell to the body. It now keeps one slot in the split and only the timeline mounts. That also stops the header shrinking into the space left by a large drag when the pane gets short, since the header no longer sits in a min-height-0 wrapper. The header exposes aria-expanded on web, which React Native Web does not derive from accessibilityState. The Unistyles test stub now lets explicit props override mapped ones, matching the library's merge order. * test(app): fill unpinned test-theme tokens from the light theme The Unistyles stub now runs uniProps mappings, and the markdown renderer's mapping reads colors.terminal, which the hand-written test theme lacked. Tokens a test does not pin now come from the real light theme. * fix(app): save the PR pane separator where it is drawn Dragging past the end of short checks left the separator at the content's bottom but saved the pointer's share, so the separator jumped down when more checks arrived. The saved share is now capped at the overview's content height. * fix(app): keep the PR pane's earlier share after a drag past short checks Capping the saved share at the content height made any downward drag over short checks pin the overview at that height, even a drag that visibly did nothing. A drag that ends at or past the content's bottom now keeps the larger of the current share and the content's, so growing checks return to the share the overview had, and never to the pointer's position. * fix(app): decide the PR pane's saved share when a drag ends Drag previews wrote straight into the saved share, so a move above the end of short checks during a drag replaced the share the overview had before it, and a drag that ended back at the content's bottom left the overview pinned there. Previews now live in their own drag state, and the saved share is resolved once, on commit, against the share from before the drag. --- .../git/pull-request-panel/checks-section.tsx | 19 +- .../pull-request-panel/pane.browser.test.tsx | 231 ++++++++++++++++++ .../app/src/git/pull-request-panel/pane.tsx | 130 +++++----- .../git/pull-request-panel/section-kit.tsx | 59 +++-- .../app/src/git/pull-request-panel/split.tsx | 162 ++++++++++++ .../app/test-stubs/react-native-unistyles.ts | 25 +- 6 files changed, 517 insertions(+), 109 deletions(-) create mode 100644 packages/app/src/git/pull-request-panel/pane.browser.test.tsx create mode 100644 packages/app/src/git/pull-request-panel/split.tsx diff --git a/packages/app/src/git/pull-request-panel/checks-section.tsx b/packages/app/src/git/pull-request-panel/checks-section.tsx index ad542c8695..a8b08a0281 100644 --- a/packages/app/src/git/pull-request-panel/checks-section.tsx +++ b/packages/app/src/git/pull-request-panel/checks-section.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo } from "react"; -import { Pressable, ScrollView, Text, View, type GestureResponderEvent } from "react-native"; +import { Pressable, Text, View, type GestureResponderEvent } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import { ChevronDown, ChevronRight, MessageSquarePlus } from "lucide-react-native"; @@ -18,12 +18,6 @@ import { useCheckGroupState } from "./check-group-state"; const ThemedChevronDown = withUnistyles(ChevronDown); const ThemedChevronRight = withUnistyles(ChevronRight); -/** - * Roughly eight rows. A repo with thirty checks would otherwise push the activity - * timeline off the pane entirely, so past this height the list scrolls in place. - */ -const LIST_MAX_HEIGHT = 268; - /** * The three statuses the pane has always labelled for tests. Skipped has no id because * nothing asserts on it. @@ -112,11 +106,7 @@ export function ChecksSection({ {open && summary.groups.length > 0 ? ( - + {summary.groups.map((group) => ( ))} - + ) : null} ); @@ -263,9 +253,6 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.foregroundMuted, }, list: { - maxHeight: LIST_MAX_HEIGHT, - }, - listContent: { paddingBottom: theme.spacing[2], }, groupHeader: { diff --git a/packages/app/src/git/pull-request-panel/pane.browser.test.tsx b/packages/app/src/git/pull-request-panel/pane.browser.test.tsx new file mode 100644 index 0000000000..a25b5c72a6 --- /dev/null +++ b/packages/app/src/git/pull-request-panel/pane.browser.test.tsx @@ -0,0 +1,231 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { within } from "@testing-library/dom"; +import { SafeAreaInsetsContext } from "react-native-safe-area-context"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { i18n } from "@/i18n/i18next"; +import { ToastApiProvider } from "@/contexts/toast-context"; +import type { ToastApi } from "@/components/toast-host"; +import type { PrPaneCheck, PrPaneData } from "./data"; +import { PullRequestPane } from "./pane"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +const PANE_HEIGHT = 600; + +const silentToasts: ToastApi = { + show: () => () => {}, + copied: () => {}, + error: () => {}, +}; + +let root: Root | null = null; +let container: HTMLDivElement | null = null; + +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +function successfulChecks(count: number): PrPaneCheck[] { + return Array.from({ length: count }, (_, index) => ({ + provider: "github", + name: `check-${index + 1}`, + status: "success", + url: `https://example.test/checks/${index + 1}`, + })); +} + +function pullRequest(checks: PrPaneCheck[]): PrPaneData { + return { + provider: { id: "github", label: "GitHub" }, + forge: "github", + number: 42, + repoOwner: "acme", + repoName: "widgets", + title: "Ship the widget", + state: "open", + url: "https://example.test/pull/42", + reviewDecision: "pending", + awaitingReviewers: [], + checks, + activity: [], + }; +} + +/** A phone's home indicator: the pane clears it with bottom padding. */ +const HOME_INDICATOR_INSETS = { top: 0, right: 0, bottom: 34, left: 0 }; + +const NO_INSETS = { top: 0, right: 0, bottom: 0, left: 0 }; + +function renderPane(data: PrPaneData, insets = NO_INSETS) { + act(() => + root?.render( + + + + + , + ), + ); +} + +function mountPane(data: PrPaneData, insets = NO_INSETS) { + container = document.createElement("div"); + container.style.height = `${PANE_HEIGHT}px`; + container.style.width = "600px"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + document.body.appendChild(container); + root = createRoot(container); + renderPane(data, insets); + const pane = container.querySelector('[data-testid="pr-pane"]'); + if (!pane) throw new Error("The pull request pane did not render"); + return pane; +} + +/** The pressable row holding the Activity title. */ +function activityHeader(pane: HTMLElement): HTMLElement { + const title = within(pane).getByText(i18n.t("workspace.git.pr.sections.activity")); + const header = title.closest("[tabindex]"); + if (!header) throw new Error("The Activity title is not inside a pressable header"); + return header; +} + +function checksRegionBottom(pane: HTMLElement): number { + return within(pane).getByRole("separator").getBoundingClientRect().top; +} + +/** Whether a user sees the element: no scroll container clips it out of view. */ +function isOnScreen(element: HTMLElement): boolean { + const rect = element.getBoundingClientRect(); + const hit = document.elementFromPoint(rect.left + 8, rect.top + rect.height / 2); + return hit !== null && element.contains(hit); +} + +/** React Native Web reports layout from a ResizeObserver, a frame or two after mounting. */ +async function settleLayout() { + for (let frame = 0; frame < 2; frame++) { + await act(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); + } +} + +/** Drags the separator through each offset from where it starts, releasing at the last one. */ +function dragSeparator(pane: HTMLElement, ...deltasY: number[]) { + const separator = within(pane).getByRole("separator"); + const rect = separator.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const startY = rect.top + rect.height / 2; + const pointer = { pointerId: 1, bubbles: true, cancelable: true, clientX: x, button: 0 }; + act(() => { + separator.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientY: startY })); + }); + for (const deltaY of deltasY) { + act(() => { + window.dispatchEvent( + new PointerEvent("pointermove", { ...pointer, clientY: startY + deltaY }), + ); + }); + } + const endY = startY + (deltasY.at(-1) ?? 0); + act(() => { + window.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientY: endY })); + }); +} + +describe("pull request pane layout", () => { + it("docks a collapsed Activity section to the bottom and gives the checks the pane", async () => { + const pane = mountPane(pullRequest(successfulChecks(10))); + + act(() => activityHeader(pane).click()); + + await expect + .poll(() => Math.round(activityHeader(pane).getBoundingClientRect().bottom)) + .toBe(Math.round(pane.getBoundingClientRect().bottom)); + const rows = within(pane).getAllByTestId("pr-pane-check-row"); + expect(rows).toHaveLength(10); + expect(rows.every(isOnScreen)).toBe(true); + }); + + it("keeps keyboard focus on the Activity header while it collapses and expands", () => { + const pane = mountPane(pullRequest(successfulChecks(3))); + const header = activityHeader(pane); + act(() => header.focus()); + + act(() => header.click()); + expect(document.activeElement).toBe(header); + act(() => header.click()); + expect(document.activeElement).toBe(header); + }); + + it("exposes whether Activity is expanded to assistive technology", () => { + const pane = mountPane(pullRequest(successfulChecks(3))); + expect(activityHeader(pane).getAttribute("aria-expanded")).toBe("true"); + + act(() => activityHeader(pane).click()); + + expect(activityHeader(pane).getAttribute("aria-expanded")).toBe("false"); + }); + + it("keeps the Activity header inside the pane when a dragged pane gets short", async () => { + const pane = mountPane(pullRequest(successfulChecks(30))); + await settleLayout(); + dragSeparator(pane, PANE_HEIGHT); + await settleLayout(); + + act(() => { + if (container) container.style.height = "160px"; + }); + await settleLayout(); + + await expect + .poll(() => activityHeader(pane).getBoundingClientRect().bottom) + .toBeLessThanOrEqual(pane.getBoundingClientRect().bottom); + expect(isOnScreen(activityHeader(pane))).toBe(true); + }); + + it.each([ + ["5px down", [5]], + ["400px down", [400]], + ["up past their end and back down", [-20, 100]], + ])("gives the checks their earlier share when they grow after a drag %s", async (_name, path) => { + const pane = mountPane(pullRequest(successfulChecks(2))); + await settleLayout(); + const drawn = checksRegionBottom(pane); + + dragSeparator(pane, ...path); + await settleLayout(); + expect(checksRegionBottom(pane)).toBeCloseTo(drawn, 0); + + renderPane(pullRequest(successfulChecks(30))); + await settleLayout(); + const overview = within(pane).getByTestId("pr-pane-overview"); + expect(overview.getBoundingClientRect().height).toBeCloseTo(PANE_HEIGHT / 2, 0); + }); + + it("resizes the checks against Activity by dragging the separator between them", async () => { + const pane = mountPane(pullRequest(successfulChecks(30))); + await settleLayout(); + const before = checksRegionBottom(pane); + + dragSeparator(pane, 120); + + await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120); + expect(activityHeader(pane).getBoundingClientRect().top).toBeGreaterThan(before + 100); + }); + + it("keeps the separator under the pointer when the pane clears a bottom inset", async () => { + const pane = mountPane(pullRequest(successfulChecks(30)), HOME_INDICATOR_INSETS); + await settleLayout(); + const before = checksRegionBottom(pane); + + dragSeparator(pane, 120); + + await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120); + }); +}); diff --git a/packages/app/src/git/pull-request-panel/pane.tsx b/packages/app/src/git/pull-request-panel/pane.tsx index 1f36a8749e..ff2b9c8682 100644 --- a/packages/app/src/git/pull-request-panel/pane.tsx +++ b/packages/app/src/git/pull-request-panel/pane.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useState } from "react"; -import { Image, Pressable, ScrollView, Text, View, type ViewStyle } from "react-native"; +import { Image, Pressable, Text, View, type ViewStyle } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { CircleCheck, @@ -74,13 +74,14 @@ import { type PrTimelineEntry, } from "./timeline"; import { - Section, + SectionHeader, SummaryPill, dangerColorMapping, foregroundMutedColorMapping, sectionKitStyles, successColorMapping, } from "./section-kit"; +import { PullRequestPaneSplit } from "./split"; const ThemedCircleCheck = withUnistyles(CircleCheck); const ThemedCircleX = withUnistyles(CircleX); @@ -478,8 +479,8 @@ export function PullRequestPane({ : null; return ( - - + + <> + + ) : null} + {activityLoading ? : null} + {!activityLoading && visibleEntries.length === 0 ? ( + {t("workspace.git.pr.empty.noActivity")} + ) : null} + {!activityLoading + ? visibleEntries.map(({ entry, collapsed }) => ( + - - - } - > - {timelineEntries.length > 0 && attachEnabled && visibleEntries.length > 0 ? ( - - - - ) : null} - {activityLoading ? : null} - {!activityLoading && visibleEntries.length === 0 ? ( - {t("workspace.git.pr.empty.noActivity")} - ) : null} - {!activityLoading - ? visibleEntries.map(({ entry, collapsed }) => ( - - )) - : null} - - - + )) + : null} + + ); } @@ -1192,15 +1193,6 @@ function ThreadComment({ } const styles = StyleSheet.create((theme) => ({ - root: { - flex: 1, - minHeight: 0, - backgroundColor: theme.colors.surfaceSidebar, - }, - scroll: { - flex: 1, - minHeight: 0, - }, invisible: { opacity: 0, }, @@ -1261,10 +1253,6 @@ const styles = StyleSheet.create((theme) => ({ marginLeft: theme.spacing[1], opacity: 0, }, - divider: { - height: 1, - backgroundColor: theme.colors.border, - }, toolbar: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/git/pull-request-panel/section-kit.tsx b/packages/app/src/git/pull-request-panel/section-kit.tsx index b4a9d00a3a..e28f0ac050 100644 --- a/packages/app/src/git/pull-request-panel/section-kit.tsx +++ b/packages/app/src/git/pull-request-panel/section-kit.tsx @@ -1,8 +1,9 @@ -import React, { type ReactNode } from "react"; +import React, { useMemo, type ReactNode } from "react"; import { Pressable, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import type { CountedCheckPresentation } from "@/git/check-presentation"; import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry"; +import { isWeb } from "@/constants/platform"; import { CheckPresentationIcon, getCheckPresentationTone, @@ -21,39 +22,57 @@ export const successColorMapping = (theme: Theme) => ({ color: theme.colors.stat export const dangerColorMapping = (theme: Theme) => ({ color: theme.colors.statusDanger }); export const warningColorMapping = (theme: Theme) => ({ color: theme.colors.statusWarning }); -interface SectionProps { +interface SectionHeaderProps { title: string; open: boolean; onToggle: () => void; summary: ReactNode; - children: ReactNode; accessibilityLabel?: string; } -export function Section({ +interface SectionProps extends SectionHeaderProps { + children: ReactNode; +} + +/** The disclosure row of a section, for layouts that place the section's body themselves. */ +export function SectionHeader({ title, open, onToggle, summary, - children, accessibilityLabel, -}: SectionProps) { +}: SectionHeaderProps) { + const accessibilityState = useMemo(() => ({ expanded: open }), [open]); + // React Native Web does not map `accessibilityState.expanded` to `aria-expanded`. + const webExpandedProps = useMemo( + () => (isWeb ? ({ "aria-expanded": open } as const) : null), + [open], + ); + return ( + + {open ? ( + + ) : ( + + )} + {title} + {summary} + + ); +} + +export function Section({ children, ...header }: SectionProps) { return ( - - {open ? ( - - ) : ( - - )} - {title} - {summary} - - {open ? {children} : null} + + {header.open ? {children} : null} ); } diff --git a/packages/app/src/git/pull-request-panel/split.tsx b/packages/app/src/git/pull-request-panel/split.tsx new file mode 100644 index 0000000000..1491e6d406 --- /dev/null +++ b/packages/app/src/git/pull-request-panel/split.tsx @@ -0,0 +1,162 @@ +import { Children, useCallback, useMemo, useState, type ReactNode } from "react"; +import { ScrollView, View, type LayoutChangeEvent } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { ResizeHandle } from "@/components/resize-handle"; + +/** Most of the pane the overview may take before it scrolls, until the user drags the separator. */ +const DEFAULT_OVERVIEW_SHARE = 0.5; +const SPLIT_GROUP_ID = "pr-pane"; + +interface PullRequestPaneSplitProps { + /** + * Exactly three children, in order: + * 1. the overview (the PR's header and checks), which scrolls in its own region; + * 2. the Activity disclosure row, docked to the bottom of the pane while collapsed; + * 3. the Activity timeline, filling the space below the separator while open. + * + * Slots are children because `react-perf/jsx-no-jsx-as-prop` rejects JSX in a prop. Pass all + * three unconditionally, the way `TreeRail` takes its slots. + */ + children: ReactNode; + activityOpen: boolean; +} + +/** + * Lays the pane out the way stacked sidebar sections behave: the overview and Activity share the + * height, a separator between them resizes the share, and a collapsed Activity gives its space + * back by docking its header to the bottom. + */ +export function PullRequestPaneSplit({ children, activityOpen }: PullRequestPaneSplitProps) { + const [overview, activityHeader, activityTimeline] = Children.toArray(children); + const insets = useSafeAreaInsets(); + const [overviewShare, setOverviewShare] = useState(DEFAULT_OVERVIEW_SHARE); + // The pointer's share while a drag is in progress. The saved share is decided once, when the + // drag ends, so moves along the way cannot overwrite the share the overview had before it. + const [dragShare, setDragShare] = useState(null); + const [splitHeight, setSplitHeight] = useState(0); + const [overviewHeight, setOverviewHeight] = useState(0); + const [overviewContentHeight, setOverviewContentHeight] = useState(0); + + const handleSplitLayout = useCallback((event: LayoutChangeEvent) => { + setSplitHeight(event.nativeEvent.layout.height); + }, []); + const handleOverviewLayout = useCallback((event: LayoutChangeEvent) => { + setOverviewHeight(event.nativeEvent.layout.height); + }, []); + const handleOverviewContentSizeChange = useCallback((_width: number, height: number) => { + setOverviewContentHeight(height); + }, []); + const handlePreviewResize = useCallback((_groupId: string, sizes: number[]) => { + const [share] = sizes; + if (share !== undefined) setDragShare(share); + }, []); + const handleResize = useCallback( + (_groupId: string, sizes: number[]) => { + setDragShare(null); + const [share] = sizes; + if (share === undefined || splitHeight <= 0) return; + const contentShare = overviewContentHeight / splitHeight; + setOverviewShare((current) => resolveDraggedShare(share, current, contentShare)); + }, + [overviewContentHeight, splitHeight], + ); + + // The overview stops at its content height, so a drag starts from where the separator is + // drawn rather than from the share the overview may grow to. + const separatorSizes = useMemo(() => { + const share = splitHeight > 0 ? overviewHeight / splitHeight : DEFAULT_OVERVIEW_SHARE; + return [share, 1 - share]; + }, [overviewHeight, splitHeight]); + // The Activity header docks to the bottom edge, so it clears the home indicator the way the + // Changes pane's docked Commits section does. The split is measured inside that padding: the + // overview's percentage height resolves against this box, so the drag must use the same one. + const rootStyle = useMemo(() => [styles.root, { paddingBottom: insets.bottom }], [insets.bottom]); + const drawnShare = dragShare ?? overviewShare; + const overviewStyle = useMemo( + () => + activityOpen + ? [styles.overviewShared, { maxHeight: `${drawnShare * 100}%` as const }] + : styles.overviewFill, + [activityOpen, drawnShare], + ); + + return ( + + + + {overview} + + {activityOpen ? ( + + ) : ( + + )} + {/* The header keeps one slot in both states, so toggling it does not remount the row + and drop keyboard focus. Only the timeline mounts and unmounts. */} + {activityHeader} + {activityOpen ? ( + + {activityTimeline} + + ) : null} + + + ); +} + +/** + * The share a drag leaves the overview. Short content stops the separator at the content's + * bottom, so a drag that ends there or below saves what was drawn and keeps any larger share + * the overview already had. The separator then neither jumps to the pointer nor stays pinned + * at the old content height when the content grows. + */ +function resolveDraggedShare(pointerShare: number, currentShare: number, contentShare: number) { + if (pointerShare < contentShare) return pointerShare; + return Math.max(currentShare, contentShare); +} + +const styles = StyleSheet.create((theme) => ({ + root: { + flex: 1, + minHeight: 0, + backgroundColor: theme.colors.surfaceSidebar, + }, + split: { + flex: 1, + minHeight: 0, + }, + overviewShared: { + flexGrow: 0, + flexShrink: 1, + minHeight: 0, + }, + overviewFill: { + flex: 1, + minHeight: 0, + }, + // Same 1px line the separator draws, so collapsing Activity does not move the boundary's look. + divider: { + height: 1, + backgroundColor: theme.colors.border, + }, + activityScroll: { + flex: 1, + minHeight: 0, + }, +})); diff --git a/packages/app/test-stubs/react-native-unistyles.ts b/packages/app/test-stubs/react-native-unistyles.ts index 04f61bc77e..e33f3347c2 100644 --- a/packages/app/test-stubs/react-native-unistyles.ts +++ b/packages/app/test-stubs/react-native-unistyles.ts @@ -1,7 +1,8 @@ +import { createElement, type ElementType } from "react"; import { lightHighlightColors } from "@getpaseo/highlight"; import { lightTheme } from "../src/styles/theme"; -const testTheme = { +const pinnedTheme = { colorScheme: "light", colors: { syntax: lightHighlightColors, @@ -86,6 +87,14 @@ const testTheme = { }, }; +// Tokens a test does not pin come from the real light theme, so a style or `uniProps` mapping +// that reads one (the markdown renderer reads `colors.terminal`) gets a value instead of crashing. +const testTheme = { + ...lightTheme, + ...pinnedTheme, + colors: { ...lightTheme.colors, ...pinnedTheme.colors }, +}; + type StyleFactory = (theme: typeof testTheme) => T; function isStyleFactory(styles: T | StyleFactory): styles is StyleFactory { @@ -142,7 +151,19 @@ export const StyleSheet = { resolveStyles(isStyleFactory(styles) ? styles(testTheme) : styles), }; -export const withUnistyles = (Component: T): T => Component; +type UniPropsMapping = (theme: typeof testTheme, runtime: object) => Record; + +/** Applies `uniProps` with the test theme, the way Unistyles maps theme values onto props. */ +export const withUnistyles = (Component: T): T => { + function ThemedComponent({ uniProps, ...props }: { uniProps?: UniPropsMapping }) { + // Explicit props win over mapped ones, as in Unistyles' `deepMergeObjects(mappings, uniProps, props)`. + return createElement(Component as ElementType, { + ...(uniProps ? uniProps(testTheme, {}) : {}), + ...props, + }); + } + return ThemedComponent as T; +}; export const useUnistyles = () => ({ theme: testTheme, From ade902f195032cf8e1b568eb8b8d1c1333d10eee Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:59:29 +0000 Subject: [PATCH 046/160] Existing OpenCode sessions rebind after a daemon restart when OpenCode runs on Bun (#9653) * fix(opencode): rebind a session when the previous bridge stops listening A refused fetch proves the previous bridge is gone, but the check only matched the Node shape (`cause.code`) and Bun's older spelling (`code === "ConnectionRefused"`). OpenCode 2.2.5 runs on Bun 1.4.4, which throws a TypeError with `code === "ECONNREFUSED"` and no `cause`, so the error was rethrown, the stale binding was never deleted, and every later bind for that session answered HTTP 500 (#8780). Accept the code from either location. The narrow refusal check stays: other connection failures remain inconclusive so two daemons cannot take over the same session. The probe is now classified by an exported predicate with the runtime shapes as explicit cases, and the stale-binding test closes a real listener instead of stubbing the network, so neither test patches a global. * test(opencode): bind the session on the restarted bridge before rebinding The bridge now serves tools only for sessions it has bound, so the stale-binding test registers the session on the restarted bridge, as a restarted daemon does when it takes the agent back. Co-authored-by: quickwind --------- Co-authored-by: quickwind Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../opencode/v2/shared-bridge-plugin.mjs | 14 +-- .../opencode/v2/shared-bridge.test.ts | 87 +++++++++++++++++++ 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs index 1eaaad53af..2331be4edf 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge-plugin.mjs @@ -1,5 +1,12 @@ import { STRUCTURED_OUTPUT_TOOL } from "./structured-output-plugin.mjs"; +// A refused fetch proves the previous bridge stopped listening. Runtimes report +// it differently: Node puts the code on `cause`, Bun puts it on the error. +export function isRefused(error) { + const code = error?.code ?? error?.cause?.code; + return code === "ECONNREFUSED" || code === "ConnectionRefused"; +} + // OpenCode owns this plugin for the lifetime of a location. Paseo supplies only // live, per-session bindings over the authenticated OpenCode RPC channel. export async function registerSharedBridge(context) { @@ -130,12 +137,7 @@ export async function registerSharedBridge(context) { } catch (error) { // Refusal or rejected credentials mean this endpoint no longer // serves the previous binding. Other failures are inconclusive. - if ( - error?.status !== 401 && - error?.cause?.code !== "ECONNREFUSED" && - error?.code !== "ConnectionRefused" - ) - throw error; + if (error?.status !== 401 && !isRefused(error)) throw error; } if (active) return { error: "OpenCode session is already bound to another Paseo bridge" }; diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts index 385b6daff7..20427357dd 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-bridge.test.ts @@ -1,4 +1,6 @@ import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -167,3 +169,88 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions" await rm(home, { recursive: true, force: true }); } }); + +test("a shared plugin rebinds a session after the previous bridge stops listening", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-refused-")); + const previous = createServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json", Connection: "close" }); + response.end(JSON.stringify({ tools: [] })); + }); + await new Promise((resolve) => previous.listen(0, "127.0.0.1", resolve)); + const previousPort = (previous.address() as AddressInfo).port; + const current = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() }); + current.setManifestCatalog({ tools: new Map() }); + let rpc: Record Promise> = {}; + let dispose: (() => Promise) | undefined; + let releaseCurrent: (() => void) | undefined; + try { + const plugin = { + package: await current.materializeV2Plugin(), + options: { baseUrl: `http://127.0.0.1:${previousPort}`, token: "previous-bridge" }, + }; + const module = await import( + pathToFileURL(path.join(fileURLToPath(plugin.package), "server.js")).href + ); + dispose = await module.default.setup({ + options: {}, + location: { directory: home }, + provider: { reload: async () => {} }, + model: { reload: async () => {} }, + agent: { reload: async () => {} }, + command: { reload: async () => {} }, + skill: { reload: async () => {} }, + rpc: { + register: async (_definition: unknown, handlers: typeof rpc) => { + rpc = handlers; + return { dispose: async () => {} }; + }, + }, + tool: { transform: async () => ({ dispose: async () => {} }) }, + session: { + context: async () => [], + get: async () => ({ parentID: "" }), + hook: async () => ({ dispose: async () => {} }), + }, + }); + await expect(rpc.bind({ sessionID: "paseo", ...plugin.options })).resolves.toEqual({}); + await current.start(); + // The restarted daemon owns the agent again, so its bridge serves this session. + releaseCurrent = current.bindSession({ sessionId: "paseo", env: {} }); + await new Promise((resolve) => { + previous.close(() => resolve()); + previous.closeAllConnections(); + }); + await expect( + rpc.bind({ sessionID: "paseo", ...current.sharedV2Connection() }), + ).resolves.toEqual({}); + } finally { + await dispose?.(); + releaseCurrent?.(); + await current.close(); + await new Promise((resolve) => previous.close(() => resolve())); + await rm(home, { recursive: true, force: true }); + } +}); + +test("a refused connection is the only probe failure that clears a binding", async () => { + const source = new URL("./shared-bridge-plugin.mjs", import.meta.url).href; + const { isRefused } = (await import(source)) as { isRefused: (error: unknown) => boolean }; + const nodeShape = Object.assign(new Error("fetch failed"), { + cause: Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }), + }); + const olderBunShape = Object.assign(new TypeError("Unable to connect"), { + code: "ConnectionRefused", + }); + // OpenCode 2.2.5 runs on Bun 1.4.4, which carries the code on the error and + // leaves `cause` unset. Node puts the same failure on `cause` instead. + const bunShape = Object.assign( + new TypeError("ECONNREFUSED: Unable to connect. Is the computer able to access the url?"), + { code: "ECONNREFUSED" }, + ); + const inconclusive = Object.assign(new Error("request timed out"), { code: "ETIMEDOUT" }); + expect(isRefused(nodeShape)).toBe(true); + expect(isRefused(olderBunShape)).toBe(true); + expect(isRefused(bunShape)).toBe(true); + expect(isRefused(inconclusive)).toBe(false); + expect(isRefused(undefined)).toBe(false); +}); From 7f3967d288a010ac8dcf2871d5dcfa176ec45a8f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:23:33 +0000 Subject: [PATCH 047/160] test(server): keep the forge parent retry test from fetching over the network (#9658) Observing the workspace starts a background git fetch of origin. The test's origin is an SSH alias, so a real fetch runs ssh in the checkout and can still be running after the service is disposed. On Windows that holds the folder open and cleanup fails with EBUSY. The test now supplies a fetch that returns no ref changes; the parent lookup and status poll it checks are unchanged. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../workspace-git-service.observation.integration.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index 70b483e1a1..cbed2c8e58 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -1238,6 +1238,9 @@ test("a failed parent lookup is retried by the pull request status poll, keeping paseoHome: path.join(path.dirname(repo), "home"), deps: { now: () => new Date(nowMs), + // Observing the workspace starts a background fetch of origin. A real one would run ssh + // against the alias host in the checkout, and can outlive disposal and hold the folder. + runGitFetch: async () => ({ changes: [], error: null }), resolveSshHostname: async (host) => (host === "github.com-work" ? "github.com" : null), forgeOverrides: { // The adapter is real; only the poll is driven by the test instead of a timer. From 0e0ebc7c9e4a9c7eaebbe1ebccd73fb9e8eb418e Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:10:04 +0000 Subject: [PATCH 048/160] fix(chat): keep the reading position when older history becomes virtualized (#9664) * fix(chat): preserve scroll offset when enabling virtualization Reading older messages in a long web chat could jump to the first message when older rows moved into the virtualized history section. When the row virtualizer is enabled it scrolls to its remembered offset, which falls back to initialOffset (0) the first time. Start it from the scroll container's current position instead. Co-Authored-By: Claude Opus 5.5 * test(chat): pass mountTimeline options as an object Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: luke Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] --- .../strategy-web.browser.test.tsx | 78 +++++++++++++++++-- .../app/src/agent-stream/strategy-web.tsx | 2 + 2 files changed, 73 insertions(+), 7 deletions(-) diff --git a/packages/app/src/agent-stream/strategy-web.browser.test.tsx b/packages/app/src/agent-stream/strategy-web.browser.test.tsx index a9cc44a849..188e8d8edf 100644 --- a/packages/app/src/agent-stream/strategy-web.browser.test.tsx +++ b/packages/app/src/agent-stream/strategy-web.browser.test.tsx @@ -54,8 +54,16 @@ type OlderHistoryInput = Pick< "onNearHistoryStart" | "hasOlderHistory" | "olderHistoryProgressKey" >; -function mountTimeline(historyMounted: StreamItem[], olderHistory?: OlderHistoryInput) { - const strategy = createWebStreamStrategy({ isMobileBreakpoint: true }); +interface MountTimelineOptions { + olderHistory?: OlderHistoryInput; + isMobileBreakpoint?: boolean; +} + +function mountTimeline( + historyMounted: StreamItem[], + { olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {}, +) { + const strategy = createWebStreamStrategy({ isMobileBreakpoint }); const viewportRef = React.createRef(); const input: StreamRenderInput = { agentId: "agent", @@ -113,6 +121,13 @@ function mountTimeline(historyMounted: StreamItem[], olderHistory?: OlderHistory }, distanceFromEnd: () => scrollContainer.scrollHeight - scrollContainer.clientHeight - scrollContainer.scrollTop, + scrollTop: () => scrollContainer.scrollTop, + scrollUp: (distance: number) => + act(() => { + scrollContainer.dispatchEvent(new WheelEvent("wheel", { deltaY: -distance })); + scrollContainer.scrollTop -= distance; + scrollContainer.dispatchEvent(new Event("scroll")); + }), // Resize observers and the hold's settle run on animation frames. settle: () => act(async () => { @@ -124,6 +139,53 @@ function mountTimeline(historyMounted: StreamItem[], olderHistory?: OlderHistory } describe("web disclosure hold", () => { + it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])( + "keeps the reading position when mounted history becomes virtualized (compact: $isMobileBreakpoint)", + async (options) => { + const history = Array.from({ length: 80 }, (_, index) => row(index)); + const timeline = mountTimeline(history, options); + await timeline.settle(); + timeline.scrollUp(600); + await timeline.settle(); + const offset = timeline.scrollTop(); + const readingTop = timeline.rowTop("message-64"); + expect(offset).toBeGreaterThan(0); + + timeline.render({ + historyVirtualized: history.slice(0, 60), + historyMounted: history.slice(60), + }); + await timeline.settle(); + + expect(timeline.scrollTop()).toBe(offset); + expect(timeline.rowTop("message-64")).toBe(readingTop); + }, + ); + + it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])( + "keeps following output when mounted history becomes virtualized at the end (compact: $isMobileBreakpoint)", + async (options) => { + const history = Array.from({ length: 80 }, (_, index) => row(index)); + const timeline = mountTimeline(history, options); + await timeline.settle(); + + timeline.render({ + historyVirtualized: history.slice(0, 60), + historyMounted: history.slice(60), + }); + await timeline.settle(); + expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1); + + timeline.render({ + historyVirtualized: history.slice(0, 60), + historyMounted: history.slice(60), + liveHead: [row(80)], + }); + await timeline.settle(); + expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1); + }, + ); + it("keeps the trigger's top when an anchored toggle at the bottom opens rows below it, and stops following", async () => { const history = [1, 2, 3, 4, 5, 6].map((index) => row(index)); const timeline = mountTimeline(history); @@ -225,11 +287,13 @@ describe("web history start", () => { let olderHistoryLoads = 0; const history = [1, 2, 3, 4, 5, 6].map((index) => row(index)); const timeline = mountTimeline(history, { - hasOlderHistory: true, - olderHistoryProgressKey: "epoch:1", - onNearHistoryStart: async () => { - olderHistoryLoads += 1; - return true; + olderHistory: { + hasOlderHistory: true, + olderHistoryProgressKey: "epoch:1", + onNearHistoryStart: async () => { + olderHistoryLoads += 1; + return true; + }, }, }); await timeline.settle(); diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index 896b53b3f6..465d98e8d8 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -457,6 +457,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool const rowVirtualizer = useVirtualizer({ count: segments.historyVirtualized.length, enabled: shouldUseVirtualizer, + // History can become virtualized after the reader has already scrolled the mounted rows. + initialOffset: () => scrollContainerRef.current?.scrollTop ?? 0, initialRect: { width: scrollContainerRef.current?.clientWidth ?? 0, height: scrollContainerRef.current?.clientHeight ?? 0, From be487ce65f6953841e53dae61b327bf53550fce2 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 20:41:37 +0700 Subject: [PATCH 049/160] Keep seeded dev daemon homes from resuming agents (#9672) * fix(dev): keep seeded daemon homes from resuming agents * fix(dev): accept BOM configs when seeding homes * fix(dev): skip existing homes before reading seed config * fix(dev): seed homes from symlinked checkout paths * fix(dev): copy linked metadata into independent seed files --- docs/development.md | 2 +- .../agent/restart-recovery/index.test.ts | 132 +++++++++++++++++- scripts/dev-home.sh | 58 +------- scripts/seed-dev-home.mjs | 84 +++++++++++ scripts/seed-worktree-dev-state.mjs | 71 +--------- 5 files changed, 226 insertions(+), 121 deletions(-) create mode 100644 scripts/seed-dev-home.mjs diff --git a/docs/development.md b/docs/development.md index ddebf3ffff..389337f24f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -49,7 +49,7 @@ than downloading a published desktop release. - The **server itself** (e.g. when launched by the desktop app or `npm run start`) defaults to `~/.paseo` (see `packages/server/src/server/paseo-home.ts`). - **Repo dev scripts** default to `$ROOT/.dev/paseo-home`, where `$ROOT` is the current checkout or worktree root. This keeps all dev state scoped to the checkout instead of the packaged desktop app. - **`npm run cli -- ...`** runs through the same dev-home wrapper as the dev scripts, so the in-repo CLI automatically targets the current checkout's `.dev/paseo-home` and configured dev daemon endpoint. -- **Paseo-created worktrees** seed `$PASEO_WORKTREE_PATH/.dev/paseo-home` from `$PASEO_SOURCE_CHECKOUT_PATH/.dev/paseo-home` by copying durable JSON metadata. Runtime files like pid files, sockets, and logs are not copied. +- **Paseo-created worktrees** seed `$PASEO_WORKTREE_PATH/.dev/paseo-home` from `$PASEO_SOURCE_CHECKOUT_PATH/.dev/paseo-home` by copying agent and project JSON metadata and configuration. Both this setup and `PASEO_DEV_SEED_HOME` use the same seeder, which disables `agents.resumeOnStartup` in the copied config. Startup repairs copied running records without resuming agents or sending recovery prompts. Schedules and heartbeats (stored under `schedules/`), runtime files, identities, sockets, and logs are not copied. Existing nonempty homes are left unchanged unless explicitly reset. Copied agents still reference the original provider sessions and working directories: manually prompting one reaches that real session. - **This repo's worktree setup** also best-effort seeds `packages/app/ios` and the newest `.dev/ios-build` entry from the source checkout so iOS simulator services can reuse native project and Xcode cache state when it is safe enough to do so. Override knobs: diff --git a/packages/server/src/server/agent/restart-recovery/index.test.ts b/packages/server/src/server/agent/restart-recovery/index.test.ts index 77adf359c4..c058f5c14d 100644 --- a/packages/server/src/server/agent/restart-recovery/index.test.ts +++ b/packages/server/src/server/agent/restart-recovery/index.test.ts @@ -1,9 +1,12 @@ import { expect, test } from "vitest"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, mkdir, writeFile, readdir, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; +import { execFileSync, spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; import { join } from "node:path"; import { AgentStorage, parseStoredAgentRecord } from "../agent-storage.js"; import { createTestLogger } from "../../../test-utils/test-logger.js"; +import { readPersistedConfig } from "../../persisted-config.js"; import { createRestartRecovery } from "./index.js"; test("recovery saves intent before normalization, clears before dispatch, and resumes each agent independently", async () => { @@ -103,3 +106,130 @@ test("opt-out consumes pending recovery and excludes archived, private, owned an await rm(root, { recursive: true, force: true }); } }); + +const bashAvailable = + process.platform !== "win32" && + spawnSync("bash", ["-c", "true"], { stdio: "ignore" }).status === 0; +for (const seeder of ["setup", "shell", "setup-bom"] as const) { + test.skipIf(seeder === "shell" && !bashAvailable)( + `${seeder} seed never dispatches copied running or pending agents and excludes automation`, + async () => { + const root = await mkdtemp(join(tmpdir(), "inert-seed-")); + try { + const source = join(root, "source"); + const targetRoot = join(root, "target"); + const target = join(targetRoot, ".dev/paseo-home"); + const storage = new AgentStorage(join(root, "source-records"), createTestLogger()); + for (const [id, lastStatus, resumeOnStartup] of [ + ["live", "running", false], + ["crashed", "running", true], + ["stopped", "closed", true], + ] as const) { + await storage.upsert( + parseStoredAgentRecord({ + id, + lastStatus, + resumeOnStartup, + provider: "codex", + cwd: root, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + ); + } + await storage.flush(); + await mkdir(source, { recursive: true }); + await symlink( + join(root, "source-records"), + join(source, "agents"), + process.platform === "win32" ? "junction" : "dir", + ); + await mkdir(join(source, "schedules"), { recursive: true }); + await writeFile(join(source, "schedules", "schedule.json"), '{"kind":"scheduled"}'); + await writeFile(join(source, "schedules", "heartbeat.json"), '{"kind":"heartbeat"}'); + await writeFile( + join(source, "config.json"), + (seeder === "setup-bom" ? "\uFEFF" : "") + + JSON.stringify({ + version: 1, + agents: { resumeOnStartup: true, resumePrompt: "Continue" }, + }), + ); + const repo = fileURLToPath(new URL("../../../../../../", import.meta.url)); + const env = { + ...process.env, + PASEO_SOURCE_CHECKOUT_PATH: join(root, "checkout"), + PASEO_WORKTREE_PATH: targetRoot, + PASEO_DEV_SEED_HOME: source, + PASEO_HOME: target, + }; + if (seeder !== "shell") + execFileSync(process.execPath, [join(repo, "scripts/seed-worktree-dev-state.mjs")], { + env, + }); + else { + const linkedRepo = join(root, "linked-checkout"); + await symlink(repo, linkedRepo, "dir"); + execFileSync("bash", [join(linkedRepo, "scripts/dev-home.sh")], { env }); + } + expect((await readdir(target)).sort()).toEqual(["agents", "config.json"]); + const config = readPersistedConfig(target); + const copied = new AgentStorage(join(target, "agents"), createTestLogger()); + const dispatched: string[] = []; + const recovery = createRestartRecovery({ + storage: copied, + settings: () => ({ + enabled: config.agents?.resumeOnStartup === true, + prompt: "Continue", + }), + eligible: async () => true, + dispatch: async (id) => { + dispatched.push(id); + }, + report: () => {}, + }); + await recovery.prepareStartup(); + recovery.resumePending(); + for (const record of await copied.listAll()) + await recovery.waitForResume(record.id, new AbortController().signal); + expect(dispatched).toEqual([]); + expect((await copied.listAll()).map((r) => [r.lastStatus, r.resumeOnStartup])).toEqual([ + ["closed", false], + ["closed", false], + ["closed", false], + ]); + expect(readPersistedConfig(source).agents?.resumeOnStartup).toBe(true); + const unchangedSource = new AgentStorage(join(root, "source-records"), createTestLogger()); + expect((await unchangedSource.get("live"))?.lastStatus).toBe("running"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }, + ); +} + +test("seeding skips an existing home without reading invalid source config", async () => { + const root = await mkdtemp(join(tmpdir(), "seed-skip-")); + try { + const source = join(root, "source"); + const targetRoot = join(root, "target"); + const target = join(targetRoot, ".dev/paseo-home"); + await mkdir(source, { recursive: true }); + await mkdir(target, { recursive: true }); + await writeFile(join(source, "config.json"), "invalid JSON"); + await writeFile(join(target, "keep.json"), "{}"); + const repo = fileURLToPath(new URL("../../../../../../", import.meta.url)); + execFileSync(process.execPath, [join(repo, "scripts/seed-worktree-dev-state.mjs")], { + env: { + ...process.env, + PASEO_SOURCE_CHECKOUT_PATH: join(root, "checkout"), + PASEO_WORKTREE_PATH: targetRoot, + PASEO_DEV_SEED_HOME: source, + PASEO_DEV_RESET_HOME: "0", + }, + }); + expect(await readdir(target)).toEqual(["keep.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/dev-home.sh b/scripts/dev-home.sh index a7cea3e051..89322ccc9d 100755 --- a/scripts/dev-home.sh +++ b/scripts/dev-home.sh @@ -4,62 +4,10 @@ default_dev_paseo_root() { git rev-parse --show-toplevel 2>/dev/null || pwd } -copy_json_tree() { - local source_dir="$1" - local target_dir="$2" - - if [ ! -d "$source_dir" ]; then - return - fi - - mkdir -p "$target_dir" - if command -v rsync >/dev/null 2>&1; then - rsync -a --include='*/' --include='*.json' --exclude='*' "$source_dir/" "$target_dir/" - return - fi - - while IFS= read -r -d '' source_file; do - local relative_path="${source_file#"$source_dir"/}" - local target_file="$target_dir/$relative_path" - mkdir -p "$(dirname "$target_file")" - cp "$source_file" "$target_file" - done < <(find "$source_dir" -type f -name '*.json' -print0) -} - -has_files() { - [ -d "$1" ] && [ -n "$(find "$1" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ] -} - seed_worktree_paseo_home() { - local source_home="${PASEO_DEV_SEED_HOME:-$HOME/.paseo}" - local target_home="$1" - - if [ ! -d "$source_home" ]; then - echo " Seed: skipped (${source_home} missing)" - return - fi - - if [ "$source_home" = "$target_home" ]; then - echo " Seed: skipped (source is target)" - return - fi - - if [ "${PASEO_DEV_RESET_HOME:-0}" = "1" ]; then - rm -rf "$target_home" - elif has_files "$target_home"; then - echo " Seed: skipped (${target_home} already has data)" - return - fi - - mkdir -p "$target_home" - echo " Seed: copying metadata from ${source_home}" - copy_json_tree "$source_home/agents" "$target_home/agents" - copy_json_tree "$source_home/projects" "$target_home/projects" - if [ -f "$source_home/config.json" ]; then - cp "$source_home/config.json" "$target_home/config.json" - fi - - echo " Seed: copied metadata from ${source_home}" + local script_dir + script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + node "$script_dir/seed-dev-home.mjs" "${PASEO_DEV_SEED_HOME:-$HOME/.paseo}" "$1" } configure_dev_daemon_config() { diff --git a/scripts/seed-dev-home.mjs b/scripts/seed-dev-home.mjs new file mode 100644 index 0000000000..c82d878821 --- /dev/null +++ b/scripts/seed-dev-home.mjs @@ -0,0 +1,84 @@ +import { + cpSync, + realpathSync, + existsSync, + mkdirSync, + readdirSync, + rmSync, + statSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +export function seedPaseoHome(source, target) { + if (!existsSync(source)) { + console.log(` Seed: skipped (${source} missing)`); + return; + } + + if (source === target) { + console.log(" Seed: skipped (source is target)"); + return; + } + + if (process.env.PASEO_DEV_RESET_HOME !== "1" && hasEntries(target)) { + console.log(` Seed: skipped (${target} already has data)`); + return; + } + + const configPath = join(source, "config.json"); + const config = existsSync(configPath) + ? JSON.parse(readFileSync(configPath, "utf8").replace(/^\uFEFF/, "")) + : { version: 1 }; + + if (process.env.PASEO_DEV_RESET_HOME === "1") { + rmSync(target, { recursive: true, force: true }); + } + + mkdirSync(target, { recursive: true }); + console.log(` Seed: copying metadata from ${source}`); + copyJsonTree(join(source, "agents"), join(target, "agents")); + copyJsonTree(join(source, "projects"), join(target, "projects")); + + // A snapshot does not own the source daemon's pending work. Recovery normalizes + // copied running records on startup without sending a prompt when disabled. + config.agents = { ...config.agents, resumeOnStartup: false }; + writeFileSync(join(target, "config.json"), JSON.stringify(config, null, 2)); + + console.log(` Seed: copied metadata from ${source}`); +} + +// Durable JSON metadata only. Runtime files (pid files, sockets, logs) must not be copied. +function copyJsonTree(source, target) { + if (!existsSync(source)) { + return; + } + + cpSync(source, target, { + recursive: true, + dereference: true, + filter: (path) => isDirectory(path) || path.endsWith(".json"), + }); +} + +function hasEntries(path) { + try { + return readdirSync(path).length > 0; + } catch { + return false; + } +} + +function isDirectory(path) { + try { + return statSync(path).isDirectory(); + } catch { + return false; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) { + seedPaseoHome(process.argv[2], process.argv[3]); +} diff --git a/scripts/seed-worktree-dev-state.mjs b/scripts/seed-worktree-dev-state.mjs index d645789596..87ebd28e2a 100644 --- a/scripts/seed-worktree-dev-state.mjs +++ b/scripts/seed-worktree-dev-state.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs"; +import { cpSync, existsSync, mkdirSync } from "node:fs"; import { dirname, join } from "node:path"; // Worktree setup runs through a stable script shell: bash on macOS/Linux, but PowerShell @@ -7,6 +7,8 @@ import { dirname, join } from "node:path"; // `./scripts/*.sh`) cannot express this step portably, so the seeding lives in Node — the // one interpreter every Paseo checkout already depends on. +import { seedPaseoHome } from "./seed-dev-home.mjs"; + const sourceRoot = process.env.PASEO_SOURCE_CHECKOUT_PATH; const targetRoot = process.env.PASEO_WORKTREE_PATH || process.cwd(); @@ -14,55 +16,12 @@ if (!sourceRoot || sourceRoot === targetRoot) { process.exit(0); } -seedPaseoHome(); +seedPaseoHome( + process.env.PASEO_DEV_SEED_HOME || join(sourceRoot, ".dev/paseo-home"), + join(targetRoot, ".dev/paseo-home"), +); copyServerEnv(); -function seedPaseoHome() { - const source = process.env.PASEO_DEV_SEED_HOME || join(sourceRoot, ".dev/paseo-home"); - const target = join(targetRoot, ".dev/paseo-home"); - - if (!existsSync(source)) { - console.log(` Seed: skipped (${source} missing)`); - return; - } - - if (source === target) { - console.log(" Seed: skipped (source is target)"); - return; - } - - if (process.env.PASEO_DEV_RESET_HOME === "1") { - rmSync(target, { recursive: true, force: true }); - } else if (hasEntries(target)) { - console.log(` Seed: skipped (${target} already has data)`); - return; - } - - mkdirSync(target, { recursive: true }); - console.log(` Seed: copying metadata from ${source}`); - copyJsonTree(join(source, "agents"), join(target, "agents")); - copyJsonTree(join(source, "projects"), join(target, "projects")); - - const config = join(source, "config.json"); - if (existsSync(config)) { - cpSync(config, join(target, "config.json")); - } - - console.log(` Seed: copied metadata from ${source}`); -} - -// Durable JSON metadata only. Runtime files (pid files, sockets, logs) must not be copied. -function copyJsonTree(source, target) { - if (!existsSync(source)) { - return; - } - - cpSync(source, target, { - recursive: true, - filter: (path) => isDirectory(path) || path.endsWith(".json"), - }); -} - function copyServerEnv() { const source = join(sourceRoot, "packages/server/.env"); const target = join(targetRoot, "packages/server/.env"); @@ -77,19 +36,3 @@ function copyServerEnv() { cpSync(source, target); console.log(` Env: copied ${source}`); } - -function hasEntries(path) { - try { - return readdirSync(path).length > 0; - } catch { - return false; - } -} - -function isDirectory(path) { - try { - return statSync(path).isDirectory(); - } catch { - return false; - } -} From c81f38d7ca77b5f3091496d9e5133a036ad84f0d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 20:46:16 +0700 Subject: [PATCH 050/160] Give the sidebar list its end back: drop the permanent room for the toast (#9667) The sidebar list's bottom padding goes back to 16 and stays constant. The archive toast stays over the list's bottom edge, as on main, so nothing moves when it appears or leaves. --- .../browser/workspace-archive-undo.spec.ts | 37 +++++++++++++++++++ .../support/helpers/workspace-archive-undo.ts | 35 ++++++++++++++++++ .../src/components/sidebar-workspace-list.tsx | 6 +-- .../sidebar/sidebar-status-list.tsx | 5 ++- 4 files changed, 78 insertions(+), 5 deletions(-) diff --git a/packages/app/e2e/browser/workspace-archive-undo.spec.ts b/packages/app/e2e/browser/workspace-archive-undo.spec.ts index 9f9567b75a..68cc16166e 100644 --- a/packages/app/e2e/browser/workspace-archive-undo.spec.ts +++ b/packages/app/e2e/browser/workspace-archive-undo.spec.ts @@ -14,6 +14,7 @@ import { connectSeedClient } from "../support/helpers/seed-client"; import { createTempGitRepo } from "../support/helpers/workspace"; import { getWorkspaceTabTestIds } from "../support/helpers/workspace-tabs"; import { + archivedToast, archiveFromRowButton, createGatedTeardown, expectDirectoryPresence, @@ -25,6 +26,7 @@ import { resizeSidebarToMinimum, rowArchiveButton, rowKebab, + scrollSidebarListToEnd, undoButton, workspaceRow, workspaceTitleWidth, @@ -119,6 +121,41 @@ test.describe("Workspace archive undo", () => { expect(shortcutBox.x - (labelBox.x + labelBox.width)).toBeLessThanOrEqual(8.5); }); + test("a long list ends just below its last row, and the toast over it moves no row", async ({ + page, + }) => { + await page.clock.install({ time: Date.now() }); + const fillers: Array<{ path: string; cleanup: () => Promise }> = []; + const fillerProjectIds: string[] = []; + try { + for (let index = 0; index < 10; index += 1) { + const repo = await createTempGitRepo(`archive-toast-filler-${index}-`); + fillers.push(repo); + fillerProjectIds.push((await openProjectViaDaemon(client, repo.path)).projectId); + } + const worktree = await seedWorktree(page, "archive-toast-long-list"); + + const resting = await scrollSidebarListToEnd(page); + expect(resting.listBottom - resting.rowBottoms.at(-1)!).toBeLessThan(resting.rowHeight); + + await archiveFromRowButton(page, worktree.workspaceId); + await page.mouse.move(0, 0); + const withToast = await scrollSidebarListToEnd(page); + const toastBox = await archivedToast(page).boundingBox(); + if (!toastBox) throw new Error("Toast is not laid out"); + expect(toastBox.y + toastBox.height).toBeLessThanOrEqual(withToast.listBottom); + + await outlastUndoWindow(page); + await expect(archivedToast(page)).toHaveCount(0); + expect(await scrollSidebarListToEnd(page)).toEqual(withToast); + } finally { + for (const projectId of fillerProjectIds) { + await client.removeProject(projectId).catch(() => undefined); + } + for (const repo of fillers) await repo.cleanup().catch(() => undefined); + } + }); + test("an archive that fails after the sidebar was replaced still shows its error", async ({ page, }) => { diff --git a/packages/app/e2e/support/helpers/workspace-archive-undo.ts b/packages/app/e2e/support/helpers/workspace-archive-undo.ts index 7f6846b252..c446b163c2 100644 --- a/packages/app/e2e/support/helpers/workspace-archive-undo.ts +++ b/packages/app/e2e/support/helpers/workspace-archive-undo.ts @@ -162,3 +162,38 @@ export function createGatedTeardown(): GatedTeardown { release: () => writeFileSync(releasePath, "release\n"), }; } + +export function archivedToast(page: Page) { + return page.getByTestId("workspace-archived-toast"); +} + +export interface SidebarListLayout { + /** Bottom edge of the list's visible area. */ + listBottom: number; + /** Bottom edges of the visible project and workspace rows, top to bottom. */ + rowBottoms: number[]; + rowHeight: number; +} + +/** Scrolls the sidebar's workspace list to its end and reads where its rows sit. */ +export async function scrollSidebarListToEnd(page: Page): Promise { + const list = page.getByTestId("sidebar-project-workspace-list-scroll"); + await list.evaluate((element) => { + element.scrollTop = element.scrollHeight; + }); + return list.evaluate((element) => { + const visible = element.getBoundingClientRect(); + const rows = Array.from( + element.querySelectorAll( + '[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]', + ), + ) + .map((row) => row.getBoundingClientRect()) + .filter((row) => row.height > 0 && row.bottom > visible.top && row.top < visible.bottom); + return { + listBottom: visible.bottom, + rowBottoms: rows.map((row) => row.bottom).sort((a, b) => a - b), + rowHeight: Math.min(...rows.map((row) => row.height)), + }; + }); +} diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index 4c4c1575fd..b4f7547259 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -2592,9 +2592,9 @@ const styles = StyleSheet.create((theme) => ({ // Optical inset: aligns the visible Pinned/Workspaces glyph edge with the // Schedules icon across the divider; their layout boxes have different insets. paddingTop: 2, - // Keep the last row scrollable above the sidebar toast, including a wrapped Undo row. - // This space stays present across toast changes so the scroll range never jumps. - paddingBottom: theme.spacing[24], + // The sidebar toast floats over the list's end. Keep this padding the same whether or not + // a toast shows: changing it moves the rows when the toast leaves. + paddingBottom: theme.spacing[4], }, projectListContainer: { width: "100%", diff --git a/packages/app/src/components/sidebar/sidebar-status-list.tsx b/packages/app/src/components/sidebar/sidebar-status-list.tsx index b271157d03..459ae3cfb3 100644 --- a/packages/app/src/components/sidebar/sidebar-status-list.tsx +++ b/packages/app/src/components/sidebar/sidebar-status-list.tsx @@ -1101,8 +1101,9 @@ const styles = StyleSheet.create((theme) => ({ paddingHorizontal: theme.spacing[2], // Keep status mode's Pinned/Workspaces boundary identical to project mode. paddingTop: 2, - // Match project grouping: permanent room to scroll the final row above sidebar toasts. - paddingBottom: theme.spacing[24], + // The sidebar toast floats over the list's end. Keep this padding the same whether or not + // a toast shows: changing it moves the rows when the toast leaves. + paddingBottom: theme.spacing[4], }, pinnedSection: { marginBottom: theme.spacing[1], From 85fb5b436d5d1e6b377c19c3c6271ece66e56d33 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 21:10:17 +0700 Subject: [PATCH 051/160] Sidebar drops on iOS and Android land without a flash, keeping the current list (remount alternative) (#9681) * fix(app): drop a sidebar row without a wrong frame on native by remounting moved cells draggable-flatlist moves a cell with a held drag translate. Reanimated re-applies a view's last animated transform to every React commit, so the reorder commit painted one frame of new order plus old translate. The drop now gives each moved cell a fresh transform host, keyed per cell, so the reorder commit mounts views with no animated transform to re-apply. Moved cells remount their row subtree on each drop. * fix(app): keep a project's Show more reveal when a drop remounts it The drop remounts each project block it moves, and the block held its own reveal state, so a revealed project shrank back after a drop. The project list now owns the reveal per project, and the group hook takes it as input. * docs(app): note that a native drop resets state held inside a moved row * fix(app): render every row of a non-scrolling native list in its first commit A drop remounts the nested workspace list of each project block it moves. FlatList renders 10 rows on mount, so a moved project showing more than 10 workspaces painted 10 rows and grew a commit later. --- .../src/components/draggable-list.native.tsx | 8 + .../sidebar-workspace-list.test.tsx | 63 +++-- .../src/components/sidebar-workspace-list.tsx | 38 ++- .../sidebar/sidebar-status-list.tsx | 21 +- .../sidebar/use-limited-sidebar-group.ts | 19 +- ...eact-native-draggable-flatlist+4.0.3.patch | 231 ++++++++++++++++-- scripts/postinstall-patches.mjs | 4 + 7 files changed, 318 insertions(+), 66 deletions(-) diff --git a/packages/app/src/components/draggable-list.native.tsx b/packages/app/src/components/draggable-list.native.tsx index ee5acb7f51..5d5f4cf5f3 100644 --- a/packages/app/src/components/draggable-list.native.tsx +++ b/packages/app/src/components/draggable-list.native.tsx @@ -11,6 +11,10 @@ export type { DraggableListProps, DraggableRenderItemInfo }; const SCROLL_ENABLED_FLEX_STYLE = { flex: 1 }; +// A drop remounts every row between the drag's start and end slots (see the draggable-flatlist +// patch), so state held inside a rendered row resets when a drop moves it. Keep state that must +// survive a reorder in the list's owner, keyed by row. + export function DraggableList({ data, keyExtractor, @@ -117,6 +121,10 @@ export function DraggableList({ ListEmptyComponent={ListEmptyComponent} showsVerticalScrollIndicator={showsVerticalScrollIndicator} scrollEnabled={scrollEnabled} + // A list that doesn't scroll shows every row, so it renders them all in its first commit. + // FlatList's default first render is 10 rows; a nested list remounted by a drop would paint + // 10 rows, then grow on a later commit. + initialNumToRender={scrollEnabled ? undefined : data.length} extraData={extraData} simultaneousHandlers={simultaneousHandlers} dragGestureHostPresented={gestureHostPresented} diff --git a/packages/app/src/components/sidebar-workspace-list.test.tsx b/packages/app/src/components/sidebar-workspace-list.test.tsx index 9532c422dd..a5443c90c7 100644 --- a/packages/app/src/components/sidebar-workspace-list.test.tsx +++ b/packages/app/src/components/sidebar-workspace-list.test.tsx @@ -462,7 +462,9 @@ describe("sidebar group visibility", () => { it.each([0, 7, 8])("limits %i Done rows to seven", (count) => { const items = entries(Array(count).fill("done")); - const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy })); + const { result } = renderHook(() => + useLimitedSidebarGroup({ items, selection: null, expanded: false, policy }), + ); expect(result.current.visibleItems).toEqual(items.slice(0, 7)); expect(result.current.canToggle).toBe(count > 7); }); @@ -472,7 +474,7 @@ describe("sidebar group visibility", () => { (status) => { const items = entries([...Array(11).fill("done"), status]); const { result } = renderHook(() => - useLimitedSidebarGroup({ items, selection: null, policy }), + useLimitedSidebarGroup({ items, selection: null, expanded: false, policy }), ); expect(names(result.current.visibleItems)).toEqual([ "row-1", @@ -497,6 +499,7 @@ describe("sidebar group visibility", () => { useLimitedSidebarGroup({ items, selection: null, + expanded: false, policy: createWorkspaceVisibilityPolicy(entriesByKey), }), ); @@ -518,7 +521,9 @@ describe("sidebar group visibility", () => { "needs_input", "failed", ]); - const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy })); + const { result } = renderHook(() => + useLimitedSidebarGroup({ items, selection: null, expanded: false, policy }), + ); expect(result.current.visibleItems).toEqual(items); expect(result.current.canToggle).toBe(false); }); @@ -532,9 +537,10 @@ describe("sidebar group visibility", () => { "done", "attention", ]); - const { result, rerender, unmount } = renderHook( - ({ rows }) => useLimitedSidebarGroup({ items: rows, selection: null, policy }), - { initialProps: { rows: items } }, + const { result, rerender } = renderHook( + ({ rows, expanded }) => + useLimitedSidebarGroup({ items: rows, selection: null, expanded, policy }), + { initialProps: { rows: items, expanded: false } }, ); expect(names(result.current.visibleItems)).toEqual([ "row-1", @@ -548,16 +554,15 @@ describe("sidebar group visibility", () => { "row-10", "row-12", ]); - act(() => result.current.toggleExpanded()); + rerender({ rows: items, expanded: true }); expect(result.current.visibleItems).toEqual(items); - rerender({ rows: items.map((item) => ({ ...item, statusBucket: "running" })) }); + rerender({ rows: items.map((item) => ({ ...item, statusBucket: "running" })), expanded: true }); expect(result.current.canToggle).toBe(false); - expect(result.current.expanded).toBe(true); - rerender({ rows: items.slice(0, 3) }); + rerender({ rows: items.slice(0, 3), expanded: true }); expect(result.current.canToggle).toBe(false); - rerender({ rows: items.toReversed() }); + rerender({ rows: items.toReversed(), expanded: true }); expect(result.current.visibleItems).toEqual(items.toReversed()); - act(() => result.current.toggleExpanded()); + rerender({ rows: items.toReversed(), expanded: false }); expect(names(result.current.visibleItems)).toEqual([ "row-12", "row-11", @@ -568,15 +573,25 @@ describe("sidebar group visibility", () => { "row-6", ]); const newest = { ...items[0], workspaceId: "new", workspaceKey: "srv:new" }; - rerender({ rows: [newest, ...items] }); + rerender({ rows: [newest, ...items], expanded: false }); expect(result.current.visibleItems[0]).toBe(newest); expect(result.current.visibleItems).toHaveLength(10); - expect(result.current.expanded).toBe(false); - act(() => result.current.toggleExpanded()); - unmount(); - const remounted = renderHook(() => useLimitedSidebarGroup({ items, selection: null, policy })); - expect(remounted.result.current.expanded).toBe(false); - expect(remounted.result.current.visibleItems).toHaveLength(10); + }); + + it("shows the reveal its owner passes in on every mount", () => { + // A native drop remounts every project block it moves, so the group holds no reveal of its + // own. Only the native list remounts rows; the browser list never does, so no test here can + // drive that remount. + const items = entries([...Array(7).fill("done"), "running", "done", "failed", "done"]); + const first = renderHook(() => + useLimitedSidebarGroup({ items, selection: null, expanded: true, policy }), + ); + expect(first.result.current.visibleItems).toEqual(items); + first.unmount(); + const remounted = renderHook(() => + useLimitedSidebarGroup({ items, selection: null, expanded: true, policy }), + ); + expect(remounted.result.current.visibleItems).toEqual(items); }); it("follows effective pending creation, recovery and agent activity without changing Created order", () => { @@ -602,6 +617,7 @@ describe("sidebar group visibility", () => { useLimitedSidebarGroup({ items: [...items.slice(0, 11), last], selection: null, + expanded: false, policy, }), { initialProps: { last: items[11] } }, @@ -641,12 +657,15 @@ describe("sidebar group visibility", () => { it("preserves the twenty-row pinned policy regardless of status", () => { const items = entries(Array(21).fill("running")); - const { result } = renderHook(() => useLimitedSidebarGroup({ items, selection: null })); + const { result, rerender } = renderHook( + ({ expanded }) => useLimitedSidebarGroup({ items, selection: null, expanded }), + { initialProps: { expanded: false } }, + ); expect(result.current.visibleItems).toEqual(items.slice(0, 20)); expect(result.current.canToggle).toBe(true); - act(() => result.current.toggleExpanded()); + rerender({ expanded: true }); expect(result.current.visibleItems).toEqual(items); - act(() => result.current.toggleExpanded()); + rerender({ expanded: false }); expect(result.current.visibleItems).toHaveLength(20); }); }); diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index b4f7547259..c2b767b619 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -1557,6 +1557,8 @@ function ProjectBlock({ showShortcutBadges, shortcutIndexByWorkspaceKey, onToggleCollapsed, + workspacesExpanded, + onToggleWorkspacesExpanded, onWorkspacePress, parentGestureRef, onWorkspaceReorder, @@ -1583,6 +1585,9 @@ function ProjectBlock({ showShortcutBadges: boolean; shortcutIndexByWorkspaceKey: Map; onToggleCollapsed: (projectViewKey: string) => void; + /** "Show more" on this project's workspaces, owned by the list so a drop's remount keeps it. */ + workspacesExpanded: boolean; + onToggleWorkspacesExpanded: (projectViewKey: string) => void; onWorkspacePress?: () => void; parentGestureRef?: MutableRefObject; onWorkspaceReorder: (projectViewKey: string, workspaces: SidebarWorkspacePlacement[]) => void; @@ -1607,12 +1612,11 @@ function ProjectBlock({ const { leadingItem: leadingWorkspace, visibleItems: visibleWorkspaces, - expanded: workspacesExpanded, canToggle: canToggleWorkspaces, - toggleExpanded: toggleWorkspacesExpanded, } = useLimitedSidebarGroup({ items: project.workspaces, selection: selectionEnabled ? activeWorkspaceSelection : null, + expanded: workspacesExpanded, policy: visibilityPolicy, }); const activeServerId = activeWorkspaceSelection?.serverId ?? null; @@ -1770,6 +1774,10 @@ function ProjectBlock({ onToggleCollapsed(project.viewKey); }, [onToggleCollapsed, project.viewKey]); + const handleToggleWorkspacesExpanded = useCallback(() => { + onToggleWorkspacesExpanded(project.viewKey); + }, [onToggleWorkspacesExpanded, project.viewKey]); + let projectChildren = null; if (!collapsed) { if (project.workspaces.length > 0) { @@ -1806,7 +1814,7 @@ function ProjectBlock({ {canToggleWorkspaces ? ( ) : null} @@ -1876,6 +1884,8 @@ function areProjectBlockPropsEqual(previous: ProjectBlockProps, next: ProjectBlo previous.supportsPinningByServerId === next.supportsPinningByServerId && previous.onToggleWorkspacePin === next.onToggleWorkspacePin && previous.onToggleCollapsed === next.onToggleCollapsed && + previous.workspacesExpanded === next.workspacesExpanded && + previous.onToggleWorkspacesExpanded === next.onToggleWorkspacesExpanded && previous.onWorkspacePress === next.onWorkspacePress && previous.parentGestureRef === next.parentGestureRef && previous.onWorkspaceReorder === next.onWorkspaceReorder && @@ -2204,15 +2214,29 @@ function ProjectModeList({ const selectionEnabled = isWorkspaceRoute; const activeWorkspaceSelection = useActiveWorkspaceSelection(); const { pinnedChats, unpinnedProjects } = pinnedGroups; + const [pinnedChatsExpanded, setPinnedChatsExpanded] = useState(false); + const togglePinnedChatsExpanded = useCallback( + () => setPinnedChatsExpanded((current) => !current), + [], + ); + const [expandedProjectKeys, setExpandedProjectKeys] = useState>( + () => new Set(), + ); + const toggleProjectWorkspacesExpanded = useCallback((projectViewKey: string) => { + setExpandedProjectKeys((current) => { + const next = new Set(current); + if (!next.delete(projectViewKey)) next.add(projectViewKey); + return next; + }); + }, []); const { leadingItem: leadingPinnedChat, visibleItems: visiblePinnedChats, - expanded: pinnedChatsExpanded, canToggle: canTogglePinnedChats, - toggleExpanded: togglePinnedChatsExpanded, } = useLimitedSidebarGroup({ items: pinnedChats, selection: selectionEnabled ? activeWorkspaceSelection : null, + expanded: pinnedChatsExpanded, }); const nativeScrollGestureProps = useMemo( () => @@ -2368,6 +2392,8 @@ function ProjectModeList({ showShortcutBadges={showShortcutBadges} shortcutIndexByWorkspaceKey={shortcutIndexByWorkspaceKey} onToggleCollapsed={onToggleProjectCollapsed} + workspacesExpanded={expandedProjectKeys.has(item.viewKey)} + onToggleWorkspacesExpanded={toggleProjectWorkspacesExpanded} onWorkspacePress={onWorkspacePress} manualSort={manualSort} parentGestureRef={parentGestureRef} @@ -2389,6 +2415,8 @@ function ProjectModeList({ }, [ collapsedProjectKeys, + expandedProjectKeys, + toggleProjectWorkspacesExpanded, activeWorkspaceSelection, handleWorktreeCreated, manualSort, diff --git a/packages/app/src/components/sidebar/sidebar-status-list.tsx b/packages/app/src/components/sidebar/sidebar-status-list.tsx index 459ae3cfb3..ddc83d3cca 100644 --- a/packages/app/src/components/sidebar/sidebar-status-list.tsx +++ b/packages/app/src/components/sidebar/sidebar-status-list.tsx @@ -155,13 +155,20 @@ export function SidebarStatusWorkspaceList({ const togglePinnedCollapsed = useSidebarCollapsedSectionsStore( (state) => state.togglePinnedCollapsed, ); + const [pinnedWorkspacesExpanded, setPinnedWorkspacesExpanded] = useState(false); + const togglePinnedWorkspacesExpanded = useCallback( + () => setPinnedWorkspacesExpanded((current) => !current), + [], + ); const { leadingItem: leadingPinnedWorkspace, visibleItems: visiblePinnedWorkspaces, - expanded: pinnedWorkspacesExpanded, canToggle: canTogglePinnedWorkspaces, - toggleExpanded: togglePinnedWorkspacesExpanded, - } = useLimitedSidebarGroup({ items: pinnedWorkspaces, selection: activeWorkspaceSelection }); + } = useLimitedSidebarGroup({ + items: pinnedWorkspaces, + selection: activeWorkspaceSelection, + expanded: pinnedWorkspacesExpanded, + }); const statusShortcutIndex = showShortcutBadges ? shortcutIndexByWorkspaceKey @@ -366,15 +373,19 @@ function StatusGroupRows({ onToggleWorkspacePin: ToggleSidebarWorkspacePin; }) { const activeWorkspaceSelection = useActiveWorkspaceSelection(); + const [workspacesExpanded, setWorkspacesExpanded] = useState(false); + const toggleWorkspacesExpanded = useCallback( + () => setWorkspacesExpanded((current) => !current), + [], + ); const { leadingItem: leadingWorkspace, visibleItems: visibleWorkspaces, - expanded: workspacesExpanded, canToggle: canToggleWorkspaces, - toggleExpanded: toggleWorkspacesExpanded, } = useLimitedSidebarGroup({ items: group.rows, selection: activeWorkspaceSelection, + expanded: workspacesExpanded, policy: STATUS_GROUP_VISIBILITY, }); diff --git a/packages/app/src/components/sidebar/use-limited-sidebar-group.ts b/packages/app/src/components/sidebar/use-limited-sidebar-group.ts index c7b77bfc16..e82f1e022f 100644 --- a/packages/app/src/components/sidebar/use-limited-sidebar-group.ts +++ b/packages/app/src/components/sidebar/use-limited-sidebar-group.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from "react"; +import { useMemo } from "react"; import { selectSidebarGroupVisibility, type SidebarGroupItem, @@ -12,23 +12,22 @@ const PINNED_POLICY = { kind: "pinned" } as const; interface LimitedSidebarGroupInput { items: readonly T[]; selection: ActiveWorkspaceSelection | null; + /** + * Whether the user revealed the whole group. The caller owns it: a native drop remounts the + * rows it moved, and a reveal held inside a row would reset with them. + */ + expanded: boolean; policy?: SidebarGroupVisibilityPolicy; } export function useLimitedSidebarGroup({ items, selection, + expanded, policy = PINNED_POLICY, -}: LimitedSidebarGroupInput): SidebarGroupVisibility & { - expanded: boolean; - toggleExpanded: () => void; -} { - const [expanded, setExpanded] = useState(false); - const visibility = useMemo( +}: LimitedSidebarGroupInput): SidebarGroupVisibility { + return useMemo( () => selectSidebarGroupVisibility({ items, expanded, policy, selection }), [expanded, items, policy, selection], ); - const toggleExpanded = useCallback(() => setExpanded((current) => !current), []); - - return { ...visibility, expanded, toggleExpanded }; } diff --git a/patches/react-native-draggable-flatlist+4.0.3.patch b/patches/react-native-draggable-flatlist+4.0.3.patch index ddbdb92224..e22f549c47 100644 --- a/patches/react-native-draggable-flatlist+4.0.3.patch +++ b/patches/react-native-draggable-flatlist+4.0.3.patch @@ -57,8 +57,124 @@ index 2abb4a2..8ca967f 100644 outerScrollOffset?: Animated.SharedValue; onAnimValInit?: (animVals: ReturnType) => void; itemEnteringAnimation?: AnimateProps["entering"]; +diff --git a/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx b/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx +index e4e861a..f485139 100644 +--- a/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx ++++ b/node_modules/react-native-draggable-flatlist/src/components/CellRendererComponent.tsx +@@ -8,6 +8,7 @@ import { + } from "react-native"; + import Animated, { + runOnUI, ++ SharedValue, + useAnimatedStyle, + useSharedValue, + } from "react-native-reanimated"; +@@ -40,12 +41,12 @@ function CellRendererComponent(props: Props) { + keyExtractor, + horizontal, + layoutAnimationDisabled, ++ transformHostKeys, + } = useDraggableFlatListContext(); + + const key = keyExtractor(item, index); + const offset = useSharedValue(-1); + const size = useSharedValue(-1); +- const heldTanslate = useSharedValue(0); + + const translate = useCellTranslate({ + cellOffset: offset, +@@ -55,20 +56,6 @@ function CellRendererComponent(props: Props) { + + const isActive = activeKey === key; + +- const animStyle = useAnimatedStyle(() => { +- // When activeKey becomes null at the end of a drag and the list reorders, +- // the animated style may apply before the next paint, causing a flicker. +- // Solution is to hold over the last animated value until the next onLayout. +- // (Not required in web) +- if (translate.value && !isWeb) { +- heldTanslate.value = translate.value; +- } +- const t = activeKey ? translate.value : heldTanslate.value; +- return { +- transform: [horizontalAnim.value ? { translateX: t } : { translateY: t }], +- }; +- }, [translate, activeKey]); +- + const updateCellMeasurements = useStableCallback(() => { + const onSuccess: MeasureLayoutOnSuccessCallback = (x, y, w, h) => { + if (isWeb && horizontal) x += scrollOffset.value; +@@ -99,7 +86,6 @@ function CellRendererComponent(props: Props) { + }); + + const onCellLayout = useStableCallback((e?: LayoutChangeEvent) => { +- heldTanslate.value = 0; + updateCellMeasurements(); + if (onLayout && e) onLayout(e); + }); +@@ -162,14 +148,58 @@ function CellRendererComponent(props: Props) { + ? itemLayoutAnimation + : undefined + } +- style={[props.style, baseStyle, animStyle]} ++ style={[props.style, baseStyle]} + pointerEvents={activeKey ? "none" : "auto"} + > +- {children} ++ ++ {children} ++ + + ); + } + ++// Owns the cell's drag translate. The list remounts it, with the cell's whole subtree, when a ++// drop moves the cell: the reorder commit then paints the new slot with no translate, because a ++// new view has no last animated transform for Reanimated to re-apply. ++function CellTransformHost({ ++ translate, ++ dragging, ++ horizontal, ++ children, ++}: { ++ translate: SharedValue; ++ dragging: boolean; ++ horizontal: boolean; ++ children: React.ReactNode; ++}) { ++ const { horizontalAnim } = useAnimatedValues(); ++ const animStyle = useAnimatedStyle(() => { ++ const t = dragging ? translate.value : 0; ++ return { ++ transform: [horizontalAnim.value ? { translateX: t } : { translateY: t }], ++ }; ++ }, [translate, dragging]); ++ ++ return ( ++ ++ {children} ++ ++ ); ++} ++ ++const styles = { ++ row: { flexDirection: "row" as const }, ++ column: { flexDirection: "column" as const }, ++}; ++ + export default typedMemo(CellRendererComponent); + + declare global { diff --git a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx -index 7c88afc..a74140f 100644 +index 7c88afc..ad75714 100644 --- a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx +++ b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx @@ -16,9 +16,11 @@ import { @@ -88,13 +204,26 @@ index 7c88afc..a74140f 100644 + sessionId: number; + index: number; + } | null>(null); - + const { dragHitSlop = DEFAULT_PROPS.dragHitSlop, -@@ -144,19 +157,88 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -100,6 +113,12 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + } = props; + + let [activeKey, setActiveKey] = useState(null); ++ // Reanimated re-applies a view's last animated transform to every React commit, so a moved ++ // cell would paint once at its new slot plus its old drag translate. The drop gives each ++ // moved cell a new transform host instead: a fresh view has no animated props to re-apply. ++ const [transformHostKeys, setTransformHostKeys] = useState< ++ ReadonlyMap ++ >(() => new Map()); + const [layoutAnimationDisabled, setLayoutAnimationDisabled] = useState( + !propsRef.current.enableLayoutAnimationExperimental + ); +@@ -144,19 +163,88 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { }); }, [props.data, keyExtractor, keyToIndexRef]); - + + const onDragCancel = useStableCallback((sessionId: number, index: number) => { + if (activeDragRef.current?.sessionId !== sessionId) return; + activeDragRef.current = null; @@ -168,7 +297,7 @@ index 7c88afc..a74140f 100644 - activeCellOffset.value = cellData.measurements.offset; - activeCellSize.value = cellData.measurements.size; - } - + const { onDragBegin } = propsRef.current; if (index !== undefined) { - spacerIndexAnim.value = index; @@ -187,10 +316,10 @@ index 7c88afc..a74140f 100644 setActiveKey(activeKey); onDragBegin?.(index); } -@@ -218,8 +300,25 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -218,14 +306,46 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { props.onRelease?.(index); }); - + + const finalizeCancelledDrag = () => { + "worklet"; + const activeIndex = activeIndexAnim.value; @@ -212,12 +341,33 @@ index 7c88afc..a74140f 100644 + if (activeDragRef.current?.sessionId !== sessionId) return; + activeDragRef.current = null; const { onDragEnd, data } = props; - + const newData = [...data]; -@@ -238,26 +337,6 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + if (from !== to) { + newData.splice(from, 1); + newData.splice(to, 0, data[from]); ++ const movedKeys = data ++ .slice(Math.min(from, to), Math.max(from, to) + 1) ++ .map((item, offset) => keyExtractor(item, Math.min(from, to) + offset)); ++ setTransformHostKeys((previous) => { ++ const next = new Map(); ++ data.forEach((item, index) => { ++ const itemKey = keyExtractor(item, index); ++ const hostKey = previous.get(itemKey); ++ if (hostKey !== undefined) next.set(itemKey, hostKey); ++ }); ++ for (const movedKey of movedKeys) { ++ next.set(movedKey, (previous.get(movedKey) ?? 0) + 1); ++ } ++ return next; ++ }); + } + + onDragEnd?.({ from, to, data: newData }); +@@ -238,26 +358,6 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { props.onPlaceholderIndexChange?.(index); }); - + - // Handle case where user ends drag without moving their finger. - useAnimatedReaction( - () => { @@ -241,15 +391,15 @@ index 7c88afc..a74140f 100644 useAnimatedReaction( () => { return spacerIndexAnim.value; -@@ -271,11 +350,24 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -271,11 +371,24 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { ); - + const gestureDisabled = useSharedValue(false); + const touchStartX = useSharedValue(0); + const touchStartY = useSharedValue(0); + const manualPanActivated = useSharedValue(false); + const coordinatesDragWithExternalGesture = Boolean(props.simultaneousHandlers); - + - const panGesture = Gesture.Pan() + let panGesture = Gesture.Pan() .onBegin((evt) => { @@ -267,7 +417,7 @@ index 7c88afc..a74140f 100644 panGestureState.value = evt.state; }) .onUpdate((evt) => { -@@ -286,8 +378,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -286,8 +399,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { : evt.translationY; touchTranslate.value = translation; }) @@ -284,15 +434,15 @@ index 7c88afc..a74140f 100644 // Set touch val to current translate val isTouchActiveNative.value = false; const translation = horizontalAnim.value -@@ -299,6 +398,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { - +@@ -299,6 +419,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + // Only call onDragEnd if actually dragging a cell if (activeIndexAnim.value === -1 || disabled.value) return; + terminalHandled.value = true; disabled.value = true; runOnJS(onRelease)(activeIndexAnim.value); const springTo = placeholderOffset.value - activeCellOffset.value; -@@ -309,22 +409,84 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -309,22 +430,84 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { runOnJS(onDragEnd)({ from: activeIndexAnim.value, to: spacerIndexAnim.value, @@ -371,7 +521,7 @@ index 7c88afc..a74140f 100644 + stateManager.fail(); + } }); - + if (dragHitSlop) panGesture.hitSlop(dragHitSlop); - if (activationDistanceProp) { + if (coordinatesDragWithExternalGesture) { @@ -380,7 +530,7 @@ index 7c88afc..a74140f 100644 const activeOffset = [-activationDistanceProp, activationDistanceProp]; if (props.horizontal) { panGesture.activeOffsetX(activeOffset); -@@ -332,6 +494,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -332,6 +515,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { panGesture.activeOffsetY(activeOffset); } } @@ -399,12 +549,14 @@ index 7c88afc..a74140f 100644 + props.dragGestureHostPresented === false + ? Gesture.Simultaneous(panGesture, Gesture.Manual().enabled(false)) + : panGesture; - + const onScroll = useStableCallback((scrollOffset: number) => { props.onScrollOffsetChange?.(scrollOffset); -@@ -373,8 +550,9 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -372,9 +570,11 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + keyExtractor={keyExtractor} horizontal={!!props.horizontal} layoutAnimationDisabled={layoutAnimationDisabled} ++ transformHostKeys={transformHostKeys} > - + @@ -426,17 +578,17 @@ index 1559352..33eb5de 100644 useSharedValue, @@ -48,7 +48,7 @@ function NestableDraggableFlatListInner( }); - + const onListContainerLayout = useStableCallback(async ({ containerRef }) => { - const nodeHandle = findNodeHandle(scrollableRef.current); + const nodeHandle = scrollableRef.current; - + const onSuccess = (_x: number, y: number) => { listVerticalOffset.value = y; @@ -74,6 +74,10 @@ function NestableDraggableFlatListInner( } ); - + + const onDragTerminate = useStableCallback(() => { + setOuterScrollEnabled(true); + }); @@ -452,6 +604,37 @@ index 1559352..33eb5de 100644 onAnimValInit={onAnimValInit} /> ); +diff --git a/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx b/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx +index 75f7db7..e99faf3 100644 +--- a/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx ++++ b/node_modules/react-native-draggable-flatlist/src/context/draggableFlatListContext.tsx +@@ -5,6 +5,7 @@ type Props = { + keyExtractor: (item: T, index: number) => string; + horizontal: boolean; + layoutAnimationDisabled: boolean; ++ transformHostKeys: ReadonlyMap; + children: React.ReactNode; + }; + +@@ -19,6 +20,7 @@ export default function DraggableFlatListProvider({ + keyExtractor, + horizontal, + layoutAnimationDisabled, ++ transformHostKeys, + children, + }: Props) { + const value = useMemo( +@@ -27,8 +29,9 @@ export default function DraggableFlatListProvider({ + keyExtractor, + horizontal, + layoutAnimationDisabled, ++ transformHostKeys, + }), +- [activeKey, keyExtractor, horizontal, layoutAnimationDisabled] ++ [activeKey, keyExtractor, horizontal, layoutAnimationDisabled, transformHostKeys] + ); + + return ( diff --git a/node_modules/react-native-draggable-flatlist/src/types.ts b/node_modules/react-native-draggable-flatlist/src/types.ts index d6755c8..1b244a6 100644 --- a/node_modules/react-native-draggable-flatlist/src/types.ts diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index b67cd113aa..b8321013ff 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -48,6 +48,10 @@ const patchedPackages = [ nodeModulesPath: "node_modules/@legendapp/list", patchPrefix: "@legendapp+list+", }, + // Native sidebar lists. Besides gesture sessions and panel-gesture arbitration, the drop gives + // each moved cell a fresh transform host. Reanimated re-applies a view's last animated + // transform to every React commit, so a reused host painted one frame of new order plus old + // drag translate (upstream computerjazz/react-native-draggable-flatlist#621, open). { nodeModulesPath: "node_modules/react-native-draggable-flatlist", patchPrefix: "react-native-draggable-flatlist+", From 42c7b7f886ff1395d4d292838daaca9ca929cbda Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 14 Nov 2026 21:13:11 +0700 Subject: [PATCH 052/160] fix(app): show the Android ripple on sidebar row presses (#9678) * fix(app): show the Android ripple on sidebar row presses PressHighlight owns pressed feedback. Callers pass the pressed fill as highlightStyle and stop painting it themselves. iOS and web paint the fill; Android draws the platform ripple, clipped to the row's corners, after Android's 100 ms tap timeout. Rows that knock content out of the surface follow the fill through onHighlightChange instead of tracking press state themselves. Defaults borderWidth to 0 under clipped ripples: React Native 0.86 sends NaN when a style drops borderWidth, and an overflow-hidden view then stops painting (fixed upstream in facebook/react-native#57789). * fix(app): let PressHighlight own file header press feedback Changes-tree rows on Android painted their old flat pressed fill under the new ripple. Lock the Android row's caller border and press handlers in a test. * fix(app): skip the sidebar row press fill while renaming On web the row's pressable stays the responder for clicks inside the inline rename field, so it painted the pressed fill while the title was being edited. Drop highlightStyle while editing, as the press handlers already are. * fix(app): keep a press's fill and its report on the same edges usePressFill painted from the live pressed state but reported only at press-in and press-out, so the row fill and the badge ring could disagree when highlightStyle appeared or went away mid-press. A press now keeps the fill it started with; the paint and the report both come from that one state. --- docs/design.md | 2 +- .../src/components/settings/row-header.tsx | 6 +- .../src/components/sidebar-workspace-list.tsx | 64 ++----- .../sidebar/sidebar-group-toggle-row.tsx | 2 +- .../sidebar/sidebar-row-backdrop.ts | 7 +- .../sidebar/sidebar-status-list.tsx | 43 +---- .../app/src/components/ui/context-menu.tsx | 5 +- .../components/ui/press-highlight.android.tsx | 87 +++++++++ .../ui/press-highlight.browser.test.tsx | 177 +++++++++++++++--- .../src/components/ui/press-highlight.fill.ts | 60 ++++++ .../components/ui/press-highlight.native.tsx | 34 ++-- .../app/src/components/ui/press-highlight.tsx | 6 +- .../components/ui/press-highlight.types.ts | 11 +- packages/app/src/git/file-header.tsx | 26 +-- .../settings/voice/speech-provider-sheet.tsx | 5 +- packages/app/src/usage/sidebar-item.tsx | 5 +- 16 files changed, 385 insertions(+), 155 deletions(-) create mode 100644 packages/app/src/components/ui/press-highlight.android.tsx create mode 100644 packages/app/src/components/ui/press-highlight.fill.ts diff --git a/docs/design.md b/docs/design.md index 57b3a7c9e1..c9b1a9842a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -20,7 +20,7 @@ A semantic element used in three or more places is a primitive. One of a kind is Primitives live in `packages/app/src/components/ui/` and `packages/app/src/components/headers/`. Card and row layout live in `packages/app/src/styles/settings.ts`. Section structure lives in `packages/app/src/screens/settings/settings-section.tsx`. -A pressable styled to look like a button is wrong; the button is ` + ), }), [logs.isFetching, plugin, refresh, t], diff --git a/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx b/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx index 7b93f84746..9b3fa10c49 100644 --- a/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx +++ b/packages/app/src/screens/workspace/sheet-pane/sheet-pane.tsx @@ -94,7 +94,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee actions: sheet.policy.openAsTab ? ( diff --git a/packages/app/src/tool-calls/detail-level/overview/sheet.tsx b/packages/app/src/tool-calls/detail-level/overview/sheet.tsx index 2888f1f424..c42b7de513 100644 --- a/packages/app/src/tool-calls/detail-level/overview/sheet.tsx +++ b/packages/app/src/tool-calls/detail-level/overview/sheet.tsx @@ -1,16 +1,16 @@ -import { useCallback, useEffect, useRef, type ReactNode } from "react"; -import { Pressable, Text, View } from "react-native"; +import { useCallback, useEffect, useMemo, useRef, type ReactNode } from "react"; +import { View } from "react-native"; import { BottomSheetScrollView, type BottomSheetScrollViewMethods } from "@gorhom/bottom-sheet"; -import { Wrench, X } from "lucide-react-native"; +import { Wrench } from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { useTranslation } from "react-i18next"; import { type ContextBridge, useIsolatedBottomSheetVisibility, } from "@/components/ui/isolated-bottom-sheet-modal"; +import { SheetHeaderView, type SheetHeader } from "@/components/adaptive-modal-sheet"; import { ToolCallSheetModal, useToolCallSheetContextBridge } from "@/components/tool-call-sheet"; import { useToolCallExpansionContextBridge } from "@/tool-calls/expansion-context"; -import type { Theme } from "@/styles/theme"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; interface OverviewToolCallGroupSheetProps { visible: boolean; @@ -21,9 +21,8 @@ interface OverviewToolCallGroupSheetProps { const SNAP_POINTS = ["60%", "95%"]; const ThemedWrench = withUnistyles(Wrench); -const ThemedX = withUnistyles(X); const foregroundMapping = (theme: Theme) => ({ color: theme.colors.foreground }); -const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const headerIcon = ; export function OverviewToolCallGroupSheet({ visible, @@ -31,7 +30,6 @@ export function OverviewToolCallGroupSheet({ children, onClose, }: OverviewToolCallGroupSheetProps) { - const { t } = useTranslation(); const scrollRef = useRef(null); const sheetContextBridge = useToolCallSheetContextBridge(); const expansionContextBridge = useToolCallExpansionContextBridge(); @@ -39,6 +37,10 @@ export function OverviewToolCallGroupSheet({ (content) => sheetContextBridge(expansionContextBridge(content)), [expansionContextBridge, sheetContextBridge], ); + const header = useMemo( + () => ({ title: summary, titleTestID: "tool-call-group-sheet-summary", leading: headerIcon }), + [summary], + ); const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({ visible, onClose, @@ -68,27 +70,11 @@ export function OverviewToolCallGroupSheet({ enablePanDownToClose > - - - - - {summary} - - - - - - + {children} @@ -102,30 +88,6 @@ const styles = StyleSheet.create((theme) => ({ flex: 1, backgroundColor: theme.colors.surface2, }, - header: { - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[3], - borderBottomWidth: theme.borderWidth[1], - borderBottomColor: theme.colors.border, - }, - headerLeft: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - flex: 1, - }, - headerTitle: { - fontSize: theme.fontSize.base, - fontWeight: theme.fontWeight.medium, - color: theme.colors.foreground, - flex: 1, - }, - closeButton: { - padding: theme.spacing[2], - }, content: { flex: 1, minHeight: 0, diff --git a/packages/app/src/usage/agent-usage.tsx b/packages/app/src/usage/agent-usage.tsx index bf10054db6..98f1c9bf82 100644 --- a/packages/app/src/usage/agent-usage.tsx +++ b/packages/app/src/usage/agent-usage.tsx @@ -1,3 +1,4 @@ +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { Text, View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; @@ -8,7 +9,7 @@ import type { UsageReportEntry } from "./types"; /** * The usage of the account an agent runs under, for its context window details: one card per - * report as it streams in, without pins. Nothing on hosts that cannot report usage, or for an + * report in the user's card order, without pins. Nothing on hosts that cannot report usage, or for an * agent with no account to report. */ export function AgentUsage({ @@ -55,7 +56,8 @@ function AgentUsageCards({ refreshable: boolean; }) { const { display } = useUsageDisplay(reports); - return reports.map((entry) => ( + const arranged = useMemo(() => display.arrange(reports), [display, reports]); + return arranged.map((entry) => ( void; + /** The handle is always there; it shows while the card is hovered or where there is no hover. */ + handleVisible: boolean; +} const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); export function UsageCard({ @@ -41,6 +53,7 @@ export function UsageCard({ display, pinnable, refreshable, + arrangement, compact = false, }: { serverId: string; @@ -51,6 +64,8 @@ export function UsageCard({ pinnable: boolean; /** Whether the header has a Refresh button. Without one the freshness shows on the card. */ refreshable: boolean; + /** Present where the user arranges cards. An off card collapses to its header. */ + arrangement?: UsageCardArrangement; compact?: boolean; }) { const { t } = useTranslation(); @@ -60,9 +75,9 @@ export function UsageCard({ const showsFreshnessInline = isNative || isCompact || !refreshable; const usage = entry.report; const status = statusText(usage, t); - const footer = entry.account.label ?? null; - const { windows, balances, details, planLabel, successfulAt, retained, messages } = - resolveUsageReport(entry, t); + const collapsed = arrangement?.on === false; + const report = resolveUsageReport(entry, t); + const { planLabel, successfulAt, retained } = report; const containerStyle = useMemo( () => [styles.container, compact ? styles.containerCompact : styles.containerPadded], @@ -79,20 +94,34 @@ export function UsageCard({ return ( - + + {arrangement ? ( + + ) : null} {entry.sourceLabel} - {planLabel ? : null} + {collapsed && entry.account.label ? ( + // The body that names the account is gone, and two off cards of one source must differ. + + {entry.account.label} + + ) : null} + {planLabel && !collapsed ? ( + + ) : null} - {status ? ( + {status && !collapsed ? ( {status} ) : null} - {refreshable ? ( + {refreshable && !collapsed ? ( ) : null} + {arrangement ? ( + + + + ) : null} + {collapsed ? null : ( + + )} + + ); +} + +function UsageCardBody({ + entry, + display, + pinnable, + report, + showsFreshnessInline, + refreshState, +}: { + entry: UsageReportEntry; + display: UsageDisplay; + pinnable: boolean; + report: ReturnType; + showsFreshnessInline: boolean; + refreshState: UsageRefresh; +}) { + const { t } = useTranslation(); + const { windows, balances, details, retained, successfulAt, messages } = report; + const footer = entry.account.label ?? null; + return ( + <> {messages.length > 0 ? ( {messages.join("\n")} @@ -164,7 +240,24 @@ export function UsageCard({ {t("providerUsage.refreshFailed")} ) : null} - + + ); +} + +/** + * Drags the card. It hangs in the card's left padding, so the logo, name and body share one rail + * and revealing it on hover moves nothing. + */ +function UsageCardDragHandle({ name, visible }: { name: string; visible: boolean }) { + const { t } = useTranslation(); + return ( + + + ); } @@ -279,6 +372,21 @@ function UsageFreshness({ ); } +const DRAG_GRIP_SIZE = 14; + +// The handle fills the card's left padding beside the header. +function dragHandleSlot(spacing: { 4: number }) { + return { + position: "absolute", + left: 0, + width: spacing[4], + top: 0, + bottom: 0, + alignItems: "center", + justifyContent: "center", + } as const; +} + // The Refresh glyph lands on the card's right rail and the header keeps its text height; // the button's larger hitbox overhangs both instead of pushing them. function iconHitboxOverhang(compact: boolean) { @@ -305,11 +413,28 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", gap: theme.spacing[2], }, + // The row reaches into the card's left padding and above and below its text, so the handle + // there is inside it: Android delivers no touches to a child where it overflows its parent. + headerWithHandle: { + position: "relative", + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + marginLeft: -theme.spacing[4], + paddingLeft: theme.spacing[4], + marginVertical: -theme.spacing[2], + paddingVertical: theme.spacing[2], + }, name: { flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.base, }, + collapsedAccount: { + flexShrink: 1, + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, headerSpacer: { flex: 1, }, @@ -379,6 +504,12 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm, }, + dragHandle: dragHandleSlot(theme.spacing), + dragHandleHidden: { ...dragHandleSlot(theme.spacing), opacity: 0 }, + // The switch's reserved control height overhangs the header like the Refresh button's hitbox. + cardSwitch: { + marginVertical: -theme.spacing[2], + }, refreshButton: iconHitboxOverhang(false), refreshButtonCompact: iconHitboxOverhang(true), })); diff --git a/packages/app/src/usage/cards.test.ts b/packages/app/src/usage/cards.test.ts new file mode 100644 index 0000000000..86e62b3d21 --- /dev/null +++ b/packages/app/src/usage/cards.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from "vitest"; +import { + arrangeUsageCards, + arrangeUsageReports, + DEFAULT_USAGE_PREFERENCES, + setUsageCardOn, + UsagePreferencesSchema, + usageReportsOn, + type UsagePreferences, +} from "./preferences"; +import { resolvePinnedUsage } from "./pinned"; +import type { UsageReportEntry } from "./types"; + +function report(sourceId: string, sourceLabel: string, account?: string): UsageReportEntry { + return { + id: `${sourceId}:${account ?? "default"}`, + sourceId, + sourceLabel, + account: account ? { label: account } : {}, + fetchedAt: "2026-01-01T00:00:00.000Z", + report: { + status: "available", + windows: [{ id: "weekly", label: "Weekly", summary: true, usedPct: 40 }], + }, + }; +} + +const codex = report("codex", "Codex"); +const claudeWork = report("claude", "Claude", "work"); +const claudePersonal = report("claude", "Claude", "personal"); +const copilot = report("copilot", "Copilot"); +const gemini = report("gemini", "Gemini"); + +function ids(reports: readonly UsageReportEntry[]): string[] { + return reports.map((entry) => entry.id); +} + +function arranged(cardOrder: string[]): UsagePreferences { + return { ...DEFAULT_USAGE_PREFERENCES, cardOrder }; +} + +describe("usage card order", () => { + it("shows cards by provider, then account, whatever order they arrive in", () => { + const expected = ["claude:personal", "claude:work", "codex:default", "copilot:default"]; + for (const arrival of [ + [codex, claudeWork, copilot, claudePersonal], + [copilot, claudePersonal, codex, claudeWork], + ]) { + expect(ids(arrangeUsageReports(arrival, DEFAULT_USAGE_PREFERENCES))).toEqual(expected); + } + }); + + it("puts the cards the user arranged first, in their order", () => { + const preferences = arranged(["copilot:default", "claude:work"]); + + expect( + ids(arrangeUsageReports([claudeWork, codex, claudePersonal, copilot], preferences)), + ).toEqual(["copilot:default", "claude:work", "claude:personal", "codex:default"]); + }); + + it("lands a report from a new login in its default slot after the arranged cards", () => { + const preferences = arrangeUsageCards(DEFAULT_USAGE_PREFERENCES, { + moved: "codex:default", + after: ["codex:default", "claude:work"], + }); + const newLogin = report("claude", "Claude", "agent"); + + expect(ids(arrangeUsageReports([newLogin, claudeWork, codex], preferences))).toEqual([ + "codex:default", + "claude:work", + "claude:agent", + ]); + }); + + it("keeps another host's arrangement when a drop on this host moves a card both show", () => { + // Host A shows Codex, Claude and Gemini; host B shows Copilot and the same Claude account. + const hostA = [codex, claudeWork, gemini]; + const hostB = [claudeWork, copilot]; + const arrangedOnA = arrangeUsageCards(DEFAULT_USAGE_PREFERENCES, { + moved: "codex:default", + after: ["codex:default", "claude:work", "gemini:default"], + }); + + const after = ["copilot:default", "claude:work"]; + const arrangedOnB = arrangeUsageCards(arrangedOnA, { moved: "copilot:default", after }); + + expect(ids(arrangeUsageReports(hostA, arrangedOnB))).toEqual([ + "codex:default", + "claude:work", + "gemini:default", + ]); + expect(ids(arrangeUsageReports(hostB, arrangedOnB))).toEqual(after); + }); + + it("moves only the dragged card when it swaps with its neighbour", () => { + // Gemini sits between Codex and Copilot, but only another host shows it. + const preferences = arranged(["codex:default", "gemini:default", "copilot:default"]); + const swapped = arrangeUsageCards(preferences, { + moved: "codex:default", + after: ["copilot:default", "codex:default"], + }); + + expect(ids(arrangeUsageReports([codex, copilot], swapped))).toEqual([ + "copilot:default", + "codex:default", + ]); + expect(ids(arrangeUsageReports([gemini, copilot], swapped))).toEqual([ + "gemini:default", + "copilot:default", + ]); + }); +}); + +describe("usage cards turned off", () => { + it("turns a card off and back on", () => { + const off = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, "codex:default", false); + expect(off.cardsOff).toEqual(["codex:default"]); + expect(setUsageCardOn(off, "codex:default", true).cardsOff).toEqual([]); + }); + + it("leaves off cards out of the sidebar summary", () => { + const preferences = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, "codex:default", false); + + expect(ids(usageReportsOn([codex, claudeWork], preferences))).toEqual(["claude:work"]); + expect( + resolvePinnedUsage([codex, claudeWork], preferences).map((source) => source.key), + ).toEqual(["claude:work"]); + }); + + it("orders the sidebar summary like the cards", () => { + const preferences = arranged(["codex:default"]); + + expect( + resolvePinnedUsage([claudeWork, codex], preferences).map((source) => source.key), + ).toEqual(["codex:default", "claude:work"]); + }); +}); + +describe("stored card preferences", () => { + it("reads settings saved before cards could be arranged as no arrangement", () => { + expect(UsagePreferencesSchema.parse({ displayAs: "used", serverId: null })).toEqual( + DEFAULT_USAGE_PREFERENCES, + ); + }); + + it("survives a save and reload, and ignores a malformed arrangement", () => { + const saved = setUsageCardOn(arranged(["codex:default"]), "claude:work", false); + expect(UsagePreferencesSchema.parse(JSON.parse(JSON.stringify(saved)))).toEqual(saved); + expect( + UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardsOff: [1] }), + ).toEqual(DEFAULT_USAGE_PREFERENCES); + }); +}); diff --git a/packages/app/src/usage/controls.tsx b/packages/app/src/usage/controls.tsx index f0a8c73f5e..ffe51271e6 100644 --- a/packages/app/src/usage/controls.tsx +++ b/packages/app/src/usage/controls.tsx @@ -16,47 +16,41 @@ export interface UsageHostSelection { } /** - * The controls on the right of every usage title row: the host filter when there is more than one - * host, Refresh all, and the Settings cog. A host that cannot report usage keeps only the host filter. + * The controls on the right of every usage title row: Refresh all and the Settings cog. A host + * that cannot report usage has none. */ export function UsageControls({ view, serverId, onRefresh, - hostSelection, }: { view: UsageView; serverId: string; onRefresh: () => void; - hostSelection?: UsageHostSelection; }) { const busy = view.kind === "loading" || (view.kind === "ready" && view.isRefreshing); + if (view.kind === "unavailable") return null; return ( - {hasHostChoice(hostSelection) ? ( - - ) : null} - {view.kind === "unavailable" ? null : ( - <> - {view.kind === "off" ? null : } - - - )} + {view.kind === "off" ? null : } + ); } -function hasHostChoice( - hostSelection: UsageHostSelection | undefined, -): hostSelection is UsageHostSelection { - return hostSelection !== undefined && hostSelection.hosts.length > 1; +/** The host whose usage shows, when there is more than one to choose from. */ +function UsageHostFilter({ hostSelection }: { hostSelection: UsageHostSelection }) { + return ( + + ); } function usageHostOptionTestID(serverId: string): string { @@ -73,27 +67,28 @@ const styles = StyleSheet.create((theme) => ({ })); /** - * One host’s usage and title-row controls for the Usage modal. - * Returns null when there is nothing to control, so headers leave no empty island. + * One host’s usage for the Usage modal: its title-row controls, null when there is nothing to + * control so the header leaves no empty island, and the host filter for the top of the body, null + * with a single host. */ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { view: UsageView; refresh: () => void; controls: ReactElement | null; + hostFilter: ReactElement | null; } { const { view, refresh } = useHostUsage(hostSelection.serverId); - const hasControls = hasHostChoice(hostSelection) || view.kind !== "unavailable"; const controls = useMemo( () => - hasControls ? ( - - ) : null, - [hasControls, hostSelection, refresh, view], + view.kind === "unavailable" ? null : ( + + ), + [hostSelection.serverId, refresh, view], ); - return { view, refresh, controls }; + const hostFilter = useMemo( + () => + hostSelection.hosts.length > 1 ? : null, + [hostSelection], + ); + return { view, refresh, controls, hostFilter }; } diff --git a/packages/app/src/usage/display.ts b/packages/app/src/usage/display.ts index c62ed78fd7..f54c168834 100644 --- a/packages/app/src/usage/display.ts +++ b/packages/app/src/usage/display.ts @@ -1,21 +1,32 @@ import { useCallback, useMemo } from "react"; import { useAppSettings } from "@/hooks/use-settings"; import { + arrangeUsageCards, + arrangeUsageReports, + isUsageCardOff, isUsagePinned, + setUsageCardOn, setUsageDisplayAs, toggleUsagePin, + type UsageCardDrop, type UsageDisplayAs, type UsagePin, type UsagePreferences, } from "./preferences"; import type { UsageReportEntry } from "./types"; -/** What usage views need from the preferences: how to read percents, and the pins. */ +/** What usage views need from the preferences: how to read percents, the pins, and the cards. */ export interface UsageDisplay { displayAs: UsageDisplayAs; setDisplayAs: (displayAs: UsageDisplayAs) => void; isPinned: (pin: UsagePin) => boolean; togglePin: (pin: UsagePin) => void; + /** Reports in the order their cards show. */ + arrange: (reports: readonly UsageReportEntry[]) => UsageReportEntry[]; + /** Saves the order of the shown cards after the user drops one. */ + arrangeCards: (drop: UsageCardDrop) => void; + isCardOn: (reportId: string) => boolean; + setCardOn: (reportId: string, on: boolean) => void; } interface UsagePreferencesState { @@ -41,14 +52,30 @@ export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePref }, [updateSettings, reports], ); + const arrangeCards = useCallback( + (drop: UsageCardDrop) => { + void updateSettings((current) => ({ usage: arrangeUsageCards(current.usage, drop) })); + }, + [updateSettings], + ); + const setCardOn = useCallback( + (reportId: string, on: boolean) => { + void updateSettings((current) => ({ usage: setUsageCardOn(current.usage, reportId, on) })); + }, + [updateSettings], + ); const display = useMemo( () => ({ displayAs: preferences.displayAs, setDisplayAs, isPinned: (pin) => isUsagePinned(preferences, pin, reports), togglePin, + arrange: (shown) => arrangeUsageReports(shown, preferences), + arrangeCards, + isCardOn: (reportId) => !isUsageCardOff(preferences, reportId), + setCardOn, }), - [preferences, reports, setDisplayAs, togglePin], + [arrangeCards, preferences, reports, setCardOn, setDisplayAs, togglePin], ); return { preferences, display }; } diff --git a/packages/app/src/usage/format.ts b/packages/app/src/usage/format.ts index 867976a586..16386810fa 100644 --- a/packages/app/src/usage/format.ts +++ b/packages/app/src/usage/format.ts @@ -2,7 +2,7 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; import { formatTimeOfDay } from "@/utils/time"; import type { UsageDisplayAs } from "./preferences"; -import type { UsageBalanceUnit } from "./types"; +import type { UsageBalanceUnit, UsageReportEntry } from "./types"; const providerUsageLabels = { session: { label: "Session", key: "providerUsage.labels.session" }, @@ -13,6 +13,11 @@ const providerUsageLabels = { monthly_credits: { label: "Monthly credits", key: "providerUsage.labels.monthlyCredits" }, } as const; +/** The source, with the account when the report names one: "Claude (work)". */ +export function formatUsageAccountName(entry: UsageReportEntry): string { + return entry.account.label ? `${entry.sourceLabel} (${entry.account.label})` : entry.sourceLabel; +} + export function formatProviderUsageLabel(id: string, label: string, t: TFunction = i18n.t): string { const reviewPrefix = "Code review · "; if (id.startsWith("code_review:") && label.startsWith(reviewPrefix)) { diff --git a/packages/app/src/usage/list.tsx b/packages/app/src/usage/list.tsx index 10e76ba57f..e9218ae326 100644 --- a/packages/app/src/usage/list.tsx +++ b/packages/app/src/usage/list.tsx @@ -1,12 +1,24 @@ +import { useCallback, useMemo, useState } from "react"; import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; +import { DraggableList } from "@/components/draggable-list"; +import type { DraggableRenderItemInfo } from "@/components/draggable-list.types"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { isNative } from "@/constants/platform"; import { settingsStyles } from "@/styles/settings"; import { UsageCard } from "./card"; import type { UsageDisplay } from "./display"; import { useUsageInSidebar } from "./in-sidebar"; import type { UsageReportEntry } from "./types"; -/** One card per report (source + account). Window rows pin while the sidebar summary is on. */ +function reportKey(entry: UsageReportEntry): string { + return entry.id; +} + +/** + * One card per report (source + account), in the user's order. Each card drags by its handle and + * turns off from its switch. Window rows pin while the sidebar summary is on. + */ export function UsageList({ serverId, reports, @@ -17,25 +29,113 @@ export function UsageList({ display: UsageDisplay; }) { const { inSidebar } = useUsageInSidebar(); + const { arrange, arrangeCards } = display; + const arranged = useMemo(() => arrange(reports), [arrange, reports]); + const handleDragEnd = useCallback( + (next: UsageReportEntry[], moved: string) => + arrangeCards({ moved, after: next.map(reportKey) }), + [arrangeCards], + ); + const renderItem = useCallback( + ({ item, isActive }: DraggableRenderItemInfo) => ( + + + + ), + [display, inSidebar, serverId], + ); return ( - - {reports.map((entry) => ( - - - - ))} + + ); +} + +/** + * The card inside its hover target: the drag handle shows while the pointer is over the card or + * keyboard focus is inside it, and always where there is no hover. + */ +function UsageListCard({ + serverId, + entry, + display, + pinnable, + dragging, +}: { + serverId: string; + entry: UsageReportEntry; + display: UsageDisplay; + pinnable: boolean; + dragging: boolean; +}) { + const isCompact = useIsCompactFormFactor(); + const [isHovered, setIsHovered] = useState(false); + const handlePointerEnter = useCallback(() => setIsHovered(true), []); + const handlePointerLeave = useCallback(() => setIsHovered(false), []); + // Focus events bubble from the card's controls, so tabbing onto the handle reveals it. + const [hasFocus, setHasFocus] = useState(false); + const handleFocus = useCallback(() => setHasFocus(true), []); + const handleBlur = useCallback(() => setHasFocus(false), []); + const { isCardOn, setCardOn } = display; + const on = isCardOn(entry.id); + const handleSetOn = useCallback( + (next: boolean) => setCardOn(entry.id, next), + [entry.id, setCardOn], + ); + const arrangement = useMemo( + () => ({ + on, + onSetOn: handleSetOn, + handleVisible: isHovered || hasFocus || dragging || isNative || isCompact, + }), + [dragging, handleSetOn, hasFocus, isCompact, isHovered, on], + ); + return ( + + + + ); } const styles = StyleSheet.create((theme) => ({ + // Each card carries the gap below it, so a native drag moves it with its slot; the list + // takes the last one back. list: { - gap: theme.spacing[3], + marginBottom: -theme.spacing[3], + }, + item: { + paddingBottom: theme.spacing[3], + }, + hoverTarget: { + position: "relative", }, })); diff --git a/packages/app/src/usage/options.tsx b/packages/app/src/usage/options.tsx index cc674cb90f..9e12517da5 100644 --- a/packages/app/src/usage/options.tsx +++ b/packages/app/src/usage/options.tsx @@ -3,8 +3,11 @@ import { View } from "react-native"; import { Settings } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu"; -import { extraMutedIconColorMapping } from "@/components/ui/icon-button-chrome"; -import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { + mutedIconColorMapping, + useIconButtonChromeGlyphSize, +} from "@/components/ui/icon-button-chrome"; +import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; import { useIsCompactFormFactor } from "@/constants/layout"; import { SettingsRow, SettingsSwitch } from "@/components/settings"; import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; @@ -32,6 +35,7 @@ export function UsageOptions({ serverId }: { serverId: string | null }) { }, ]; const compact = useIsCompactFormFactor(); + const glyphSize = useIconButtonChromeGlyphSize("small", compact); const { display } = useUsageDisplay([]); const { inSidebar, setInSidebar } = useUsageInSidebar(); return ( @@ -42,10 +46,7 @@ export function UsageOptions({ serverId }: { serverId: string | null }) { compact={compact} testID="usage-options-menu" > - + { @@ -114,7 +114,7 @@ describe("resolvePinnedUsage", () => { ]); }); - it("groups pinned windows by source in report order, not pin order", () => { + it("lists pinned windows in card order, not pin order", () => { const work = report({ sourceId: "claude", sourceLabel: "Claude", @@ -161,6 +161,28 @@ describe("resolvePinnedUsage", () => { }); }); + it("follows the arranged card order, even when it separates a source's accounts", () => { + const work = report({ + sourceId: "claude", + sourceLabel: "Claude", + account: "work", + windows: [{ id: "weekly", label: "Weekly", usedPct: 90 }], + }); + const sources = resolvePinnedUsage([claude, codex, work], { + ...preferences([ + { sourceId: "claude", windowId: "weekly" }, + { sourceId: "codex", windowId: "weekly" }, + ]), + cardOrder: ["claude:default", "codex:default", "claude:work"], + }); + + expect(sources.map((source) => source.key)).toEqual([ + "claude:default", + "codex:default", + "claude:work", + ]); + }); + it("names a window by its label when the source gives no short label", () => { const items = windows([codex], preferences([{ sourceId: "codex", windowId: "weekly" }])); diff --git a/packages/app/src/usage/pinned.ts b/packages/app/src/usage/pinned.ts index acce210a7c..b725c3e086 100644 --- a/packages/app/src/usage/pinned.ts +++ b/packages/app/src/usage/pinned.ts @@ -1,8 +1,13 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; -import { formatPct, formatDisplayPct, formatProviderUsageLabel } from "./format"; +import { + formatPct, + formatDisplayPct, + formatProviderUsageLabel, + formatUsageAccountName, +} from "./format"; import { displayPercent, resolveUsageSnapshot } from "./model"; -import { effectiveUsagePins, type UsagePreferences } from "./preferences"; +import { effectiveUsagePins, usageReportsOn, type UsagePreferences } from "./preferences"; import { windowTone } from "./tone"; import type { UsageReportEntry, UsageTone } from "./types"; @@ -55,19 +60,12 @@ export function choosePinnedUsageLayout(input: { } function describe(entry: UsageReportEntry, windowLabel: string): string { - const account = entry.account.label ? ` (${entry.account.label})` : ""; - return `${entry.sourceLabel}${account} ${windowLabel}`; -} - -/** Reports with every account of a source together, sources in the order they first appear. */ -function groupBySource(reports: readonly UsageReportEntry[]): UsageReportEntry[] { - const sourceIds = [...new Set(reports.map((entry) => entry.sourceId))]; - return sourceIds.flatMap((sourceId) => reports.filter((entry) => entry.sourceId === sourceId)); + return `${formatUsageAccountName(entry)} ${windowLabel}`; } /** - * The sidebar Usage item's summary: one group per account, grouped by source, each with its - * windows in its report's order. Accounts with nothing to show are left out. + * The sidebar Usage item's summary: one group per account in card order, each with its windows in + * its report's order. Accounts turned off or with nothing to show are left out. */ export function resolvePinnedUsage( reports: readonly UsageReportEntry[], @@ -75,7 +73,7 @@ export function resolvePinnedUsage( t: TFunction = i18n.t, ): PinnedUsageSource[] { const pins = effectiveUsagePins(preferences, reports); - return groupBySource(reports).flatMap((entry) => { + return usageReportsOn(reports, preferences).flatMap((entry) => { const snapshot = resolveUsageSnapshot(entry); if (!snapshot) return []; const windows = snapshot.report.windows diff --git a/packages/app/src/usage/preferences.test.ts b/packages/app/src/usage/preferences.test.ts index 43dccc466d..064920fb5e 100644 --- a/packages/app/src/usage/preferences.test.ts +++ b/packages/app/src/usage/preferences.test.ts @@ -31,7 +31,7 @@ describe("usage preferences", () => { it("unpins a pinned window and keeps the others in order", () => { const three = [codexWeekly, claudeFiveHour, { sourceId: "claude", windowId: "weekly" }]; const unpinned = toggleUsagePin({ - preferences: { displayAs: "used", pins: three, serverId: null }, + preferences: { ...DEFAULT_USAGE_PREFERENCES, pins: three }, pin: claudeFiveHour, reports: [], }); @@ -40,18 +40,18 @@ describe("usage preferences", () => { }); it("switches between used and remaining without touching pins", () => { - const preferences = { displayAs: "used" as const, pins: [codexWeekly], serverId: null }; + const preferences = { ...DEFAULT_USAGE_PREFERENCES, pins: [codexWeekly] }; expect(setUsageDisplayAs(preferences, "remaining")).toEqual({ + ...DEFAULT_USAGE_PREFERENCES, displayAs: "remaining", pins: [codexWeekly], - serverId: null, }); }); it("remembers the picked host without touching pins", () => { expect(setUsageHost({ ...DEFAULT_USAGE_PREFERENCES, pins: [codexWeekly] }, "server")).toEqual({ - displayAs: "used", + ...DEFAULT_USAGE_PREFERENCES, pins: [codexWeekly], serverId: "server", }); @@ -59,7 +59,7 @@ describe("usage preferences", () => { it("reads preferences saved before hosts could be picked as no pick", () => { expect(UsagePreferencesSchema.parse({ displayAs: "remaining", pinned: [codexWeekly] })).toEqual( - { displayAs: "remaining", pins: [codexWeekly], serverId: null }, + { ...DEFAULT_USAGE_PREFERENCES, displayAs: "remaining", pins: [codexWeekly] }, ); }); }); @@ -125,6 +125,6 @@ it("reads old selections without losing display or host and preserves an explici ] as const) { expect( UsagePreferencesSchema.parse({ displayAs: "remaining", serverId: "host", ...input }), - ).toEqual({ displayAs: "remaining", serverId: "host", pins }); + ).toEqual({ ...DEFAULT_USAGE_PREFERENCES, displayAs: "remaining", serverId: "host", pins }); } }); diff --git a/packages/app/src/usage/preferences.ts b/packages/app/src/usage/preferences.ts index b9c5c6fde9..7ad7d5a3e8 100644 --- a/packages/app/src/usage/preferences.ts +++ b/packages/app/src/usage/preferences.ts @@ -18,15 +18,22 @@ export interface UsagePreferences { pins: UsagePin[] | null; /** The host the user picked to show usage for; null until they pick one. */ serverId: string | null; + /** Report IDs the user arranged, in their order. Shared by every host. */ + cardOrder: string[]; + /** Report IDs the user turned off. Their cards collapse and leave the sidebar summary. */ + cardsOff: string[]; } export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = { displayAs: "used", pins: null, serverId: null, + cardOrder: [], + cardsOff: [], }; const pinsSchema = z.array(z.object({ sourceId: z.string(), windowId: z.string() })); +const reportIdsSchema = z.array(z.string()).optional().catch(undefined); export const UsagePreferencesSchema = z .object({ @@ -36,10 +43,18 @@ export const UsagePreferencesSchema = z // Old [] meant defaults. Read it only when the new selection is absent. pinned: pinsSchema.optional().catch([]), serverId: z.string().nullable().catch(null), + cardOrder: reportIdsSchema, + cardsOff: reportIdsSchema, }) - .transform(({ displayAs, pins, pinned, serverId }): UsagePreferences => { + .transform(({ displayAs, pins, pinned, serverId, cardOrder, cardsOff }): UsagePreferences => { const legacyPins = pinned && pinned.length > 0 ? pinned : null; - return { displayAs, pins: pins === undefined ? legacyPins : pins, serverId }; + return { + displayAs, + pins: pins === undefined ? legacyPins : pins, + serverId, + cardOrder: cardOrder ?? [], + cardsOff: cardsOff ?? [], + }; }) .catch(DEFAULT_USAGE_PREFERENCES); @@ -104,3 +119,84 @@ export function setUsageDisplayAs( export function setUsageHost(preferences: UsagePreferences, serverId: string): UsagePreferences { return { ...preferences, serverId }; } + +/** Reports the user has not arranged: by provider, then account, then ID. */ +function compareByDefaultOrder(a: UsageReportEntry, b: UsageReportEntry): number { + return ( + a.sourceLabel.localeCompare(b.sourceLabel) || + (a.account.label ?? "").localeCompare(b.account.label ?? "") || + a.id.localeCompare(b.id) + ); +} + +/** + * Reports in the order their cards show: the ones the user arranged first, in their order, then + * the rest in the default order. Arrival order never matters, so a report that streams in late or + * appears for a new login lands in its own slot. + */ +export function arrangeUsageReports( + reports: readonly UsageReportEntry[], + preferences: UsagePreferences, +): UsageReportEntry[] { + const rank = new Map(preferences.cardOrder.map((id, index) => [id, index])); + return [...reports].sort((a, b) => { + const rankA = rank.get(a.id); + const rankB = rank.get(b.id); + if (rankA !== undefined && rankB !== undefined) return rankA - rankB; + if (rankA !== undefined) return -1; + if (rankB !== undefined) return 1; + return compareByDefaultOrder(a, b); + }); +} + +/** Reports whose cards are on, in card order: what the sidebar summary reads. */ +export function usageReportsOn( + reports: readonly UsageReportEntry[], + preferences: UsagePreferences, +): UsageReportEntry[] { + return arrangeUsageReports(reports, preferences).filter( + (entry) => !isUsageCardOff(preferences, entry.id), + ); +} + +/** A drop as the list reports it: the card the user moved and the shown cards' order after it. */ +export interface UsageCardDrop { + moved: string; + after: readonly string[]; +} + +/** + * The order after the user drops a card. Only the moved card changes place: it goes just before + * its new successor among the shown cards, or just after its new predecessor when it lands last. + * Shown cards not yet arranged are added at the end, in their shown order. Other arranged cards + * keep their places relative to each other. The order is shared by every host, so a drop that + * arranges a card another host also shows ranks it ahead of that host's unarranged cards. + */ +export function arrangeUsageCards( + preferences: UsagePreferences, + { moved, after }: UsageCardDrop, +): UsagePreferences { + const arranged = new Set([...preferences.cardOrder, moved]); + const rest = [ + ...preferences.cardOrder.filter((id) => id !== moved), + ...after.filter((id) => !arranged.has(id)), + ]; + const index = after.indexOf(moved); + const successor = after[index + 1]; + const at = successor === undefined ? rest.indexOf(after[index - 1]) + 1 : rest.indexOf(successor); + rest.splice(at, 0, moved); + return { ...preferences, cardOrder: rest }; +} + +export function isUsageCardOff(preferences: UsagePreferences, reportId: string): boolean { + return preferences.cardsOff.includes(reportId); +} + +export function setUsageCardOn( + preferences: UsagePreferences, + reportId: string, + on: boolean, +): UsagePreferences { + const others = preferences.cardsOff.filter((id) => id !== reportId); + return { ...preferences, cardsOff: on ? others : [...others, reportId] }; +} diff --git a/packages/app/src/usage/refresh-button.tsx b/packages/app/src/usage/refresh-button.tsx index 473e4442cc..80a31389e4 100644 --- a/packages/app/src/usage/refresh-button.tsx +++ b/packages/app/src/usage/refresh-button.tsx @@ -1,9 +1,12 @@ import { useTranslation } from "react-i18next"; import { RotateCw } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; -import { extraMutedIconColorMapping } from "@/components/ui/icon-button-chrome"; +import { + mutedIconColorMapping, + useIconButtonChromeGlyphSize, +} from "@/components/ui/icon-button-chrome"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; -import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; +import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; import { useIsCompactFormFactor } from "@/constants/layout"; const ThemedRotateCw = withUnistyles(RotateCw); @@ -16,7 +19,7 @@ const ThemedLoadingSpinner = withUnistyles(LoadingSpinner); export function UsageRefreshButton({ busy, onRefresh }: { busy: boolean; onRefresh: () => void }) { const { t } = useTranslation(); const compact = useIsCompactFormFactor(); - const iconSize = paneContentToolbarIconSize(compact); + const iconSize = useIconButtonChromeGlyphSize("small", compact); return ( {busy ? ( - + ) : ( - + )} ); diff --git a/packages/app/src/usage/usage-modal.tsx b/packages/app/src/usage/usage-modal.tsx index 4e049c0b58..f78b9ac3e4 100644 --- a/packages/app/src/usage/usage-modal.tsx +++ b/packages/app/src/usage/usage-modal.tsx @@ -17,8 +17,8 @@ interface UsageModalProps { /** * Usage over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. It - * shows the usage host's reports with pins, and the host filter, Refresh all, and Settings in its - * title row. + * shows the usage host's reports with pins, Refresh all and Settings in its title row, and the + * host filter at the top of its body. */ export function UsageModal(props: UsageModalProps) { const { t } = useTranslation(); @@ -56,10 +56,10 @@ function HostUsageModal({ () => ({ hosts, serverId, onSelect: onSelectHost }), [hosts, onSelectHost, serverId], ); - const { view, refresh, controls } = useHostUsageWithControls(hostSelection); + const { view, refresh, controls, hostFilter } = useHostUsageWithControls(hostSelection); const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); return ( - + @@ -72,8 +72,9 @@ function UsageModalFrame({ onClose, onDismiss, actions, + hostFilter, children, -}: UsageModalProps & { actions?: ReactNode; children: ReactNode }) { +}: UsageModalProps & { actions?: ReactNode; hostFilter?: ReactNode; children: ReactNode }) { const { t } = useTranslation(); const title = t(builtinSidebarNavLabelKey("usage")); const header = useMemo(() => ({ title, actions }), [actions, title]); @@ -87,6 +88,7 @@ function UsageModalFrame({ contextBridge={null} testID="usage-modal" > + {hostFilter} {children} ); diff --git a/packages/app/src/workspace-labels/manager-modal.tsx b/packages/app/src/workspace-labels/manager-modal.tsx index 8b0905dd16..5ef3252e5c 100644 --- a/packages/app/src/workspace-labels/manager-modal.tsx +++ b/packages/app/src/workspace-labels/manager-modal.tsx @@ -191,6 +191,7 @@ export function WorkspaceLabelManagerModal({ selectedHost={state.serverId} onSelectHost={selectHost} includeAllHost={false} + hang triggerTestID="workspace-label-manager-host" hostOptionTestID={managerHostOptionTestID} /> diff --git a/patches/react-native-draggable-flatlist+4.0.3.patch b/patches/react-native-draggable-flatlist+4.0.3.patch index e22f549c47..75f1f060a3 100644 --- a/patches/react-native-draggable-flatlist+4.0.3.patch +++ b/patches/react-native-draggable-flatlist+4.0.3.patch @@ -1,8 +1,8 @@ diff --git a/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts b/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts -index d3a4f1f..083bf19 100644 +index d3a4f1f..66e5124 100644 --- a/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts +++ b/node_modules/react-native-draggable-flatlist/lib/typescript/components/DraggableFlatList.d.ts -@@ -16,12 +16,14 @@ declare const _default: (props: Omit, "keyExtractor" | "data +@@ -16,12 +16,15 @@ declare const _default: (props: Omit, "keyExtractor" | "data keyExtractor: (item: T, index: number) => string; onDragBegin?: ((index: number) => void) | undefined; onDragEnd?: ((params: import("../types").DragEndParams) => void) | undefined; @@ -14,14 +14,15 @@ index d3a4f1f..083bf19 100644 renderPlaceholder?: import("../types").RenderPlaceholder | undefined; simultaneousHandlers?: React.Ref | React.Ref[] | undefined; + dragGestureHostPresented?: boolean | undefined; ++ dragGestureRef?: React.MutableRefObject | undefined; outerScrollOffset?: Animated.SharedValue | undefined; onAnimValInit?: ((animVals: { activeCellOffset: import("react-native-reanimated").SharedValue; diff --git a/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts b/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts -index d3c6cbb..36e9645 100644 +index d3c6cbb..a586a09 100644 --- a/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts +++ b/node_modules/react-native-draggable-flatlist/lib/typescript/components/NestableDraggableFlatList.d.ts -@@ -15,12 +15,14 @@ export declare const NestableDraggableFlatList: (props: Omit(props: Omit string; onDragBegin?: ((index: number) => void) | undefined; onDragEnd?: ((params: import("../types").DragEndParams) => void) | undefined; @@ -33,14 +34,15 @@ index d3c6cbb..36e9645 100644 renderPlaceholder?: import("../types").RenderPlaceholder | undefined; simultaneousHandlers?: React.Ref | React.Ref[] | undefined; + dragGestureHostPresented?: boolean | undefined; ++ dragGestureRef?: React.MutableRefObject | undefined; outerScrollOffset?: Animated.SharedValue | undefined; onAnimValInit?: ((animVals: { activeCellOffset: import("react-native-reanimated").SharedValue; diff --git a/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts b/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts -index 2abb4a2..8ca967f 100644 +index 2abb4a2..c60dedf 100644 --- a/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts +++ b/node_modules/react-native-draggable-flatlist/lib/typescript/types.d.ts -@@ -23,12 +23,16 @@ export declare type DraggableFlatListProps = Modify, { +@@ -23,12 +23,21 @@ export declare type DraggableFlatListProps = Modify, { keyExtractor: (item: T, index: number) => string; onDragBegin?: (index: number) => void; onDragEnd?: (params: DragEndParams) => void; @@ -54,6 +56,11 @@ index 2abb4a2..8ca967f 100644 simultaneousHandlers?: React.Ref | React.Ref[]; + /** @internal Forces handler reattachment when a retained native host is presented. */ + dragGestureHostPresented?: boolean; ++ /** ++ * Ref for the drag pan, so an enclosing gesture can wait for it to fail. The pan then arbitrates ++ * manually, as with `simultaneousHandlers`: it fails on a move unless a row is armed. ++ */ ++ dragGestureRef?: React.MutableRefObject; outerScrollOffset?: Animated.SharedValue; onAnimValInit?: (animVals: ReturnType) => void; itemEnteringAnimation?: AnimateProps["entering"]; @@ -174,7 +181,7 @@ index e4e861a..f485139 100644 declare global { diff --git a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx -index 7c88afc..ad75714 100644 +index 7c88afc..a97cb80 100644 --- a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx +++ b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx @@ -16,9 +16,11 @@ import { @@ -391,14 +398,16 @@ index 7c88afc..ad75714 100644 useAnimatedReaction( () => { return spacerIndexAnim.value; -@@ -271,11 +371,24 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -271,11 +371,26 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { ); const gestureDisabled = useSharedValue(false); + const touchStartX = useSharedValue(0); + const touchStartY = useSharedValue(0); + const manualPanActivated = useSharedValue(false); -+ const coordinatesDragWithExternalGesture = Boolean(props.simultaneousHandlers); ++ const coordinatesDragWithExternalGesture = Boolean( ++ props.simultaneousHandlers || props.dragGestureRef ++ ); - const panGesture = Gesture.Pan() + let panGesture = Gesture.Pan() @@ -417,7 +426,7 @@ index 7c88afc..ad75714 100644 panGestureState.value = evt.state; }) .onUpdate((evt) => { -@@ -286,8 +399,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -286,8 +401,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { : evt.translationY; touchTranslate.value = translation; }) @@ -434,7 +443,7 @@ index 7c88afc..ad75714 100644 // Set touch val to current translate val isTouchActiveNative.value = false; const translation = horizontalAnim.value -@@ -299,6 +419,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -299,6 +421,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { // Only call onDragEnd if actually dragging a cell if (activeIndexAnim.value === -1 || disabled.value) return; @@ -442,7 +451,7 @@ index 7c88afc..ad75714 100644 disabled.value = true; runOnJS(onRelease)(activeIndexAnim.value); const springTo = placeholderOffset.value - activeCellOffset.value; -@@ -309,22 +430,84 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -309,22 +432,85 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { runOnJS(onDragEnd)({ from: activeIndexAnim.value, to: spacerIndexAnim.value, @@ -524,13 +533,14 @@ index 7c88afc..ad75714 100644 if (dragHitSlop) panGesture.hitSlop(dragHitSlop); - if (activationDistanceProp) { ++ if (props.dragGestureRef) panGesture.withRef(props.dragGestureRef); + if (coordinatesDragWithExternalGesture) { + panGesture = panGesture.manualActivation(true); + } else if (activationDistanceProp) { const activeOffset = [-activationDistanceProp, activationDistanceProp]; if (props.horizontal) { panGesture.activeOffsetX(activeOffset); -@@ -332,6 +515,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -332,6 +518,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { panGesture.activeOffsetY(activeOffset); } } @@ -552,7 +562,7 @@ index 7c88afc..ad75714 100644 const onScroll = useStableCallback((scrollOffset: number) => { props.onScrollOffsetChange?.(scrollOffset); -@@ -372,9 +570,11 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -372,9 +573,11 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { keyExtractor={keyExtractor} horizontal={!!props.horizontal} layoutAnimationDisabled={layoutAnimationDisabled} @@ -636,10 +646,10 @@ index 75f7db7..e99faf3 100644 return ( diff --git a/node_modules/react-native-draggable-flatlist/src/types.ts b/node_modules/react-native-draggable-flatlist/src/types.ts -index d6755c8..1b244a6 100644 +index d6755c8..af70a01 100644 --- a/node_modules/react-native-draggable-flatlist/src/types.ts +++ b/node_modules/react-native-draggable-flatlist/src/types.ts -@@ -36,12 +36,16 @@ export type DraggableFlatListProps = Modify< +@@ -36,12 +36,21 @@ export type DraggableFlatListProps = Modify< keyExtractor: (item: T, index: number) => string; onDragBegin?: (index: number) => void; onDragEnd?: (params: DragEndParams) => void; @@ -653,6 +663,11 @@ index d6755c8..1b244a6 100644 simultaneousHandlers?: React.Ref | React.Ref[]; + /** @internal Forces handler reattachment when a retained native host is presented. */ + dragGestureHostPresented?: boolean; ++ /** ++ * Ref for the drag pan, so an enclosing gesture can wait for it to fail. The pan then arbitrates ++ * manually, as with `simultaneousHandlers`: it fails on a move unless a row is armed. ++ */ ++ dragGestureRef?: React.MutableRefObject; outerScrollOffset?: Animated.SharedValue; onAnimValInit?: (animVals: ReturnType) => void; itemEnteringAnimation?: AnimateProps["entering"]; diff --git a/plugins/codex-usage-source/server/usage.test.ts b/plugins/codex-usage-source/server/usage.test.ts index 4cdefa2bcd..c793d8dd12 100644 --- a/plugins/codex-usage-source/server/usage.test.ts +++ b/plugins/codex-usage-source/server/usage.test.ts @@ -328,9 +328,10 @@ test("reports every named additional limit with its own duration identity", asyn test("a weekly pin means weekly after the provider moves it between slots", async () => { const { resolvePinnedUsage } = await import("../../../packages/app/src/usage/pinned.js"); + const { DEFAULT_USAGE_PREFERENCES } = + await import("../../../packages/app/src/usage/preferences.js"); const preferences = { - displayAs: "used" as const, - serverId: null, + ...DEFAULT_USAGE_PREFERENCES, pins: [{ sourceId: "codex", windowId: "weekly" }], }; for (const primaryWeekly of [false, true]) { From 5f89e666d0f1450f109da4f4c04882d42a0ed944 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:00:54 +0000 Subject: [PATCH 073/160] Keep New workspace plugin metadata when the first agent start is retried (#9734) When New workspace hands its draft to the ready workspace's draft tab, the text and setup move with it but the draft's plugin metadata did not: it was cleared with the New workspace draft and never written to the destination draft. A send after a failed first start then created the agent without the metadata. Copy the metadata into the destination draft at handoff, before the New workspace draft is cleared. Closes #9716 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Michael Wu Co-authored-by: Claude Opus 5.5 --- .../e2e/browser/creation-idempotency.spec.ts | 17 ++++++ packages/app/e2e/support/creation-fixtures.ts | 52 ++++++++++++++++++- packages/app/e2e/support/helpers/creation.ts | 10 ++++ .../app/e2e/support/helpers/seed-client.ts | 1 + .../app/src/screens/new-workspace-screen.tsx | 6 ++- .../new-workspace/background-handoff.ts | 22 ++++++++ 6 files changed, 105 insertions(+), 3 deletions(-) diff --git a/packages/app/e2e/browser/creation-idempotency.spec.ts b/packages/app/e2e/browser/creation-idempotency.spec.ts index 8de9f40fbb..60809142f6 100644 --- a/packages/app/e2e/browser/creation-idempotency.spec.ts +++ b/packages/app/e2e/browser/creation-idempotency.spec.ts @@ -148,6 +148,23 @@ for (const scenario of [ }); } +test("retrying failed agent initialization keeps the plugin metadata set on New workspace", async ({ + creation, + startup, + composerMetadata, +}) => { + await creation.openWorkspaceForm("local"); + await composerMetadata.set({ "composer-metadata.tag": "kept" }); + await creation.submitPrompt("Start the tagged task.", "Create"); + await creation.expectAgentStillStarting(); + await startup.fail(); + await creation.expectStartupFailure(); + await creation.expectOneCreatedWorkspace(); + await creation.submitPrompt("Start the tagged task."); + await creation.expectAgentCount(1); + await creation.expectAgentMetadata({ "composer-metadata.tag": "kept" }); +}); + test("an edited agent draft starts after its first start failed", async ({ creation, startup, diff --git a/packages/app/e2e/support/creation-fixtures.ts b/packages/app/e2e/support/creation-fixtures.ts index c6d3579206..e7be00626f 100644 --- a/packages/app/e2e/support/creation-fixtures.ts +++ b/packages/app/e2e/support/creation-fixtures.ts @@ -1,6 +1,8 @@ -import { writeFile, rm, rename } from "node:fs/promises"; +import { mkdtemp, writeFile, rm, rename } from "node:fs/promises"; +import { tmpdir } from "node:os"; import path from "node:path"; -import { copyPluginExample } from "./helpers/plugin-fixture"; +import type { Page } from "@playwright/test"; +import { copyPluginExample, pluginRequirements } from "./helpers/plugin-fixture"; import { connectNewWorkspaceDaemonClient } from "./helpers/new-workspace"; import { test as base } from "./fixtures"; import { @@ -14,6 +16,7 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace"; export const test = base.extend<{ startup: { release(): Promise; fail(): Promise }; promptRejection: void; + composerMetadata: { set(patch: Record): Promise }; creation: Awaited>; promptRetry: ReturnType; agentRetries: Awaited>; @@ -98,6 +101,39 @@ export default function contribute(server) { await client.close(); } }, + composerMetadata: async ({ page }, provide) => { + const client = await connectNewWorkspaceDaemonClient(); + const previous = await client.getDaemonConfig(); + const directory = await mkdtemp(path.join(tmpdir(), "paseo-composer-metadata-")); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "composer-metadata", requirements: pluginRequirements }), + ); + await writeFile( + path.join(directory, "index.client.tsx"), + `import { useComposer } from "@getpaseo/plugin/client"; + +function Holder() { + globalThis.metadataComposer = useComposer(); + return null; +} + +export default function contribute(client) { + client.addComposerItem({ id: "holder", Component: Holder }); + return () => {}; +}`, + ); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + await provide({ set: (patch) => setComposerMetadata(page, patch) }); + } finally { + await client.removePlugin("composer-metadata"); + await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled }); + await rm(directory, { recursive: true, force: true }); + await client.close(); + } + }, creation: async ({ page }, provide) => { const creation = await createCreationScenario(page); try { @@ -126,3 +162,15 @@ export default function contribute(server) { } }, }); + +type MetadataComposerGlobal = typeof globalThis & { + metadataComposer?: { setMetadata(patch: Record): Promise }; +}; + +async function setComposerMetadata(page: Page, patch: Record) { + await page.waitForFunction(() => (globalThis as MetadataComposerGlobal).metadataComposer); + await page.evaluate( + (value) => (globalThis as MetadataComposerGlobal).metadataComposer!.setMetadata(value), + patch, + ); +} diff --git a/packages/app/e2e/support/helpers/creation.ts b/packages/app/e2e/support/helpers/creation.ts index 0de6d6672a..0c4acc38ad 100644 --- a/packages/app/e2e/support/helpers/creation.ts +++ b/packages/app/e2e/support/helpers/creation.ts @@ -258,6 +258,16 @@ export async function createCreationScenario(page: Page) { .filter(({ agent }) => agent.workspaceId === workspaceId) .map(({ agent }) => agent.id); }, + async expectAgentMetadata(metadata: Record) { + await expect + .poll( + async () => + (await project.client.fetchAgents()).entries.find( + ({ agent }) => agent.workspaceId === workspaceId, + )?.agent.metadata, + ) + .toEqual(metadata); + }, async expectAgentTitle(title: string) { await expect .poll( diff --git a/packages/app/e2e/support/helpers/seed-client.ts b/packages/app/e2e/support/helpers/seed-client.ts index 41e676473f..05895f7769 100644 --- a/packages/app/e2e/support/helpers/seed-client.ts +++ b/packages/app/e2e/support/helpers/seed-client.ts @@ -131,6 +131,7 @@ export interface SeedDaemonClient { currentModeId: string | null; status: string; title?: string | null; + metadata?: Record; }; }>; }>; diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index ccf49c9b4a..4be45f134a 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -121,7 +121,10 @@ import { type ListTerminalsPayload, upsertCreatedTerminalPayload, } from "./workspace/terminals/state"; -import { captureWorkspaceDraftCleanup } from "./new-workspace/background-handoff"; +import { + captureWorkspaceDraftCleanup, + handOffDraftMetadata, +} from "./new-workspace/background-handoff"; import { useNewWorkspaceScreenPresence } from "./new-workspace/screen-presence"; function useIsNewWorkspaceDraftHandoffActive(input: { @@ -635,6 +638,7 @@ function submitWorkspaceDraft(input: SubmitDraftInput): SubmitOutcome { allowEmptyText: true, agentCreation: input.agentCreation, }); + handOffDraftMetadata({ serverId, draftId, metadata: composerState.metadata }); clearDraft("sent"); navigateToWorkspace({ serverId, diff --git a/packages/app/src/screens/new-workspace/background-handoff.ts b/packages/app/src/screens/new-workspace/background-handoff.ts index 598772f1a1..68a64b987a 100644 --- a/packages/app/src/screens/new-workspace/background-handoff.ts +++ b/packages/app/src/screens/new-workspace/background-handoff.ts @@ -1,7 +1,29 @@ import { useWorkspaceAttachmentsStore } from "@/attachments/workspace-attachments-store"; +import { buildDraftStoreKey } from "@/stores/draft-keys"; import { useDraftStore } from "@/stores/draft-store"; +import type { JsonValue } from "@getpaseo/protocol/agent-types"; import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store"; +/** + * The ready workspace's draft tab owns the draft once New workspace hands it off, including a + * retry after the first agent start fails. Its metadata moves with it, like its text and setup. + */ +export function handOffDraftMetadata(input: { + serverId: string; + draftId: string; + metadata: Readonly>; +}): void { + if (Object.keys(input.metadata).length === 0) return; + useDraftStore.getState().patchDraftMetadata({ + draftKey: buildDraftStoreKey({ + serverId: input.serverId, + agentId: input.draftId, + draftId: input.draftId, + }), + patch: { ...input.metadata }, + }); +} + interface WorkspaceDraftCleanupInput { draftId?: string; draftKey: string; From fed8624516f5e46c0a4fb1f594933cdc814dce68 Mon Sep 17 00:00:00 2001 From: Eric Butler Date: Sun, 15 Nov 2026 00:01:44 -0500 Subject: [PATCH 074/160] fix(claude): state why a permission prompt appeared (#3950) * fix(claude): state why a permission prompt appeared ### Linked issue Closes # No open issue tracks this. The behavior appeared in a live session on a remote host. ### Type of change - [x] Bug fix - [ ] New feature - [ ] Enhancement - [ ] Refactor - [ ] Docs ### Reasoning A user selects Bypass and expects no prompts. A `permissions.ask` rule or a `PreToolUse` hook outranks the mode, so the agent asks anyway, and the card gives no cause. The user reads this as a broken mode. Claude explains each prompt in `canUseTool`'s `decisionReason`. Paseo dropped it. The card now shows that sentence, so a user can find the hook that owns the rule instead of guessing. Codex already puts its approval reason in `description`. Claude now matches, so no new field and no protocol change are needed. `description` was unset on every Claude permission request except `AskUserQuestion`, which keeps its own summary because that spread still runs after this line. ### Goals - The card shows the provider's reason when the provider sends one. Acceptance: a hook-forced prompt in Bypass shows the hook's `permissionDecisionReason`. - A card without a reason looks exactly as it does today. Acceptance: no new row, no layout shift. - Claude and Codex carry an approval reason the same way. Acceptance: one field, no provider-specific rendering. ### Non-goals - Changing the CLI's precedence. A hook that asks still asks. Paseo shows the cause; it does not overrule the hook. - Auto-approving hook-forced tools in Bypass. `f998ee169` did that and was reverted the same day. A blanket allow defeats a real safety hook. ### QA Real Claude, web (browser), one live session in `bypassPermissions`, driven through the app by Playwright. ``` npx playwright test --project=real-provider e2e/browser/permission-reason-card.real.spec.ts 1 passed (52.7s) ``` The run forces two prompts in the same session and captures both. Forced by a `permissions.ask` rule, which sends no reason. This is the card before this change: ![before-rule-forced-no-reason.png](https://github.com/user-attachments/assets/75d30b5f-b26c-48bb-a3dd-82074ae30d6c) Forced by a `PreToolUse` hook that returns a reason, same session: ![after-hook-forced-with-reason.png](https://github.com/user-attachments/assets/78b8c01b-6adb-4107-92a7-7e45cd4357e8) The spec asserts both states, so the screenshots are not the only proof: the hook's sentence is absent from the first card and visible on the second. Both cards come from one session on this branch. The pair shows the two render paths, with a reason and without. It is not an old build beside a new one. A card without a reason renders exactly as it did before this change, which is why the first shot stands in for the old card. The spec lives at `packages/app/e2e/browser/permission-reason-card.real.spec.ts`. It is not part of this commit. Unit: ``` npx vitest run packages/server/src/server/agent/providers/claude/agent.test.ts Test Files 1 passed (1) Tests 75 passed (75) ``` Platforms: the daemon fills a field the card already rendered, so every platform gets it through the existing path. Web verified above with real Claude. ### Checklist - [x] One focused change - [x] `npm run typecheck` passes - [x] `npm run lint` passes - [x] `npm run format` passes - [x] QA evidence - [x] Tests added or updated where it made sense Co-Authored-By: Claude Opus 5 (1M context) * fix: preserve context for Claude permission reasons --------- Co-authored-by: Claude Opus 5 (1M context) Co-authored-by: Mohamed Boudra --- .../src/agent-attention-notification.test.ts | 19 ++++++++++ .../src/agent-attention-notification.ts | 5 +++ .../agent/providers/claude/agent.test.ts | 37 +++++++++++++++++++ .../server/agent/providers/claude/agent.ts | 2 + 4 files changed, 63 insertions(+) diff --git a/packages/protocol/src/agent-attention-notification.test.ts b/packages/protocol/src/agent-attention-notification.test.ts index 04aabceb2c..9166d907de 100644 --- a/packages/protocol/src/agent-attention-notification.test.ts +++ b/packages/protocol/src/agent-attention-notification.test.ts @@ -71,6 +71,25 @@ describe("buildAgentAttentionNotificationPayload", () => { }); }); + it("includes the tool input when a permission has a reason but no title", () => { + const payload = buildAgentAttentionNotificationPayload({ + reason: "permission", + serverId: "srv-1", + workspaceId: "workspace-1", + agentId: "agent-1", + permissionRequest: { + id: "perm-1", + provider: "claude", + name: "Bash", + kind: "tool", + input: { command: "echo hello" }, + description: "Hook requires approval", + }, + }); + + expect(payload.body).toBe('{"command":"echo hello"} - Hook requires approval'); + }); + it("uses error-specific defaults when reason is error", () => { const payload = buildAgentAttentionNotificationPayload({ reason: "error", diff --git a/packages/protocol/src/agent-attention-notification.ts b/packages/protocol/src/agent-attention-notification.ts index 961e864d85..5b9d229d47 100644 --- a/packages/protocol/src/agent-attention-notification.ts +++ b/packages/protocol/src/agent-attention-notification.ts @@ -115,6 +115,11 @@ const buildPermissionDetails = ( if (title) { details.push(title); + } else if (description && request.input) { + const inputPreview = safeStringify(request.input); + if (inputPreview) { + details.push(inputPreview); + } } if (description && description !== title) { details.push(description); diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index 3aa96635fc..43632a0cdb 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -998,6 +998,43 @@ describe("ClaudeAgentSession features", () => { } }); + test("carries the SDK decision reason onto the permission request description", async () => { + const { queryFactory } = createQueryMock(); + const session = await new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }).createSession({ provider: "claude", cwd: process.cwd(), modeId: "bypassPermissions" }); + const events: AgentStreamEvent[] = []; + const unsubscribe = session.subscribe((event) => events.push(event)); + + try { + await session.startTurn("run the tool"); + const canUseTool = queryFactory.mock.calls[0]?.[0].options.canUseTool; + if (!canUseTool) throw new Error("Expected canUseTool callback"); + canUseTool( + "Bash", + { command: "printf test" }, + { + toolUseID: "tool-hook-ask", + decisionReason: + "\u001b[33mHeredoc input to python3 -- cannot statically verify safety\u001b[0m", + }, + ).catch(() => undefined); + + expect(events.find((event) => event.type === "permission_requested")).toMatchObject({ + type: "permission_requested", + request: { + name: "Bash", + description: "Heredoc input to python3 -- cannot statically verify safety", + }, + }); + } finally { + unsubscribe(); + await session.close(); + } + }); + test("passes exact configured Fable 5 IDs through to Claude Code", async () => { const { queryFactory, queryMock } = createQueryMock(); const client = new ClaudeAgentClient({ diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index bee13ed78e..ace2320de6 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -9,6 +9,7 @@ import fs from "node:fs"; import { promises } from "node:fs"; import path from "node:path"; import { LRUCache } from "lru-cache"; +import stripAnsi from "strip-ansi"; import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.js"; import { type AgentDefinition, @@ -5330,6 +5331,7 @@ class ClaudeAgentSession implements AgentSession { provider: "claude", name: toolName, kind, + description: readNonEmptyString(stripAnsi(options.decisionReason ?? ""))?.trim(), ...buildClaudeQuestionPermissionSummary(toolName, input), input: requestInput, detail: toolDetail, From 5b1baa0e720e389b8b57e387239d9390b80e799c Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:10:47 +0000 Subject: [PATCH 075/160] Mark a closed agent as read even when its provider session is gone (#9737) * fix(server): clear attention without resuming closed agents * fix(server): serialize attention clearing with reloads * fix(server): keep cleared attention when a queued resume lands Clearing attention on a closed agent no longer resumes its provider session, so a resume that the loader queued behind the clear must not restore the attention it read before the clear. Resume now reads attention from the record inside the agent's lifecycle lane, as it already does for metadata. Adds a daemon regression test for a closed agent whose provider session is gone: on main the clear_agent_attention request never gets a response and the agent stays unread. Co-authored-by: luke Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: luke Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/agent-manager.test.ts | 66 +++++++++++++++++++ .../server/src/server/agent/agent-manager.ts | 10 ++- .../server/owned-subscriptions.e2e.test.ts | 64 ++++++++++++++++++ packages/server/src/server/session.ts | 14 ++-- 4 files changed, 142 insertions(+), 12 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index f0064ebb4d..966b66f2ec 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -3020,6 +3020,72 @@ test("opening during reload waits for the replacement", async () => { } }); +test("clearing attention during reload waits for the replacement", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reload-clear-attention-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new HeldReloadCloseClient(); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + try { + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + await manager.markAgentUnread(created.id); + const reloading = manager.reloadAgentSession(created.id); + await client.waitForCloseToStart(); + let cleared = false; + const clearing = manager.clearAgentAttention(created.id).then(() => { + cleared = true; + return true; + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(cleared).toBe(false); + client.finishClosing(); + await Promise.all([reloading, clearing]); + expect(manager.getAgent(created.id)?.attention.requiresAttention).toBe(false); + expect((await storage.get(created.id))?.requiresAttention).toBe(false); + await manager.closeAgent(created.id); + } finally { + client.finishClosing(); + await storage.flush(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("resuming after a queued attention clear keeps the agent read", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-resume-clear-attention-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + try { + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const handle = manager.getAgent(created.id)!.persistence!; + await manager.closeAgent(created.id); + await manager.markAgentUnread(created.id); + // A loader read the record before the clear landed, then queued the resume behind it. + const unreadAttention = { + requiresAttention: true, + attentionReason: "finished", + attentionTimestamp: new Date(), + } as const; + const clearing = manager.clearAgentAttention(created.id); + const resumed = await manager.resumeAgentFromPersistence(handle, { cwd: workdir }, created.id, { + attention: unreadAttention, + }); + await clearing; + expect(resumed.attention.requiresAttention).toBe(false); + expect((await storage.get(created.id))?.requiresAttention).toBe(false); + await manager.closeAgent(created.id); + } finally { + await storage.flush(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("closing during reload leaves the replacement closed", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reload-close-race-")); const storage = new AgentStorage(join(workdir, "agents"), logger); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 0ccb209e0f..34af303027 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -1722,9 +1722,9 @@ export class AgentManager { return this.registerSession(session, storedConfig, resolvedAgentId, { launchedOptions, ...options, - // The caller read its metadata before this turn in the lane; a setMetadata queued ahead of - // it has saved a newer record, the one the open hooks saw. - ...(record ? { metadata: record.metadata } : {}), + // The caller read its metadata and attention before this turn in the lane; a setMetadata + // or attention clear queued ahead of it has saved a newer record, the one the open hooks saw. + ...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}), workspaceId, launchEnv, persistence: handle, @@ -2763,6 +2763,10 @@ export class AgentManager { } async clearAgentAttention(agentId: string): Promise { + return this.runLifecycleMutation(agentId, () => this.clearAgentAttentionUnlocked(agentId)); + } + + private async clearAgentAttentionUnlocked(agentId: string): Promise { const agent = this.agents.get(agentId); if (agent) { if (agent.attention.requiresAttention) { diff --git a/packages/server/src/server/owned-subscriptions.e2e.test.ts b/packages/server/src/server/owned-subscriptions.e2e.test.ts index c210118f1f..75822ffeca 100644 --- a/packages/server/src/server/owned-subscriptions.e2e.test.ts +++ b/packages/server/src/server/owned-subscriptions.e2e.test.ts @@ -16,6 +16,7 @@ import { } from "@getpaseo/protocol/binary-frames/index"; import { DaemonClient } from "./test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js"; +import { withTimeout } from "../utils/promise-timeout.js"; import { SessionInboundMessageSchema, type SessionInboundMessage, @@ -1645,6 +1646,69 @@ test("request outcomes for import and attention reach only their requesting sock } }); +test("clearing a closed agent's attention does not resume its provider session", async () => { + const daemon = await createTestPaseoDaemon({ + mcpEnabled: false, + isDev: true, + agentClients: { mock: new MockLoadTestAgentClient() }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + const agent = await client.createAgent({ provider: "mock", cwd: daemon.staticDir }); + await daemon.daemon.agentManager.closeAgent(agent.id); + await daemon.daemon.agentManager.markAgentUnread(agent.id); + await client.clearAgentAttention(agent.id); + expect(daemon.daemon.agentManager.getAgent(agent.id)).toBeNull(); + const snapshot = await client.fetchAgent(agent.id); + expect(snapshot?.agent.requiresAttention).toBe(false); + expect(snapshot?.agent.status).toBe("closed"); + } finally { + await client.close(); + await daemon.close(); + } +}); + +class SessionGoneAgentClient extends MockLoadTestAgentClient { + resumeCalls = 0; + + override async resumeSession(): Promise { + this.resumeCalls += 1; + throw new Error("Session not found"); + } +} + +test("clearing a closed agent's attention succeeds when its provider session is gone", async () => { + const agentClient = new SessionGoneAgentClient(); + const daemon = await createTestPaseoDaemon({ + mcpEnabled: false, + isDev: true, + agentClients: { mock: agentClient }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + const agent = await client.createAgent({ provider: "mock", cwd: daemon.staticDir }); + await daemon.daemon.agentManager.closeAgent(agent.id); + await client.markWorkspaceUnread(agent.workspaceId!); + expect((await client.fetchAgent(agent.id))?.agent.requiresAttention).toBe(true); + + await withTimeout( + client.clearAgentAttention(agent.id), + 5_000, + "clear_agent_attention got no response", + ); + + const snapshot = await client.fetchAgent(agent.id); + expect(snapshot?.agent.requiresAttention).toBe(false); + expect(snapshot?.agent.status).toBe("closed"); + expect(agentClient.resumeCalls).toBe(0); + } finally { + await client.close(); + await daemon.close(); + } +}); + test("SDK import failure settles without waiting for the request timeout", async () => { const daemon = await createTestPaseoDaemon({ mcpEnabled: false }); const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 164792308e..231e987020 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -5394,15 +5394,11 @@ export class Session { const agentIds = Array.isArray(agentId) ? agentId : [agentId]; try { - await Promise.all( - agentIds.map((id) => - ensureAgentLoaded(id, { - agentManager: this.agentManager, - agentStorage: this.agentStorage, - logger: this.sessionLogger, - }), - ), - ); + for (const id of agentIds) { + if (!this.agentManager.getAgent(id) && !(await this.agentStorage.get(id))) { + throw new Error(`Agent not found: ${id}`); + } + } await Promise.all(agentIds.map((id) => this.agentManager.clearAgentAttention(id))); if (requestId) { const agents = ( From fee32c9594d6fe804c5b113bb285316e43455bcb Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 14:03:37 +0700 Subject: [PATCH 076/160] docs(hub): rename the GitHub connect button to Connect GitHub (#9738) * docs(hub): explain connecting existing GitHub installations * docs(hub): reduce the change to the Connect GitHub button label --- public-docs/hub/self-hosting/github-app.md | 2 +- public-docs/hub/self-hosting/github-app.zh-CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/public-docs/hub/self-hosting/github-app.md b/public-docs/hub/self-hosting/github-app.md index ad47a03f42..75fc05eca0 100644 --- a/public-docs/hub/self-hosting/github-app.md +++ b/public-docs/hub/self-hosting/github-app.md @@ -35,7 +35,7 @@ Under **Subscribe to events**, select **Issue comment**, **Issues**, **Pull requ ## Connect repositories -After Hub verifies the App, choose **Install on GitHub**. Select the account or organization and repositories the App may access. +After Hub verifies the App, choose **Connect GitHub**. Select the account or organization and repositories the App may access. Start from Hub rather than GitHub's own install button. The round trip binds the installation to the active Hub organization. diff --git a/public-docs/hub/self-hosting/github-app.zh-CN.md b/public-docs/hub/self-hosting/github-app.zh-CN.md index ef892fe815..3c1329b6d1 100644 --- a/public-docs/hub/self-hosting/github-app.zh-CN.md +++ b/public-docs/hub/self-hosting/github-app.zh-CN.md @@ -33,7 +33,7 @@ GitHub 会使用以下 Hub URL: ## 连接仓库 {#connect-repositories} -Hub 验证 App 之后,选择 **Install on GitHub**。选择 App 可以访问的账号或组织以及仓库。 +Hub 验证 App 之后,选择 **Connect GitHub**。选择 App 可以访问的账号或组织以及仓库。 请从 Hub 发起安装,而不是使用 GitHub 自己的安装按钮。这一来一回会把安装绑定到当前的 Hub 组织。 From dc2dfdab9396abb41bec6a22cb210584f6a8b62d Mon Sep 17 00:00:00 2001 From: "Adam C. Stephens" <2071575+adamcstephens@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:06:52 -0500 Subject: [PATCH 077/160] fix(client): recover routed hosts when their gateway reconnects (#9558) * client: recover routed hosts when their gateway reconnects Assisted-By: OpenAI GPT-6.1 Sol high in omp/18.16.0 * client: wake routed clients before waiting for probes Assisted-By: OpenAI GPT-6.1 Sol high in omp/18.18.9 --- packages/app/src/runtime/host-runtime.test.ts | 202 ++++++++++++++++++ packages/app/src/runtime/host-runtime.ts | 17 ++ packages/client/src/daemon-client.test.ts | 68 +++++- packages/client/src/hosts/index.ts | 3 +- 4 files changed, 288 insertions(+), 2 deletions(-) diff --git a/packages/app/src/runtime/host-runtime.test.ts b/packages/app/src/runtime/host-runtime.test.ts index c802a945c3..1981a68975 100644 --- a/packages/app/src/runtime/host-runtime.test.ts +++ b/packages/app/src/runtime/host-runtime.test.ts @@ -2149,6 +2149,68 @@ describe("HostRuntimeController", () => { }); }); + it("wakes an active routed client before an unrelated direct probe settles", async () => { + useHostRuntimeClock(); + const route: HostConnection = { + id: "via:srv_parent", + type: "routed", + originServerId: "srv_parent", + }; + const host = makeHost({ connections: [route] }); + const client = makeConnectedProbeClient(5); + const directProbeStarted = createDeferred(); + const directProbe = createDeferred(); + let directProbeCalls = 0; + const controller = new HostRuntimeController({ + host, + deps: { + getClientId: async () => "blocked-direct-probe", + createClient: () => new FakeDaemonClient() as unknown as DaemonClient, + connectToDaemon: async ({ connection }) => { + if (connection.type === "directTcp") { + directProbeCalls += 1; + directProbeStarted.resolve(); + await directProbe.promise; + throw new Error("Direct connection unavailable"); + } + return { + client: client as unknown as DaemonClient, + serverId: host.serverId, + hostname: host.label, + }; + }, + }, + }); + await controller.start({ autoProbe: false }); + client.setConnectionState({ + status: "disconnected", + reason: "origin offline", + nextRetryAt: new Date(Date.now() + 12000).toISOString(), + }); + const probing = controller.updateHost({ + ...host, + connections: [ + route, + { id: "direct:unreachable", type: "directTcp", endpoint: "unreachable:6767" }, + ], + }); + await directProbeStarted.promise; + const recovering = controller.reconnectVia("srv_parent"); + try { + expect(client.ensureConnectedCalls).toBe(1); + expect(controller.getSnapshot().connectionStatus).toBe("online"); + expect(directProbeCalls).toBe(1); + await vi.advanceTimersByTimeAsync(0); + expect(client.ensureConnectedCalls).toBe(1); + expect(directProbeCalls).toBe(1); + } finally { + directProbe.resolve(); + await Promise.all([probing, recovering]); + await controller.stop(); + } + expect(directProbeCalls).toBe(1); + }); + it("keeps active client generation stable during background probe cycles", async () => { useHostRuntimeClock(); const host = makeHost({ @@ -2195,6 +2257,146 @@ describe("HostRuntimeController", () => { }); describe("HostRuntimeStore", () => { + function gatewayRecoveryFixture() { + const parent = new FakeDaemonClient(); + parent.connectedHosts = true; + parent.hostDirectory = Promise.resolve({ + self: { serverId: "srv_parent", label: "parent" }, + hosts: ["srv_child", "srv_healthy"].map((serverId) => ({ + registrationId: `reg_${serverId}`, + serverId, + label: serverId, + source: { id: "user", key: serverId }, + metadata: {}, + enabled: true, + status: "online" as const, + targetDescription: "relay", + lastOnlineAt: null, + nextRetryAt: null, + error: null, + })), + }); + const parentReady = createDeferred(); + const child = makeConnectedProbeClient(5); + const healthy = makeConnectedProbeClient(5); + const unrelated = makeConnectedProbeClient(5); + const attempts = new Map(); + const hosts = [ + makeHost({ + serverId: "srv_parent", + connections: [ + { + id: "relay:parent", + type: "relay", + relayEndpoint: "relay.paseo.sh:443", + daemonPublicKeyB64: "pk_parent", + }, + ], + }), + ...["srv_child", "srv_healthy"].map((serverId) => + makeHost({ + serverId, + connections: [ + { + id: "via:srv_parent", + type: "routed" as const, + originServerId: "srv_parent", + }, + ], + }), + ), + makeHost({ + serverId: "srv_unrelated", + connections: [ + { + id: "direct:unrelated:6767", + type: "directTcp", + endpoint: "unrelated:6767", + }, + ], + }), + ]; + const store = new HostRuntimeStore({ + storage: createMemoryHostRuntimeStorage({ + "@paseo:e2e": "1", + "@paseo:daemon-registry": JSON.stringify(hosts), + }), + deps: { + getClientId: async () => "gateway-recovery", + createClient: () => new FakeDaemonClient() as unknown as DaemonClient, + connectToDaemon: async ({ host, connection }) => { + attempts.set(host.serverId, (attempts.get(host.serverId) ?? 0) + 1); + let client: FakeDaemonClient; + if (host.serverId === "srv_parent") { + await parentReady.promise; + parent.setConnectionState({ status: "connected" }); + client = parent; + } else if (connection.type === "routed") { + if (!parent.isConnected) throw new Error("Origin host srv_parent is unavailable"); + client = host.serverId === "srv_child" ? child : healthy; + } else { + client = unrelated; + } + return { + client: client as unknown as DaemonClient, + serverId: host.serverId, + hostname: host.label, + }; + }, + }, + }); + return { store, parent, parentReady, child, healthy, unrelated, attempts }; + } + + it("retries saved child routes immediately when their relay gateway first connects", async () => { + useHostRuntimeClock(); + const { store, parentReady, attempts } = gatewayRecoveryFixture(); + try { + await store.boot(); + await vi.advanceTimersByTimeAsync(100); + expect(attempts.get("srv_child")).toBe(1); + expect(store.getSnapshot("srv_child")?.connectionStatus).not.toBe("online"); + parentReady.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(store.getSnapshot("srv_parent")?.connectionStatus).toBe("online"); + expect(store.getSnapshot("srv_child")?.connectionStatus).toBe("online"); + expect(store.getSnapshot("srv_healthy")?.connectionStatus).toBe("online"); + expect(attempts.get("srv_child")).toBe(2); + expect(attempts.get("srv_healthy")).toBe(2); + expect(attempts.get("srv_unrelated")).toBe(1); + } finally { + store.syncHosts([]); + } + }); + + it("wakes disconnected routed clients on gateway recovery without disturbing healthy hosts", async () => { + useHostRuntimeClock(); + const { store, parent, parentReady, child, healthy, unrelated } = gatewayRecoveryFixture(); + try { + parentReady.resolve(); + await store.boot(); + await vi.advanceTimersByTimeAsync(2000); + expect(store.getSnapshot("srv_child")?.connectionStatus).toBe("online"); + parent.setConnectionState({ status: "disconnected", reason: "relay lost" }); + child.setConnectionState({ + status: "disconnected", + reason: "origin offline", + nextRetryAt: new Date(Date.now() + 12000).toISOString(), + }); + parent.setConnectionState({ status: "connected" }); + await vi.advanceTimersByTimeAsync(0); + expect(child.ensureConnectedCalls).toBe(1); + expect(store.getSnapshot("srv_child")?.connectionStatus).toBe("online"); + expect(healthy.ensureConnectedCalls).toBe(0); + expect(unrelated.ensureConnectedCalls).toBe(0); + parent.setConnectionState({ status: "connected" }); + await vi.advanceTimersByTimeAsync(0); + expect(child.ensureConnectedCalls).toBe(1); + } finally { + store.syncHosts([]); + } + }); + it.each([false, true])( "keeps B and C distinct with routed and direct candidates (B direct first: %s)", async (directFirst) => { diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index 15a86b7bb4..b2d6871f0c 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -869,6 +869,22 @@ export class HostRuntimeController { this.activeClient?.ensureConnected(options); } + async reconnectVia(originServerId: string): Promise { + const routes = this.host.connections.filter( + (connection) => + connection.type === "routed" && + connection.originServerId === originServerId && + !this.authRejectedConnectionIds.has(connection.id), + ); + if (routes.length === 0 || !this.started || isHostRuntimeConnected(this.snapshot)) return; + if (routes.some((route) => route.id === this.snapshot.activeConnectionId)) + this.ensureConnected(); + await this.probeCycleInFlight; + if (!this.started || this.snapshot.connectionStatus === "online") return; + for (const route of routes) this.connectionLastProbedAt.delete(route.id); + await this.runProbeCycleNow(); + } + markAgentDirectorySyncLoading(): void { const status = this.snapshot.hasEverLoadedAgentDirectory ? "revalidating" : "initial_loading"; this.updateSnapshot({ @@ -2601,6 +2617,7 @@ export class HostRuntimeStore { snapshot.connectionStatus === "online" && previousStatus !== "online"; if (didTransitionOnline) { useSessionStore.getState().bumpHistorySyncGeneration(serverId); + for (const child of this.controllers.values()) void child.reconnectVia(serverId); // Checkout git data is push-driven; pushes emitted while disconnected are gone for // good (the daemon dedupes by snapshot fingerprint). Mark the caches stale so active // queries refetch now and evicted ones on their next mount. diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 2ddef8cc61..057e6550c8 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -12,6 +12,7 @@ import { type PluginClientBundle, type PluginClientBundleStore, } from "./daemon-client"; +import { createHostChannelTransport } from "./hosts/index.js"; import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities"; import { ChunkedTransport } from "@getpaseo/protocol/chunked-transport"; import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas"; @@ -9562,7 +9563,6 @@ test.each(["latency", "dictation start", "dictation finish"])( ); test("routed channels inherit an origin without drain support", async () => { - const { createHostChannelTransport } = await import("./hosts/index.js"); const mock = createMockTransport(); mock.transport.supportsDrain = false; const client = new DaemonClient({ @@ -10133,3 +10133,69 @@ describe("provider options across daemon versions", () => { }); }); }); + +test.each([ + { name: "route", initialRouteId: null, link: false }, + { name: "link", initialRouteId: null, link: true }, + { name: "initial route", initialRouteId: "route", link: false }, +])( + "$name fails promptly when its origin is offline during initialization", + async ({ initialRouteId, link }) => { + vi.useFakeTimers(); + const origin = new DaemonClient({ + url: "ws://origin", + clientId: "offline-origin", + transportFactory: () => createMockTransport().transport, + reconnect: { enabled: false }, + logger: createMockLogger(), + }); + clients.push(origin); + const unsubscribe = vi.fn(); + const subscribe = origin.subscribeConnectionStatus.bind(origin); + vi.spyOn(origin, "subscribeConnectionStatus").mockImplementation((listener) => { + const release = subscribe(listener); + return () => { + release(); + unsubscribe(); + }; + }); + const child = new DaemonClient({ + url: "ws://routed-host/ws", + clientId: "offline-origin-child", + transportFactory: createHostChannelTransport(origin, "child", "scope", initialRouteId, link), + reconnect: { enabled: false }, + logger: createMockLogger(), + }); + clients.push(child); + const rejected = expect(child.connect()).rejects.toThrow(); + await vi.advanceTimersByTimeAsync(0); + expect(child.getConnectionState().status).toBe("disconnected"); + await rejected; + expect(unsubscribe).toHaveBeenCalledTimes(1); + }, +); + +test("disposing a route before its deferred close does not reopen it on origin recovery", async () => { + vi.useFakeTimers(); + const mock = createMockTransport(); + const origin = new DaemonClient({ + url: "ws://origin", + clientId: "disposed-route-origin", + transportFactory: () => mock.transport, + reconnect: { enabled: false }, + logger: createMockLogger(), + }); + clients.push(origin); + const route = createHostChannelTransport(origin, "child", "scope", null)({ url: "ws://route" }); + const opened = vi.fn(); + const closed = vi.fn(); + route.onOpen(opened); + route.onClose(closed); + route.close(); + const connecting = origin.connect(); + mock.triggerOpen({ features: { ownedSubscriptions: true, connectedHosts: true } }); + await connecting; + await vi.advanceTimersByTimeAsync(0); + expect(opened).not.toHaveBeenCalled(); + expect(closed).toHaveBeenCalledTimes(1); +}); diff --git a/packages/client/src/hosts/index.ts b/packages/client/src/hosts/index.ts index 150cf48071..47504f0ebe 100644 --- a/packages/client/src/hosts/index.ts +++ b/packages/client/src/hosts/index.ts @@ -86,7 +86,8 @@ export function createHostChannelTransport( ); cleanups.push( origin.subscribeConnectionStatus((connectionState) => { - if (connectionState.status !== "connected") close(); + // The initial status arrives before the client installs transport handlers. + if (connectionState.status !== "connected") queueMicrotask(close); }), ); let opening: Promise; From da3be528e98c90ca82bf85e568da185ff36df57c Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 14:30:58 +0700 Subject: [PATCH 078/160] Open the project chooser with Cmd+N on New workspace (#9741) * feat(app): open the project chooser with the new workspace shortcut * fix(app): claim project shortcuts while projects load * fix(app): keep project shortcuts owned by the focused screen --- .../e2e/browser/new-workspace-entry.spec.ts | 16 ++++++++++++++ .../app/e2e/support/helpers/new-workspace.ts | 7 +++++-- .../app/src/screens/new-workspace-screen.tsx | 21 +++++++++++-------- .../new-workspace/form/field-trigger.tsx | 16 ++++++++++++-- .../src/screens/new-workspace/form/index.tsx | 1 + 5 files changed, 48 insertions(+), 13 deletions(-) diff --git a/packages/app/e2e/browser/new-workspace-entry.spec.ts b/packages/app/e2e/browser/new-workspace-entry.spec.ts index 90c9e19964..b61f39e000 100644 --- a/packages/app/e2e/browser/new-workspace-entry.spec.ts +++ b/packages/app/e2e/browser/new-workspace-entry.spec.ts @@ -160,6 +160,22 @@ test.describe("New workspace entry points", () => { } }); + test("Ctrl+N opens the project picker with search focused", async ({ page }) => { + const seeded: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-shortcut-" }); + + try { + await gotoAppShell(page); + await waitForSidebarHydration(page); + await openGlobalNewWorkspaceComposer(page); + + await openGlobalNewWorkspaceComposer(page); + await page.goBack(); + await openNewWorkspaceProjectPickerWithShortcut(page, "Control+N"); + } finally { + await seeded.cleanup(); + } + }); + test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({ page, }) => { diff --git a/packages/app/e2e/support/helpers/new-workspace.ts b/packages/app/e2e/support/helpers/new-workspace.ts index 23696cf4ce..d383f8cd34 100644 --- a/packages/app/e2e/support/helpers/new-workspace.ts +++ b/packages/app/e2e/support/helpers/new-workspace.ts @@ -232,8 +232,11 @@ export async function expectNewWorkspaceControlsEnabled(page: Page): Promise { - await page.keyboard.press("Control+P"); +export async function openNewWorkspaceProjectPickerWithShortcut( + page: Page, + shortcut = "Control+P", +): Promise { + await page.keyboard.press(shortcut); const searchInput = page.getByPlaceholder("Search projects"); await expect(searchInput).toBeVisible({ timeout: 30_000 }); diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index 4be45f134a..96d076224d 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -3,7 +3,7 @@ import type { CreateWorkspaceRequestOptions } from "@getpaseo/client/internal/da import type { AgentSnapshotPayload, CreationSnapshot } from "@getpaseo/protocol/messages"; import { encodeImages } from "@/utils/encode-images"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { ReactNode } from "react"; import { useIsFocused } from "expo-router/react-navigation"; import { useTranslation } from "react-i18next"; @@ -188,7 +188,10 @@ function noopChangeAttachments() {} function noopClearDraft() {} // Stable reference so the keyboard-action handler doesn't re-register each render. -const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = ["workspace.project.pick"]; +const PROJECT_PICK_ACTIONS: readonly KeyboardActionId[] = [ + "workspace.project.pick", + "workspace.new", +]; interface WorkspaceIsolationState { isolation: "local" | "worktree"; @@ -907,6 +910,7 @@ export function NewWorkspaceScreen({ const isDraftHandoffActive = useIsNewWorkspaceDraftHandoffActive({ draftId, selectedServerId }); const isStillOnCreateScreen = useNewWorkspaceScreenPresence(); const isScreenFocused = useIsFocused(); + const projectPickHandlerId = useId(); // Launch target: what the composer submits to (chat agent, or a terminal // profile). Mirrors useWorkspaceIsolation's pattern below: the derived @@ -1181,19 +1185,18 @@ export function NewWorkspaceScreen({ setProjectPickerOpen(true); }, []); - // Cmd/Ctrl+P opens the project picker with its search focused so the user can - // switch projects from the keyboard. Registered only while this screen is - // mounted, so the shortcut doesn't swallow the browser's native print - // elsewhere; gated on having projects to pick. + // On this screen, both project-pick and new-workspace open the chooser. + // Take precedence over global new-workspace navigation to preserve the draft. const handleProjectPick = useCallback(() => { openProjectPicker(); return true; }, [openProjectPicker]); useKeyboardActionHandler({ - handlerId: "new-workspace-project-pick", + handlerId: `new-workspace-project-pick:${projectPickHandlerId}`, actions: PROJECT_PICK_ACTIONS, - enabled: projectPickerOptions.length > 0, - priority: 0, + enabled: isScreenFocused, + isActive: isStillOnCreateScreen, + priority: 10, handle: handleProjectPick, }); diff --git a/packages/app/src/screens/new-workspace/form/field-trigger.tsx b/packages/app/src/screens/new-workspace/form/field-trigger.tsx index 8c0be791dc..e4ed92d8ea 100644 --- a/packages/app/src/screens/new-workspace/form/field-trigger.tsx +++ b/packages/app/src/screens/new-workspace/form/field-trigger.tsx @@ -5,6 +5,8 @@ import { ChevronDown } from "lucide-react-native"; import { ComboboxTrigger } from "@/components/ui/combobox-trigger"; import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { Shortcut } from "@/components/ui/shortcut"; +import { useShortcutKeys } from "@/hooks/use-shortcut-keys"; import { ICON_SIZE, type Theme } from "@/styles/theme"; /** @@ -97,15 +99,17 @@ export interface FieldTriggerProps extends FieldTriggerContentProps { disabled?: boolean; /** Desktop hover hint; badges only, since a field shows its label. */ tooltip?: string; + shortcutAction?: string; testID?: string; } /** A field trigger that anchors a Combobox. */ export const FieldTrigger = forwardRef(function FieldTrigger( - { accessibilityLabel, onPress, disabled = false, tooltip, testID, ...content }, + { accessibilityLabel, onPress, disabled = false, tooltip, shortcutAction, testID, ...content }, ref, ): ReactElement { const style = useFieldTriggerStyle(content.variant, disabled); + const shortcutKeys = useShortcutKeys(shortcutAction ?? null); const trigger = ( (function FieldTr {trigger} - {tooltip} + + {tooltip} + {shortcutKeys ? : null} + ); @@ -210,6 +217,11 @@ const styles = StyleSheet.create((theme) => ({ detail: { color: theme.colors.foregroundExtraMuted, }, + tooltipRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, tooltipText: { fontSize: theme.fontSize.base, color: theme.colors.popoverForeground, diff --git a/packages/app/src/screens/new-workspace/form/index.tsx b/packages/app/src/screens/new-workspace/form/index.tsx index 3b2040d389..da9368a6a7 100644 --- a/packages/app/src/screens/new-workspace/form/index.tsx +++ b/packages/app/src/screens/new-workspace/form/index.tsx @@ -209,6 +209,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement label={t("newWorkspace.fields.project")} accessibilityLabel="Workspace project" tooltip={t("newWorkspace.tooltips.project")} + shortcutAction="new-workspace" icon={projectIcon} value={project.triggerLabel} onPress={project.open} From a5015dba803e68aff1c80427de3b43b168905651 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 14:37:14 +0700 Subject: [PATCH 079/160] Pick the Usage host in Usage settings, and name it under the title (#9740) * Share the host menu row, a plain sheet subtitle, and settings rows on a menu's rail - HostMenuItem: a host as a menu option (status dot, check), extracted from the sidebar Display menu so other host pages reuse it. - SheetHeaderSubtitle: one muted, truncating line under a sheet title. - MenuSettingsRows: settings rows that share a menu surface with menu rows put their labels on the menu rows' label rail (menuLabelInset). * Pick the Usage host in Usage settings, and name it under the title The host picker leaves the top of the Usage modal body. With more than one connected host, the cog's options lead with a Host row showing the current host; it opens a page of the same surface (a flyout when wide, an in-place page with Back in the compact sheet), so no sheet opens over another. The modal names the shown host in the header subtitle, muted and truncating, so a long host name never crowds the title. With one host, neither shows. Picking a host on a phone no longer dismisses Usage: only the body is keyed by host, so the compact sheet no longer remounts (and dismisses) on a switch. * A Usage host switch shows the new host loading, not the old host's cards The host's reports list was read with a list shape, which keeps the previous key's data while the next loads. Its key differs only by host, so after a switch the old host's cards showed under the new host's name until its reports arrived. Read it as a value. The title-row controls are keyed by host too, so a failed setting change on one host never shows on another. * Put menu settings rows on the menu's existing content rail menuRowContentInset already names the menu row's label rail next to the style it mirrors; drop the duplicate menuLabelInset. --- docs/design.md | 2 +- packages/app/e2e/browser/usage-modal.spec.ts | 75 ++++++++-- .../e2e/browser/usage-sidebar-item.spec.ts | 9 +- .../e2e/support/helpers/usage-sidebar-item.ts | 13 ++ .../src/components/adaptive-modal-sheet.tsx | 13 ++ .../src/components/hosts/host-menu-item.tsx | 47 +++++++ .../app/src/components/settings/index.tsx | 1 + .../src/components/settings/row-density.tsx | 72 ++++++---- .../sidebar/display-preferences/menu.tsx | 46 +----- packages/app/src/i18n/resources/ar.ts | 1 + packages/app/src/i18n/resources/en.ts | 1 + packages/app/src/i18n/resources/es.ts | 1 + packages/app/src/i18n/resources/fr.ts | 1 + packages/app/src/i18n/resources/ja.ts | 1 + packages/app/src/i18n/resources/ko.ts | 1 + packages/app/src/i18n/resources/pt-BR.ts | 1 + packages/app/src/i18n/resources/ru.ts | 1 + packages/app/src/i18n/resources/zh-CN.ts | 1 + packages/app/src/usage/controls.tsx | 71 ++++------ packages/app/src/usage/hosts.ts | 14 ++ packages/app/src/usage/options.tsx | 133 +++++++++++++----- packages/app/src/usage/queries.ts | 9 +- packages/app/src/usage/usage-modal.tsx | 47 ++++--- 23 files changed, 382 insertions(+), 179 deletions(-) create mode 100644 packages/app/src/components/hosts/host-menu-item.tsx diff --git a/docs/design.md b/docs/design.md index 7cd1eb5191..e4acbe8af2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -136,7 +136,7 @@ Cards inside a section sit closer than sections. Rows inside a card touch — on Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows. -Rows revealed under a `` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. +Rows revealed under a `` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside ``, which puts their labels on the menu rows' label rail (`menuRowContentInset`). The whitespace is the design. diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index fc25ff00c1..8101beefbf 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -8,6 +8,7 @@ import { gotoAppShell, openSettings } from "../support/helpers/app"; import { addConnectedHostAndReload } from "../support/helpers/hosts"; import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon"; import { openSettingsSection } from "../support/helpers/settings"; +import { gate } from "../support/helpers/context-window"; import { getServerId } from "../support/helpers/server-id"; import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings"; import { @@ -33,6 +34,8 @@ import { pinRow, openUsageOptions, closeUsageOptions, + pickUsageHost, + usageModalHost, dragUsageCardAbove, expectUsageCardOrder, expectUsageOptionsFitContent, @@ -96,10 +99,6 @@ async function qaScreenshot(page: Page, name: string, target: "page" | "summary" await page.screenshot({ path: file }); } -function hostFilter(page: Page) { - return page.locator('[data-testid="usage-host-filter-trigger"]:visible'); -} - function weeklyReport(sourceId: string, usedPct: number): UsageReportEntry { return { id: `${sourceId}:a`, @@ -154,7 +153,7 @@ async function refreshUsageAndWaitForReports(page: Page, usage: UsageReportsFixt } test.describe("usage modal", () => { - test("opens from the sidebar on the host's reports, with no host filter for one host", async ({ + test("opens from the sidebar on the host's reports, with no host named for one host", async ({ page, }) => { test.setTimeout(120_000); @@ -194,7 +193,7 @@ test.describe("usage modal", () => { const group = page.getByTestId(`usage-host-${serverId}`); await expect(group.getByText("Alpha plan", { exact: true })).toBeVisible({ timeout: 10_000 }); - await expect(hostFilter(page)).toHaveCount(0); + await expect(page.getByTestId("usage-modal-host")).toHaveCount(0); await qaScreenshot(page, "usage-modal-one-host"); await expect(group.getByText("31% used")).toBeVisible(); await expect(group.getByText("Beta plan", { exact: true })).toBeVisible(); @@ -377,9 +376,11 @@ test.describe("usage modal", () => { ); try { await installUsageReportsFixture(page, { lists: [[weeklyReport("alpha", 31)]] }); + // The second host's reports wait until the test lets them through, like a slow host. + const secondaryReports = gate(); await installUsageReportsFixture(page, { port: secondary.port, - lists: [[weeklyReport("beta", 12)]], + lists: [{ stream: [secondaryReports.promise, weeklyReport("beta", 12)] }], }); await gotoAppShell(page); await addConnectedHostAndReload(page, { @@ -393,12 +394,15 @@ test.describe("usage modal", () => { await openUsageFromItem(page); await expect(page.getByTestId(`usage-host-${primaryServerId}`)).toBeVisible(); - await hostFilter(page).click(); - await page.getByTestId(`usage-host-filter-item-${secondary.serverId}`).click(); - await expect( - page.getByTestId(`usage-host-${secondary.serverId}`).getByText("12% used"), - ).toBeVisible({ timeout: 30_000 }); - await expect(hostFilter(page)).toContainText("Secondary box"); + await expect(usageModalHost(page)).toHaveText("localhost"); + await pickUsageHost(page, secondary.serverId); + // Until its reports arrive, the picked host loads; it never shows the first host's cards. + const secondaryBody = page.getByTestId(`usage-host-${secondary.serverId}`); + await expect(secondaryBody.getByText("Loading usage...")).toBeVisible(); + await expect(page.getByTestId("usage-modal-body").getByText("31% used")).toHaveCount(0); + await expect(usageModalHost(page)).toHaveText("Secondary box"); + secondaryReports.open(); + await expect(secondaryBody.getByText("12% used")).toBeVisible({ timeout: 30_000 }); await qaScreenshot(page, "usage-modal-picked-host"); await expectPinnedUsage(page, ["12% Weekly"]); @@ -417,6 +421,51 @@ test.describe("usage modal", () => { await secondary.close().catch(() => undefined); } }); + + test("on a phone, picking a host in Settings keeps Usage open on that host", async ({ page }) => { + test.setTimeout(420_000); + const longName = "build-box-eu-west-gpu-runner-02.internal"; + const secondary = await startIsolatedHostDaemon( + `srv_usage_${randomUUID().replaceAll("-", "").slice(0, 12)}`, + ); + try { + await installUsageReportsFixture(page, { lists: [[weeklyReport("alpha", 31)]] }); + await installUsageReportsFixture(page, { + port: secondary.port, + lists: [[weeklyReport("beta", 12)]], + }); + await page.setViewportSize({ width: 375, height: 812 }); + await gotoAppShell(page); + await addConnectedHostAndReload(page, { + serverId: secondary.serverId, + label: longName, + port: secondary.port, + }); + await openCompactSidebar(page); + await openUsageFromItem(page); + + await pickUsageHost(page, secondary.serverId); + + // The sheet stays up once Settings has closed over it, showing the picked host's cards. + await expect( + page.getByTestId(`usage-host-${secondary.serverId}`).getByText("12% used"), + ).toBeVisible({ timeout: 30_000 }); + await expect(usageModalHost(page)).toHaveText(longName); + // The long name truncates under the title; the title itself reads in full. + const title = page.locator('[data-testid="usage-modal-title"]:visible'); + await expect(title).toHaveText("Usage"); + expect(await title.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe( + true, + ); + const host = usageModalHost(page); + expect(await host.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe( + true, + ); + await qaScreenshot(page, "usage-phone-picked-long-host"); + } finally { + await secondary.close().catch(() => undefined); + } + }); }); const loginWindows: UsageReportEntry["report"] = { diff --git a/packages/app/e2e/browser/usage-sidebar-item.spec.ts b/packages/app/e2e/browser/usage-sidebar-item.spec.ts index 1308bdf512..1724409714 100644 --- a/packages/app/e2e/browser/usage-sidebar-item.spec.ts +++ b/packages/app/e2e/browser/usage-sidebar-item.spec.ts @@ -318,10 +318,11 @@ test.describe("Usage item", () => { await test.step("pinning Claude 5-hour and Codex weekly shows both in the Usage item", async () => { await expect(screen.getByText("Claude", { exact: true })).toBeVisible({ timeout: 10_000 }); - // One host: no host filter, as on History. - await expect(page.locator('[data-testid="usage-host-filter-trigger"]:visible')).toHaveCount( - 0, - ); + // One host: Settings has no Host row, and the title no host under it. + await expect(page.getByTestId("usage-modal-host")).toHaveCount(0); + await openUsageOptions(page); + await expect(page.getByTestId("usage-options-host")).toHaveCount(0); + await closeUsageOptions(page); await togglePin(screen, "Claude", "Weekly"); await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]); await expect(pinRow(screen, "Claude", "Session")).toBeChecked(); diff --git a/packages/app/e2e/support/helpers/usage-sidebar-item.ts b/packages/app/e2e/support/helpers/usage-sidebar-item.ts index 0c1365998e..f4d1b006e5 100644 --- a/packages/app/e2e/support/helpers/usage-sidebar-item.ts +++ b/packages/app/e2e/support/helpers/usage-sidebar-item.ts @@ -317,6 +317,19 @@ export async function openUsageOptions(page: Page): Promise { await expect(visible(page, "usage-display-used")).toBeVisible(); } +/** Picks the host Usage shows, from the Host row of its Settings. */ +export async function pickUsageHost(page: Page, serverId: string): Promise { + await openUsageOptions(page); + await visible(page, "usage-options-host").click(); + await visible(page, `usage-options-host-${serverId}`).click(); + await expect(page.getByTestId("usage-display-used")).toHaveCount(0); +} + +/** The host Usage shows, under its title; absent with a single host. */ +export function usageModalHost(page: Page): Locator { + return visible(page, "usage-modal-host"); +} + export function usageOptionsSurface(page: Page): Locator { return page .locator( diff --git a/packages/app/src/components/adaptive-modal-sheet.tsx b/packages/app/src/components/adaptive-modal-sheet.tsx index 31a605bdfc..a20c4a1a47 100644 --- a/packages/app/src/components/adaptive-modal-sheet.tsx +++ b/packages/app/src/components/adaptive-modal-sheet.tsx @@ -139,6 +139,10 @@ const styles = StyleSheet.create((theme) => ({ fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.medium, }, + subtitle: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, headerTrailing: { flexDirection: "row", alignItems: "center", @@ -421,6 +425,15 @@ function SheetHeaderBackButton({ back }: { back: SheetHeaderBack }) { ); } +/** A plain-text header subtitle: one muted line under the title that truncates, never the title. */ +export function SheetHeaderSubtitle({ text, testID }: { text: string; testID?: string }) { + return ( + + {text} + + ); +} + export function SheetHeaderView({ header, onClose, diff --git a/packages/app/src/components/hosts/host-menu-item.tsx b/packages/app/src/components/hosts/host-menu-item.tsx new file mode 100644 index 0000000000..6c88152d2a --- /dev/null +++ b/packages/app/src/components/hosts/host-menu-item.tsx @@ -0,0 +1,47 @@ +import { useCallback, useMemo, type ReactElement } from "react"; +import { View } from "react-native"; +import { HostStatusDot } from "@/components/host-status-dot"; +import { MenuItem } from "@/components/ui/menu"; + +interface HostMenuItemProps { + serverId: string; + label: string; + selected: boolean; + onSelect: (serverId: string) => void; + /** Off for a multi-select page, where choosing a host is one of several toggles. */ + closeOnSelect?: boolean; + testID?: string; + statusTestID?: string; +} + +/** A host as a menu option: its live status dot leads, and the chosen host carries the check. */ +export function HostMenuItem({ + serverId, + label, + selected, + onSelect, + closeOnSelect = true, + testID, + statusTestID, +}: HostMenuItemProps): ReactElement { + const handleSelect = useCallback(() => onSelect(serverId), [onSelect, serverId]); + const leading = useMemo( + () => ( + + + + ), + [serverId, statusTestID], + ); + return ( + + {label} + + ); +} diff --git a/packages/app/src/components/settings/index.tsx b/packages/app/src/components/settings/index.tsx index 567b13bd4e..567becfd01 100644 --- a/packages/app/src/components/settings/index.tsx +++ b/packages/app/src/components/settings/index.tsx @@ -31,6 +31,7 @@ export { SettingsSection } from "./headings/settings-section"; export { SettingsCollapsibleRow } from "./collapsible-row"; export { SettingsDetailRow } from "./detail-row"; export { SettingsInfoTip } from "./headings/settings-info-tip"; +export { MenuSettingsRows } from "./row-density"; /** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */ interface AppRowExtras { diff --git a/packages/app/src/components/settings/row-density.tsx b/packages/app/src/components/settings/row-density.tsx index 3682899624..25c360591d 100644 --- a/packages/app/src/components/settings/row-density.tsx +++ b/packages/app/src/components/settings/row-density.tsx @@ -2,16 +2,27 @@ import { createContext, useContext, useMemo, type ReactNode } from "react"; import type { StyleProp, TextStyle, ViewStyle } from "react-native"; import { StyleSheet } from "react-native-unistyles"; import { CONTROL_HEIGHTS, mapLayout, type ControlSize } from "@/components/ui/control-geometry"; +import { menuRowContentInset } from "@/components/ui/menu"; import { settingsStyles } from "@/styles/settings"; -// Rows revealed under a collapsible row belong to it, so they sit one step smaller than the rows -// of the card: tighter padding, smaller text, smaller controls. The container decides; a row -// never knows on its own that it is nested. -const NestedRowsContext = createContext(false); +// The container decides how its rows lay out; a row never knows on its own where it is. +// +// - card: the rows of a settings card. +// - nested: rows revealed under a collapsible row belong to it, so they sit one step smaller than +// the rows of the card: tighter padding, smaller text, smaller controls. +// - menu: rows that share a menu surface with menu rows put their labels on the menu's label rail. +type RowPlacement = "card" | "nested" | "menu"; + +const RowPlacementContext = createContext("card"); export function NestedSettingsRows({ children }: { children: ReactNode }) { - return {children}; + return {children}; +} + +/** Settings rows rendered in a menu surface, alongside menu rows. */ +export function MenuSettingsRows({ children }: { children: ReactNode }) { + return {children}; } export interface SettingsRowLayout { @@ -22,26 +33,36 @@ export interface SettingsRowLayout { controlSize: ControlSize; } -/** How a row lays out where it is rendered: in a card, or nested under a collapsible row. */ +function layoutFor(placement: RowPlacement): SettingsRowLayout { + switch (placement) { + case "nested": + return { + row: [settingsStyles.row, styles.nestedRow], + title: [settingsStyles.rowTitle, styles.nestedText], + hint: [settingsStyles.rowHint, styles.nestedText], + controlSize: "sm", + }; + case "menu": + return { + row: [settingsStyles.row, styles.menuRow], + title: settingsStyles.rowTitle, + hint: settingsStyles.rowHint, + controlSize: "md", + }; + case "card": + return { + row: settingsStyles.row, + title: settingsStyles.rowTitle, + hint: settingsStyles.rowHint, + controlSize: "md", + }; + } +} + +/** How a row lays out where it is rendered: in a card, nested under a collapsible row, or in a menu. */ export function useSettingsRowLayout(): SettingsRowLayout { - const nested = useContext(NestedRowsContext); - return useMemo( - () => - nested - ? { - row: [settingsStyles.row, styles.nestedRow], - title: [settingsStyles.rowTitle, styles.nestedText], - hint: [settingsStyles.rowHint, styles.nestedText], - controlSize: "sm", - } - : { - row: settingsStyles.row, - title: settingsStyles.rowTitle, - hint: settingsStyles.rowHint, - controlSize: "md", - }, - [nested], - ); + const placement = useContext(RowPlacementContext); + return useMemo(() => layoutFor(placement), [placement]); } const styles = StyleSheet.create((theme) => ({ @@ -54,4 +75,7 @@ const styles = StyleSheet.create((theme) => ({ nestedText: { fontSize: theme.fontSize.sm, }, + menuRow: { + paddingHorizontal: menuRowContentInset(theme), + }, })); diff --git a/packages/app/src/components/sidebar/display-preferences/menu.tsx b/packages/app/src/components/sidebar/display-preferences/menu.tsx index 93a31c3c0d..7d56275ce7 100644 --- a/packages/app/src/components/sidebar/display-preferences/menu.tsx +++ b/packages/app/src/components/sidebar/display-preferences/menu.tsx @@ -7,7 +7,7 @@ import { type ReactNode, } from "react"; import { useTranslation } from "react-i18next"; -import { View, type PressableStateCallbackType } from "react-native"; +import type { PressableStateCallbackType } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { Captions, @@ -35,7 +35,7 @@ import { MenuTrigger, type MenuPageDefinition, } from "@/components/ui/menu"; -import { HostStatusDot } from "@/components/host-status-dot"; +import { HostMenuItem } from "@/components/hosts/host-menu-item"; import { isWeb } from "@/constants/platform"; import { useHosts } from "@/runtime/host-runtime"; import { useSidebarModel } from "@/components/sidebar/sidebar-model"; @@ -813,53 +813,21 @@ function HostFilterPage({ {t("sidebar.display.hostFilter.all")} {hosts.map((host) => ( - ))} ); } -/** The one option row whose mark is live state rather than an icon. */ -function HostFilterItem({ - serverId, - label, - selected, - onToggle, -}: { - serverId: string; - label: string; - selected: boolean; - onToggle: (serverId: string) => void; -}): ReactElement { - const handleSelect = useCallback(() => onToggle(serverId), [onToggle, serverId]); - const leading = useMemo( - () => ( - - - - ), - [serverId], - ); - - return ( - - {label} - - ); -} - const styles = StyleSheet.create((theme) => ({ trigger: { width: 28, diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index c712619f51..51250d04b1 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2210,6 +2210,7 @@ export const ar: TranslationResources = { turnOn: "تشغيل", options: "الإعدادات", + host: "المضيف", refreshFailed: "تعذّر تحديث الاستخدام", noHosts: "لا توجد مضيفات متصلة", agentError: "تعذّر تحميل الاستخدام: {{reason}}", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index dd4c8ca104..3cc5de9da3 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2236,6 +2236,7 @@ export const en = { turnOn: "Turn on", options: "Settings", + host: "Host", refreshFailed: "Unable to refresh usage", noHosts: "No connected hosts", agentError: "Unable to load usage: {{reason}}", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index dc675d3091..6f3c051837 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2259,6 +2259,7 @@ export const es: TranslationResources = { turnOn: "Activar", options: "Configuración", + host: "Host", refreshFailed: "No se pudo actualizar el uso", noHosts: "No hay hosts conectados", agentError: "No se pudo cargar el uso: {{reason}}", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index e796aa767c..022bc3dd4c 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2260,6 +2260,7 @@ export const fr: TranslationResources = { turnOn: "Activer", options: "Paramètres", + host: "Hôte", refreshFailed: "Impossible d’actualiser l’utilisation", noHosts: "Aucun hôte connecté", agentError: "Impossible de charger l’utilisation : {{reason}}", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 2b6c655889..75f2d55795 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2233,6 +2233,7 @@ export const ja: TranslationResources = { turnOn: "オンにする", options: "設定", + host: "ホスト", refreshFailed: "使用状況を更新できません", noHosts: "接続中のホストがありません", agentError: "使用状況を読み込めません: {{reason}}", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index fc1cfec2c1..d4ec87ad8e 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2221,6 +2221,7 @@ export const ko: TranslationResources = { turnOn: "켜기", options: "설정", + host: "호스트", refreshFailed: "사용량을 새로 고칠 수 없습니다", noHosts: "연결된 호스트가 없습니다", agentError: "사용량을 불러올 수 없습니다: {{reason}}", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 2e2a3d144d..54516fc2de 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2244,6 +2244,7 @@ export const ptBR: TranslationResources = { turnOn: "Ativar", options: "Configurações", + host: "Host", refreshFailed: "Não foi possível atualizar o uso", noHosts: "Nenhum host conectado", agentError: "Não foi possível carregar o uso: {{reason}}", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index dd6c52eee7..9ee2f1746c 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2245,6 +2245,7 @@ export const ru: TranslationResources = { turnOn: "Включить", options: "Настройки", + host: "Хост", refreshFailed: "Не удалось обновить использование", noHosts: "Нет подключённых хостов", agentError: "Не удалось загрузить использование: {{reason}}", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index ae6592a73a..e2b6762830 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2187,6 +2187,7 @@ export const zhCN: TranslationResources = { turnOn: "开启", options: "设置", + host: "主机", refreshFailed: "无法刷新用量", noHosts: "没有已连接的主机", agentError: "无法加载用量:{{reason}}", diff --git a/packages/app/src/usage/controls.tsx b/packages/app/src/usage/controls.tsx index ffe51271e6..b4637778c7 100644 --- a/packages/app/src/usage/controls.tsx +++ b/packages/app/src/usage/controls.tsx @@ -1,60 +1,42 @@ import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; -import { HostFilter } from "@/components/hosts/host-filter"; import { useMemo, type ReactElement } from "react"; import { UsageRefreshButton } from "./refresh-button"; import { UsageOptions } from "./options"; -import type { UsageHost } from "./model"; +import { hasHostChoice, type UsageHostSelection } from "./hosts"; import { useHostUsage } from "./queries"; import type { UsageView } from "./types"; -/** The hosts to choose between, and which one is shown. */ -export interface UsageHostSelection { - hosts: UsageHost[]; - serverId: string; - onSelect: (serverId: string) => void; -} - /** * The controls on the right of every usage title row: Refresh all and the Settings cog. A host - * that cannot report usage has none. + * that cannot report usage has none, unless there is another host to switch to: the host choice + * lives in the cog, so the cog stays. */ export function UsageControls({ view, serverId, onRefresh, + hostSelection, }: { view: UsageView; serverId: string; onRefresh: () => void; + hostSelection?: UsageHostSelection; }) { const busy = view.kind === "loading" || (view.kind === "ready" && view.isRefreshing); - if (view.kind === "unavailable") return null; + if (!hasUsageControls(view, hostSelection)) return null; return ( - {view.kind === "off" ? null : } - + {view.kind === "off" || view.kind === "unavailable" ? null : ( + + )} + ); } -/** The host whose usage shows, when there is more than one to choose from. */ -function UsageHostFilter({ hostSelection }: { hostSelection: UsageHostSelection }) { - return ( - - ); -} - -function usageHostOptionTestID(serverId: string): string { - return `usage-host-filter-item-${serverId}`; +function hasUsageControls(view: UsageView, hostSelection: UsageHostSelection | undefined): boolean { + return view.kind !== "unavailable" || hasHostChoice(hostSelection); } const styles = StyleSheet.create((theme) => ({ @@ -67,28 +49,29 @@ const styles = StyleSheet.create((theme) => ({ })); /** - * One host’s usage for the Usage modal: its title-row controls, null when there is nothing to - * control so the header leaves no empty island, and the host filter for the top of the body, null - * with a single host. + * One host’s usage for the Usage modal, and its title-row controls: null when there is nothing to + * control, so the header leaves no empty island. */ export function useHostUsageWithControls(hostSelection: UsageHostSelection): { view: UsageView; refresh: () => void; controls: ReactElement | null; - hostFilter: ReactElement | null; } { const { view, refresh } = useHostUsage(hostSelection.serverId); const controls = useMemo( () => - view.kind === "unavailable" ? null : ( - - ), - [hostSelection.serverId, refresh, view], + hasUsageControls(view, hostSelection) ? ( + // Keyed by host, so state one host's controls hold, such as a failed setting change, + // never shows on another's. + + ) : null, + [hostSelection, refresh, view], ); - const hostFilter = useMemo( - () => - hostSelection.hosts.length > 1 ? : null, - [hostSelection], - ); - return { view, refresh, controls, hostFilter }; + return { view, refresh, controls }; } diff --git a/packages/app/src/usage/hosts.ts b/packages/app/src/usage/hosts.ts index dba21dc316..f07c6d7dcd 100644 --- a/packages/app/src/usage/hosts.ts +++ b/packages/app/src/usage/hosts.ts @@ -57,3 +57,17 @@ export function useUsageHostSelection(): { ); return { serverId: resolveUsageModalHostId(choice), connectedHosts, select }; } + +/** The hosts to choose between, and which one is shown. */ +export interface UsageHostSelection { + hosts: UsageHost[]; + serverId: string; + onSelect: (serverId: string) => void; +} + +/** Whether there is more than one host to show usage for. */ +export function hasHostChoice( + hostSelection: UsageHostSelection | undefined, +): hostSelection is UsageHostSelection { + return (hostSelection?.hosts.length ?? 0) > 1; +} diff --git a/packages/app/src/usage/options.tsx b/packages/app/src/usage/options.tsx index 9e12517da5..53277eb20a 100644 --- a/packages/app/src/usage/options.tsx +++ b/packages/app/src/usage/options.tsx @@ -2,14 +2,22 @@ import { useTranslation } from "react-i18next"; import { View } from "react-native"; import { Settings } from "lucide-react-native"; import { withUnistyles } from "react-native-unistyles"; -import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu"; +import { useMemo } from "react"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuSubTrigger, + type MenuPageDefinition, +} from "@/components/ui/dropdown-menu"; +import { HostMenuItem } from "@/components/hosts/host-menu-item"; +import { getHostPickerLabel } from "@/components/hosts/host-picker"; import { mutedIconColorMapping, useIconButtonChromeGlyphSize, } from "@/components/ui/icon-button-chrome"; import { ToolbarButton } from "@/components/ui/pane-content-toolbar"; import { useIsCompactFormFactor } from "@/constants/layout"; -import { SettingsRow, SettingsSwitch } from "@/components/settings"; +import { MenuSettingsRows, SettingsRow, SettingsSwitch } from "@/components/settings"; import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; import { Alert } from "@/components/ui/alert"; import { useHosts } from "@/runtime/host-runtime"; @@ -17,12 +25,25 @@ import { settingsStyles } from "@/styles/settings"; import { useUsageSetting } from "./setting"; import { useUsageDisplay } from "./display"; import { useUsageInSidebar } from "./in-sidebar"; +import { hasHostChoice, type UsageHostSelection } from "./hosts"; import type { UsageDisplayAs } from "./preferences"; const ThemedSettings = withUnistyles(Settings); -/** The shared usage preferences, opened from a cog as a popover or compact sheet. */ -export function UsageOptions({ serverId }: { serverId: string | null }) { +const HOST_PAGE = "host"; + +/** + * The shared usage preferences, opened from a cog as a popover or compact sheet. With more than + * one host, it leads with the host whose usage shows: the row reads as the current host, and the + * hosts are a page of the same surface, so a compact sheet never opens a second sheet over it. + */ +export function UsageOptions({ + serverId, + hostSelection, +}: { + serverId: string | null; + hostSelection?: UsageHostSelection; +}) { const setting = useUsageSetting(serverId); const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId; const { t } = useTranslation(); @@ -38,6 +59,20 @@ export function UsageOptions({ serverId }: { serverId: string | null }) { const glyphSize = useIconButtonChromeGlyphSize("small", compact); const { display } = useUsageDisplay([]); const { inSidebar, setInSidebar } = useUsageInSidebar(); + const hostChoice = hasHostChoice(hostSelection) ? hostSelection : null; + const pages = useMemo( + () => + hostChoice + ? [ + { + id: HOST_PAGE, + title: t("providerUsage.host"), + content: , + }, + ] + : undefined, + [hostChoice, t], + ); return ( - - {setting.error ? : null} - {setting.supported ? ( - - ) : null} - - - - - - + {t("providerUsage.host")} + + ) : null} + + + {setting.error ? : null} + {setting.supported ? ( + - - + ) : null} + + + + + + + + + ); } + +function UsageHostPage({ hostSelection }: { hostSelection: UsageHostSelection }) { + return ( + <> + {hostSelection.hosts.map((host) => ( + + ))} + + ); +} diff --git a/packages/app/src/usage/queries.ts b/packages/app/src/usage/queries.ts index 26a7fa62ea..702f115253 100644 --- a/packages/app/src/usage/queries.ts +++ b/packages/app/src/usage/queries.ts @@ -43,6 +43,11 @@ function hostUsageQueryKey(serverId: string) { return ["usage", serverId] as const; } +/** + * A host's own reports. The key differs only by host, so it is read with `dataShape: "value"`: + * a list shape keeps the previous key's data while the next one loads, which would show one host's + * reports as another's. + */ function usageReportsQueryKey(serverId: string) { return [...hostUsageQueryKey(serverId), "reports"] as const; } @@ -150,7 +155,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () = queryKey: usageReportsQueryKey(serverId), queryFn: () => listReports(queryClient, serverId), enabled: isConnected && isSupported && setting.enabled, - dataShape: "list", + dataShape: "value", staleTimeMs: REPORTS_STALE_TIME_MS, }); const refresh = useCallback(() => { @@ -189,7 +194,7 @@ export function useUsageHostReports({ enabled: setting.enabled, queryKey: usageReportsQueryKey(serverId ?? ""), queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken, - dataShape: "list", + dataShape: "value", staleTimeMs: REPORTS_STALE_TIME_MS, refetchInterval: shouldPoll ? REPORTS_REFETCH_INTERVAL_MS : false, }); diff --git a/packages/app/src/usage/usage-modal.tsx b/packages/app/src/usage/usage-modal.tsx index f78b9ac3e4..d93bea8b1b 100644 --- a/packages/app/src/usage/usage-modal.tsx +++ b/packages/app/src/usage/usage-modal.tsx @@ -1,11 +1,12 @@ import { useMemo, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { View } from "react-native"; -import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet"; +import { AdaptiveModalSheet, SheetHeaderSubtitle } from "@/components/adaptive-modal-sheet"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; import { useHostUsageWithControls } from "./controls"; import { useUsageDisplay } from "./display"; -import { useUsageHostSelection } from "./hosts"; +import { getHostPickerLabel } from "@/components/hosts/host-picker"; +import { hasHostChoice, useUsageHostSelection } from "./hosts"; import type { UsageHost } from "./model"; import { UsageBody, UsageMessage } from "./usage-section"; @@ -17,8 +18,8 @@ interface UsageModalProps { /** * Usage over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. It - * shows the usage host's reports with pins, Refresh all and Settings in its title row, and the - * host filter at the top of its body. + * shows the usage host's reports with pins, and Refresh all and Settings in its title row. With more + * than one host, the host shown is the title's subtitle, and Settings is where it is picked. */ export function UsageModal(props: UsageModalProps) { const { t } = useTranslation(); @@ -30,15 +31,8 @@ export function UsageModal(props: UsageModalProps) { ); } - // Keyed by host so a refresh in flight on one host never shows on another's cards. return ( - + ); } @@ -56,11 +50,17 @@ function HostUsageModal({ () => ({ hosts, serverId, onSelect: onSelectHost }), [hosts, onSelectHost, serverId], ); - const { view, refresh, controls, hostFilter } = useHostUsageWithControls(hostSelection); + const { view, refresh, controls } = useHostUsageWithControls(hostSelection); const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); + const hostLabel = hasHostChoice(hostSelection) + ? getHostPickerLabel(hostSelection.hosts, hostSelection.serverId) + : undefined; return ( - - + + {/* Keyed by host so state the cards hold, such as a refresh in flight, never shows on another + host's cards. The frame is not keyed: remounting it would dismiss a compact sheet, and Usage + with it. */} + @@ -72,12 +72,22 @@ function UsageModalFrame({ onClose, onDismiss, actions, - hostFilter, + subtitle, children, -}: UsageModalProps & { actions?: ReactNode; hostFilter?: ReactNode; children: ReactNode }) { +}: UsageModalProps & { actions?: ReactNode; subtitle?: string; children: ReactNode }) { const { t } = useTranslation(); const title = t(builtinSidebarNavLabelKey("usage")); - const header = useMemo(() => ({ title, actions }), [actions, title]); + const header = useMemo( + () => ({ + title, + titleTestID: "usage-modal-title", + subtitle: subtitle ? ( + + ) : undefined, + actions, + }), + [actions, subtitle, title], + ); return ( - {hostFilter} {children} ); From fe59a6c1a266c9f83abf7bf564c913a709f5ac07 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:34:41 +0000 Subject: [PATCH 080/160] Keep an archived worktree restorable when reconciliation races its removal (#9753) Archiving a worktree archives its record, then deletes the directory. A reconciliation pass that listed the workspace before the archive went on to read its checkout while the directory was being deleted, saw no Git checkout, and wrote kind "directory" onto the archived record. Undo then refused to recreate the worktree: "The archived workspace directory no longer exists and cannot be recreated." Reconciliation now skips a record that is archived when it re-reads it and when it writes the update, as it already does when listing. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../workspace-reconciliation-service.test.ts | 78 ++++++++++++++++++- .../workspace-reconciliation-service.ts | 18 ++++- 2 files changed, 91 insertions(+), 5 deletions(-) diff --git a/packages/server/src/server/workspace-reconciliation-service.test.ts b/packages/server/src/server/workspace-reconciliation-service.test.ts index 3d0057bcae..6f34b69853 100644 --- a/packages/server/src/server/workspace-reconciliation-service.test.ts +++ b/packages/server/src/server/workspace-reconciliation-service.test.ts @@ -641,7 +641,83 @@ describe("WorkspaceReconciliationService", () => { expect(workspaces.get("w1")).toMatchObject({ archivedAt, - branch: "new-branch", + branch: "old-branch", + }); + }); + + test("keeps a worktree restorable when it is archived while its checkout read is in flight", async () => { + const projectRoot = "/reconcile/archive-worktree/root"; + const worktreeCwd = "/reconcile/archive-worktree/worktrees/feature"; + const { projects, workspaces, projectRegistry, workspaceRegistry } = createTestRegistries(); + projects.set( + "p1", + createPersistedProjectRecord({ + projectId: "p1", + rootPath: projectRoot, + projectKey: deriveProjectKey({ + rootPath: projectRoot, + remoteUrl: null, + worktreeRoot: projectRoot, + mainRepoRoot: null, + }), + kind: "git", + displayName: "archive-worktree", + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + workspaces.set( + "w1", + createPersistedWorkspaceRecord({ + workspaceId: "w1", + projectId: "p1", + cwd: worktreeCwd, + kind: "worktree", + displayName: "feature", + branch: "feature", + worktreeRoot: worktreeCwd, + isPaseoOwnedWorktree: true, + mainRepoRoot: projectRoot, + createdAt: timestamp, + updatedAt: timestamp, + }), + ); + const worktreeReadStarted = deferred(); + const allowWorktreeRead = deferred(); + const service = new WorkspaceReconciliationService({ + projectRegistry, + workspaceRegistry, + logger: createTestLogger(), + inspectDirectory: async () => "directory", + workspaceGitService: { + getCheckout: async (cwd) => { + if (cwd === projectRoot) { + return createCheckout(cwd, { isGit: true, currentBranch: "main", worktreeRoot: cwd }); + } + worktreeReadStarted.resolve(); + await allowWorktreeRead.promise; + // Archive deletes the worktree after archiving its record, so a read that + // lands mid-deletion no longer sees a Git checkout there. + return createCheckout(cwd); + }, + }, + }); + + const reconciliation = service.runOnce(); + await worktreeReadStarted.promise; + const archivedAt = "2025-01-02T00:00:00.000Z"; + await workspaceRegistry.archive("w1", archivedAt); + allowWorktreeRead.resolve(); + const result = await reconciliation; + + expect(result.changesApplied).toEqual([]); + expect(workspaces.get("w1")).toMatchObject({ + archivedAt, + kind: "worktree", + branch: "feature", + worktreeRoot: worktreeCwd, + isPaseoOwnedWorktree: true, + mainRepoRoot: projectRoot, }); }); diff --git a/packages/server/src/server/workspace-reconciliation-service.ts b/packages/server/src/server/workspace-reconciliation-service.ts index f1fe5c9444..84a0221a7f 100644 --- a/packages/server/src/server/workspace-reconciliation-service.ts +++ b/packages/server/src/server/workspace-reconciliation-service.ts @@ -396,8 +396,7 @@ export class WorkspaceReconciliationService { const workspaceCheckouts = await Promise.all( siblings.map(async (workspace) => { const current = await this.workspaceRegistry.get(workspace.workspaceId); - if (!current || current.cwd !== workspace.cwd || current.projectId !== workspace.projectId) - return null; + if (!current || !isStillReconcilable(current, workspace)) return null; return { workspace: current, checkout: await readCheckout(current.cwd) }; }), ); @@ -446,8 +445,9 @@ export class WorkspaceReconciliationService { return; let fields: Partial | null = null; await this.workspaceRegistry.update(workspace.workspaceId, (current) => { - if (current.cwd !== workspace.cwd || current.projectId !== workspace.projectId) - return current; + // Archive removes a worktree only after archiving its record, so a read + // that raced the archive may have seen the directory mid-deletion. + if (!isStillReconcilable(current, workspace)) return current; const update = reconcileWorkspacePlacement({ workspace: current, checkout: wsGit, @@ -685,3 +685,13 @@ async function mapBounded(items: T[], visit: (item: T) => Promise): Pro ); return results; } + +/** An archived record keeps the placement its restore depends on. */ +function isStillReconcilable( + current: PersistedWorkspaceRecord, + scanned: PersistedWorkspaceRecord, +): boolean { + return ( + !current.archivedAt && current.cwd === scanned.cwd && current.projectId === scanned.projectId + ); +} From 96a143efe90ca3fd3737fe675c0e5fb29455827d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 16:39:08 +0700 Subject: [PATCH 081/160] Show orchestration and remote in the homepage hero (#9750) * feat(website): show orchestration and remote in an animated hero mockup The homepage hero now has five scenes: Orchestration, Remote, Code review, Pull requests, and Plugins. Orchestration and Remote were missing before, and they are what separates Paseo from a single-machine agent app. Orchestration, Code review, and Plugins play a script once the mockup is 60% on screen, and again on every pill click. Each script is a list of beats (wait, click, type, user, agent, tools, turnEnd, mark) laid end to end. A non-React clock owns the time and components read one fact at a time, so only the part that changed renders. A pointer clicks the composer, the subagents pill, and the review controls. Reduced motion shows each finished scene. The right panel is 300px for the file tree and grows to 424px for the pull request and the plugin. Picking a pill scrolls the pills and the mockup into view. * fix(website): keep a picked hero scene playing and scroll it into view the same in every browser A pill click before the mockup was 60% on screen played its scene, and then the visibility start played the same scene again from zero. The player now starts the opening scene only when no scene has played, and the hero stops the clock when it unmounts. Picking a pill used scrollIntoView with `nearest`. For an element taller than the window, each engine picks its own edge, and WebKit left the pill 25% visible in a 1280x600 window. The hero now computes the scroll itself: the least that shows the pills and the mockup, never past the pills at the top. * fix(website): scroll a picked hero scene by where the hero settles, not where it slides The hero slides up 40px as it enters. A pill clicked during the slide measured the frame 40px low, so the scroll stopped with the pills 24px above the window once the slide ended. This was the cause of the WebKit failure in CI. The earlier explanation, that engines differ on scrollIntoView, was wrong. The scroll now measures the frame from layout offsets, which ignore the slide. The test holds the page clock so the slide stays at its first frame. * test(website): hold the hero's slide-in still when a pill is picked during it The test stopped the page timers but let time run, so it caught the bug only when the click landed in the first second after load. It now pauses the clock before the page loads and checks that the slide is still in progress at the click. * test(website): put the hero's 40px slide-in back by hand in the slide-in test The test held the page clock to freeze the slide, but WebKit did not hold it, so the test failed on its own precondition. It now waits for the slide to end, puts the 40px offset on the container, picks a scene, and removes the offset. Reduced motion makes the scroll instant, so the test asserts the result without waiting for a scroll to settle. * fix(website): start the opening hero scene in a window shorter than most of the mockup The scene waited for 60% of the mockup to be on screen. A window shorter than 60% of the mockup, such as a wide browser with devtools docked at the bottom, never reaches that, so the scene never started. It now starts when a line 60% of the way down the mockup is on screen. That is the same moment in an ordinary window, and a short window reaches it as the page scrolls past. --- packages/website/e2e/mockups.spec.ts | 223 +++++++++- .../website/src/components/hero-mockup.tsx | 93 ++++- .../website/src/components/landing-page.tsx | 4 +- .../website/src/components/mockup/atoms.tsx | 7 + .../website/src/components/mockup/chat.tsx | 390 +++++++++++++----- .../website/src/components/mockup/diff.tsx | 46 ++- .../website/src/components/mockup/geometry.ts | 15 +- .../website/src/components/mockup/hosts.tsx | 157 +++++++ .../website/src/components/mockup/icons.tsx | 64 +++ .../website/src/components/mockup/index.ts | 7 +- .../src/components/mockup/orchestration.ts | 102 +++++ .../website/src/components/mockup/panes.tsx | 79 +++- .../src/components/mockup/player.test.ts | 71 ++++ .../website/src/components/mockup/player.ts | 130 ++++++ .../src/components/mockup/plugin-build.ts | 55 +++ .../website/src/components/mockup/pointer.tsx | 45 ++ .../src/components/mockup/providers.ts | 11 + .../src/components/mockup/review-thread.tsx | 231 +++++++++++ .../website/src/components/mockup/review.ts | 54 +++ .../src/components/mockup/right-panel.tsx | 71 +++- .../src/components/mockup/script.test.ts | 177 ++++++++ .../website/src/components/mockup/script.ts | 267 ++++++++++++ .../website/src/components/mockup/sidebar.tsx | 47 ++- .../website/src/components/mockup/states.ts | 10 +- .../src/components/mockup/titlebar.tsx | 16 +- .../website/src/components/mockup/window.tsx | 176 ++++++-- packages/website/src/i18n/resources/en.json | 20 +- .../website/src/i18n/resources/zh-CN.json | 20 +- packages/website/src/styles.css | 4 + 29 files changed, 2365 insertions(+), 227 deletions(-) create mode 100644 packages/website/src/components/mockup/hosts.tsx create mode 100644 packages/website/src/components/mockup/orchestration.ts create mode 100644 packages/website/src/components/mockup/player.test.ts create mode 100644 packages/website/src/components/mockup/player.ts create mode 100644 packages/website/src/components/mockup/plugin-build.ts create mode 100644 packages/website/src/components/mockup/pointer.tsx create mode 100644 packages/website/src/components/mockup/providers.ts create mode 100644 packages/website/src/components/mockup/review-thread.tsx create mode 100644 packages/website/src/components/mockup/review.ts create mode 100644 packages/website/src/components/mockup/script.test.ts create mode 100644 packages/website/src/components/mockup/script.ts diff --git a/packages/website/e2e/mockups.spec.ts b/packages/website/e2e/mockups.spec.ts index 82a440fa1c..8ae8a9c272 100644 --- a/packages/website/e2e/mockups.spec.ts +++ b/packages/website/e2e/mockups.spec.ts @@ -6,7 +6,7 @@ const desktopName = async function openHomepage(page: Page) { await page.setViewportSize({ width: 1512, height: 930 }); await page.goto("/"); - await expect(page.getByRole("button", { name: "Parallel agents", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Orchestration", exact: true })).toBeVisible(); } async function viewPhones(page: Page) { @@ -60,6 +60,227 @@ test("desktop mockup corners shrink in proportion on a phone", async ({ page }) await expect.poll(() => cornerProportion(mockup)).toBeCloseTo(desktopCorner, 3); }); +/** Each hero pill and one thing only its finished scene draws. */ +const HERO_SCENES = [ + { pill: "Orchestration", shows: "Pi · GLM-5.2" }, + { pill: "Remote", shows: "Tailscale" }, + { pill: "Code review", shows: "Feedback sent to Codex" }, + { pill: "Pull requests", shows: "https://github.com/getpaseo/paseo/pull/3981" }, + { pill: "Plugins", shows: "app-tests (macos)" }, +]; + +/** Clicks a hero pill until its scene starts. A click before hydration selects nothing. */ +async function playScene(page: Page, pill: string, opensWith: Locator) { + await expect(async () => { + await page.getByRole("button", { name: pill, exact: true }).click(); + await expect(opensWith).toBeVisible({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); +} + +test("each hero pill shows its finished scene when motion is reduced", async ({ page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await mockup.scrollIntoViewIfNeeded(); + // Last to first, so the opening scene is also reached by a click. + for (const scene of HERO_SCENES.toReversed()) { + await playScene(page, scene.pill, mockup.getByText(scene.shows, { exact: true }).first()); + } +}); + +test("the hero opens on orchestration across providers and machines", async ({ page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(page.getByRole("button", { name: "Orchestration", exact: true })).toHaveAttribute( + "aria-pressed", + "true", + ); + for (const agent of ["Codex · GPT-5.6-Sol", "OpenCode · Kimi K3", "Pi · GLM-5.2"]) { + await expect(mockup.getByText(agent, { exact: true })).toBeVisible(); + } + // The task on another machine carries that host's badge in its tool call and its subagent row. + for (const remoteTask of ["OpenCode · fix/menu-bar-icon", "OpenCode · Kimi K3"]) { + const row = mockup.getByText(remoteTask, { exact: true }).locator("xpath=.."); + await expect(row.getByText("mac-mini", { exact: true })).toBeVisible(); + } +}); + +test("the orchestration scene plays from an empty chat to the open roster of subagents", async ({ + page, +}) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const composer = mockup.getByText("Message the agent, tag @files, or use /commands and /skills"); + await playScene(page, "Orchestration", composer); + await expect(mockup.getByText("Create agent", { exact: true })).toHaveCount(0); + await expect(mockup.getByText("3 subagents", { exact: true })).toHaveCount(0); + + // The orchestrator lists the issues and the agent profiles, launches three agents and says so, + // then the pointer clicks the pill and the roster opens. + await expect(mockup.getByText("3 subagents", { exact: true })).toBeVisible({ timeout: 20_000 }); + await expect(mockup.getByText("gh issue list --label ready", { exact: true })).toBeVisible(); + await expect(mockup.getByText("List agent profiles", { exact: true })).toBeVisible(); + await expect( + mockup.getByText( + "I will launch the UI agent on your mac-mini, because that issue is specific to macOS.", + ), + ).toBeVisible(); + await expect(mockup.getByText("Create agent", { exact: true })).toHaveCount(3); + await expect( + mockup.getByText("All three are launched. Paseo will notify me when each one finishes."), + ).toBeVisible(); + await expect(mockup.getByText("Pi · GLM-5.2", { exact: true })).toBeVisible({ timeout: 10_000 }); +}); + +test("the opening scene waits until most of the mockup is on screen", async ({ page }) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); + await expect(mockup).not.toBeInViewport({ ratio: 0.6 }); + + // A scene that started at load sends the request within three seconds. + await page.waitForTimeout(4500); + await expect(request).toHaveCount(0); + + await mockup.scrollIntoViewIfNeeded(); + await expect(request).toBeVisible({ timeout: 10_000 }); +}); + +test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => { + await page.setViewportSize({ width: 1400, height: 400 }); + await page.goto("/"); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); + await mockup.scrollIntoViewIfNeeded(); + await expect(mockup).not.toBeInViewport({ ratio: 0.6 }); + await expect(request).toBeVisible({ timeout: 10_000 }); +}); + +test("the plugins scene installs the panel, then changes it on request", async ({ page }) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const changesPanel = mockup.getByText("Uncommitted", { exact: true }); + const pluginPanel = mockup.getByText("Recently merged", { exact: true }); + const failingCheck = mockup.getByText("app-tests (macos)", { exact: true }); + await playScene(page, "Plugins", page.getByRole("button", { name: "Plugins", pressed: true })); + await expect(changesPanel).toBeVisible(); + await expect(pluginPanel).toHaveCount(0); + + // Installing the plugin swaps the docked panel for the one the agent built. + await expect(pluginPanel).toBeVisible({ timeout: 20_000 }); + await expect(changesPanel).toHaveCount(0); + await expect(failingCheck).toHaveCount(0); + + // The second request reloads the plugin and the open panel lists the failing check. + await expect(failingCheck).toBeVisible({ timeout: 15_000 }); + await expect( + mockup.getByText("paseo plugin reload release-radar", { exact: true }), + ).toBeVisible(); +}); + +test("the code review scene comments on a line and sends the feedback to an agent", async ({ + page, +}) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + const comment = mockup.getByText("Add “write”. The agent edits files too.", { exact: true }); + const sendFeedback = mockup.getByText("Send feedback (1)", { exact: true }); + await playScene( + page, + "Code review", + page.getByRole("button", { name: "Code review", pressed: true }), + ); + await expect(comment).toHaveCount(0); + + // The pointer opens the editor on a line, and the typed comment is saved under that line. + await expect(sendFeedback).toBeVisible({ timeout: 10_000 }); + await expect(comment).toBeVisible(); + + // Send feedback asks which agent, and the sent comment leaves the diff. + await expect(mockup.getByText("Claude Code", { exact: true })).toHaveCount(2, { + timeout: 10_000, + }); + await expect(mockup.getByText("Feedback sent to Codex", { exact: true })).toBeVisible({ + timeout: 10_000, + }); + await expect(sendFeedback).toHaveCount(0); + await expect(comment).toHaveCount(0); +}); + +test("picking a scene brings the pills and the whole mockup on screen", async ({ page }) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(mockup).not.toBeInViewport({ ratio: 0.9 }); + + await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); + await expect(mockup).toBeInViewport({ ratio: 0.99 }); + await expect(page.getByRole("button", { name: "Remote", exact: true })).toBeInViewport({ + ratio: 1, + }); +}); + +test("picking a scene in a window too short for the mockup keeps the pills on screen", async ({ + page, +}) => { + await openHomepage(page); + await page.setViewportSize({ width: 1280, height: 600 }); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(mockup).not.toBeInViewport(); + + await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); + await expect(mockup).toBeInViewport({ ratio: 0.7 }); + await expect(page.getByRole("button", { name: "Remote", exact: true })).toBeInViewport({ + ratio: 1, + }); +}); + +test("picking a scene while the hero is still sliding in keeps the pills on screen", async ({ + page, +}) => { + // Reduced motion makes the scroll instant, so the test does not wait for one to settle. + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.setViewportSize({ width: 1280, height: 700 }); + await page.goto("/"); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); + + // The hero slides up 40px as it enters. The test waits for that to end, puts the same 40px back + // on the container, picks a scene, and lets the slide end again. A click during a real slide + // does the same, but only inside the first second after load. + const sliding = page + .getByRole("button", { name: "Remote", exact: true }) + .locator("xpath=../../../.."); + await expect(sliding).toHaveCSS("transform", "none"); + await page.evaluate(() => window.scrollTo(0, 0)); + await expect(mockup).not.toBeInViewport({ ratio: 0.99 }); + const slideBy = (pixels: number) => + sliding.evaluate((container, y) => { + container.style.transform = y === 0 ? "none" : `translateY(${y}px)`; + }, pixels); + + const codeReview = page.getByRole("button", { name: "Code review", exact: true }); + await slideBy(40); + await codeReview.click(); + await slideBy(0); + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0); + await expect(codeReview).toBeInViewport({ ratio: 1 }); +}); + +test("the remote scene lists hosts with how each connects and its round trip time", async ({ + page, +}) => { + await openHomepage(page); + const mockup = page.getByRole("img", { name: desktopName, exact: true }); + await expect(async () => { + await page.getByRole("button", { name: "Remote", exact: true }).click(); + await expect(mockup.getByText("Hosts", { exact: true })).toBeVisible({ timeout: 500 }); + }).toPass({ timeout: 10_000 }); + for (const fact of ["Local", "Relay", "Tailscale", "SSH", "38ms", "mo@workstation"]) { + await expect(mockup.getByText(fact, { exact: true })).toBeVisible(); + } +}); + /** Opacity as rendered: the element's own times every ancestor's. */ async function renderedOpacity(locator: Locator) { return locator.evaluate((element) => { diff --git a/packages/website/src/components/hero-mockup.tsx b/packages/website/src/components/hero-mockup.tsx index 1249d5c3d5..6a3e0a219b 100644 --- a/packages/website/src/components/hero-mockup.tsx +++ b/packages/website/src/components/hero-mockup.tsx @@ -1,24 +1,57 @@ -import { motion } from "framer-motion"; -import { useCallback, useState } from "react"; +import { motion, useInView, useReducedMotion } from "framer-motion"; +import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { - DEFAULT_MOCKUP_STATE, + createMockupPlayer, DESIGN_HEIGHT, DESIGN_WIDTH, MOCKUP_STATES, type MockupStateId, MockupWindow, ScaledMockup, + useMockupScene, } from "~/components/mockup"; +const IN_VIEW = { once: true }; +/** How far down the mockup its start line sits. */ +const START_LINE = "60%"; +/** The space left between the top or bottom of the window and the pills or the mockup. */ +const PAGE_MARGIN = 16; +const START_LINE_STYLE = { top: START_LINE }; const PILL_TRANSITION = { duration: 0.34, ease: [0.22, 0.61, 0.36, 1] as const }; export function HeroMockup() { const { t } = useTranslation(); - const [state, setState] = useState(DEFAULT_MOCKUP_STATE); + const [player] = useState(createMockupPlayer); + const state = useMockupScene(player); + + // The opening scene plays once most of the mockup is on screen, so a visitor who scrolls to it + // sees it from the start. "Most" is a line 60% of the way down the mockup. A window shorter than + // 60% of the mockup still reaches the line, which a share of the mockup on screen would not. + // With reduced motion there is nothing to miss, so the finished scene shows at once. + const frame = useRef(null); + const startLine = useRef(null); + const reduceMotion = useReducedMotion(); + const onScreen = useInView(startLine, IN_VIEW); + const ready = onScreen || reduceMotion === true; + useEffect(() => { + if (ready) player.start(); + }, [ready, player]); + useEffect(() => player.stop, [player]); + + // The pills can sit above a mockup that is partly below the fold, most of all on a phone. + // Picking a scene brings the pills and the mockup on screen together. A window too short for + // both keeps the pills at its top edge, so the next pill is still in reach. + const select = useCallback( + (scene: MockupStateId) => { + player.select(scene); + if (frame.current) scrollOnScreen(frame.current, reduceMotion ? "auto" : "smooth"); + }, + [player, reduceMotion], + ); return ( -
+
{MOCKUP_STATES.map((option) => ( ))}
- - - +
+
); } +/** Where an element sits in the window, from layout alone. A slide-in that is still running does not count. */ +function layoutRect(element: HTMLElement) { + let top = -window.scrollY; + for (let node: Element | null = element; node instanceof HTMLElement; node = node.offsetParent) { + top += node.offsetTop; + } + return { top, bottom: top + element.offsetHeight }; +} + +/** + * Scrolls the least that shows all of an element, and never past the point where its top edge is + * at the top of the window. The element is measured where it settles, because the hero slides up + * as it enters and a click can come before it stops. + */ +function scrollOnScreen(element: HTMLElement, behavior: ScrollBehavior) { + const { top, bottom } = layoutRect(element); + const aboveWindow = top - PAGE_MARGIN; + const belowWindow = bottom + PAGE_MARGIN - window.innerHeight; + const distance = aboveWindow < 0 ? aboveWindow : Math.min(Math.max(belowWindow, 0), aboveWindow); + if (distance !== 0) window.scrollBy({ top: distance, behavior }); +} + function StatePill({ id, label, diff --git a/packages/website/src/components/landing-page.tsx b/packages/website/src/components/landing-page.tsx index 77869e7379..d6fa15f3d9 100644 --- a/packages/website/src/components/landing-page.tsx +++ b/packages/website/src/components/landing-page.tsx @@ -714,8 +714,8 @@ function AutomationDetail({ kind }: { kind: AutomationKind }) { } const MCP_AGENT_CALLS: ToolCall[] = [ - { kind: "paseo", label: "Create agent", detail: "Fix #412: retry flaky relay handshake" }, - { kind: "paseo", label: "Create agent", detail: "Fix #417: group schedules by project" }, + { kind: "paseo", label: "Create agent", detail: "Fix #412: relay handshake race" }, + { kind: "paseo", label: "Create agent", detail: "Fix #417: menu bar icon on macOS" }, ]; function McpAutomationTranscript() { diff --git a/packages/website/src/components/mockup/atoms.tsx b/packages/website/src/components/mockup/atoms.tsx index c90310be79..02f060b336 100644 --- a/packages/website/src/components/mockup/atoms.tsx +++ b/packages/website/src/components/mockup/atoms.tsx @@ -18,6 +18,13 @@ export function DiffStat({ add, remove }: { add: string; remove: string }) { ); } +/** The text caret of an input that has focus. */ +export function Caret({ className }: { className: string }) { + return ( + + ); +} + export type DotTone = "success" | "danger" | "warning" | "running" | "idle"; const DOT_TONE: Record = { diff --git a/packages/website/src/components/mockup/chat.tsx b/packages/website/src/components/mockup/chat.tsx index dc951a8517..167d55acb6 100644 --- a/packages/website/src/components/mockup/chat.tsx +++ b/packages/website/src/components/mockup/chat.tsx @@ -15,15 +15,19 @@ import { SquareTerminal, Zap, } from "lucide-react"; +import { motion } from "framer-motion"; import type * as React from "react"; import { useTranslation } from "react-i18next"; -import { DiffStat } from "./atoms"; -import { CodexIcon, PaseoMark } from "./icons"; - -// Icons passed as props are hoisted so they are not rebuilt on every render. -const MODEL_ICON = ; -const EFFORT_ICON = ; -const ACCESS_ICON = ; +import { Caret, DiffStat } from "./atoms"; +import { HostBadge } from "./hosts"; +import { PaseoMark } from "./icons"; +import { FADE_IN, FADE_OUT } from "./motion"; +import { DELEGATED_TASKS, SUBAGENTS_CLICK, tasksDelegated } from "./orchestration"; +import { useSceneClock } from "./player"; +import { Pointer } from "./pointer"; +import { PROVIDERS, type ProviderId } from "./providers"; +import { COMPOSER, type SceneScript, type ToolCall, type TranscriptEntry } from "./script"; +import type { MockupStateId } from "./states"; // --- transcript ------------------------------------------------------------- @@ -62,6 +66,38 @@ function TurnFooter({ duration }: { duration: string }) { ); } +const BUILT_IN_LABELS = { read: "Read", write: "Write", shell: "Shell" } as const; + +function toolCallLabel(call: ToolCall): string { + return call.kind === "paseo" ? call.label : BUILT_IN_LABELS[call.kind]; +} + +function ToolCallIcon({ kind }: { kind: ToolCall["kind"] }) { + if (kind === "read") return ; + if (kind === "write") return ; + if (kind === "paseo") return ; + return ; +} + +/** + * One tool call row, drawn like the app's collapsed timeline item + * (`packages/app/src/components/message.tsx`): icon, label, then the summary, + * all muted and in the UI font. A Paseo call that targets another machine ends + * with that host's badge, which the app's row does not draw. + */ +export function ToolCallRow({ call }: { call: ToolCall }) { + return ( +
+ + + + {toolCallLabel(call)} + {call.detail ? {call.detail} : null} + {call.kind === "paseo" && call.host ? : null} +
+ ); +} + export function AgentTranscript() { return (
@@ -88,161 +124,273 @@ export function AgentTranscript() { Includes responsive mobile proof and the supporting homepage story. Formatting, typecheck, and lint are clean.
- Ready for review.
); } -/** - * A collapsed tool call as the app's timeline shows it. Built-in tools carry a - * fixed label; Paseo MCP tools name their action, such as "Create agent". - */ -export type ToolCall = - | { kind: "read" | "write" | "shell"; detail: string } - | { kind: "paseo"; label: string; detail: string }; - -const BUILT_IN_LABELS = { read: "Read", write: "Write", shell: "Shell" } as const; - -function toolCallLabel(call: ToolCall): string { - return call.kind === "paseo" ? call.label : BUILT_IN_LABELS[call.kind]; -} - -const PLUGIN_TOOL_CALLS: ToolCall[] = [ - { kind: "read", detail: "paseo-plugin/SKILL.md" }, - { kind: "shell", detail: "paseo plugin init ~/dev/release-radar" }, - { kind: "write", detail: "~/dev/release-radar/index.ts" }, - { kind: "write", detail: "~/dev/release-radar/release-radar.client.tsx" }, - { kind: "shell", detail: "npm install && npm run typecheck" }, - { kind: "shell", detail: "paseo plugin install ~/dev/release-radar" }, -]; - -const PLUGIN_DISCOVERY_CALLS = PLUGIN_TOOL_CALLS.slice(0, 1); -const PLUGIN_BUILD_CALLS = PLUGIN_TOOL_CALLS.slice(1, 4); -const PLUGIN_INSTALL_CALLS = PLUGIN_TOOL_CALLS.slice(4); - -function ToolCallIcon({ kind }: { kind: ToolCall["kind"] }) { - if (kind === "read") return ; - if (kind === "write") return ; - if (kind === "paseo") return ; - return ; -} - -/** - * One tool call row, drawn like the app's collapsed timeline item - * (`packages/app/src/components/message.tsx`): icon, label, then the summary, - * all muted and in the UI font. - */ -export function ToolCallRow({ call }: { call: ToolCall }) { +/** Something that fades in when the script reaches it. */ +function Entering({ children }: { children: React.ReactNode }) { return ( -
- - - - {toolCallLabel(call)} - {call.detail} -
+ + {children} + ); } -function PluginToolGroup({ calls }: { calls: ToolCall[] }) { +interface ScriptedProps { + scene: MockupStateId; + script: SceneScript; +} + +function StreamedText({ scene, script, entry }: ScriptedProps & { entry: TranscriptEntry }) { + const text = useSceneClock(scene, (ms) => script.streamed(entry, ms)); + return {text}; +} + +function LandedTools({ + scene, + script, + entry, + calls, +}: ScriptedProps & { entry: TranscriptEntry; calls: ToolCall[] }) { + const landed = useSceneClock(scene, (ms) => script.landed(entry, ms)); return (
- {calls.map((call) => ( - + {calls.slice(0, landed).map((call) => ( + + + ))}
); } -export function PluginBuildTranscript() { +function TranscriptEntryView({ scene, script, entry }: ScriptedProps & { entry: TranscriptEntry }) { + const { beat } = entry; + if (beat.kind === "agent") return ; + if (beat.kind === "tools") { + return ; + } + if (beat.kind === "user") { + return ( + + {beat.text} + + ); + } + return ( + + + + ); +} + +/** The transcript of a scripted scene, as far as its script has played. */ +export function ScriptedTranscript({ scene, script }: ScriptedProps) { + const entered = useSceneClock(scene, script.entered); return (
- - Build me a release radar for Paseo. I want an explorer panel showing merged PRs, changes in - review, failing checks, and seven-day activity, accessible from the sidebar. - - - I’ll scaffold a local plugin, add the explorer surface, and wire it into the sidebar. - - - - The plugin API exposes Paseo’s live project and workspace state, so the radar - doesn’t need a separate service. - - - The surface is wired. I’m checking the project and installing it now. - - Release Radar is live. It should now be visible in the right sidebar. - + {script.entries.slice(0, entered).map((entry) => ( + + ))}
); } // --- composer --------------------------------------------------------------- -function ControlPill({ icon, label }: { icon: React.ReactNode; label: string }) { +/** One composer control: its icon as the child, then the current value. */ +function ControlPill({ label, children }: { label: string; children: React.ReactNode }) { return ( - - {icon} + + {children} {label} ); } -/** A rounded pill that floats above the composer — task tracker, subagents, diff. */ -function ComposerPill({ children }: { children: React.ReactNode }) { +/** + * A rounded pill that floats above the composer — task tracker, subagents, diff. An open pill is + * the one whose panel is showing. + */ +function ComposerPill({ children, open = false }: { children: React.ReactNode; open?: boolean }) { return ( - + {children} ); } +function SubagentsPill({ count, open = false }: { count: number; open?: boolean }) { + const { t } = useTranslation(); + return ( + + + {t("landing.mockup.app.subagents", { count })} + + ); +} + +/** The row of pills above the composer input. */ +function ComposerTrack({ children }: { children: React.ReactNode }) { + return
{children}
; +} + +/** The trackers of a turn in progress: tasks, subagents, and the diff so far. */ +export function ProgressTrack() { + const { t } = useTranslation(); + return ( + +
+ + {t("landing.mockup.app.tasksProgress", { completed: 6, total: 6 })} + + + + + +
+
+ ); +} + +function SubagentRow({ task }: { task: (typeof DELEGATED_TASKS)[number] }) { + const provider = PROVIDERS[task.provider]; + return ( +
+ + + + + + {task.title} + + + {provider.name} · {provider.model} + + {task.host ? ( + <> + · + + + ) : null} + + +
+ ); +} + +// Where the pointer sets off from, in design pixels from the spot it clicks. +const POINTER_TO_PILL = { x: 236, y: -128 }; +const POINTER_TO_COMPOSER = { x: 230, y: -140 }; + +const ROSTER_CLOSED = { opacity: 0, scale: 0.97, y: 6 }; +const ROSTER_OPEN = { opacity: 1, scale: 1, y: 0 }; + +/** + * The Subagents track of the orchestration scene. Its pill appears with the first subagent and + * counts each one the orchestrator launches. When the pointer clicks the pill, the roster opens: + * one row per agent, drawn like the app's track rows (`packages/app/src/subagents/track.tsx`). + * The title is the task and the line under it names the provider and model. An agent on another + * machine ends that line with the host's badge, where the app writes the host's name in plain text. + */ +export function SubagentsTrack() { + const launched = useSceneClock("orchestrate", tasksDelegated); + const pressed = useSceneClock("orchestrate", SUBAGENTS_CLICK.pressed); + const open = useSceneClock("orchestrate", SUBAGENTS_CLICK.done); + if (launched === 0) return null; + return ( + + {open ? ( + + {DELEGATED_TASKS.map((task) => ( + + ))} + + ) : null} + + + + + + + + ); +} + /** The amber ring the app shows while a turn is streaming. */ function BusyRing() { return ; } export function Composer({ - showProgress = true, - busy = true, + track, + agent = "codex", + busy = false, + draft = "", + focused = false, + children, }: { - showProgress?: boolean; + /** The composer track shown above the input, such as `ProgressTrack`. It brings its own spacing. */ + track?: React.ReactNode; + /** Which provider's agent this composer talks to. */ + agent?: ProviderId; busy?: boolean; + /** What the user has typed and not yet sent. Empty shows the placeholder. */ + draft?: string; + /** Whether the caret is in the input. */ + focused?: boolean; + /** Something drawn over the input box, such as the pointer that clicks it. */ + children?: React.ReactNode; }) { const { t } = useTranslation(); + const provider = PROVIDERS[agent]; return (
-
- {showProgress ? ( -
- - {t("landing.mockup.app.tasksProgress", { completed: 6, total: 6 })} - - - - {t("landing.mockup.app.subagents", { count: 3 })} - - - - -
- ) : null} -
-
+ {track} +
+ {children}
- - {t("landing.mockup.app.composerPlaceholder")} - + {draft ? ( + + {draft} + + + ) : ( + + {/* The caret takes no room, so the placeholder does not move when it appears. */} + {focused ? : null} + {t("landing.mockup.app.composerPlaceholder")} + + )}
- - - + + + + + + + + + @@ -255,3 +403,29 @@ export function Composer({
); } + +/** + * The composer of a scripted scene. The pointer clicks it, which puts the caret in it. Then the + * script types into it and says when a turn is running. + */ +export function ScriptedComposer({ + scene, + script, + agent, + track, +}: ScriptedProps & { agent: ProviderId; track?: React.ReactNode }) { + const click = script.click(COMPOSER); + const draft = useSceneClock(scene, script.draft); + const busy = useSceneClock(scene, script.busy); + const focused = useSceneClock(scene, (ms) => click.pressed(ms) || click.done(ms)); + return ( + + + + ); +} diff --git a/packages/website/src/components/mockup/diff.tsx b/packages/website/src/components/mockup/diff.tsx index 9a0d3a5f25..abc32d4d31 100644 --- a/packages/website/src/components/mockup/diff.tsx +++ b/packages/website/src/components/mockup/diff.tsx @@ -9,6 +9,8 @@ import { RefreshCw, Rows3, } from "lucide-react"; +import { Fragment } from "react"; +import type * as React from "react"; import { useTranslation } from "react-i18next"; import { Code, DiffStat } from "./atoms"; import { TABBAR_H } from "./geometry"; @@ -29,7 +31,7 @@ const SUBHEADER_STYLE = { height: TABBAR_H }; export type DiffRow = | { kind: "file"; name: string; path?: string; add: string; remove: string } | { kind: "hunk"; label: string } - | { kind: "line"; n: string; text: string; mark?: DiffMark } + | { kind: "line"; n: string; text: string; mark?: DiffMark; reviewed?: boolean } | { kind: "scrollbar" } | { kind: "gap" }; @@ -47,16 +49,35 @@ const NUMBER_COLOR: Record = { remove: "text-mock-danger", }; -function DiffLine({ n, text, mark }: { n: string; text: string; mark?: DiffMark }) { +/** What a review adds to the line it comments on. Rows mark that line with `reviewed`. */ +export interface LineReview { + /** Drawn on the line's gutter, such as the button that adds a comment. */ + action: React.ReactNode; + /** Drawn under the line: the thread of comments. */ + thread: React.ReactNode; +} + +function DiffLine({ + n, + text, + mark, + action, +}: { + n: string; + text: string; + mark?: DiffMark; + action?: React.ReactNode; +}) { const fill = mark ? ROW_FILL[mark] : ""; const number = mark ? NUMBER_COLOR[mark] : "text-mock-fg-muted"; return (
{n} + {action} @@ -88,7 +109,15 @@ function FileRow({ ); } -export function DiffRows({ rows, flush }: { rows: DiffRow[]; flush?: boolean }) { +export function DiffRows({ + rows, + flush, + review, +}: { + rows: DiffRow[]; + flush?: boolean; + review?: LineReview; +}) { return (
{rows.map((row, index) => { @@ -110,6 +139,14 @@ export function DiffRows({ rows, flush }: { rows: DiffRow[]; flush?: boolean })
); + if (row.reviewed && review) { + return ( + + + {review.thread} + + ); + } return ; })} {!flush ? ( @@ -333,6 +370,7 @@ export const REVIEW_DIFF_ROWS: DiffRow[] = [ n: "23", text: 'type ToolKind = "read" | "shell";', mark: "add", + reviewed: true, }, { kind: "line", n: "24", text: "" }, { diff --git a/packages/website/src/components/mockup/geometry.ts b/packages/website/src/components/mockup/geometry.ts index be8e6c43bb..6485fe077a 100644 --- a/packages/website/src/components/mockup/geometry.ts +++ b/packages/website/src/components/mockup/geometry.ts @@ -4,14 +4,17 @@ * plain px number you can reason about directly, and nothing has to change when * the hero column gets wider or narrower. * - * The numbers come from measuring public/homepage-hero.png (a 2x capture of a - * 2249x1289 window region) and dividing by 1.5617 so the window lands at 1440 - * wide — the widest the hero column ever renders it. + * The window is 1280 wide, the widest the hero column ever renders it, so on a + * wide screen one design pixel is one CSS pixel and the text is as large as the + * app's. The type and control sizes come from measuring public/homepage-hero.png + * (a 2x capture of a 2249x1289 window region) and dividing by 1.5617. */ -export const DESIGN_WIDTH = 1440; -export const DESIGN_HEIGHT = 826; +export const DESIGN_WIDTH = 1280; +export const DESIGN_HEIGHT = 734; export const TITLEBAR_H = 39; export const TABBAR_H = 31; export const SIDEBAR_W = 262; -export const RIGHT_PANEL_W = 424; +// The docked panel is as wide as the file tree needs. A pull request or a plugin panel gets more room. +export const RIGHT_PANEL_W = 300; +export const RIGHT_PANEL_WIDE_W = 424; diff --git a/packages/website/src/components/mockup/hosts.tsx b/packages/website/src/components/mockup/hosts.tsx new file mode 100644 index 0000000000..2fefb7a204 --- /dev/null +++ b/packages/website/src/components/mockup/hosts.tsx @@ -0,0 +1,157 @@ +import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal, X } from "lucide-react"; +import type * as React from "react"; +import { useTranslation } from "react-i18next"; +import { TailscaleMark } from "./icons"; + +/** + * The machines the mockup's workspaces live on. A host's name is the label its owner gave it, and + * its color is the identity color they picked for its badge. The local machine draws no badge, as + * a host set to hide its badge does in the app. + */ +export type RemoteHostId = "devbox" | "mac-mini"; + +/** Badge ink per host, as the app's `HostBadge` paints glyph and label in one identity color. */ +const HOST_TONE: Record = { + devbox: "text-mock-host-teal", + "mac-mini": "text-mock-host-violet", +}; + +/** + * The mark that says which machine something runs on: the server glyph and the host's name in its + * identity color. It inherits its text size, so it sits in a sidebar row, a tool call, or a + * subagent row alike. + */ +export function HostBadge({ host, glyph = 12 }: { host: RemoteHostId; glyph?: number }) { + return ( + + + {host} + + ); +} + +// --- hosts modal -------------------------------------------------------------- + +type IconComponent = React.ComponentType<{ size?: number; className?: string }>; + +/** How the app reaches a host. Tailscale is a direct TCP connection to a tailnet name. */ +type HostLink = "local" | "relay" | "tailscale" | "ssh"; + +const LINK_ICON: Record = { + local: Monitor, + relay: Globe, + tailscale: TailscaleMark, + ssh: Terminal, +}; + +interface ConnectedHost { + name: string; + device: IconComponent; + tone: string; + link: HostLink; + /** The address in use. The local daemon has none worth showing. */ + endpoint?: string; + /** Round trip time, formatted as the app's `formatLatency` prints it. */ + latency: string; + agents: number; +} + +const CONNECTED_HOSTS: ConnectedHost[] = [ + { + name: "MacBook Pro", + device: Laptop, + tone: "text-mock-fg-muted", + link: "local", + latency: "1ms", + agents: 4, + }, + { + name: "devbox", + device: Server, + tone: HOST_TONE.devbox, + link: "relay", + endpoint: "relay.paseo.sh", + latency: "38ms", + agents: 6, + }, + { + name: "mac-mini", + device: Computer, + tone: HOST_TONE["mac-mini"], + link: "tailscale", + endpoint: "mac-mini:6767", + latency: "12ms", + agents: 3, + }, + { + name: "workstation", + device: PcCase, + tone: "text-mock-host-orange", + link: "ssh", + endpoint: "mo@workstation", + latency: "24ms", + agents: 2, + }, +]; + +function HostRow({ host }: { host: ConnectedHost }) { + const { t } = useTranslation(); + const Device = host.device; + const LinkIcon = LINK_ICON[host.link]; + return ( +
+ + + + + + + {host.name} + + + + {t(`landing.mockup.app.hostLinks.${host.link}`)} + {host.endpoint ? {host.endpoint} : null} + + + + + {host.latency} + + + {t("landing.mockup.app.agentCount", { count: host.agents })} + + +
+ ); +} + +/** + * Every machine this window is connected to: what kind of machine it is, how the app reaches it, + * the round trip time, and how many agents it runs. + */ +export function HostsModal() { + const { t } = useTranslation(); + return ( +
+
+ + {t("landing.mockup.app.hosts")} + + +
+ {CONNECTED_HOSTS.map((host) => ( + + ))} +
+ {/* The plus sits on the center line of the device tiles above it. */} + + + + {t("landing.mockup.app.addHost")} +
+
+ ); +} diff --git a/packages/website/src/components/mockup/icons.tsx b/packages/website/src/components/mockup/icons.tsx index 9b4cd39e08..260aeefd09 100644 --- a/packages/website/src/components/mockup/icons.tsx +++ b/packages/website/src/components/mockup/icons.tsx @@ -1,5 +1,7 @@ // Exact SVG paths from packages/app/src/components/icons/ +import { OpenCodeIcon as OpenCodeBrandIcon, PiIcon as PiBrandIcon } from "../agent-icons"; + /** The Paseo brand swirl — public/logo.svg, drawn as a small sidebar avatar mark. */ export function PaseoMark({ size = 13, className }: { size?: number; className?: string }) { return ( @@ -112,3 +114,65 @@ export function SourceControlIcon({ size = 14, className }: { size?: number; cla ); } + +export function OpenCodeIcon({ size = 13, className }: { size?: number; className?: string }) { + return ; +} + +export function PiIcon({ size = 13, className }: { size?: number; className?: string }) { + return ; +} + +const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) => + [3, 12, 21].map((cx, column) => ({ + cx, + cy, + // The mark is a T: the middle row and the dot under its center are solid. + solid: row === 1 || (row === 2 && column === 1), + })), +); + +/** The Tailscale mark: a three by three dot grid with a solid T. */ +export function TailscaleMark({ size = 12, className }: { size?: number; className?: string }) { + return ( + + ); +} + +/** A mouse pointer. Its tip is the top left corner of the glyph. */ +export function PointerArrow({ size = 24, className }: { size?: number; className?: string }) { + return ( + + ); +} diff --git a/packages/website/src/components/mockup/index.ts b/packages/website/src/components/mockup/index.ts index d07c4d1f56..8b624ff1fd 100644 --- a/packages/website/src/components/mockup/index.ts +++ b/packages/website/src/components/mockup/index.ts @@ -1,10 +1,11 @@ export { ClaudeIcon, CodexIcon, SourceControlIcon } from "./icons"; -export { type ToolCall, ToolCallRow } from "./chat"; +export { ToolCallRow } from "./chat"; +export type { ToolCall } from "./script"; export { DESIGN_HEIGHT, DESIGN_WIDTH } from "./geometry"; export { PhoneFrame } from "./mobile/frame"; export { MobileChat } from "./mobile/chat"; export { MobileDiff } from "./mobile/diff"; export { MobileSidebar } from "./mobile/sidebar"; -export { DEFAULT_MOCKUP_STATE, MOCKUP_STATES, type MockupStateId } from "./states"; -export { MockupWindow } from "./window"; +export { MOCKUP_STATES, type MockupStateId } from "./states"; +export { createMockupPlayer, MockupWindow, useMockupScene } from "./window"; export { ScaledMockup } from "./scaled-mockup"; diff --git a/packages/website/src/components/mockup/orchestration.ts b/packages/website/src/components/mockup/orchestration.ts new file mode 100644 index 0000000000..0d913527ff --- /dev/null +++ b/packages/website/src/components/mockup/orchestration.ts @@ -0,0 +1,102 @@ +import type { RemoteHostId } from "./hosts"; +import { PROVIDERS, type ProviderId } from "./providers"; +import { COMPOSER, script, type ToolCall } from "./script"; + +/** + * The work the orchestrating agent hands out in the orchestration scene. The sidebar draws one + * workspace per task and the chat draws the tool calls and the subagent rows from the same list. + */ +export const DELEGATED_TASKS: { + id: string; + title: string; + branch: string; + provider: Exclude; + host?: RemoteHostId; +}[] = [ + { + id: "issue-412", + title: "Fix #412: relay handshake race", + branch: "fix/relay-handshake-race", + provider: "codex", + }, + { + id: "issue-417", + title: "Fix #417: menu bar icon on macOS", + branch: "fix/menu-bar-icon", + provider: "opencode", + host: "mac-mini", + }, + { + id: "issue-421", + title: "Fix #421: stale Docker setup docs", + branch: "docs/docker-setup", + provider: "pi", + }, +]; + +/** + * The orchestrator's Paseo tool calls, one per delegated task. One call creates the worktree + * workspace and starts the agent in it. + */ +const DELEGATION_CALLS: ToolCall[] = DELEGATED_TASKS.map((task) => ({ + kind: "paseo", + label: "Create agent", + detail: `${PROVIDERS[task.provider].name} · ${task.branch}`, + host: task.host, +})); + +/** + * What the orchestrator looks up before it delegates: the issues to fix, and the agent profiles + * the user set up, which say which model takes which kind of work. + */ +const LOOKUP_CALLS: ToolCall[] = [ + { kind: "shell", detail: "gh issue list --label ready" }, + { kind: "paseo", label: "List agent profiles" }, +]; + +const REQUEST = "Fix the issues labeled ready, one worktree each."; + +/** + * The orchestration scene: the user asks Claude to fix the ready issues, each in a worktree. Claude + * lists the issues and the user's agent profiles, picks a model for each issue, and puts the one + * that needs macOS on another machine. It says that Paseo will notify it when the agents finish. + * Then the pointer opens the subagents roster. + */ +export const ORCHESTRATION = script([ + { kind: "wait", ms: 200 }, + { kind: "click", target: COMPOSER }, + { kind: "wait", ms: 250 }, + { kind: "type", text: REQUEST }, + { kind: "user", text: REQUEST }, + { kind: "tools", calls: LOOKUP_CALLS }, + { + kind: "agent", + text: `I loaded your orchestration preferences: ${PROVIDERS.codex.model} for the hard bug, ${PROVIDERS.opencode.model} for UI, ${PROVIDERS.pi.model} for docs.`, + }, + { + kind: "agent", + text: "I will launch the UI agent on your mac-mini, because that issue is specific to macOS.", + }, + { kind: "tools", calls: DELEGATION_CALLS }, + { + kind: "agent", + text: "All three are launched. Paseo will notify me when each one finishes.", + }, + // No footer: with it, the transcript and the open roster do not both fit in the pane. + { kind: "turnEnd" }, + { kind: "click", target: "subagents" }, +]); + +/** The pointer's click on the subagents pill. It opens the roster of subagents. */ +export const SUBAGENTS_CLICK = ORCHESTRATION.click("subagents"); + +/** + * How many tasks the orchestrator delegated so far. Each one adds a workspace to the sidebar and a + * subagent to the composer's pill. + */ +export function tasksDelegated(ms: number): number { + const delegation = ORCHESTRATION.entries.find( + (entry) => entry.beat.kind === "tools" && entry.beat.calls === DELEGATION_CALLS, + ); + return delegation ? ORCHESTRATION.landed(delegation, ms) : 0; +} diff --git a/packages/website/src/components/mockup/panes.tsx b/packages/website/src/components/mockup/panes.tsx index 3f0554f403..32831b582a 100644 --- a/packages/website/src/components/mockup/panes.tsx +++ b/packages/website/src/components/mockup/panes.tsx @@ -1,15 +1,86 @@ -import { DiffRows, REVIEW_DIFF_ROWS, ScopeRow } from "./diff"; +import { DiffRows, type LineReview, REVIEW_DIFF_ROWS, ScopeRow } from "./diff"; +import { AddCommentAction, ReviewFeedback, ReviewThread } from "./review-thread"; import { useTranslation } from "react-i18next"; // --- review ----------------------------------------------------------------- -/** The selected Changes-tree file, open in its own workspace tab. */ +const LINE_REVIEW: LineReview = { action: , thread: }; + +/** + * The selected Changes-tree file, open in its own workspace tab. The review scene comments on one + * of its lines and sends that feedback to an agent. + */ export function DiffReviewPane() { const { t } = useTranslation(); return ( -
+
- + + +
+ ); +} + +// --- remote ----------------------------------------------------------------- + +function ShellPrompt() { + return ( + <> + mo@devbox: + ~/dev/paseo${" "} + + ); +} + +function ViteArrow() { + return {" ➜ "}; +} + +function HmrLine({ time, file }: { time: string; file: string }) { + return ( +
+ {time}{" "} + [vite]{" "} + hmr update{" "} + {file} +
+ ); +} + +/** + * The workspace's terminal tab. The workspace lives on devbox, so the shell does too: the prompt + * names the remote machine while the pane sits in the same window as every local workspace. + */ +export function RemoteTerminalPane() { + return ( +
+
+ + npm run dev +
+
+
> @getpaseo/website dev
+
> vite
+
+
+ {" "} + VITE v7.3.3 + {" ready in "}412 ms +
+
+
+ + {"Local: "} + http://localhost:3000/ +
+
+ + press h + enter to show help +
+
+ + +
); } diff --git a/packages/website/src/components/mockup/player.test.ts b/packages/website/src/components/mockup/player.test.ts new file mode 100644 index 0000000000..73732638f0 --- /dev/null +++ b/packages/website/src/components/mockup/player.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { createScenePlayer, type Frames } from "./player"; + +/** A page clock that moves only when the test turns it. */ +function handClock() { + let time = 0; + let nextId = 0; + const waiting = new Map void>(); + const frames: Frames = { + now: () => time, + request(callback) { + nextId += 1; + waiting.set(nextId, callback); + return nextId; + }, + cancel: (id) => waiting.delete(id), + reducedMotion: () => false, + }; + return { + frames, + /** Moves the clock on and runs the frames that were waiting for it. */ + advance(ms: number) { + time += ms; + const due = [...waiting.values()]; + waiting.clear(); + for (const callback of due) callback(time); + }, + framesWaiting: () => waiting.size, + }; +} + +function setUp() { + const clock = handClock(); + const player = createScenePlayer("orchestrate", { orchestrate: 1000, review: 500 }, clock.frames); + return { clock, player }; +} + +describe("scene player", () => { + it("plays the opening scene from the start when the page starts it", () => { + const { clock, player } = setUp(); + player.start(); + clock.advance(16); + clock.advance(16); + expect(player.elapsed("orchestrate")).toBe(32); + }); + + it("keeps the place of a scene that a pill click started before the page did", () => { + const { clock, player } = setUp(); + player.select("review"); + clock.advance(16); + clock.advance(16); + expect(player.elapsed("review")).toBe(32); + + player.start(); + expect(player.scene()).toBe("review"); + expect(player.elapsed("review")).toBe(32); + expect(player.elapsed("orchestrate")).toBe(0); + }); + + it("stops the clock", () => { + const { clock, player } = setUp(); + player.start(); + clock.advance(16); + expect(clock.framesWaiting()).toBe(1); + + player.stop(); + expect(clock.framesWaiting()).toBe(0); + clock.advance(16); + expect(player.elapsed("orchestrate")).toBe(16); + }); +}); diff --git a/packages/website/src/components/mockup/player.ts b/packages/website/src/components/mockup/player.ts new file mode 100644 index 0000000000..30828d0155 --- /dev/null +++ b/packages/website/src/components/mockup/player.ts @@ -0,0 +1,130 @@ +import { createContext, useContext, useSyncExternalStore } from "react"; +import type { MockupStateId } from "./states"; + +/** + * Which scene the mockup shows and how far into its script each scene is. The player owns the + * clock. Components read the time through `useSceneClock` and never keep time themselves. + */ +export interface ScenePlayer { + scene(): MockupStateId; + /** Milliseconds into a scene's script. Each scene keeps its own, so a scene that is fading out holds its last frame. */ + elapsed(scene: MockupStateId): number; + /** Shows a scene and plays its script from the start. */ + select(scene: MockupStateId): void; + /** + * Plays the opening scene from the start, unless a scene has played already. A pill click can + * come before the page decides to start, and that scene keeps its place. + */ + start(): void; + /** Stops the clock. A scene that is playing holds its last frame. */ + stop(): void; + subscribe(listener: () => void): () => void; +} + +// A background tab stops animation frames. On return the script resumes where it paused. +const LONGEST_FRAME_MS = 64; + +/** What the player needs from the page to keep time. Tests pass a clock they turn by hand. */ +export interface Frames { + now(): number; + request(callback: (now: number) => void): number; + cancel(id: number): void; + reducedMotion(): boolean; +} + +const browserFrames: Frames = { + now: () => performance.now(), + request: (callback) => requestAnimationFrame(callback), + cancel: (id) => cancelAnimationFrame(id), + // Visitors who ask for reduced motion get the finished scene. + reducedMotion: () => window.matchMedia("(prefers-reduced-motion: reduce)").matches, +}; + +/** + * @param durations How long each scene's script runs. A scene without a script has no entry and is + * always at its finished state. + */ +export function createScenePlayer( + initial: MockupStateId, + durations: Partial>, + frames: Frames = browserFrames, +): ScenePlayer { + let scene = initial; + const times = new Map(); + const listeners = new Set<() => void>(); + let frame = 0; + let lastFrameAt = 0; + let played = false; + + function emit() { + for (const listener of listeners) listener(); + } + + function stop() { + if (frame) frames.cancel(frame); + frame = 0; + } + + function tick(now: number) { + const end = durations[scene] ?? 0; + const next = Math.min( + end, + (times.get(scene) ?? 0) + Math.min(now - lastFrameAt, LONGEST_FRAME_MS), + ); + lastFrameAt = now; + times.set(scene, next); + frame = next < end ? frames.request(tick) : 0; + emit(); + } + + function play() { + played = true; + stop(); + const end = durations[scene] ?? 0; + const animated = end > 0 && !frames.reducedMotion(); + times.set(scene, animated ? 0 : end); + if (animated) { + lastFrameAt = frames.now(); + frame = frames.request(tick); + } + emit(); + } + + return { + scene: () => scene, + elapsed: (of) => times.get(of) ?? 0, + select(next) { + scene = next; + play(); + }, + start() { + if (!played) play(); + }, + stop, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }; +} + +export const ScenePlayerContext = createContext(null); + +/** The scene a player shows. */ +export function usePlayerScene(player: ScenePlayer): MockupStateId { + return useSyncExternalStore(player.subscribe, player.scene, player.scene); +} + +/** + * Reads one fact about a scene at its current time, such as how many tool calls have landed. + * The component renders again only when that fact changes, so `select` must return a primitive. + */ +export function useSceneClock( + scene: MockupStateId, + select: (ms: number) => Fact, +): Fact { + const player = useContext(ScenePlayerContext); + if (!player) throw new Error("useSceneClock needs a ScenePlayerContext"); + const read = () => select(player.elapsed(scene)); + return useSyncExternalStore(player.subscribe, read, read); +} diff --git a/packages/website/src/components/mockup/plugin-build.ts b/packages/website/src/components/mockup/plugin-build.ts new file mode 100644 index 0000000000..99a6c747eb --- /dev/null +++ b/packages/website/src/components/mockup/plugin-build.ts @@ -0,0 +1,55 @@ +import { COMPOSER, script } from "./script"; + +const BUILD_REQUEST = "Build a release radar panel for merged PRs and failing checks."; +const CHANGE_REQUEST = "Show which check is failing."; + +/** + * The plugins scene: the user asks for a panel, the agent builds and installs a plugin, and the + * panel opens. Then the user asks for a change and the open panel shows it. + */ +export const PLUGIN_BUILD = script([ + { kind: "wait", ms: 200 }, + { kind: "click", target: COMPOSER }, + { kind: "wait", ms: 250 }, + { kind: "type", text: BUILD_REQUEST }, + { kind: "user", text: BUILD_REQUEST }, + { + kind: "agent", + text: "I’ll scaffold a local plugin, add the explorer surface, and wire it into the sidebar.", + }, + { + kind: "tools", + calls: [ + { kind: "read", detail: "paseo-plugin/SKILL.md" }, + { kind: "shell", detail: "paseo plugin init ~/dev/release-radar" }, + { kind: "write", detail: "~/dev/release-radar/release-radar.client.tsx" }, + { kind: "shell", detail: "paseo plugin install ~/dev/release-radar" }, + ], + }, + { kind: "mark", name: "installed", ms: 500 }, + { kind: "agent", text: "Release Radar is live. It should now be visible in the right sidebar." }, + { kind: "turnEnd", worked: "2m 14s" }, + { kind: "wait", ms: 900 }, + { kind: "type", text: CHANGE_REQUEST }, + { kind: "user", text: CHANGE_REQUEST }, + { + kind: "tools", + calls: [ + { kind: "write", detail: "~/dev/release-radar/release-radar.client.tsx" }, + { kind: "shell", detail: "paseo plugin reload release-radar" }, + ], + }, + { kind: "mark", name: "revised", ms: 500 }, + { kind: "agent", text: "Reloaded. The radar now lists the failing check under the tiles." }, + { kind: "turnEnd", worked: "19s" }, +]); + +/** Whether the plugin is installed: its panel is open and its item is in the sidebar. */ +export function pluginInstalled(ms: number): boolean { + return PLUGIN_BUILD.reached("installed", ms); +} + +/** Whether the reloaded plugin lists the failing check. */ +export function failingCheckListed(ms: number): boolean { + return PLUGIN_BUILD.reached("revised", ms); +} diff --git a/packages/website/src/components/mockup/pointer.tsx b/packages/website/src/components/mockup/pointer.tsx new file mode 100644 index 0000000000..23086c0239 --- /dev/null +++ b/packages/website/src/components/mockup/pointer.tsx @@ -0,0 +1,45 @@ +import { useMemo } from "react"; +import { PointerArrow } from "./icons"; +import { useSceneClock } from "./player"; +import type { PointerClick } from "./script"; +import type { MockupStateId } from "./states"; + +/** + * The visitor's stand-in: a mouse pointer that glides to a spot and clicks it. The spot is where + * `className` places the pointer in its nearest positioned ancestor. + */ +export function Pointer({ + scene, + click, + from, + className, +}: { + scene: MockupStateId; + click: PointerClick; + /** Where the pointer sets off from, in design pixels from the spot it clicks. */ + from: { x: number; y: number }; + className: string; +}) { + const opacity = useSceneClock(scene, click.opacity); + const approach = useSceneClock(scene, click.approach); + const pressed = useSceneClock(scene, click.pressed); + const style = useMemo( + () => ({ + opacity, + transform: `translate(${(1 - approach) * from.x}px, ${(1 - approach) * from.y}px)`, + }), + [opacity, approach, from], + ); + if (opacity === 0) return null; + return ( + + + + ); +} diff --git a/packages/website/src/components/mockup/providers.ts b/packages/website/src/components/mockup/providers.ts new file mode 100644 index 0000000000..167438ff7b --- /dev/null +++ b/packages/website/src/components/mockup/providers.ts @@ -0,0 +1,11 @@ +import { ClaudeIcon, CodexIcon, OpenCodeIcon, PiIcon } from "./icons"; + +/** Each agent provider the mockup shows: its name, its mark, and the model it runs. */ +export const PROVIDERS = { + claude: { name: "Claude Code", Icon: ClaudeIcon, model: "Opus 5.5" }, + codex: { name: "Codex", Icon: CodexIcon, model: "GPT-5.6-Sol" }, + opencode: { name: "OpenCode", Icon: OpenCodeIcon, model: "Kimi K3" }, + pi: { name: "Pi", Icon: PiIcon, model: "GLM-5.2" }, +}; + +export type ProviderId = keyof typeof PROVIDERS; diff --git a/packages/website/src/components/mockup/review-thread.tsx b/packages/website/src/components/mockup/review-thread.tsx new file mode 100644 index 0000000000..dffb3993ab --- /dev/null +++ b/packages/website/src/components/mockup/review-thread.tsx @@ -0,0 +1,231 @@ +import { AnimatePresence, motion } from "framer-motion"; +import { CircleCheck, Pencil, Plus, Send, Trash2 } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Caret } from "./atoms"; +import { FADE_IN, FADE_OUT, MOCKUP_TRANSITION } from "./motion"; +import { useSceneClock } from "./player"; +import { Pointer } from "./pointer"; +import { PROVIDERS, type ProviderId } from "./providers"; +import { + ADD_COMMENT_CLICK, + lineHovered, + RECIPIENT_CLICK, + recipientHovered, + REVIEW, + REVIEW_COMMENT, + reviewPhase, + SEND_FEEDBACK_CLICK, +} from "./review"; + +// The review scene, drawn like the app's review module (`packages/app/src/review`): the add +// button of a hovered line, the inline editor, the saved comment, and Send feedback. + +// --- on the line ------------------------------------------------------------ + +const POINTER_TO_LINE = { x: 240, y: 150 }; + +/** + * The add button a hovered line shows across its gutter's edge, and the pointer that clicks it. + * Goes in the line's gutter. + */ +export function AddCommentAction() { + const hovered = useSceneClock("review", lineHovered); + const pressed = useSceneClock("review", ADD_COMMENT_CLICK.pressed); + return ( + + {hovered ? ( + + + + ) : null} + + + ); +} + +function CommentEditor() { + const { t } = useTranslation(); + const body = useSceneClock("review", REVIEW.draft); + return ( +
+
+ {body ? ( + + {body} + + + ) : ( + + + {t("landing.mockup.app.reviewCommentPlaceholder")} + + )} +
+
+ + {t("landing.mockup.app.reviewCancel")} + + + {t("landing.mockup.app.reviewSave")} + +
+
+ ); +} + +function SavedComment() { + return ( +
+ {REVIEW_COMMENT} + + +
+ ); +} + +// The thread is as tall as what it holds plus 8 of padding above and below. +const THREAD_CLOSED = { height: 0, opacity: 0 }; +const THREAD_WRITING = { height: 110, opacity: 1 }; +const THREAD_COMMENTED = { height: 58, opacity: 1 }; + +/** The comment thread under the line: the editor first, then the saved comment until it is sent. */ +export function ReviewThread() { + const phase = useSceneClock("review", reviewPhase); + const writing = phase === "writing"; + const open = writing || phase === "commented" || phase === "choosing"; + return ( + + {open ? ( + +
{writing ? : }
+
+ ) : null} +
+ ); +} + +// --- over the diff ---------------------------------------------------------- + +function RecipientRow({ agent, lit = false }: { agent: ProviderId; lit?: boolean }) { + const provider = PROVIDERS[agent]; + return ( + + + + + {provider.name} + + ); +} + +/** Who gets the feedback. The workspace has two agent tabs, so Send feedback asks which one. */ +const RECIPIENT: ProviderId = "codex"; + +// Where the pointer sets off for Send feedback, and how far the picked agent's row is from there. +// The button is 32 high. The list floats 6 above it, with 4 of padding around two rows of 30. +const POINTER_TO_SEND = { x: -190, y: -170 }; +const POINTER_TO_RECIPIENT = { x: -6, y: 73 }; + +const FLOATING = "pointer-events-none absolute inset-x-0 bottom-[16px] flex justify-center"; +const FLOATING_SHADOW = "shadow-[0_8px_24px_rgba(0,0,0,0.4)]"; + +/** + * What floats over the bottom of the diff: Send feedback while a comment waits, the list of + * agents it opens, and the toast that says who got the feedback. + */ +export function ReviewFeedback() { + const { t } = useTranslation(); + const phase = useSceneClock("review", reviewPhase); + const pressed = useSceneClock("review", SEND_FEEDBACK_CLICK.pressed); + const recipientLit = useSceneClock("review", recipientHovered); + return ( + <> + + {phase === "commented" || phase === "choosing" ? ( + + + {phase === "choosing" ? ( + + + + + ) : null} + + + {t("landing.mockup.app.sendFeedback", { count: 1 })} + + + + ) : null} + {phase === "sent" ? ( + + + + {t("landing.mockup.app.feedbackSent", { recipient: PROVIDERS[RECIPIENT].name })} + + + ) : null} + + {/* Both spots are measured from the middle of the button's bottom edge. */} + + + + + + ); +} diff --git a/packages/website/src/components/mockup/review.ts b/packages/website/src/components/mockup/review.ts new file mode 100644 index 0000000000..858d633e28 --- /dev/null +++ b/packages/website/src/components/mockup/review.ts @@ -0,0 +1,54 @@ +import { script } from "./script"; + +/** What the reviewer writes on the line. */ +export const REVIEW_COMMENT = "Add “write”. The agent edits files too."; + +/** + * The code review scene: the pointer adds a comment on a line of the diff and the user types it. + * Then the pointer sends the feedback and picks the agent that gets it. + */ +export const REVIEW = script([ + { kind: "wait", ms: 300 }, + { kind: "click", target: "addComment" }, + { kind: "wait", ms: 250 }, + { kind: "type", text: REVIEW_COMMENT }, + { kind: "mark", name: "saved", ms: 450 }, + { kind: "click", target: "sendFeedback" }, + { kind: "click", target: "recipient" }, +]); + +/** The click on the add button of the line. It opens the comment editor. */ +export const ADD_COMMENT_CLICK = REVIEW.click("addComment"); +/** The click on Send feedback. It opens the list of agents. */ +export const SEND_FEEDBACK_CLICK = REVIEW.click("sendFeedback"); +/** The click on the agent that gets the feedback. */ +export const RECIPIENT_CLICK = REVIEW.click("recipient"); + +/** + * Where the review stands. + * + * - `reading`: no comment yet. + * - `writing`: the comment editor is open. + * - `commented`: the comment is saved and waits to be sent. + * - `choosing`: the list of agents is open. + * - `sent`: an agent has the feedback, and the saved comment is gone. + */ +export type ReviewPhase = "reading" | "writing" | "commented" | "choosing" | "sent"; + +export function reviewPhase(ms: number): ReviewPhase { + if (RECIPIENT_CLICK.done(ms)) return "sent"; + if (SEND_FEEDBACK_CLICK.done(ms)) return "choosing"; + if (REVIEW.reached("saved", ms)) return "commented"; + if (ADD_COMMENT_CLICK.done(ms)) return "writing"; + return "reading"; +} + +/** Whether the pointer is over the line. A hovered line shows its add button. */ +export function lineHovered(ms: number): boolean { + return ADD_COMMENT_CLICK.approach(ms) > 0.93 && !ADD_COMMENT_CLICK.done(ms); +} + +/** Whether the pointer is over the agent it is about to pick. */ +export function recipientHovered(ms: number): boolean { + return RECIPIENT_CLICK.approach(ms) > 0.8; +} diff --git a/packages/website/src/components/mockup/right-panel.tsx b/packages/website/src/components/mockup/right-panel.tsx index dc4e300683..32997a3fb2 100644 --- a/packages/website/src/components/mockup/right-panel.tsx +++ b/packages/website/src/components/mockup/right-panel.tsx @@ -1,5 +1,6 @@ import { CircleCheck, + CircleX, ChevronDown, ExternalLink, FileDiff, @@ -14,12 +15,26 @@ import type { TFunction } from "i18next"; import type * as React from "react"; import { useTranslation } from "react-i18next"; import { ChangesBranchRow, ChangesCommitsRow, ChangesScopeRow, ExplorerChangesTree } from "./diff"; -import { RIGHT_PANEL_W, TABBAR_H, TITLEBAR_H } from "./geometry"; -import type { MockupStateId } from "./states"; +import { RIGHT_PANEL_W, RIGHT_PANEL_WIDE_W, TABBAR_H, TITLEBAR_H } from "./geometry"; +import { AnimatePresence, motion } from "framer-motion"; +import { useSceneClock } from "./player"; +import { failingCheckListed } from "./plugin-build"; const TABBAR_STYLE = { height: TITLEBAR_H }; const SUBHEADER_STYLE = { height: TABBAR_H }; -const PANEL_STYLE = { width: RIGHT_PANEL_W }; + +export type PanelId = "changes" | "ship" | "plugin"; + +/** How wide the docked panel is for what it shows. Only the file tree fits the narrow width. */ +export function panelWidth(panel: PanelId): number { + return panel === "changes" ? RIGHT_PANEL_W : RIGHT_PANEL_WIDE_W; +} + +const PANEL_STYLES: Record = { + changes: { width: panelWidth("changes") }, + ship: { width: panelWidth("ship") }, + plugin: { width: panelWidth("plugin") }, +}; interface PanelTab { label: string; @@ -52,10 +67,12 @@ function PanelTabs({ tabs, active }: { tabs: PanelTab[]; active: number }) { } function PanelShell({ + panel, tabs, active, children, }: { + panel: PanelId; tabs: PanelTab[]; active: number; children: React.ReactNode; @@ -63,7 +80,7 @@ function PanelShell({ return (
{children} @@ -88,7 +105,7 @@ function changesTabs(t: TFunction): PanelTab[] { function ChangesPanel({ selectedFile }: { selectedFile?: string }) { const { t } = useTranslation(); return ( - + @@ -118,7 +135,7 @@ function CheckGlyph() { function ShipPanel() { const { t } = useTranslation(); return ( - +
+ +
+ {t("landing.mockup.app.failing")} +
+
+ + + + app-tests (macos) + + + #3976 · Honor configured commit signing + + + 5m 02s +
+
+ ); +} + +function PluginDashboard() { + const { t } = useTranslation(); + const listsFailingCheck = useSceneClock("extend", failingCheckListed); + return ( +
+ + {listsFailingCheck ? : null} + +
{t("landing.mockup.app.mergesWeek")} @@ -307,8 +356,8 @@ function PluginDashboard() { ); } -export function RightPanel({ state }: { state: MockupStateId }) { - if (state === "ship") return ; - if (state === "extend") return ; +export function RightPanel({ panel }: { panel: PanelId }) { + if (panel === "ship") return ; + if (panel === "plugin") return ; return ; } diff --git a/packages/website/src/components/mockup/script.test.ts b/packages/website/src/components/mockup/script.test.ts new file mode 100644 index 0000000000..10d27775d5 --- /dev/null +++ b/packages/website/src/components/mockup/script.test.ts @@ -0,0 +1,177 @@ +import { describe, expect, it } from "vitest"; +import { script } from "./script"; + +const REQUEST = "Rename the panel."; +const REPLY = "Renamed. The panel is now called Radar."; + +const scene = script([ + { kind: "wait", ms: 500 }, + { kind: "type", text: REQUEST }, + { kind: "user", text: REQUEST }, + { + kind: "tools", + calls: [ + { kind: "read", detail: "panel.tsx" }, + { kind: "write", detail: "panel.tsx" }, + ], + }, + { kind: "mark", name: "renamed", ms: 400 }, + { kind: "agent", text: REPLY }, + { kind: "turnEnd", worked: "8s" }, +]); + +const [sent, tools, reply, turnEnd] = scene.entries; + +function midway(entry: { start: number; end: number }): number { + return (entry.start + entry.end) / 2; +} + +const POINTER_ENTERS = 200; +const PAUSE_BEFORE_TYPING = 100; + +const pointed = script([ + { kind: "wait", ms: POINTER_ENTERS }, + { kind: "click", target: "composer" }, + { kind: "wait", ms: PAUSE_BEFORE_TYPING }, + { kind: "type", text: REQUEST }, + { kind: "user", text: REQUEST }, + { kind: "click", target: "pill" }, + { kind: "click", target: "menu" }, +]); +const composerClick = pointed.click("composer"); +const pillClick = pointed.click("pill"); +const menuClick = pointed.click("menu"); + +/** The first millisecond of the pointed scene at which something is true. */ +function firstMs(holds: (ms: number) => boolean): number { + for (let ms = 0; ms <= pointed.duration; ms += 1) { + if (holds(ms)) return ms; + } + throw new Error("It never holds"); +} + +describe("script", () => { + it("starts with an empty composer, an empty transcript, and no turn running", () => { + expect(scene.draft(0)).toBe(""); + expect(scene.entered(0)).toBe(0); + expect(scene.busy(0)).toBe(false); + }); + + it("types the request into the composer, then clears it when the message is sent", () => { + const typing = { start: 500, end: sent.start }; + const partial = scene.draft(typing.start + 200); + expect(partial.length).toBeGreaterThan(0); + expect(partial.length).toBeLessThan(REQUEST.length); + expect(REQUEST.startsWith(partial)).toBe(true); + + expect(scene.draft(typing.end - 1)).toBe(REQUEST); + expect(scene.draft(sent.start)).toBe(""); + expect(scene.entered(midway(sent))).toBe(1); + }); + + it("runs the turn from the sent message until the turn ends", () => { + expect(scene.busy(sent.start - 1)).toBe(false); + expect(scene.busy(sent.start)).toBe(true); + expect(scene.busy(midway(reply))).toBe(true); + expect(scene.busy(turnEnd.start)).toBe(false); + }); + + it("lands tool calls one at a time", () => { + expect(scene.landed(tools, tools.start)).toBe(0); + expect(scene.landed(tools, tools.start + 1)).toBe(1); + expect(scene.landed(tools, tools.end)).toBe(2); + }); + + it("streams the agent's text", () => { + expect(scene.streamed(reply, reply.start)).toBe(""); + const partial = scene.streamed(reply, midway(reply)); + expect(partial.length).toBeGreaterThan(0); + expect(partial.length).toBeLessThan(REPLY.length); + expect(REPLY.startsWith(partial)).toBe(true); + expect(scene.streamed(reply, reply.end)).toBe(REPLY); + }); + + it("reaches a mark after the beats before it and reports progress through it", () => { + expect(scene.reached("renamed", tools.end)).toBe(false); + expect(scene.reached("renamed", tools.end + 1)).toBe(true); + expect(scene.progress("renamed", tools.end + 100)).toBeCloseTo(0.25); + expect(scene.progress("renamed", reply.start)).toBe(1); + }); + + it("glides the pointer to its target, presses, and lets go", () => { + const pressedAt = firstMs(composerClick.pressed); + const doneAt = firstMs(composerClick.done); + + expect(composerClick.opacity(POINTER_ENTERS)).toBe(0); + expect(composerClick.approach(POINTER_ENTERS)).toBe(0); + + const gliding = (POINTER_ENTERS + pressedAt) / 2; + expect(composerClick.opacity(gliding)).toBe(1); + expect(composerClick.approach(gliding)).toBeGreaterThan(0); + expect(composerClick.approach(gliding)).toBeLessThan(1); + expect(composerClick.pressed(gliding)).toBe(false); + + expect(composerClick.approach(pressedAt)).toBe(1); + expect(composerClick.done(pressedAt)).toBe(false); + + expect(doneAt).toBeGreaterThan(pressedAt); + expect(composerClick.pressed(doneAt)).toBe(false); + }); + + it("keeps the pointer where it clicked until the user types", () => { + const typingAt = firstMs(composerClick.done) + PAUSE_BEFORE_TYPING; + expect(composerClick.opacity(typingAt - 1)).toBe(1); + expect(pointed.draft(typingAt - 1)).toBe(""); + + // The pointer fades away while the first characters land. + expect(pointed.draft(typingAt + 1)).not.toBe(""); + expect(composerClick.opacity(typingAt + 1)).toBeLessThan(1); + expect(composerClick.opacity(typingAt + 500)).toBe(0); + expect(composerClick.done(typingAt + 500)).toBe(true); + }); + + it("fades the pointer in when it comes back after typing", () => { + const setsOffAt = firstMs((ms) => pillClick.approach(ms) > 0); + expect(pillClick.opacity(setsOffAt)).toBeGreaterThan(0); + expect(pillClick.opacity(setsOffAt)).toBeLessThan(1); + }); + + it("moves one pointer from a click to the click after it", () => { + const handoffAt = firstMs(pillClick.done); + expect(pillClick.opacity(handoffAt - 1)).toBe(1); + expect(menuClick.opacity(handoffAt - 1)).toBe(0); + + expect(pillClick.opacity(handoffAt)).toBe(0); + expect(menuClick.opacity(handoffAt)).toBe(1); + expect(menuClick.approach(handoffAt)).toBe(0); + }); + + it("leaves the pointer on the last thing it clicked", () => { + expect(menuClick.opacity(pointed.duration)).toBe(1); + expect(menuClick.approach(pointed.duration)).toBe(1); + expect(menuClick.done(pointed.duration)).toBe(true); + expect(composerClick.opacity(pointed.duration)).toBe(0); + expect(composerClick.done(pointed.duration)).toBe(true); + }); + + it("ends a turn without a footer when the beat gives no time worked", () => { + const quiet = script([ + { kind: "user", text: REQUEST }, + { kind: "agent", text: REPLY }, + { kind: "turnEnd" }, + { kind: "wait", ms: 300 }, + ]); + const [, quietReply] = quiet.entries; + expect(quiet.entries.map((entry) => entry.beat.kind)).toEqual(["user", "agent"]); + expect(quiet.busy(quietReply.end - 1)).toBe(true); + expect(quiet.busy(quietReply.end)).toBe(false); + }); + + it("shows the finished scene at its duration", () => { + expect(scene.duration).toBe(turnEnd.end); + expect(scene.entered(scene.duration)).toBe(scene.entries.length); + expect(scene.draft(scene.duration)).toBe(""); + expect(scene.busy(scene.duration)).toBe(false); + expect(scene.reached("renamed", scene.duration)).toBe(true); + }); +}); diff --git a/packages/website/src/components/mockup/script.ts b/packages/website/src/components/mockup/script.ts new file mode 100644 index 0000000000..7079a587f0 --- /dev/null +++ b/packages/website/src/components/mockup/script.ts @@ -0,0 +1,267 @@ +import type { RemoteHostId } from "./hosts"; + +/** + * A collapsed tool call as the app's timeline shows it. Built-in tools carry a + * fixed label; Paseo MCP tools name their action, such as "Create agent". + */ +export type ToolCall = + | { kind: "read" | "write" | "shell"; detail: string } + | { kind: "paseo"; label: string; detail?: string; host?: RemoteHostId }; + +/** + * One step of a scripted scene. Beats play in order, each after the one before it ends. + * + * - `wait`: nothing happens. + * - `click`: the pointer glides to a named target and clicks it. + * - `type`: the user types into the composer. + * - `user`: the typed message is sent and joins the transcript. + * - `agent`: the agent's text streams into the transcript. + * - `tools`: the agent's tool calls land one at a time. + * - `turnEnd`: the turn finishes. With `worked`, its footer joins the transcript. + * - `mark`: a named moment the rest of the window reacts to, such as a panel opening. + */ +export type Beat = + | { kind: "wait"; ms: number } + | { kind: "click"; target: Target } + | { kind: "type"; text: string } + | { kind: "user"; text: string } + | { kind: "agent"; text: string } + | { kind: "tools"; calls: ToolCall[] } + | { kind: "turnEnd"; worked?: string } + | { kind: "mark"; name: Mark; ms: number }; + +type TranscriptBeat = + | Extract + | { kind: "turnEnd"; worked: string }; + +/** A beat that leaves something in the transcript, with the span of time it plays over. */ +export interface TranscriptEntry { + id: string; + start: number; + end: number; + beat: TranscriptBeat; +} + +/** One click of the pointer: it glides to its target, presses the button, and lets go. */ +export interface PointerClick { + /** + * How visible the pointer is for this click, from 0 to 1. It fades in on its way, and fades out + * when the user types. A click right after another one takes the same pointer over, with no fade. + */ + opacity(ms: number): number; + /** How far the pointer has come on its way to the target, from 0 to 1. */ + approach(ms: number): number; + /** Whether the pointer's button is down on the target. */ + pressed(ms: number): boolean; + /** Whether the click has happened: the button went down and came back up. */ + done(ms: number): boolean; +} + +/** The click target every scripted chat has. Clicking it puts the caret in the composer. */ +export const COMPOSER = "composer"; + +/** What a chat pane reads from a script: the composer and the transcript at a point in time. */ +export interface SceneScript { + /** The length of the whole script. At this time the scene shows its finished state. */ + duration: number; + entries: TranscriptEntry[]; + /** What the user is typing: the text so far, until it is sent. */ + draft(ms: number): string; + /** Whether a turn is running: from the user's message until the turn ends. */ + busy(ms: number): boolean; + /** How many transcript entries have started. */ + entered(ms: number): number; + /** How much of an agent entry's text has streamed in. */ + streamed(entry: TranscriptEntry, ms: number): string; + /** How many of a tools entry's calls have landed. */ + landed(entry: TranscriptEntry, ms: number): number; + /** The script's click on a target. */ + click(target: string): PointerClick; +} + +export interface Script extends SceneScript { + click(target: Target): PointerClick; + /** Whether a mark has started. */ + reached(mark: Mark, ms: number): boolean; + /** How far through a mark the scene is, from 0 to 1. */ + progress(mark: Mark, ms: number): number; +} + +// A demo types and streams faster than a person or a model does, and still reads as both. +const TYPING_MS_PER_CHARACTER = 14; +const SHORTEST_TYPING_MS = 700; +const PAUSE_BEFORE_SEND_MS = 320; +const SEND_MS = 420; +const STREAM_MS_PER_CHARACTER = 8; +const TOOL_CALL_MS = 320; +const TURN_END_MS = 420; +const POINTER_APPROACH_MS = 900; +const POINTER_PRESS_MS = 240; +const POINTER_FADE_MS = 150; + +function typingMs(text: string): number { + return Math.max(SHORTEST_TYPING_MS, text.length * TYPING_MS_PER_CHARACTER); +} + +function beatMs(beat: Beat): number { + switch (beat.kind) { + case "wait": + case "mark": + return beat.ms; + case "click": + return POINTER_APPROACH_MS + POINTER_PRESS_MS; + case "type": + return typingMs(beat.text) + PAUSE_BEFORE_SEND_MS; + case "user": + return SEND_MS; + case "agent": + return beat.text.length * STREAM_MS_PER_CHARACTER; + case "tools": + return beat.calls.length * TOOL_CALL_MS; + case "turnEnd": + return TURN_END_MS; + } +} + +function isTranscriptBeat(beat: Beat): beat is TranscriptBeat { + if (beat.kind === "turnEnd") return beat.worked !== undefined; + return beat.kind === "user" || beat.kind === "agent" || beat.kind === "tools"; +} + +function fraction(start: number, end: number, ms: number): number { + if (ms <= start) return 0; + if (ms >= end) return 1; + return (ms - start) / (end - start); +} + +// A hand speeds a mouse up and slows it down again. +function easeInOut(linear: number): number { + return linear < 0.5 ? 2 * linear * linear : 1 - (-2 * linear + 2) ** 2 / 2; +} + +function hundredths(value: number): number { + return Math.round(value * 100) / 100; +} + +/** How a click's pointer comes and goes. */ +interface PointerPresence { + /** When the pointer sets off. */ + start: number; + /** Whether the pointer is already on screen, at the click before this one. */ + continues: boolean; + /** When the pointer goes away, or `Infinity` when it stays to the end of the scene. */ + leaves: number; + /** Whether the next click takes the pointer over. Otherwise typing fades it out. */ + handsOver: boolean; +} + +function pointerClick({ start, continues, leaves, handsOver }: PointerPresence): PointerClick { + const pressStart = start + POINTER_APPROACH_MS; + const pressEnd = pressStart + POINTER_PRESS_MS; + return { + opacity(ms) { + if (ms >= leaves) { + return handsOver ? 0 : hundredths(1 - fraction(leaves, leaves + POINTER_FADE_MS, ms)); + } + if (continues) return ms >= start ? 1 : 0; + return hundredths(fraction(start, start + POINTER_FADE_MS, ms)); + }, + approach: (ms) => Math.round(easeInOut(fraction(start, pressStart, ms)) * 1000) / 1000, + pressed: (ms) => ms >= pressStart && ms < pressEnd, + done: (ms) => ms >= pressEnd, + }; +} + +/** Lays beats end to end and answers what the scene shows at any time. */ +export function script( + beats: Beat[], +): Script { + let clock = 0; + const timed = beats.map((beat, index) => { + const start = clock; + clock += beatMs(beat); + return { id: `${index}:${beat.kind}`, start, end: clock, beat }; + }); + const duration = clock; + + const entries: TranscriptEntry[] = []; + const typing: { start: number; end: number; text: string }[] = []; + const turns: { start: number; end: number }[] = []; + const marks = new Map(); + const clicks = new Map(); + // A hand that types is off the mouse, and the pointer has one place at a time. So typing takes + // the pointer off screen, and a click that follows a click takes the pointer over from it. + let pointerOnScreen = false; + timed.forEach(({ start, beat }, index) => { + if (beat.kind === "type") pointerOnScreen = false; + if (beat.kind !== "click") return; + const next = timed + .slice(index + 1) + .find((later) => later.beat.kind === "type" || later.beat.kind === "click"); + clicks.set( + beat.target, + pointerClick({ + start, + continues: pointerOnScreen, + leaves: next ? next.start : Infinity, + handsOver: next?.beat.kind === "click", + }), + ); + pointerOnScreen = true; + }); + for (const { id, start, end, beat } of timed) { + if (isTranscriptBeat(beat)) entries.push({ id, start, end, beat }); + if (beat.kind === "type") typing.push({ start, end, text: beat.text }); + if (beat.kind === "user") turns.push({ start, end: duration }); + if (beat.kind === "turnEnd") { + const turn = turns.at(-1); + if (turn) turn.end = start; + } + if (beat.kind === "mark") marks.set(beat.name, { start, end }); + } + + function span(mark: Mark) { + const found = marks.get(mark); + if (!found) throw new Error(`The script has no mark named ${mark}`); + return found; + } + + return { + duration, + entries, + draft(ms) { + const beat = typing.find(({ start, end }) => ms >= start && ms < end); + if (!beat) return ""; + const typed = fraction(beat.start, beat.start + typingMs(beat.text), ms); + return beat.text.slice(0, Math.ceil(typed * beat.text.length)); + }, + busy(ms) { + return turns.some(({ start, end }) => ms >= start && ms < end); + }, + entered(ms) { + // The last entry enters at the end of a script that closes on it, so the end counts. + return entries.filter(({ start }) => ms > start || ms >= duration).length; + }, + streamed(entry, ms) { + if (entry.beat.kind !== "agent") return ""; + const { text } = entry.beat; + return text.slice(0, Math.ceil(fraction(entry.start, entry.end, ms) * text.length)); + }, + landed(entry, ms) { + if (entry.beat.kind !== "tools") return 0; + return Math.ceil(fraction(entry.start, entry.end, ms) * entry.beat.calls.length); + }, + reached(mark, ms) { + return ms > span(mark).start || ms >= duration; + }, + progress(mark, ms) { + const { start, end } = span(mark); + return fraction(start, end, ms); + }, + click(target) { + const found = clicks.get(target); + if (!found) throw new Error(`The script has no click on ${target}`); + return found; + }, + }; +} diff --git a/packages/website/src/components/mockup/sidebar.tsx b/packages/website/src/components/mockup/sidebar.tsx index f1e5eeeed4..b536a760bf 100644 --- a/packages/website/src/components/mockup/sidebar.tsx +++ b/packages/website/src/components/mockup/sidebar.tsx @@ -6,7 +6,6 @@ import { CircleHelp, GitPullRequest, History, - House, PanelBottom, PanelLeft, Plus, @@ -18,10 +17,15 @@ import { SquarePlus, } from "lucide-react"; import type * as React from "react"; +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { SIDEBAR_W, TITLEBAR_H } from "./geometry"; +import { HostBadge, type RemoteHostId } from "./hosts"; import { PaseoMark } from "./icons"; import { FADE_IN, FADE_OUT } from "./motion"; +import { DELEGATED_TASKS, tasksDelegated } from "./orchestration"; +import { useSceneClock } from "./player"; +import { pluginInstalled } from "./plugin-build"; import type { MockupStateId } from "./states"; const SIDEBAR_STYLE = { width: SIDEBAR_W }; @@ -41,7 +45,7 @@ interface WorkspaceRow { title: string; avatar: Avatar; time: string; - host?: string; + host?: RemoteHostId; pr?: string; passed?: boolean; running?: boolean; @@ -65,6 +69,7 @@ const WORKING_ROWS: WorkspaceRow[] = [ id: "safe-area", title: "Fix commit safe area in emulators", avatar: PASEO, + host: "mac-mini", time: "4m", running: true, }, @@ -82,6 +87,7 @@ const READY_TO_REVIEW_ROWS: WorkspaceRow[] = [ id: "lineage", title: "Paseo homepage", avatar: PASEO, + host: "devbox", pr: "3981", passed: true, time: "now", @@ -97,6 +103,16 @@ const READY_TO_REVIEW_ROWS: WorkspaceRow[] = [ }, ]; +/** The workspaces the orchestrating agent created, one per delegated task. */ +const DELEGATED_ROWS: WorkspaceRow[] = DELEGATED_TASKS.map((task) => ({ + id: task.id, + title: task.title, + avatar: PASEO, + host: task.host, + time: "now", + running: true, +})); + const DONE_ROWS: WorkspaceRow[] = [ { id: "beta", title: "Release v0.7.0-beta.2", avatar: PASEO, time: "2h" }, { @@ -111,7 +127,7 @@ const DONE_ROWS: WorkspaceRow[] = [ id: "perms", title: "Design semantic permission sy…", avatar: PASEO, - host: "my-server", + host: "devbox", pr: "3981", passed: true, time: "7h", @@ -120,6 +136,7 @@ const DONE_ROWS: WorkspaceRow[] = [ id: "modules", title: "Plan modules and abstractions", avatar: PASEO, + host: "mac-mini", pr: "3884", passed: true, time: "1d", @@ -202,12 +219,7 @@ function RowMeta({ row }: { row: WorkspaceRow }) { if (row.host || row.pr) { return ( - {row.host ? ( - - - {row.host} - - ) : null} + {row.host ? : null} {row.host && row.pr ? · : null} {row.pr ? ( @@ -267,7 +279,18 @@ function GroupHeader({ icon, label }: { icon: React.ReactNode; label: string }) export function Sidebar({ state }: { state: MockupStateId }) { const { t } = useTranslation(); - const extending = state === "extend"; + // The plugin's item joins the nav when the plugin is installed, and each delegated workspace + // joins Working when the orchestrator creates it. + const pluginIsInstalled = useSceneClock("extend", pluginInstalled); + const delegated = useSceneClock("orchestrate", tasksDelegated); + const extending = state === "extend" && pluginIsInstalled; + const workingRows = useMemo( + () => + state === "orchestrate" + ? [...DELEGATED_ROWS.slice(0, delegated), ...WORKING_ROWS] + : WORKING_ROWS, + [state, delegated], + ); return (
@@ -321,7 +344,7 @@ export function Sidebar({ state }: { state: MockupStateId }) { - {WORKING_ROWS.map((row) => ( + {workingRows.map((row) => ( @@ -340,7 +363,7 @@ export function Sidebar({ state }: { state: MockupStateId }) { {t("landing.mockup.app.addProject")} - +
diff --git a/packages/website/src/components/mockup/states.ts b/packages/website/src/components/mockup/states.ts index 392244c267..c78033c8ae 100644 --- a/packages/website/src/components/mockup/states.ts +++ b/packages/website/src/components/mockup/states.ts @@ -1,13 +1,9 @@ -/** - * The states the hero mockup can be in, in pill order. Labels are copy — edit - * them here and nothing else has to change. - */ -/** The scenes the hero mockup can show; each pill's label is `landing.mockup.`. */ -export const MOCKUP_STATES = ["build", "review", "ship", "extend"] as const; +/** The scenes the hero mockup can show, in pill order. Each pill's label is `landing.mockup.`. */ +export const MOCKUP_STATES = ["orchestrate", "remote", "review", "ship", "extend"] as const; export type MockupStateId = (typeof MOCKUP_STATES)[number]; -export const DEFAULT_MOCKUP_STATE: MockupStateId = "build"; +export const DEFAULT_MOCKUP_STATE: MockupStateId = "orchestrate"; /** Which states keep a panel docked to the right of the workspace. */ export function hasRightPanel(_state: MockupStateId): boolean { diff --git a/packages/website/src/components/mockup/titlebar.tsx b/packages/website/src/components/mockup/titlebar.tsx index de99f4db76..849519739a 100644 --- a/packages/website/src/components/mockup/titlebar.tsx +++ b/packages/website/src/components/mockup/titlebar.tsx @@ -106,9 +106,17 @@ const WORKSPACE_TABS: Tab[] = [ const DIFF_TAB: Tab = { id: "diff", label: "Diff", icon: }; +/** The tab a scene has in front. The orchestrating agent is Claude; the remote scene is a terminal. */ +function activeTabId(state: MockupStateId): string { + if (state === "review") return DIFF_TAB.id; + if (state === "orchestrate") return "claude"; + if (state === "remote") return "terminal"; + return "codex"; +} + export function TabStrip({ state }: { state: MockupStateId }) { - const review = state === "review"; - const tabs = review ? [...WORKSPACE_TABS, DIFF_TAB] : WORKSPACE_TABS; + const tabs = state === "review" ? [...WORKSPACE_TABS, DIFF_TAB] : WORKSPACE_TABS; + const activeId = activeTabId(state); return (
{tab.icon} diff --git a/packages/website/src/components/mockup/window.tsx b/packages/website/src/components/mockup/window.tsx index ae95b68867..b2cf07bb3f 100644 --- a/packages/website/src/components/mockup/window.tsx +++ b/packages/website/src/components/mockup/window.tsx @@ -1,57 +1,123 @@ import { AnimatePresence, MotionConfig, motion, useReducedMotion } from "framer-motion"; -import { AgentTranscript, Composer, PluginBuildTranscript } from "./chat"; -import { DESIGN_HEIGHT, DESIGN_WIDTH, RIGHT_PANEL_W } from "./geometry"; +import type * as React from "react"; +import { useMemo } from "react"; +import { + AgentTranscript, + Composer, + ProgressTrack, + ScriptedComposer, + ScriptedTranscript, + SubagentsTrack, +} from "./chat"; +import { DESIGN_HEIGHT, DESIGN_WIDTH } from "./geometry"; +import { HostsModal } from "./hosts"; import { FADE_IN, FADE_OUT, INSTANT_TRANSITION, MOCKUP_TRANSITION } from "./motion"; -import { DiffReviewPane } from "./panes"; -import { RightPanel } from "./right-panel"; +import { ORCHESTRATION } from "./orchestration"; +import { DiffReviewPane, RemoteTerminalPane } from "./panes"; +import { + createScenePlayer, + type ScenePlayer, + ScenePlayerContext, + usePlayerScene, + useSceneClock, +} from "./player"; +import { PLUGIN_BUILD, pluginInstalled } from "./plugin-build"; +import { REVIEW } from "./review"; +import type { ProviderId } from "./providers"; +import { type PanelId, panelWidth, RightPanel } from "./right-panel"; +import type { SceneScript } from "./script"; import { Sidebar } from "./sidebar"; -import { hasRightPanel, type MockupStateId } from "./states"; +import { DEFAULT_MOCKUP_STATE, hasRightPanel, type MockupStateId } from "./states"; import { TabStrip, TitleBar } from "./titlebar"; const WINDOW_STYLE = { width: DESIGN_WIDTH, height: DESIGN_HEIGHT }; -const PANEL_STYLE = { width: RIGHT_PANEL_W }; const PANEL_COLLAPSED = { width: 0, opacity: 0 }; -const PANEL_OPEN = { width: RIGHT_PANEL_W + 1, opacity: 1 }; -/** Which center pane a state shows. States sharing a key keep it mounted. */ -function centerKey(state: MockupStateId): string { - if (state === "review") return "review"; - if (state === "extend") return "extend"; - return "chat"; +/** Which panel is docked on the right. The plugin's panel exists once the plugin is installed. */ +function dockedPanel(state: MockupStateId, pluginIsInstalled: boolean): PanelId { + if (state === "ship") return "ship"; + if (state === "extend" && pluginIsInstalled) return "plugin"; + return "changes"; } -function panelKey(state: MockupStateId): string { - if (state === "ship") return "ship"; - if (state === "extend") return "extend"; - return "changes"; +// Elements passed as props are hoisted so they are not rebuilt on every render. +const PROGRESS_TRACK = ; + +/** The scenes that play a script, with the agent the user talks to and that agent's composer track. */ +const SCRIPTED_SCENES: Partial< + Record +> = { + orchestrate: { script: ORCHESTRATION, agent: "claude", track: }, + extend: { script: PLUGIN_BUILD, agent: "codex" }, +}; + +/** A player for the mockup's scenes. It opens on the default scene. */ +export function createMockupPlayer(): ScenePlayer { + return createScenePlayer(DEFAULT_MOCKUP_STATE, { + orchestrate: ORCHESTRATION.duration, + extend: PLUGIN_BUILD.duration, + review: REVIEW.duration, + }); +} + +export { usePlayerScene as useMockupScene }; + +/** What the agent tab in front says in each scene. */ +function Transcript({ state }: { state: MockupStateId }) { + const scripted = SCRIPTED_SCENES[state]; + if (scripted) return ; + return ; +} + +/** The composer under that transcript: whose agent it is, its track, and whether a turn runs. */ +function ChatComposer({ state }: { state: MockupStateId }) { + const scripted = SCRIPTED_SCENES[state]; + if (scripted) { + return ( + + ); + } + return ; } function CenterPane({ state }: { state: MockupStateId }) { if (state === "review") return ; + if (state === "remote") return ; return (
- {/* Bottom-anchored: the newest turn sits on the composer, older text clips. */} -
- {state === "extend" ? : } + {/* A chat scrolls like this: a short transcript starts at the top, and one taller than the + pane keeps its newest turn on the composer while older text clips. The reversed column + pins the bottom, and the auto margin lifts a short transcript to the top. */} +
+
+ +
- +
); } -/** The docked panel keeps its width while its contents swap. */ -function PanelCrossfade({ state }: { state: MockupStateId }) { +/** The docked panel's contents cross-fade when the panel it shows changes. */ +function PanelCrossfade({ panel }: { panel: PanelId }) { return ( -
+
+ {/* Each panel keeps its own width and the dock clips it, so nothing inside a panel + reflows while the dock resizes. */} - +
@@ -67,7 +133,7 @@ function CenterColumn({ state }: { state: MockupStateId }) {
({ width: panelWidth(panel) + 1, opacity: 1 }), [panel]); return (
- + ); } -export function MockupWindow({ state }: { state: MockupStateId }) { +export function MockupWindow({ player }: { player: ScenePlayer }) { const reduceMotion = useReducedMotion(); + const state = usePlayerScene(player); return ( - -
- {/* Three full-height columns, each owning its own header. The middle + + +
+ {/* Three full-height columns, each owning its own header. The middle header stops at the divider — it never spans over the right panel. */} - -
- - - {hasRightPanel(state) ? : null} - -
- + +
+ + + {hasRightPanel(state) ? : null} + + {/* The remote scene opens the hosts modal over the whole window, as the app dims + everything behind a modal. */} + + {state === "remote" ? ( + + + + ) : null} + +
+ + ); } diff --git a/packages/website/src/i18n/resources/en.json b/packages/website/src/i18n/resources/en.json index b179f26326..9326886f40 100644 --- a/packages/website/src/i18n/resources/en.json +++ b/packages/website/src/i18n/resources/en.json @@ -446,7 +446,8 @@ }, "mockup": { "alt": "Paseo desktop app with coding agents, a conversation, and a code diff open side by side", - "build": "Parallel agents", + "orchestrate": "Orchestration", + "remote": "Remote", "review": "Code review", "ship": "Pull requests", "extend": "Plugins", @@ -459,6 +460,15 @@ "working": "Working", "done": "Done", "addProject": "Add project", + "addHost": "Add host", + "hosts": "Hosts", + "agentCount": "{{count}} agents", + "hostLinks": { + "local": "Local", + "relay": "Relay", + "tailscale": "Tailscale", + "ssh": "SSH" + }, "files": "Files", "changes": "Changes", "uncommitted": "Uncommitted", @@ -473,6 +483,11 @@ "tasksProgress": "{{completed}}/{{total}} tasks", "composerPlaceholder": "Message the agent, tag @files, or use /commands and /skills", "mobileComposerPlaceholder": "Message, @files, /commands", + "reviewCommentPlaceholder": "Leave a comment", + "reviewCancel": "Cancel", + "reviewSave": "Comment", + "sendFeedback": "Send feedback ({{count}})", + "feedbackSent": "Feedback sent to {{recipient}}", "plugin": "plugin", "mergedWeek": "Merged · 7d", "inReview": "In review", @@ -482,7 +497,8 @@ "minutesAgo": "{{count}}m ago", "hoursAgo": "{{count}}h ago", "reviewing": "reviewing", - "subagents": "{{count}} subagents", + "subagents_one": "{{count}} subagent", + "subagents_other": "{{count}} subagents", "checksPassedShort": "passed" } } diff --git a/packages/website/src/i18n/resources/zh-CN.json b/packages/website/src/i18n/resources/zh-CN.json index cc20bdb43e..7c1d8d9617 100644 --- a/packages/website/src/i18n/resources/zh-CN.json +++ b/packages/website/src/i18n/resources/zh-CN.json @@ -446,7 +446,8 @@ }, "mockup": { "alt": "Paseo 桌面应用,并排打开了编程 Agent、一段对话和一份代码 diff", - "build": "并行 Agent", + "orchestrate": "编排", + "remote": "远程", "review": "代码审查", "ship": "Pull Request", "extend": "插件", @@ -459,6 +460,15 @@ "working": "运行中", "done": "已完成", "addProject": "添加 project", + "addHost": "添加主机", + "hosts": "主机", + "agentCount": "{{count}} 个 Agent", + "hostLinks": { + "local": "本地", + "relay": "中继", + "tailscale": "Tailscale", + "ssh": "SSH" + }, "files": "文件", "changes": "变更", "uncommitted": "未 commit", @@ -473,6 +483,11 @@ "tasksProgress": "{{completed}}/{{total}} 项任务", "composerPlaceholder": "给 Agent 发消息,标记 @files,或使用 /commands 和 /skills", "mobileComposerPlaceholder": "发消息,@files,/commands", + "reviewCommentPlaceholder": "留下评论", + "reviewCancel": "取消", + "reviewSave": "评论", + "sendFeedback": "发送反馈 ({{count}})", + "feedbackSent": "已向 {{recipient}} 发送反馈", "plugin": "插件", "mergedWeek": "已合并 · 7 天", "inReview": "审查中", @@ -482,7 +497,8 @@ "minutesAgo": "{{count}} 分钟前", "hoursAgo": "{{count}} 小时前", "reviewing": "审查中", - "subagents": "{{count}} 个 subagent", + "subagents_one": "{{count}} 个 subagent", + "subagents_other": "{{count}} 个 subagent", "checksPassedShort": "通过" } } diff --git a/packages/website/src/styles.css b/packages/website/src/styles.css index cadcce2b6d..8d007eb5d4 100644 --- a/packages/website/src/styles.css +++ b/packages/website/src/styles.css @@ -770,7 +770,11 @@ --color-mock-tile-violet: #7a6aa8; --color-mock-tile-amber: #8f7838; --color-mock-tile-teal: #368080; + /* Host badge ink — the identity colors as foreground, IDENTITY_FOREGROUND_DARK in the + same file. */ --color-mock-host-teal: #6cacab; + --color-mock-host-violet: #a392d5; + --color-mock-host-orange: #cc8f64; /* Status *dot* band (dark: L=0.72, chroma 90%). Sidebar row state dots only. theme.ts:198-204. */ From 2eba291a8e47e8718880ef1eb5f41fbb2342ebad Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:01:41 +0000 Subject: [PATCH 082/160] Keep idle Claude agents running while a session cron or /loop wakeup is pending (#9744) * fix(claude): keep an idle agent running while it has a session cron Claude keeps session-only crons and /loop wakeups in its own process, so stopping that process drops them. The idle runtime cleanup asked the Claude session whether it could stop, and the session never knew about these jobs: they appear nowhere on the message stream. Claude lists them as session_crons on every Stop hook. The session now records that list, and canStopRuntime() refuses while it is non-empty. The next Stop after a fire, a CronDelete or an expiry updates the list. Co-authored-by: KronixDev <35991992+KronixDev@users.noreply.github.com> * refactor(claude): type the Stop hook with the SDK's hook input Co-authored-by: KronixDev <35991992+KronixDev@users.noreply.github.com> * fix(claude): hold the runtime after a cron tool call until the next Stop Claude lists session crons only in the Stop hook, and runs Stop only for turns that complete. A turn that called CronCreate and was interrupted or failed left the count at zero, so idle cleanup could still stop the process holding the cron. A CronCreate, CronDelete or ScheduleWakeup call now marks the count unknown until the next Stop reports it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: KronixDev <35991992+KronixDev@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../claude/agent.background-subagent.test.ts | 29 +++++- .../server/agent/providers/claude/agent.ts | 9 +- .../providers/claude/runtime-safety.test.ts | 44 ++++++++++ .../agent/providers/claude/runtime-safety.ts | 22 ++++- ...session-cron-idle-cleanup.real.e2e.test.ts | 88 +++++++++++++++++++ 5 files changed, 188 insertions(+), 4 deletions(-) create mode 100644 packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts diff --git a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts index 432071741f..aaad3592a3 100644 --- a/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.background-subagent.test.ts @@ -1,5 +1,12 @@ import { ClaudeRuntimeSafety } from "./runtime-safety.js"; -import type { Query, SDKMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { + HookCallback, + Query, + SDKMessage, + SDKUserMessage, + SessionCronSummary, + StopHookInput, +} from "@anthropic-ai/claude-agent-sdk"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -884,6 +891,7 @@ test("Claude session runtime safety observes pumped background work and autonomo wake?.(); }; let nativeInput!: AsyncIterator; + let stopHook: HookCallback | undefined; let connected!: () => void; const connection = new Promise((resolve) => { connected = resolve; @@ -908,9 +916,10 @@ test("Claude session runtime safety observes pumped background work and autonomo const session = await new ClaudeAgentClient({ logger: createTestLogger(), resolveBinary: async () => "/test/claude/bin", - queryFactory: ({ prompt }) => { + queryFactory: ({ prompt, options }) => { if (typeof prompt === "string") throw new Error("Expected streaming input"); nativeInput = prompt[Symbol.asyncIterator](); + stopHook = options?.hooks?.Stop?.[0]?.hooks[0]; connected(); return query; }, @@ -957,6 +966,22 @@ test("Claude session runtime safety observes pumped background work and autonomo expect(await session.canStopRuntime!()).toBe(false); await push(result); expect(await session.canStopRuntime!()).toBe(true); + // A session-only cron lives in this process, and Claude reports it only to the Stop hook. + const stop = (session_crons: SessionCronSummary[]) => { + const stopInput: StopHookInput = { + hook_event_name: "Stop", + session_id: "runtime-safety", + transcript_path: "", + cwd: process.cwd(), + stop_hook_active: false, + session_crons, + }; + return stopHook!(stopInput, undefined, { signal: new AbortController().signal }); + }; + await stop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" }]); + expect(await session.canStopRuntime!()).toBe(false); + await stop([]); + expect(await session.canStopRuntime!()).toBe(true); } finally { await session.close(); } diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index ace2320de6..f4ef42bc2c 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -14,6 +14,7 @@ import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.j import { type AgentDefinition, type CanUseTool, + type HookCallback, type McpServerConfig as ClaudeSdkMcpServerConfig, type PermissionMode, type PermissionResult, @@ -3804,7 +3805,7 @@ class ClaudeAgentSession implements AgentSession { // subagents keep running. Without this declaration an interrupt kills every one of them. // Claude stops a helper itself with its TaskStop tool. perTaskStopAffordance: true, - hooks: this.buildSubagentEffortHooks(), + hooks: { ...this.buildSubagentEffortHooks(), Stop: [{ hooks: [this.observeStopHook] }] }, ...(this.persistSession === undefined ? {} : { persistSession: this.persistSession }), env: sdkEnv, }; @@ -5480,6 +5481,12 @@ class ClaudeAgentSession implements AgentSession { }; } + // Observation-only, like the effort hooks: it never alters turn control. + private readonly observeStopHook: HookCallback = async (input) => { + if (input.hook_event_name === "Stop") this.runtimeSafety.observeStop(input.session_crons); + return {}; + }; + private notifySubscribers(event: AgentStreamEvent): void { const turnId = getAgentStreamEventTurnId(event) ?? this.activeForegroundTurnId ?? this.autonomousTurn?.id; diff --git a/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts b/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts index 6651f3e909..a56516a70d 100644 --- a/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts +++ b/packages/server/src/server/agent/providers/claude/runtime-safety.test.ts @@ -46,3 +46,47 @@ test("enriches only live tasks with their correlated launch metadata", () => { runtime.observe(message({ type: "system", subtype: "background_tasks_changed", tasks: [] })), ).toEqual([]); }); + +test("keeps the runtime while Claude's last Stop hook lists session crons", () => { + const runtime = new ClaudeRuntimeSafety(); + runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" })); + const cron = { id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" }; + + runtime.observeStop([cron]); + expect(runtime.canStopRuntime()).toBe(false); + + runtime.observeStop(undefined); + expect(runtime.canStopRuntime()).toBe(false); + + runtime.observeStop([]); + expect(runtime.canStopRuntime()).toBe(true); + + runtime.observeStop([cron]); + runtime.reset(); + runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" })); + expect(runtime.canStopRuntime()).toBe(true); +}); + +test("holds the runtime when a turn that called a cron tool ends without a Stop hook", () => { + const runtime = new ClaudeRuntimeSafety(); + runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" })); + const callTool = (name: string) => + runtime.observe( + message({ + type: "assistant", + message: { content: [{ type: "tool_use", id: `${name}-1`, name, input: {} }] }, + }), + ); + + // The turn schedules a cron and is interrupted, so no Stop hook reports it. + callTool("CronCreate"); + expect(runtime.canStopRuntime()).toBe(false); + + runtime.observeStop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "hi" }]); + callTool("CronDelete"); + runtime.observeStop([]); + expect(runtime.canStopRuntime()).toBe(true); + + callTool("ScheduleWakeup"); + expect(runtime.canStopRuntime()).toBe(false); +}); diff --git a/packages/server/src/server/agent/providers/claude/runtime-safety.ts b/packages/server/src/server/agent/providers/claude/runtime-safety.ts index 8688e93f45..e8ff315a58 100644 --- a/packages/server/src/server/agent/providers/claude/runtime-safety.ts +++ b/packages/server/src/server/agent/providers/claude/runtime-safety.ts @@ -1,8 +1,10 @@ -import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { SDKMessage, SessionCronSummary } from "@anthropic-ai/claude-agent-sdk"; import type { AgentBackgroundWorkInput } from "../../background-work/index.js"; import { parseClaudeCodeVersion } from "./model-manifest.js"; import { toBackgroundWorkInputs, type ClaudeBackgroundTask } from "./background-work.js"; +const SESSION_CRON_TOOLS = new Set(["CronCreate", "CronDelete", "ScheduleWakeup"]); + /** Process-local background ownership. Completion delivery can follow an empty roster. */ export class ClaudeRuntimeSafety { private inventoryState: "unknown" | "supported" | "retired" = "unknown"; @@ -16,8 +18,15 @@ export class ClaudeRuntimeSafety { private readonly monitorTools = new Set(); private readonly toolInputs = new Map(); private readonly taskTools = new Map(); + // Session-only crons and wakeups live in the process and die with it. Only the Stop hook + // lists them, and Claude runs it only for turns that complete. A cron tool call makes the + // count unknown until the next Stop, so an interrupted or failed turn keeps the runtime. + private sessionCrons = 0; + private sessionCronsUnknown = false; reset(): void { + this.sessionCrons = 0; + this.sessionCronsUnknown = false; this.inventoryState = "unknown"; this.turnSeen = false; this.liveTasks = []; @@ -38,6 +47,13 @@ export class ClaudeRuntimeSafety { this.turnSeen = true; } + /** Called with the session crons of each main-thread Stop hook. Older CLIs omit them. */ + observeStop(sessionCrons: readonly SessionCronSummary[] | undefined): void { + if (this.inventoryState === "retired") return; + this.sessionCronsUnknown = false; + if (sessionCrons) this.sessionCrons = sessionCrons.length; + } + /** Returns a full replacement only when the visible inventory changes. */ observe(message: SDKMessage): AgentBackgroundWorkInput[] | undefined { if (this.inventoryState === "retired") return undefined; @@ -54,6 +70,8 @@ export class ClaudeRuntimeSafety { if (message.type === "assistant") { let relevant = false; for (const block of message.message.content) { + if (block.type === "tool_use" && SESSION_CRON_TOOLS.has(block.name)) + this.sessionCronsUnknown = true; if (block.type === "tool_use" && (block.name === "Monitor" || block.name === "Bash")) { if (block.name === "Monitor") relevant = this.observeMonitor(block.id) || relevant; relevant = this.observeInput(block.id, block.input) || relevant; @@ -129,6 +147,8 @@ export class ClaudeRuntimeSafety { if (this.inventoryState === "unknown" && !this.turnSeen) return true; return ( this.inventoryState === "supported" && + this.sessionCrons === 0 && + !this.sessionCronsUnknown && this.liveTasks.length === 0 && this.awaitingNotifications.size === 0 ); diff --git a/packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts new file mode 100644 index 0000000000..eb8352c348 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/claude-session-cron-idle-cleanup.real.e2e.test.ts @@ -0,0 +1,88 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; +import { beforeAll, beforeEach, describe, expect, test } from "vitest"; + +import type { AgentStreamEvent } from "../agent/agent-sdk-types.js"; +import { + canRunRealProvider, + createRealProviderClient, + getRealProviderConfig, +} from "./real-provider-test-config.js"; + +describe("real claude: idle runtime cleanup and session crons", () => { + let canRun = false; + beforeAll(async () => { + canRun = await canRunRealProvider("claude"); + }); + beforeEach((context) => { + if (!canRun) context.skip(); + }); + + test("a runtime holding a session-only cron is kept until the cron is deleted", async () => { + const logger = pino({ level: "silent" }); + const client = createRealProviderClient("claude", logger); + const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-session-cron-")); + const session = await client.createSession({ + cwd, + ...getRealProviderConfig("claude"), + }); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.run( + "Call the CronCreate tool exactly once with cron '0 */6 * * *', recurring true, durable false, prompt 'say hi'. Then reply with exactly: DONE", + ); + const cronResult = events.find( + (event) => + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.name === "CronCreate" && + event.item.status === "completed", + ); + expect(cronResult, JSON.stringify(events.slice(-5))).toBeDefined(); + expect(await session.canStopRuntime!()).toBe(false); + + await session.run( + "Delete every scheduled cron job with the CronDelete tool. Then reply with exactly: DONE", + ); + expect(await session.canStopRuntime!()).toBe(true); + } finally { + await session.close(); + } + }, 240_000); + + test("a turn interrupted after it creates a session-only cron keeps the runtime", async () => { + const logger = pino({ level: "silent" }); + const client = createRealProviderClient("claude", logger); + const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-session-cron-")); + const session = await client.createSession({ + cwd, + ...getRealProviderConfig("claude"), + }); + const cronCreated = new Promise((resolve) => { + session.subscribe((event) => { + if ( + event.type === "timeline" && + event.item.type === "tool_call" && + event.item.name === "CronCreate" && + event.item.status === "completed" + ) + resolve(); + }); + }); + try { + await session.startTurn( + "Call the CronCreate tool exactly once with cron '0 */6 * * *', recurring true, durable false, prompt 'say hi'. Then run the Bash command 'sleep 120' in the foreground. Then reply with exactly: DONE", + ); + await cronCreated; + await session.interrupt(); + // The cancelled turn settles about a second after interrupt() resolves. + await new Promise((resolve) => setTimeout(resolve, 5_000)); + expect(await session.canStopRuntime!()).toBe(false); + } finally { + await session.close(); + } + }, 240_000); +}); From dd06bc083361e9d8f669df88f83ba607644d7620 Mon Sep 17 00:00:00 2001 From: Marcel Wysocki Date: Sun, 15 Nov 2026 18:52:01 +0800 Subject: [PATCH 083/160] test(terminal): wait for the newer worker to exit after a kill stop (#9290) Cleanup counts a worker gone once its socket refuses connections, and the worker stops listening before its process exits. The test checked the worker pid right after closeTerminals() resolved, so it failed whenever the worker was still exiting. Wait for the pid to disappear, as the adjacent shutdown tests do. --- packages/server/src/terminal/worker-terminal-manager.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/server/src/terminal/worker-terminal-manager.test.ts b/packages/server/src/terminal/worker-terminal-manager.test.ts index e57e413b4c..6864c76152 100644 --- a/packages/server/src/terminal/worker-terminal-manager.test.ts +++ b/packages/server/src/terminal/worker-terminal-manager.test.ts @@ -1690,8 +1690,10 @@ it("leaves a worker from a newer Paseo running, reports it incompatible, and clo await manager.closeTerminals(); - expect(isProcessAlive(newer.workerPid)).toBe(false); expect(isProcessAlive(newer.programPid)).toBe(false); + // Cleanup counts the worker gone once its socket refuses connections, which happens before + // its process exits. + await waitForCondition(() => !isProcessAlive(newer.workerPid), 5000); expect(await workerRecords(paseoHome)).toEqual([]); }); From 5a7a60ae50809d4dcbe2126b24501080fa61f3fe Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 18:32:17 +0700 Subject: [PATCH 084/160] test(website): wait for hydration before the hero tests scroll (#9762) The router scrolls the window back to the top when the page hydrates. The hero tests scrolled to the mockup right after load, so in WebKit the reset sometimes landed after the test's scroll and the opening scene never started. The language button turns enabled in the render after that reset. The changelog and plugins specs already waited on it with their own copies; the wait now lives in the shared fixtures and the hero tests open the page with it. --- packages/website/e2e/changelog.spec.ts | 7 ++----- packages/website/e2e/fixtures.ts | 11 ++++++++++- packages/website/e2e/mockups.spec.ts | 15 +++++++-------- packages/website/e2e/plugins.spec.ts | 16 +++++----------- 4 files changed, 24 insertions(+), 25 deletions(-) diff --git a/packages/website/e2e/changelog.spec.ts b/packages/website/e2e/changelog.spec.ts index c95b389544..2e50ff5da4 100644 --- a/packages/website/e2e/changelog.spec.ts +++ b/packages/website/e2e/changelog.spec.ts @@ -1,4 +1,4 @@ -import { expect, test, type Locator, type Page } from "./fixtures"; +import { expect, test, waitForHydration, type Locator, type Page } from "./fixtures"; // The page renders the repository's CHANGELOG.md, so releases are found by shape, never by version: // a release with highlights has the toggle, a release without them does not. @@ -6,12 +6,9 @@ function releases(page: Page): Locator { return page.getByRole("region"); } -// The router resets the scroll position when the page hydrates. A click sent before that is aimed -// at where the control was, so wait for the page to be interactive: the language button is enabled -// once it has hydrated. async function openChangelog(page: Page): Promise { await page.goto("/changelog"); - await expect(page.getByRole("button", { name: /^Language/ }).first()).toBeEnabled(); + await waitForHydration(page); } function releaseWithHighlights(page: Page): Locator { diff --git a/packages/website/e2e/fixtures.ts b/packages/website/e2e/fixtures.ts index a0d0ed2e8f..16ed1a3bb0 100644 --- a/packages/website/e2e/fixtures.ts +++ b/packages/website/e2e/fixtures.ts @@ -1,8 +1,17 @@ -import { test as base } from "playwright/test"; +import { expect, test as base, type Page } from "playwright/test"; export { expect } from "playwright/test"; export type { Locator, Page } from "playwright/test"; +/** + * Waits until the page has hydrated. Server-rendered content shows before that, but it has no + * click handlers yet, and the router scrolls the window back to the top when it hydrates. + * The language button stays disabled until the render after that reset. + */ +export async function waitForHydration(page: Page) { + await expect(page.getByRole("button", { name: /^(Language|语言)/ }).first()).toBeEnabled(); +} + export const test = base.extend({ page: async ({ page, baseURL }, run) => { page.on("response", async (response) => { diff --git a/packages/website/e2e/mockups.spec.ts b/packages/website/e2e/mockups.spec.ts index 8ae8a9c272..174f17781a 100644 --- a/packages/website/e2e/mockups.spec.ts +++ b/packages/website/e2e/mockups.spec.ts @@ -1,12 +1,13 @@ -import { expect, test, type Locator, type Page } from "./fixtures"; +import { expect, test, waitForHydration, type Locator, type Page } from "./fixtures"; const desktopName = "Paseo desktop app with coding agents, a conversation, and a code diff open side by side"; -async function openHomepage(page: Page) { - await page.setViewportSize({ width: 1512, height: 930 }); +/** Opens the homepage once it has hydrated, so the router's scroll reset cannot undo a later scroll. */ +async function openHomepage(page: Page, window = { width: 1512, height: 930 }) { + await page.setViewportSize(window); await page.goto("/"); - await expect(page.getByRole("button", { name: "Orchestration", exact: true })).toBeVisible(); + await waitForHydration(page); } async function viewPhones(page: Page) { @@ -148,8 +149,7 @@ test("the opening scene waits until most of the mockup is on screen", async ({ p }); test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => { - await page.setViewportSize({ width: 1400, height: 400 }); - await page.goto("/"); + await openHomepage(page, { width: 1400, height: 400 }); const mockup = page.getByRole("img", { name: desktopName, exact: true }); const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); await mockup.scrollIntoViewIfNeeded(); @@ -240,8 +240,7 @@ test("picking a scene while the hero is still sliding in keeps the pills on scre }) => { // Reduced motion makes the scroll instant, so the test does not wait for one to settle. await page.emulateMedia({ reducedMotion: "reduce" }); - await page.setViewportSize({ width: 1280, height: 700 }); - await page.goto("/"); + await openHomepage(page, { width: 1280, height: 700 }); const mockup = page.getByRole("img", { name: desktopName, exact: true }); await playScene(page, "Remote", page.getByRole("button", { name: "Remote", pressed: true })); diff --git a/packages/website/e2e/plugins.spec.ts b/packages/website/e2e/plugins.spec.ts index 26e1ccfd94..7d02e9d7d5 100644 --- a/packages/website/e2e/plugins.spec.ts +++ b/packages/website/e2e/plugins.spec.ts @@ -1,5 +1,5 @@ import securityPlugin from "./overview.fixture.json" with { type: "json" }; -import { expect, test, type Page, type Locator } from "./fixtures"; +import { expect, test, waitForHydration, type Page, type Locator } from "./fixtures"; import registry from "./registry.fixture.json" with { type: "json" }; import { CATEGORIES } from "../src/plugins/categories"; import copy from "../src/i18n/resources/en.json" with { type: "json" }; @@ -9,12 +9,6 @@ async function openPlugins(page: Page) { await expect(page.getByRole("heading", { level: 1, name: /^Plugins/ })).toBeVisible(); } -async function waitForInteractivePage(page: Page) { - // Server-rendered content is visible before hydration attaches its click handlers. - // The language selector stays disabled until that page has hydrated. - await expect(page.getByRole("button", { name: "Language: English" }).first()).toBeEnabled(); -} - function pluginCards(page: Page, section: string): Locator { return page .getByRole("region", { name: section }) @@ -84,18 +78,18 @@ test("browses from the directory into a category, a plugin, and its author", asy }); }); await openPlugins(page); - await waitForInteractivePage(page); + await waitForHydration(page); await page.getByRole("region", { name: "Categories" }).getByRole("link", { name: /Git/ }).click(); await expect(page).toHaveURL(/\/plugins\/category\/git$/); await expect(page.getByRole("heading", { level: 1, name: /^Git/ })).toBeVisible(); - await waitForInteractivePage(page); + await waitForHydration(page); await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0); await page.getByRole("link", { name: /Fresh Worktrees/ }).click(); await expect(page).toHaveURL(/\/plugins\/omercnet\/fresh-worktrees$/); await expect(page.getByRole("heading", { name: "Fresh Worktrees" })).toHaveCount(1); - await waitForInteractivePage(page); + await waitForHydration(page); await expect(page.getByText("paseo plugin add omercnet/fresh-worktrees")).toHaveCount(1); await expect( page.getByRole("heading", { level: 2, name: "Behavior", exact: true }), @@ -192,7 +186,7 @@ test("keeps the directory's ranking window when searching", async ({ page }) => test("submits the visible search term when its input event was missed", async ({ page }) => { await page.goto("/plugins?window=month"); - await expect(page.getByRole("button", { name: "Language: English" }).first()).toBeEnabled(); + await waitForHydration(page); await fillSearchWithMissedInputEvent(page, "graphite"); await page.keyboard.press("Enter"); From 116b0a9190979dc47ee7f221a00dea343262bfdc Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:46:57 +0000 Subject: [PATCH 085/160] Open the Explorer from its toggle state after a resize to phone width (#9771) ensureExplorerSidebar clicked the toggle only when no Explorer was visible. Right after a resize to phone width one still is for a moment: the wide layout until the app switches, then the closed phone overlay's first frame. The helper skipped the click and the phone Explorer, which starts closed, never opened. The helper now decides from the toggle's aria-expanded, and the Explorer spec waits for the app shell to switch layouts after resizing. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../app/e2e/browser/explorer-sidebar.spec.ts | 33 ++++++++++++++----- .../app/e2e/support/helpers/workspace-tabs.ts | 7 ++-- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/packages/app/e2e/browser/explorer-sidebar.spec.ts b/packages/app/e2e/browser/explorer-sidebar.spec.ts index b63775ab2b..d6fa4b7622 100644 --- a/packages/app/e2e/browser/explorer-sidebar.spec.ts +++ b/packages/app/e2e/browser/explorer-sidebar.spec.ts @@ -20,6 +20,21 @@ function explorerSidebar(page: Parameters[0]) { return page.getByTestId("workspace-explorer-sidebar").filter({ visible: true }); } +const LAYOUT_VIEWPORTS = { + compact: { width: 390, height: 844 }, + wide: { width: 1280, height: 900 }, +}; + +// The previous layout stays on screen for a few renders after the resize. Wait for the shell to +// switch so the next step reads the layout it resized to. +async function resizeToLayout( + page: Parameters[0], + layout: keyof typeof LAYOUT_VIEWPORTS, +) { + await page.setViewportSize(LAYOUT_VIEWPORTS[layout]); + await expect(page.getByTestId(`${layout}-shell`)).toBeVisible(); +} + async function expectExplorerActiveTabForeground( page: Parameters[0], ) { @@ -244,7 +259,7 @@ test("tablet prototype keeps Explorer tabs when resizing down to a phone", async await page.screenshot({ path: testInfo.outputPath("tablet-951.png") }); await openExplorerAgentDraft(page); await page.screenshot({ path: testInfo.outputPath("tablet-agent-draft.png") }); - await page.setViewportSize({ width: 390, height: 844 }); + await resizeToLayout(page, "compact"); await revealPhoneExplorer(page); await expect( explorerSidebar(page).getByRole("button", { name: "New tab", exact: true }), @@ -289,10 +304,10 @@ test("retains the Explorer host through appearance changes and folding", async ( .poll(() => explorer.evaluate((element) => getComputedStyle(element).backgroundColor)) .not.toBe(previousColor); expect(await host.evaluate((element) => element.isConnected)).toBe(true); - await page.setViewportSize({ width: 390, height: 844 }); + await resizeToLayout(page, "compact"); await ensureExplorerSidebar(page); expect(await host.evaluate((element) => element.isConnected)).toBe(true); - await page.setViewportSize({ width: 1280, height: 900 }); + await resizeToLayout(page, "wide"); await expect(explorer).toBeVisible(); expect(await host.evaluate((element) => element.isConnected)).toBe(true); } finally { @@ -327,7 +342,7 @@ test("reorders compact Explorer tabs with a pointer without changing selection", const workspace = await seedWorkspace({ repoPrefix: "explorer-compact-drag-" }); try { await gotoWorkspace(page, workspace.workspaceId); - await page.setViewportSize({ width: 390, height: 844 }); + await resizeToLayout(page, "compact"); await openFilesPanel(page); await reorderCompactExplorerTabs(page); await expect( @@ -394,9 +409,9 @@ test("updates populated code and diff appearance without losing the editor insta .getByTestId("file-source-editor") .elementHandle(); await text.fill(`${source}\n// retained Explorer edit`); - await page.setViewportSize({ width: 390, height: 844 }); + await resizeToLayout(page, "compact"); await ensureExplorerSidebar(page); - await page.setViewportSize({ width: 1280, height: 900 }); + await resizeToLayout(page, "wide"); expect(await explorerEditor!.evaluate((node) => node.isConnected)).toBe(true); await expect(text).toContainText("retained Explorer edit"); } finally { @@ -461,9 +476,9 @@ test("retains populated Explorer chat and terminal attachments through appearanc const terminalNode = await terminal.elementHandle(); await page.getByTestId("workspace-explorer-toggle").first().click(); await ensureExplorerSidebar(page); - await page.setViewportSize({ width: 390, height: 844 }); + await resizeToLayout(page, "compact"); await ensureExplorerSidebar(page); - await page.setViewportSize({ width: 1280, height: 900 }); + await resizeToLayout(page, "wide"); await cycleWorkspaceTheme(page); expect(await terminalNode!.evaluate((node) => node.isConnected)).toBe(true); expect(attaches).toHaveLength(1); @@ -483,7 +498,7 @@ test("compact file sheets cover Explorer and return to its retained file list", try { await writeFile(`${workspace.repoPath}/sheet-marker.txt`, "Explorer sheet marker\n"); await gotoWorkspace(page, workspace.workspaceId); - await page.setViewportSize({ width: 390, height: 844 }); + await resizeToLayout(page, "compact"); const explorer = await ensureExplorerSidebar(page); await openFilesPanel(page); const host = await explorer.elementHandle(); diff --git a/packages/app/e2e/support/helpers/workspace-tabs.ts b/packages/app/e2e/support/helpers/workspace-tabs.ts index c124e12df2..95b5499ea5 100644 --- a/packages/app/e2e/support/helpers/workspace-tabs.ts +++ b/packages/app/e2e/support/helpers/workspace-tabs.ts @@ -91,10 +91,13 @@ async function selectWorkspaceTab(tab: Locator): Promise { export async function ensureExplorerSidebar(page: Page): Promise { const toggle = page.getByTestId("workspace-explorer-toggle").first(); await expect(toggle).toBeVisible({ timeout: 30_000 }); - const explorer = explorerSidebar(page); - if ((await explorer.count()) === 0) { + // Decide from the toggle, which reports the open state. The sidebar's own visibility lags it: + // a compact layout draws its closed Explorer for a frame before hiding it. + if ((await toggle.getAttribute("aria-expanded")) !== "true") { await toggle.click(); } + await expect(toggle).toHaveAttribute("aria-expanded", "true"); + const explorer = explorerSidebar(page); await expect(explorer).toBeVisible({ timeout: 30_000 }); return explorer; } From 781cb8d5b0bb7c247175863a67bff03b5f36f5a7 Mon Sep 17 00:00:00 2001 From: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:51:47 +0000 Subject: [PATCH 086/160] fix(server): reject plugin timeline kinds the app cannot register (#7677) timeline.append accepted any string as the row kind, but the app registers renderer kinds with /^[a-z][a-z0-9-]*$/. A plugin that appended a kind such as repro.card got a successful append, then its client setup threw in addTimelineRenderer and the whole plugin client failed to load. The daemon now rejects an append whose kind breaks that rule and names the rule in the error. The wire schema stays a plain string. Document the rule in the plugin docs. Fixes #7326 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- docs/plugins.md | 7 +++-- .../server/agent/agent-timeline-content.ts | 10 ++++++ packages/server/src/server/session.test.ts | 31 +++++++++++++++++++ packages/server/src/server/session.ts | 6 +++- public-docs/plugins/reference.md | 9 ++++-- public-docs/plugins/reference.zh-CN.md | 4 ++- 6 files changed, 59 insertions(+), 8 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index d6c2228d69..61f21cd61c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -873,9 +873,10 @@ await paseo.agents.ref(agentId).timeline.append({ The daemon stamps the runtime `pluginId`; plugin code never supplies it. Reusing the same `id` replaces the previous row from that plugin on live clients and fresh timeline fetches. Rows live in the daemon's in-memory timeline and survive scroll, refetch, and reconnect, but not a daemon -restart. A row without an installed renderer shows an unavailable placeholder. Serialized `data` -must be at most 64 KiB; the daemon rejects a larger append instead of storing a payload that cannot -be rendered intact. The daemon advertises this RPC through +restart. A row without an installed renderer shows an unavailable placeholder. `kind` must match +`/^[a-z][a-z0-9-]*$/`, the rule `addTimelineRenderer` enforces; the daemon rejects any other kind. +Serialized `data` must be at most 64 KiB; the daemon rejects a larger append instead of storing a +payload that cannot be rendered intact. The daemon advertises this RPC through `server_info.features.pluginTimelineItems`. ## Contribute client slash commands diff --git a/packages/server/src/server/agent/agent-timeline-content.ts b/packages/server/src/server/agent/agent-timeline-content.ts index 5117073e14..4f9cc8f690 100644 --- a/packages/server/src/server/agent/agent-timeline-content.ts +++ b/packages/server/src/server/agent/agent-timeline-content.ts @@ -1,5 +1,6 @@ import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { JsonValue } from "@getpaseo/protocol/agent-types"; +import { PluginIdSchema } from "@getpaseo/protocol/plugin-config"; export const PLUGIN_TIMELINE_DATA_MAX_BYTES = 64 * 1024; @@ -14,6 +15,15 @@ const MARKER_COST = 32; const SHORT_STRING = 1024; const MAX_DEPTH = 64; +// The app registers renderer kinds under the plugin ID rule, so stored kinds must use that format. +export function assertPluginTimelineKind(kind: string): void { + if (!PluginIdSchema.safeParse(kind).success) { + throw new Error( + `Plugin timeline item kind must start with a lowercase letter and contain only lowercase letters, digits, and dashes: ${JSON.stringify(kind)}`, + ); + } +} + export function assertPluginTimelineDataSize(data: JsonValue): void { const serializedBytes = Buffer.byteLength(JSON.stringify(data), "utf8"); if (serializedBytes > PLUGIN_TIMELINE_DATA_MAX_BYTES) { diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index b2f8932b90..83ed767460 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -1660,6 +1660,37 @@ describe("plugin timeline append RPC", () => { }), ); }); + + test.each(["repro.card", "Review", "review_card", "1review", ""])( + "rejects the kind %j that no client renderer can register", + async (kind) => { + const messages: SessionOutboundMessage[] = []; + const appendTimelineItem = vi.fn(); + const session = createSessionForTest({ + clientId: "plugin:review", + messages, + agentManager: { appendTimelineItem }, + }); + + await session.handleMessage({ + type: "agent.timeline.append.request", + requestId: "append-kind", + agentId: "agent-1", + item: { type: "plugin", id: "review-1", kind, version: 1, data: {} }, + }); + + expect(appendTimelineItem).not.toHaveBeenCalled(); + expect(messages).toContainEqual({ + type: "rpc_error", + payload: { + requestId: "append-kind", + requestType: "agent.timeline.append.request", + error: `Request failed: Plugin timeline item kind must start with a lowercase letter and contain only lowercase letters, digits, and dashes: ${JSON.stringify(kind)}`, + code: "handler_error", + }, + }); + }, + ); }); describe("agent detach RPC", () => { diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 231e987020..77f30ee0f0 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -144,7 +144,10 @@ import { updateAgentCommand, } from "./agent/lifecycle-command.js"; import { buildStoredAgentPayload, toAgentPayload } from "./agent/agent-projections.js"; -import { assertPluginTimelineDataSize } from "./agent/agent-timeline-content.js"; +import { + assertPluginTimelineDataSize, + assertPluginTimelineKind, +} from "./agent/agent-timeline-content.js"; import { parsePluginClientId } from "./plugins/plugin-session-identity.js"; import { buildAgentForkContextAttachment } from "./agent/activity-curator.js"; import { buildAgentPrompt } from "./agent/prompt-attachments.js"; @@ -8504,6 +8507,7 @@ export class Session { ): Promise { const pluginId = parsePluginClientId(this.clientId); if (!pluginId) throw new Error("Only plugin sessions can append plugin timeline items"); + assertPluginTimelineKind(msg.item.kind); assertPluginTimelineDataSize(msg.item.data); const { seq, epoch } = await this.agentManager.appendTimelineItem(msg.agentId, { ...msg.item, diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 7e9247d452..692313bc5c 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -1279,9 +1279,12 @@ async function publishReview(agentId: string, { paseo }: PluginHandlerContext) { The daemon stamps `pluginId` from the calling plugin session and rejects this RPC from non-plugin sessions. The row appears live, survives timeline refetches, and keeps only the latest value for the -same plugin and `id`. If its renderer is missing, Paseo shows the existing unavailable row. Daemons -reject `data` over the limit rather than truncating it. Daemons that support this operation -advertise `server_info.features.pluginTimelineItems`. +same plugin and `id`. If its renderer is missing, Paseo shows the existing unavailable row. + +`kind` starts with a lowercase letter and contains lowercase letters, numbers, or hyphens, the same +rule `addTimelineRenderer` applies. Daemons reject any other `kind`. Daemons reject `data` over the +limit rather than truncating it. Daemons that support this operation advertise +`server_info.features.pluginTimelineItems`. ## Theme and layout diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index 05d34ac07c..724ce623ae 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -1060,7 +1060,9 @@ async function publishReview(agentId: string, { paseo }: PluginHandlerContext) { | `version` | 正整数 | 是 | 选择渲染器契约的版本。 | | `data` | 兼容 JSON | 是 | 渲染器负载,JSON 序列化后最多 64 KiB。 | -daemon 会根据发起调用的插件会话写入 `pluginId`,并拒绝来自非插件会话的此 RPC。该行会实时出现,在时间线重新获取后依然保留,并且对于同一插件和 `id` 只保留最新的值。如果它的渲染器缺失,Paseo 会显示现有的“不可用”行。daemon 会拒绝超过限制的 `data`,而不是截断它。支持此操作的 daemon 会声明 `server_info.features.pluginTimelineItems`。 +daemon 会根据发起调用的插件会话写入 `pluginId`,并拒绝来自非插件会话的此 RPC。该行会实时出现,在时间线重新获取后依然保留,并且对于同一插件和 `id` 只保留最新的值。如果它的渲染器缺失,Paseo 会显示现有的“不可用”行。 + +`kind` 以小写字母开头,只包含小写字母、数字或连字符,与 `addTimelineRenderer` 使用的规则相同。daemon 会拒绝其他任何 `kind`。daemon 会拒绝超过限制的 `data`,而不是截断它。支持此操作的 daemon 会声明 `server_info.features.pluginTimelineItems`。 ## 主题与布局 {#theme-and-layout} From aa988dd8a817263b00495d93766ae3f80d4206f6 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 20:34:05 +0700 Subject: [PATCH 087/160] fix(claude): honor bypass without execution permission prompts (#9760) Approve Claude execution permission callbacks before creating or emitting permission events, preventing approval cards and transient waiting states in Bypass. Keep AskUserQuestion and ExitPlanMode interactive. Add regression coverage for silent approval and live mode changes. --- .../claude/agent.auto-plan-approval.test.ts | 61 ++++++++++++++++++- .../agent/providers/claude/agent.test.ts | 2 +- .../server/agent/providers/claude/agent.ts | 7 +++ 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts b/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts index 711dea79ec..23b1e79058 100644 --- a/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "vitest"; import type { CanUseTool, PermissionMode, Query } from "@anthropic-ai/claude-agent-sdk"; import { createTestLogger } from "../../../../test-utils/test-logger.js"; -import type { AgentPermissionRequest } from "../../agent-sdk-types.js"; +import type { AgentPermissionRequest, AgentStreamEvent } from "../../agent-sdk-types.js"; import { ClaudeAgentClient } from "./agent.js"; // The injected SDK adapter supplies requests through Claude's permission callback. @@ -90,3 +90,62 @@ test.each([ await plan.session.close(); } }); + +test("bypass allows execution without publishing permission events and follows live mode changes", async () => { + let requestPermission: CanUseTool | undefined; + const query = Object.assign((async function* () {})(), { + async setPermissionMode(_mode: PermissionMode) {}, + close() {}, + }); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + resolveBinary: async () => "/test/claude", + queryFactory: ({ options }) => { + requestPermission = options.canUseTool; + return query as Query; + }, + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + modeId: "bypassPermissions", + }); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + try { + await session.setMode("bypassPermissions"); + if (!requestPermission) throw new Error("SDK permission callback was not installed"); + const controller = new AbortController(); + const input = { command: "echo hello" }; + const result = requestPermission("Bash", input, { + signal: controller.signal, + toolUseID: "execution", + decisionReason: "Explicit ask rule", + }); + // Abort also settles the pre-fix callback, so this repro never hangs. + controller.abort(); + await expect(result).resolves.toMatchObject({ behavior: "allow", updatedInput: input }); + expect(events.filter((event) => event.type.startsWith("permission_"))).toEqual([]); + + for (const [mode, tool, toolInput] of [ + ["bypassPermissions", "AskUserQuestion", { questions: [] }], + ["bypassPermissions", "ExitPlanMode", { plan: "Review this" }], + ["default", "Bash", input], + ["plan", "Bash", input], + ] as const) { + await session.setMode(mode); + const resolution = requestPermission(tool, toolInput, { + signal: new AbortController().signal, + toolUseID: tool, + }); + const requestEvent = events.at(-1); + expect(requestEvent?.type).toBe("permission_requested"); + if (requestEvent?.type !== "permission_requested") + throw new Error("Missing permission request"); + await session.respondToPermission(requestEvent.request.id, { behavior: "deny" }); + await expect(resolution).resolves.toMatchObject({ behavior: "deny" }); + } + } finally { + await session.close(); + } +}); diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index 43632a0cdb..ff76e5186d 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -1004,7 +1004,7 @@ describe("ClaudeAgentSession features", () => { logger, queryFactory, resolveBinary: async () => "/test/claude/bin", - }).createSession({ provider: "claude", cwd: process.cwd(), modeId: "bypassPermissions" }); + }).createSession({ provider: "claude", cwd: process.cwd(), modeId: "default" }); const events: AgentStreamEvent[] = []; const unsubscribe = session.subscribe((event) => events.push(event)); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index f4ef42bc2c..8bafb4e1e1 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -5307,6 +5307,13 @@ class ClaudeAgentSession implements AgentSession { input, options, ): Promise => { + // Decide before publishing anything: bypassed tools never enter the permission UI. + // Claude also routes questions and plan review through this callback. + const needsUserAnswer = toolName === "AskUserQuestion" || toolName === "ExitPlanMode"; + if (this.currentMode === "bypassPermissions" && !needsUserAnswer) { + return { behavior: "allow", updatedInput: input, toolUseID: options.toolUseID }; + } + const requestId = `permission-${randomUUID()}`; const kind = resolvePermissionKind(toolName, input); const requestInput = normalizeClaudeAskUserQuestionRequestInput(toolName, input); From 2e4dab055642694768d25e86cee8d35f7e8e081d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 20:34:07 +0700 Subject: [PATCH 088/160] fix(app): preserve Android Usage drag order and sheet gestures (#9748) On Android, a slow drag on a Usage card handle moved the sheet instead of the card. A drop in the same slot left the sheet ignoring body swipes. A drop in a new slot painted the original order for one or two frames. The sheet gesture now registers a content drag as both a failure requirement and a simultaneous relation, and the Gorhom patch spreads relation arrays into RNGH, so the waiting sheet recognizer no longer cancels the card drag. The old-order frames came from the list clearing its drag state before the reordered data arrived. The sheet portal forwards changed children from an effect, so the list committed old data with fresh transform hosts and a cleared active key, and the new data about 200 ms later. The draggable-flatlist patch now renews moved hosts and clears the active key in the render that receives the reordered data. A same-slot drop resets explicitly because its data does not change. Every native list that uses the patch gets the drop change. Repro tooling for both device checks is in packages/app/e2e/mobile/usage-drag. --- packages/app/e2e/mobile/usage-drag/README.md | 27 ++++ .../app/e2e/mobile/usage-drag/android.mjs | 71 ++++++++++ packages/app/e2e/mobile/usage-drag/frames.py | 59 ++++++++ .../index.test.tsx | 122 +++++++++++++++- .../ui/isolated-bottom-sheet-modal/index.tsx | 18 ++- patches/@gorhom+bottom-sheet+5.2.14.patch | 132 ++++++++++++++++++ ...eact-native-draggable-flatlist+4.0.3.patch | 78 +++++++---- 7 files changed, 473 insertions(+), 34 deletions(-) create mode 100644 packages/app/e2e/mobile/usage-drag/README.md create mode 100644 packages/app/e2e/mobile/usage-drag/android.mjs create mode 100644 packages/app/e2e/mobile/usage-drag/frames.py diff --git a/packages/app/e2e/mobile/usage-drag/README.md b/packages/app/e2e/mobile/usage-drag/README.md new file mode 100644 index 0000000000..57bad4d75a --- /dev/null +++ b/packages/app/e2e/mobile/usage-drag/README.md @@ -0,0 +1,27 @@ +# Android Usage drop regressions + +Use a device you own and fixed reports from an isolated daemon. Keep recordings in `.artifacts/`. Do not upload recordings containing account details. + +## Same-slot drop + +Open Usage with two cards that fit without scrolling. Run: + +```sh +ANDROID_SERIAL=emulator-5580 node packages/app/e2e/mobile/usage-drag/android.mjs +``` + +Set `PASEO_DEVICE_SESSION` to reuse your Agent Device session. The test holds the first handle, moves within its slot, drops it, then swipes the sheet body. It asserts sheet movement while the finger is still down: after release, the sheet can snap back to its starting position. + +## Old-order frame + +Record a drop with Android `screenrecord`. Include the original order, the held arrangement, the release, and at least five seconds after release. Take a reference screenshot before recording. Use fixed labels that stay visible throughout the drop. + +Create a JSON map of label names to screenshot rectangles `[x, y, width, height]`, in physical pixels. Crop each label tightly, without changing text or the pointer. Install `opencv-python-headless` in a local virtual environment under `.artifacts/`, then run: + +```sh +.artifacts/frames-venv/bin/python packages/app/e2e/mobile/usage-drag/frames.py \ + --reference .artifacts/before.png --labels .artifacts/labels.json \ + .artifacts/drop-up.mp4 .artifacts/drop-down.mp4 +``` + +The check requires recognized labels in the first and last frames and a changed final order. After every label first reaches its final slot, it fails on any frame showing all original slots again. It prints the offending frame numbers for each recording. This exercises the Android compositor; a JavaScript render test cannot establish which intermediate commit reached the screen. diff --git a/packages/app/e2e/mobile/usage-drag/android.mjs b/packages/app/e2e/mobile/usage-drag/android.mjs new file mode 100644 index 0000000000..8189889c1f --- /dev/null +++ b/packages/app/e2e/mobile/usage-drag/android.mjs @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { setTimeout } from "node:timers/promises"; + +// Open Usage with a fixture whose cards fit without scrolling before running. +// A same-slot drop must release the list's recognizer so a body swipe moves the sheet. +const serial = process.env.ANDROID_SERIAL; +assert.ok(serial, "Set ANDROID_SERIAL to the device owned by this test"); +const session = process.env.PASEO_DEVICE_SESSION ?? "usage-drag-regression"; +const artifacts = resolve(".artifacts/usage-drag-regression"); +mkdirSync(artifacts, { recursive: true }); +function ad(...args) { + return execFileSync( + "agent-device", + [...args, "--platform", "android", "--serial", serial, "--session", session], + { encoding: "utf8", timeout: 30_000 }, + ); +} +function adb(...args) { + return execFileSync("adb", ["-s", serial, ...args], { timeout: 30_000 }); +} +function snapshot() { + return JSON.parse(ad("snapshot", "--json")).data.nodes; +} +function touch(kind, x, y) { + adb("shell", "input", "motionevent", kind, String(Math.round(x)), String(Math.round(y))); +} +try { + ad("open", process.env.PASEO_MOBILE_APP_ID ?? "sh.paseo.debug"); + const nodes = snapshot(); + writeFileSync(resolve(artifacts, "before.json"), JSON.stringify(nodes)); + const handle = nodes.find((node) => node.identifier === "usage-card-drag-handle"); + const list = nodes.find((node) => node.identifier === "usage-list"); + assert.ok(handle?.rect && list?.rect, "Open Usage with a visible card handle"); + const x = handle.rect.x + handle.rect.width / 2; + const y = handle.rect.y + handle.rect.height / 2; + touch("DOWN", x, y); + await setTimeout(600); + touch("MOVE", x, y + 60); + await setTimeout(200); + touch("MOVE", x, y + 90); + touch("MOVE", x, y + 60); + ad("screenshot", resolve(artifacts, "dragging.png")); + touch("UP", x, y + 60); + await setTimeout(2000); + ad("screenshot", resolve(artifacts, "dropped.png")); + const swipeX = list.rect.x + list.rect.width / 2; + touch("DOWN", swipeX, y + 80); + for (let offset = 90; offset <= 500; offset += 10) { + touch("MOVE", swipeX, y + offset); + } + const during = snapshot(); + writeFileSync(resolve(artifacts, "during.json"), JSON.stringify(during)); + ad("screenshot", resolve(artifacts, "during.png")); + touch("UP", swipeX, y + 500); + await setTimeout(1500); + const after = snapshot(); + writeFileSync(resolve(artifacts, "after.json"), JSON.stringify(after)); + ad("screenshot", resolve(artifacts, "after.png")); + const beforeSheet = nodes.find((node) => node.label === "Bottom sheet handle"); + const afterSheet = during.find((node) => node.label === "Bottom sheet handle"); + assert.ok(beforeSheet?.rect, "Usage must start as a sheet"); + assert.ok( + !afterSheet || afterSheet.rect.y > beforeSheet.rect.y + 50, + "A body swipe after a same-slot drop must move the sheet", + ); +} finally { + ad("close"); +} diff --git a/packages/app/e2e/mobile/usage-drag/frames.py b/packages/app/e2e/mobile/usage-drag/frames.py new file mode 100644 index 0000000000..1b72e8d029 --- /dev/null +++ b/packages/app/e2e/mobile/usage-drag/frames.py @@ -0,0 +1,59 @@ +"""Check native drop recordings against visible row labels (requires opencv-python-headless). + +Supply a before screenshot and a JSON map of label names to [x, y, width, height]. +A recording must start in the original order and end in a different order. Once +all labels reach their final slots, any frame returning to the original slots fails. +Keep the pointer clear of the labels and use fixed fixture data. +""" +import argparse +import json +from pathlib import Path + +import cv2 + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--reference", required=True) +parser.add_argument("--labels", required=True) +parser.add_argument("--top", type=int, default=0) +parser.add_argument("--bottom", type=int) +parser.add_argument("videos", nargs="+") +args = parser.parse_args() +reference = cv2.imread(args.reference, cv2.IMREAD_GRAYSCALE) +assert reference is not None, "Cannot read reference image" +labels = json.loads(Path(args.labels).read_text()) +results = [] +for video in args.videos: + capture = cv2.VideoCapture(video) + frames = [] + while True: + ok, image = capture.read() + if not ok: + break + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + positions = {} + for label, (x, y, width, height) in labels.items(): + template = reference[y:y + height, x:x + width] + matches = cv2.matchTemplate(gray[args.top:args.bottom, x:x + width], template, cv2.TM_CCOEFF_NORMED) + _, confidence, _, point = cv2.minMaxLoc(matches) + positions[label] = (point[1] + args.top, confidence) + frames.append(positions) + capture.release() + assert frames, f"No frames in {video}" + initial, final = frames[0], frames[-1] + assert all(confidence >= 0.95 for _, confidence in initial.values()), f"Unrecognized initial labels: {video}" + assert all(confidence >= 0.95 for _, confidence in final.values()), f"Unrecognized final labels: {video}" + assert sorted(initial, key=lambda key: initial[key][0]) != sorted(final, key=lambda key: final[key][0]), f"Drop did not reorder: {video}" + + def matches_slots(frame, target): + return all(confidence >= 0.95 and abs(y - target[label][0]) <= 2 + for label, (y, confidence) in frame.items()) + + reached_final = False + wrong = [] + for number, frame in enumerate(frames, start=1): + reached_final = reached_final or matches_slots(frame, final) + if reached_final and matches_slots(frame, initial): + wrong.append(number) + results.append({"recording": video, "oldOrderFrames": wrong, "count": len(wrong)}) +print(json.dumps(results, indent=2)) +raise SystemExit(1 if any(result["count"] for result in results) else 0) diff --git a/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx b/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx index 17aa4a5b75..1de2dd8f84 100644 --- a/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx +++ b/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.test.tsx @@ -43,6 +43,7 @@ vi.mock("@gorhom/portal", () => ({ /** Every `waitFor` Gorhom received, in render order. Gorhom rebuilds its content pan per value. */ const sheetWaitFor = vi.hoisted(() => [] as unknown[]); +const sheetSimultaneousHandlers = vi.hoisted(() => [] as unknown[]); vi.mock("@gorhom/bottom-sheet", async () => { const { Portal } = await import("@gorhom/portal"); @@ -55,10 +56,17 @@ vi.mock("@gorhom/bottom-sheet", async () => { children, stackBehavior, waitFor, - }: { children?: React.ReactNode; stackBehavior?: string; waitFor?: unknown }, + simultaneousHandlers, + }: { + children?: React.ReactNode; + stackBehavior?: string; + waitFor?: unknown; + simultaneousHandlers?: unknown; + }, _ref, ) => { sheetWaitFor.push(waitFor); + sheetSimultaneousHandlers.push(simultaneousHandlers); return React.createElement( Portal, null, @@ -259,6 +267,7 @@ describe("IsolatedBottomSheetModal content drag", () => { document.body.appendChild(container); root = createRoot(container); sheetWaitFor.length = 0; + sheetSimultaneousHandlers.length = 0; }); afterEach(() => { @@ -275,11 +284,19 @@ describe("IsolatedBottomSheetModal content drag", () => { return null; } - function renderSheet(content: React.ReactNode) { + function renderSheet( + content: React.ReactNode, + handlers: Pick< + React.ComponentProps, + "waitFor" | "simultaneousHandlers" + > = {}, + ) { act(() => { root.render( <> - {content} + + {content} + , ); @@ -291,9 +308,106 @@ describe("IsolatedBottomSheetModal content drag", () => { expect(sheetWaitFor.at(-1)).toBeUndefined(); renderSheet(); - expect(sheetWaitFor.at(-1)).toBe(dragGesture); + expect(sheetSimultaneousHandlers.at(-1)).toEqual([dragGesture]); + expect(sheetWaitFor.at(-1)).toEqual([dragGesture]); renderSheet(null); expect(sheetWaitFor.at(-1)).toBeUndefined(); + expect(sheetSimultaneousHandlers.at(-1)).toBeUndefined(); }); + + it.each([false, true])( + "preserves supplied relations when a content drag mounts and unmounts (array=%s)", + (array) => { + const waiting = React.createRef(); + const simultaneous = React.createRef(); + const handlers = { + waitFor: array ? [waiting] : waiting, + simultaneousHandlers: array ? [simultaneous] : simultaneous, + }; + renderSheet(, handlers); + expect(sheetWaitFor.at(-1)).toEqual([waiting, dragGesture]); + expect(sheetSimultaneousHandlers.at(-1)).toEqual([simultaneous, dragGesture]); + renderSheet(null, handlers); + expect(sheetWaitFor.at(-1)).toBe(handlers.waitFor); + expect(sheetSimultaneousHandlers.at(-1)).toBe(handlers.simultaneousHandlers); + }, + ); +}); + +// Load the real vendored implementations at runtime without typechecking Gorhom's entire source +// tree (its hooks barrel reaches upstream files that don't compile under the app's TS settings). +const gorhomSource = "@gorhom/bottom-sheet/src"; +const { default: BottomSheetDraggableView } = await import( + `${gorhomSource}/components/bottomSheetDraggableView/BottomSheetDraggableView` +); +const { BottomSheetInternalContext } = await import(`${gorhomSource}/contexts/internal`); +const { BottomSheetDraggableContext, BottomSheetGestureHandlersContext } = await import( + `${gorhomSource}/contexts/gesture` +); +const rnghSource = "react-native-gesture-handler/src"; +const { extractGestureRelations } = await import( + `${rnghSource}/handlers/gestures/GestureDetector/utils` +); +import { Gesture, type GestureType } from "react-native-gesture-handler"; + +const noGestureWork = () => {}; +const gestureHandlerContext = { + contentPanGestureHandler: { + handleOnStart: noGestureWork, + handleOnChange: noGestureWork, + handleOnEnd: noGestureWork, + handleOnFinalize: noGestureWork, + }, + handlePanGestureHandler: { + handleOnStart: noGestureWork, + handleOnChange: noGestureWork, + handleOnEnd: noGestureWork, + handleOnFinalize: noGestureWork, + }, +}; +function dragInternalContext(relations: SheetContentDragGesture | SheetContentDragGesture[]) { + return { + enableContentPanningGesture: true, + waitFor: relations, + simultaneousHandlers: relations, + }; +} + +describe("bottom sheet native drag relations", () => { + it.each([false, true])( + "resolves both relations through the real content pan (array=%s)", + (array) => { + const container = document.createElement("div"); + const root = createRoot(container); + const child = Gesture.Pan(); + child.handlerTag = 42; + const ref = { current: child }; + const relations = array ? [ref] : ref; + let resolved: ReturnType | undefined; + const internal = dragInternalContext(relations); + function Probe() { + const pan = useContext(BottomSheetDraggableContext) as GestureType | null; + if (pan) resolved = extractGestureRelations(pan); + return null; + } + try { + act(() => + root.render( + + + + + + + , + ), + ); + expect(resolved?.waitFor).toEqual([42]); + expect(resolved?.simultaneousHandlers).toEqual([42]); + } finally { + act(() => root.unmount()); + } + }, + ); }); diff --git a/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.tsx b/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.tsx index fcde3a6e37..1ae6b1111d 100644 --- a/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.tsx +++ b/packages/app/src/components/ui/isolated-bottom-sheet-modal/index.tsx @@ -105,6 +105,8 @@ export const IsolatedBottomSheetModal = forwardRef< contextBridge, backdropOpacity, enableDismissOnClose = true, + waitFor, + simultaneousHandlers, ...bottomSheetProps } = props; // State, not a ref the child fills in: Gorhom builds its pan once per `waitFor`, and RNGH reads @@ -115,6 +117,19 @@ export const IsolatedBottomSheetModal = forwardRef< setContentDragGesture(gesture); return () => setContentDragGesture((current) => (current === gesture ? undefined : current)); }, []); + // RNGH Android's shouldBeCancelledByActiveHandler treats a waiting ancestor's raw ACTIVE + // state as ownership and cancels its child at activation. Simultaneity lets the child activate; + // waitFor still keeps the sheet stationary until the child fails. + const contentDragHandlers = useMemo(() => { + if (!contentDragGesture) return { waitFor, simultaneousHandlers }; + return { + waitFor: [...(waitFor ? [waitFor].flat() : []), contentDragGesture], + simultaneousHandlers: [ + ...(simultaneousHandlers ? [simultaneousHandlers].flat() : []), + contentDragGesture, + ], + }; + }, [contentDragGesture, waitFor, simultaneousHandlers]); const renderBackdrop = useCallback( (backdropProps: BottomSheetBackdropProps) => ( {contextBridge ? contextBridge(children) : children} diff --git a/patches/@gorhom+bottom-sheet+5.2.14.patch b/patches/@gorhom+bottom-sheet+5.2.14.patch index 13d7df0565..7943d4cb19 100644 --- a/patches/@gorhom+bottom-sheet+5.2.14.patch +++ b/patches/@gorhom+bottom-sheet+5.2.14.patch @@ -1,3 +1,37 @@ +diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js +index f3d8f55..72d4322 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetDraggableView/BottomSheetDraggableView.js +@@ -55,10 +55,10 @@ const BottomSheetDraggableViewComponent = ({ + const draggableGesture = (0, _react.useMemo)(() => { + let gesture = _reactNativeGestureHandler.Gesture.Pan().enabled(enableContentPanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(contentPanGestureHandler.handleOnStart).onChange(contentPanGestureHandler.handleOnChange).onEnd(contentPanGestureHandler.handleOnEnd).onFinalize(contentPanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); +diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js +index ee9e898..1500886 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetHandle/BottomSheetHandleContainer.js +@@ -59,10 +59,10 @@ function BottomSheetHandleContainerComponent({ + const panGesture = (0, _react.useMemo)(() => { + let gesture = _reactNativeGestureHandler.Gesture.Pan().enabled(enableHandlePanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(handlePanGestureHandler.handleOnStart).onChange(handlePanGestureHandler.handleOnChange).onEnd(handlePanGestureHandler.handleOnEnd).onFinalize(handlePanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); diff --git a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetModal/BottomSheetModal.js b/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetModal/BottomSheetModal.js index ee51e76..5fe8f75 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/commonjs/components/bottomSheetModal/BottomSheetModal.js @@ -70,6 +104,40 @@ index e44ad86..96555ef 100644 var _useScrollEventsHandlersDefault = require("./hooks/useScrollEventsHandlersDefault"); var _useGestureEventsHandlersDefault = require("./hooks/useGestureEventsHandlersDefault"); var _useBottomSheetGestureHandlers = require("./hooks/useBottomSheetGestureHandlers"); +diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js +index 9efadd2..942b78a 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetDraggableView/BottomSheetDraggableView.js +@@ -49,10 +49,10 @@ const BottomSheetDraggableViewComponent = ({ + const draggableGesture = useMemo(() => { + let gesture = Gesture.Pan().enabled(enableContentPanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(contentPanGestureHandler.handleOnStart).onChange(contentPanGestureHandler.handleOnChange).onEnd(contentPanGestureHandler.handleOnEnd).onFinalize(contentPanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); +diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js +index 3d1eafe..bf8e366 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js ++++ b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetHandle/BottomSheetHandleContainer.js +@@ -53,10 +53,10 @@ function BottomSheetHandleContainerComponent({ + const panGesture = useMemo(() => { + let gesture = Gesture.Pan().enabled(enableHandlePanningGesture).shouldCancelWhenOutside(false).runOnJS(false).onStart(handlePanGestureHandler.handleOnStart).onChange(handlePanGestureHandler.handleOnChange).onEnd(handlePanGestureHandler.handleOnEnd).onFinalize(handlePanGestureHandler.handleOnFinalize); + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + if (simultaneousHandlers) { +- gesture = gesture.simultaneousWithExternalGesture(simultaneousHandlers); ++ gesture = gesture.simultaneousWithExternalGesture(...simultaneousHandlers); + } + if (activeOffsetX) { + gesture = gesture.activeOffsetX(activeOffsetX); diff --git a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetModal/BottomSheetModal.js b/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetModal/BottomSheetModal.js index 94fabdb..d870aa7 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/module/components/bottomSheetModal/BottomSheetModal.js @@ -128,6 +196,19 @@ index 8259637..eb057fe 100644 export { useScrollEventsHandlersDefault } from './hooks/useScrollEventsHandlersDefault'; export { useGestureEventsHandlersDefault } from './hooks/useGestureEventsHandlersDefault'; export { useBottomSheetGestureHandlers } from './hooks/useBottomSheetGestureHandlers'; +diff --git a/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts b/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts +index 6b23056..8d92aae 100644 +--- a/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts ++++ b/node_modules/@gorhom/bottom-sheet/lib/typescript/components/bottomSheet/types.d.ts +@@ -353,6 +353,6 @@ export type BottomSheetGestureProps = { + + simultaneousHandlers: Parameters< + PanGesture['simultaneousWithExternalGesture'] +- >[0]; +- waitFor: Parameters[0]; ++ >[0] | Parameters; ++ waitFor: Parameters[0] | Parameters; + }; diff --git a/node_modules/@gorhom/bottom-sheet/lib/typescript/index.d.ts b/node_modules/@gorhom/bottom-sheet/lib/typescript/index.d.ts index ffc6caa..550f1b3 100644 --- a/node_modules/@gorhom/bottom-sheet/lib/typescript/index.d.ts @@ -141,6 +222,57 @@ index ffc6caa..550f1b3 100644 export { useScrollEventsHandlersDefault } from './hooks/useScrollEventsHandlersDefault'; export { useGestureEventsHandlersDefault } from './hooks/useGestureEventsHandlersDefault'; export { useBottomSheetGestureHandlers } from './hooks/useBottomSheetGestureHandlers'; +diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts +index 6b23056..8d92aae 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts ++++ b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheet/types.d.ts +@@ -353,6 +353,6 @@ export type BottomSheetGestureProps = { + + simultaneousHandlers: Parameters< + PanGesture['simultaneousWithExternalGesture'] +- >[0]; +- waitFor: Parameters[0]; ++ >[0] | Parameters; ++ waitFor: Parameters[0] | Parameters; + }; +diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx +index 923e430..eeef8cf 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx ++++ b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetDraggableView/BottomSheetDraggableView.tsx +@@ -65,12 +65,12 @@ const BottomSheetDraggableViewComponent = ({ + .onFinalize(contentPanGestureHandler.handleOnFinalize); + + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + + if (simultaneousHandlers) { + gesture = gesture.simultaneousWithExternalGesture( +- simultaneousHandlers as never ++ ...(simultaneousHandlers as Parameters) + ); + } + +diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx +index 0223843..4ca56e5 100644 +--- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx ++++ b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetHandle/BottomSheetHandleContainer.tsx +@@ -67,12 +67,12 @@ function BottomSheetHandleContainerComponent({ + .onFinalize(handlePanGestureHandler.handleOnFinalize); + + if (waitFor) { +- gesture = gesture.requireExternalGestureToFail(waitFor); ++ gesture = gesture.requireExternalGestureToFail(...(Array.isArray(waitFor) ? waitFor : [waitFor])); + } + + if (simultaneousHandlers) { + gesture = gesture.simultaneousWithExternalGesture( +- simultaneousHandlers as never ++ ...(simultaneousHandlers as Parameters) + ); + } + diff --git a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetModal/BottomSheetModal.tsx b/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetModal/BottomSheetModal.tsx index 2954b3f..936300b 100644 --- a/node_modules/@gorhom/bottom-sheet/src/components/bottomSheetModal/BottomSheetModal.tsx diff --git a/patches/react-native-draggable-flatlist+4.0.3.patch b/patches/react-native-draggable-flatlist+4.0.3.patch index 75f1f060a3..9cd964268c 100644 --- a/patches/react-native-draggable-flatlist+4.0.3.patch +++ b/patches/react-native-draggable-flatlist+4.0.3.patch @@ -181,7 +181,7 @@ index e4e861a..f485139 100644 declare global { diff --git a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx -index 7c88afc..a97cb80 100644 +index 7c88afc..05618ec 100644 --- a/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx +++ b/node_modules/react-native-draggable-flatlist/src/components/DraggableFlatList.tsx @@ -16,9 +16,11 @@ import { @@ -227,7 +227,37 @@ index 7c88afc..a97cb80 100644 const [layoutAnimationDisabled, setLayoutAnimationDisabled] = useState( !propsRef.current.enableLayoutAnimationExperimental ); -@@ -144,19 +163,88 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -113,10 +132,26 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + + const dataRef = useRef(props.data); + const dataHasChanged = +- dataRef.current.map(keyExtractor).join("") !== +- props.data.map(keyExtractor).join(""); +- dataRef.current = props.data; ++ dataRef.current.map(keyExtractor).join("") !== props.data.map(keyExtractor).join(""); ++ // Sheet portals can deliver reordered data after the drop callback commits. ++ // Keep the held transforms until that data arrives, then renew moved hosts ++ // in the same render as their new slots. + if (dataHasChanged) { ++ const wasDragging = activeKey !== null; ++ const previousIndices = new Map( ++ dataRef.current.map((item, index) => [keyExtractor(item, index), index]), ++ ); ++ setTransformHostKeys((previous) => { ++ const next = new Map(); ++ props.data.forEach((item, index) => { ++ const key = keyExtractor(item, index); ++ const generation = previous.get(key) ?? 0; ++ next.set(key, generation + (wasDragging && previousIndices.get(key) !== index ? 1 : 0)); ++ }); ++ return next; ++ }); ++ dataRef.current = props.data; ++ setActiveKey(null); + // When data changes make sure `activeKey` is nulled out in the same render pass + activeKey = null; + InteractionManager.runAfterInteractions(() => { +@@ -144,19 +179,88 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { }); }, [props.data, keyExtractor, keyToIndexRef]); @@ -323,7 +353,7 @@ index 7c88afc..a97cb80 100644 setActiveKey(activeKey); onDragBegin?.(index); } -@@ -218,14 +306,46 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -218,8 +322,25 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { props.onRelease?.(index); }); @@ -350,28 +380,18 @@ index 7c88afc..a97cb80 100644 const { onDragEnd, data } = props; const newData = [...data]; - if (from !== to) { - newData.splice(from, 1); - newData.splice(to, 0, data[from]); -+ const movedKeys = data -+ .slice(Math.min(from, to), Math.max(from, to) + 1) -+ .map((item, offset) => keyExtractor(item, Math.min(from, to) + offset)); -+ setTransformHostKeys((previous) => { -+ const next = new Map(); -+ data.forEach((item, index) => { -+ const itemKey = keyExtractor(item, index); -+ const hostKey = previous.get(itemKey); -+ if (hostKey !== undefined) next.set(itemKey, hostKey); -+ }); -+ for (const movedKey of movedKeys) { -+ next.set(movedKey, (previous.get(movedKey) ?? 0) + 1); -+ } -+ return next; -+ }); - } +@@ -230,34 +351,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { onDragEnd?.({ from, to, data: newData }); -@@ -238,26 +358,6 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { + +- setActiveKey(null); +- } ++ // A drop in place doesn't change data, so no data-change reset will clear the armed index. ++ if (from === to) reset(); ++ }, + ); + + const onPlaceholderIndexChange = useStableCallback((index: number) => { props.onPlaceholderIndexChange?.(index); }); @@ -398,7 +418,7 @@ index 7c88afc..a97cb80 100644 useAnimatedReaction( () => { return spacerIndexAnim.value; -@@ -271,11 +371,26 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -271,11 +373,26 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { ); const gestureDisabled = useSharedValue(false); @@ -426,7 +446,7 @@ index 7c88afc..a97cb80 100644 panGestureState.value = evt.state; }) .onUpdate((evt) => { -@@ -286,8 +401,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -286,8 +403,15 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { : evt.translationY; touchTranslate.value = translation; }) @@ -443,7 +463,7 @@ index 7c88afc..a97cb80 100644 // Set touch val to current translate val isTouchActiveNative.value = false; const translation = horizontalAnim.value -@@ -299,6 +421,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -299,6 +423,7 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { // Only call onDragEnd if actually dragging a cell if (activeIndexAnim.value === -1 || disabled.value) return; @@ -451,7 +471,7 @@ index 7c88afc..a97cb80 100644 disabled.value = true; runOnJS(onRelease)(activeIndexAnim.value); const springTo = placeholderOffset.value - activeCellOffset.value; -@@ -309,22 +432,85 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -309,22 +434,85 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { runOnJS(onDragEnd)({ from: activeIndexAnim.value, to: spacerIndexAnim.value, @@ -540,7 +560,7 @@ index 7c88afc..a97cb80 100644 const activeOffset = [-activationDistanceProp, activationDistanceProp]; if (props.horizontal) { panGesture.activeOffsetX(activeOffset); -@@ -332,6 +518,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -332,6 +520,21 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { panGesture.activeOffsetY(activeOffset); } } @@ -562,7 +582,7 @@ index 7c88afc..a97cb80 100644 const onScroll = useStableCallback((scrollOffset: number) => { props.onScrollOffsetChange?.(scrollOffset); -@@ -372,9 +573,11 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { +@@ -372,9 +575,11 @@ function DraggableFlatListInner(props: DraggableFlatListProps) { keyExtractor={keyExtractor} horizontal={!!props.horizontal} layoutAnimationDisabled={layoutAnimationDisabled} From ef146bc62d79eeac1c8e765e23032caf4d0a16d4 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 20:34:13 +0700 Subject: [PATCH 089/160] Browse, install and manage plugins from a built-in gallery (#9752) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(app): browse, install and manage plugins from a built-in gallery Settings → Host → Plugins becomes a gallery with two tabs. Installed lists the host's plugins with on/off switches and pending updates. Browse lists the plugin directory with featured cards, categories, sorting and search. Each plugin has its own page with its screenshots, overview, details, install or on/off controls, and its own settings screens inline. Every install asks first, in a sheet naming the source and version, because installing runs the plugin's code on the host. Uninstalling also asks first; its confirm says what is deleted. The daemon fetches the directory from its configured registry (plugin.registry.list/get, gated by server_info.features.pluginRegistry). The app never fetches from the registry itself, so a host with a private registry shows that registry. README overviews render with the registry's overview contract (the same one the website uses): only https links and images work, and nothing is read as a workspace file. Before this, a word like "Node.js" became a broken relative link. * fix(app): refresh plugin failures and leave Settings cleanly from a plugin page The Installed row read the app-side evaluation error without subscribing to the registry, so a plugin fixed by Reload kept its "failed" badge. Rows and the plugin page now subscribe through usePluginEvaluationError. Leaving Settings with no remembered workspace replaced only the top stack entry; with a plugin page pushed on top, the Plugins list stayed mounted underneath and reopening Settings stacked a second copy. Dismiss the Settings entries first. * fix(app): keep Browse working as the registry grows, and test it end to end Registry listings now reach apps through an open wire schema (plugin.registry.list/get carry PluginListing*), and the daemon drops a listing it cannot read instead of failing the whole index. A registry that adds an artifact kind or bumps schemaVersion no longer breaks Browse on older apps. The gallery picks its opening tab once, so installing the first plugin keeps the user on Browse. README links open only https: the parser still autolinks bare http, www and email text, so a press checks the URL again. Adds a Browse e2e test against a local registry and Git repository: install from a row through the confirm sheet, stay on Browse, open the listing page, uninstall from it. * test(server): give the oversized-sibling diff refresh the same time budget as its siblings expect.poll defaults to one second, which a Windows git diff refresh can exceed. * test(server): wait as long as the other observer tests for native watcher events expect.poll defaults to one second; macOS FSEvents can deliver later than that on CI. * fix(app): keep a listed plugin's page usable after uninstalling it, and fetch the directory less An installed plugin's page finds its listing through the plugin, so uninstalling a directory plugin from the Installed tab left "not installed or listed" with no way back. The page now becomes the listing's page, offering Install again. Updates are re-checked when the host's plugins change and after a failed update, whose proposal named a revision that no longer exists. The directory, listing and update queries refetch on mount only once stale, so opening a plugin's page no longer refetches the whole directory and every update check. * test(app): install the plugin before opening Plugins in the busy-queue reload test Plugins opens on Browse when the host has no plugins and stays there after the first install, so a plugin installed through the daemon after the page opened never showed on Installed. * test(website): wait for hydration before scrolling to the hero in a short window The router resets the scroll position when the page hydrates. Scrolling to the mockup before that left it below the window, so its start line never came on screen and the opening scene never played. It failed 7 of 10 runs on webkit. * fix(server): show the registry setup error on Browse instead of asking to retry The registry's request headers were built inside the try around fetch, so a setup error such as credentials over plain HTTP came back as "Could not reach plugin registry. Retry later." Install already built them first. * fix(app): show plugin errors without the request details meant for logs A daemon RPC error's message ends with requestType=… code=…; the daemon's own text is in userMessage. Gallery alerts and toasts now show that text. * fix(app): show why an update failed on the plugin's page The update operation's failure was recorded under the plugin ID, but the page only read it to show the spinner, so a failed update looked as if nothing happened. The page now shows the error in its own alert, without the plugin's Failed badge, because the installed version keeps running. While an update is still available the button reads Retry. * fix(app): show a plugin page's update error only while the update is offered The failed update stayed in the operations store after the plugin was updated elsewhere or uninstalled, so the page kept saying the update failed. The page now shows it with the Update button it belongs to, as the Installed tab's Updates row does, and uninstalling forgets it. --- docs/markdown-renderer.md | 2 + .../app/e2e/browser/plugin-directory.spec.ts | 24 + .../app/e2e/browser/plugin-management.spec.ts | 340 ++++++---- .../app/e2e/browser/plugin-settings.spec.ts | 31 +- .../mobile/appearance-keyboard/android.mjs | 12 +- .../e2e/support/helpers/plugin-directory.ts | 205 ++++++ .../app/e2e/support/helpers/plugin-gallery.ts | 269 ++++++++ .../support/helpers/plugin-requirements.ts | 24 +- .../e2e/support/helpers/plugin-settings.ts | 107 ++-- .../support/helpers/versioned-host-daemon.ts | 40 +- packages/app/src/app/_layout.tsx | 2 + .../plugin-directory/[owner]/[slug].tsx | 23 + .../[serverId]/plugins/[pluginId]/index.tsx | 23 + .../app/src/components/markdown/images.ts | 11 +- .../src/components/markdown/renderer.test.ts | 27 + .../app/src/components/markdown/renderer.tsx | 27 +- .../app/src/components/markdown/source.ts | 50 +- .../app/src/components/page-layout/index.tsx | 12 +- packages/app/src/i18n/resources/en.ts | 14 +- .../app/src/i18n/resources/plugin-gallery.ts | 559 +++++++++++++++++ .../app/src/i18n/resources/plugin-settings.ts | 82 ++- .../app/src/navigation/settings-navigation.ts | 9 +- packages/app/src/plugins/gallery/actions.ts | 78 +++ .../app/src/plugins/gallery/browse-tab.tsx | 459 ++++++++++++++ .../src/plugins/gallery/error-text.test.ts | 19 + .../app/src/plugins/gallery/error-text.ts | 9 + .../app/src/plugins/gallery/gallery-page.tsx | 157 +++++ packages/app/src/plugins/gallery/index.ts | 4 + .../src/plugins/gallery/install-control.tsx | 72 +++ .../app/src/plugins/gallery/install-sheet.tsx | 191 ++++++ .../app/src/plugins/gallery/installed-tab.tsx | 276 ++++++++ .../app/src/plugins/gallery/listing.test.ts | 121 ++++ packages/app/src/plugins/gallery/listing.ts | 115 ++++ packages/app/src/plugins/gallery/menus.tsx | 325 ++++++++++ .../app/src/plugins/gallery/operations.ts | 159 +++++ .../app/src/plugins/gallery/plugin-page.tsx | 581 +++++++++++++++++ .../app/src/plugins/gallery/plugin-row.tsx | 202 ++++++ .../src/plugins/gallery/plugins-off-alert.tsx | 48 ++ packages/app/src/plugins/gallery/queries.ts | 112 ++++ packages/app/src/plugins/gallery/routes.ts | 16 + .../app/src/plugins/gallery/skeletons.tsx | 105 ++++ packages/app/src/plugins/plugin-list.ts | 6 +- packages/app/src/plugins/registry.ts | 6 + packages/app/src/plugins/settings/index.tsx | 55 +- packages/app/src/screens/settings-screen.tsx | 67 +- .../plugin-install-form-model.test.ts | 25 - .../settings/plugin-install-form-model.ts | 53 -- .../settings/plugins-page-state.test.ts | 17 - .../screens/settings/plugins-page-state.ts | 15 - .../screens/settings/plugins-page.test.tsx | 257 -------- .../app/src/screens/settings/plugins-page.tsx | 590 ------------------ packages/client/src/daemon-client.ts | 33 + packages/protocol/src/messages.ts | 35 +- packages/protocol/src/plugin-registry.test.ts | 13 + packages/protocol/src/plugin-registry.ts | 33 +- .../authorization/operation-permissions.ts | 4 + .../src/server/checkout-diff-manager.test.ts | 4 +- .../file-observer/native-recursive.test.ts | 8 +- packages/server/src/server/plugins/index.ts | 9 + .../plugins/managed-source.posix.test.ts | 105 ++++ .../src/server/plugins/managed-source.ts | 15 +- .../server/plugins/managed-source/registry.ts | 77 ++- packages/server/src/server/session.ts | 30 +- .../src/server/test-utils/paseo-daemon.ts | 2 + .../src/server/test-utils/versioned-daemon.ts | 2 + .../server/src/server/websocket-server.ts | 2 + 66 files changed, 5093 insertions(+), 1312 deletions(-) create mode 100644 packages/app/e2e/browser/plugin-directory.spec.ts create mode 100644 packages/app/e2e/support/helpers/plugin-directory.ts create mode 100644 packages/app/e2e/support/helpers/plugin-gallery.ts create mode 100644 packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx create mode 100644 packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx create mode 100644 packages/app/src/i18n/resources/plugin-gallery.ts create mode 100644 packages/app/src/plugins/gallery/actions.ts create mode 100644 packages/app/src/plugins/gallery/browse-tab.tsx create mode 100644 packages/app/src/plugins/gallery/error-text.test.ts create mode 100644 packages/app/src/plugins/gallery/error-text.ts create mode 100644 packages/app/src/plugins/gallery/gallery-page.tsx create mode 100644 packages/app/src/plugins/gallery/index.ts create mode 100644 packages/app/src/plugins/gallery/install-control.tsx create mode 100644 packages/app/src/plugins/gallery/install-sheet.tsx create mode 100644 packages/app/src/plugins/gallery/installed-tab.tsx create mode 100644 packages/app/src/plugins/gallery/listing.test.ts create mode 100644 packages/app/src/plugins/gallery/listing.ts create mode 100644 packages/app/src/plugins/gallery/menus.tsx create mode 100644 packages/app/src/plugins/gallery/operations.ts create mode 100644 packages/app/src/plugins/gallery/plugin-page.tsx create mode 100644 packages/app/src/plugins/gallery/plugin-row.tsx create mode 100644 packages/app/src/plugins/gallery/plugins-off-alert.tsx create mode 100644 packages/app/src/plugins/gallery/queries.ts create mode 100644 packages/app/src/plugins/gallery/routes.ts create mode 100644 packages/app/src/plugins/gallery/skeletons.tsx delete mode 100644 packages/app/src/screens/settings/plugin-install-form-model.test.ts delete mode 100644 packages/app/src/screens/settings/plugin-install-form-model.ts delete mode 100644 packages/app/src/screens/settings/plugins-page-state.test.ts delete mode 100644 packages/app/src/screens/settings/plugins-page-state.ts delete mode 100644 packages/app/src/screens/settings/plugins-page.test.tsx delete mode 100644 packages/app/src/screens/settings/plugins-page.tsx diff --git a/docs/markdown-renderer.md b/docs/markdown-renderer.md index 11b9f09405..255d68e8ec 100644 --- a/docs/markdown-renderer.md +++ b/docs/markdown-renderer.md @@ -12,6 +12,8 @@ Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, Workspace file links use the shared file-link resolver. The workspace supplies its client, root and open-file action once; chat can supply the agent's more specific context. URLs use the same link press path. Recognized inline-code paths stay tappable. The library callback carries the tapped occurrence’s syntax context. Preserve it when opening files: explicit Markdown links decode URL escapes, while recognized inline-code paths preserve literal percent characters and use suffix lookup. Identical URL strings in different occurrences must stay distinct. Explicit absolute workspace links receive a relative hover title; existing authored titles remain intact. Inside a workspace, forge references such as `#12` and `owner/repo#12` are recognized in prose (not code) and open the workspace forge; the reference pattern comes before path recognition so `group/project#12` is not read as a path. See [forge providers](forge-providers.md#gotchas). +Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge. + Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[![Retrigger](badge.svg)](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (local patch in `patches/react-native-enriched-markdown+*.patch`). ## Engine constraints diff --git a/packages/app/e2e/browser/plugin-directory.spec.ts b/packages/app/e2e/browser/plugin-directory.spec.ts new file mode 100644 index 0000000000..e9d3367954 --- /dev/null +++ b/packages/app/e2e/browser/plugin-directory.spec.ts @@ -0,0 +1,24 @@ +import { + test, + expectStillBrowsing, + installFromPage, + installListingFromRow, + openDirectory, + openFromInstalledTab, + openListingPage, + uninstallFromPage, +} from "../support/helpers/plugin-directory"; + +test("installs a listed plugin from Browse and uninstalls it from either of its pages", async ({ + page, + directoryHost, +}) => { + await openDirectory(page, directoryHost); + await installListingFromRow(page); + await expectStillBrowsing(page); + await openListingPage(page); + await uninstallFromPage(page); + await installFromPage(page); + await openFromInstalledTab(page); + await uninstallFromPage(page); +}); diff --git a/packages/app/e2e/browser/plugin-management.spec.ts b/packages/app/e2e/browser/plugin-management.spec.ts index 4a866a8f44..cfa6d83c75 100644 --- a/packages/app/e2e/browser/plugin-management.spec.ts +++ b/packages/app/e2e/browser/plugin-management.spec.ts @@ -14,6 +14,44 @@ import { daemonWsRoutePattern } from "../support/helpers/daemon-port"; import { getServerId } from "../support/helpers/server-id"; import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace"; import { waitForSettledPosition } from "../support/helpers/sheet-layout"; +import { + backToPlugins, + clearSearch, + closePluginLogs, + expectGalleryMenuWithoutSourceInstall, + expectPluginActionPending, + expectPluginFailed, + expectPluginHealthy, + expectPluginOff, + expectPluginOn, + expectPluginRemoved, + expectPluginsOff, + expectPluginsOn, + expectPluginsRoute, + expectSourceInstallFailed, + expectSourceInstallTurnsPluginsOn, + expectSourceInstalled, + expectToast, + expectUpdateAvailable, + installFromSource, + openPluginLogs, + openPluginPage, + openPluginPageActions, + openSourceInstall, + pluginRow, + reloadPluginFromPage, + removePluginFromPage, + searchInstalled, + selectInstalledTab, + selectPluginPageAction, + submitSourceInstall, + turnOffPluginsFromMenu, + turnOnPluginsFromAlert, + turnOnPluginsFromMenu, + turnPluginOff, + turnPluginOn, + updatePlugin, +} from "../support/helpers/plugin-gallery"; import { expectSettingsHeader, openCompactSettings, @@ -170,22 +208,12 @@ async function openCompactPluginSettings(page: Page): Promise { const serverId = getServerId(); await openCompactSettings(page, buildOpenProjectRoute()); await openHostSection(page, serverId, "plugins"); - await expect(page.getByRole("textbox", { name: "Plugin source", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: /^Installed/ })).toBeVisible(); } -async function reloadPlugin(page: Page): Promise { - await selectPluginAction(page, "e2e-plugin", "Reload"); - await expect(page.getByText("Reloaded e2e-plugin", { exact: true })).toBeVisible(); -} - -async function openPluginActions(page: Page, pluginId: string): Promise { - await page.getByRole("button", { name: `Actions for ${pluginId}`, exact: true }).click(); - await expect(page.getByRole("menuitem").first()).toBeVisible(); -} - -async function selectPluginAction(page: Page, pluginId: string, action: string): Promise { - await openPluginActions(page, pluginId); - await page.getByRole("menuitem", { name: action, exact: true }).click(); +async function openPluginPageFromSettings(page: Page, name: string): Promise { + await openPluginSettings(page); + await openPluginPage(page, name); } async function expectContributionBody(page: Page, expectedBody: string): Promise { @@ -238,11 +266,6 @@ async function capturePluginInstallForm( }); } -async function installPlugin(page: Page, source: string): Promise { - await page.getByLabel("Plugin source").fill(source); - await page.getByRole("button", { name: "Install plugin" }).click(); -} - async function expectPluginSourceDocsOpen(page: Page): Promise { const requestedPage = page .context() @@ -266,6 +289,17 @@ async function expectPluginSourceDocsOpen(page: Page): Promise { } } +function commitAll(repository: string, message: string): void { + execFileSync("git", ["add", "-A"], { cwd: repository, stdio: "ignore" }); + execFileSync("git", ["commit", "-m", message], { cwd: repository, stdio: "ignore" }); +} + +/** A new commit on the remote is an update for a plugin installed from that Git repository. */ +async function publishGitPluginChange(repository: string, title: string): Promise { + await writeFile(path.join(repository, "index.client.tsx"), pluginSource(title)); + commitAll(repository, title); +} + async function createGitPluginRepository(root: string): Promise { const repository = path.join(root, "repository"); await mkdir(repository); @@ -359,14 +393,12 @@ async function createGatedBuildRepository( } async function installFailedPlugin( - page: Page, client: Awaited>, directory: string, ): Promise { await client.installPluginSource({ source: directory }); await writeFile(path.join(directory, "index.client.tsx"), "export default broken !!!"); await client.reloadPlugin("failed-preview-plugin"); - await expect(page.getByLabel("failed-preview-plugin failed")).toBeVisible(); } test("installs, reloads, recovers, disables, and removes a trusted local plugin", async ({ @@ -378,12 +410,15 @@ test("installs, reloads, recovers, disables, and removes a trusted local plugin" await toggleRemoveAndReinstallLocalPlugin(page, directory); }); -test("installs a Git source after a failed source remains editable", async ({ +test("installs a Git source after a failed source remains editable, then updates it", async ({ page, pluginEnvironment, }, testInfo) => { const source = await prepareCompactGitInstall(page, pluginEnvironment); await retryGitInstallAndInspectRows(page, source, testInfo); + await updateGitPlugin(page, source.repository); + await expectCompactPluginMenuFits(page, testInfo); + await failUpdateFromPluginPage(page, source.repository); }); for (const sourceSupport of [undefined, false]) { @@ -400,7 +435,7 @@ for (const viewport of [ { width: 1280, height: 900 }, { width: 390, height: 844 }, ]) { - test(`installs an npm source and manages its row at ${viewport.width}px`, async ({ + test(`installs an npm source and manages it at ${viewport.width}px`, async ({ page, pluginEnvironment, }, testInfo) => { @@ -415,18 +450,19 @@ async function openNpmPluginSettings(page: Page, width: number) { else await openPluginSettings(page); } -async function expectSourceHierarchy(page: Page, description: string, source: string) { - const descriptionText = page.getByText(description, { exact: false }); - const sourceText = page.getByText(source, { exact: false }); - const descriptionSize = await descriptionText.evaluate((element) => - Number.parseFloat(getComputedStyle(element).fontSize), +/** The row's description reads before where the plugin was installed from. */ +async function expectSourceHierarchy( + page: Page, + pluginId: string, + description: string, + source: string, +) { + const row = pluginRow(page, pluginId); + await expect(row.getByText(description, { exact: true })).toHaveCSS( + "color", + "rgb(113, 113, 122)", ); - const sourceSize = await sourceText.evaluate((element) => - Number.parseFloat(getComputedStyle(element).fontSize), - ); - expect(sourceSize).toBeLessThan(descriptionSize); - await expect(sourceText).toHaveCSS("color", "rgb(161, 161, 170)"); - await expect(descriptionText).toHaveCSS("color", "rgb(113, 113, 122)"); + await expect(row.getByText(source, { exact: true })).toHaveCSS("color", "rgb(161, 161, 170)"); } async function installLocalPluginWithStatusExamples( @@ -457,36 +493,51 @@ async function installLocalPluginWithStatusExamples( }), ); await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v1")); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installPluginSource({ source: disabledDirectory }); + await client.disablePlugin("disabled-preview-plugin-with-a-long-name"); + await installFailedPlugin(client, failedDirectory); const catalog = observePluginCatalog(page); await gotoAppShell(page); await openPluginSettings(page); await catalog.waitForInitialFetch(); - await expect(page.getByRole("textbox", { name: "Plugin installation ID" })).toHaveCount(0); - await expectPluginSourceDocsOpen(page); + await expectPluginFailed(page, "failed-preview-plugin"); + + // Plugins off on the host: the Installed tab says so and turns them back on. await client.patchDaemonConfig({ pluginsEnabled: false }); - await page.getByRole("switch", { name: "Enable plugins" }).click(); - await expect(page.getByText("Plugins enabled", { exact: true })).toBeVisible(); - await client.installPluginSource({ source: disabledDirectory }); - await client.disablePlugin("disabled-preview-plugin-with-a-long-name"); - await installFailedPlugin(page, client, failedDirectory); - await page.getByLabel("Plugin source").fill(directory); - await page.getByRole("button", { name: "Install plugin" }).click(); - await expect(page.getByText("Installed e2e-plugin", { exact: true })).toBeVisible(); - await expect(page.getByLabel("e2e-plugin running")).toBeVisible(); + await expectPluginsOff(page); + await turnOnPluginsFromAlert(page); + await turnOffPluginsFromMenu(page); + await turnOnPluginsFromMenu(page); + + await openSourceInstall(page); + await expectPluginSourceDocsOpen(page); + await submitSourceInstall(page, directory); + await expectSourceInstalled(page, "e2e-plugin"); + await expectPluginOn(page, "e2e-plugin"); + await expectPluginHealthy(page, "e2e-plugin"); await expect(page.getByText("Exercises the complete local plugin lifecycle")).toBeVisible(); await expect( page.getByText("Keeps optional previews off until this plugin is enabled"), ).toBeVisible(); await expect(page.getByText("Demonstrates a plugin that needs attention")).toBeVisible(); - await expect(page.getByLabel("disabled-preview-plugin-with-a-long-name disabled")).toBeVisible(); - await expect(page.getByLabel("failed-preview-plugin failed")).toBeVisible(); + await expectPluginOff(page, "disabled-preview-plugin-with-a-long-name"); + await expectPluginFailed(page, "failed-preview-plugin"); + + await searchInstalled(page, "needs attention"); + await expect(pluginRow(page, "failed-preview-plugin")).toBeVisible(); + await expect(pluginRow(page, "e2e-plugin")).toHaveCount(0); + await clearSearch(page); + await expect(pluginRow(page, "e2e-plugin")).toBeVisible(); await capturePluginInstallForm(page, testInfo, "wide"); - await openPluginActions(page, "e2e-plugin"); + + await openPluginPage(page, "e2e-plugin"); + await openPluginPageActions(page, "e2e-plugin"); await capturePluginInstallForm(page, testInfo, "wide-menu"); - await page.getByRole("menuitem", { name: "Logs", exact: true }).click(); - await expect(page.getByRole("dialog")).toContainText("Logs: e2e-plugin"); - await page.getByRole("button", { name: "Close", exact: true }).click(); + await page.keyboard.press("Escape"); + await openPluginLogs(page, "e2e-plugin"); + await closePluginLogs(page); await openContributionFromSettings(page, "Plugin v1", "Plugin v1 cleanup 0"); return directory; @@ -497,13 +548,13 @@ async function reloadAndRecoverLocalPlugin( client: PluginEnvironment["client"], directory: string, ) { - await openPluginSettings(page); - await reloadPlugin(page); + await openPluginPageFromSettings(page, "e2e-plugin"); + await reloadPluginFromPage(page, "e2e-plugin"); await openContributionFromSettings(page, "Plugin v1", "Plugin v1 cleanup 1"); await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v2")); - await openPluginSettings(page); - await reloadPlugin(page); + await openPluginPageFromSettings(page, "e2e-plugin"); + await reloadPluginFromPage(page, "e2e-plugin"); await openContributionFromSettings(page, "Plugin v2", "Plugin v2 cleanup 2"); await expect(page.getByRole("button", { name: "Plugin v1", exact: true })).not.toBeVisible(); @@ -511,8 +562,8 @@ async function reloadAndRecoverLocalPlugin( path.join(directory, "index.client.tsx"), pluginSource("Broken surface", "render exploded"), ); - await openPluginSettings(page); - await reloadPlugin(page); + await openPluginPageFromSettings(page, "e2e-plugin"); + await reloadPluginFromPage(page, "e2e-plugin"); await openContributionFromSettings(page, "Broken surface", "Plugin failed: render exploded"); await openContribution(page, "Healthy surface", "Healthy contribution"); await openContribution(page, "Broken surface", "Plugin failed: render exploded"); @@ -522,39 +573,39 @@ async function reloadAndRecoverLocalPlugin( await expect(page.getByRole("button", { name: "Broken surface", exact: true })).not.toBeVisible(); await writeFile(path.join(directory, "index.client.tsx"), "export default broken syntax !!!"); - await openPluginSettings(page); - await selectPluginAction(page, "e2e-plugin", "Reload"); - await expect(page.getByTestId("plugin-management-feedback")).toContainText("Request failed"); - await expect(page.getByLabel("e2e-plugin failed")).toBeVisible(); + await openPluginPageFromSettings(page, "e2e-plugin"); + await selectPluginPageAction(page, "e2e-plugin", "Reload"); + await expectToast(page, "Request failed"); + await backToPlugins(page, "e2e-plugin"); + await expectPluginFailed(page, "e2e-plugin"); await leavePluginSettings(page); await expectContributionRemoved(page, "Recovered surface"); await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v3")); - await openPluginSettings(page); - await selectPluginAction(page, "e2e-plugin", "Reload"); - await expect(page.getByLabel("e2e-plugin running")).toBeVisible(); + await openPluginPageFromSettings(page, "e2e-plugin"); + await reloadPluginFromPage(page, "e2e-plugin"); + await backToPlugins(page, "e2e-plugin"); + await expectPluginHealthy(page, "e2e-plugin"); await openContributionFromSettings(page, "Plugin v3", "Plugin v3 cleanup 5"); } async function toggleRemoveAndReinstallLocalPlugin(page: Page, directory: string) { await openPluginSettings(page); - await page.getByRole("switch", { name: "e2e-plugin: Disable", exact: true }).click(); - await expect(page.getByLabel("e2e-plugin disabled")).toBeVisible(); + await turnPluginOff(page, "e2e-plugin"); await leavePluginSettings(page); await expectContributionRemoved(page, "Plugin v3"); await openPluginSettings(page); - await page.getByRole("switch", { name: "e2e-plugin: Enable", exact: true }).click(); - await expect(page.getByLabel("e2e-plugin running")).toBeVisible(); + await turnPluginOn(page, "e2e-plugin"); await openContributionFromSettings(page, "Plugin v3", "Plugin v3 cleanup 6"); - await openPluginSettings(page); - page.once("dialog", (dialog) => dialog.accept()); - await selectPluginAction(page, "e2e-plugin", "Remove"); - await expect(page.getByTestId("plugin-row-e2e-plugin")).toHaveCount(0); + await openPluginPageFromSettings(page, "e2e-plugin"); + await removePluginFromPage(page, "e2e-plugin"); + await expectPluginsRoute(page); + await expectPluginRemoved(page, "e2e-plugin"); - await installPlugin(page, directory); - await expect(page.getByLabel("e2e-plugin running")).toBeVisible(); + await installFromSource(page, directory, "e2e-plugin"); + await expectPluginOn(page, "e2e-plugin"); await gotoAppShell(page); await openContribution(page, "Plugin v3", "Plugin v3 cleanup 7"); } @@ -583,10 +634,8 @@ async function prepareCompactGitInstall(page: Page, pluginEnvironment: PluginEnv await client.disablePlugin("compact-disabled-plugin"); await gotoAppShell(page); await openCompactPluginSettings(page); - await expect(page.getByRole("textbox", { name: "Plugin installation ID" })).toHaveCount(0); await client.patchDaemonConfig({ pluginsEnabled: false }); - await page.getByRole("switch", { name: "Enable plugins" }).click(); - await expect(page.getByText("Plugins enabled", { exact: true })).toBeVisible(); + await expectPluginsOff(page); return { repository, missingSource }; } @@ -598,24 +647,58 @@ async function retryGitInstallAndInspectRows( ) { const { repository, missingSource } = source; - await installPlugin(page, missingSource); - await expect(page.getByTestId("plugin-management-feedback")).toContainText( + await openSourceInstall(page); + // Plugins are off, so the confirmation says installing turns them on. + await expectSourceInstallTurnsPluginsOn(page); + await submitSourceInstall(page, missingSource); + await expectSourceInstallFailed( + page, + missingSource, `Plugin directory does not exist: ${missingSource}`, ); - await expect(page.getByLabel("Plugin source")).toHaveValue(missingSource); await capturePluginInstallForm(page, testInfo, "compact-error"); - await installPlugin(page, pathToFileURL(repository).href); - await expect(page.getByText("Installed git-e2e-plugin", { exact: true })).toBeVisible(); - await expect(page.getByLabel("git-e2e-plugin running")).toBeVisible(); + await submitSourceInstall(page, pathToFileURL(repository).href); + await expectSourceInstalled(page, "git-e2e-plugin"); + await expectPluginsOn(page); + await expectPluginOn(page, "git-e2e-plugin"); await expect( page.getByText("Shows how a realistically long plugin description wraps on a compact screen"), ).toBeVisible(); - await expect(page.getByLabel("compact-disabled-plugin disabled")).toBeVisible(); - await expect(page.getByLabel("Plugin source")).toHaveValue(""); + await expectPluginOff(page, "compact-disabled-plugin"); await capturePluginInstallForm(page, testInfo, "compact-success"); - await openPluginActions(page, "git-e2e-plugin"); - const removeAction = page.getByRole("menuitem", { name: "Remove", exact: true }); +} + +async function updateGitPlugin(page: Page, repository: string) { + await publishGitPluginChange(repository, "Git plugin v2"); + // Updates are checked when Plugins opens. + await page.reload(); + await expectUpdateAvailable(page, "git-e2e-plugin"); + await updatePlugin(page, "git-e2e-plugin"); + await expectPluginOn(page, "git-e2e-plugin"); +} + +/** An update that fails on the plugin's page says why there, and offers Retry. */ +async function failUpdateFromPluginPage(page: Page, repository: string) { + await publishGitPluginChange(repository, "Git plugin v3"); + await page.reload(); + const update = page.getByTestId("plugin-update").filter({ visible: true }); + await expect(update).toHaveText("Update"); + // Rewriting the commit the page checked leaves its update pointing at a commit the remote no + // longer serves. The next check offers the rewritten commit. + execFileSync("git", ["commit", "--amend", "-m", "Git plugin v3, amended"], { + cwd: repository, + stdio: "ignore", + }); + await update.click(); + await expect(update).toHaveText("Retry"); + await expect(page.getByText(/Git command failed/)).toBeVisible(); +} + +async function expectCompactPluginMenuFits(page: Page, testInfo: TestInfo) { + await openPluginPage(page, "git-e2e-plugin"); + await openPluginPageActions(page, "git-e2e-plugin"); + const removeAction = page.getByRole("menuitem", { name: "Uninstall", exact: true }); await expect(removeAction).toBeInViewport({ ratio: 1 }); await waitForSettledPosition(removeAction); await capturePluginInstallForm(page, testInfo, "compact-menu"); @@ -648,12 +731,11 @@ async function prepareLegacyPluginHost( async function verifyLegacyPluginManagement(page: Page, directory: string) { await expect( - page.getByText("Update this host to install plugins", { exact: true }), + pluginRow(page, "legacy-source-plugin").getByText(directory, { exact: true }), ).toBeVisible(); - await expect(page.getByRole("textbox", { name: "Plugin source", exact: true })).toHaveCount(0); - await expect(page.getByText(directory, { exact: true })).toBeVisible(); - await selectPluginAction(page, "legacy-source-plugin", "Reload"); - await expect(page.getByText("Reloaded legacy-source-plugin", { exact: true })).toBeVisible(); + await expectGalleryMenuWithoutSourceInstall(page); + await openPluginPage(page, "legacy-source-plugin"); + await reloadPluginFromPage(page, "legacy-source-plugin"); } async function prepareNpmPluginHost( @@ -667,23 +749,22 @@ async function prepareNpmPluginHost( await client.patchDaemonConfig({ pluginsEnabled: true }); await gotoAppShell(page); await openNpmPluginSettings(page, viewport.width); + await selectInstalledTab(page); } async function retryNpmInstallAndInspectRow(page: Page, width: number, testInfo: TestInfo) { - await installPlugin(page, "npm:missing-plugin"); - await expect(page.getByTestId("plugin-management-feedback")).toContainText("404"); - await expect(page.getByLabel("Plugin source")).toHaveValue("npm:missing-plugin"); - await installPlugin(page, "npm:@paseo-fixture/review@^2.0.0"); - await expect(page.getByText("Installed npm-review", { exact: true })).toBeVisible(); - await expect(page.getByLabel("npm-review running")).toBeVisible(); + await openSourceInstall(page); + await submitSourceInstall(page, "npm:missing-plugin"); + await expectSourceInstallFailed(page, "npm:missing-plugin", "404"); + await submitSourceInstall(page, "npm:@paseo-fixture/review@^2.0.0"); + await expectSourceInstalled(page, "npm-review"); + await expectPluginOn(page, "npm-review"); await expectSourceHierarchy( page, + "npm-review", "Installed from the npm fixture registry", "npm:@paseo-fixture/review · 2.0.0", ); - await expect( - page.getByText("Installed from the npm fixture registry", { exact: true }), - ).toBeVisible(); await page.screenshot({ path: testInfo.outputPath(`npm-plugin-${width}.png`), animations: "disabled", @@ -691,12 +772,11 @@ async function retryNpmInstallAndInspectRow(page: Page, width: number, testInfo: } async function reloadAndRemoveNpmPlugin(page: Page) { - await selectPluginAction(page, "npm-review", "Reload"); - await expect(page.getByText("Reloaded npm-review", { exact: true })).toBeVisible(); - page.once("dialog", (dialog) => dialog.accept()); - await selectPluginAction(page, "npm-review", "Remove"); - await expect(page.getByText("Removed npm-review", { exact: true })).toBeVisible(); - await expect(page.getByLabel("npm-review running")).toHaveCount(0); + await openPluginPage(page, "npm-review"); + await reloadPluginFromPage(page, "npm-review"); + await removePluginFromPage(page, "npm-review"); + await expectPluginsRoute(page); + await expectPluginRemoved(page, "npm-review"); } test("renders installed-plugin descriptions as plain text", async ({ page, pluginEnvironment }) => { @@ -793,19 +873,6 @@ async function holdPluginLifecycleQueue( }; } -function pluginRowActions(page: Page, pluginId: string) { - return page.getByRole("button", { name: `Actions for ${pluginId}`, exact: true }); -} - -async function expectPluginRowPending(page: Page, pluginId: string): Promise { - await expect(pluginRowActions(page, pluginId)).toBeDisabled(); -} - -async function expectPluginRowSettled(page: Page, pluginId: string): Promise { - await expect(pluginRowActions(page, pluginId)).toBeEnabled(); - await expect(page.getByLabel(`${pluginId} running`)).toBeVisible(); -} - async function capturePluginSurface(page: Page, testInfo: TestInfo, name: string): Promise { await page.screenshot({ path: testInfo.outputPath(name), @@ -836,39 +903,36 @@ test("keeps Reload pending past a minute while the plugin queue is busy", async // Observe before the app loads: its daemon socket comes up with the page. const reload = observePluginReload(page); await gotoAppShell(page); - await openPluginSettings(page); - // Plugins on is a precondition here, not the subject: set it through the daemon instead of the - // switch, whose transient "Plugins enabled" confirmation this scenario must not depend on. + // Plugins on is a precondition here, not the subject: set it through the daemon. await client.patchDaemonConfig({ pluginsEnabled: true }); await client.installPluginSource({ source: pluginDirectory }); - await expectPluginRowSettled(page, "e2e-plugin"); + // Installed before Plugins opens, so it opens on the Installed tab. + await openPluginSettings(page); + await expectPluginOn(page, "e2e-plugin"); + await openPluginPage(page, "e2e-plugin"); const queue = await holdPluginLifecycleQueue(client, directory); try { - await selectPluginAction(page, "e2e-plugin", "Reload"); + await selectPluginPageAction(page, "e2e-plugin", "Reload"); await reload.waitForRequest(); - // Pending: the row's actions stay disabled, so a second reload cannot be submitted. - await expectPluginRowPending(page, "e2e-plugin"); + // Pending: the plugin's controls stay disabled, so a second action cannot be submitted. + await expectPluginActionPending(page, "e2e-plugin"); await capturePluginSurface(page, testInfo, "plugin-reload-pending.png"); await waitPastFormerReloadDeadline(page, reload.requestedAt()); - // Past the former deadline the reload is still pending, the row shows its previous state, and - // no timeout error reached the surface. - await expectPluginRowPending(page, "e2e-plugin"); - await expect(page.getByLabel("e2e-plugin running")).toBeVisible(); - await expect(page.getByTestId("plugin-management-feedback")).toHaveCount(0); + // Past the former deadline the reload is still pending; a request timeout would have settled + // it and released the switch. + await expectPluginActionPending(page, "e2e-plugin"); + await expect(page.getByTestId("app-toast-message")).toHaveCount(0); await capturePluginSurface(page, testInfo, "plugin-reload-past-deadline.png"); await queue.release(); - // The daemon's answer only arrives once the plugin really started again; a request timeout - // would have shown up as feedback during the wait above. + // The daemon's answer only arrives once the plugin really started again. await reload.waitForResponse(); expect(reload.requestCount()).toBe(1); - await expect(page.getByTestId("plugin-management-feedback")).toContainText( - "Reloaded e2e-plugin", - ); - await expectPluginRowSettled(page, "e2e-plugin"); + await expectToast(page, "Reloaded e2e-plugin"); + await expectPluginOn(page, "e2e-plugin"); await capturePluginSurface(page, testInfo, "plugin-reload-completed.png"); } finally { await queue.settle(); diff --git a/packages/app/e2e/browser/plugin-settings.spec.ts b/packages/app/e2e/browser/plugin-settings.spec.ts index 4a15063cd0..2407cc93d8 100644 --- a/packages/app/e2e/browser/plugin-settings.spec.ts +++ b/packages/app/e2e/browser/plugin-settings.spec.ts @@ -18,11 +18,12 @@ import { expectSettingsUnavailable, openPluginsPage, expectActionsMenuWithoutSettings, - expectNoSettingsCogWithoutScreens, + expectSettingsFollowPluginSwitch, + expectSettingsHidden, + expectSettingsTab, openTabbedSettings, selectSettingsTab, openTabbedSettingsLink, - expectSettingsTooltip, expectNamedPluginRow, } from "../support/helpers/plugin-settings"; @@ -52,35 +53,41 @@ test("another client's save preserves a conflicting draft", async ({ page }) => await discardTitle(page); }); -test("Back to plugins returns from a plugin settings screen", async ({ page }) => { +test("Back to plugins returns from a plugin page", async ({ page }) => { await openDisplaySettings(page); await returnToPluginsPage(page); }); -test("plugin settings open from the cog and show a tab per screen", async ({ page }) => { +test("plugin pages open from their row and show a tab per settings screen", async ({ page }) => { await openPluginsPage(page); await test.step("plugin rows show the display name", async () => { await expectNamedPluginRow(page); }); - await test.step("the cog explains itself", async () => { - await expectSettingsTooltip(page); + await test.step("the row opens the plugin's page", async () => { + await openTabbedSettings(page); }); - await test.step("the actions menu keeps only plugin actions", async () => { + await test.step("the page's menu keeps only plugin actions", async () => { await expectActionsMenuWithoutSettings(page); }); await test.step("tabs switch between the plugin's settings screens", async () => { - await openTabbedSettings(page); await selectSettingsTab(page, "Advanced"); await selectSettingsTab(page, "General"); await returnToPluginsPage(page); }); - await test.step("a plugin without settings screens shows no cog", async () => { - await expectNoSettingsCogWithoutScreens(page); + await test.step("turning a plugin off removes its settings from its page", async () => { + await expectSettingsFollowPluginSwitch(page); }); }); -test("a settings screen link opens its tab", async ({ page }) => { +test("a settings screen link opens its tab, unavailable while the plugin is off", async ({ + page, + settingsPlugin, +}) => { await openTabbedSettingsLink(page, "Advanced"); + await settingsPlugin.disablePlugin("settings-tabs"); + await expectSettingsUnavailable(page); + await settingsPlugin.enablePlugin("settings-tabs"); + await expectSettingsTab(page, "Advanced"); }); test.describe("compact plugin settings", () => { @@ -95,7 +102,7 @@ test.describe("compact plugin settings", () => { await hideMetadata(page); await returnAndReopenSettings(page); await settingsPlugin.disablePlugin("settings-example"); - await expectSettingsUnavailable(page); + await expectSettingsHidden(page); await settingsPlugin.enablePlugin("settings-example"); await reloadSavedDisplaySettings(page); }); diff --git a/packages/app/e2e/mobile/appearance-keyboard/android.mjs b/packages/app/e2e/mobile/appearance-keyboard/android.mjs index 1320a94d6b..cb56dec907 100644 --- a/packages/app/e2e/mobile/appearance-keyboard/android.mjs +++ b/packages/app/e2e/mobile/appearance-keyboard/android.mjs @@ -111,11 +111,13 @@ try { "android", "--no-test-ime", ); - ad("wait", "text", "Plugin source", "5000"); - const plugins = JSON.parse(ad("snapshot", "-i", "--json")); - const source = plugins.data.nodes.find((node) => node.type === "android.widget.EditText"); - assert(source, "The connected host must support installing plugins from source"); - ad("press", `@${source.ref}`); + // The source field lives in the Install from source sheet, behind the page's menu. + ad("wait", 'label="More plugin actions"', "5000"); + ad("press", 'label="More plugin actions"'); + ad("wait", 'text="Install from source"', "5000"); + ad("press", 'text="Install from source"'); + ad("wait", 'id="plugin-source-input"', "5000"); + ad("press", 'id="plugin-source-input"'); ad("type", "qa-source"); const pluginMeasurement = await waitForFocusedInput(); // A FormTextInput draws its border and padding on the native input's parent. diff --git a/packages/app/e2e/support/helpers/plugin-directory.ts b/packages/app/e2e/support/helpers/plugin-directory.ts new file mode 100644 index 0000000000..45c4838e96 --- /dev/null +++ b/packages/app/e2e/support/helpers/plugin-directory.ts @@ -0,0 +1,205 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { expect, test as base, type Page } from "../fixtures"; +import appPackage from "../../../package.json"; +import { gotoAppShell, openSettings } from "./app"; +import { addConnectedHostAndReload } from "./hosts"; +import { pluginRequirements } from "./plugin-fixture"; +import { + expectToast, + openPluginPage, + pluginPageName, + selectInstalledTab, + selectPluginPageAction, +} from "./plugin-gallery"; +import { openHostSection, selectSettingsHost } from "./settings"; +import { startHostDaemon } from "./versioned-host-daemon"; + +/** + * Settings → Plugins → Browse against a host whose registry is a local server. The one listing + * installs from a local Git repository, so installing needs no network. + */ + +export const LISTING = { + id: "acme/directory-example", + name: "Directory example", + description: "Adds a review checklist to every workspace", + overview: "Directory example keeps a checklist beside your agents.", +}; + +export const test = base.extend<{ directoryHost: { serverId: string; port: number } }>({ + directoryHost: async ({ e2eWorker }, provide) => { + void e2eWorker; + const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-directory-")); + const registry = await startRegistry(await createListedPlugin(root)); + try { + const host = await startHostDaemon({ + version: appPackage.version, + pluginRegistryUrl: registry.url, + }); + try { + await provide({ serverId: host.serverId, port: host.port }); + } finally { + await host.dispose(); + } + } finally { + await registry.close(); + await rm(root, { recursive: true, force: true }); + } + }, +}); + +async function createListedPlugin(root: string) { + const repository = path.join(root, "repository"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "ignore" }); + await writeFile( + path.join(repository, "paseo-plugin.json"), + JSON.stringify({ + id: "directory-example", + name: LISTING.name, + requirements: pluginRequirements, + }), + ); + await writeFile( + path.join(repository, "index.client.ts"), + "export default function () { return () => {}; }", + ); + const git = (...args: string[]) => + execFileSync( + "git", + ["-c", "user.name=Paseo Tests", "-c", "user.email=e2e@paseo.test", ...args], + { + cwd: repository, + encoding: "utf8", + }, + ).trim(); + git("add", "-A"); + git("commit", "-m", "initial"); + const date = "2026-10-03T00:00:00.000Z"; + return { + id: LISTING.id, + name: LISTING.name, + description: LISTING.description, + categories: ["tools"], + author: { github: "acme", name: "Acme" }, + repository: { url: "https://github.com/acme/directory-example" }, + artifact: { + kind: "git", + remote: pathToFileURL(repository).href, + commit: git("rev-parse", "HEAD"), + }, + media: [], + submittedAt: date, + reviewedAt: date, + updatedAt: date, + publishedAt: date, + installs: 1200, + }; +} + +async function startRegistry(listing: Record) { + const documents: Record = { + "/index.json": { + schemaVersion: 1, + registry: { name: "Local", url: "http://127.0.0.1" }, + categories: [{ slug: "tools", label: "Tools" }], + plugins: [listing], + featured: [], + generatedAt: "2026-10-03T00:00:00.000Z", + }, + [`/plugins/${LISTING.id}.json`]: { + ...listing, + readme: `# ${LISTING.name}\n\n${LISTING.overview}`, + }, + }; + const server = createServer((request, response) => { + const document = request.url ? documents[request.url] : undefined; + if (!document) { + response.writeHead(404).end(); + return; + } + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(document)); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing registry address"); + return { + url: `http://127.0.0.1:${address.port}`, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +function listingRow(page: Page) { + return page.getByTestId(`plugin-listing-${LISTING.id}`).filter({ visible: true }); +} + +function browseTab(page: Page) { + return page.getByRole("button", { name: "Browse", exact: true }); +} + +/** A host with no plugins opens Plugins on Browse. */ +export async function openDirectory(page: Page, host: { serverId: string; port: number }) { + await gotoAppShell(page); + await addConnectedHostAndReload(page, { ...host, label: "Plugin directory" }); + await openSettings(page); + await selectSettingsHost(page, host.serverId); + await openHostSection(page, host.serverId, "plugins"); + await expect(browseTab(page)).toHaveAttribute("aria-selected", "true"); + await expect(listingRow(page)).toContainText(LISTING.description); +} + +/** Install asks first, naming the author and version, then the row offers Uninstall. */ +export async function installListingFromRow(page: Page) { + await listingRow(page).getByTestId(`plugin-install-${LISTING.id}`).click(); + const sheet = page.getByTestId("plugin-install-sheet"); + await expect(sheet).toContainText("Acme"); + await sheet.getByTestId("plugin-install-confirm").click(); + await expect(listingRow(page).getByTestId(`plugin-uninstall-${LISTING.id}`)).toBeVisible({ + timeout: 60_000, + }); +} + +/** Installing the first plugin keeps the user on Browse. */ +export async function expectStillBrowsing(page: Page) { + await expect(browseTab(page)).toHaveAttribute("aria-selected", "true"); + await expect(page.getByRole("button", { name: /^Installed · 1/ })).toBeVisible(); +} + +export async function openListingPage(page: Page) { + await listingRow(page).getByText(LISTING.name, { exact: true }).click(); + await expect(pluginPageName(page)).toHaveText(LISTING.name); + await expect(page.getByText(LISTING.overview, { exact: true })).toBeVisible(); +} + +/** + * Uninstalling keeps the plugin's page open on its listing, back on Install, whether the page was + * opened from Browse or from the Installed tab. + */ +export async function uninstallFromPage(page: Page) { + page.once("dialog", (dialog) => dialog.accept()); + await selectPluginPageAction(page, LISTING.name, "Uninstall"); + await expectToast(page, `Uninstalled ${LISTING.name}`); + await expect(pluginPageName(page)).toHaveText(LISTING.name); + await expect( + page.getByTestId(`plugin-install-${LISTING.id}`).filter({ visible: true }), + ).toBeVisible(); +} + +export async function installFromPage(page: Page) { + await page.getByTestId(`plugin-install-${LISTING.id}`).filter({ visible: true }).click(); + await page.getByTestId("plugin-install-confirm").click(); + await expect( + page.getByRole("button", { name: `Actions for ${LISTING.name}`, exact: true }), + ).toBeVisible({ timeout: 60_000 }); +} + +export async function openFromInstalledTab(page: Page) { + await page.getByRole("button", { name: "Back to plugins", exact: true }).click(); + await selectInstalledTab(page); + await openPluginPage(page, LISTING.name, "directory-example"); +} diff --git a/packages/app/e2e/support/helpers/plugin-gallery.ts b/packages/app/e2e/support/helpers/plugin-gallery.ts new file mode 100644 index 0000000000..129f92488b --- /dev/null +++ b/packages/app/e2e/support/helpers/plugin-gallery.ts @@ -0,0 +1,269 @@ +import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; +import { expect, type Page } from "../fixtures"; +import { getServerId } from "./server-id"; +import { expectAppRoute } from "./route-assertions"; + +/** + * Settings → Host → Plugins: the Installed and Browse tabs, the page menu, the install sheet and a + * plugin's own page. Helpers that take a plugin name expect the manifest name, which is the plugin + * ID when the manifest has none. + */ + +export function pluginsRoute(serverId = getServerId()): string { + return buildSettingsHostSectionRoute(serverId, "plugins"); +} + +export function pluginPageRoute(pluginId: string, serverId = getServerId()): string { + return `${pluginsRoute(serverId)}/${encodeURIComponent(pluginId)}`; +} + +/** Settings keeps the Plugins page mounted beneath a plugin's page, so read visible rows only. */ +export function pluginRow(page: Page, pluginId: string) { + return page.getByTestId(`plugin-row-${pluginId}`).filter({ visible: true }); +} + +function pluginSwitch(page: Page, name: string, action: "Disable" | "Enable") { + return page.getByRole("switch", { name: `${name}: ${action}`, exact: true }).filter({ + visible: true, + }); +} + +export async function expectToast(page: Page, message: string): Promise { + await expect(page.getByTestId("app-toast-message")).toContainText(message); +} + +// Tabs and search + +export async function selectInstalledTab(page: Page): Promise { + const tab = page.getByRole("button", { name: /^Installed/ }); + await tab.click(); + await expect(tab).toHaveAttribute("aria-selected", "true"); +} + +export async function searchInstalled(page: Page, query: string): Promise { + await page.getByRole("textbox", { name: "Search installed", exact: true }).fill(query); +} + +export async function clearSearch(page: Page): Promise { + await page.getByRole("button", { name: "Clear search", exact: true }).click(); + await expect(page.getByRole("textbox", { name: "Search installed", exact: true })).toHaveValue( + "", + ); +} + +// Installed rows + +export async function expectPluginOn(page: Page, name: string): Promise { + await expect(pluginSwitch(page, name, "Disable")).toBeVisible(); + await expect(pluginSwitch(page, name, "Disable")).toBeEnabled(); +} + +export async function expectPluginOff(page: Page, name: string): Promise { + await expect(pluginSwitch(page, name, "Enable")).toBeVisible(); +} + +export async function turnPluginOff(page: Page, name: string): Promise { + await pluginSwitch(page, name, "Disable").click(); + await expectPluginOff(page, name); +} + +export async function turnPluginOn(page: Page, name: string): Promise { + await pluginSwitch(page, name, "Enable").click(); + await expectPluginOn(page, name); +} + +/** The switch stays disabled while an action on the plugin runs, so a second one cannot start. */ +export async function expectPluginActionPending(page: Page, name: string): Promise { + await expect(pluginSwitch(page, name, "Disable")).toBeDisabled(); +} + +export async function expectPluginFailed(page: Page, pluginId: string): Promise { + await expect(pluginRow(page, pluginId).getByText("failed", { exact: true })).toBeVisible(); +} + +export async function expectPluginHealthy(page: Page, pluginId: string): Promise { + await expect(pluginRow(page, pluginId)).toBeVisible(); + await expect(pluginRow(page, pluginId).getByText("failed", { exact: true })).toHaveCount(0); +} + +export async function expectPluginRemoved(page: Page, pluginId: string): Promise { + await expect(page.getByTestId(`plugin-row-${pluginId}`)).toHaveCount(0); +} + +// Plugins on the host + +function pluginsOffAlert(page: Page) { + return page.getByRole("alert").filter({ hasText: "Plugins are off on" }); +} + +export async function expectPluginsOff(page: Page): Promise { + await expect(pluginsOffAlert(page)).toBeVisible(); +} + +export async function expectPluginsOn(page: Page): Promise { + await expect(pluginsOffAlert(page)).toHaveCount(0); +} + +export async function turnOnPluginsFromAlert(page: Page): Promise { + await pluginsOffAlert(page).getByRole("button", { name: "Turn on", exact: true }).click(); + await expectPluginsOn(page); +} + +// The page menu + +function galleryMenu(page: Page) { + return page.getByRole("button", { name: "More plugin actions", exact: true }).filter({ + visible: true, + }); +} + +async function openGalleryMenu(page: Page): Promise { + await galleryMenu(page).click(); + await expect(page.getByRole("menuitem").first()).toBeVisible(); +} + +export async function expectGalleryMenuWithoutSourceInstall(page: Page): Promise { + await openGalleryMenu(page); + await expect(page.getByRole("menuitem", { name: "Turn off plugins", exact: true })).toBeVisible(); + await expect( + page.getByRole("menuitem", { name: "Install from source", exact: true }), + ).toHaveCount(0); + await page.keyboard.press("Escape"); +} + +export async function turnOffPluginsFromMenu(page: Page): Promise { + await openGalleryMenu(page); + await page.getByRole("menuitem", { name: "Turn off plugins", exact: true }).click(); + await expectToast(page, "Plugins disabled"); + await expectPluginsOff(page); +} + +export async function turnOnPluginsFromMenu(page: Page): Promise { + await openGalleryMenu(page); + await page.getByRole("menuitem", { name: "Turn on plugins", exact: true }).click(); + await expectToast(page, "Plugins enabled"); + await expectPluginsOn(page); +} + +// Install from source + +function sourceField(page: Page) { + return page.getByRole("textbox", { name: "Plugin source", exact: true }); +} + +export async function openSourceInstall(page: Page): Promise { + await openGalleryMenu(page); + await page.getByRole("menuitem", { name: "Install from source", exact: true }).click(); + await expect(sourceField(page)).toBeVisible(); +} + +export async function expectSourceInstallTurnsPluginsOn(page: Page): Promise { + await expect( + page.getByText("Plugins are not sandboxed. Installing also turns plugins on.", { + exact: true, + }), + ).toBeVisible(); +} + +export async function submitSourceInstall(page: Page, source: string): Promise { + await sourceField(page).fill(source); + await page.getByRole("button", { name: "Install", exact: true }).click(); +} + +/** A failed install keeps the sheet open with the source, so the user can correct it. */ +export async function expectSourceInstallFailed( + page: Page, + source: string, + message: string, +): Promise { + await expect(page.getByRole("alert").filter({ hasText: message })).toBeVisible(); + await expect(sourceField(page)).toHaveValue(source); +} + +export async function expectSourceInstalled(page: Page, name: string): Promise { + await expectToast(page, `Installed ${name}`); + await expect(sourceField(page)).toHaveCount(0); +} + +export async function installFromSource(page: Page, source: string, name: string): Promise { + await openSourceInstall(page); + await submitSourceInstall(page, source); + await expectSourceInstalled(page, name); +} + +// Updates + +function updateRow(page: Page, pluginId: string) { + return page.getByTestId(`plugin-update-${pluginId}`).filter({ visible: true }); +} + +export async function updatePlugin(page: Page, pluginId: string): Promise { + await updateRow(page, pluginId).getByRole("button", { name: "Update", exact: true }).click(); + await expectToast(page, `${pluginId} updated`); + await expect(page.getByTestId(`plugin-update-${pluginId}`)).toHaveCount(0); +} + +export async function expectUpdateAvailable(page: Page, pluginId: string): Promise { + await expect(updateRow(page, pluginId)).toBeVisible(); +} + +// A plugin's page + +export function pluginPageName(page: Page) { + return page.getByTestId("plugin-page-name").filter({ visible: true }); +} + +/** Opens the plugin's page from its row on the Installed tab. */ +export async function openPluginPage(page: Page, name: string, pluginId = name): Promise { + await pluginRow(page, pluginId).getByText(name, { exact: true }).click(); + await expect(pluginPageName(page)).toHaveText(name); +} + +export async function backToPlugins(page: Page, pluginId: string): Promise { + await page.getByRole("button", { name: "Back to plugins", exact: true }).click(); + await expect(pluginRow(page, pluginId)).toBeVisible(); +} + +export async function openPluginPageActions(page: Page, name: string): Promise { + await page + .getByRole("button", { name: `Actions for ${name}`, exact: true }) + .filter({ visible: true }) + .click(); + await expect(page.getByRole("menuitem").first()).toBeVisible(); +} + +export async function selectPluginPageAction( + page: Page, + name: string, + action: "Reload" | "Logs" | "Uninstall", +): Promise { + await openPluginPageActions(page, name); + await page.getByRole("menuitem", { name: action, exact: true }).click(); +} + +export async function reloadPluginFromPage(page: Page, name: string): Promise { + await selectPluginPageAction(page, name, "Reload"); + await expectToast(page, `Reloaded ${name}`); +} + +export async function openPluginLogs(page: Page, name: string): Promise { + await selectPluginPageAction(page, name, "Logs"); + await expect(page.getByRole("dialog")).toContainText(`Logs: ${name}`); +} + +export async function closePluginLogs(page: Page): Promise { + await page.getByRole("button", { name: "Close", exact: true }).click(); + await expect(page.getByRole("dialog")).toHaveCount(0); +} + +/** Uninstall confirms first; uninstalling a plugin that is not in the directory returns to Plugins. */ +export async function removePluginFromPage(page: Page, name: string): Promise { + page.once("dialog", (dialog) => dialog.accept()); + await selectPluginPageAction(page, name, "Uninstall"); + await expectToast(page, `Uninstalled ${name}`); + await expect(pluginPageName(page)).toHaveCount(0); +} + +export async function expectPluginsRoute(page: Page): Promise { + await expectAppRoute(page, pluginsRoute()); +} diff --git a/packages/app/e2e/support/helpers/plugin-requirements.ts b/packages/app/e2e/support/helpers/plugin-requirements.ts index cf680c11b4..152018a1b4 100644 --- a/packages/app/e2e/support/helpers/plugin-requirements.ts +++ b/packages/app/e2e/support/helpers/plugin-requirements.ts @@ -9,6 +9,15 @@ import { addConnectedHostAndReload } from "./hosts"; import { gotoAppShell, openSettings } from "./app"; import { openHostSection, selectSettingsHost } from "./settings"; import { pluginRequirements } from "./plugin-fixture"; +import { + backToPlugins, + expectPluginFailed, + expectPluginHealthy, + openPluginPage, + selectPluginPageAction, +} from "./plugin-gallery"; + +const PLUGIN_ID = "requirements-example"; export const test = base.extend<{ requirementHost: { serverId: string; port: number; directory: string; client: DaemonClient }; @@ -80,7 +89,7 @@ export const test = base.extend<{ async function writeRequirements(directory: string, paseo: string) { await writeFile( path.join(directory, "paseo-plugin.json"), - JSON.stringify({ id: "requirements-example", requirements: { paseo } }), + JSON.stringify({ id: PLUGIN_ID, requirements: { paseo } }), ); } @@ -93,7 +102,7 @@ export async function openRequirementHost(page: Page, host: { serverId: string; } export async function expectAppMismatch(page: Page) { - await expect(page.getByLabel("requirements-example failed", { exact: true })).toBeVisible(); + await expectPluginFailed(page, PLUGIN_ID); await expect( page.getByText(/Plugin "requirements-example" requires Paseo \^99.0.0. Your app is/), ).toBeVisible(); @@ -102,18 +111,21 @@ export async function expectAppMismatch(page: Page) { export async function correctRequirementAndReload(page: Page, directory: string) { await writeRequirements(directory, pluginRequirements.paseo); await reloadRequirementsPlugin(page); - await expect(page.getByLabel("requirements-example running", { exact: true })).toBeVisible(); + await backToPlugins(page, PLUGIN_ID); + await expectPluginHealthy(page, PLUGIN_ID); await expect(page.getByText(/Your app is/)).toHaveCount(0); } export async function rejectDaemonMismatch(page: Page, directory: string) { await writeRequirements(directory, ">=100.0.0"); await reloadRequirementsPlugin(page); - await expect(page.getByLabel("requirements-example failed", { exact: true })).toBeVisible(); + await backToPlugins(page, PLUGIN_ID); + await expectPluginFailed(page, PLUGIN_ID); await expect(page.getByText(/Your daemon is 99.0.0/).first()).toBeVisible(); } +/** Reload lives on the plugin's page. */ async function reloadRequirementsPlugin(page: Page) { - await page.getByRole("button", { name: "Actions for requirements-example", exact: true }).click(); - await page.getByRole("menuitem", { name: "Reload", exact: true }).click(); + await openPluginPage(page, PLUGIN_ID); + await selectPluginPageAction(page, PLUGIN_ID, "Reload"); } diff --git a/packages/app/e2e/support/helpers/plugin-settings.ts b/packages/app/e2e/support/helpers/plugin-settings.ts index 53048359f1..900040afff 100644 --- a/packages/app/e2e/support/helpers/plugin-settings.ts +++ b/packages/app/e2e/support/helpers/plugin-settings.ts @@ -7,8 +7,18 @@ import { gotoAppShell, openSettings } from "./app"; import { goBackInSettings, openCompactSettings, openHostSection } from "./settings"; import { getServerId } from "./server-id"; import { expectAppRoute } from "./route-assertions"; -import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; import { connectNewWorkspaceDaemonClient } from "./new-workspace"; +import { + backToPlugins, + openPluginPage, + openPluginPageActions, + pluginPageName, + pluginPageRoute, + pluginRow, + pluginsRoute, + turnPluginOff, + turnPluginOn, +} from "./plugin-gallery"; type SettingsClient = Awaited>; @@ -90,68 +100,64 @@ export const test = base.extend<{ settingsPlugin: SettingsClient }>({ export async function openDisplaySettings(page: Page) { await gotoAppShell(page); await openSettings(page); - await openPluginScreen(page); + await openSettingsExamplePage(page); } export async function openCompactDisplaySettings(page: Page) { await gotoAppShell(page); await openCompactSettings(page, new URL(page.url()).pathname); - await openPluginScreen(page); + await openSettingsExamplePage(page); } -async function openPluginScreen(page: Page) { +async function openSettingsExamplePage(page: Page) { await openHostSection(page, getServerId(), "plugins"); - await openSettingsFromCog(page); + await openPluginPage(page, "settings-example"); + await expectSettingsExampleScreen(page); } -/** The cog on a plugin's row. Its label is "Settings"; the row tells plugins apart. */ -function settingsButton(page: Page, pluginId: string) { - return page - .getByTestId(`plugin-row-${pluginId}`) - .filter({ visible: true }) - .getByRole("button", { name: "Settings", exact: true }); -} -async function openSettingsFromCog(page: Page) { - await settingsButton(page, "settings-example").click(); +/** A plugin's page shows its settings inline. With one screen there are no tabs. */ +async function expectSettingsExampleScreen(page: Page) { await expect(page.getByRole("switch", { name: "Show metadata" })).toBeVisible(); - // A plugin with one settings screen shows no tabs, and the header names only the plugin. await expect(page.getByTestId("plugin-settings-tabs")).toHaveCount(0); - await expectSettingsHeader(page, "settings-example"); + await expectAppRoute(page, pluginPageRoute("settings-example")); } export async function openPluginsPage(page: Page) { await gotoAppShell(page); await openSettings(page); await openHostSection(page, getServerId(), "plugins"); } +/** The page's menu holds plugin actions only; its settings screens are on the page itself. */ export async function expectActionsMenuWithoutSettings(page: Page) { - await page.getByRole("button", { name: "Actions for settings-example", exact: true }).click(); + await openPluginPageActions(page, TABBED_PLUGIN_NAME); await expect(page.getByRole("menuitem", { name: "Reload", exact: true })).toBeVisible(); - await expect(page.getByRole("menuitem", { name: "Display", exact: true })).toHaveCount(0); + await expect(page.getByRole("menuitem", { name: "General", exact: true })).toHaveCount(0); + await expect(page.getByRole("menuitem", { name: "Advanced", exact: true })).toHaveCount(0); await page.keyboard.press("Escape"); } -export async function expectNoSettingsCogWithoutScreens(page: Page) { - await page.getByRole("switch", { name: "settings-example: Disable" }).click(); - await expect(page.getByRole("switch", { name: "settings-example: Enable" })).toBeVisible(); - await expect(settingsButton(page, "settings-example")).toHaveCount(0); - await page.getByRole("switch", { name: "settings-example: Enable" }).click(); - await expect(settingsButton(page, "settings-example")).toBeVisible(); +/** Turning a plugin off unloads its settings screens, so its page no longer shows them. */ +export async function expectSettingsFollowPluginSwitch(page: Page) { + await openPluginPage(page, "settings-example"); + await turnPluginOff(page, "settings-example"); + await expectSettingsHidden(page); + await turnPluginOn(page, "settings-example"); + await expect(page.getByRole("switch", { name: "Show metadata" })).toBeVisible(); } -export async function expectSettingsTooltip(page: Page) { - await settingsButton(page, "settings-example").hover(); - await expect(page.getByRole("tooltip")).toHaveText("Settings"); - await page.mouse.move(0, 0); +export async function expectSettingsHidden(page: Page) { + await expect(page.getByRole("switch", { name: "Show metadata" })).toHaveCount(0); } -/** A manifest `name` titles the row and its controls; the id stays visible beneath it. */ +/** A manifest `name` titles the row and its switch, and opens the plugin's page. */ export async function expectNamedPluginRow(page: Page) { - const row = page.getByTestId(`plugin-row-${TABBED_PLUGIN_ID}`).filter({ visible: true }); + const row = pluginRow(page, TABBED_PLUGIN_ID); await expect(row.getByText(TABBED_PLUGIN_NAME, { exact: true })).toBeVisible(); - await expect(row.getByText(TABBED_PLUGIN_ID, { exact: true })).toBeVisible(); await expect( page.getByRole("switch", { name: `${TABBED_PLUGIN_NAME}: Disable`, exact: true }), ).toBeVisible(); - await expect( - page.getByRole("button", { name: `Actions for ${TABBED_PLUGIN_NAME}`, exact: true }), - ).toBeVisible(); + await expect(row).toHaveAccessibleName(TABBED_PLUGIN_NAME); } +/** The page names the plugin by its manifest name, with the ID beneath it. */ export async function openTabbedSettings(page: Page) { - await settingsButton(page, TABBED_PLUGIN_ID).click(); + await openPluginPage(page, TABBED_PLUGIN_NAME, TABBED_PLUGIN_ID); + await expect( + page.getByText(TABBED_PLUGIN_ID, { exact: true }).filter({ visible: true }), + ).toBeVisible(); + await expectAppRoute(page, pluginPageRoute(TABBED_PLUGIN_ID)); await expectSettingsTab(page, "General"); // The Advanced icon reads the plugin's translations; the General icon throws and is dropped. await expect(page.getByTestId("advanced-tab-icon")).toBeVisible(); @@ -159,27 +165,25 @@ export async function openTabbedSettings(page: Page) { function settingsTab(page: Page, title: string) { return page.getByTestId("plugin-settings-tabs").getByRole("button", { name: title, exact: true }); } +/** Tabs swap the screen in place on the plugin's page, so Back still returns to Plugins. */ export async function selectSettingsTab(page: Page, title: "General" | "Advanced") { await settingsTab(page, title).click(); await expectSettingsTab(page, title); + await expectAppRoute( + page, + `${pluginPageRoute(TABBED_PLUGIN_ID)}?screenId=${title.toLowerCase()}`, + ); } export async function expectSettingsTab(page: Page, title: "General" | "Advanced") { const other = title === "General" ? "Advanced" : "General"; await expect(settingsTab(page, title)).toHaveAttribute("aria-selected", "true"); await expect(page.getByText(`${title} settings body`, { exact: true })).toBeVisible(); await expect(page.getByText(`${other} settings body`, { exact: true })).toHaveCount(0); - // The header names the plugin by its manifest name; the tab names the screen. - await expectSettingsHeader(page, TABBED_PLUGIN_NAME); - await expectAppRoute( - page, - `${buildSettingsHostSectionRoute(getServerId(), "plugins")}/${TABBED_PLUGIN_ID}/${title.toLowerCase()}`, - ); + await expect(pluginPageName(page)).toHaveText(TABBED_PLUGIN_NAME); } export async function openTabbedSettingsLink(page: Page, title: "General" | "Advanced") { await gotoAppShell(page); - await page.goto( - `${buildSettingsHostSectionRoute(getServerId(), "plugins")}/${TABBED_PLUGIN_ID}/${title.toLowerCase()}`, - ); + await page.goto(`${pluginPageRoute(TABBED_PLUGIN_ID)}/${title.toLowerCase()}`); await expectSettingsTab(page, title); } export async function groupByWorkspace(page: Page) { @@ -235,18 +239,13 @@ export async function discardTitle(page: Page) { } export async function returnAndReopenSettings(page: Page) { await goBackInSettings(page); - await openSettingsFromCog(page); + await expectAppRoute(page, pluginsRoute()); + await openPluginPage(page, "settings-example"); + await expectSettingsExampleScreen(page); } export async function returnToPluginsPage(page: Page) { - await page.getByRole("button", { name: "Back to plugins", exact: true }).click(); - await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "plugins")); - await expect( - page.getByRole("button", { name: "Actions for settings-example", exact: true }), - ).toBeVisible(); -} -async function expectSettingsHeader(page: Page, title: string) { - // Settings keeps the Plugins page mounted beneath, so read the visible title only. - await expect(page.getByText(title, { exact: true }).filter({ visible: true })).toHaveCount(1); + await backToPlugins(page, "settings-example"); + await expectAppRoute(page, pluginsRoute()); } export async function expectSettingsUnavailable(page: Page) { await expect( diff --git a/packages/app/e2e/support/helpers/versioned-host-daemon.ts b/packages/app/e2e/support/helpers/versioned-host-daemon.ts index ee281a322f..0568319508 100644 --- a/packages/app/e2e/support/helpers/versioned-host-daemon.ts +++ b/packages/app/e2e/support/helpers/versioned-host-daemon.ts @@ -62,6 +62,38 @@ export async function startRestartableHostDaemon(version: string): Promise; +} + +/** A host daemon of its own, for tests that need host configuration the worker daemon lacks. */ +export async function startHostDaemon(options: { + version: string; + pluginRegistryUrl?: string; +}): Promise { + const paseoHomeRoot = await mkdtemp(path.join(tmpdir(), "paseo-e2e-host-")); + try { + const daemon = await startVersionedHostDaemon({ + ...options, + port: await getAvailableHostDaemonPort(), + paseoHomeRoot, + }); + return { + serverId: daemon.serverId, + port: daemon.port, + async dispose() { + await daemon.stop(); + await rm(paseoHomeRoot, { recursive: true, force: true }); + }, + }; + } catch (error) { + await rm(paseoHomeRoot, { recursive: true, force: true }); + throw error; + } +} + interface VersionedHostDaemon { serverId: string; port: number; @@ -73,6 +105,7 @@ interface VersionedHostDaemonOptions { version: string; port: number; paseoHomeRoot: string; + pluginRegistryUrl?: string; } // Starts the versioned test daemon on an explicit port with a caller-owned PASEO_HOME. The caller @@ -83,7 +116,12 @@ async function startVersionedHostDaemon( const child = spawnTsx( VERSIONED_DAEMON_ENTRYPOINT, [options.version, String(options.port), options.paseoHomeRoot], - { stdio: ["ignore", "pipe", "pipe", "ipc"] }, + { + stdio: ["ignore", "pipe", "pipe", "ipc"], + env: options.pluginRegistryUrl + ? { ...process.env, PASEO_PLUGIN_REGISTRY: options.pluginRegistryUrl } + : process.env, + }, ); const ready = Promise.withResolvers<{ port: number; serverId: string }>(); let output = ""; diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index 787e0c20e4..c9d9bf4ebb 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -931,7 +931,9 @@ function RootStack() { + + diff --git a/packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx b/packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx new file mode 100644 index 0000000000..01cab4d2d9 --- /dev/null +++ b/packages/app/src/app/settings/hosts/[serverId]/plugin-directory/[owner]/[slug].tsx @@ -0,0 +1,23 @@ +import { useMemo } from "react"; + +import { useLocalSearchParams } from "expo-router"; +import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; +import SettingsScreen from "@/screens/settings-screen"; + +/** A plugin directory listing's page, by its `owner/slug` ID. */ +export default function PluginListingRoute() { + const { serverId, owner, slug } = useLocalSearchParams<{ + serverId: string; + owner: string; + slug: string; + }>(); + const view = useMemo( + () => ({ kind: "pluginListing" as const, serverId, listingId: `${owner}/${slug}` }), + [serverId, owner, slug], + ); + return ( + + + + ); +} diff --git a/packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx b/packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx new file mode 100644 index 0000000000..a99bc5d4d6 --- /dev/null +++ b/packages/app/src/app/settings/hosts/[serverId]/plugins/[pluginId]/index.tsx @@ -0,0 +1,23 @@ +import { useMemo } from "react"; + +import { useLocalSearchParams } from "expo-router"; +import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary"; +import SettingsScreen from "@/screens/settings-screen"; + +/** An installed plugin's page. A settings tab chosen on it arrives as `screenId`. */ +export default function PluginPageRoute() { + const { serverId, pluginId, screenId } = useLocalSearchParams<{ + serverId: string; + pluginId: string; + screenId?: string; + }>(); + const view = useMemo( + () => ({ kind: "plugin" as const, serverId, pluginId, screenId }), + [serverId, pluginId, screenId], + ); + return ( + + + + ); +} diff --git a/packages/app/src/components/markdown/images.ts b/packages/app/src/components/markdown/images.ts index 9a52491125..5df2e18dc4 100644 --- a/packages/app/src/components/markdown/images.ts +++ b/packages/app/src/components/markdown/images.ts @@ -38,18 +38,23 @@ export interface MarkdownImageContext { export function useMarkdownSource( text: string, context: MarkdownImageContext, - links: { commandNames?: ReadonlySet; forgeReferencePattern?: string } = {}, + links: { + commandNames?: ReadonlySet; + forgeReferencePattern?: string; + external?: boolean; + } = {}, ) { const occurrenceKey = useId(); - const { commandNames, forgeReferencePattern } = links; + const { commandNames, forgeReferencePattern, external } = links; const prepared = useMemo( () => prepareMarkdownSource(text, context.workspaceRoot, { supportsSvg: isWeb, commandNames, forgeReferencePattern, + external, }), - [text, context.workspaceRoot, commandNames, forgeReferencePattern], + [text, context.workspaceRoot, commandNames, forgeReferencePattern, external], ); const sources = [...new Set(prepared.images.map((image) => image.source))]; const acquisitions = sources.map((source) => { diff --git a/packages/app/src/components/markdown/renderer.test.ts b/packages/app/src/components/markdown/renderer.test.ts index 6ce7e59ca2..61d3e0e4d4 100644 --- a/packages/app/src/components/markdown/renderer.test.ts +++ b/packages/app/src/components/markdown/renderer.test.ts @@ -1096,3 +1096,30 @@ it.each([false, true])( expect(markdownStyle.codeBlock?.fontSize).toBe(theme.fontSize.code); }, ); + +describe("external Markdown", () => { + const external = (source: string) => prepareMarkdownSource(source, undefined, { external: true }); + + it("recognizes no files, forge references or commands, only https URLs", () => { + const { linkRecognition } = external("Needs Node.js 22 and `~/.dsh/.env`, see #12"); + expect("Needs Node.js 22, see #12".match(linkRecognition.text)).toBeNull(); + expect(linkRecognition.inlineCode.test("~/.dsh/.env")).toBe(false); + expect("Docs at https://example.com/a.".match(linkRecognition.text)).toEqual([ + "https://example.com/a", + ]); + }); + + it("keeps https links and leaves any other destination as its label", () => { + expect( + external( + "[Guide](docs/guide.md), [site](https://example.com), [mail](mailto:a@b.c), [ref][r]\n\n[r]: ./x", + ).render(), + ).toBe("Guide, [site](https://example.com), mail, ref\n\n[r]: ./x"); + }); + + it("shows a relative image as its alt text", () => { + expect(external("![Demo](media/demo.png) ![Shot](https://x/a.png)").render()).toBe( + "Demo ![Shot](https://x/a.png)", + ); + }); +}); diff --git a/packages/app/src/components/markdown/renderer.tsx b/packages/app/src/components/markdown/renderer.tsx index 19d3134eec..1f9756e9b8 100644 --- a/packages/app/src/components/markdown/renderer.tsx +++ b/packages/app/src/components/markdown/renderer.tsx @@ -8,6 +8,7 @@ import { import { useStableEvent } from "@/hooks/use-stable-event"; import { matchCommandLink, useAgentCommandHints, type CommandHints } from "@/agent-commands"; import { useForgeShorthand } from "@/git/forge-shorthand"; +import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview"; import { openExternalUrl } from "@/utils/open-external-url"; import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox"; import type { Theme } from "@/styles/theme"; @@ -24,6 +25,8 @@ import { MermaidFence, MermaidStreamingContext, splitMermaidFences } from "./fen const ThemedMarkdown = withUnistyles(EnrichedMarkdownText); const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true }; +// A README is written for its forge, where the lines of a paragraph join into one. +const EXTERNAL_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false }; // Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it. const markdownStyle = @@ -52,6 +55,12 @@ export interface MarkdownRendererProps extends MarkdownImageContext { streaming?: boolean; onLinkPress?: (url: string) => unknown; agentCommands?: boolean; + /** + * Author-controlled Markdown from outside this host, such as a plugin README: only its https + * links and images work, nothing is read as a file, forge reference or command, and the lines of + * a paragraph join as they do on its forge. + */ + external?: boolean; } /** All Markdown surfaces share the same engine and source adaptation. */ @@ -86,12 +95,14 @@ const MarkdownPart = memo(function MarkdownPart({ streaming = false, onLinkPress, agentCommands: _agentCommands, + external = false, commandHints = null, ...imageContext }: MarkdownRendererProps & { commandHints?: CommandHints | null }) { const environment = useAssistantFileLinkEnvironment(); const actions = useAssistantFileLinkActions(); - const forgeShorthand = useForgeShorthand(); + const workspaceForgeShorthand = useForgeShorthand(); + const forgeShorthand = external ? null : workspaceForgeShorthand; const client = imageContext.client ?? (environment.client?.readFile @@ -105,10 +116,20 @@ const MarkdownPart = memo(function MarkdownPart({ ...imageContext, client, }, - { commandNames: commandHints?.names, forgeReferencePattern: forgeShorthand?.pattern }, + { + commandNames: commandHints?.names, + forgeReferencePattern: forgeShorthand?.pattern, + external, + }, ); const [image, setImage] = useState(null); const pressLink = useStableEvent(({ url, sourceType }: LinkPressEvent) => { + if (external) { + // The parser still autolinks bare http, www and email text; only https links open. + const safe = pluginOverviewUrl(url); + if (safe) void openExternalUrl(safe); + return; + } const command = commandHints && matchCommandLink(url, sourceType, commandHints.names); if (command) { commandHints.insert(command); @@ -145,7 +166,7 @@ const MarkdownPart = memo(function MarkdownPart({ uniProps={pickMarkdownStyle(compact, muted)} flavor="github" selectable={selectable} - md4cFlags={MD4C_FLAGS} + md4cFlags={external ? EXTERNAL_MD4C_FLAGS : MD4C_FLAGS} linkRecognition={linkRecognition} enableTaskListItemToggle={false} enableLinkPreview={false} diff --git a/packages/app/src/components/markdown/source.ts b/packages/app/src/components/markdown/source.ts index 8b15b8ff98..ae3cdcba46 100644 --- a/packages/app/src/components/markdown/source.ts +++ b/packages/app/src/components/markdown/source.ts @@ -1,3 +1,4 @@ +import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview"; import { classifyAssistantFileLink } from "@/assistant-file-links"; import { ASSISTANT_FILE_EXTENSIONS } from "@/assistant-file-links/extensions"; import { normalizeMarkdownHtml } from "./html"; @@ -53,6 +54,12 @@ function textPattern(forgeReferencePattern?: string): RegExp { return pattern; } +// External Markdown links only what its author wrote as an https URL. +const EXTERNAL_LINKS = { + text: new RegExp(BARE_URL.replace("https?", "https"), "g"), + inlineCode: /^https:\/\/[^\s<>]+$/, +}; + function linkMetadata(inlineCodePaths: ReadonlySet, forgeReferencePattern?: string) { // The engine accepts regexes on both platforms. Classify complete code spans // first, then pass literal matches rather than maintaining a second path grammar. @@ -139,6 +146,12 @@ export function prepareMarkdownSource( commandNames?: ReadonlySet; /** Regex source for forge references such as `#12`; see `@/git/forge-shorthand`. */ forgeReferencePattern?: string; + /** + * Author-controlled Markdown from outside this host, such as a plugin README. It follows the + * registry's overview contract: only absolute https links and images, and nothing is + * recognized as a file, forge reference or command. + */ + external?: boolean; } = {}, ) { source = normalizeMarkdownHtml(source); @@ -149,10 +162,13 @@ export function prepareMarkdownSource( extensions: [gfmTable()], mdastExtensions: [gfmTableFromMarkdown()], })); - const metadata = linkMetadata( - collectInlineCodePaths(source, workspaceRoot, options.commandNames), - options.forgeReferencePattern, - ); + const external = options.external === true; + const metadata = external + ? { linkRecognition: EXTERNAL_LINKS, linkSource: markdownLinkSource } + : linkMetadata( + collectInlineCodePaths(source, workspaceRoot, options.commandNames), + options.forgeReferencePattern, + ); const edits: { start: number; end: number; text: string }[] = []; if ( !source.includes("![") && @@ -162,7 +178,8 @@ 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("](")) + !(workspaceRoot && source.includes("](")) && + !(external && /\]|<[a-z]+:/i.test(source)) ) { return { images, ...metadata, render: () => source }; } @@ -181,9 +198,10 @@ export function prepareMarkdownSource( ) { const target = node.type === "image" ? node : definitions.get(node.identifier); if ( - target && - options.supportsSvg === false && - /(?:\.svg(?:[?#]|$)|^data:image\/svg\+xml)/i.test(target.url) + (external && !pluginOverviewUrl(target?.url)) || + (target && + options.supportsSvg === false && + /(?:\.svg(?:[?#]|$)|^data:image\/svg\+xml)/i.test(target.url)) ) { edits.push({ start, end, text: escapeMarkdownText(node.alt ?? "") }); return; @@ -236,6 +254,21 @@ export function prepareMarkdownSource( if (lineEnd < end) split(lineEnd); } } + // An external link to anything but an https URL keeps its label and loses the brackets and + // destination around it, so edits inside the label still apply. + function dropUnsafeDestination(node: Nodes, start: number, end: number) { + if (node.type !== "link" && node.type !== "linkReference") return; + const target = node.type === "link" ? node : definitions.get(node.identifier); + if (pluginOverviewUrl(target?.url)) return; + const labelStart = node.children[0]?.position?.start.offset; + const labelEnd = node.children.at(-1)?.position?.end.offset; + if (labelStart === undefined || labelEnd === undefined) { + edits.push({ start, end, text: "" }); + return; + } + edits.push({ start, end: labelStart, text: "" }); + edits.push({ start: labelEnd, end, text: "" }); + } function visit(node: Nodes, previous?: Nodes) { const position = node.position; if (position?.start.offset !== undefined && position.end.offset !== undefined) { @@ -255,6 +288,7 @@ export function prepareMarkdownSource( const boundary = lineStart - newline.length; edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` }); } + if (external) dropUnsafeDestination(node, start, end); if (node.type === "link") { const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot); if (title !== null) diff --git a/packages/app/src/components/page-layout/index.tsx b/packages/app/src/components/page-layout/index.tsx index 44280ec3e8..cf70d5c31d 100644 --- a/packages/app/src/components/page-layout/index.tsx +++ b/packages/app/src/components/page-layout/index.tsx @@ -19,6 +19,8 @@ interface PageLayoutProps { titleTestID?: string; /** Controls for the whole page: right of the title on desktop, in the back header on compact. */ actions?: ReactNode; + /** `wide` for pages that lay content out in a grid, such as a gallery. Defaults to a reading column. */ + width?: "default" | "wide"; children: ReactNode; } @@ -33,6 +35,7 @@ export function PageLayout({ testID, titleTestID, actions, + width = "default", children, }: PageLayoutProps) { const isCompact = useIsCompactFormFactor(); @@ -54,7 +57,7 @@ export function PageLayout({ contentContainerStyle={scrollContentStyle} testID={testID} > - + {showTitle ? ( @@ -85,6 +88,13 @@ const styles = StyleSheet.create((theme) => ({ maxWidth: 720, alignSelf: "center", }, + contentWide: { + padding: theme.spacing[4], + paddingTop: theme.spacing[6], + width: "100%", + maxWidth: 1080, + alignSelf: "center", + }, titleRow: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 3cc5de9da3..f7452c2fc3 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1,3 +1,5 @@ +import { pluginGallery } from "./plugin-gallery"; + export const en = { pluginCombobox: { searching: "Searching…", @@ -2421,6 +2423,7 @@ export const en = { host: "Overview", }, plugins: { + gallery: pluginGallery.en, title: "Plugins", screens: { open: "Open", @@ -2458,21 +2461,22 @@ export const en = { enabling: "Enabling…", disable: "Disable", disabling: "Disabling…", - remove: "Remove", - removing: "Removing…", + remove: "Uninstall", + removing: "Uninstalling…", }, feedback: { installed: "Installed {{name}}", reload: "Reloaded {{name}}", enable: "Enabled {{name}}", disable: "Disabled {{name}}", - remove: "Removed {{name}}", + remove: "Uninstalled {{name}}", kept: "Kept {{name}}", globalEnabled: "Plugins enabled", globalDisabled: "Plugins disabled", }, - removeConfirmTitle: "Remove {{name}}?", - removeConfirmMessage: "This removes the configuration. The source directory is not deleted.", + removeConfirmTitle: "Uninstall {{name}}?", + removeConfirmMessage: "Its download and settings on this host are deleted.", + removeConfirmLocalMessage: "Its settings are deleted. Its folder stays on disk.", states: { offlineTitle: "Plugin host is offline", offlineDescription: "Reconnect to this host to manage its plugins.", diff --git a/packages/app/src/i18n/resources/plugin-gallery.ts b/packages/app/src/i18n/resources/plugin-gallery.ts new file mode 100644 index 0000000000..959f1c4077 --- /dev/null +++ b/packages/app/src/i18n/resources/plugin-gallery.ts @@ -0,0 +1,559 @@ +/** Settings → Plugins: the installed list, the directory and a plugin's page. */ +export const pluginGallery = { + en: { + tabs: { installed: "Installed", installedCount: "Installed · {{count}}", browse: "Browse" }, + search: { installed: "Search installed", browse: "Search plugins", clear: "Clear search" }, + filters: { + category: "Category", + allCategories: "All categories", + sort: "Sort", + popular: "Most installed", + recent: "Recently updated", + name: "Name", + }, + sections: { + updates: "Updates", + installed: "Installed", + featured: "Featured", + all: "All plugins", + overview: "Overview", + details: "Details", + }, + installs: "{{installs}} installs", + installs_one: "{{installs}} install", + menu: "More plugin actions", + actions: { + install: "Install", + installing: "Installing…", + installed: "Installed", + retry: "Retry", + update: "Update", + updating: "Updating…", + updateAll: "Update all", + turnOn: "Turn on", + turnOnAll: "Turn on plugins", + turnOff: "Turn off plugins", + installFromSource: "Install from source", + submit: "Submit a plugin", + repository: "Repository", + showMore: "Show more", + browse: "Browse plugins", + }, + off: { title: "Plugins are off on {{host}}" }, + empty: { noMatches: "No plugins match" }, + directory: { + errorTitle: "Unable to load the plugin directory", + update: "Update this host to browse plugins", + }, + install: { + title: "Install {{name}}?", + sourceTitle: "Install from source", + author: "Author", + source: "Source", + version: "Version", + warningTitle: "Runs with your access on {{host}}", + warningDescription: "Plugins are not sandboxed. Install only code you trust.", + turnsOn: "Plugins are not sandboxed. Installing also turns plugins on.", + }, + update: { updated: "{{name}} updated", updatedMany: "{{count}} plugins updated" }, + details: { license: "License", updated: "Updated", openImage: "Open image" }, + missing: "This plugin is not installed or listed", + }, + ar: { + tabs: { installed: "المثبّتة", installedCount: "المثبّتة · {{count}}", browse: "تصفّح" }, + search: { installed: "ابحث في المثبّتة", browse: "ابحث عن إضافات", clear: "مسح البحث" }, + filters: { + category: "الفئة", + allCategories: "كل الفئات", + sort: "الترتيب", + popular: "الأكثر تثبيتًا", + recent: "المحدّثة مؤخرًا", + name: "الاسم", + }, + sections: { + updates: "التحديثات", + installed: "المثبّتة", + featured: "مميّزة", + all: "كل الإضافات", + overview: "نظرة عامة", + details: "التفاصيل", + }, + installs: "{{installs}} تثبيت", + installs_one: "{{installs}} تثبيت", + menu: "إجراءات أخرى للإضافات", + actions: { + install: "تثبيت", + installing: "جارٍ التثبيت…", + installed: "مثبّتة", + retry: "إعادة المحاولة", + update: "تحديث", + updating: "جارٍ التحديث…", + updateAll: "تحديث الكل", + turnOn: "تشغيل", + turnOnAll: "تشغيل الإضافات", + turnOff: "إيقاف الإضافات", + installFromSource: "التثبيت من مصدر", + submit: "إرسال إضافة", + repository: "المستودع", + showMore: "عرض المزيد", + browse: "تصفّح الإضافات", + }, + off: { title: "الإضافات متوقفة على {{host}}" }, + empty: { noMatches: "لا توجد إضافات مطابقة" }, + directory: { + errorTitle: "تعذّر تحميل دليل الإضافات", + update: "حدّث هذا المضيف لتصفّح الإضافات", + }, + install: { + title: "تثبيت {{name}}؟", + sourceTitle: "التثبيت من مصدر", + author: "المؤلف", + source: "المصدر", + version: "الإصدار", + warningTitle: "تعمل بصلاحياتك على {{host}}", + warningDescription: "الإضافات غير معزولة. ثبّت فقط التعليمات البرمجية التي تثق بها.", + turnsOn: "الإضافات غير معزولة. يؤدي التثبيت أيضًا إلى تشغيل الإضافات.", + }, + update: { updated: "تم تحديث {{name}}", updatedMany: "تم تحديث {{count}} إضافات" }, + details: { license: "الترخيص", updated: "آخر تحديث", openImage: "فتح الصورة" }, + missing: "هذه الإضافة غير مثبّتة وغير مدرجة", + }, + es: { + tabs: { installed: "Instalados", installedCount: "Instalados · {{count}}", browse: "Explorar" }, + search: { installed: "Buscar instalados", browse: "Buscar plugins", clear: "Borrar búsqueda" }, + filters: { + category: "Categoría", + allCategories: "Todas las categorías", + sort: "Orden", + popular: "Más instalados", + recent: "Actualizados recientemente", + name: "Nombre", + }, + sections: { + updates: "Actualizaciones", + installed: "Instalados", + featured: "Destacados", + all: "Todos los plugins", + overview: "Descripción general", + details: "Detalles", + }, + installs: "{{installs}} instalaciones", + installs_one: "{{installs}} instalación", + menu: "Más acciones de plugins", + actions: { + install: "Instalar", + installing: "Instalando…", + installed: "Instalado", + retry: "Reintentar", + update: "Actualizar", + updating: "Actualizando…", + updateAll: "Actualizar todo", + turnOn: "Activar", + turnOnAll: "Activar plugins", + turnOff: "Desactivar plugins", + installFromSource: "Instalar desde una fuente", + submit: "Enviar un plugin", + repository: "Repositorio", + showMore: "Mostrar más", + browse: "Explorar plugins", + }, + off: { title: "Los plugins están desactivados en {{host}}" }, + empty: { noMatches: "Ningún plugin coincide" }, + directory: { + errorTitle: "No se pudo cargar el directorio de plugins", + update: "Actualiza este host para explorar plugins", + }, + install: { + title: "¿Instalar {{name}}?", + sourceTitle: "Instalar desde una fuente", + author: "Autor", + source: "Fuente", + version: "Versión", + warningTitle: "Se ejecuta con tu acceso en {{host}}", + warningDescription: "Los plugins no están aislados. Instala solo código de confianza.", + turnsOn: "Los plugins no están aislados. Instalar también activa los plugins.", + }, + update: { updated: "{{name}} actualizado", updatedMany: "{{count}} plugins actualizados" }, + details: { license: "Licencia", updated: "Actualizado", openImage: "Abrir imagen" }, + missing: "Este plugin no está instalado ni publicado", + }, + fr: { + tabs: { installed: "Installés", installedCount: "Installés · {{count}}", browse: "Parcourir" }, + search: { + installed: "Rechercher dans les installés", + browse: "Rechercher des plugins", + clear: "Effacer la recherche", + }, + filters: { + category: "Catégorie", + allCategories: "Toutes les catégories", + sort: "Tri", + popular: "Les plus installés", + recent: "Mis à jour récemment", + name: "Nom", + }, + sections: { + updates: "Mises à jour", + installed: "Installés", + featured: "À la une", + all: "Tous les plugins", + overview: "Présentation", + details: "Détails", + }, + installs: "{{installs}} installations", + installs_one: "{{installs}} installation", + menu: "Autres actions sur les plugins", + actions: { + install: "Installer", + installing: "Installation…", + installed: "Installé", + retry: "Réessayer", + update: "Mettre à jour", + updating: "Mise à jour…", + updateAll: "Tout mettre à jour", + turnOn: "Activer", + turnOnAll: "Activer les plugins", + turnOff: "Désactiver les plugins", + installFromSource: "Installer depuis une source", + submit: "Proposer un plugin", + repository: "Dépôt", + showMore: "Afficher plus", + browse: "Parcourir les plugins", + }, + off: { title: "Les plugins sont désactivés sur {{host}}" }, + empty: { noMatches: "Aucun plugin ne correspond" }, + directory: { + errorTitle: "Impossible de charger l’annuaire des plugins", + update: "Mettez à jour cet hôte pour parcourir les plugins", + }, + install: { + title: "Installer {{name}} ?", + sourceTitle: "Installer depuis une source", + author: "Auteur", + source: "Source", + version: "Version", + warningTitle: "S’exécute avec vos accès sur {{host}}", + warningDescription: "Les plugins ne sont pas isolés. N’installez que du code de confiance.", + turnsOn: "Les plugins ne sont pas isolés. L’installation active aussi les plugins.", + }, + update: { updated: "{{name}} mis à jour", updatedMany: "{{count}} plugins mis à jour" }, + details: { license: "Licence", updated: "Mis à jour", openImage: "Ouvrir l’image" }, + missing: "Ce plugin n’est ni installé ni publié", + }, + ja: { + tabs: { + installed: "インストール済み", + installedCount: "インストール済み · {{count}}", + browse: "見つける", + }, + search: { + installed: "インストール済みを検索", + browse: "プラグインを検索", + clear: "検索をクリア", + }, + filters: { + category: "カテゴリ", + allCategories: "すべてのカテゴリ", + sort: "並び順", + popular: "インストール数順", + recent: "最近の更新順", + name: "名前順", + }, + sections: { + updates: "アップデート", + installed: "インストール済み", + featured: "おすすめ", + all: "すべてのプラグイン", + overview: "概要", + details: "詳細", + }, + installs: "{{installs}} 件のインストール", + installs_one: "{{installs}} 件のインストール", + menu: "その他のプラグイン操作", + actions: { + install: "インストール", + installing: "インストール中…", + installed: "インストール済み", + retry: "再試行", + update: "アップデート", + updating: "アップデート中…", + updateAll: "すべてアップデート", + turnOn: "オンにする", + turnOnAll: "プラグインをオンにする", + turnOff: "プラグインをオフにする", + installFromSource: "ソースからインストール", + submit: "プラグインを申請", + repository: "リポジトリ", + showMore: "さらに表示", + browse: "プラグインを見つける", + }, + off: { title: "{{host}} ではプラグインがオフです" }, + empty: { noMatches: "一致するプラグインはありません" }, + directory: { + errorTitle: "プラグインディレクトリを読み込めません", + update: "プラグインを探すにはこのホストをアップデートしてください", + }, + install: { + title: "{{name}} をインストールしますか?", + sourceTitle: "ソースからインストール", + author: "作者", + source: "ソース", + version: "バージョン", + warningTitle: "{{host}} であなたの権限で動作します", + warningDescription: + "プラグインはサンドボックス化されていません。信頼できるコードのみインストールしてください。", + turnsOn: + "プラグインはサンドボックス化されていません。インストールするとプラグインもオンになります。", + }, + update: { + updated: "{{name}} をアップデートしました", + updatedMany: "{{count}} 個のプラグインをアップデートしました", + }, + details: { license: "ライセンス", updated: "更新日", openImage: "画像を開く" }, + missing: "このプラグインはインストールも公開もされていません", + }, + ko: { + tabs: { installed: "설치됨", installedCount: "설치됨 · {{count}}", browse: "찾아보기" }, + search: { installed: "설치된 항목 검색", browse: "플러그인 검색", clear: "검색 지우기" }, + filters: { + category: "카테고리", + allCategories: "모든 카테고리", + sort: "정렬", + popular: "설치 많은 순", + recent: "최근 업데이트 순", + name: "이름순", + }, + sections: { + updates: "업데이트", + installed: "설치됨", + featured: "추천", + all: "모든 플러그인", + overview: "개요", + details: "세부 정보", + }, + installs: "{{installs}}회 설치", + installs_one: "{{installs}}회 설치", + menu: "기타 플러그인 작업", + actions: { + install: "설치", + installing: "설치 중…", + installed: "설치됨", + retry: "다시 시도", + update: "업데이트", + updating: "업데이트 중…", + updateAll: "모두 업데이트", + turnOn: "켜기", + turnOnAll: "플러그인 켜기", + turnOff: "플러그인 끄기", + installFromSource: "소스에서 설치", + submit: "플러그인 제출", + repository: "저장소", + showMore: "더 보기", + browse: "플러그인 찾아보기", + }, + off: { title: "{{host}}에서 플러그인이 꺼져 있습니다" }, + empty: { noMatches: "일치하는 플러그인이 없습니다" }, + directory: { + errorTitle: "플러그인 디렉터리를 로드할 수 없습니다", + update: "플러그인을 찾아보려면 이 호스트를 업데이트하세요", + }, + install: { + title: "{{name}}을(를) 설치할까요?", + sourceTitle: "소스에서 설치", + author: "작성자", + source: "소스", + version: "버전", + warningTitle: "{{host}}에서 사용자 권한으로 실행됩니다", + warningDescription: "플러그인은 격리되지 않습니다. 신뢰하는 코드만 설치하세요.", + turnsOn: "플러그인은 격리되지 않습니다. 설치하면 플러그인도 켜집니다.", + }, + update: { updated: "{{name}} 업데이트됨", updatedMany: "플러그인 {{count}}개 업데이트됨" }, + details: { license: "라이선스", updated: "업데이트", openImage: "이미지 열기" }, + missing: "이 플러그인은 설치되지 않았고 등록되어 있지도 않습니다", + }, + "pt-BR": { + tabs: { installed: "Instalados", installedCount: "Instalados · {{count}}", browse: "Explorar" }, + search: { installed: "Buscar instalados", browse: "Buscar plugins", clear: "Limpar busca" }, + filters: { + category: "Categoria", + allCategories: "Todas as categorias", + sort: "Ordem", + popular: "Mais instalados", + recent: "Atualizados recentemente", + name: "Nome", + }, + sections: { + updates: "Atualizações", + installed: "Instalados", + featured: "Destaques", + all: "Todos os plugins", + overview: "Visão geral", + details: "Detalhes", + }, + installs: "{{installs}} instalações", + installs_one: "{{installs}} instalação", + menu: "Mais ações de plugins", + actions: { + install: "Instalar", + installing: "Instalando…", + installed: "Instalado", + retry: "Tentar novamente", + update: "Atualizar", + updating: "Atualizando…", + updateAll: "Atualizar tudo", + turnOn: "Ativar", + turnOnAll: "Ativar plugins", + turnOff: "Desativar plugins", + installFromSource: "Instalar de uma fonte", + submit: "Enviar um plugin", + repository: "Repositório", + showMore: "Mostrar mais", + browse: "Explorar plugins", + }, + off: { title: "Os plugins estão desativados em {{host}}" }, + empty: { noMatches: "Nenhum plugin corresponde" }, + directory: { + errorTitle: "Não foi possível carregar o diretório de plugins", + update: "Atualize este host para explorar plugins", + }, + install: { + title: "Instalar {{name}}?", + sourceTitle: "Instalar de uma fonte", + author: "Autor", + source: "Fonte", + version: "Versão", + warningTitle: "Roda com o seu acesso em {{host}}", + warningDescription: "Plugins não são isolados. Instale apenas código confiável.", + turnsOn: "Plugins não são isolados. Instalar também ativa os plugins.", + }, + update: { updated: "{{name}} atualizado", updatedMany: "{{count}} plugins atualizados" }, + details: { license: "Licença", updated: "Atualizado", openImage: "Abrir imagem" }, + missing: "Este plugin não está instalado nem publicado", + }, + ru: { + tabs: { + installed: "Установленные", + installedCount: "Установленные · {{count}}", + browse: "Обзор", + }, + search: { + installed: "Поиск среди установленных", + browse: "Поиск плагинов", + clear: "Очистить поиск", + }, + filters: { + category: "Категория", + allCategories: "Все категории", + sort: "Сортировка", + popular: "По установкам", + recent: "Недавно обновлённые", + name: "По названию", + }, + sections: { + updates: "Обновления", + installed: "Установленные", + featured: "Рекомендуемые", + all: "Все плагины", + overview: "Обзор", + details: "Подробности", + }, + installs: "Установок: {{installs}}", + installs_one: "Установок: {{installs}}", + menu: "Другие действия с плагинами", + actions: { + install: "Установить", + installing: "Установка…", + installed: "Установлен", + retry: "Повторить", + update: "Обновить", + updating: "Обновление…", + updateAll: "Обновить все", + turnOn: "Включить", + turnOnAll: "Включить плагины", + turnOff: "Выключить плагины", + installFromSource: "Установить из источника", + submit: "Предложить плагин", + repository: "Репозиторий", + showMore: "Показать ещё", + browse: "Обзор плагинов", + }, + off: { title: "Плагины выключены на {{host}}" }, + empty: { noMatches: "Нет подходящих плагинов" }, + directory: { + errorTitle: "Не удалось загрузить каталог плагинов", + update: "Обновите этот хост, чтобы просматривать плагины", + }, + install: { + title: "Установить {{name}}?", + sourceTitle: "Установить из источника", + author: "Автор", + source: "Источник", + version: "Версия", + warningTitle: "Работает с вашим доступом на {{host}}", + warningDescription: "Плагины не изолированы. Устанавливайте только код, которому доверяете.", + turnsOn: "Плагины не изолированы. Установка также включит плагины.", + }, + update: { updated: "{{name}} обновлён", updatedMany: "Обновлено плагинов: {{count}}" }, + details: { license: "Лицензия", updated: "Обновлён", openImage: "Открыть изображение" }, + missing: "Этот плагин не установлен и не опубликован", + }, + "zh-CN": { + tabs: { installed: "已安装", installedCount: "已安装 · {{count}}", browse: "浏览" }, + search: { installed: "搜索已安装", browse: "搜索插件", clear: "清除搜索" }, + filters: { + category: "分类", + allCategories: "全部分类", + sort: "排序", + popular: "安装最多", + recent: "最近更新", + name: "名称", + }, + sections: { + updates: "更新", + installed: "已安装", + featured: "精选", + all: "全部插件", + overview: "概览", + details: "详情", + }, + installs: "{{installs}} 次安装", + installs_one: "{{installs}} 次安装", + menu: "更多插件操作", + actions: { + install: "安装", + installing: "正在安装…", + installed: "已安装", + retry: "重试", + update: "更新", + updating: "正在更新…", + updateAll: "全部更新", + turnOn: "开启", + turnOnAll: "开启插件", + turnOff: "关闭插件", + installFromSource: "从来源安装", + submit: "提交插件", + repository: "仓库", + showMore: "显示更多", + browse: "浏览插件", + }, + off: { title: "{{host}} 上的插件已关闭" }, + empty: { noMatches: "没有匹配的插件" }, + directory: { + errorTitle: "无法加载插件目录", + update: "请更新此主机以浏览插件", + }, + install: { + title: "安装 {{name}}?", + sourceTitle: "从来源安装", + author: "作者", + source: "来源", + version: "版本", + warningTitle: "以你在 {{host}} 上的权限运行", + warningDescription: "插件没有沙箱隔离。只安装你信任的代码。", + turnsOn: "插件没有沙箱隔离。安装后也会开启插件。", + }, + update: { updated: "已更新 {{name}}", updatedMany: "已更新 {{count}} 个插件" }, + details: { license: "许可证", updated: "更新于", openImage: "打开图片" }, + missing: "此插件既未安装也未上架", + }, +} as const; diff --git a/packages/app/src/i18n/resources/plugin-settings.ts b/packages/app/src/i18n/resources/plugin-settings.ts index a5d829bff1..9069063137 100644 --- a/packages/app/src/i18n/resources/plugin-settings.ts +++ b/packages/app/src/i18n/resources/plugin-settings.ts @@ -1,3 +1,5 @@ +import { pluginGallery } from "./plugin-gallery"; + const shared = { logs: { action: "Logs", @@ -13,6 +15,7 @@ const shared = { export const pluginSettings = { ar: { ...shared, + gallery: pluginGallery.ar, screens: { open: "فتح", offline: "اتصل بهذا المضيف لفتح إعدادات الإضافة.", @@ -41,21 +44,22 @@ export const pluginSettings = { enabling: "جارٍ التفعيل…", disable: "تعطيل", disabling: "جارٍ التعطيل…", - remove: "إزالة", - removing: "جارٍ الإزالة…", + remove: "إلغاء التثبيت", + removing: "جارٍ إلغاء التثبيت…", }, feedback: { installed: "تم تثبيت {{name}}", reload: "تمت إعادة تحميل {{name}}", enable: "تم تفعيل {{name}}", disable: "تم تعطيل {{name}}", - remove: "تمت إزالة {{name}}", + remove: "تم إلغاء تثبيت {{name}}", kept: "تم الإبقاء على {{name}}", globalEnabled: "تم تفعيل الإضافات", globalDisabled: "تم تعطيل الإضافات", }, - removeConfirmTitle: "إزالة {{name}}؟", - removeConfirmMessage: "يؤدي هذا إلى إزالة الإعداد فقط. لن يُحذف مجلد المصدر.", + removeConfirmTitle: "إلغاء تثبيت {{name}}؟", + removeConfirmMessage: "تُحذف نسختها المنزّلة وإعداداتها على هذا المضيف.", + removeConfirmLocalMessage: "تُحذف إعداداتها. يبقى مجلدها على القرص.", states: { offlineTitle: "مضيف الإضافات غير متصل", offlineDescription: "أعد الاتصال بهذا المضيف لإدارة إضافاته.", @@ -69,6 +73,7 @@ export const pluginSettings = { }, es: { ...shared, + gallery: pluginGallery.es, screens: { open: "Abrir", offline: "Conéctate a este host para abrir los ajustes del plugin.", @@ -97,21 +102,22 @@ export const pluginSettings = { enabling: "Activando…", disable: "Desactivar", disabling: "Desactivando…", - remove: "Eliminar", - removing: "Eliminando…", + remove: "Desinstalar", + removing: "Desinstalando…", }, feedback: { installed: "{{name}} instalado", reload: "{{name}} recargado", enable: "{{name}} activado", disable: "{{name}} desactivado", - remove: "{{name}} eliminado", + remove: "{{name}} desinstalado", kept: "Se conservó {{name}}", globalEnabled: "Plugins activados", globalDisabled: "Plugins desactivados", }, - removeConfirmTitle: "¿Eliminar {{name}}?", - removeConfirmMessage: "Esto elimina la configuración. El directorio de origen no se borra.", + removeConfirmTitle: "¿Desinstalar {{name}}?", + removeConfirmMessage: "Se borran su descarga y sus ajustes en este host.", + removeConfirmLocalMessage: "Se borran sus ajustes. Su carpeta se queda en el disco.", states: { offlineTitle: "El host de plugins está sin conexión", offlineDescription: "Vuelve a conectar este host para gestionar sus plugins.", @@ -125,6 +131,7 @@ export const pluginSettings = { }, fr: { ...shared, + gallery: pluginGallery.fr, screens: { open: "Ouvrir", offline: "Connectez-vous à cet hôte pour ouvrir les paramètres du plugin.", @@ -153,21 +160,22 @@ export const pluginSettings = { enabling: "Activation…", disable: "Désactiver", disabling: "Désactivation…", - remove: "Supprimer", - removing: "Suppression…", + remove: "Désinstaller", + removing: "Désinstallation…", }, feedback: { installed: "{{name}} installé", reload: "{{name}} rechargé", enable: "{{name}} activé", disable: "{{name}} désactivé", - remove: "{{name}} supprimé", + remove: "{{name}} désinstallé", kept: "{{name}} conservé", globalEnabled: "Plugins activés", globalDisabled: "Plugins désactivés", }, - removeConfirmTitle: "Supprimer {{name}} ?", - removeConfirmMessage: "La configuration sera supprimée. Le dossier source ne sera pas effacé.", + removeConfirmTitle: "Désinstaller {{name}} ?", + removeConfirmMessage: "Son téléchargement et ses réglages sur cet hôte sont supprimés.", + removeConfirmLocalMessage: "Ses réglages sont supprimés. Son dossier reste sur le disque.", states: { offlineTitle: "L’hôte des plugins est hors ligne", offlineDescription: "Reconnectez cet hôte pour gérer ses plugins.", @@ -181,6 +189,7 @@ export const pluginSettings = { }, ja: { ...shared, + gallery: pluginGallery.ja, screens: { open: "開く", offline: "このホストに接続してプラグイン設定を開いてください。", @@ -209,21 +218,22 @@ export const pluginSettings = { enabling: "有効化中…", disable: "無効化", disabling: "無効化中…", - remove: "削除", - removing: "削除中…", + remove: "アンインストール", + removing: "アンインストール中…", }, feedback: { installed: "{{name}} をインストールしました", reload: "{{name}} を再読み込みしました", enable: "{{name}} を有効にしました", disable: "{{name}} を無効にしました", - remove: "{{name}} を削除しました", + remove: "{{name}} をアンインストールしました", kept: "{{name}} を保持しました", globalEnabled: "プラグインを有効にしました", globalDisabled: "プラグインを無効にしました", }, - removeConfirmTitle: "{{name}} を削除しますか?", - removeConfirmMessage: "設定のみを削除します。ソースディレクトリは削除されません。", + removeConfirmTitle: "{{name}} をアンインストールしますか?", + removeConfirmMessage: "このホスト上のダウンロードと設定が削除されます。", + removeConfirmLocalMessage: "設定が削除されます。フォルダはディスクに残ります。", states: { offlineTitle: "プラグインホストはオフラインです", offlineDescription: "プラグインを管理するにはホストに再接続してください。", @@ -237,6 +247,7 @@ export const pluginSettings = { }, ko: { ...shared, + gallery: pluginGallery.ko, screens: { open: "열기", offline: "플러그인 설정을 열려면 이 호스트에 연결하세요.", @@ -278,7 +289,8 @@ export const pluginSettings = { globalDisabled: "플러그인 비활성화됨", }, removeConfirmTitle: "{{name}}을(를) 제거할까요?", - removeConfirmMessage: "설정만 제거합니다. 소스 디렉터리는 삭제되지 않습니다.", + removeConfirmMessage: "이 호스트의 다운로드와 설정이 삭제됩니다.", + removeConfirmLocalMessage: "설정이 삭제됩니다. 폴더는 디스크에 남습니다.", states: { offlineTitle: "플러그인 호스트가 오프라인입니다", offlineDescription: "플러그인을 관리하려면 호스트에 다시 연결하세요.", @@ -292,6 +304,7 @@ export const pluginSettings = { }, "pt-BR": { ...shared, + gallery: pluginGallery["pt-BR"], screens: { open: "Abrir", offline: "Conecte-se a este host para abrir as configurações do plugin.", @@ -320,21 +333,22 @@ export const pluginSettings = { enabling: "Ativando…", disable: "Desativar", disabling: "Desativando…", - remove: "Remover", - removing: "Removendo…", + remove: "Desinstalar", + removing: "Desinstalando…", }, feedback: { installed: "{{name}} instalado", reload: "{{name}} recarregado", enable: "{{name}} ativado", disable: "{{name}} desativado", - remove: "{{name}} removido", + remove: "{{name}} desinstalado", kept: "{{name}} mantido", globalEnabled: "Plugins ativados", globalDisabled: "Plugins desativados", }, - removeConfirmTitle: "Remover {{name}}?", - removeConfirmMessage: "Isso remove a configuração. O diretório de origem não será excluído.", + removeConfirmTitle: "Desinstalar {{name}}?", + removeConfirmMessage: "O download e as configurações neste host são apagados.", + removeConfirmLocalMessage: "As configurações são apagadas. A pasta continua no disco.", states: { offlineTitle: "O host de plugins está offline", offlineDescription: "Reconecte este host para gerenciar seus plugins.", @@ -348,6 +362,7 @@ export const pluginSettings = { }, ru: { ...shared, + gallery: pluginGallery.ru, screens: { open: "Открыть", offline: "Подключитесь к этому хосту, чтобы открыть настройки плагина.", @@ -390,7 +405,8 @@ export const pluginSettings = { globalDisabled: "Плагины отключены", }, removeConfirmTitle: "Удалить {{name}}?", - removeConfirmMessage: "Конфигурация будет удалена. Исходный каталог останется на месте.", + removeConfirmMessage: "Загруженные файлы и настройки на этом хосте будут удалены.", + removeConfirmLocalMessage: "Настройки будут удалены. Папка останется на диске.", states: { offlineTitle: "Хост плагинов не в сети", offlineDescription: "Подключите хост снова, чтобы управлять плагинами.", @@ -404,6 +420,7 @@ export const pluginSettings = { }, "zh-CN": { ...shared, + gallery: pluginGallery["zh-CN"], screens: { open: "打开", offline: "连接到此主机以打开插件设置。", @@ -431,21 +448,22 @@ export const pluginSettings = { enabling: "正在启用…", disable: "禁用", disabling: "正在禁用…", - remove: "移除", - removing: "正在移除…", + remove: "卸载", + removing: "正在卸载…", }, feedback: { installed: "已安装 {{name}}", reload: "已重新加载 {{name}}", enable: "已启用 {{name}}", disable: "已禁用 {{name}}", - remove: "已移除 {{name}}", + remove: "已卸载 {{name}}", kept: "已保留 {{name}}", globalEnabled: "插件已启用", globalDisabled: "插件已禁用", }, - removeConfirmTitle: "移除 {{name}}?", - removeConfirmMessage: "这会移除配置,但不会删除源目录。", + removeConfirmTitle: "卸载 {{name}}?", + removeConfirmMessage: "将删除此主机上的下载内容和设置。", + removeConfirmLocalMessage: "将删除其设置。文件夹保留在磁盘上。", states: { offlineTitle: "插件主机离线", offlineDescription: "重新连接此主机以管理其插件。", diff --git a/packages/app/src/navigation/settings-navigation.ts b/packages/app/src/navigation/settings-navigation.ts index 889eb093fc..34989d9d21 100644 --- a/packages/app/src/navigation/settings-navigation.ts +++ b/packages/app/src/navigation/settings-navigation.ts @@ -35,7 +35,8 @@ export function openSettingsFromSidebar(input: { } export type SettingsView = - | { kind: "plugin"; serverId: string; pluginId: string; screenId: string } + | { kind: "plugin"; serverId: string; pluginId: string; screenId?: string } + | { kind: "pluginListing"; serverId: string; listingId: string } | { kind: "root" } | { kind: "section"; section: SettingsSectionSlug } | { kind: "host"; serverId: string; section: HostSectionSlug } @@ -61,13 +62,17 @@ export function returnFromSettings(view: SettingsView): void { return; } if (!navigateToLastWorkspace()) { + // Detail pages such as a plugin's page are pushed onto Settings; replacing only the top + // entry would leave the rest of Settings mounted underneath. + if (router.canDismiss()) router.dismissAll(); router.replace(buildOpenProjectRoute()); } return; } let parent: Href = buildSettingsRoute(); - if (view.kind === "plugin") parent = buildSettingsHostSectionRoute(view.serverId, "plugins"); + if (view.kind === "plugin" || view.kind === "pluginListing") + parent = buildSettingsHostSectionRoute(view.serverId, "plugins"); if (view.kind === "project") parent = buildProjectsSettingsRoute(view.serverId); router.dismissTo(parent as Href); } diff --git a/packages/app/src/plugins/gallery/actions.ts b/packages/app/src/plugins/gallery/actions.ts new file mode 100644 index 0000000000..0647d85720 --- /dev/null +++ b/packages/app/src/plugins/gallery/actions.ts @@ -0,0 +1,78 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import { useToast } from "@/contexts/toast-api-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { pluginDisplayName, pluginListQueryKey } from "@/plugins/plugin-list"; +import { confirmDialog } from "@/utils/confirm-dialog"; +import { pluginErrorText } from "./error-text"; +import { dismissFailedOperation } from "./operations"; + +export type PluginAction = "enable" | "disable" | "reload" | "remove"; + +/** + * Turning a plugin on or off, reloading and removing it. Each action writes its result into the + * plugin list, so every row and page showing the plugin agrees. Toggling says nothing; the switch + * already shows the result. + */ +export function usePluginActions(serverId: string) { + const { t } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + const [pending, setPending] = useState<{ pluginId: string; action: PluginAction } | null>(null); + + const replace = useCallback( + (plugin: PluginListItem) => + queryClient.setQueryData(pluginListQueryKey(serverId), (plugins) => + plugins?.map((candidate) => (candidate.id === plugin.id ? plugin : candidate)), + ), + [queryClient, serverId], + ); + + const run = useCallback( + /** Resolves true once the action is done; false when it was cancelled or failed. */ + async (action: PluginAction, plugin: PluginListItem): Promise => { + if (!client) return false; + const name = pluginDisplayName(plugin); + if (action === "remove") { + const confirmed = await confirmDialog({ + title: t("settings.plugins.removeConfirmTitle", { name }), + // A plugin installed from a source has its download deleted; a local folder is kept. + message: plugin.installation + ? t("settings.plugins.removeConfirmMessage") + : t("settings.plugins.removeConfirmLocalMessage"), + confirmLabel: t("settings.plugins.actions.remove"), + destructive: true, + }); + if (!confirmed) return false; + } + setPending({ pluginId: plugin.id, action }); + try { + if (action === "remove") { + await client.removePlugin(plugin.id); + // A failed update belonged to this installation, not to a later one with the same ID. + dismissFailedOperation(serverId, plugin.id); + queryClient.setQueryData(pluginListQueryKey(serverId), (plugins) => + plugins?.filter((candidate) => candidate.id !== plugin.id), + ); + toast.show(t("settings.plugins.feedback.remove", { name }), { variant: "success" }); + } else { + replace(await client[`${action}Plugin`](plugin.id)); + if (action === "reload") + toast.show(t("settings.plugins.feedback.reload", { name }), { variant: "success" }); + } + return true; + } catch (error) { + toast.error(pluginErrorText(error)); + return false; + } finally { + setPending(null); + } + }, + [client, queryClient, replace, serverId, t, toast], + ); + + return useMemo(() => ({ run, pending }), [pending, run]); +} diff --git a/packages/app/src/plugins/gallery/browse-tab.tsx b/packages/app/src/plugins/gallery/browse-tab.tsx new file mode 100644 index 0000000000..a7c8d08d34 --- /dev/null +++ b/packages/app/src/plugins/gallery/browse-tab.tsx @@ -0,0 +1,459 @@ +import { router } from "expo-router"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Image, ScrollView, Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import type { PluginListingIndex, PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { SettingsCard, SettingsSection } from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"; +import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useContainerWidthBelow } from "@/hooks/use-container-width"; +import { settingsStyles } from "@/styles/settings"; +import { usePluginActions } from "./actions"; +import { ListingInstallControl } from "./install-control"; +import { + ALL_CATEGORIES, + categoryLabel, + featuredListings, + filterDirectory, + formatInstallCount, + listingAuthor, + listingAuthorAvatar, + listingImages, + listingText, + type DirectorySort, +} from "./listing"; +import { usePluginOperation } from "./operations"; +import { PluginMeta, PluginRow, PluginTile } from "./plugin-row"; +import { usePluginDirectory } from "./queries"; +import { buildPluginListingRoute } from "./routes"; +import { PluginRowsSkeleton } from "./skeletons"; +import { pluginErrorText } from "./error-text"; + +const SORTS: DirectorySort[] = ["popular", "recent", "name"]; +// Below this width the featured grid has two columns instead of four. +const FEATURED_FOUR_COLUMNS = 760; +const LISTING_PAGE = 50; + +/** "author · 1.1k installs". */ +export function useListingMeta() { + const { t } = useTranslation(); + return useCallback( + (listing: PluginListing) => + listing.installs === undefined + ? listingAuthor(listing) + : `${listingAuthor(listing)} · ${t("settings.plugins.gallery.installs", { + count: listing.installs, + installs: formatInstallCount(listing.installs), + })}`, + [t], + ); +} + +function ListingRow({ + serverId, + listing, + installedPlugin, + uninstalling, + onInstall, + onUninstall, +}: { + serverId: string; + listing: PluginListing; + installedPlugin?: PluginListItem; + uninstalling: boolean; + onInstall(listing: PluginListing): void; + onUninstall(plugin: PluginListItem): void; +}) { + const { i18n } = useTranslation(); + const meta = useListingMeta(); + const operation = usePluginOperation(serverId, listing.id); + const { name, description } = listingText(listing, i18n.language); + const open = useCallback( + () => router.push(buildPluginListingRoute(serverId, listing.id)), + [listing.id, serverId], + ); + return ( + + + + ); +} + +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +function FeaturedCard({ serverId, listing }: { serverId: string; listing: PluginListing }) { + const { i18n } = useTranslation(); + const meta = useListingMeta(); + const { name, description } = listingText(listing, i18n.language); + const image = listingImages(listing)[0]; + const source = useMemo(() => (image ? { uri: image } : null), [image]); + const open = useCallback( + () => router.push(buildPluginListingRoute(serverId, listing.id)), + [listing.id, serverId], + ); + const cardStyle = useCallback( + ({ hovered }: HoverState) => [styles.featured, hovered && styles.featuredHovered], + [], + ); + return ( + + + {source ? : null} + + + + + + {name} + + + + {description} + + + + + ); +} + +/** Every featured listing: a row to swipe on a phone, a grid of four or two columns otherwise. */ +function Featured({ serverId, listings }: { serverId: string; listings: PluginListing[] }) { + const { t } = useTranslation(); + const compact = useIsCompactFormFactor(); + const grid = useContainerWidthBelow(FEATURED_FOUR_COLUMNS, { initialIsBelow: false }); + const cellStyle = grid.isBelow ? styles.cellHalf : styles.cellQuarter; + return ( + + {compact ? ( + + {listings.map((listing) => ( + + + + ))} + + ) : ( + + {listings.map((listing) => ( + + + + ))} + + )} + + ); +} + +function FilterOption({ + option, + selected, + onChange, +}: { + option: { value: Value; label: string }; + selected: boolean; + onChange(value: Value): void; +}) { + const select = useCallback(() => onChange(option.value), [onChange, option.value]); + return ( + + {option.label} + + ); +} + +function FilterMenu({ + label, + value, + options, + onChange, + testID, +}: { + label: string; + value: Value; + options: { value: Value; label: string }[]; + onChange(value: Value): void; + testID: string; +}) { + const selected = options.find((option) => option.value === value)?.label ?? value; + return ( + + + {selected} + + + {options.map((option) => ( + + ))} + + + ); +} + +/** + * The listings in pages: the directory has hundreds, and rendering them all makes switching to + * Browse and typing in search lag. A new query, category or sort starts again at the first page. + */ +function ListingList({ + serverId, + listings, + installed, + onInstall, +}: { + serverId: string; + listings: PluginListing[]; + installed: ReadonlyMap; + onInstall(listing: PluginListing): void; +}) { + const { t } = useTranslation(); + const actions = usePluginActions(serverId); + const uninstall = useCallback( + (plugin: PluginListItem) => void actions.run("remove", plugin), + [actions], + ); + const [limit, setLimit] = useState(LISTING_PAGE); + const showMore = useCallback(() => setLimit((value) => value + LISTING_PAGE), []); + if (!listings.length) + return ( + + + + {t("settings.plugins.gallery.empty.noMatches")} + + + + ); + return ( + <> + + {listings.slice(0, limit).map((listing) => ( + + ))} + + {listings.length > limit ? ( + + + + ) : null} + + ); +} + +function Directory({ + serverId, + index, + installed, + query, + onInstall, +}: { + serverId: string; + index: PluginListingIndex; + installed: ReadonlyMap; + query: string; + onInstall(listing: PluginListing): void; +}) { + const { t, i18n } = useTranslation(); + const [category, setCategory] = useState(ALL_CATEGORIES); + const [sort, setSort] = useState("popular"); + const listings = filterDirectory(index, { query, category, sort }, i18n.language); + const browsing = !query.trim() && category === ALL_CATEGORIES; + const featured = browsing ? featuredListings(index) : []; + const categoryOptions = useMemo( + () => [ + { value: ALL_CATEGORIES, label: t("settings.plugins.gallery.filters.allCategories") }, + ...index.categories.map((entry) => ({ value: entry.slug, label: entry.label })), + ], + [index.categories, t], + ); + const sortOptions = useMemo( + (): { value: DirectorySort; label: string }[] => + SORTS.map((value) => ({ value, label: t(`settings.plugins.gallery.filters.${value}`) })), + [t], + ); + const listTitle = + category === ALL_CATEGORIES + ? t("settings.plugins.gallery.sections.all") + : categoryLabel(index, category); + return ( + <> + + + + label={t("settings.plugins.gallery.filters.sort")} + value={sort} + options={sortOptions} + onChange={setSort} + testID="plugin-sort" + /> + + {featured.length ? : null} + + + + + ); +} + +export function BrowseTab({ + serverId, + installed, + query, + onInstall, +}: { + serverId: string; + /** Installed plugins by the listing they came from. */ + installed: ReadonlyMap; + query: string; + onInstall(listing: PluginListing): void; +}) { + const { t } = useTranslation(); + const directory = usePluginDirectory(serverId); + const retry = useCallback(() => void directory.query.refetch(), [directory.query]); + if (!directory.supported) + return ( + + ); + if (directory.query.isError) + return ( + + + + ); + if (!directory.query.data) return ; + return ( + + ); +} + +const styles = StyleSheet.create((theme) => ({ + filters: { + flexDirection: "row", + flexWrap: "wrap", + gap: theme.spacing[2], + marginBottom: theme.spacing[6], + }, + featuredRow: { flexDirection: "row", gap: theme.spacing[3] }, + // Percent widths and a gap would overflow the row, so each cell carries half the gap on each side + // and the grid pulls out by the same amount to keep the cards on the section's edges. + featuredGrid: { + flexDirection: "row", + flexWrap: "wrap", + marginHorizontal: -theme.spacing[3] / 2, + marginBottom: -theme.spacing[3], + }, + cellQuarter: { + width: "25%", + paddingHorizontal: theme.spacing[3] / 2, + marginBottom: theme.spacing[3], + }, + cellHalf: { + width: "50%", + paddingHorizontal: theme.spacing[3] / 2, + marginBottom: theme.spacing[3], + }, + cellSwipe: { width: 260 }, + featured: { + flexGrow: 1, + backgroundColor: theme.colors.surface1, + borderRadius: theme.borderRadius.lg, + borderWidth: 1, + borderColor: theme.colors.border, + overflow: "hidden", + }, + featuredHovered: { backgroundColor: theme.colors.surface2 }, + featuredPressed: { backgroundColor: theme.colors.surface3 }, + media: { + aspectRatio: 16 / 10, + backgroundColor: theme.colors.surface2, + borderBottomWidth: 1, + borderBottomColor: theme.colors.border, + }, + mediaImage: { width: "100%", height: "100%" }, + featuredBody: { padding: theme.spacing[3], gap: theme.spacing[1] }, + featuredTitle: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + featuredName: { flex: 1, color: theme.colors.foreground, fontSize: theme.fontSize.base }, + featuredDescription: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm }, + empty: { padding: theme.spacing[6], alignItems: "center" }, + more: { alignItems: "center", marginTop: theme.spacing[3] }, +})); diff --git a/packages/app/src/plugins/gallery/error-text.test.ts b/packages/app/src/plugins/gallery/error-text.test.ts new file mode 100644 index 0000000000..04c01d1891 --- /dev/null +++ b/packages/app/src/plugins/gallery/error-text.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { pluginErrorText } from "./error-text"; + +describe("pluginErrorText", () => { + it("shows the daemon's text without the request details an RPC error adds", () => { + const rpcError = Object.assign( + new Error( + "Registry credentials require HTTPS requestType=plugin.registry.list.request code=handler_error", + ), + { userMessage: "Registry credentials require HTTPS" }, + ); + expect(pluginErrorText(rpcError)).toBe("Registry credentials require HTTPS"); + }); + + it("shows any other error's message", () => { + expect(pluginErrorText(new Error("Socket closed"))).toBe("Socket closed"); + expect(pluginErrorText("offline")).toBe("offline"); + }); +}); diff --git a/packages/app/src/plugins/gallery/error-text.ts b/packages/app/src/plugins/gallery/error-text.ts new file mode 100644 index 0000000000..151a071456 --- /dev/null +++ b/packages/app/src/plugins/gallery/error-text.ts @@ -0,0 +1,9 @@ +/** + * What a failed plugin request tells the user. A daemon RPC error keeps the daemon's text in + * `userMessage`; its `message` adds the request type and code for logs. + */ +export function pluginErrorText(error: unknown): string { + if (!(error instanceof Error)) return String(error); + const userMessage: unknown = Reflect.get(error, "userMessage"); + return typeof userMessage === "string" ? userMessage : error.message; +} diff --git a/packages/app/src/plugins/gallery/gallery-page.tsx b/packages/app/src/plugins/gallery/gallery-page.tsx new file mode 100644 index 0000000000..68cebe165e --- /dev/null +++ b/packages/app/src/plugins/gallery/gallery-page.tsx @@ -0,0 +1,157 @@ +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { SearchField } from "@/components/ui/search-field"; +import { SegmentedControl } from "@/components/ui/segmented-control"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { useInstalledPlugins } from "@/plugins/registry"; +import { BrowseTab } from "./browse-tab"; +import { InstallPluginSheet, type InstallTarget } from "./install-sheet"; +import { InstalledTab } from "./installed-tab"; +import { installedByListing } from "./listing"; +import { PluginsOffAlert } from "./plugins-off-alert"; +import { useLivePluginList, usePluginDirectory } from "./queries"; +import { PluginRowsSkeleton } from "./skeletons"; +import { pluginErrorText } from "./error-text"; + +type GalleryTab = "installed" | "browse"; + +/** + * Settings → Plugins: the plugins on this host and the directory to add more, behind one switch. + * Opens on Installed when something is installed, otherwise on Browse. + */ +export function PluginGalleryPage({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const connected = useHostRuntimeIsConnected(serverId); + const supported = useHostFeature(serverId, "pluginManagement"); + useInstalledPlugins(); + const plugins = useLivePluginList(serverId); + const directory = usePluginDirectory(serverId); + const [chosenTab, setChosenTab] = useState(null); + const [query, setQuery] = useState(""); + const [installTarget, setInstallTarget] = useState(null); + const installed = useMemo(() => plugins.data ?? [], [plugins.data]); + // The opening tab is chosen once, so installing the first plugin does not move the user off Browse. + if (chosenTab === null && plugins.data) + setChosenTab(plugins.data.length === 0 ? "browse" : "installed"); + const tab: GalleryTab = chosenTab ?? "installed"; + const byListing = useMemo(() => installedByListing(installed), [installed]); + const listings = useMemo( + () => new Map((directory.query.data?.plugins ?? []).map((listing) => [listing.id, listing])), + [directory.query.data], + ); + const tabs = useMemo( + () => [ + { + value: "installed" as const, + label: plugins.data + ? t("settings.plugins.gallery.tabs.installedCount", { count: plugins.data.length }) + : t("settings.plugins.gallery.tabs.installed"), + testID: "plugin-tab-installed", + }, + { + value: "browse" as const, + label: t("settings.plugins.gallery.tabs.browse"), + testID: "plugin-tab-browse", + }, + ], + [plugins.data, t], + ); + const browse = useCallback(() => setChosenTab("browse"), []); + const install = useCallback( + (listing: PluginListing) => setInstallTarget({ kind: "listing", listing }), + [], + ); + const closeInstall = useCallback(() => setInstallTarget(null), []); + const retry = useCallback(() => void plugins.refetch(), [plugins]); + + if (!connected) + return ( + + ); + if (!supported) + return ; + + let content = ; + if (plugins.isError) { + content = ( + + + + ); + } else if (plugins.data) { + content = + tab === "installed" ? ( + + ) : ( + + ); + } + + return ( + + + + + + + + {tab === "installed" ? : null} + {content} + {installTarget ? ( + + ) : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + toolbar: { + flexDirection: "row", + flexWrap: "wrap", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[6], + }, + // The search box sits at the end of the row, as on the website, and takes the whole row when the + // tabs leave it too little room. + search: { flexGrow: 1, flexBasis: 220, flexDirection: "row", justifyContent: "flex-end" }, +})); diff --git a/packages/app/src/plugins/gallery/index.ts b/packages/app/src/plugins/gallery/index.ts new file mode 100644 index 0000000000..9c78298a41 --- /dev/null +++ b/packages/app/src/plugins/gallery/index.ts @@ -0,0 +1,4 @@ +export { PluginGalleryPage } from "./gallery-page"; +export { PluginGalleryMenu } from "./menus"; +export { PluginPage, type PluginPageSubject } from "./plugin-page"; +export { buildPluginListingRoute, buildPluginPageRoute } from "./routes"; diff --git a/packages/app/src/plugins/gallery/install-control.tsx b/packages/app/src/plugins/gallery/install-control.tsx new file mode 100644 index 0000000000..218bfd9eb2 --- /dev/null +++ b/packages/app/src/plugins/gallery/install-control.tsx @@ -0,0 +1,72 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { Button } from "@/components/ui/button"; +import type { PluginOperation } from "./operations"; + +function useInstallLabel(operation: PluginOperation | undefined): string { + const { t } = useTranslation(); + if (operation?.status === "running") return t("settings.plugins.gallery.actions.installing"); + if (operation?.status === "failed") return t("settings.plugins.gallery.actions.retry"); + return t("settings.plugins.gallery.actions.install"); +} + +/** + * A listing's install state where the user is looking: Install, Installing… while it runs, Retry + * after a failure (the row or page shows why), and Uninstall once it is on the host. Both ask + * before they act. + */ +export function ListingInstallControl({ + listing, + installedPlugin, + operation, + uninstalling = false, + onInstall, + onUninstall, + primary = false, +}: { + listing: PluginListing; + /** The plugin this listing installed on the host, when it is installed. */ + installedPlugin?: PluginListItem; + operation: PluginOperation | undefined; + uninstalling?: boolean; + onInstall(listing: PluginListing): void; + onUninstall?(plugin: PluginListItem): void; + /** The page's one accent action, on the plugin's own page. */ + primary?: boolean; +}) { + const { t } = useTranslation(); + const installLabel = useInstallLabel(operation); + const install = useCallback(() => onInstall(listing), [listing, onInstall]); + const uninstall = useCallback(() => { + if (installedPlugin) onUninstall?.(installedPlugin); + }, [installedPlugin, onUninstall]); + if (installedPlugin) { + const label = uninstalling + ? t("settings.plugins.actions.removing") + : t("settings.plugins.actions.remove"); + return ( + + ); + } + return ( + + ); +} diff --git a/packages/app/src/plugins/gallery/install-sheet.tsx b/packages/app/src/plugins/gallery/install-sheet.tsx new file mode 100644 index 0000000000..e07ec7ee7f --- /dev/null +++ b/packages/app/src/plugins/gallery/install-sheet.tsx @@ -0,0 +1,191 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { SettingsCard, SettingsRow } from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { ExternalLink } from "@/components/ui/external-link"; +import { Field, FormTextInput } from "@/components/ui/form-field"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import { listingAuthor, listingSource, listingText, listingVersion } from "./listing"; +import { dismissFailedOperation, installPlugin, usePluginOperation } from "./operations"; + +const PLUGIN_SOURCE_DOCS_URL = "https://paseo.sh/docs/plugins/reference#plugin-sources"; +const SOURCE_SUBJECT = "source"; + +/** What the sheet installs: a directory listing, or a source the user types. */ +export type InstallTarget = { kind: "listing"; listing: PluginListing } | { kind: "source" }; + +export function useHostLabel(serverId: string): string { + const hosts = useHosts(); + return hosts.find((host) => host.serverId === serverId)?.label ?? serverId; +} + +/** + * Every install is confirmed here: who made the plugin, where its code comes from, and that it runs + * unsandboxed on the host. A listing install closes the sheet and reports on the listing's row; an + * install from source has no row, so the sheet stays open until it finishes. + */ +export function InstallPluginSheet({ + serverId, + target, + onClose, +}: { + serverId: string; + target: InstallTarget; + onClose(): void; +}) { + const { t, i18n } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + const hostLabel = useHostLabel(serverId); + const { config } = useDaemonConfig(serverId); + const pluginsOff = config?.pluginsEnabled !== true; + const [source, setSource] = useState(""); + const sourceRun = usePluginOperation(serverId, target.kind === "source" ? SOURCE_SUBJECT : ""); + const sourceRunning = target.kind === "source" && sourceRun?.status === "running"; + const close = useCallback(() => { + if (target.kind === "source") dismissFailedOperation(serverId, SOURCE_SUBJECT); + onClose(); + }, [onClose, serverId, target.kind]); + const name = + target.kind === "listing" + ? listingText(target.listing, i18n.language).name + : t("settings.plugins.gallery.install.sourceTitle"); + + const onInstalled = useCallback( + (plugin: PluginListItem) => { + toast.show(t("settings.plugins.feedback.installed", { name: pluginDisplayName(plugin) }), { + variant: "success", + }); + }, + [t, toast], + ); + const confirm = useCallback(() => { + if (!client) return; + const request = { client, queryClient, serverId, enablePlugins: pluginsOff, onInstalled }; + if (target.kind === "listing") { + void installPlugin({ ...request, source: target.listing.id, subject: target.listing.id }); + onClose(); + return; + } + void installPlugin({ + ...request, + source: source.trim(), + subject: SOURCE_SUBJECT, + onInstalled: (plugin) => { + onInstalled(plugin); + close(); + }, + }); + }, [client, close, onClose, onInstalled, pluginsOff, queryClient, serverId, source, target]); + + const header = useMemo( + () => ({ + title: + target.kind === "listing" + ? t("settings.plugins.gallery.install.title", { name }) + : t("settings.plugins.gallery.install.sourceTitle"), + }), + [name, t, target.kind], + ); + // Until the config loads, the sheet cannot say whether installing also turns plugins on. + const canInstall = + Boolean(client && config) && (target.kind === "listing" || source.trim().length > 0); + const footer = useMemo( + () => ( + + + + + ), + [canInstall, close, confirm, sourceRunning, t], + ); + const docsLink = useMemo( + () => , + [t], + ); + + return ( + + + {target.kind === "listing" ? ( + + + {listingAuthor(target.listing)} + + + + {listingSource(target.listing)} + + + + {listingVersion(target.listing)} + + + ) : ( + + + + )} + + {target.kind === "source" && sourceRun?.status === "failed" ? ( + + ) : null} + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + body: { gap: theme.spacing[4] }, + value: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.base, maxWidth: 260 }, + actions: { flex: 1, flexDirection: "row", justifyContent: "flex-end", gap: theme.spacing[2] }, +})); diff --git a/packages/app/src/plugins/gallery/installed-tab.tsx b/packages/app/src/plugins/gallery/installed-tab.tsx new file mode 100644 index 0000000000..ee84b2a35a --- /dev/null +++ b/packages/app/src/plugins/gallery/installed-tab.tsx @@ -0,0 +1,276 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { router } from "expo-router"; +import { useCallback, useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem, PluginUpdatePreview } from "@getpaseo/protocol/messages"; +import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference"; +import type { PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { SettingsCard, SettingsSection } from "@/components/settings"; +import { Button } from "@/components/ui/button"; +import { StatusBadge } from "@/components/ui/status-badge"; +import { Switch } from "@/components/ui/switch"; +import { useToast } from "@/contexts/toast-api-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { usePluginEvaluationError } from "@/plugins/registry"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import { settingsStyles } from "@/styles/settings"; +import { usePluginActions } from "./actions"; +import { listingAuthor, listingAuthorAvatar, installedListingId } from "./listing"; +import { updatePlugins, usePluginOperation } from "./operations"; +import { PluginRow } from "./plugin-row"; +import { usePluginUpdates } from "./queries"; +import { buildPluginPageRoute } from "./routes"; + +function shortRevision(revision: string | undefined): string | undefined { + return revision && /^[0-9a-f]{40,64}$/.test(revision) ? revision.slice(0, 7) : revision; +} + +function matchesQuery(plugin: PluginListItem, query: string): boolean { + if (!query) return true; + return [plugin.id, plugin.name ?? "", plugin.description ?? ""] + .join("\n") + .toLowerCase() + .includes(query); +} + +/** "author · version" for a listed plugin; where it was installed from otherwise. */ +function installedMeta(plugin: PluginListItem, listing: PluginListing | undefined) { + if (!plugin.installation) return plugin.path; + if (!listing) return formatPluginInstallation(plugin.installation); + const version = shortRevision(plugin.installation.currentRevision); + return version ? `${listingAuthor(listing)} · ${version}` : listingAuthor(listing); +} + +function useUpdate(serverId: string) { + const { t } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + return useCallback( + (previews: PluginUpdatePreview[]) => { + if (!client) return; + void updatePlugins({ + client, + queryClient, + serverId, + proposals: previews.flatMap((preview) => preview.proposal ?? []), + onUpdated: (plugins) => + toast.show( + plugins.length === 1 + ? t("settings.plugins.gallery.update.updated", { + name: pluginDisplayName(plugins[0]!), + }) + : t("settings.plugins.gallery.update.updatedMany", { count: plugins.length }), + { variant: "success" }, + ), + }); + }, + [client, queryClient, serverId, t, toast], + ); +} + +function UpdateRow({ + serverId, + plugin, + preview, + listing, + onUpdate, +}: { + serverId: string; + plugin: PluginListItem; + preview: PluginUpdatePreview; + listing?: PluginListing; + onUpdate(previews: PluginUpdatePreview[]): void; +}) { + const { t } = useTranslation(); + const operation = usePluginOperation(serverId, plugin.id); + const running = operation?.status === "running"; + const name = pluginDisplayName(plugin); + const target = + preview.target?.kind === "npm" ? preview.target.version : preview.target?.commit.slice(0, 7); + const current = shortRevision(preview.current?.currentRevision); + const open = useCallback( + () => router.push(buildPluginPageRoute(serverId, plugin.id)), + [plugin.id, serverId], + ); + const update = useCallback(() => onUpdate([preview]), [onUpdate, preview]); + let label = t("settings.plugins.gallery.actions.update"); + if (running) label = t("settings.plugins.gallery.actions.updating"); + else if (operation?.status === "failed") label = t("settings.plugins.gallery.actions.retry"); + return ( + + + + ); +} + +function InstalledRow({ + serverId, + plugin, + listing, + pending, + onToggle, +}: { + serverId: string; + plugin: PluginListItem; + listing?: PluginListing; + pending: boolean; + onToggle(plugin: PluginListItem, enabled: boolean): void; +}) { + const { t } = useTranslation(); + const name = pluginDisplayName(plugin); + const error = usePluginEvaluationError(serverId, plugin.id) ?? plugin.error; + const failed = error !== undefined || plugin.status === "failed"; + const open = useCallback( + () => router.push(buildPluginPageRoute(serverId, plugin.id)), + [plugin.id, serverId], + ); + const toggle = useCallback((enabled: boolean) => onToggle(plugin, enabled), [onToggle, plugin]); + const badge = useMemo( + () => + failed ? ( + + ) : null, + [failed, t], + ); + return ( + + + + ); +} + +export function InstalledTab({ + serverId, + plugins, + listings, + query, + onBrowse, +}: { + serverId: string; + plugins: readonly PluginListItem[]; + /** Directory listings by ID, for icons and authors. Empty until the directory loads. */ + listings: ReadonlyMap; + query: string; + onBrowse(): void; +}) { + const { t } = useTranslation(); + const actions = usePluginActions(serverId); + const updates = usePluginUpdates(serverId); + const update = useUpdate(serverId); + const normalizedQuery = query.trim().toLowerCase(); + const shown = plugins.filter((plugin) => matchesQuery(plugin, normalizedQuery)); + const byId = new Map(plugins.map((plugin) => [plugin.id, plugin])); + const pendingUpdates = (updates.data ?? []).filter((preview) => byId.has(preview.id)); + const listingOf = (plugin: PluginListItem) => { + const id = installedListingId(plugin); + return id ? listings.get(id) : undefined; + }; + const toggle = useCallback( + (plugin: PluginListItem, enabled: boolean) => + void actions.run(enabled ? "enable" : "disable", plugin), + [actions], + ); + const updateAll = useCallback(() => update(pendingUpdates), [pendingUpdates, update]); + const updatesTrailing = useMemo( + () => + pendingUpdates.length > 1 ? ( + + ) : undefined, + [pendingUpdates.length, t, updateAll], + ); + + return ( + <> + {pendingUpdates.length > 0 && !normalizedQuery ? ( + + + {pendingUpdates.map((preview) => { + const plugin = byId.get(preview.id)!; + return ( + + ); + })} + + + ) : null} + + + {shown.length ? ( + shown.map((plugin) => ( + + )) + ) : ( + + + {normalizedQuery + ? t("settings.plugins.gallery.empty.noMatches") + : t("settings.plugins.states.empty")} + + {normalizedQuery ? null : ( + + )} + + )} + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + empty: { padding: theme.spacing[6], alignItems: "center", gap: theme.spacing[3] }, +})); diff --git a/packages/app/src/plugins/gallery/listing.test.ts b/packages/app/src/plugins/gallery/listing.test.ts new file mode 100644 index 0000000000..51ebd84d7b --- /dev/null +++ b/packages/app/src/plugins/gallery/listing.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vitest"; +import type { PluginListingIndex, PluginListing } from "@getpaseo/protocol/plugin-registry"; +import { + ALL_CATEGORIES, + featuredListings, + filterDirectory, + formatInstallCount, + listingImages, + listingText, +} from "./listing"; + +function listing(id: string, overrides: Partial = {}): PluginListing { + return { + id, + name: id.split("/")[1] ?? id, + description: `${id} description`, + categories: [], + author: { github: id.split("/")[0] ?? id }, + repository: { url: `https://github.com/${id}` }, + artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) }, + media: [], + submittedAt: "2026-01-01T00:00:00Z", + reviewedAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + publishedAt: "2026-01-01T00:00:00Z", + ...overrides, + } as PluginListing; +} + +function directory(plugins: PluginListing[], featured: string[] = []): PluginListingIndex { + return { + schemaVersion: 1, + registry: { name: "Paseo", url: "https://plugins.paseo.sh" }, + categories: [{ slug: "git", label: "Git" }], + plugins, + featured, + generatedAt: "2026-01-01T00:00:00Z", + }; +} + +const ids = (listings: PluginListing[]) => listings.map((entry) => entry.id); + +describe("filterDirectory", () => { + const index = directory([ + listing("acme/zeta", { installs: 5, updatedAt: "2026-03-01T00:00:00Z", categories: ["git"] }), + listing("acme/alpha", { installs: 50, updatedAt: "2026-01-01T00:00:00Z" }), + listing("other/beta", { + updatedAt: "2026-02-01T00:00:00Z", + translations: { fr: { name: "Bêta", description: "Revue de code" } }, + }), + ]); + + it("orders by installs, recency or name", () => { + const all = { query: "", category: ALL_CATEGORIES }; + expect(ids(filterDirectory(index, { ...all, sort: "popular" }, "en"))).toEqual([ + "acme/alpha", + "acme/zeta", + "other/beta", + ]); + expect(ids(filterDirectory(index, { ...all, sort: "recent" }, "en"))).toEqual([ + "acme/zeta", + "other/beta", + "acme/alpha", + ]); + expect(ids(filterDirectory(index, { ...all, sort: "name" }, "en"))).toEqual([ + "acme/alpha", + "other/beta", + "acme/zeta", + ]); + }); + + it("keeps only the chosen category", () => { + expect( + ids(filterDirectory(index, { query: "", category: "git", sort: "popular" }, "en")), + ).toEqual(["acme/zeta"]); + }); + + it("matches the query against the author and the reader's translation", () => { + const search = (query: string, language: string) => + ids(filterDirectory(index, { query, category: ALL_CATEGORIES, sort: "name" }, language)); + expect(search(" ACME ", "en")).toEqual(["acme/alpha", "acme/zeta"]); + expect(search("revue", "fr-CA")).toEqual(["other/beta"]); + expect(search("revue", "en")).toEqual([]); + }); +}); + +describe("listing presentation", () => { + it("falls back from a regional language to its base translation, then English", () => { + const entry = listing("other/beta", { translations: { fr: { name: "Bêta" } } }); + expect(listingText(entry, "fr-CA")).toEqual({ + name: "Bêta", + description: "other/beta description", + }); + expect(listingText(entry, "ja").name).toBe("beta"); + }); + + it("formats install counts compactly", () => { + expect([999, 1000, 1149, 9950, 12_400].map(formatInstallCount)).toEqual([ + "999", + "1k", + "1.1k", + "9.9k", + "12k", + ]); + }); + + it("shows images and leaves videos out", () => { + const entry = listing("acme/alpha", { + media: ["https://cdn.test/a.png", "https://cdn.test/demo.mp4", "https://cdn.test/b.webp"], + }); + expect(listingImages(entry)).toEqual(["https://cdn.test/a.png", "https://cdn.test/b.webp"]); + }); + + it("features listed plugins in the maintainer's order and skips unlisted ones", () => { + const index = directory( + [listing("acme/alpha"), listing("acme/zeta")], + ["acme/zeta", "gone/plugin", "acme/alpha"], + ); + expect(ids(featuredListings(index))).toEqual(["acme/zeta", "acme/alpha"]); + }); +}); diff --git a/packages/app/src/plugins/gallery/listing.ts b/packages/app/src/plugins/gallery/listing.ts new file mode 100644 index 0000000000..184bf78bb6 --- /dev/null +++ b/packages/app/src/plugins/gallery/listing.ts @@ -0,0 +1,115 @@ +import type { PluginListItem } from "@getpaseo/protocol/messages"; +import { + pluginMediaKind, + type PluginListingIndex, + type PluginListing, +} from "@getpaseo/protocol/plugin-registry"; + +export type DirectorySort = "popular" | "recent" | "name"; +export const ALL_CATEGORIES = "all"; + +export interface DirectoryFilter { + query: string; + category: string; + sort: DirectorySort; +} + +/** The listing's name and description in the reader's language, falling back to English. */ +export function listingText(listing: PluginListing, language: string) { + const translation = listing.translations?.[language] ?? listing.translations?.[baseTag(language)]; + return { + name: translation?.name ?? listing.name, + description: translation?.description ?? listing.description, + }; +} + +function baseTag(language: string): string { + return language.split("-")[0] ?? language; +} + +export function listingAuthor(listing: PluginListing): string { + return listing.author.name ?? listing.author.github; +} + +/** The author's GitHub avatar, the same picture the website shows. */ +export function listingAuthorAvatar(listing: PluginListing): string { + return `https://github.com/${encodeURIComponent(listing.author.github)}.png?size=40`; +} + +/** The version a listing pins: the npm version, or the short Git commit. */ +export function listingVersion(listing: PluginListing): string | undefined { + return listing.artifact.version ?? listing.artifact.commit?.slice(0, 7); +} + +/** Where a listing's code comes from: the npm package, or the repository. */ +export function listingSource(listing: PluginListing): string { + return listing.artifact.package ?? listing.repository.url; +} + +/** Image media in display order. Videos are left to the website. */ +export function listingImages(listing: PluginListing): string[] { + return listing.media.filter((url) => pluginMediaKind(url) === "image"); +} + +/** "1.1k" style counts: one decimal below ten thousand, whole thousands above. */ +export function formatInstallCount(count: number): string { + if (count < 1000) return String(count); + if (count < 10_000) return `${(count / 1000).toFixed(1).replace(/\.0$/, "")}k`; + return `${Math.round(count / 1000)}k`; +} + +/** The registry listing an installed plugin came from, if it came from one. */ +export function installedListingId(plugin: PluginListItem): string | undefined { + const identity = plugin.installation?.identity; + if (!identity || identity.kind === "directory") return undefined; + return identity.registry?.id; +} + +/** Installed plugins by the listing they came from. */ +export function installedByListing(plugins: readonly PluginListItem[]) { + const byListing = new Map(); + for (const plugin of plugins) { + const listingId = installedListingId(plugin); + if (listingId) byListing.set(listingId, plugin); + } + return byListing; +} + +function matches(listing: PluginListing, language: string, query: string): boolean { + if (!query) return true; + const { name, description } = listingText(listing, language); + const haystack = [name, description, listing.id, listingAuthor(listing)].join("\n").toLowerCase(); + return haystack.includes(query); +} + +const SORTS: Record number> = { + popular: (left, right) => (right.installs ?? 0) - (left.installs ?? 0), + recent: (left, right) => right.updatedAt.localeCompare(left.updatedAt), + name: (left, right) => left.name.localeCompare(right.name), +}; + +/** The directory's listings that pass the filter, in the chosen order. */ +export function filterDirectory( + index: PluginListingIndex, + filter: DirectoryFilter, + language: string, +): PluginListing[] { + const query = filter.query.trim().toLowerCase(); + return index.plugins + .filter( + (listing) => + (filter.category === ALL_CATEGORIES || listing.categories.includes(filter.category)) && + matches(listing, language, query), + ) + .sort(SORTS[filter.sort]); +} + +/** Featured listings that exist, in the maintainer's order. */ +export function featuredListings(index: PluginListingIndex): PluginListing[] { + const byId = new Map(index.plugins.map((listing) => [listing.id, listing])); + return index.featured.flatMap((id) => byId.get(id) ?? []); +} + +export function categoryLabel(index: PluginListingIndex, slug: string): string { + return index.categories.find((category) => category.slug === slug)?.label ?? slug; +} diff --git a/packages/app/src/plugins/gallery/menus.tsx b/packages/app/src/plugins/gallery/menus.tsx new file mode 100644 index 0000000000..aec3f028ed --- /dev/null +++ b/packages/app/src/plugins/gallery/menus.tsx @@ -0,0 +1,325 @@ +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { + ArrowUpRight, + FileText, + MoreHorizontal, + PackagePlus, + Power, + RotateCw, + Trash2, +} from "lucide-react-native"; +import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages"; +import { + AdaptiveModalSheet, + SheetHeaderIconButton, + type SheetHeader, +} from "@/components/adaptive-modal-sheet"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + iconButtonChromeHang, + useIconButtonChromeGlyphSize, + useIconButtonChromeStyle, +} from "@/components/ui/icon-button-chrome"; +import { foregroundIconColorMapping, mutedIconColorMapping } from "@/components/ui/icon-color"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-api-context"; +import { useFetchQuery } from "@/data/query"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import type { Theme } from "@/styles/theme"; +import { openExternalUrl } from "@/utils/open-external-url"; +import type { PluginAction } from "./actions"; +import { InstallPluginSheet } from "./install-sheet"; +import { pluginErrorText } from "./error-text"; + +const SUBMIT_PLUGIN_URL = + "https://github.com/getpaseo/plugins/issues/new?template=submit-plugin.yml"; +const ThemedMore = withUnistyles(MoreHorizontal); +const dangerIconMapping = (theme: Theme) => ({ color: theme.colors.statusDanger }); +const ThemedPackagePlus = withUnistyles(PackagePlus); +const ThemedPower = withUnistyles(Power); +const ThemedArrow = withUnistyles(ArrowUpRight); +const ThemedRotate = withUnistyles(RotateCw); +const ThemedLogs = withUnistyles(FileText); +const ThemedTrash = withUnistyles(Trash2); +const installIcon = ; +const powerIcon = ; +const linkIcon = ; +const reloadIcon = ; +const logsIcon = ; +const removeIcon = ; + +type TriggerState = PressableStateCallbackType & { hovered?: boolean; open?: boolean }; +// The trigger hangs by how far its frame reaches past the glyph, so the glyph sits on the trailing +// content rail and the frame does not grow the row. +const TRIGGER_HANG = iconButtonChromeHang("small"); + +function MenuTrigger({ label, testID }: { label: string; testID: string }) { + const compact = useIsCompactFormFactor(); + const style = useIconButtonChromeStyle({ size: "small", compact, style: styles.trigger }); + const glyphSize = useIconButtonChromeGlyphSize("small", compact); + return ( + + {({ hovered, open }: TriggerState) => ( + + )} + + ); +} + +/** The page's occasional actions: install from a source, turn plugins off, submit a plugin. */ +export function PluginGalleryMenu({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const toast = useToast(); + // COMPAT(pluginSourceInstallation): added in v0.8.0; remove gate after 2027-03-16. + const sourceInstallSupported = useHostFeature(serverId, "pluginSourceInstallation"); + const { config, patchConfig } = useDaemonConfig(serverId); + const [installing, setInstalling] = useState(false); + const pluginsOn = config?.pluginsEnabled === true; + const openInstall = useCallback(() => setInstalling(true), []); + const closeInstall = useCallback(() => setInstalling(false), []); + const toggle = useCallback(async () => { + try { + await patchConfig({ pluginsEnabled: !pluginsOn }); + toast.show( + pluginsOn + ? t("settings.plugins.feedback.globalDisabled") + : t("settings.plugins.feedback.globalEnabled"), + { variant: "success" }, + ); + } catch (error) { + toast.error(pluginErrorText(error)); + } + }, [patchConfig, pluginsOn, t, toast]); + const submit = useCallback(() => void openExternalUrl(SUBMIT_PLUGIN_URL), []); + const label = t("settings.plugins.gallery.menu"); + return ( + <> + + + + {sourceInstallSupported ? ( + + {t("settings.plugins.gallery.actions.installFromSource")} + + ) : null} + + {pluginsOn + ? t("settings.plugins.gallery.actions.turnOff") + : t("settings.plugins.gallery.actions.turnOnAll")} + + + {t("settings.plugins.gallery.actions.submit")} + + + + {installing ? ( + + ) : null} + + ); +} +const SOURCE_TARGET = { kind: "source" } as const; + +/** One installed plugin's occasional actions, on its page. */ +export function PluginActionsMenu({ + serverId, + plugin, + repositoryUrl, + pendingAction, + onAction, +}: { + serverId: string; + plugin: PluginListItem; + repositoryUrl?: string; + pendingAction?: PluginAction; + onAction(action: PluginAction): void; +}) { + const { t } = useTranslation(); + // COMPAT(pluginLogs): added in v0.4.0, remove gate after 2027-08-16. + const logsSupported = useHostFeature(serverId, "pluginLogs"); + const [logsOpen, setLogsOpen] = useState(false); + const reload = useCallback(() => onAction("reload"), [onAction]); + const remove = useCallback(() => onAction("remove"), [onAction]); + const openLogs = useCallback(() => setLogsOpen(true), []); + const closeLogs = useCallback(() => setLogsOpen(false), []); + const openRepository = useCallback(() => { + if (repositoryUrl) void openExternalUrl(repositoryUrl); + }, [repositoryUrl]); + const label = t("settings.plugins.actions.menu", { name: pluginDisplayName(plugin) }); + return ( + <> + + + + + {t("settings.plugins.actions.reload")} + + {logsSupported ? ( + + {t("settings.plugins.logs.action")} + + ) : null} + {repositoryUrl ? ( + + {t("settings.plugins.gallery.actions.repository")} + + ) : null} + + {t("settings.plugins.actions.remove")} + + + + {logsOpen ? ( + + ) : null} + + ); +} + +function PluginLogsSheet({ + serverId, + plugin, + onClose, +}: { + serverId: string; + plugin: PluginListItem; + onClose(): void; +}) { + const { t } = useTranslation(); + const client = useHostRuntimeClient(serverId); + const pluginId = plugin.id; + const logs = useFetchQuery({ + queryKey: ["plugin-logs", serverId, pluginId], + queryFn: () => { + if (!client) throw new Error("Plugin host is offline"); + return client.getPluginLogs(pluginId); + }, + enabled: Boolean(client), + dataShape: "list", + staleTimeMs: 0, + }); + const refresh = useCallback(() => { + void logs.refetch(); + }, [logs]); + const header = useMemo( + () => ({ + title: t("settings.plugins.logs.title", { name: pluginDisplayName(plugin) }), + actions: ( + + ), + }), + [logs.isFetching, plugin, refresh, t], + ); + + let content = {t("settings.plugins.logs.loading")}; + if (logs.isError) { + content = ( + + + + ); + } else if (!logs.isLoading) { + content = logs.data?.length ? ( + + {logs.data.map((entry: PluginLogEntry) => ( + + + {entry.timestamp} {entry.stream} + + {entry.message} + + ))} + + ) : ( + {t("settings.plugins.logs.empty")} + ); + } + + return ( + + {content} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + trigger: { marginVertical: TRIGGER_HANG, marginRight: TRIGGER_HANG }, + logsState: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + textAlign: "center", + paddingVertical: theme.spacing[6], + }, + logList: { gap: theme.spacing[2] }, + logEntry: { + padding: theme.spacing[3], + gap: theme.spacing[1], + backgroundColor: theme.colors.surface2, + borderRadius: theme.borderRadius.md, + }, + logStdout: { + color: theme.colors.foregroundMuted, + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.sm, + }, + logStderr: { + color: theme.colors.statusDanger, + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.sm, + }, + logMessage: { + color: theme.colors.foreground, + fontFamily: theme.fontFamily.mono, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/plugins/gallery/operations.ts b/packages/app/src/plugins/gallery/operations.ts new file mode 100644 index 0000000000..edd4964c6a --- /dev/null +++ b/packages/app/src/plugins/gallery/operations.ts @@ -0,0 +1,159 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { useCallback, useSyncExternalStore } from "react"; +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import type { + PluginListItem, + PluginUpdatePreview, + PluginUpdateProposal, +} from "@getpaseo/protocol/messages"; +import { daemonConfigQueryKey } from "@/data/daemon-config"; +import { pluginListQueryKey } from "@/plugins/plugin-list"; +import { pluginErrorText } from "./error-text"; + +/** + * Installs and updates outlive the screen that started them: leaving Plugins and coming back + * mid-run still shows the run on its row. A finished run leaves no entry; the plugin list says + * what changed. + */ +export type PluginOperation = + | { kind: "install" | "update"; status: "running" } + | { kind: "install" | "update"; status: "failed"; error: string }; + +type Listener = () => void; + +const operations = new Map(); +const listeners = new Set(); + +function operationKey(serverId: string, subject: string): string { + return `${serverId}\n${subject}`; +} + +function setOperation(serverId: string, subject: string, operation: PluginOperation | null) { + const key = operationKey(serverId, subject); + if (operation) operations.set(key, operation); + else operations.delete(key); + for (const listener of listeners) listener(); +} + +function subscribe(listener: Listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** The install or update running or failed for a plugin, keyed by listing ID or plugin ID. */ +export function usePluginOperation(serverId: string, subject: string | undefined) { + const read = useCallback( + () => (subject ? operations.get(operationKey(serverId, subject)) : undefined), + [serverId, subject], + ); + return useSyncExternalStore(subscribe, read, read); +} + +/** Forgets a failed run once its error has been read. A running one keeps going. */ +export function dismissFailedOperation(serverId: string, subject: string) { + if (operations.get(operationKey(serverId, subject))?.status === "failed") + setOperation(serverId, subject, null); +} + +export function pluginUpdatesQueryKey(serverId: string) { + return ["plugin-updates", serverId] as const; +} + +function upsertPlugin(queryClient: QueryClient, serverId: string, plugin: PluginListItem) { + queryClient.setQueryData(pluginListQueryKey(serverId), (plugins = []) => { + const others = plugins.filter((candidate) => candidate.id !== plugin.id); + return [...others, plugin].sort((left, right) => left.id.localeCompare(right.id)); + }); +} + +interface HostContext { + client: DaemonClient; + queryClient: QueryClient; + serverId: string; +} + +export interface InstallRequest extends HostContext { + /** A registry ID such as `acme/example`, or any source the CLI accepts. */ + source: string; + /** Where the run shows: the listing ID, or the source for an install from source. */ + subject: string; + /** Plugins are off on the host; the confirmation said installing turns them on. */ + enablePlugins: boolean; + onInstalled(plugin: PluginListItem): void; +} + +export async function installPlugin(request: InstallRequest): Promise { + const { client, queryClient, serverId, subject } = request; + if (operations.get(operationKey(serverId, subject))?.status === "running") return; + setOperation(serverId, subject, { kind: "install", status: "running" }); + try { + if (request.enablePlugins) { + const result = await client.patchDaemonConfig({ pluginsEnabled: true }); + queryClient.setQueryData(daemonConfigQueryKey(serverId), result.config); + } + const plugin = await client.installPluginSource({ source: request.source }); + // Write the result before clearing the run, so the row goes straight to Installed. + upsertPlugin(queryClient, serverId, plugin); + setOperation(serverId, subject, null); + request.onInstalled(plugin); + } catch (error) { + setOperation(serverId, subject, { + kind: "install", + status: "failed", + error: pluginErrorText(error), + }); + } +} + +export interface UpdateRequest extends HostContext { + proposals: PluginUpdateProposal[]; + onUpdated(plugins: PluginListItem[]): void; +} + +export async function updatePlugins(request: UpdateRequest): Promise { + const { client, queryClient, serverId } = request; + const proposals = request.proposals.filter( + (proposal) => operations.get(operationKey(serverId, proposal.id))?.status !== "running", + ); + if (proposals.length === 0) return; + for (const proposal of proposals) + setOperation(serverId, proposal.id, { kind: "update", status: "running" }); + try { + const results = await client.applyPluginUpdates(proposals); + const updated: PluginListItem[] = []; + for (const result of results) { + if (result.outcome === "updated" && result.plugin) { + upsertPlugin(queryClient, serverId, result.plugin); + updated.push(result.plugin); + setOperation(serverId, result.id, null); + } else { + setOperation(serverId, result.id, { + kind: "update", + status: "failed", + error: result.error ?? "Update failed", + }); + } + } + const updatedIds = new Set(updated.map((plugin) => plugin.id)); + queryClient.setQueryData(pluginUpdatesQueryKey(serverId), (previews) => + previews?.filter((preview) => !updatedIds.has(preview.id)), + ); + if (updated.length) request.onUpdated(updated); + if (updated.length < results.length) recheckUpdates(request); + } catch (error) { + for (const proposal of proposals) + setOperation(serverId, proposal.id, { + kind: "update", + status: "failed", + error: pluginErrorText(error), + }); + recheckUpdates(request); + } +} + +// A proposal fails when the plugin changed since it was reviewed; Retry needs a fresh one. +function recheckUpdates({ queryClient, serverId }: HostContext): void { + void queryClient.invalidateQueries({ queryKey: pluginUpdatesQueryKey(serverId) }); +} diff --git a/packages/app/src/plugins/gallery/plugin-page.tsx b/packages/app/src/plugins/gallery/plugin-page.tsx new file mode 100644 index 0000000000..0e83ed5e49 --- /dev/null +++ b/packages/app/src/plugins/gallery/plugin-page.tsx @@ -0,0 +1,581 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { router } from "expo-router"; +import { ArrowLeft } from "lucide-react-native"; +import { useCallback, useMemo, useState, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { Image, ScrollView, Text, View } from "react-native"; +import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox"; +import { StyleSheet } from "react-native-unistyles"; +import type { PluginListItem, PluginUpdatePreview } from "@getpaseo/protocol/messages"; +import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference"; +import type { + PluginListingIndex, + PluginListing, + PluginListingDetail, +} from "@getpaseo/protocol/plugin-registry"; +import { MarkdownRenderer } from "@/components/markdown/renderer"; +import { SettingsCard, SettingsRow, SettingsSection } from "@/components/settings"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { ExternalLink } from "@/components/ui/external-link"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { StatusBadge } from "@/components/ui/status-badge"; +import { Switch } from "@/components/ui/switch"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useToast } from "@/contexts/toast-api-context"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import { useInstalledPlugin, usePluginEvaluationError } from "@/plugins/registry"; +import { pluginDisplayName } from "@/plugins/plugin-list"; +import { PluginSettingsContent } from "@/plugins/settings"; +import { usePluginActions, type PluginAction } from "./actions"; +import { useListingMeta } from "./browse-tab"; +import { ListingInstallControl } from "./install-control"; +import { InstallPluginSheet, type InstallTarget } from "./install-sheet"; +import { + categoryLabel, + installedByListing, + installedListingId, + listingAuthorAvatar, + listingImages, + listingText, + listingSource, + listingVersion, +} from "./listing"; +import { PluginActionsMenu } from "./menus"; +import { updatePlugins, usePluginOperation, type PluginOperation } from "./operations"; +import { PluginMeta, PluginTile } from "./plugin-row"; +import { buildPluginListingRoute } from "./routes"; +import { PluginsOffAlert } from "./plugins-off-alert"; +import { OverviewSkeleton, PluginPageSkeleton } from "./skeletons"; +import { + useLivePluginList, + usePluginDirectory, + usePluginListing, + usePluginUpdates, +} from "./queries"; +import { pluginErrorText } from "./error-text"; + +/** Which plugin the page is for: one installed on the host, or one listed in the directory. */ +export type PluginPageSubject = + | { kind: "installed"; pluginId: string; screenId?: string } + | { kind: "listing"; listingId: string }; + +function useResolvedPlugin(serverId: string, subject: PluginPageSubject) { + const plugins = useLivePluginList(serverId); + const plugin = useMemo(() => { + const list = plugins.data ?? []; + if (subject.kind === "installed") return list.find((item) => item.id === subject.pluginId); + return installedByListing(list).get(subject.listingId); + }, [plugins.data, subject]); + const listingId = + subject.kind === "listing" ? subject.listingId : plugin && installedListingId(plugin); + const detail = usePluginListing(serverId, listingId); + const directory = usePluginDirectory(serverId); + // The directory the user came from already has the listing, so the page shows it at once and + // only the overview waits for the listing's own request. + const listing = + detail.data ?? directory.query.data?.plugins.find((entry) => entry.id === listingId); + const listingLoading = detail.isLoading && !listing; + return { + plugin, + listingId, + listing, + detail, + loading: plugins.isLoading || (subject.kind === "listing" && listingLoading), + }; +} + +function UpdateButton({ serverId, plugin }: { serverId: string; plugin: PluginListItem }) { + const { t } = useTranslation(); + const toast = useToast(); + const queryClient = useQueryClient(); + const client = useHostRuntimeClient(serverId); + const updates = usePluginUpdates(serverId); + const operation = usePluginOperation(serverId, plugin.id); + const preview = updates.data?.find((candidate) => candidate.id === plugin.id); + const update = useCallback(() => { + if (!client || !preview?.proposal) return; + void updatePlugins({ + client, + queryClient, + serverId, + proposals: [preview.proposal], + onUpdated: ([updated]) => + toast.show( + t("settings.plugins.gallery.update.updated", { name: pluginDisplayName(updated!) }), + { variant: "success" }, + ), + }); + }, [client, preview, queryClient, serverId, t, toast]); + if (!preview) return null; + const running = operation?.status === "running"; + let label = t("settings.plugins.gallery.actions.update"); + if (running) label = t("settings.plugins.gallery.actions.updating"); + else if (operation?.status === "failed") label = t("settings.plugins.gallery.actions.retry"); + return ( + + ); +} + +function InstalledControls({ + serverId, + plugin, + repositoryUrl, + onRemoved, +}: { + serverId: string; + plugin: PluginListItem; + repositoryUrl?: string; + onRemoved(): void; +}) { + const { t } = useTranslation(); + const actions = usePluginActions(serverId); + const name = pluginDisplayName(plugin); + const pendingAction = + actions.pending?.pluginId === plugin.id ? actions.pending.action : undefined; + const toggle = useCallback( + (enabled: boolean) => void actions.run(enabled ? "enable" : "disable", plugin), + [actions, plugin], + ); + const act = useCallback( + async (action: PluginAction) => { + if ((await actions.run(action, plugin)) && action === "remove") onRemoved(); + }, + [actions, onRemoved, plugin], + ); + const onAction = useCallback((action: PluginAction) => void act(action), [act]); + return ( + + + + + + ); +} + +function MediaImage({ url, onOpen }: { url: string; onOpen(url: string): void }) { + const { t } = useTranslation(); + const source = useMemo(() => ({ uri: url }), [url]); + const open = useCallback(() => onOpen(url), [onOpen, url]); + return ( + + + + ); +} + +/** The listing's screenshots in a row; one opens full size in the lightbox. */ +function MediaStrip({ urls }: { urls: string[] }) { + const [image, setImage] = useState(null); + const open = useCallback((uri: string) => setImage({ type: "uri", uri }), []); + const close = useCallback(() => setImage(null), []); + if (urls.length === 0) return null; + return ( + <> + + {urls.map((url) => ( + + ))} + + + + ); +} + +function DetailValue({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +function detailSource(plugin: PluginListItem | undefined, listing: PluginListing | undefined) { + if (plugin?.installation) return formatPluginInstallation(plugin.installation); + if (plugin) return plugin.path; + if (!listing) return undefined; + return listingSource(listing); +} + +function Details({ plugin, listing }: { plugin?: PluginListItem; listing?: PluginListing }) { + const { t } = useTranslation(); + const version = plugin?.installation?.currentRevision ?? (listing && listingVersion(listing)); + const source = detailSource(plugin, listing); + const repository = listing?.repository.url; + return ( + + + {version ? ( + + {version} + + ) : null} + {source ? ( + + {source} + + ) : null} + {listing?.license ? ( + + {listing.license} + + ) : null} + {listing ? ( + + {listing.updatedAt.slice(0, 10)} + + ) : null} + {repository ? ( + + + + ) : null} + + + ); +} + +/** What the page shows about the plugin, from whichever of the installed plugin and listing exist. */ +interface PluginPageModel { + name: string; + description?: string; + /** "author · installs · category" for a listing; the ID when the name hides it. */ + metaLine?: string; + /** The listing author's picture, before the meta line. */ + authorAvatar?: string; + /** Why the plugin failed to load, or why its install failed. */ + error?: string; + /** Why the last update failed, while the update is still offered. The installed version keeps running. */ + updateError?: string; + /** The plugin's own settings screen, shown inline. */ + screenId?: string; + overview?: string; +} + +function usePluginPageModel({ + serverId, + subject, + plugin, + listing, + detail, + installOperation, +}: { + serverId: string; + subject: PluginPageSubject; + plugin?: PluginListItem; + listing?: PluginListing; + /** The listing with its overview, once its own request returns. */ + detail?: PluginListingDetail; + installOperation: PluginOperation | undefined; +}): PluginPageModel { + const { i18n } = useTranslation(); + const directory = usePluginDirectory(serverId); + const meta = useListingMeta(); + const pluginId = plugin?.id ?? ""; + const installedPlugin = useInstalledPlugin(serverId, pluginId); + const evaluationError = usePluginEvaluationError(serverId, pluginId); + const pluginOperation = usePluginOperation(serverId, pluginId); + const updates = usePluginUpdates(serverId); + const text = listing ? listingText(listing, i18n.language) : undefined; + const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined; + return { + name: plugin ? pluginDisplayName(plugin) : (text?.name ?? subjectId(subject)), + description: text?.description ?? plugin?.description, + metaLine: listing + ? listingMetaLine(meta(listing), directory.query.data, listing) + : installedMetaLine(plugin), + authorAvatar: listing && listingAuthorAvatar(listing), + error: plugin ? (evaluationError ?? plugin.error) : failedError(installOperation), + updateError: failedUpdateError(pluginOperation, updates.data, pluginId), + screenId: plugin ? (requestedScreen ?? installedPlugin?.settingsScreens[0]?.id) : undefined, + overview: detail && listingOverview(detail, i18n.language), + }; +} + +function subjectId(subject: PluginPageSubject): string { + return subject.kind === "listing" ? subject.listingId : subject.pluginId; +} + +function listingOverview(listing: PluginListingDetail, language: string): string { + return (listing.overviewTranslations?.[language] ?? listing.readme).trim(); +} + +function listingMetaLine( + meta: string, + index: PluginListingIndex | undefined, + listing: PluginListing, +): string { + const category = listing.categories[0]; + return category && index ? `${meta} · ${categoryLabel(index, category)}` : meta; +} + +function installedMetaLine(plugin: PluginListItem | undefined): string | undefined { + return plugin?.name && plugin.name !== plugin.id ? plugin.id : undefined; +} + +function failedError(operation: PluginOperation | undefined): string | undefined { + return operation?.status === "failed" ? operation.error : undefined; +} + +/** Shown with the Update button it belongs to, as on the Installed tab's Updates row. */ +function failedUpdateError( + operation: PluginOperation | undefined, + updates: PluginUpdatePreview[] | undefined, + pluginId: string, +): string | undefined { + if (operation?.kind !== "update" || !updates?.some((preview) => preview.id === pluginId)) + return undefined; + return failedError(operation); +} + +function HeaderControl({ + serverId, + plugin, + listing, + installOperation, + onInstall, + onRemoved, +}: { + serverId: string; + plugin?: PluginListItem; + listing?: PluginListing; + installOperation: PluginOperation | undefined; + onInstall(listing: PluginListing): void; + onRemoved(): void; +}) { + if (plugin) + return ( + + ); + if (!listing) return null; + return ( + + ); +} + +/** + * A plugin's page: what it is, its install or on/off control, its own settings, its overview and + * the facts about where it came from. The same page serves an installed plugin and a listing. + */ +export function PluginPage({ + serverId, + subject, + onBack, +}: { + serverId: string; + subject: PluginPageSubject; + onBack(): void; +}) { + const { t } = useTranslation(); + const compact = useIsCompactFormFactor(); + const { plugin, listingId, listing, detail, loading } = useResolvedPlugin(serverId, subject); + const installOperation = usePluginOperation(serverId, listingId); + const model = usePluginPageModel({ + serverId, + subject, + plugin, + listing, + detail: detail.data, + installOperation, + }); + const [installTarget, setInstallTarget] = useState(null); + const install = useCallback( + (target: PluginListing) => setInstallTarget({ kind: "listing", listing: target }), + [], + ); + const closeInstall = useCallback(() => setInstallTarget(null), []); + // An installed page finds its listing through the plugin, which uninstalling removes. A listed + // plugin's page becomes its listing's page, offering Install again; any other returns to Plugins. + const onRemoved = useCallback(() => { + if (subject.kind !== "installed") return; + if (listingId) router.replace(buildPluginListingRoute(serverId, listingId)); + else onBack(); + }, [listingId, onBack, serverId, subject.kind]); + + const back = compact ? null : ( + + ); + if (loading) + return ( + + {back} + + + ); + if (!plugin && !listing) + return ( + + ); + + return ( + + {back} + + + + + + {model.name} + + {plugin && model.error ? ( + + ) : null} + + {model.metaLine ? ( + + ) : null} + + + + + {installTarget ? ( + + ) : null} + + ); +} + +function PluginPageBody({ + serverId, + plugin, + listing, + overviewLoading, + model, +}: { + serverId: string; + plugin?: PluginListItem; + listing?: PluginListing; + overviewLoading: boolean; + model: PluginPageModel; +}) { + const { t } = useTranslation(); + return ( + <> + {plugin ? : null} + {model.description ? {model.description} : null} + {model.error ? ( + + + + ) : null} + {model.updateError ? ( + + + + ) : null} + {listing ? : null} + {plugin && model.screenId ? ( + // The plugin's settings screen brings its own sections. + + ) : null} + {model.overview || (listing && overviewLoading) ? ( + + {model.overview ? ( + + + + + + ) : ( + + )} + + ) : null} +
+ + ); +} + +const styles = StyleSheet.create((theme) => ({ + back: { alignSelf: "flex-start", paddingHorizontal: 0, marginBottom: theme.spacing[4] }, + header: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[4], + }, + identity: { flex: 1, minWidth: 0, gap: theme.spacing[1] }, + nameRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + name: { flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.xl }, + controls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + description: { + color: theme.colors.foreground, + fontSize: theme.fontSize.base, + marginBottom: theme.spacing[6], + }, + block: { marginBottom: theme.spacing[6] }, + // The settings row's padding, so the overview's text sits where a row's label would. + overview: { padding: theme.spacing[4] }, + mediaStrip: { flexGrow: 0, marginBottom: theme.spacing[6] }, + mediaRow: { gap: theme.spacing[3] }, + media: { + height: 180, + aspectRatio: 16 / 10, + borderRadius: theme.borderRadius.lg, + borderWidth: 1, + borderColor: theme.colors.border, + backgroundColor: theme.colors.surface2, + overflow: "hidden", + }, + mediaImage: { width: "100%", height: "100%" }, + detailValue: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + maxWidth: 320, + }, +})); diff --git a/packages/app/src/plugins/gallery/plugin-row.tsx b/packages/app/src/plugins/gallery/plugin-row.tsx new file mode 100644 index 0000000000..456fda3b37 --- /dev/null +++ b/packages/app/src/plugins/gallery/plugin-row.tsx @@ -0,0 +1,202 @@ +import { ChevronRight } from "lucide-react-native"; +import { useCallback, useMemo, type ReactNode } from "react"; +import { Image, Text, View, type PressableStateCallbackType } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { foregroundIconColorMapping, mutedIconColorMapping } from "@/components/ui/icon-color"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { settingsStyles } from "@/styles/settings"; +import { ICON_SIZE } from "@/styles/theme"; + +const ThemedChevron = withUnistyles(ChevronRight); +type HoverState = PressableStateCallbackType & { hovered?: boolean }; + +/** A plugin's icon, or its initial on a neutral tile when it has none. */ +export function PluginTile({ + name, + icon, + size = "md", +}: { + name: string; + icon?: string; + size?: "md" | "lg"; +}) { + const tileStyle = useMemo(() => [styles.tile, size === "lg" && styles.tileLarge], [size]); + const source = useMemo(() => (icon ? { uri: icon } : null), [icon]); + if (source) return ; + return ( + + + {name.slice(0, 1).toUpperCase()} + + + ); +} + +/** A listing author's GitHub picture, before their name in a meta line. */ +export function AuthorAvatar({ url }: { url: string }) { + const source = useMemo(() => ({ uri: url }), [url]); + return ; +} + +/** A line of facts, led by the author's picture when the plugin is listed. */ +export function PluginMeta({ + text, + authorAvatar, + testID, +}: { + text: string; + authorAvatar?: string; + testID?: string; +}) { + return ( + + {authorAvatar ? : null} + + {text} + + + ); +} + +export interface PluginRowProps { + name: string; + icon?: string; + /** Beside the name, such as a Failed badge. */ + badge?: ReactNode; + description?: string; + /** Who made it and which version, or how many installs. */ + meta?: string; + /** The listing author's picture, before the meta line. */ + authorAvatar?: string; + /** Replaces the meta line: what went wrong, in the row the user is looking at. */ + error?: string; + /** The row's control: a switch, or the install or update button. The chevron follows it. */ + children?: ReactNode; + onPress(): void; + accessibilityLabel: string; + testID?: string; +} + +/** + * One plugin in a card: icon, name, a line of description and a line of facts. The whole row opens + * the plugin's page; the control in the trailing slot acts without opening it. + */ +export function PluginRow({ + name, + icon, + badge, + description, + meta, + authorAvatar, + error, + children, + onPress, + accessibilityLabel, + testID, +}: PluginRowProps) { + const rowStyle = useCallback( + ({ hovered }: HoverState) => [settingsStyles.row, styles.row, hovered && styles.hovered], + [], + ); + return ( + + {({ hovered }: HoverState) => ( + <> + + + + + {name} + + {badge} + + {description ? ( + + {description} + + ) : null} + {error ? ( + + {error} + + ) : null} + {meta && !error ? ( + + + + ) : null} + + {children} + + + + + )} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + row: { gap: theme.spacing[3] }, + hovered: { backgroundColor: theme.colors.surface2 }, + pressed: { backgroundColor: theme.colors.surface3 }, + tile: { + width: theme.spacing[8], + height: theme.spacing[8], + borderRadius: theme.borderRadius.lg, + borderWidth: 1, + borderColor: theme.colors.border, + backgroundColor: theme.colors.surface2, + alignItems: "center", + justifyContent: "center", + overflow: "hidden", + }, + tileLarge: { + width: theme.spacing[12], + height: theme.spacing[12], + borderRadius: theme.borderRadius.xl, + }, + initial: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.base }, + initialLarge: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.xl }, + text: { flex: 1, minWidth: 0 }, + titleRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, + title: { flexShrink: 1, color: theme.colors.foreground, fontSize: theme.fontSize.base }, + description: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + marginTop: theme.spacing[0.5], + }, + meta: { marginTop: theme.spacing[0.5] }, + metaRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[1.5] }, + metaText: { + flexShrink: 1, + color: theme.colors.foregroundExtraMuted, + fontSize: theme.fontSize.sm, + }, + avatar: { + width: theme.iconSize.sm, + height: theme.iconSize.sm, + borderRadius: theme.borderRadius.full, + borderWidth: 1, + borderColor: theme.colors.border, + backgroundColor: theme.colors.surface2, + }, + error: { + color: theme.colors.statusDanger, + fontSize: theme.fontSize.sm, + marginTop: theme.spacing[0.5], + }, + // Optical: the chevron's ink sits about 4px inside its box; this puts it on the card's trailing + // rail, the same as SettingsRowHeader. + chevron: { marginRight: -theme.spacing[1] }, +})); diff --git a/packages/app/src/plugins/gallery/plugins-off-alert.tsx b/packages/app/src/plugins/gallery/plugins-off-alert.tsx new file mode 100644 index 0000000000..2e87f9dc55 --- /dev/null +++ b/packages/app/src/plugins/gallery/plugins-off-alert.tsx @@ -0,0 +1,48 @@ +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { useToast } from "@/contexts/toast-api-context"; +import { useDaemonConfig } from "@/hooks/use-daemon-config"; +import { useHostLabel } from "./install-sheet"; +import { pluginErrorText } from "./error-text"; + +/** Says that installed plugins are not running on this host, with the switch that runs them. */ +export function PluginsOffAlert({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const toast = useToast(); + const hostLabel = useHostLabel(serverId); + const { config, patchConfig } = useDaemonConfig(serverId); + const [turningOn, setTurningOn] = useState(false); + const turnOn = useCallback(async () => { + setTurningOn(true); + try { + await patchConfig({ pluginsEnabled: true }); + } catch (error) { + toast.error(pluginErrorText(error)); + } finally { + setTurningOn(false); + } + }, [patchConfig, toast]); + if (!config || config.pluginsEnabled === true) return null; + return ( + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + block: { marginBottom: theme.spacing[6] }, +})); diff --git a/packages/app/src/plugins/gallery/queries.ts b/packages/app/src/plugins/gallery/queries.ts new file mode 100644 index 0000000000..8f4451c957 --- /dev/null +++ b/packages/app/src/plugins/gallery/queries.ts @@ -0,0 +1,112 @@ +import { useCallback, useEffect } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { usePluginList } from "@/plugins/plugin-list"; +import { useFetchQuery } from "@/data/query"; +import { useHostFeature } from "@/runtime/host-features"; +import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +import { pluginUpdatesQueryKey } from "./operations"; + +// The directory changes when a maintainer publishes, not while someone browses. These queries +// refetch on mount only once stale, so opening a plugin's page does not fetch them again. +const DIRECTORY_STALE_MS = 10 * 60_000; + +function useHostReady(serverId: string) { + const client = useHostRuntimeClient(serverId); + const connected = useHostRuntimeIsConnected(serverId); + return { client, ready: Boolean(client && connected) }; +} + +/** The host's plugin directory. `supported` is false until the host proxies the registry. */ +export function usePluginDirectory(serverId: string) { + const { client, ready } = useHostReady(serverId); + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + const supported = useHostFeature(serverId, "pluginRegistry"); + const query = useFetchQuery({ + queryKey: ["plugin-directory", serverId] as const, + queryFn: () => { + if (!client) throw new Error("Plugin host is offline"); + return client.listPluginRegistry(); + }, + enabled: ready && supported, + dataShape: "value", + staleTimeMs: DIRECTORY_STALE_MS, + refetchOnMount: true, + }); + return { supported, query }; +} + +/** One listing with its overview. */ +export function usePluginListing(serverId: string, listingId: string | undefined) { + const { client, ready } = useHostReady(serverId); + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + const supported = useHostFeature(serverId, "pluginRegistry"); + return useFetchQuery({ + queryKey: ["plugin-listing", serverId, listingId] as const, + queryFn: () => { + if (!client || !listingId) throw new Error("Plugin host is offline"); + return client.getRegistryPlugin(listingId); + }, + enabled: ready && supported && listingId !== undefined, + dataShape: "value", + staleTimeMs: DIRECTORY_STALE_MS, + refetchOnMount: true, + }); +} + +/** Installed plugins with a newer reviewed version, by plugin ID. */ +export function usePluginUpdates(serverId: string) { + const { client, ready } = useHostReady(serverId); + // COMPAT(pluginSourceUpdates): added in v0.8.0, remove gate after 2027-03-16. + const supported = useHostFeature(serverId, "pluginSourceUpdates"); + return useFetchQuery({ + queryKey: pluginUpdatesQueryKey(serverId), + queryFn: () => { + if (!client) throw new Error("Plugin host is offline"); + return client.previewPluginUpdates(); + }, + enabled: ready && supported, + dataShape: "list", + staleTimeMs: DIRECTORY_STALE_MS, + refetchOnMount: true, + select: (previews) => previews.filter((preview) => preview.outcome === "update"), + }); +} + +/** Refetches the plugin list when another client or the CLI changes it. */ +function usePluginCatalogFeed(serverId: string, refetch: () => unknown) { + const client = useHostRuntimeClient(serverId); + const connected = useHostRuntimeIsConnected(serverId); + const supported = useHostFeature(serverId, "pluginManagement"); + useEffect(() => { + if (!client || !connected || !supported) return; + const observation = client.observeEvents(["status.plugin_catalog_changed"]); + observation.subscribe({ + snapshot: () => {}, + update: (message) => { + if (message.type === "status" && message.payload.status === "plugin_catalog_changed") + void refetch(); + }, + }); + return () => { + void observation + .release() + .catch((error) => console.warn("[Plugins] Failed to release settings feed", error)); + }; + }, [client, connected, supported, refetch]); +} + +/** + * The host's plugins, refetched whenever another client or the CLI changes them. A change also + * re-checks updates, whose proposals name the revision each plugin had when checked. + */ +export function useLivePluginList(serverId: string) { + const plugins = usePluginList(serverId); + const queryClient = useQueryClient(); + const { refetch } = plugins; + const refresh = useCallback(() => { + void queryClient.invalidateQueries({ queryKey: pluginUpdatesQueryKey(serverId) }); + return refetch(); + }, [queryClient, refetch, serverId]); + usePluginCatalogFeed(serverId, refresh); + return plugins; +} diff --git a/packages/app/src/plugins/gallery/routes.ts b/packages/app/src/plugins/gallery/routes.ts new file mode 100644 index 0000000000..f8677ceab9 --- /dev/null +++ b/packages/app/src/plugins/gallery/routes.ts @@ -0,0 +1,16 @@ +/** An installed plugin's page. Its settings screens open at `buildPluginSettingsRoute`. */ +export function buildPluginPageRoute(serverId: string, pluginId: string) { + return { + pathname: "/settings/hosts/[serverId]/plugins/[pluginId]" as const, + params: { serverId, pluginId }, + }; +} + +/** A directory listing's page, by its `owner/slug` ID. */ +export function buildPluginListingRoute(serverId: string, listingId: string) { + const [owner = "", slug = ""] = listingId.split("/"); + return { + pathname: "/settings/hosts/[serverId]/plugin-directory/[owner]/[slug]" as const, + params: { serverId, owner, slug }, + }; +} diff --git a/packages/app/src/plugins/gallery/skeletons.tsx b/packages/app/src/plugins/gallery/skeletons.tsx new file mode 100644 index 0000000000..ed7ca61826 --- /dev/null +++ b/packages/app/src/plugins/gallery/skeletons.tsx @@ -0,0 +1,105 @@ +import { useMemo } from "react"; +import { View, type Animated } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { SettingsCard } from "@/components/settings"; +import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton"; +import { settingsStyles } from "@/styles/settings"; + +const ROWS = [0, 1, 2, 3]; +const LINES = [0, 1, 2]; + +function RowSkeleton({ pulse }: { pulse: Animated.Value }) { + const rowStyle = useMemo(() => [settingsStyles.row, styles.row], []); + return ( + + + + + + + + + ); +} + +/** A card of plugin rows while the list or the directory loads. */ +export function PluginRowsSkeleton({ testID }: { testID?: string }) { + const pulse = useSkeletonPulse(); + return ( + + {ROWS.map((row) => ( + + ))} + + ); +} + +/** Lines of text in a card, where the overview will be. */ +export function OverviewSkeleton() { + const pulse = useSkeletonPulse(); + return ( + + + {LINES.map((line) => ( + + ))} + + + ); +} + +/** The plugin page's header and description before anything about the plugin is known. */ +export function PluginPageSkeleton() { + const pulse = useSkeletonPulse(); + return ( + + + + + + + + + + + + + + + ); +} + +// The shapes take the size of what they stand for: a row's tile and text, the page's large tile and +// name, and a button. +const styles = StyleSheet.create((theme) => { + const shape = { backgroundColor: theme.colors.surface2, borderRadius: theme.borderRadius.sm }; + return { + row: { gap: theme.spacing[3] }, + header: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[3], + marginBottom: theme.spacing[4], + }, + text: { flex: 1, minWidth: 0, gap: theme.spacing[2] }, + tile: { + ...shape, + width: theme.spacing[8], + height: theme.spacing[8], + borderRadius: theme.borderRadius.lg, + }, + tileLarge: { + ...shape, + width: theme.spacing[12], + height: theme.spacing[12], + borderRadius: theme.borderRadius.xl, + }, + name: { ...shape, width: 180, height: theme.fontSize.xl }, + title: { ...shape, width: 140, height: theme.fontSize.sm }, + line: { ...shape, width: "100%", maxWidth: 420, height: theme.fontSize.sm }, + short: { ...shape, width: "60%", maxWidth: 260, height: theme.fontSize.sm }, + control: { ...shape, width: 72, height: 28, borderRadius: theme.borderRadius.md }, + overview: { padding: theme.spacing[4], gap: theme.spacing[3] }, + description: { gap: theme.spacing[2], marginBottom: theme.spacing[6] }, + }; +}); diff --git a/packages/app/src/plugins/plugin-list.ts b/packages/app/src/plugins/plugin-list.ts index 387e0c6b56..40278883b2 100644 --- a/packages/app/src/plugins/plugin-list.ts +++ b/packages/app/src/plugins/plugin-list.ts @@ -3,13 +3,17 @@ import { useFetchQuery } from "@/data/query"; import { useHostFeature } from "@/runtime/host-features"; import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; +export function pluginListQueryKey(serverId: string) { + return ["plugins", serverId] as const; +} + /** A host's configured plugins, as listed on Settings → Plugins. One cache entry per host. */ export function usePluginList(serverId: string, options: { enabled?: boolean } = {}) { const client = useHostRuntimeClient(serverId); const connected = useHostRuntimeIsConnected(serverId); const supported = useHostFeature(serverId, "pluginManagement"); return useFetchQuery({ - queryKey: ["plugins", serverId] as const, + queryKey: pluginListQueryKey(serverId), queryFn: async () => { if (!client) throw new Error("Plugin host is offline"); return client.listPlugins(); diff --git a/packages/app/src/plugins/registry.ts b/packages/app/src/plugins/registry.ts index c291681601..8319861dc9 100644 --- a/packages/app/src/plugins/registry.ts +++ b/packages/app/src/plugins/registry.ts @@ -283,6 +283,12 @@ export function usePluginCatalogStatus(serverId: string): PluginCatalogStatus { ); } +/** Why the app could not run the plugin's client bundle, updated when the host's catalog changes. */ +export function usePluginEvaluationError(serverId: string, pluginId: string): string | undefined { + const read = () => pluginRegistry.getEvaluationError(serverId, pluginId); + return useSyncExternalStore(pluginRegistry.subscribe, read, read); +} + export function usePluginInstallations(pluginId: string): InstalledPlugin[] { const installed = useInstalledPlugins(); return useMemo(() => installed.filter((plugin) => plugin.id === pluginId), [installed, pluginId]); diff --git a/packages/app/src/plugins/settings/index.tsx b/packages/app/src/plugins/settings/index.tsx index f2e510872a..122415dace 100644 --- a/packages/app/src/plugins/settings/index.tsx +++ b/packages/app/src/plugins/settings/index.tsx @@ -3,10 +3,8 @@ import { useTranslation } from "react-i18next"; import { Platform, ScrollView, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { router } from "expo-router"; -import { ArrowLeft, Settings } from "lucide-react-native"; import type { PluginHostProps } from "@getpaseo/plugin/client"; import { Button } from "@/components/ui/button"; -import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar"; import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; import { useIsCompactFormFactor } from "@/constants/layout"; import { useHostFeature } from "@/runtime/host-features"; @@ -18,7 +16,6 @@ import type { InstalledPlugin } from "../types"; import { PluginInstallationProvider } from "../installation-provider"; import { SurfaceErrorBoundary } from "../surface-error-boundary"; import { toPluginTheme } from "../theme"; -import { buildPluginSettingsRoute } from "./routes"; interface SettingsIdentity { serverId: string; @@ -26,32 +23,6 @@ interface SettingsIdentity { screenId: string; } -const ThemedSettingsIcon = withUnistyles(Settings); -const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); - -/** Opens the plugin's settings at its first screen. Renders nothing when it has none. */ -export function PluginSettingsButton({ serverId, pluginId }: Omit) { - const { t } = useTranslation(); - const plugin = useInstalledPlugin(serverId, pluginId); - const supported = useHostFeature(serverId, "pluginSettings"); - const firstScreenId = plugin?.settingsScreens[0]?.id; - const open = useCallback(() => { - if (firstScreenId) router.push(buildPluginSettingsRoute(serverId, pluginId, firstScreenId)); - }, [serverId, pluginId, firstScreenId]); - const compact = useIsCompactFormFactor(); - if (!supported || !firstScreenId) return null; - return ( - - - - ); -} - function renderNoIcon() { return null; } @@ -172,30 +143,12 @@ function SettingsContent({ const ThemedSettingsContent = withUnistyles(SettingsContent); // Settings routes carry no screen params. const themeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) }); -export function PluginSettingsContent({ - onBackToPlugins, - showBackToPlugins, - ...identity -}: SettingsIdentity & { onBackToPlugins: () => void; showBackToPlugins: boolean }) { - const { t } = useTranslation(); - return ( - - {showBackToPlugins ? ( - - ) : null} - - - ); + +/** One of the plugin's settings screens, with tabs to the others. Renders inside its plugin page. */ +export function PluginSettingsContent(identity: SettingsIdentity) { + return ; } const styles = StyleSheet.create((theme) => ({ message: { color: theme.colors.foregroundMuted }, tabs: { flexGrow: 0, marginBottom: theme.spacing[4] }, - backButton: { alignSelf: "flex-start", paddingHorizontal: 0, marginBottom: theme.spacing[4] }, })); diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 1d98e8e288..7fc6dbe248 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -108,9 +108,12 @@ import { HostWorkspacesPage, HostTerminalsPage, } from "@/screens/settings/host-page"; -import { PluginSettingsContent } from "@/plugins/settings"; -import { usePluginDisplayName } from "@/plugins/plugin-list"; -import { HostPluginsPage } from "@/screens/settings/plugins-page"; +import { + PluginGalleryMenu, + PluginGalleryPage, + PluginPage, + type PluginPageSubject, +} from "@/plugins/gallery"; import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-page"; import { HostVoicePage } from "@/screens/settings/voice/voice-page"; import ProjectsScreen from "@/screens/projects-screen"; @@ -280,7 +283,7 @@ function renderHostSettingsContent( case "terminals": return ; case "plugins": - return ; + return ; case "host": return ; } @@ -987,7 +990,7 @@ function SettingsSidebar({ let selectedHostSection: HostSectionSlug | null = null; if (view.kind === "host") selectedHostSection = view.section; if (view.kind === "project") selectedHostSection = "projects"; - if (view.kind === "plugin") selectedHostSection = "plugins"; + if (view.kind === "plugin" || view.kind === "pluginListing") selectedHostSection = "plugins"; const sidebarBody = ( <> @@ -1130,7 +1133,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { // The host the four sections scope to: the host on the active view, otherwise // the picker choice, otherwise the connected local daemon, otherwise the first host. const activeHostServerId = useMemo(() => { - if (view.kind === "host" || view.kind === "project" || view.kind === "plugin") + if ( + view.kind === "host" || + view.kind === "project" || + view.kind === "plugin" || + view.kind === "pluginListing" + ) return view.serverId; return resolveActiveHostServerId({ selectedServerId: selectedSettingsHostServerId, @@ -1263,10 +1271,20 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { returnFromSettings({ kind: "root" }); }, []); - // The header names the plugin; its tabs name the open settings screen. - const pluginDisplayName = usePluginDisplayName(view.kind === "plugin" ? view : null); + // A plugin's page draws its own header; the compact back header names the plugin. + const pluginPage = useMemo((): { serverId: string; subject: PluginPageSubject } | null => { + if (view.kind === "plugin") + return { + serverId: view.serverId, + subject: { kind: "installed", pluginId: view.pluginId, screenId: view.screenId }, + }; + if (view.kind === "pluginListing") + return { serverId: view.serverId, subject: { kind: "listing", listingId: view.listingId } }; + return null; + }, [view]); const detailTitle = ((): string | undefined => { - if (view.kind === "plugin") return pluginDisplayName; + // The plugin page heads itself with the plugin's name and icon. + if (pluginPage) return undefined; if (view.kind === "host") { const item = HOST_SECTION_ITEMS.find((s) => s.id === view.section); return item ? t(item.labelKey) : undefined; @@ -1281,15 +1299,23 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { return undefined; })(); + const pluginGalleryServerId = + view.kind === "host" && view.section === "plugins" ? view.serverId : null; + const detailActions = useMemo( + () => + pluginGalleryServerId ? : undefined, + [pluginGalleryServerId], + ); + // The gallery and a plugin's page share one width, so opening a plugin keeps the page edges put. + const detailWidth = pluginGalleryServerId || pluginPage ? "wide" : "default"; + const content: ReactNode = (() => { - if (view.kind === "plugin") + if (pluginPage) return ( - ); if (view.kind === "host") { @@ -1373,7 +1399,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { if (isCompactLayout) { return ( - + {content} @@ -1402,6 +1433,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { diff --git a/packages/app/src/screens/settings/plugin-install-form-model.test.ts b/packages/app/src/screens/settings/plugin-install-form-model.test.ts deleted file mode 100644 index 3ee48f43d7..0000000000 --- a/packages/app/src/screens/settings/plugin-install-form-model.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { openPluginInstallForm } from "./plugin-install-form-model"; - -describe("plugin install form", () => { - it("keeps the edited source in the submission until explicitly reset", () => { - const model = openPluginInstallForm(); - - model.setSource("owner/review"); - - expect(model.getSubmission()).toEqual({ source: "owner/review" }); - - model.reset(); - expect(model.getState()).toEqual({ - source: "", - canSubmit: false, - resetKey: 1, - }); - }); - - it("trims the submitted source", () => { - const model = openPluginInstallForm(); - model.setSource(" /plugins/review "); - expect(model.getSubmission()).toEqual({ source: "/plugins/review" }); - }); -}); diff --git a/packages/app/src/screens/settings/plugin-install-form-model.ts b/packages/app/src/screens/settings/plugin-install-form-model.ts deleted file mode 100644 index 82fbfa12e2..0000000000 --- a/packages/app/src/screens/settings/plugin-install-form-model.ts +++ /dev/null @@ -1,53 +0,0 @@ -export interface PluginInstallFormState { - source: string; - canSubmit: boolean; - resetKey: number; -} - -export interface PluginInstallSubmission { - source: string; -} - -export interface PluginInstallFormModel { - getState(): PluginInstallFormState; - subscribe(listener: () => void): () => void; - close(): void; - setSource(value: string): void; - getSubmission(): PluginInstallSubmission; - reset(): void; -} - -export function openPluginInstallForm(): PluginInstallFormModel { - const listeners = new Set<() => void>(); - let state: PluginInstallFormState = { - source: "", - canSubmit: false, - resetKey: 0, - }; - - const publish = (next: Pick) => { - state = { ...next, canSubmit: next.source.trim().length > 0 }; - for (const listener of listeners) listener(); - }; - - return { - getState: () => state, - subscribe(listener) { - listeners.add(listener); - return () => listeners.delete(listener); - }, - close() { - listeners.clear(); - }, - setSource(source) { - publish({ ...state, source }); - }, - getSubmission() { - const source = state.source.trim(); - return { source }; - }, - reset() { - publish({ source: "", resetKey: state.resetKey + 1 }); - }, - }; -} diff --git a/packages/app/src/screens/settings/plugins-page-state.test.ts b/packages/app/src/screens/settings/plugins-page-state.test.ts deleted file mode 100644 index 192436029f..0000000000 --- a/packages/app/src/screens/settings/plugins-page-state.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { resolvePluginPageState } from "./plugins-page-state"; - -describe("resolvePluginPageState", () => { - it.each([ - ["offline", false, false, false, false, 0], - ["unsupported", true, false, false, false, 0], - ["loading", true, true, true, false, 0], - ["error", true, true, false, true, 0], - ["empty", true, true, false, false, 0], - ["ready", true, true, false, false, 1], - ] as const)("resolves %s", (expected, connected, supported, loading, error, pluginCount) => { - expect(resolvePluginPageState({ connected, supported, loading, error, pluginCount })).toBe( - expected, - ); - }); -}); diff --git a/packages/app/src/screens/settings/plugins-page-state.ts b/packages/app/src/screens/settings/plugins-page-state.ts deleted file mode 100644 index 0623dca047..0000000000 --- a/packages/app/src/screens/settings/plugins-page-state.ts +++ /dev/null @@ -1,15 +0,0 @@ -export type PluginPageState = "offline" | "unsupported" | "loading" | "error" | "empty" | "ready"; - -export function resolvePluginPageState(input: { - connected: boolean; - supported: boolean; - loading: boolean; - error: boolean; - pluginCount: number; -}): PluginPageState { - if (!input.connected) return "offline"; - if (!input.supported) return "unsupported"; - if (input.loading) return "loading"; - if (input.error) return "error"; - return input.pluginCount === 0 ? "empty" : "ready"; -} diff --git a/packages/app/src/screens/settings/plugins-page.test.tsx b/packages/app/src/screens/settings/plugins-page.test.tsx deleted file mode 100644 index dfb16ccfa7..0000000000 --- a/packages/app/src/screens/settings/plugins-page.test.tsx +++ /dev/null @@ -1,257 +0,0 @@ -import { subscriptionFixture } from "@/runtime/subscription-fixture"; -/** - * @vitest-environment jsdom - */ -import { i18n as testI18n } from "@/i18n/i18next"; -import React, { type ReactElement } from "react"; -import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; -import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { HostPluginsPage } from "./plugins-page"; - -void testI18n; - -const runtime = vi.hoisted(() => ({ - connected: true, - supported: true, - logsSupported: true, - client: null as DaemonClient | null, -})); - -vi.mock("@/runtime/host-runtime", async (importOriginal) => ({ - ...(await importOriginal()), - useHostRuntimeClient: () => runtime.client, - useHostRuntimeIsConnected: () => runtime.connected, -})); - -vi.mock("@/runtime/host-features", () => ({ - useHostFeature: (_serverId: string, feature: string) => { - if (feature === "pluginLogs") return runtime.logsSupported; - return runtime.supported; - }, -})); - -vi.mock("@/components/adaptive-modal-sheet", async () => { - const ReactModule = await vi.importActual("react"); - const actual = await vi.importActual( - "@/components/adaptive-modal-sheet", - ); - return { - ...actual, - AdaptiveModalSheet: ({ - header, - children, - onClose, - }: { - header: { title: string; actions?: React.ReactNode }; - children: React.ReactNode; - onClose(): void; - }) => - ReactModule.createElement( - "div", - { role: "dialog" }, - ReactModule.createElement("h2", null, header.title), - header.actions, - ReactModule.createElement("button", { type: "button", onClick: onClose }, "Close"), - children, - ), - }; -}); - -vi.mock("react-native-reanimated", () => ({ - default: { View: "div" }, - Keyframe: class { - duration() { - return this; - } - }, - Easing: { ease: "ease", inOut: (value: unknown) => value }, - interpolateColor: (value: number, _input: number[], output: string[]) => - value >= 1 ? output[1] : output[0], - useAnimatedStyle: (factory: () => unknown) => factory(), - useDerivedValue: (factory: () => unknown) => ({ value: factory() }), - withTiming: (value: unknown) => value, -})); - -vi.mock("@gorhom/bottom-sheet", async () => { - const ReactModule = await vi.importActual("react"); - const { ScrollView, TextInput } = - await vi.importActual("react-native"); - return { - BottomSheetBackdrop: () => null, - BottomSheetHandle: () => null, - BottomSheetModal: ReactModule.forwardRef(() => null), - BottomSheetScrollView: ScrollView, - BottomSheetTextInput: TextInput, - useBottomSheetInternal: () => null, - }; -}); - -vi.mock("react-native-safe-area-context", () => ({ - useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }), -})); - -function plugin(enabled = true): PluginListItem { - return { - id: "example", - description: "Reviews changes before merge", - path: "/plugins/example", - enabled, - status: enabled ? "running" : "disabled", - }; -} - -async function selectPluginAction(action: string): Promise { - fireEvent.click(await screen.findByRole("button", { name: "Actions for example" })); - fireEvent.click(await screen.findByRole("menuitem", { name: action })); -} - -function createClient() { - return { - observeEvents: () => - subscriptionFixture( - Promise.resolve({ events: ["status.plugin_catalog_changed"] }), - () => () => {}, - ), - getDaemonConfig: vi.fn(async () => ({ config: { pluginsEnabled: true } })), - patchDaemonConfig: vi.fn(async () => ({ config: { pluginsEnabled: true } })), - listPlugins: vi.fn(async (): Promise => []), - installPluginSource: vi.fn(async () => plugin()), - reloadPlugin: vi.fn(async () => plugin()), - enablePlugin: vi.fn(async () => plugin()), - disablePlugin: vi.fn(async () => plugin(false)), - removePlugin: vi.fn(async () => undefined), - getPluginLogs: vi.fn(async (): Promise => []), - }; -} - -type PluginClient = ReturnType; - -function renderPage(client: PluginClient | null): void { - runtime.client = client as unknown as DaemonClient | null; - const queryClient = new QueryClient({ - defaultOptions: { - queries: { retry: false }, - mutations: { retry: false }, - }, - }); - const element: ReactElement = ( - - - - ); - render(element); -} - -describe("HostPluginsPage", () => { - beforeEach(() => { - vi.stubGlobal("React", React); - runtime.connected = true; - runtime.supported = true; - runtime.logsSupported = true; - runtime.client = null; - vi.stubGlobal( - "confirm", - vi.fn(() => true), - ); - }); - - afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - }); - - it("renders the offline state", () => { - runtime.connected = false; - renderPage(null); - - expect(screen.getByRole("alert").textContent).toContain("Plugin host is offline"); - }); - - it("renders a catalog error and retries through the real query", async () => { - const client = createClient(); - client.listPlugins.mockRejectedValueOnce(new Error("catalog exploded")); - renderPage(client); - - expect(await screen.findByText("Unable to load plugins")).toBeDefined(); - expect(screen.getByText("catalog exploded")).toBeDefined(); - - fireEvent.click(screen.getByRole("button", { name: "Retry" })); - - await waitFor(() => expect(client.listPlugins).toHaveBeenCalledTimes(2)); - expect(await screen.findByText("No plugins configured")).toBeDefined(); - }); - - it.each([ - ["reloadPlugin", "Reload"], - ["removePlugin", "Remove"], - ] as const)("runs %s from the plugin actions menu", async (method, action) => { - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - renderPage(client); - - await selectPluginAction(action); - - await waitFor(() => expect(client[method]).toHaveBeenCalledTimes(1)); - }); - - it("hides the logs action when the host does not advertise support", async () => { - runtime.logsSupported = false; - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - renderPage(client); - - await screen.findByText("example"); - fireEvent.click(screen.getByRole("button", { name: "Actions for example" })); - expect(screen.queryByRole("menuitem", { name: "Logs" })).toBeNull(); - }); - - it("opens readable stdout and stderr logs and refreshes them", async () => { - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - client.getPluginLogs.mockResolvedValue([ - { - sequence: 1, - timestamp: "2026-08-16T12:00:00.000Z", - stream: "stdout", - message: "ready", - }, - { - sequence: 2, - timestamp: "2026-08-16T12:00:01.000Z", - stream: "stderr", - message: "warning", - }, - ]); - renderPage(client); - - await selectPluginAction("Logs"); - - expect(await screen.findByRole("dialog")).toBeDefined(); - expect(screen.getByText("Logs: example")).toBeDefined(); - expect(await screen.findByText("ready")).toBeDefined(); - expect(screen.getByText("warning")).toBeDefined(); - expect(screen.getByText(/stdout/)).toBeDefined(); - expect(screen.getByText(/stderr/)).toBeDefined(); - - fireEvent.click(screen.getByRole("button", { name: "Refresh" })); - await waitFor(() => expect(client.getPluginLogs).toHaveBeenCalledTimes(2)); - }); - - it("shows empty and recoverable error states for plugin logs", async () => { - const client = createClient(); - client.listPlugins.mockResolvedValue([plugin()]); - client.getPluginLogs.mockRejectedValueOnce(new Error("logs exploded")); - renderPage(client); - - await selectPluginAction("Logs"); - expect(await screen.findByText("Unable to load plugin logs")).toBeDefined(); - expect(screen.getByText("logs exploded")).toBeDefined(); - - fireEvent.click(screen.getAllByRole("button", { name: "Refresh" }).at(-1)!); - await waitFor(() => expect(client.getPluginLogs).toHaveBeenCalledTimes(2)); - expect(await screen.findByText("No plugin output yet")).toBeDefined(); - }); -}); diff --git a/packages/app/src/screens/settings/plugins-page.tsx b/packages/app/src/screens/settings/plugins-page.tsx deleted file mode 100644 index 946978e434..0000000000 --- a/packages/app/src/screens/settings/plugins-page.tsx +++ /dev/null @@ -1,590 +0,0 @@ -import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference"; -import { PluginSettingsButton } from "@/plugins/settings"; -import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; -import { useTranslation } from "react-i18next"; -import { Text, View } from "react-native"; -import { StyleSheet } from "react-native-unistyles"; -import { useMutation } from "@tanstack/react-query"; -import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages"; -import { MoreHorizontal, RotateCw, Trash2 } from "lucide-react-native"; -import { - AdaptiveModalSheet, - SheetHeaderIconButton, - type SheetHeader, -} from "@/components/adaptive-modal-sheet"; -import { SettingsCard, SettingsRow } from "@/components/settings"; -import { Alert } from "@/components/ui/alert"; -import { Button } from "@/components/ui/button"; -import { ExternalLink } from "@/components/ui/external-link"; -import { Field, FormTextInput } from "@/components/ui/form-field"; -import { StatusBadge } from "@/components/ui/status-badge"; -import { Switch } from "@/components/ui/switch"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { useFetchQuery } from "@/data/query"; -import { useDaemonConfig } from "@/hooks/use-daemon-config"; -import { useHostFeature } from "@/runtime/host-features"; -import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime"; -import { SettingsSection } from "@/components/settings/headings/settings-section"; -import { resolvePluginPageState } from "@/screens/settings/plugins-page-state"; -import { openPluginInstallForm } from "@/screens/settings/plugin-install-form-model"; -import { pluginRegistry, useInstalledPlugins } from "@/plugins/registry"; -import { pluginDisplayName, usePluginList } from "@/plugins/plugin-list"; -import { settingsStyles } from "@/styles/settings"; -import { confirmDialog } from "@/utils/confirm-dialog"; - -const PLUGIN_SOURCE_DOCS_URL = "https://paseo.sh/docs/plugins/reference#plugin-sources"; -type PluginRowAction = "reload" | "enable" | "disable" | "remove"; - -function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); -} - -function pluginRowAction(action: string | undefined): PluginRowAction | undefined { - if (action === "reload" || action === "enable" || action === "disable" || action === "remove") { - return action; - } - return undefined; -} - -function PluginActionsMenu({ - plugin, - pending, - pendingAction, - onAction, - onOpenLogs, - supportsLogs, -}: { - plugin: PluginListItem; - pending: boolean; - pendingAction?: PluginRowAction; - onAction(action: PluginRowAction, plugin: PluginListItem): void; - onOpenLogs(plugin: PluginListItem): void; - supportsLogs: boolean; -}) { - const { t } = useTranslation(); - const reload = useCallback(() => onAction("reload", plugin), [onAction, plugin]); - const remove = useCallback(() => onAction("remove", plugin), [onAction, plugin]); - const openLogs = useCallback(() => onOpenLogs(plugin), [onOpenLogs, plugin]); - const removeIcon = useMemo(() => , []); - const menuLabel = t("settings.plugins.actions.menu", { name: pluginDisplayName(plugin) }); - - return ( - - - - - - {supportsLogs ? ( - - {t("settings.plugins.logs.action")} - - ) : null} - - {t("settings.plugins.actions.reload")} - - - {t("settings.plugins.actions.remove")} - - - - ); -} - -function PluginRow({ - plugin, - serverId, - clientError, - pending, - pendingAction, - onAction, - onOpenLogs, - supportsLogs, -}: { - plugin: PluginListItem; - serverId: string; - clientError?: string; - pending: boolean; - pendingAction?: PluginRowAction; - onAction(action: PluginRowAction, plugin: PluginListItem): void; - onOpenLogs(plugin: PluginListItem): void; - supportsLogs: boolean; -}) { - const { t } = useTranslation(); - const toggle = useCallback( - (enabled: boolean) => onAction(enabled ? "enable" : "disable", plugin), - [onAction, plugin], - ); - const status = clientError ? "failed" : plugin.status; - let badgeVariant: "success" | "error" | "muted" = "muted"; - if (status === "running") badgeVariant = "success"; - else if (status === "failed") badgeVariant = "error"; - const statusLabel = t(`settings.plugins.status.${status}`); - const statusBadge = useMemo( - () => , - [badgeVariant, statusLabel], - ); - const name = pluginDisplayName(plugin); - // A display name hides the id that the CLI and plugin routes use, so show it beneath. - const shownId = name === plugin.id ? null : plugin.id; - const hint = useMemo( - () => - shownId || plugin.description || plugin.installation ? ( - - {shownId ? {shownId} : null} - {plugin.description ? ( - {plugin.description} - ) : null} - {plugin.installation ? ( - {formatPluginInstallation(plugin.installation)} - ) : null} - - ) : undefined, - [shownId, plugin.description, plugin.installation], - ); - const toggleLabel = `${name}: ${t( - plugin.enabled ? "settings.plugins.actions.disable" : "settings.plugins.actions.enable", - )}`; - return ( - - - - - - - - ); -} - -function PluginLogsSheet({ - client, - plugin, - serverId, - onClose, -}: { - client: NonNullable>; - plugin: PluginListItem; - serverId: string; - onClose(): void; -}) { - const pluginId = plugin.id; - const { t } = useTranslation(); - const logs = useFetchQuery({ - queryKey: ["plugin-logs", serverId, pluginId], - queryFn: () => client.getPluginLogs(pluginId), - dataShape: "list", - staleTimeMs: 0, - }); - const refresh = useCallback(() => { - void logs.refetch(); - }, [logs]); - const header = useMemo( - () => ({ - title: t("settings.plugins.logs.title", { name: pluginDisplayName(plugin) }), - actions: ( - - ), - }), - [logs.isFetching, plugin, refresh, t], - ); - - let content = {t("settings.plugins.logs.loading")}; - if (logs.isError) { - content = ( - - - - ); - } else if (!logs.isLoading) { - content = logs.data?.length ? ( - - {logs.data.map((entry: PluginLogEntry) => ( - - - {entry.timestamp} {entry.stream} - - {entry.message} - - ))} - - ) : ( - {t("settings.plugins.logs.empty")} - ); - } - - return ( - - {content} - - ); -} - -export function HostPluginsPage({ serverId }: { serverId: string }) { - const { t } = useTranslation(); - const client = useHostRuntimeClient(serverId); - const connected = useHostRuntimeIsConnected(serverId); - const supported = useHostFeature(serverId, "pluginManagement"); - // COMPAT(pluginSourceInstallation): added in v0.8.0; remove gate after 2027-03-16 once daemon floor supports source identifiers. - const sourceInstallSupported = useHostFeature(serverId, "pluginSourceInstallation"); - // COMPAT(pluginLogs): added in v0.4.0, remove gate after 2027-08-16. - const logsSupported = useHostFeature(serverId, "pluginLogs"); - const { config, patchConfig } = useDaemonConfig(serverId); - const refreshQueue = useRef(Promise.resolve()); - useInstalledPlugins(); - const [installForm] = useState(openPluginInstallForm); - const installState = useSyncExternalStore( - installForm.subscribe, - installForm.getState, - installForm.getState, - ); - const sourceDocsLink = useMemo( - () => ( - - ), - [t], - ); - const [logsPlugin, setLogsPlugin] = useState(null); - const [feedback, setFeedback] = useState<{ kind: "success" | "error"; message: string } | null>( - null, - ); - const plugins = usePluginList(serverId); - const refetchPlugins = plugins.refetch; - const refresh = useCallback(async () => { - if (!client) return; - const refetch = async () => { - await refetchPlugins(); - }; - refreshQueue.current = refreshQueue.current.then(refetch, refetch); - await refreshQueue.current; - }, [client, refetchPlugins]); - useEffect(() => { - return () => installForm.close(); - }, [installForm]); - useEffect(() => { - if (!client || !connected || !supported) return; - const observation = client.observeEvents(["status.plugin_catalog_changed"]); - observation.subscribe({ - snapshot: () => {}, - update: (message) => { - if (message.type === "status" && message.payload.status === "plugin_catalog_changed") - void refresh(); - }, - }); - return () => { - void observation - .release() - .catch((error) => console.warn("[Plugins] Failed to release settings feed", error)); - }; - }, [client, connected, supported, refresh]); - const mutation = useMutation({ - mutationFn: async (operation: { - action: string; - pluginId?: string; - run: () => Promise; - }) => operation.run(), - onSuccess: async (message) => { - setFeedback({ kind: "success", message }); - await refresh(); - }, - onError: (error) => setFeedback({ kind: "error", message: errorMessage(error) }), - }); - const install = useCallback(() => { - if (!client || !sourceInstallSupported || !installState.canSubmit) return; - const input = installForm.getSubmission(); - setFeedback(null); - mutation.mutate({ - action: "install", - run: async () => { - const installed = await client.installPluginSource(input); - installForm.reset(); - return t("settings.plugins.feedback.installed", { name: pluginDisplayName(installed) }); - }, - }); - }, [client, installForm, installState.canSubmit, mutation, sourceInstallSupported, t]); - const action = useCallback( - (name: PluginRowAction, plugin: PluginListItem) => { - if (!client) return; - const pluginName = pluginDisplayName(plugin); - const run = async () => { - if (name === "remove") { - const confirmed = await confirmDialog({ - title: t("settings.plugins.removeConfirmTitle", { name: pluginName }), - message: t("settings.plugins.removeConfirmMessage"), - confirmLabel: t("settings.plugins.actions.remove"), - destructive: true, - }); - if (!confirmed) return t("settings.plugins.feedback.kept", { name: pluginName }); - await client.removePlugin(plugin.id); - } else { - await client[`${name}Plugin`](plugin.id); - } - return t(`settings.plugins.feedback.${name}`, { name: pluginName }); - }; - setFeedback(null); - mutation.mutate({ action: name, pluginId: plugin.id, run }); - }, - [client, mutation, t], - ); - const toggleGlobal = useCallback( - (enabled: boolean) => { - setFeedback(null); - mutation.mutate({ - action: enabled ? "global-enable" : "global-disable", - run: async () => { - await patchConfig({ pluginsEnabled: enabled }); - return enabled - ? t("settings.plugins.feedback.globalEnabled") - : t("settings.plugins.feedback.globalDisabled"); - }, - }); - }, - [mutation, patchConfig, t], - ); - const pageState = resolvePluginPageState({ - connected, - supported, - loading: plugins.isLoading, - error: plugins.isError, - pluginCount: plugins.data?.length ?? 0, - }); - const retry = useCallback(() => { - void refetchPlugins(); - }, [refetchPlugins]); - const closeLogs = useCallback(() => setLogsPlugin(null), []); - - if (pageState === "offline") { - return ( - - ); - } - if (pageState === "unsupported") { - return ; - } - - let catalogContent = ; - if (pageState === "error") { - catalogContent = ( - - - - ); - } else if (pageState !== "loading") { - catalogContent = ( - - {plugins.data?.length ? ( - plugins.data.map((plugin) => { - const clientError = pluginRegistry.getEvaluationError(serverId, plugin.id); - const pending = mutation.isPending && mutation.variables?.pluginId === plugin.id; - return ( - - ); - }) - ) : ( - - {t("settings.plugins.states.empty")} - - )} - - ); - } - - return ( - - - - - - - {t("settings.plugins.globalTitle")} - {t("settings.plugins.globalHint")} - - - - - {sourceInstallSupported ? ( - - - - - - - ) : ( - - )} - {feedback ? ( - - ) : null} - {catalogContent} - - {client && logsPlugin ? ( - - ) : null} - - ); -} - -const styles = StyleSheet.create((theme) => ({ - pluginDescription: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - marginTop: theme.spacing[1], - }, - pluginSource: { - color: theme.colors.foregroundExtraMuted, - fontSize: theme.fontSize.sm, - marginTop: theme.spacing[1], - }, - install: { padding: theme.spacing[4], gap: theme.spacing[3] }, - pluginControls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] }, - menuButton: { padding: theme.spacing[1], borderRadius: theme.borderRadius.sm }, - menuIcon: { color: theme.colors.foregroundMuted }, - dangerIcon: { color: theme.colors.statusDanger }, - empty: { padding: theme.spacing[4], alignItems: "center" }, - logsState: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - textAlign: "center", - paddingVertical: theme.spacing[6], - }, - logList: { gap: theme.spacing[2] }, - logEntry: { - padding: theme.spacing[3], - gap: theme.spacing[1], - backgroundColor: theme.colors.surface2, - borderRadius: theme.borderRadius.md, - }, - logStdout: { - color: theme.colors.foregroundMuted, - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.sm, - }, - logStderr: { - color: theme.colors.statusDanger, - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.sm, - }, - logMessage: { - color: theme.colors.foreground, - fontFamily: theme.fontFamily.mono, - fontSize: theme.fontSize.base, - }, -})); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index a401de273f..6ab5e64f32 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -16,6 +16,7 @@ import { } from "@getpaseo/protocol/binary-frames/index"; import { messageTooLargeError } from "./daemon-client-transport-utils.js"; import type { HostAdd, HostUpdate, HostDirectory } from "@getpaseo/protocol/hosts"; +import type { PluginListingDetail, PluginListingIndex } from "@getpaseo/protocol/plugin-registry"; import { legacyUsageIcon } from "./legacy-usage-icons.js"; import { subscribeTimeline, type TimelineMessage } from "./timeline-subscription/index.js"; import { ProviderSnapshotUpdates } from "./provider-snapshots/index.js"; @@ -6575,6 +6576,38 @@ export class DaemonClient { return payload.plugins; } + private requirePluginRegistry(): void { + // COMPAT(pluginRegistry): added in v0.16.0; remove after 2027-05-15 once daemon floor proxies the registry. + if (this.getLastServerInfoMessage()?.features?.pluginRegistry !== true) + throw new Error("Update the host to browse plugins."); + } + + /** The host's default plugin registry directory. */ + async listPluginRegistry(): Promise { + this.requirePluginRegistry(); + const requestId = this.createRequestId(); + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "plugin.registry.list.request", requestId }, + responseType: "plugin.registry.list.response", + timeout: 60_000, + }); + return payload.index; + } + + /** One registry listing with its overview. */ + async getRegistryPlugin(id: string): Promise { + this.requirePluginRegistry(); + const requestId = this.createRequestId(); + const payload = await this.sendCorrelatedSessionRequest({ + requestId, + message: { type: "plugin.registry.get.request", requestId, id }, + responseType: "plugin.registry.get.response", + timeout: 60_000, + }); + return payload.plugin; + } + private requirePluginUpdates(): void { // COMPAT(pluginSourceUpdates): added in v0.8.0; remove after 2027-03-16 once daemon floor supports reviewed updates. if (this.getLastServerInfoMessage()?.features?.pluginSourceUpdates !== true) diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index ab903ac898..e62cf8357e 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -19,7 +19,12 @@ import { HostsRouteFrameSchema, HostsRouteClosedSchema, } from "./hosts.js"; -import { PluginRegistryIdentitySchema } from "./plugin-registry.js"; +import { + PluginRegistryIdSchema, + PluginRegistryIdentitySchema, + PluginListingDetailSchema, + PluginListingIndexSchema, +} from "./plugin-registry.js"; import { AgentProfileSchema, AgentSkillSelectionSchema } from "./agent-profile.js"; export { AgentProfileSchema, @@ -1673,6 +1678,17 @@ export const PluginSourceStatusRequestSchema = z.object({ pluginId: PluginIdSchema.optional(), }); +export const PluginRegistryListRequestSchema = z.object({ + type: z.literal("plugin.registry.list.request"), + requestId: z.string(), +}); + +export const PluginRegistryGetRequestSchema = z.object({ + type: z.literal("plugin.registry.get.request"), + requestId: z.string(), + id: PluginRegistryIdSchema, +}); + export const PluginSourceUpdateRequestSchema = z.object({ type: z.literal("plugin.source.update.request"), requestId: z.string(), @@ -3560,6 +3576,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ PluginDirectoryInspectRequestSchema, PluginSourceInstallRequestSchema, PluginSourceStatusRequestSchema, + PluginRegistryListRequestSchema, + PluginRegistryGetRequestSchema, PluginSourceUpdateRequestSchema, PluginUpdatePreviewRequestSchema, PluginUpdateApplyRequestSchema, @@ -3973,6 +3991,8 @@ export const ServerInfoStatusPayloadSchema = z pluginSourceInstallation: z.boolean().optional(), // COMPAT(pluginSourceUpdates): added in v0.8.0; remove gate after 2027-03-16 once daemon floor supports reviewed updates. pluginSourceUpdates: z.boolean().optional(), + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + pluginRegistry: z.boolean().optional(), // COMPAT(pluginThemes): added in v0.5.0, remove gate after 2027-08-20. // A daemon that predates this flag keeps `addTheme` in the server bundle it compiles, // so a theme plugin cannot start there at all. @@ -7259,6 +7279,17 @@ export const PluginSourceStatusItemSchema = z.object({ }); export type PluginSourceStatusItem = z.infer; +/** The host's plugin directory index, fetched by the daemon from its configured registry. */ +export const PluginRegistryListResponseSchema = z.object({ + type: z.literal("plugin.registry.list.response"), + payload: z.object({ requestId: z.string(), index: PluginListingIndexSchema }), +}); + +export const PluginRegistryGetResponseSchema = z.object({ + type: z.literal("plugin.registry.get.response"), + payload: z.object({ requestId: z.string(), plugin: PluginListingDetailSchema }), +}); + export const PluginSourceStatusResponseSchema = z.object({ type: z.literal("plugin.source.status.response"), payload: z.object({ requestId: z.string(), plugins: z.array(PluginSourceStatusItemSchema) }), @@ -7409,6 +7440,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ PluginDirectoryInspectResponseSchema, PluginSourceInstallResponseSchema, PluginSourceStatusResponseSchema, + PluginRegistryListResponseSchema, + PluginRegistryGetResponseSchema, PluginSourceUpdateResponseSchema, PluginUpdatePreviewResponseSchema, PluginUpdateApplyResponseSchema, diff --git a/packages/protocol/src/plugin-registry.test.ts b/packages/protocol/src/plugin-registry.test.ts index c923193a36..d7b06fd77e 100644 --- a/packages/protocol/src/plugin-registry.test.ts +++ b/packages/protocol/src/plugin-registry.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { + PluginListingIndexSchema, PluginRegistryIndexSchema, PublishedPluginDetailSchema, pluginMediaKind, @@ -81,3 +82,15 @@ describe("plugin listing translations", () => { expect(result.success).toBe(false); }); }); + +describe("plugin listings sent to apps", () => { + it("keep a listing whose artifact kind or index version the app does not know", () => { + const future = { ...LEGACY_PLUGIN, id: "acme/future", artifact: { kind: "oci", image: "x" } }; + const index = PluginListingIndexSchema.parse({ + ...LEGACY_INDEX, + schemaVersion: 2, + plugins: [LEGACY_PLUGIN, future], + }); + expect(index.plugins.map((plugin) => plugin.artifact.kind)).toEqual(["git", "oci"]); + }); +}); diff --git a/packages/protocol/src/plugin-registry.ts b/packages/protocol/src/plugin-registry.ts index 08bbf07f18..bd08057176 100644 --- a/packages/protocol/src/plugin-registry.ts +++ b/packages/protocol/src/plugin-registry.ts @@ -79,12 +79,43 @@ export const PluginRegistryIndexSchema = z.object({ featured: z.array(z.string()), generatedAt: z.string(), }); + +/** + * A listing as a host sends it to apps. The registry's schema is closed, so its artifact is open + * here: an app older than its host keeps listing plugins whose artifact kind it does not know, and + * installs them through the host by ID. + */ +const PluginListingArtifactSchema = z.object({ + kind: z.string(), + package: z.string().optional(), + version: z.string().optional(), + commit: z.string().optional(), +}); +export const PluginListingSchema = PublishedPluginSchema.extend({ + artifact: PluginListingArtifactSchema, +}); +export const PluginListingDetailSchema = PublishedPluginDetailSchema.extend({ + artifact: PluginListingArtifactSchema, +}); +export const PluginListingIndexSchema = PluginRegistryIndexSchema.extend({ + schemaVersion: z.number().int(), + plugins: z.array(PluginListingSchema), +}); +export type PluginListing = z.infer; +export type PluginListingDetail = z.infer; +export type PluginListingIndex = z.infer; + export type PluginRegistryIdentity = z.infer; export type PluginRegistries = z.infer; +export type PublishedPlugin = z.infer; +export type PublishedPluginDetail = z.infer; +export type PluginRegistryIndex = z.infer; + +export const DEFAULT_PLUGIN_REGISTRY_URL = "https://plugins.paseo.sh"; export function parsePluginRegistryReference( source: string, - defaultUrl = "https://plugins.paseo.sh", + defaultUrl = DEFAULT_PLUGIN_REGISTRY_URL, ): PluginRegistryIdentity | null { const segments = source.split("/"); if (segments.length === 2 && PluginRegistryIdSchema.safeParse(source).success) diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 1f44e10dc4..2015316b07 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -149,6 +149,8 @@ const INBOUND_PERMISSION = { "plugin.rpc.subscribe.request": "daemon.manage", "plugin.source.install.request": "daemon.manage", "plugin.source.status.request": "daemon.manage", + "plugin.registry.list.request": "daemon.manage", + "plugin.registry.get.request": "daemon.manage", "plugin.source.update.request": "daemon.manage", "plugin.source.update.preview.request": "daemon.manage", "plugin.source.update.apply.request": "daemon.manage", @@ -399,6 +401,8 @@ const OUTBOUND_PERMISSION = { "plugin.rpc.closed": "daemon.manage", "plugin.source.install.response": "daemon.manage", "plugin.source.status.response": "daemon.manage", + "plugin.registry.list.response": "daemon.manage", + "plugin.registry.get.response": "daemon.manage", "plugin.source.update.response": "daemon.manage", "plugin.source.update.preview.response": "daemon.manage", "plugin.source.update.apply.response": "daemon.manage", diff --git a/packages/server/src/server/checkout-diff-manager.test.ts b/packages/server/src/server/checkout-diff-manager.test.ts index e1f0e25a33..8274bad3ff 100644 --- a/packages/server/src/server/checkout-diff-manager.test.ts +++ b/packages/server/src/server/checkout-diff-manager.test.ts @@ -260,7 +260,7 @@ test("legacy diffs retain successful bodies when an oversized sibling is removed ]); await rm(join(cwd, "b.txt")); await manager.scheduleRefreshForCwd(cwd); - await expect.poll(() => updates.at(-1)?.error).toBeNull(); + await expect.poll(() => updates.at(-1)?.error, { timeout: 10000 }).toBeNull(); expect(updates.at(-1)?.files[0]).toMatchObject({ path: "a.ts", hunks: [ @@ -271,7 +271,7 @@ test("legacy diffs retain successful bodies when an oversized sibling is removed }); subscription.unsubscribe(); }); -}); +}, 30000); test("legacy subscriptions reselect the preferred base when a remote ref appears", async () => { await withCheckout(async ({ cwd, manager, git }) => { diff --git a/packages/server/src/server/file-observer/native-recursive.test.ts b/packages/server/src/server/file-observer/native-recursive.test.ts index cb442729fc..ce97e64fd7 100644 --- a/packages/server/src/server/file-observer/native-recursive.test.ts +++ b/packages/server/src/server/file-observer/native-recursive.test.ts @@ -47,7 +47,9 @@ test("the recursive watcher remembers newly announced files before reconciliatio const path = join(root, "new.txt"); await writeFile(path, "created"); await expect - .poll(() => changes.some((event) => event.path === path && event.type === "create")) + .poll(() => changes.some((event) => event.path === path && event.type === "create"), { + timeout: 10_000, + }) .toBe(true); // Consumers have seen this file. A later audit needs it in its comparison // inventory even if the native watcher coalesces the subsequent delete. @@ -55,7 +57,9 @@ test("the recursive watcher remembers newly announced files before reconciliatio await rm(path); await backend.updateIgnore(); await expect - .poll(() => changes.some((event) => event.path === path && event.type === "delete")) + .poll(() => changes.some((event) => event.path === path && event.type === "delete"), { + timeout: 10_000, + }) .toBe(true); } finally { active = false; diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index c3ffb6bef2..784acd523b 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -396,6 +396,15 @@ export class PluginService { }); } + /** Reads the default registry's directory. Not queued: it touches no local state. */ + listRegistry() { + return this.requireManagedSources().listRegistry(); + } + + getRegistryPlugin(id: string) { + return this.requireManagedSources().getRegistryPlugin(id); + } + async statusSources(pluginId?: string): Promise { return this.enqueue(async () => { const sources = this.configStore.get().plugins ?? {}; diff --git a/packages/server/src/server/plugins/managed-source.posix.test.ts b/packages/server/src/server/plugins/managed-source.posix.test.ts index 6e5646b1e6..ff336ba125 100644 --- a/packages/server/src/server/plugins/managed-source.posix.test.ts +++ b/packages/server/src/server/plugins/managed-source.posix.test.ts @@ -577,6 +577,111 @@ describe("registry plugin sources", () => { }); }); +it("reads the registry directory and a listing with the registry's credentials, without install intent", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-browse-home-")); + roots.push(home); + const listing = { + id: "acme/example", + name: "Example", + description: "Test", + categories: ["tools"], + author: { github: "acme" }, + repository: { url: "https://github.com/acme/example" }, + artifact: { + kind: "git", + remote: "https://github.com/acme/example.git", + commit: "a".repeat(40), + }, + media: [], + submittedAt: "2026-10-03", + reviewedAt: "2026-10-03", + updatedAt: "2026-10-03", + publishedAt: "2026-10-03", + }; + const documents: Record = { + "/internal/index.json": { + schemaVersion: 1, + registry: { name: "Internal", url: "http://registry.test" }, + categories: [{ slug: "tools", label: "Tools" }], + // A listing this host cannot read is left out; the rest stay browsable. + plugins: [listing, { ...listing, id: "acme/future", artifact: { kind: "oci" } }], + featured: ["acme/example"], + generatedAt: "2026-10-03", + }, + "/internal/plugins/acme/example.json": { ...listing, readme: "# Example" }, + "/internal/plugins/acme/other.json": { ...listing, readme: "# Example" }, + }; + const requests: Array<{ path?: string; intent?: string | string[]; authorization?: string }> = []; + const server = createServer((req, res) => { + requests.push({ + path: req.url, + intent: req.headers["x-paseo-install"], + authorization: req.headers.authorization, + }); + const document = req.url ? documents[req.url] : undefined; + if (!document) { + res.writeHead(404).end(); + return; + } + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify(document)); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing registry address"); + const host = `127.0.0.1:${address.port}`; + try { + const sources = new ManagedPluginSources(home, { + defaultUrl: `http://${host}/internal/`, + registries: { [host]: { authorization: "Bearer test" } }, + }); + const index = await sources.listRegistry(); + expect(index.plugins.map((plugin) => plugin.id)).toEqual(["acme/example"]); + expect(index.featured).toEqual(["acme/example"]); + expect((await sources.getRegistryPlugin("acme/example")).readme).toBe("# Example"); + await expect(sources.getRegistryPlugin("acme/other")).rejects.toThrow( + "Registry returned a different plugin ID", + ); + await expect(sources.getRegistryPlugin("acme/missing")).rejects.toThrow( + "Plugin registry returned 404 for plugins/acme/missing.json", + ); + await expect(sources.getRegistryPlugin("../index")).rejects.toThrow(); + expect(requests).toEqual([ + { path: "/internal/index.json", intent: undefined, authorization: "Bearer test" }, + { + path: "/internal/plugins/acme/example.json", + intent: undefined, + authorization: "Bearer test", + }, + { + path: "/internal/plugins/acme/other.json", + intent: undefined, + authorization: "Bearer test", + }, + { + path: "/internal/plugins/acme/missing.json", + intent: undefined, + authorization: "Bearer test", + }, + ]); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +it("reports a misconfigured registry instead of asking the user to retry", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-registry-browse-config-")); + roots.push(home); + const sources = new ManagedPluginSources(home, { + defaultUrl: "http://registry.example", + registries: { "registry.example": { authorization: "Bearer test" } }, + }); + await expect(sources.listRegistry()).rejects.toThrow("Registry credentials require HTTPS"); + await expect(sources.getRegistryPlugin("acme/example")).rejects.toThrow( + "Registry credentials require HTTPS", + ); +}); + it("installs and updates only the npm artifacts pinned by the plugin registry", async () => { const { startNpmRegistry, npmPluginPackages } = await import("../../../../../scripts/test-support/npm-registry.mjs"); diff --git a/packages/server/src/server/plugins/managed-source.ts b/packages/server/src/server/plugins/managed-source.ts index a20be890b3..636ffd8161 100644 --- a/packages/server/src/server/plugins/managed-source.ts +++ b/packages/server/src/server/plugins/managed-source.ts @@ -2,7 +2,12 @@ import { PluginRegistryIdentitySchema, parsePluginRegistryReference, } from "@getpaseo/protocol/plugin-registry"; -import { resolveRegistryPlugin, type RegistryOptions } from "./managed-source/registry.js"; +import { + getRegistryPlugin, + listRegistryPlugins, + resolveRegistryPlugin, + type RegistryOptions, +} from "./managed-source/registry.js"; import { randomUUID } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; import { mkdir, realpath, rename, rm } from "node:fs/promises"; @@ -357,6 +362,14 @@ export class ManagedPluginSources { } } + listRegistry() { + return listRegistryPlugins(this.registryOptions); + } + + getRegistryPlugin(id: string) { + return getRegistryPlugin(id, this.registryOptions); + } + async status(pluginId: string, configuredPath: string): Promise { const preview = await this.preview(pluginId, configuredPath); const installation = preview.current!; diff --git a/packages/server/src/server/plugins/managed-source/registry.ts b/packages/server/src/server/plugins/managed-source/registry.ts index 009cac5a68..2225b9f983 100644 --- a/packages/server/src/server/plugins/managed-source/registry.ts +++ b/packages/server/src/server/plugins/managed-source/registry.ts @@ -1,7 +1,12 @@ import { + DEFAULT_PLUGIN_REGISTRY_URL, PluginRegistryArtifactSchema, PluginRegistryIdSchema, + PluginRegistryIndexSchema, + PublishedPluginDetailSchema, + PublishedPluginSchema, type PluginRegistries, + type PluginRegistryIndex, type PluginRegistryIdentity, } from "@getpaseo/protocol/plugin-registry"; import type { PluginUpdateTarget } from "@getpaseo/protocol/messages"; @@ -17,12 +22,9 @@ export interface RegistryOptions { defaultUrl?: string; registries?: PluginRegistries; } -export async function resolveRegistryPlugin( - identity: PluginRegistryIdentity, - options: RegistryOptions, - install: boolean, -) { - const base = new URL(identity.url); +/** Request headers for a registry, with its configured credentials. Rejects unsafe bases. */ +function registryHeaders(url: string, options: RegistryOptions): Record { + const base = new URL(url); if (!["http:", "https:"].includes(base.protocol) || base.username || base.password) throw new Error("Registry base must be an HTTP(S) URL without credentials"); const authorization = options.registries?.[base.host]?.authorization; @@ -32,8 +34,67 @@ export async function resolveRegistryPlugin( !["localhost", "127.0.0.1", "[::1]"].includes(base.hostname) ) throw new Error("Registry credentials require HTTPS"); - const headers: Record = {}; - if (authorization) headers.Authorization = authorization; + return authorization ? { Authorization: authorization } : {}; +} + +function defaultRegistryUrl(options: RegistryOptions): string { + return (options.defaultUrl ?? DEFAULT_PLUGIN_REGISTRY_URL).replace(/\/+$/, ""); +} + +/** Reads a display document from the default registry; never used to choose what installs. */ +async function readRegistryDocument(options: RegistryOptions, path: string): Promise { + const base = defaultRegistryUrl(options); + const url = `${base}/${path}`; + // Built before the request, so a registry setup error reaches the user instead of "Retry later". + const headers = registryHeaders(base, options); + let response: Response; + try { + response = await fetch(url, { + headers, + redirect: "error", + signal: AbortSignal.timeout(30000), + }); + } catch (cause) { + throw new Error(`Could not reach plugin registry ${url}. Retry later.`, { cause }); + } + if (!response.ok) throw new Error(`Plugin registry returned ${response.status} for ${path}`); + return response.json(); +} + +// Listings are read one by one, so a listing this host cannot read leaves the rest browsable. +const RegistryIndexDocumentSchema = PluginRegistryIndexSchema.extend({ + plugins: z.array(z.unknown()), +}); + +/** The default registry's plugin directory, for browsing, without listings this host cannot read. */ +export async function listRegistryPlugins(options: RegistryOptions): Promise { + const index = RegistryIndexDocumentSchema.parse( + await readRegistryDocument(options, "index.json"), + ); + const plugins = index.plugins.flatMap((listing) => { + const parsed = PublishedPluginSchema.safeParse(listing); + return parsed.success ? [parsed.data] : []; + }); + return { ...index, plugins }; +} + +/** One listing with its overview, for the plugin's page. */ +export async function getRegistryPlugin(id: string, options: RegistryOptions) { + const pluginId = PluginRegistryIdSchema.parse(id); + const plugin = PublishedPluginDetailSchema.parse( + await readRegistryDocument(options, `plugins/${pluginId}.json`), + ); + if (plugin.id !== pluginId) throw new Error("Registry returned a different plugin ID"); + return plugin; +} + +export async function resolveRegistryPlugin( + identity: PluginRegistryIdentity, + options: RegistryOptions, + install: boolean, +) { + const base = new URL(identity.url); + const headers = registryHeaders(identity.url, options); if (install) headers["X-Paseo-Install"] = "1"; const url = `${identity.url.replace(/\/+$/, "")}/plugins/${identity.id}.json`; let response: Response; diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 77f30ee0f0..fcdbbae1ed 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -541,6 +541,10 @@ export interface SessionOptions { statusSources( pluginId?: string, ): Promise; + listRegistry(): Promise; + getRegistryPlugin( + id: string, + ): Promise; previewUpdates(input: { pluginId?: string; target?: import("@getpaseo/protocol/messages").PluginUpdateSelection; @@ -2904,6 +2908,30 @@ export class Session { }); } + private dispatchPluginRegistryMessage(msg: SessionInboundMessage): Promise | undefined { + if (msg.type === "plugin.registry.list.request") { + if (!this.pluginRuntime) throw new Error("Plugin service is unavailable"); + return this.pluginRuntime.listRegistry().then((index) => { + this.emit({ + type: "plugin.registry.list.response", + payload: { requestId: msg.requestId, index }, + }); + return undefined; + }); + } + if (msg.type === "plugin.registry.get.request") { + if (!this.pluginRuntime) throw new Error("Plugin service is unavailable"); + return this.pluginRuntime.getRegistryPlugin(msg.id).then((plugin) => { + this.emit({ + type: "plugin.registry.get.response", + payload: { requestId: msg.requestId, plugin }, + }); + return undefined; + }); + } + return undefined; + } + private dispatchPluginDirectoryMessage(msg: SessionInboundMessage): Promise | undefined { if (msg.type === "plugin.source.install.request") { if (!this.pluginRuntime) throw new Error("Plugin service is unavailable"); @@ -2984,7 +3012,7 @@ export class Session { return undefined; }); } - return undefined; + return this.dispatchPluginRegistryMessage(msg); } private subscribeToPluginChanges( diff --git a/packages/server/src/server/test-utils/paseo-daemon.ts b/packages/server/src/server/test-utils/paseo-daemon.ts index 766fd49919..17f47df629 100644 --- a/packages/server/src/server/test-utils/paseo-daemon.ts +++ b/packages/server/src/server/test-utils/paseo-daemon.ts @@ -55,6 +55,7 @@ interface TestPaseoDaemonOptions { resumeOnStartup?: boolean; resumePrompt?: string; pluginsEnabled?: PaseoDaemonConfig["pluginsEnabled"]; + pluginRegistryUrl?: PaseoDaemonConfig["pluginRegistryUrl"]; builtinPlugins?: BuiltinPluginLoader; plugins?: PaseoDaemonConfig["plugins"]; } @@ -232,6 +233,7 @@ async function prepareTestDaemonConfig( resumePrompt: options.resumePrompt, pluginsEnabled: options.pluginsEnabled, plugins: options.plugins, + pluginRegistryUrl: options.pluginRegistryUrl, }; return { config, paseoHomeRoot, paseoHome, staticDir, createdDirs }; } diff --git a/packages/server/src/server/test-utils/versioned-daemon.ts b/packages/server/src/server/test-utils/versioned-daemon.ts index f8763e0d6f..ac46db8c8f 100644 --- a/packages/server/src/server/test-utils/versioned-daemon.ts +++ b/packages/server/src/server/test-utils/versioned-daemon.ts @@ -1,6 +1,7 @@ // Browser compatibility tests run a real daemon in a separate Node runtime. // // argv: [port] [paseoHomeRoot] +// env: PASEO_PLUGIN_REGISTRY, read as the real daemon reads it. // A fixed port and a caller-owned home let a test stop this daemon and start a // replacement under the same endpoint and serverId. import path from "node:path"; @@ -24,6 +25,7 @@ const daemon = await createTestPaseoDaemon({ } : {}), pluginsEnabled: true, + pluginRegistryUrl: process.env.PASEO_PLUGIN_REGISTRY, mcpEnabled: false, corsAllowedOrigins: ["*"], }); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 50c5edac99..cbbdd9685d 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -2092,6 +2092,8 @@ export class VoiceAssistantWebSocketServer { pluginGitManagement: true, pluginSourceInstallation: true, pluginSourceUpdates: true, + // COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15. + pluginRegistry: true, pluginLogs: true, // COMPAT(pluginThemes): added in v0.5.0, remove gate after 2027-08-20. pluginThemes: true, From c4ff5599c76bb63ff56c3ce4d65f5fdcfcc26fed Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 20:34:17 +0700 Subject: [PATCH 090/160] fix(app): close slash picker after inserting a command (#9755) Publish the resolved replacement selection to the composer. iOS does not emit a native selection event for this edit, leaving autocomplete at the slash until the next keystroke. --- .../native-composer-command-selection.ios.ad | 13 +++++++++++++ packages/app/src/composer/input/input.tsx | 13 ++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 packages/app/e2e/mobile/agent-device/native-composer-command-selection.ios.ad diff --git a/packages/app/e2e/mobile/agent-device/native-composer-command-selection.ios.ad b/packages/app/e2e/mobile/agent-device/native-composer-command-selection.ios.ad new file mode 100644 index 0000000000..c02272bf8e --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-composer-command-selection.ios.ad @@ -0,0 +1,13 @@ +context platform=ios timeout=60000 retries=0 +# Start in an empty, connected composer with the Claude provider selected. +# COMMAND_ROW must name an inserting command, not an immediate client action. +env COMMAND_ROW="/advisor, Let Claude consult a stronger model at key moments" +env COMMAND_TEXT="/advisor " +open sh.paseo.debug +wait "editable=true" 60000 +fill "editable=true" "/" +wait "label=\"${COMMAND_ROW}\"" 15000 +press "label=\"${COMMAND_ROW}\"" +# Do not type or move the caret: replacement itself must close autocomplete. +wait absent "label=\"${COMMAND_ROW}\"" 3000 +wait "editable=true value=\"${COMMAND_TEXT}\"" 3000 diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index b0ed623304..0153911627 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -204,7 +204,7 @@ export interface MessageInputProps { onSubmitLoadingPress?: () => void; /** Intercept key press events before default handling. Return true to prevent default. */ onKeyPress?: (event: ComposerKeyPressEvent) => boolean; - /** Reports cursor selection updates from the underlying input. */ + /** Reports selection updates from user input and programmatic replacements. */ onSelectionChange?: (selection: { start: number; end: number }) => void; onFocusChange?: (focused: boolean) => void; onHeightChange?: (height: number) => void; @@ -1468,11 +1468,18 @@ export const MessageInput = forwardRef( if (nextText === "") { textInputRef.current?.reset(); } else { - textInputRef.current?.replaceText(nextText, selection); + textInputRef.current?.replaceText(nextText, selectionRef.current); } onChangeText(nextText); + // iOS does not emit a selection event for a programmatic text replacement. + onSelectionChangeCallback?.(selectionRef.current); }, - [onChangeText, updateComposerHeightForText, updateLiveTextPresence], + [ + onChangeText, + onSelectionChangeCallback, + updateComposerHeightForText, + updateLiveTextPresence, + ], ); useLayoutEffect( From aa9984b89988febb7b3bf9f2005ddc59c646972c Mon Sep 17 00:00:00 2001 From: Junjie ZHANG <51326516+junjzhang@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:53:12 +0800 Subject: [PATCH 091/160] fix(app): show the keyboard focus ring on icon buttons (#9745) The shared icon button chrome set outlineWidth: 0, which overrides the :focus-visible ring from public/index.html. Header and toolbar icon buttons (sidebar toggle, workspace actions, Explorer toggle, new tab, pane menu, diff toolbar) showed no indication of keyboard focus. Drop the reset and draw the ring 2px inside the frame: the header title row clips overflow, so an outset ring loses its top and bottom edges. Pointer focus stays unringed through the existing *:focus rule. --- .../browser/icon-button-focus-ring.spec.ts | 56 +++++++++++++++++++ .../src/components/ui/icon-button-chrome.ts | 13 +++-- 2 files changed, 63 insertions(+), 6 deletions(-) create mode 100644 packages/app/e2e/browser/icon-button-focus-ring.spec.ts diff --git a/packages/app/e2e/browser/icon-button-focus-ring.spec.ts b/packages/app/e2e/browser/icon-button-focus-ring.spec.ts new file mode 100644 index 0000000000..56029381c6 --- /dev/null +++ b/packages/app/e2e/browser/icon-button-focus-ring.spec.ts @@ -0,0 +1,56 @@ +import { expect, type Locator, type Page } from "@playwright/test"; +import { test } from "../support/fixtures"; +import { gotoWorkspace } from "../support/helpers/launcher"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs"; + +const HEADER_ICON_BUTTONS = ["workspace-header-menu-trigger", "workspace-explorer-toggle"]; + +function visible(page: Page, testId: string): Locator { + return page.getByTestId(testId).filter({ visible: true }).first(); +} + +function matchesFocusVisible(target: Locator): Promise { + return target.evaluate((el) => el.matches(":focus-visible")); +} + +async function expectKeyboardFocusRing(page: Page, testId: string): Promise { + const button = visible(page, testId); + // Chromium matches :focus-visible on a programmatic focus that follows keyboard input. + await page.keyboard.press("Shift"); + await button.focus(); + await expect(button).toBeFocused(); + expect(await matchesFocusVisible(button)).toBe(true); + await expect(button).toHaveCSS("outline-style", "solid"); + await expect(button).toHaveCSS("outline-width", "2px"); + // Header rows clip overflow; an outset ring would lose its top and bottom edges. + await expect(button).toHaveCSS("outline-offset", "-2px"); +} + +async function expectNoPointerFocusRing(page: Page, testId: string): Promise { + const button = visible(page, testId); + await button.blur(); + // Toggle twice so the layout ends where it started. + await button.click(); + await button.click(); + await expect(button).toBeFocused(); + expect(await matchesFocusVisible(button)).toBe(false); + await expect(button).toHaveCSS("outline-style", "none"); +} + +test.describe("Icon button focus ring", () => { + test("header icon buttons show the focus ring for keyboard focus only", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }); + const workspace = await seedWorkspace({ repoPrefix: "icon-button-focus-" }); + try { + await gotoWorkspace(page, workspace.workspaceId); + await waitForWorkspaceTabsVisible(page); + for (const testId of HEADER_ICON_BUTTONS) { + await expectKeyboardFocusRing(page, testId); + } + await expectNoPointerFocusRing(page, "workspace-explorer-toggle"); + } finally { + await workspace.cleanup(); + } + }); +}); diff --git a/packages/app/src/components/ui/icon-button-chrome.ts b/packages/app/src/components/ui/icon-button-chrome.ts index da738df59f..8cf68e8925 100644 --- a/packages/app/src/components/ui/icon-button-chrome.ts +++ b/packages/app/src/components/ui/icon-button-chrome.ts @@ -126,6 +126,10 @@ export function smallIconButtonChromeFrameSize(compact = false): number { return ICON_BUTTON_SIZES.small[controlSizingForLayout(compact)]; } +// Icon buttons sit in header and toolbar rows that clip overflow, so the keyboard focus ring +// from public/index.html is drawn inside the frame instead of around it. +const FOCUS_RING_INSET = -2; + const styles = StyleSheet.create((theme) => ({ large: { width: bySizing(ICON_BUTTON_SIZES.large), @@ -135,8 +139,7 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", justifyContent: "center", flexShrink: 0, - outlineWidth: 0, - outlineColor: "transparent", + outlineOffset: FOCUS_RING_INSET, }, small: { width: ICON_BUTTON_SIZES.small.pointer, @@ -146,8 +149,7 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", justifyContent: "center", flexShrink: 0, - outlineWidth: 0, - outlineColor: "transparent", + outlineOffset: FOCUS_RING_INSET, }, smallTouch: { width: ICON_BUTTON_SIZES.small.touch, @@ -157,8 +159,7 @@ const styles = StyleSheet.create((theme) => ({ alignItems: "center", justifyContent: "center", flexShrink: 0, - outlineWidth: 0, - outlineColor: "transparent", + outlineOffset: FOCUS_RING_INSET, }, round: { borderRadius: theme.borderRadius.full, From 1c175b36b3cdf139c048b6eba8101e170282e0df Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 15 Nov 2026 21:51:37 +0700 Subject: [PATCH 092/160] Keep a dropped Usage card in its new slot on web (#9780) On web and desktop, dropping a Usage card made it jump above its new slot and slide back down for 200 ms. The web list cleared its drag state on drop and rendered the owner's data again. Usage saves the order through app settings, so the new order arrived in a later render. The render in between had the old order with dnd-kit's transforms cleared, which started a transition back to the old slot. The new order then moved the row's slot under that running transition. The list now holds the dropped key order until the owner's data changes order, and renders the owner's current rows in that order. The drop and the new order commit in one render, so dnd-kit skips the transition. A drag that starts during the hold picks up the rows as displayed. Sidebar lists already reorder in the drop's render and behave as before. The native list has followed the same rule since #9748. --- packages/app/e2e/browser/usage-modal.spec.ts | 7 ++ .../e2e/support/helpers/usage-sidebar-item.ts | 38 ++++++++ .../drag-reorder/drag-reducer.test.ts | 28 ++++-- .../components/drag-reorder/drag-reducer.ts | 28 ++++-- .../drag-reorder/use-drag-reorder-state.ts | 69 +++++++++++---- .../src/components/draggable-list.types.ts | 5 +- .../draggable-list.web.browser.test.tsx | 86 ++++++++++++++++++- 7 files changed, 225 insertions(+), 36 deletions(-) diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 8101beefbf..c1d717e241 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -37,6 +37,7 @@ import { pickUsageHost, usageModalHost, dragUsageCardAbove, + recordUsageCardPositionsAfterRelease, expectUsageCardOrder, expectUsageOptionsFitContent, setUsageCardOn, @@ -254,9 +255,15 @@ test.describe("usage modal", () => { await expect(work.getByText("work", { exact: true })).toBeVisible(); await expectPinnedUsage(page, ["31% Weekly", "20% Weekly"]); + const stopRecording = await recordUsageCardPositionsAfterRelease(page); await dragUsageCardAbove(page, "beta:home", "alpha:a"); await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]); await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]); + // The cards are in their new slots from the first frame after the drop. + const framesAfterDrop = await stopRecording(); + const settled = framesAfterDrop.at(-1); + expect(settled).toBeDefined(); + expect(framesAfterDrop.filter((frame) => frame !== settled)).toEqual([]); await page.reload(); await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]); diff --git a/packages/app/e2e/support/helpers/usage-sidebar-item.ts b/packages/app/e2e/support/helpers/usage-sidebar-item.ts index f4d1b006e5..f6faf3be65 100644 --- a/packages/app/e2e/support/helpers/usage-sidebar-item.ts +++ b/packages/app/e2e/support/helpers/usage-sidebar-item.ts @@ -187,6 +187,44 @@ export async function dragUsageCardAbove( await page.mouse.up(); } +/** + * Starts recording where the cards are painted on every frame after the next mouse release. + * Call the returned function to stop and read the frames, each as "id@top" for every card. + */ +export async function recordUsageCardPositionsAfterRelease( + page: Page, +): Promise<() => Promise> { + const recording = await usageModal(page).evaluateHandle((modal) => { + const state = { released: false, stopped: false, frames: [] as string[] }; + const markReleased = () => { + state.released = true; + }; + window.addEventListener("mouseup", markReleased, { capture: true, once: true }); + const recordFrame = () => { + if (state.stopped) return; + if (state.released) { + const cards = Array.from(modal.querySelectorAll('[data-testid^="usage-report-"]')); + state.frames.push( + cards + .map((card) => { + const id = card.getAttribute("data-testid")?.slice("usage-report-".length); + return `${id}@${Math.round(card.getBoundingClientRect().top)}`; + }) + .join(" "), + ); + } + requestAnimationFrame(recordFrame); + }; + requestAnimationFrame(recordFrame); + return state; + }); + return () => + recording.evaluate((state) => { + state.stopped = true; + return state.frames; + }); +} + /** Each pinned window as it reads: its percent and short label, "31% 5h". */ export async function expectPinnedUsage(page: Page, windows: string[]): Promise { const pinned = usageItem(page).getByTestId("sidebar-usage-pinned-window"); diff --git a/packages/app/src/components/drag-reorder/drag-reducer.test.ts b/packages/app/src/components/drag-reorder/drag-reducer.test.ts index 623f7cdca0..b347bb3c98 100644 --- a/packages/app/src/components/drag-reorder/drag-reducer.test.ts +++ b/packages/app/src/components/drag-reorder/drag-reducer.test.ts @@ -2,31 +2,41 @@ import { describe, expect, it } from "vitest"; import { dragStateInitial, dragStateReducer } from "./drag-reducer"; describe("dragStateReducer", () => { - it("starts tracking the active item with a snapshot of the data", () => { + it("starts tracking the active item with the rows on screen", () => { const next = dragStateReducer(dragStateInitial(), { type: "start", id: "alpha", - data: ["alpha", "beta"], + items: ["alpha", "beta"], }); - expect(next).toEqual({ activeId: "alpha", dragItems: ["alpha", "beta"] }); + expect(next).toEqual({ activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }); }); - it("clears the active item and the snapshot", () => { + it("clears the active item and the rows", () => { const next = dragStateReducer( - { activeId: "alpha", dragItems: ["alpha", "beta"] }, + { activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }, { type: "clear" }, ); - expect(next).toEqual({ activeId: null, dragItems: null }); + expect(next).toEqual({ activeId: null, dragItems: null, dropped: null }); + }); + + it("holds the dropped order in place of the order it replaces", () => { + const dropped = { order: ["beta", "alpha"], replaces: ["alpha", "beta"] }; + const next = dragStateReducer( + { activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }, + { type: "drop", dropped }, + ); + + expect(next).toEqual({ activeId: null, dragItems: null, dropped }); }); it("replaces an in-flight drag when a new one starts", () => { const next = dragStateReducer( - { activeId: "alpha", dragItems: ["alpha", "beta"] }, - { type: "start", id: "beta", data: ["beta", "gamma"] }, + { activeId: "alpha", dragItems: ["alpha", "beta"], dropped: null }, + { type: "start", id: "beta", items: ["beta", "gamma"] }, ); - expect(next).toEqual({ activeId: "beta", dragItems: ["beta", "gamma"] }); + expect(next).toEqual({ activeId: "beta", dragItems: ["beta", "gamma"], dropped: null }); }); }); diff --git a/packages/app/src/components/drag-reorder/drag-reducer.ts b/packages/app/src/components/drag-reorder/drag-reducer.ts index b9b508f2d2..7e4acfe055 100644 --- a/packages/app/src/components/drag-reorder/drag-reducer.ts +++ b/packages/app/src/components/drag-reorder/drag-reducer.ts @@ -1,19 +1,33 @@ -export interface DragState { - activeId: string | null; - dragItems: T[] | null; +/** A dropped key order, shown in place of the owner's until the owner's order changes. */ +export interface DroppedOrder { + order: string[]; + /** The owner's key order at the drop. */ + replaces: string[]; } -export type DragAction = { type: "start"; id: string; data: T[] } | { type: "clear" }; +export interface DragState { + activeId: string | null; + /** The rows on screen while a drag is in flight. */ + dragItems: T[] | null; + dropped: DroppedOrder | null; +} + +export type DragAction = + | { type: "start"; id: string; items: T[] } + | { type: "drop"; dropped: DroppedOrder } + | { type: "clear" }; export function dragStateInitial(): DragState { - return { activeId: null, dragItems: null }; + return { activeId: null, dragItems: null, dropped: null }; } export function dragStateReducer(state: DragState, action: DragAction): DragState { switch (action.type) { case "start": - return { activeId: action.id, dragItems: action.data }; + return { activeId: action.id, dragItems: action.items, dropped: null }; + case "drop": + return { activeId: null, dragItems: null, dropped: action.dropped }; case "clear": - return { activeId: null, dragItems: null }; + return dragStateInitial(); } } diff --git a/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts b/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts index ba64619e0f..986a2c578b 100644 --- a/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts +++ b/packages/app/src/components/drag-reorder/use-drag-reorder-state.ts @@ -1,6 +1,6 @@ -import { useCallback, useReducer } from "react"; +import { useCallback, useMemo, useReducer } from "react"; import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core"; -import { dragStateInitial, dragStateReducer } from "./drag-reducer"; +import { dragStateInitial, dragStateReducer, type DroppedOrder } from "./drag-reducer"; import { reorderItemsOnDragEnd } from "./reorder-items"; export interface DragReorderHandlers { @@ -15,6 +15,28 @@ export interface DragReorderState { handlers: DragReorderHandlers; } +/** + * The owner's rows in the dropped order, or null once the owner's own order has changed since + * the drop. + */ +function arrangeAsDropped( + data: T[], + keys: string[], + { order, replaces }: DroppedOrder, +): T[] | null { + const ownerOrderUnchanged = + keys.length === replaces.length && keys.every((key, index) => key === replaces[index]); + if (!ownerOrderUnchanged) return null; + + const indexByKey = new Map(keys.map((key, index) => [key, index])); + const arranged: T[] = []; + for (const key of order) { + const index = indexByKey.get(key); + if (index !== undefined) arranged.push(data[index]); + } + return arranged.length === data.length ? arranged : null; +} + export function useDragReorderState({ data, keyExtractor, @@ -30,13 +52,22 @@ export function useDragReorderState({ }): DragReorderState { const [state, dispatch] = useReducer(dragStateReducer, undefined, dragStateInitial); + const keys = useMemo(() => data.map(keyExtractor), [data, keyExtractor]); + const held = useMemo( + () => (state.dropped ? arrangeAsDropped(data, keys, state.dropped) : null), + [data, keys, state.dropped], + ); + // The owner's order changed, so the dropped order has nothing left to stand in for. + if (state.dropped && !held) dispatch({ type: "clear" }); + const items = state.dragItems ?? held ?? data; + const handleDragStart = useCallback( (event: DragStartEvent) => { if (disabled) return; - dispatch({ type: "start", id: String(event.active.id), data }); + dispatch({ type: "start", id: String(event.active.id), items }); onDragBegin?.(); }, - [data, disabled, onDragBegin], + [disabled, items, onDragBegin], ); const clearDragState = useCallback(() => { @@ -46,25 +77,29 @@ export function useDragReorderState({ const handleDragEnd = useCallback( (event: DragEndEvent) => { const { active, over } = event; - const items = state.dragItems ?? data; - dispatch({ type: "clear" }); - if (disabled) return; - const activeId = String(active.id); - const reordered = reorderItemsOnDragEnd({ - items, - activeId, - overId: over ? String(over.id) : null, - keyExtractor, - }); - if (reordered) onDragEnd?.(reordered, activeId); + const reordered = disabled + ? null + : reorderItemsOnDragEnd({ + items, + activeId, + overId: over ? String(over.id) : null, + keyExtractor, + }); + if (!reordered) { + dispatch({ type: "clear" }); + return; + } + // The owner's new order can arrive in a later render. Hold the dropped order until it does. + dispatch({ type: "drop", dropped: { order: reordered.map(keyExtractor), replaces: keys } }); + onDragEnd?.(reordered, activeId); }, - [data, disabled, keyExtractor, onDragEnd, state.dragItems], + [disabled, items, keyExtractor, keys, onDragEnd], ); return { activeId: state.activeId, - items: state.dragItems ?? data, + items, handlers: { onDragStart: handleDragStart, onDragCancel: clearDragState, diff --git a/packages/app/src/components/draggable-list.types.ts b/packages/app/src/components/draggable-list.types.ts index 67b628cc4d..e9bc66ae68 100644 --- a/packages/app/src/components/draggable-list.types.ts +++ b/packages/app/src/components/draggable-list.types.ts @@ -36,7 +36,10 @@ export interface DraggableListProps { data: T[]; keyExtractor: (item: T, index: number) => string; renderItem: (info: DraggableRenderItemInfo) => ReactElement; - /** The new order, and the key of the item the user moved to reach it. */ + /** + * The new order, and the key of the item the user moved to reach it. The list keeps showing + * this order until `data` arrives in a different order, so the owner must apply it. + */ onDragEnd: (data: T[], movedKey: string) => void; style?: StyleProp; /** Outer container style (useful for nested, non-scrolling lists). */ diff --git a/packages/app/src/components/draggable-list.web.browser.test.tsx b/packages/app/src/components/draggable-list.web.browser.test.tsx index 6839bb5b2a..db4ed66e40 100644 --- a/packages/app/src/components/draggable-list.web.browser.test.tsx +++ b/packages/app/src/components/draggable-list.web.browser.test.tsx @@ -1,4 +1,4 @@ -import React, { act } from "react"; +import React, { act, useCallback, useState } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { @@ -11,6 +11,7 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); interface Item { id: string; + label?: string; } function keyExtractor(item: Item): string { @@ -41,7 +42,7 @@ function renderRowWithHandle(info: DraggableRenderItemInfo) { grip - {info.item.id} + {info.item.label ?? info.item.id}
); } @@ -87,6 +88,87 @@ function pressAndMove(element: HTMLElement, distance: number) { }); } +const OWNER_DELAY_MS = 50; + +function wait(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +/** + * An owner that relabels its rows as soon as one is dropped, and whose new order reaches the list + * in a later render, like one that saves to a store. + */ +function ListWithLateOwner() { + const [items, setItems] = useState([{ id: "one" }, { id: "two" }]); + const relabelThenReorderLater = useCallback((next: Item[]) => { + const relabel = (item: Item): Item => ({ id: item.id, label: `${item.id} dropped` }); + setItems((current) => current.map(relabel)); + setTimeout(() => setItems(next.map(relabel)), OWNER_DELAY_MS); + }, []); + return ( + + ); +} + +function rowOrder(): (string | null)[] { + return Array.from(container?.querySelectorAll('[data-testid="row-body"]') ?? []).map( + (row) => row.textContent, + ); +} + +/** Drag the element down by `distance` in two mouse moves, letting dnd-kit measure in between. */ +async function dragDown(element: HTMLElement, distance: number) { + const { left, top, width, height } = element.getBoundingClientRect(); + const x = left + width / 2; + const y = top + height / 2; + await act(async () => { + element.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, button: 0, clientX: x, clientY: y }), + ); + }); + for (const moved of [distance / 2, distance]) { + await act(async () => { + document.dispatchEvent( + new MouseEvent("mousemove", { bubbles: true, clientX: x, clientY: y + moved }), + ); + await wait(20); + }); + } + act(() => { + document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })); + }); +} + +describe("DraggableList on web", () => { + it("shows the owner's current rows in the dropped order until its new order arrives", async () => { + act(() => { + root?.render(); + }); + const [firstHandle] = Array.from( + container?.querySelectorAll('[data-testid="row-handle"]') ?? [], + ); + const [firstRow, secondRow] = Array.from( + container?.querySelectorAll('[data-testid="row-body"]') ?? [], + ); + const rowDistance = + secondRow.getBoundingClientRect().top - firstRow.getBoundingClientRect().top; + + await dragDown(firstHandle, rowDistance); + expect(rowOrder()).toEqual(["two dropped", "one dropped"]); + + await act(() => wait(OWNER_DELAY_MS * 2)); + expect(rowOrder()).toEqual(["two dropped", "one dropped"]); + }); +}); + describe("DraggableListHandle on web", () => { it("starts the row's drag from the handle, and only from the handle", () => { const onDragBegin = vi.fn(); From 2a432b1e0a520f71ec4f87c18498686bc4220350 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:51:53 +0000 Subject: [PATCH 093/160] test(app): wait for the slash search itself before erasing it (#9790) The arrow-choice test waited for /tdd to leave the list as proof that the search had become "h". The option list is a FlatList that mounts only the rows near its scroll position: right after the arrows wrap to /exit at the top, /tdd at the bottom is unmounted while the search is still "". The wait then passed early, Backspace landed before the cursor reached the search, the /exit choice stood, and Enter archived the agent. The test now waits for a popover that shows /help with neither /tdd nor /exit, in one query. With the search at "" the list always mounts the bottom row or the chosen one; only the search "h" leaves both out. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../app/e2e/browser/composer-autocomplete.spec.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/app/e2e/browser/composer-autocomplete.spec.ts b/packages/app/e2e/browser/composer-autocomplete.spec.ts index bf854c89b7..108433cda2 100644 --- a/packages/app/e2e/browser/composer-autocomplete.spec.ts +++ b/packages/app/e2e/browser/composer-autocomplete.spec.ts @@ -788,11 +788,20 @@ test.describe("Composer autocomplete", () => { await input.press("ArrowDown"); await input.press("h"); // On web the search reads the cursor after paint, so the input's value runs ahead of - // the list. Wait on the list itself: /tdd is hidden only while the search is "h", and - // back only once the search is "" again. - await expect(popover.getByText("/tdd", { exact: true })).toHaveCount(0); + // the list. Wait on the list itself. The list mounts only the rows near its scroll + // position, so one missing row proves nothing: right after the arrows wrap to the top, + // /tdd at the bottom is unmounted while the search is still "". With the search at "", + // the list always mounts the bottom row (/tdd) or the chosen one (/exit); only the + // search "h" leaves both out. Check them in one query so no frame falls between them. + await expect( + popover.filter({ + has: page.getByText("/help", { exact: true }), + hasNot: page.getByText(/^\/(tdd|exit)$/), + }), + ).toBeVisible(); await input.press("Backspace"); await expect(input).toHaveValue("/"); + // /tdd is back only once the search is "" again. await expect(popover.getByText("/tdd", { exact: true }).first()).toBeVisible(); await input.press("Enter"); From 4421f0473a37cc734279c54e1fc66687ed55d291 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:59:25 +0000 Subject: [PATCH 094/160] Archive non-Git workspaces from the command center (#9777) * fix(app): show archive workspace in command center * test(app): cover archive workspace command center entry * fix(app): expose archive for non-git workspaces * fix(app): archive non-Git workspaces from the command center A plain directory workspace had no Archive workspace entry in the command center, because the entry came only from the Git action list, which is empty outside Git. The command center now lists archive for any workspace that is not Git and runs the workspace's own archive controller, the same one the Git action uses, so it works whether or not the workspace's sidebar row is rendered. Git workspaces are unchanged: archive stays a Git action that shows on the default list only when it is the promoted primary action. Co-authored-by: Andreas Heiberg Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Andreas Heiberg Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- ...center-archive-directory-workspace.spec.ts | 105 ++++++++++++++++++ .../workspace-contributions.test.ts | 45 +++++++- .../command-center/workspace-contributions.ts | 21 ++++ .../command-center/workspace-registration.tsx | 6 +- packages/app/src/git/use-actions.tsx | 16 ++- 5 files changed, 190 insertions(+), 3 deletions(-) create mode 100644 packages/app/e2e/browser/command-center-archive-directory-workspace.spec.ts diff --git a/packages/app/e2e/browser/command-center-archive-directory-workspace.spec.ts b/packages/app/e2e/browser/command-center-archive-directory-workspace.spec.ts new file mode 100644 index 0000000000..1d880c11a1 --- /dev/null +++ b/packages/app/e2e/browser/command-center-archive-directory-workspace.spec.ts @@ -0,0 +1,105 @@ +import { existsSync } from "node:fs"; +import { expect, test } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { openCommandCenter } from "../support/helpers/command-center"; +import { openWorkspaceFromCommandCenter } from "../support/helpers/command-center-workspace-actions"; +import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client"; +import { projectEquivalenceViewKey } from "../support/helpers/project-view-key"; +import { getServerId } from "../support/helpers/server-id"; +import { expectWorkspaceAbsentFromSidebar } from "../support/helpers/sidebar"; + +async function isWorkspaceListed(seeded: SeededWorkspace): Promise { + const result = await seeded.client.fetchWorkspaces(); + return result.entries.some((entry) => entry.id === seeded.workspaceId); +} + +async function expectWorkspaceArchivedOnDaemon(seeded: SeededWorkspace): Promise { + await expect.poll(() => isWorkspaceListed(seeded), { timeout: 30_000 }).toBe(false); +} + +test.describe("Command center archive for a non-Git workspace", () => { + test("archives a plain directory workspace from the command center", async ({ page }) => { + const title = "Command Center Directory Archive"; + const seeded = await seedWorkspace({ repoPrefix: "cc-archive-dir-", title, git: false }); + + try { + await gotoAppShell(page); + await openWorkspaceFromCommandCenter(page, seeded, title); + + const panel = await openCommandCenter(page); + await panel.getByTestId("command-center-input").fill("archive"); + const archive = panel.getByRole("button", { name: /^Archive(?: workspace)?(?:\s|$)/ }); + await expect(archive).toBeVisible({ timeout: 30_000 }); + await archive.click(); + + await expectWorkspaceAbsentFromSidebar(page, seeded.workspaceId); + expect(existsSync(seeded.repoPath)).toBe(true); + } finally { + await seeded.cleanup(); + } + }); + + test("archives a plain directory workspace from the command center with the sidebar closed", async ({ + page, + }) => { + const title = "Command Center Directory Archive Closed Sidebar"; + const seeded = await seedWorkspace({ repoPrefix: "cc-archive-dir-closed-", title, git: false }); + + try { + await gotoAppShell(page); + await openWorkspaceFromCommandCenter(page, seeded, title); + + await page.getByTestId("menu-button").click(); + await expect(page.getByTestId("sidebar-search")).toBeHidden({ timeout: 10_000 }); + + const modifier = process.platform === "darwin" ? "Meta" : "Control"; + await page.keyboard.press(`${modifier}+k`); + const panel = page.getByTestId("command-center-panel"); + await expect(panel).toBeVisible({ timeout: 30_000 }); + await panel.getByTestId("command-center-input").fill("archive"); + const archive = panel.getByRole("button", { name: /^Archive(?: workspace)?(?:\s|$)/ }); + await expect(archive).toBeVisible({ timeout: 30_000 }); + await archive.click(); + + await expectWorkspaceArchivedOnDaemon(seeded); + } finally { + await seeded.cleanup(); + } + }); + + test("archives a plain directory workspace from the command center with its project collapsed", async ({ + page, + }) => { + const title = "Command Center Directory Archive Collapsed Project"; + const seeded = await seedWorkspace({ + repoPrefix: "cc-archive-dir-collapsed-", + title, + git: false, + }); + + try { + await gotoAppShell(page); + await openWorkspaceFromCommandCenter(page, seeded, title); + + const workspaceRow = page.getByTestId( + `sidebar-workspace-row-${getServerId()}:${seeded.workspaceId}`, + ); + await expect(workspaceRow).toBeVisible({ timeout: 30_000 }); + await page + .getByTestId(`sidebar-project-row-${projectEquivalenceViewKey(seeded.projectKey)}`) + .first() + .click(); + await expect(workspaceRow).toHaveCount(0, { timeout: 10_000 }); + + const panel = await openCommandCenter(page); + await panel.getByTestId("command-center-input").fill("archive"); + const archive = panel.getByRole("button", { name: /^Archive(?: workspace)?(?:\s|$)/ }); + await expect(archive).toBeVisible({ timeout: 30_000 }); + await archive.click(); + + await expectWorkspaceArchivedOnDaemon(seeded); + } finally { + await seeded.cleanup(); + } + }); +}); diff --git a/packages/app/src/command-center/workspace-contributions.test.ts b/packages/app/src/command-center/workspace-contributions.test.ts index 076f054146..7fb3071046 100644 --- a/packages/app/src/command-center/workspace-contributions.test.ts +++ b/packages/app/src/command-center/workspace-contributions.test.ts @@ -25,12 +25,13 @@ function source(gitActions: GitActions): { dispatched: KeyboardActionDefinition[]; copiedPaths: number; copiedBranchNames: number; + archivedWorkspaces: number; toggledLabels: Array<{ name: string; assigned: boolean }>; } { const runGitActions: GitAction[] = []; const dispatched: KeyboardActionDefinition[] = []; const toggledLabels: Array<{ name: string; assigned: boolean }> = []; - const counters = { copiedPaths: 0, copiedBranchNames: 0 }; + const counters = { copiedPaths: 0, copiedBranchNames: 0, archivedWorkspaces: 0 }; return { value: { gitActions, @@ -68,6 +69,7 @@ function source(gitActions: GitActions): { closePane: "Close pane", toggleFocusMode: "Toggle focus mode", toggleExplorerSidebar: "Toggle Explorer sidebar", + archiveWorkspace: "Archive workspace", rename: "Rename workspace", copyPath: "Copy workspace path", copyBranchName: "Copy branch name", @@ -93,6 +95,9 @@ function source(gitActions: GitActions): { labelCatalog: null, dispatch: (action) => dispatched.push(action), runGitAction: (action) => runGitActions.push(action), + archiveWorkspace: () => { + counters.archivedWorkspaces += 1; + }, copyPath: () => { counters.copiedPaths += 1; }, @@ -112,10 +117,48 @@ function source(gitActions: GitActions): { get copiedBranchNames() { return counters.copiedBranchNames; }, + get archivedWorkspaces() { + return counters.archivedWorkspaces; + }, }; } describe("workspace command center contributions", () => { + it("offers archive in a non-Git workspace and runs the workspace's archive", () => { + const fixture = source({ primary: null, secondary: [], menu: [] }); + + const archive = buildWorkspaceCommandCenterContributions(fixture.value).find( + (item) => item.id === "workspace:archive", + ); + + expect(archive?.visibility).toBe("query"); + expect(archive?.presentation).toMatchObject({ title: "Archive workspace" }); + archive?.run(); + expect(fixture.archivedWorkspaces).toBe(1); + expect(fixture.dispatched).toEqual([]); + }); + + it("omits archive while the workspace cannot be archived", () => { + const fixture = source({ primary: null, secondary: [], menu: [] }); + fixture.value.archiveWorkspace = null; + + const contributions = buildWorkspaceCommandCenterContributions(fixture.value); + + expect(contributions.some((item) => item.id === "workspace:archive")).toBe(false); + }); + + it("lists archive once in a Git workspace, through its Git action", () => { + const archive = gitAction("archive-workspace", "Archive workspace"); + const fixture = source({ primary: null, secondary: [archive], menu: [] }); + fixture.value.capabilities.isGit = true; + + const contributions = buildWorkspaceCommandCenterContributions(fixture.value); + + expect( + contributions.filter((item) => item.id.includes("archive")).map((item) => item.id), + ).toEqual(["git:archive-workspace"]); + }); + it("makes only the policy-selected primary Git action default-visible and runs it", () => { const primary = gitAction("commit", "Commit"); const fixture = source({ diff --git a/packages/app/src/command-center/workspace-contributions.ts b/packages/app/src/command-center/workspace-contributions.ts index 538905cb4a..f3e6e933f9 100644 --- a/packages/app/src/command-center/workspace-contributions.ts +++ b/packages/app/src/command-center/workspace-contributions.ts @@ -50,6 +50,7 @@ export interface WorkspaceCommandCenterLabels { toggleFocusMode: string; toggleExplorerSidebar: string; // Workspace management actions + archiveWorkspace: string; rename: string; copyPath: string; copyBranchName: string; @@ -79,6 +80,7 @@ export interface WorkspaceCommandCenterIcons { focusMode?: CommandCenterIcon; explorerSidebar?: CommandCenterIcon; // Workspace management action icons + archiveWorkspace?: CommandCenterIcon; copyPath?: CommandCenterIcon; copyBranchName?: CommandCenterIcon; pin?: CommandCenterIcon; @@ -131,6 +133,8 @@ export interface WorkspaceCommandCenterSource { labelCatalog: readonly WorkspaceCommandCenterLabelChoice[] | null; dispatch(action: KeyboardActionDefinition): void; runGitAction(action: GitAction): void; + /** Null while the workspace cannot be archived. A Git workspace archives through `gitActions`. */ + archiveWorkspace: (() => void) | null; copyPath(): void; copyBranchName(): void; toggleLabel(name: string, assigned: boolean): void | Promise; @@ -585,6 +589,23 @@ export function buildWorkspaceCommandCenterContributions( contributions.push(buildGitContribution(source, action, 100 + index, "query")); } + // A Git workspace lists archive among its Git actions; any other workspace archives here. + if (!source.capabilities.isGit && source.archiveWorkspace) { + contributions.push( + buildWorkspaceCallback({ + source, + id: "workspace:archive", + rank: 100, + title: source.labels.archiveWorkspace, + keywords: ["archive", "workspace"], + icon: source.icons.archiveWorkspace, + shortcutKeys: source.shortcuts.archiveWorkspace, + run: source.archiveWorkspace, + visibility: "query", + }), + ); + } + if (source.capabilities.canPin) { contributions.push( buildWorkspaceAction({ diff --git a/packages/app/src/command-center/workspace-registration.tsx b/packages/app/src/command-center/workspace-registration.tsx index 41416d30eb..3de2b6d21b 100644 --- a/packages/app/src/command-center/workspace-registration.tsx +++ b/packages/app/src/command-center/workspace-registration.tsx @@ -203,7 +203,7 @@ export function useWorkspaceCommandCenterActions(): void { supportsSetupObservation, ); const { overrides } = useKeyboardShortcutOverrides(); - const { gitActions, isGit } = useGitActions({ + const { gitActions, isGit, archiveWorkspace } = useGitActions({ serverId: serverId ?? "", cwd: cwd ?? "", icons: GIT_ACTION_ICONS, @@ -270,6 +270,7 @@ export function useWorkspaceCommandCenterActions(): void { toggleFocusMode: t("settings.shortcuts.help.toggleFocusMode"), toggleExplorerSidebar: t("workspace.tabs.explorerSidebar.toggle"), // Workspace management labels + archiveWorkspace: t("workspace.git.actions.archive.label"), rename: t("sidebar.workspace.actions.rename"), copyPath: t("workspace.header.actions.copyPath"), copyBranchName: t("workspace.header.actions.copyBranchName"), @@ -280,6 +281,7 @@ export function useWorkspaceCommandCenterActions(): void { }, icons: { ...WORKSPACE_COMMAND_CENTER_ICONS, + archiveWorkspace: staticIcon(GIT_ACTION_ICONS.archive), git: (action) => staticIcon(action.icon), }, shortcuts: resolveWorkspaceShortcuts(overrides), @@ -301,12 +303,14 @@ export function useWorkspaceCommandCenterActions(): void { keyboardActionDispatcher.dispatch(action); }, runGitAction, + archiveWorkspace, copyPath, copyBranchName, toggleLabel, }), [ activeTabIndex, + archiveWorkspace, activeTabKind, canPin, canShowSetup, diff --git a/packages/app/src/git/use-actions.tsx b/packages/app/src/git/use-actions.tsx index 877efa769a..649a8ec5ce 100644 --- a/packages/app/src/git/use-actions.tsx +++ b/packages/app/src/git/use-actions.tsx @@ -209,6 +209,8 @@ interface UseGitActionsResult { gitActions: GitActions; branchLabel: string; isGit: boolean; + /** Archives this workspace, Git or not. Null while it cannot be archived. */ + archiveWorkspace: (() => void) | null; } interface UseWorkspaceScreenArchiveControllerInput { @@ -266,6 +268,13 @@ function canArchiveWorkspace( ); } +function availableArchive( + controller: { canArchive: boolean; isArchiving: boolean }, + archive: () => void, +): (() => void) | null { + return controller.canArchive && !controller.isArchiving ? archive : null; +} + function useWorkspaceScreenArchiveController({ serverId, activeWorkspaceSelection, @@ -864,7 +873,12 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use [gitActionsInput, baseRefLabel, hasPullRequest, forge, t], ); - return { gitActions, branchLabel, isGit }; + return { + gitActions, + branchLabel, + isGit, + archiveWorkspace: availableArchive(archiveController, handleArchiveWorkspace), + }; } function translateGitActions( From 28322f1519d89d79cf4aac59dc6b498a400b9660 Mon Sep 17 00:00:00 2001 From: Huyvux12 <152865675+Huyvux12@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:09:46 +0700 Subject: [PATCH 095/160] fix(server): include local provider config when turn detection is local (#9766) (#9779) --- .../server/speech/providers/local/config.ts | 7 +- .../speech/speech-config-resolver.test.ts | 116 ++++++++++++++++++ 2 files changed, 122 insertions(+), 1 deletion(-) diff --git a/packages/server/src/server/speech/providers/local/config.ts b/packages/server/src/server/speech/providers/local/config.ts index dd52537796..5f504addea 100644 --- a/packages/server/src/server/speech/providers/local/config.ts +++ b/packages/server/src/server/speech/providers/local/config.ts @@ -87,7 +87,12 @@ function shouldIncludeLocalProviderConfig(params: { params.providers.dictationStt.provider === "local") || (params.providers.voiceStt.enabled !== false && params.providers.voiceStt.provider === "local") || - (params.providers.voiceTts.enabled !== false && params.providers.voiceTts.provider === "local"); + (params.providers.voiceTts.enabled !== false && + params.providers.voiceTts.provider === "local") || + // Turn detection is always local, so an enabled local turn detector + // needs the local provider config even when no speech site uses it. + (params.providers.voiceTurnDetection.enabled !== false && + params.providers.voiceTurnDetection.provider === "local"); return ( localRequestedByFeature || diff --git a/packages/server/src/server/speech/speech-config-resolver.test.ts b/packages/server/src/server/speech/speech-config-resolver.test.ts index c83d2c45fa..bca1b85d18 100644 --- a/packages/server/src/server/speech/speech-config-resolver.test.ts +++ b/packages/server/src/server/speech/speech-config-resolver.test.ts @@ -168,6 +168,122 @@ describe("resolveSpeechConfig", () => { }, ); + test("includes local provider config for local turn detection with OpenAI voice STT/TTS", () => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { enabled: false }, + voiceMode: { + enabled: true, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + tts: { provider: "openai", apiKey: "test-key", model: "gpt-4o-mini-tts", voice: "alloy" }, + }, + }, + }); + + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: {} as NodeJS.ProcessEnv, + persisted, + }); + + expect(result.speech.providers.voiceTurnDetection).toEqual({ + provider: "local", + explicit: false, + enabled: true, + }); + expect(result.speech.providers.voiceStt).toEqual({ + provider: "openai", + explicit: true, + enabled: true, + }); + expect(result.speech.providers.voiceTts).toEqual({ + provider: "openai", + explicit: true, + enabled: true, + }); + expect(result.speech.providers.dictationStt).toEqual({ + provider: "local", + explicit: false, + enabled: false, + }); + // Turn detection is always local, so the local provider config must be + // present even when no speech site uses the local provider and no + // models directory is configured; otherwise voice mode reports + // turn_detection_unavailable. + expect(result.speech.local).toEqual({ + modelsDir: path.join("/tmp/paseo-home", "models", "local-speech"), + models: { + dictationStt: "parakeet-tdt-0.6b-v2-int8", + voiceStt: "parakeet-tdt-0.6b-v2-int8", + voiceTts: "kokoro-en-v0_19", + voiceTtsSpeakerId: 0, + }, + }); + }); + + test("includes local provider config for local turn detection with dictation on OpenAI", () => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { + enabled: true, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + }, + voiceMode: { + enabled: true, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + tts: { provider: "openai", apiKey: "test-key", model: "gpt-4o-mini-tts", voice: "alloy" }, + }, + }, + }); + + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: {} as NodeJS.ProcessEnv, + persisted, + }); + + expect(result.speech.providers.voiceTurnDetection).toEqual({ + provider: "local", + explicit: false, + enabled: true, + }); + expect(result.speech.local).toEqual({ + modelsDir: path.join("/tmp/paseo-home", "models", "local-speech"), + models: { + dictationStt: "parakeet-tdt-0.6b-v2-int8", + voiceStt: "parakeet-tdt-0.6b-v2-int8", + voiceTts: "kokoro-en-v0_19", + voiceTtsSpeakerId: 0, + }, + }); + }); + + test("omits local provider config when voice mode is off and no speech site is local", () => { + const persisted = PersistedConfigSchema.parse({ + features: { + dictation: { enabled: false }, + voiceMode: { + enabled: false, + stt: { provider: "openai", apiKey: "test-key", model: "gpt-4o-transcribe" }, + tts: { provider: "openai", apiKey: "test-key", model: "gpt-4o-mini-tts", voice: "alloy" }, + }, + }, + }); + + const result = resolveSpeechConfig({ + paseoHome: "/tmp/paseo-home", + env: {} as NodeJS.ProcessEnv, + persisted, + }); + + expect(result.speech.providers.voiceTurnDetection).toEqual({ + provider: "local", + explicit: false, + enabled: false, + }); + expect(result.speech.local).toBeUndefined(); + }); + test("respects disabled dictation and voice mode feature flags", () => { const persisted = PersistedConfigSchema.parse({ features: { From 685e113358111a9314861be6e1dfae28eb47ecae Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:54:27 +0000 Subject: [PATCH 096/160] Fail paseo agent wait when no agent matches the id (#9782) * fix(cli): fail agent wait when the daemon resolved no agent The daemon answers wait_for_finish with status "error" both when it could not resolve the identifier to an agent (final: null) and when the agent it did resolve finished in error (final: the agent payload). runWaitCommand handed both to buildWaitResult, which returns a normal result row, so `paseo agent wait ` printed "Agent not found: ..." and exited 0 while every sibling command exits 1 with AGENT_NOT_FOUND (#9736). Throw AGENT_NOT_FOUND when the state is error and the payload is null, and let that command error through the inner catch instead of rewrapping it as WAIT_FAILED. A genuine agent failure still carries its payload, so it keeps printing its result row. The wire schema is unchanged. * test(cli): cover the agent wait not-found mapping without module mocks Move the not-found decision into buildWaitResult, which maps the daemon's wait reply to the command result, and test that function directly with plain reply objects instead of mocking the daemon client module. The e2e test in tests/11-agent-wait.test.ts still covers the command against a real daemon. Co-authored-by: Eapp1e <163811520+Eapp1e@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * fix(cli): keep daemon errors during agent wait reported as WAIT_FAILED Map the wait reply to the result after the wait's try/catch, so the AGENT_NOT_FOUND error leaves without the inner catch passing every coded error through. Connection and RPC errors from waitForFinish are wrapped as WAIT_FAILED again, as on main. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Eapp1e <163811520+Eapp1e@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/cli/src/commands/agent/wait.test.ts | 49 ++++++++++++++++++++ packages/cli/src/commands/agent/wait.ts | 27 ++++++++--- packages/cli/tests/11-agent-wait.test.ts | 23 +++++++++ 3 files changed, 93 insertions(+), 6 deletions(-) create mode 100644 packages/cli/src/commands/agent/wait.test.ts diff --git a/packages/cli/src/commands/agent/wait.test.ts b/packages/cli/src/commands/agent/wait.test.ts new file mode 100644 index 0000000000..4cb0b7b7e4 --- /dev/null +++ b/packages/cli/src/commands/agent/wait.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; +import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; +import { buildWaitResult } from "./wait.js"; + +const agentId = "11111111-1111-4111-8111-111111111111"; + +describe("buildWaitResult", () => { + it("reports an identifier the daemon could not resolve as a missing agent", () => { + expect(() => + buildWaitResult({ + state: { + status: "error", + final: null, + error: "Agent not found: does-not-exist", + lastMessage: null, + }, + resolvedAgentId: "does-not-exist", + recentActivity: null, + timeoutLabel: null, + }), + ).toThrow( + expect.objectContaining({ + code: "AGENT_NOT_FOUND", + message: "Agent not found: does-not-exist", + details: "Use `paseo ls` to list available agents", + }), + ); + }); + + it("still reports an agent that finished in error as a result", () => { + const result = buildWaitResult({ + state: { + status: "error", + final: { id: agentId, lastError: "The provider returned 500" } as AgentSnapshotPayload, + error: "The provider returned 500", + lastMessage: null, + }, + resolvedAgentId: agentId, + recentActivity: null, + timeoutLabel: null, + }); + + expect(result).toEqual({ + agentId, + status: "error", + message: "The provider returned 500", + }); + }); +}); diff --git a/packages/cli/src/commands/agent/wait.ts b/packages/cli/src/commands/agent/wait.ts index 3e5e5b533a..1fc91f6772 100644 --- a/packages/cli/src/commands/agent/wait.ts +++ b/packages/cli/src/commands/agent/wait.ts @@ -86,7 +86,12 @@ type WaitFinishState = Awaited< ReturnType>["waitForFinish"]> >; -function buildWaitResult(args: { +/** + * Turn the daemon's wait reply into the command result. Throws AGENT_NOT_FOUND when the + * daemon resolved no agent: it answers an unknown identifier with an error and no agent + * payload, while an agent that finished in error always comes with its payload. + */ +export function buildWaitResult(args: { state: WaitFinishState; resolvedAgentId: string; recentActivity: string | null; @@ -117,6 +122,13 @@ function buildWaitResult(args: { } if (state.status === "error") { + if (state.final === null) { + throw { + code: "AGENT_NOT_FOUND", + message: state.error ?? `Agent not found: ${resolvedAgentId}`, + details: "Use `paseo ls` to list available agents", + } satisfies CommandError; + } return { agentId: resolvedAgentId, status: "error", @@ -155,6 +167,7 @@ export async function runWaitCommand( const client = await connectToDaemon({ target: options.daemonTarget }); + let reply: Omit[0], "timeoutLabel">; try { try { const state = await client.waitForFinish(agentIdArg, timeoutMs); @@ -166,11 +179,7 @@ export async function runWaitCommand( await client.close(); - return { - type: "single", - data: buildWaitResult({ state, resolvedAgentId, recentActivity, timeoutLabel }), - schema: agentWaitSchema, - }; + reply = { state, resolvedAgentId, recentActivity }; } catch (waitErr) { await client.close().catch(() => {}); @@ -198,4 +207,10 @@ export async function runWaitCommand( }; throw error; } + + return { + type: "single", + data: buildWaitResult({ ...reply, timeoutLabel }), + schema: agentWaitSchema, + }; } diff --git a/packages/cli/tests/11-agent-wait.test.ts b/packages/cli/tests/11-agent-wait.test.ts index 198fa08910..5b179b1c3e 100644 --- a/packages/cli/tests/11-agent-wait.test.ts +++ b/packages/cli/tests/11-agent-wait.test.ts @@ -20,6 +20,7 @@ import assert from "node:assert"; import { getAvailablePort } from "./helpers/network.ts"; +import { runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts"; import { $ } from "zx"; import { mkdtemp, rm } from "fs/promises"; import { tmpdir } from "os"; @@ -177,6 +178,28 @@ try { ); console.log("timeout option documents no default limit\n"); } + + // Test 13: wait reports AGENT_NOT_FOUND for an unknown ID + { + console.log("Test 13: wait reports AGENT_NOT_FOUND for an unknown ID"); + const daemon = await startTestDaemon(); + try { + const result = await runPaseoCli(daemon, [ + "wait", + "does-not-exist", + "--host", + `127.0.0.1:${daemon.port}`, + "--json", + ]); + assert.notStrictEqual(result.exitCode, 0, "wait should fail for an unknown ID"); + const { error } = JSON.parse(result.stderr); + assert.strictEqual(error.code, "AGENT_NOT_FOUND", result.stderr); + assert.match(error.details, /paseo ls/); + } finally { + await daemon.stop(); + } + console.log("✓ wait reports AGENT_NOT_FOUND for an unknown ID\n"); + } } finally { // Clean up temp directory await rm(paseoHome, { recursive: true, force: true }); From 2c5f5a1485982adb69154ce2cb455a96673490b7 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:38:16 +0000 Subject: [PATCH 097/160] test(e2e): keep the planted zombie until its shell has exec'd (#9808) The daemon-lifecycle cleanup-failure test planted a zombie with `sleep 0 & echo $!; exec sleep 600`. dash reaps any exited child after a builtin, so when `sleep 0` exited before `echo` returned, the shell reaped it and `ps -o stat= -p ` failed. The child now reads fd 3 until the helper closes it, which it does only after the shell has become `sleep`. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- packages/app/e2e/support/helpers/daemon-lifecycle.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/app/e2e/support/helpers/daemon-lifecycle.ts b/packages/app/e2e/support/helpers/daemon-lifecycle.ts index c38c0f5f78..dba8a25db2 100644 --- a/packages/app/e2e/support/helpers/daemon-lifecycle.ts +++ b/packages/app/e2e/support/helpers/daemon-lifecycle.ts @@ -96,7 +96,7 @@ export async function listTerminalIds(daemon: IsolatedHostDaemon): Promise { +async function psField(pid: number, field: "stat" | "lstart" | "comm"): Promise { const { stdout } = await execFileAsync("ps", ["-o", `${field}=`, "-p", String(pid)], { env: { ...process.env, LC_ALL: "C" }, }); @@ -117,17 +117,22 @@ export interface UnclosableTerminalProgram { export async function plantUnclosableTerminalProgram( daemon: IsolatedHostDaemon, ): Promise { - const parent = spawn("/bin/sh", ["-c", "sleep 0 & echo $!; exec sleep 600"], { - stdio: ["ignore", "pipe", "ignore"], + // The shell reaps any child that has exited whenever it finishes a builtin, so the program + // reads fd 3 until we close it, which happens only once the shell has become `sleep`. + const parent = spawn("/bin/sh", ["-c", "cat <&3 >/dev/null & echo $!; exec sleep 600 3<&-"], { + stdio: ["ignore", "pipe", "ignore", "pipe"], }); parent.unref(); const release = () => { + parent.stdio[3]?.destroy(); if (parent.exitCode === null && parent.signalCode === null) parent.kill("SIGKILL"); }; try { const pid = await new Promise((resolve) => { parent.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim()))); }); + await expect.poll(() => psField(parent.pid!, "comm")).toMatch(/(^|\/)sleep$/); + parent.stdio[3]!.destroy(); await expect.poll(async () => (await psField(pid, "stat")).startsWith("Z")).toBe(true); const gone = spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); await new Promise((resolve) => gone.once("exit", resolve)); From b55955541e4e77d5881ec3de5141d4f1571c0c73 Mon Sep 17 00:00:00 2001 From: tieo <65707274+tieo@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:05:47 +0100 Subject: [PATCH 098/160] fix(dictation): surface the daemon's stream error instead of a delivery timeout (#9784) The daemon drops a dictation stream when its STT session errors and answers every later chunk with dictation_stream_error. The app only listened for acks, so finishing waited 30s and reported a generic timeout. The sender now fails finish with the daemon's message, and the daemon logs the failure that dropped the stream once instead of nothing. Co-authored-by: Claude Opus 5.5 --- .../dictation/dictation-stream-sender.test.ts | 33 +++++++++++++++++ .../src/dictation/dictation-stream-sender.ts | 35 +++++++++++++++++-- .../dictation/dictation-stream-manager.ts | 16 ++++++++- 3 files changed, 80 insertions(+), 4 deletions(-) diff --git a/packages/app/src/dictation/dictation-stream-sender.test.ts b/packages/app/src/dictation/dictation-stream-sender.test.ts index 1af06997a5..ea56e2db5c 100644 --- a/packages/app/src/dictation/dictation-stream-sender.test.ts +++ b/packages/app/src/dictation/dictation-stream-sender.test.ts @@ -90,6 +90,16 @@ class FakeDaemonClient { cancelDictationStream(dictationId: string): void { this.cancels.push(dictationId); } + + emitStreamError(dictationId: string, error: string): void { + const message = { + type: "dictation_stream_error", + payload: { dictationId, error, retryable: true }, + } as SessionOutboundMessage; + for (const listener of this.rawMessageListeners) { + listener(message); + } + } } const tick = async () => { @@ -314,6 +324,29 @@ describe("DictationStreamSender", () => { await expect(finish).resolves.toEqual({ dictationId: "d1", text: "ok" }); }); + it("fails finish with the daemon's stream error instead of waiting for acks", async () => { + const client = new FakeDaemonClient(); + client.autoAck = false; + let nextId = 0; + const sender = new DictationStreamSender({ + client, + format: "audio/pcm;rate=16000;bits=16", + createDictationId: () => `d${++nextId}`, + }); + + sender.enqueueSegment("seg0"); + await tick(); + client.emitStreamError("d1", "Local speech worker request timed out: commit"); + sender.enqueueSegment("seg1"); + await tick(); + + const finish = sender.finish(1); + await expect(promiseOutcome(finish, 1000)).resolves.toBe("rejected"); + await expect(finish).rejects.toThrow("Local speech worker request timed out"); + expect(client.finishes).toEqual([]); + expect(sender.getSegmentCount()).toBe(2); + }); + it("does not replay long buffered native dictation in one synchronous burst", async () => { const client = new FakeDaemonClient(); client.isConnected = false; diff --git a/packages/app/src/dictation/dictation-stream-sender.ts b/packages/app/src/dictation/dictation-stream-sender.ts index 2388458843..387155bc3d 100644 --- a/packages/app/src/dictation/dictation-stream-sender.ts +++ b/packages/app/src/dictation/dictation-stream-sender.ts @@ -8,6 +8,10 @@ const DICTATION_DRAIN_IDLE_TIMEOUT_MS = 30_000; const waitForNextFlushTurn = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); type DictationStreamAckMessage = Extract; +type DictationStreamErrorMessage = Extract< + SessionOutboundMessage, + { type: "dictation_stream_error" } +>; interface DrainWaitResult { kind: "signaled" | "timed-out"; @@ -64,6 +68,7 @@ export class DictationStreamSender { private startGeneration = 0; private startPromise: Promise | null = null; + private streamError: Error | null = null; constructor(params: DictationStreamSenderParams) { this.format = params.format; @@ -88,10 +93,11 @@ export class DictationStreamSender { } this.clientCleanup = client.subscribeRawMessages((message) => { - if (message.type !== "dictation_stream_ack") { - return; + if (message.type === "dictation_stream_ack") { + this.handleAck(message); + } else if (message.type === "dictation_stream_error") { + this.handleStreamError(message); } - this.handleAck(message); }); } @@ -127,6 +133,7 @@ export class DictationStreamSender { this.acknowledgedSeq = -1; this.streamReady = false; this.startPromise = null; + this.streamError = null; this.startGeneration += 1; this.resolveDrainWaiters(); } @@ -197,6 +204,7 @@ export class DictationStreamSender { this.sendSeq = 0; this.acknowledgedSeq = -1; this.streamReady = false; + this.streamError = null; const start = (async () => { await client.startDictationStream(dictationId, this.format); @@ -285,6 +293,25 @@ export class DictationStreamSender { this.resolveDrainWaiters(); } + // The daemon drops a stream after an error and answers later chunks with + // errors instead of acks, so waiting for delivery can only time out. + private handleStreamError(message: DictationStreamErrorMessage): void { + if (message.payload.dictationId !== this.dictationId || this.streamError) { + return; + } + this.streamError = new Error(message.payload.error); + this.resolveDrainWaiters(); + } + + private throwStreamError(): void { + const error = this.streamError; + if (!error) { + return; + } + this.invalidateStream(); + throw error; + } + private invalidateStream(): void { this.resetStreamForReplay(); } @@ -309,11 +336,13 @@ export class DictationStreamSender { private async waitForFlushDrain(finalSeq: number): Promise { while (this.hasPendingDelivery(finalSeq)) { + this.throwStreamError(); const client = this.client; if (!client?.isConnected || !this.dictationId || !this.streamReady) { throw new Error("Failed to flush dictation stream"); } const result = await this.waitForDrainSignal(); + this.throwStreamError(); if (result.kind === "timed-out") { this.invalidateStream(); throw new Error("Timed out waiting for dictation stream delivery"); diff --git a/packages/server/src/server/dictation/dictation-stream-manager.ts b/packages/server/src/server/dictation/dictation-stream-manager.ts index b1b061501f..ac91fba00e 100644 --- a/packages/server/src/server/dictation/dictation-stream-manager.ts +++ b/packages/server/src/server/dictation/dictation-stream-manager.ts @@ -345,7 +345,7 @@ export class DictationStreamManager { }): Promise { const state = this.streams.get(params.dictationId); if (!state) { - this.failDictationStream(params.dictationId, "Dictation stream not started", true); + this.emitUnknownStreamError(params.dictationId); return; } @@ -528,7 +528,17 @@ export class DictationStreamManager { return path; } + // Chunks keep arriving for a stream the daemon already dropped, one error + // per chunk; the failure that dropped it is logged where it happened. + private emitUnknownStreamError(dictationId: string): void { + this.emit({ + type: "dictation_stream_error", + payload: { dictationId, error: "Dictation stream not started", retryable: true }, + }); + } + private failDictationStream(dictationId: string, error: string, retryable: boolean): void { + this.logger.warn({ dictationId, error, retryable }, "Dictation stream failed"); this.emit({ type: "dictation_stream_error", payload: { dictationId, error, retryable }, @@ -543,6 +553,10 @@ export class DictationStreamManager { const state = this.streams.get(dictationId); const debugRecordingPath = await this.maybePersistDictationStreamAudio(dictationId); if (!state || this.streams.get(dictationId) !== state) return; + this.logger.warn( + { dictationId, error, retryable, ackSeq: state.ackSeq }, + "Dictation stream failed", + ); this.emit({ type: "dictation_stream_error", payload: { From 8c88b83cd8d835a51d64870bdded92a193532cdf Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:02:46 +0000 Subject: [PATCH 099/160] fix(server): preview the newest turn's reply in finished notifications (#9793) A turn the provider starts on its own, such as Claude waking after a background subagent, has no user message before its reply. The last assistant message lookup joined every adjacent assistant row, so it returned the previous turn's reply with the new one appended, and the 220-character notification preview showed only the old reply. Stop the backward scan at the turn boundary so the lookup returns only the newest turn's reply, while chunks of one turn are still joined. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/agent-manager.test.ts | 45 +++++++++++++++++++ .../server/src/server/agent/agent-manager.ts | 23 +++++++--- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 966b66f2ec..4c592d5387 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -13487,6 +13487,51 @@ test.each(["live", "history", "accepted"] as const)( }, ); +test("the last assistant message is the newest turn's reply, not joined to the previous turn's", async () => { + const session = new TestAgentSession({ provider: "codex", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-last-reply-")); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ clients: { codex: client }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const reply = (turnId: string, messageId: string, text: string) => + session.pushEvent({ + type: "timeline", + provider: "codex", + turnId, + item: { type: "assistant_message", messageId, text }, + }); + try { + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn-1" }); + reply("turn-1", "message-1", "Earlier status, "); + reply("turn-1", "message-1", "streamed in two chunks."); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "turn-1" }); + await vi.waitFor(async () => + expect(await manager.getLastAssistantMessage(agent.id)).toBe( + "Earlier status, streamed in two chunks.", + ), + ); + + // A turn the provider starts on its own, such as a background task waking the agent, + // has no user message between its reply and the previous turn's. + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn-2" }); + reply("turn-2", "message-2", "New status."); + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "turn-2" }); + await vi.waitFor(() => + expect(manager.getTimeline(agent.id).at(-1)).toMatchObject({ messageId: "message-2" }), + ); + expect(await manager.getLastAssistantMessage(agent.id)).toBe("New status."); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("reads the last durable assistant response without loading a stored-only child", async () => { const store = new RecordingTimelineStore(); await store.appendCommitted("stored-child", { diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 34af303027..81d25be675 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -4049,23 +4049,33 @@ export class AgentManager { private getLastAssistantMessageFromTimeline( timeline: readonly AgentTimelineItem[], ): string | null { - return this.getLastAssistantMessageSegmentFromTimeline(timeline)?.text ?? null; + return ( + this.getLastAssistantMessageSegmentFromTimeline(timeline.map((item) => ({ item })))?.text ?? + null + ); } private getLastAssistantMessageSegmentFromTimeline( - timeline: readonly AgentTimelineItem[], + timeline: readonly Pick[], ): { text: string; startsAtBeginning: boolean } | null { - // Collect the last contiguous assistant messages (Claude streams chunks) + // Collect the last contiguous assistant messages of one turn (Claude streams chunks). + // A turn the provider starts on its own has no user message before its reply. const chunks: string[] = []; + let replyTurnId: string | undefined; let startsAtBeginning = false; for (let i = timeline.length - 1; i >= 0; i--) { - const item = timeline[i]; + const { item, turnId } = timeline[i]; if (item.type !== "assistant_message") { if (chunks.length) { break; } continue; } + if (chunks.length === 0) { + replyTurnId = turnId; + } else if (turnId !== replyTurnId) { + break; + } chunks.push(item.text); startsAtBeginning = i === 0; } @@ -4081,8 +4091,9 @@ export class AgentManager { } private async getLastAssistantMessageFromStores(agentId: string): Promise { - const liveTimeline = this.timelineStore.getItems(agentId); - const liveSegment = this.getLastAssistantMessageSegmentFromTimeline(liveTimeline); + const liveSegment = this.getLastAssistantMessageSegmentFromTimeline( + this.timelineStore.getRows(agentId), + ); if (!this.durableTimelineStore) { return liveSegment?.text ?? null; } From 0273b6b614bac623168d03e7f89f9e161274b468 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:52:24 +0000 Subject: [PATCH 100/160] fix(app): end bare URLs at CJK and fullwidth punctuation (#9799) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bare URL that md4c does not autolink is linked by the text-link pattern. That pattern stopped only at ASCII whitespace, quotes and sentence punctuation, so "https://a.com、https://b.com!" became one link, and "看这里:https://example.com/foo,还有" linked ",还有" too. Opening the link went to a URL ending in the encoded punctuation. CJK, fullwidth and typographic punctuation (、。,()【】「」“”…) now ends the URL. CJK letters in paths still stay in the link. Refs #9743 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/components/markdown/renderer.test.ts | 28 +++++++++++++++++++ .../app/src/components/markdown/source.ts | 7 +++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/app/src/components/markdown/renderer.test.ts b/packages/app/src/components/markdown/renderer.test.ts index 61d3e0e4d4..e74d12a697 100644 --- a/packages/app/src/components/markdown/renderer.test.ts +++ b/packages/app/src/components/markdown/renderer.test.ts @@ -562,6 +562,34 @@ describe("bare URL sentence punctuation", () => { expect(tree.children?.[0]?.children?.[0]?.attributes?.url).toBe("https://example.com/a."); }, ); + + it.each([ + ["https://a.com、https://b.com!", ["https://a.com", "、", "https://b.com", "!"]], + ["https://a.com(说明)以及", ["https://a.com", "(说明)以及"]], + ["看这里:https://example.com/foo,还有", ["看这里:", "https://example.com/foo", ",还有"]], + ["(https://example.com/a)", ["(", "https://example.com/a", ")"]], + ["见【https://example.com/a】。", ["见【", "https://example.com/a", "】。"]], + ["“https://example.com/a”…", ["“", "https://example.com/a", "”…"]], + [ + "见https://zh.wikipedia.org/wiki/人工智能。", + ["见", "https://zh.wikipedia.org/wiki/人工智能", "。"], + ], + ])("ends a bare URL at CJK and typographic punctuation: %s", async (source, expected) => { + const prepared = prepareMarkdownSource(source); + const tree = recognizeTextLinks( + await parseMarkdown(prepared.render(), { latexMath: false }), + prepared.linkRecognition.text, + prepared.linkRecognition.inlineCode, + ); + const parts = (tree.children?.[0]?.children ?? []).map((node) => + node.type === "Link" ? String(node.attributes?.url) : String(node.content), + ); + expect(parts).toEqual(expected); + expect(toNativeLinkRecognition(prepared.linkRecognition).text).toMatchObject({ + isDisabled: false, + isDefault: false, + }); + }); }); it("requires workspace context for relative inline paths and escapes literal regex characters", () => { diff --git a/packages/app/src/components/markdown/source.ts b/packages/app/src/components/markdown/source.ts index ae3cdcba46..0a87dc0163 100644 --- a/packages/app/src/components/markdown/source.ts +++ b/packages/app/src/components/markdown/source.ts @@ -37,9 +37,12 @@ function createTextPattern(path: string, forgeReferencePattern?: string): RegExp // Matches bare URLs that MD4C does not autolink, like single-label or bracketed hosts. // Quotes and unbalanced closing parentheses end the URL. Trailing sentence punctuation stays outside. -const URL_CHARACTER = String.raw`[^\s<>()"'\x60]`; +// CJK, fullwidth and typographic punctuation (、。,()【】「」“”…) also ends it; CJK letters do not. +const URL_BOUNDARY = + "\\u2018\\u2019\\u201C\\u201D\\u2026\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65"; +const URL_CHARACTER = String.raw`[^\s<>()"'\x60${URL_BOUNDARY}]`; const URL_GROUP = String.raw`\(${URL_CHARACTER}*\)`; -const BARE_URL = String.raw`https?://(?:${URL_CHARACTER}|${URL_GROUP})*(?:[^\s<>()"'\x60.,;:!?]|${URL_GROUP})`; +const BARE_URL = String.raw`https?://(?:${URL_CHARACTER}|${URL_GROUP})*(?:[^\s<>()"'\x60.,;:!?${URL_BOUNDARY}]|${URL_GROUP})`; const TEXT_PATTERN = createTextPattern(PROSE_PATH); // One entry per distinct workspace forge remote; reuse keeps the engine's regex identity stable. From a7a12ef4cdcaa183bbedfc876580971a43e3b5be Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 09:37:55 +0700 Subject: [PATCH 101/160] fix(app): keep expanded tool details within their group (#9770) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(app): bound complete inline tool details within groups Apply the detail height allowance to the complete input/output/error disclosure so expanding a tool cannot bury its collapse header outside the group viewport. * test(app): verify tool disclosure geometry across painted frames * test(app): measure disclosure bounds without evidence capture * fix(app): give capped tool details one vertical scroll owner * fix(app): allow inline tool details to scroll on iPad A hover-only Pressable claimed the native responder around the detail scroll view. Keep hover reporting on a passive View so drags reach the capped detail and its later sections remain accessible. * fix(app): preserve scroll position inside overflowing tool groups Content-size changes also come from nested disclosures. Follow newly appended calls while preserving the reader’s position when a disclosure changes height. * test(app): assert inline tool visibility on iPad Offscreen Output nodes exist before the pan, so selector waits cannot prove reachability. Assert visibility before and after scrolling and verify that collapsing hides the contents before reopening. * refactor(app): remove unused tool detail hover callbacks * docs(app): correct inline detail test coverage note * fix(app): apply grouped detail allowance to reasoning --- .../browser/tool-call-overview-sheet.spec.ts | 232 +++++++++++++++++- ...native-inline-tool-scroll-preconditions.md | 28 +++ .../native-inline-tool-scroll.ios.yaml | 28 +++ .../agent-stream/disclosure.browser.test.tsx | 85 +++++++ packages/app/src/agent-stream/view.tsx | 4 + packages/app/src/components/diff-viewer.tsx | 13 +- packages/app/src/components/message.tsx | 27 +- .../app/src/components/tool-call-details.tsx | 94 ++++--- .../tool-calls/detail-level/overview/view.tsx | 48 ++-- 9 files changed, 463 insertions(+), 96 deletions(-) create mode 100644 packages/app/e2e/mobile/agent-device/native-inline-tool-scroll-preconditions.md create mode 100644 packages/app/e2e/mobile/agent-device/native-inline-tool-scroll.ios.yaml diff --git a/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts b/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts index 0b3a068e63..e9fa05ea1e 100644 --- a/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts +++ b/packages/app/e2e/browser/tool-call-overview-sheet.spec.ts @@ -153,21 +153,29 @@ async function holdStreamAfterFirstCompletedToolCall(page: Page, agentId: string type OverviewChatDisplay = "collapseToolCalls" | "collapseTurns"; // Expand thinking keeps reasoning out of tool call runs, so the first tool call starts alone. -async function configureOverviewToolCalls(page: Page, chatDisplay: OverviewChatDisplay) { - await page.addInitScript((display) => { - localStorage.setItem( - "@paseo:app-settings", - JSON.stringify({ chatDisplay: display, autoExpandReasoning: true }), - ); - }, chatDisplay); +async function configureOverviewToolCalls( + page: Page, + chatDisplay: OverviewChatDisplay, + autoExpandReasoning: boolean, +) { + await page.addInitScript( + ({ display, expandReasoning }) => { + localStorage.setItem( + "@paseo:app-settings", + JSON.stringify({ chatDisplay: display, autoExpandReasoning: expandReasoning }), + ); + }, + { display: chatDisplay, expandReasoning: autoExpandReasoning }, + ); } async function createOverviewAgent( page: Page, title: string, chatDisplay: OverviewChatDisplay = "collapseToolCalls", + autoExpandReasoning = true, ) { - await configureOverviewToolCalls(page, chatDisplay); + await configureOverviewToolCalls(page, chatDisplay, autoExpandReasoning); return seedMockAgentWorkspace({ repoPrefix: "tool-call-overview-sheet-", title, @@ -401,3 +409,211 @@ test("forms a closed group when the lone tool call was left closed", async ({ pa await agent.cleanup(); } }); + +const longGroupedDetail = { + type: "unknown", + input: Array.from({ length: 80 }, (_, i) => `Long input ${i}`), + output: Array.from({ length: 80 }, (_, i) => `Long output ${i}`), +}; + +function provideLongReadDetail(item: Record | undefined) { + if (item?.type === "tool_call" && item.name === "read") item.detail = longGroupedDetail; +} + +function provideLongReasoningDetail(item: Record | undefined) { + if (item?.type === "reasoning") { + item.text = Array.from({ length: 80 }, (_, i) => `Long reasoning ${i}`).join("\n"); + } +} + +async function provideLongToolDetails(page: Page, transformItem = provideLongReadDetail) { + await page.routeWebSocket(daemonWsRoutePattern(), (ws) => { + const server = ws.connectToServer(); + ws.onMessage((message) => server.send(message)); + server.onMessage((message) => { + const raw = typeof message === "string" ? message : message.toString("utf8"); + const envelope = JSON.parse(raw); + const item = envelope.message?.payload?.event?.item; + transformItem(item); + if (envelope.message?.type === "fetch_agent_timeline_response") { + for (const entry of envelope.message.payload.entries) transformItem(entry.item); + } + ws.send(JSON.stringify(envelope)); + }); + }); +} + +async function toggleAndMeasureTool(badge: Locator) { + await badge.scrollIntoViewIfNeeded(); + await badge.evaluate((node) => { + // Inline groups own a bounded viewport; opened turns use the chat viewport. + const container = + node.closest('[data-testid="tool-call-group"]') ?? + node.closest('[data-testid="agent-chat-scroll"]'); + if (!container) throw new Error("Expected a tool inside a group or chat viewport"); + const frames: { top: number; height: number; containerHeight: number }[] = []; + (node as HTMLElement & { disclosureFrames: typeof frames }).disclosureFrames = frames; + node.querySelector("button")!.addEventListener( + "click", + () => { + const measure = () => { + const bounds = node.getBoundingClientRect(); + frames.push({ + top: bounds.top, + height: bounds.height, + containerHeight: container.getBoundingClientRect().height, + }); + if (frames.length < 20) requestAnimationFrame(measure); + }; + requestAnimationFrame(measure); + }, + { once: true }, + ); + }); + await openToolDetails(badge); + await expect + .poll(() => + badge.evaluate( + (node) => (node as HTMLElement & { disclosureFrames: unknown[] }).disclosureFrames.length, + ), + ) + .toBe(20); + return badge.evaluate( + (node) => + ( + node as HTMLElement & { + disclosureFrames: { top: number; height: number; containerHeight: number }[]; + } + ).disclosureFrames, + ); +} + +for (const display of ["collapseToolCalls", "collapseTurns"] as const) { + test(`keeps multi-section tool details within the group (${display})`, async ({ page }) => { + test.setTimeout(120_000); + const agent = await createOverviewAgent(page, "Bounded grouped tool details", display); + try { + await provideLongToolDetails(page); + await openOverviewAgent(page, agent); + await agent.client.sendAgentMessage(agent.agentId, "Exercise bounded grouped details."); + await agent.client.waitForAgentUpsert( + agent.agentId, + (snapshot) => snapshot.status === "idle", + 30_000, + ); + // A fresh mount of a finished conversation starts with its disclosures closed. + await page.reload(); + await expectComposerVisible(page); + if (display === "collapseToolCalls") { + await scrollChatAwayFromBottom(page, { deltaY: -10_000, minDistanceFromBottom: 1 }); + } + const group = page.getByTestId("tool-call-group").first(); + if (display === "collapseTurns") { + await expect(page.getByTestId("tool-call-badge")).toHaveCount(0); + await openToolDetails(page.getByTestId("turn-summary").first()); + } else { + await expect(group).toBeVisible(); + await expect(group.getByTestId("tool-call-badge")).toHaveCount(0); + await openToolDetails(group); + } + const scope = display === "collapseTurns" ? page : group; + const badge = scope.getByTestId("tool-call-badge").filter({ hasText: "Read" }).first(); + await expect(badge).toBeVisible(); + const expandedFrames = await toggleAndMeasureTool(badge); + for (const frame of expandedFrames) + expect(frame.height).toBeLessThanOrEqual(frame.containerHeight); + expect( + Math.max(...expandedFrames.map((frame) => frame.top)) - + Math.min(...expandedFrames.map((frame) => frame.top)), + ).toBeLessThanOrEqual(1); + await expect(badge).toContainText("Long output"); + const collapsedFrames = await toggleAndMeasureTool(badge); + expect( + Math.max(...collapsedFrames.map((frame) => frame.top)) - + Math.min(...collapsedFrames.map((frame) => frame.top)), + ).toBeLessThanOrEqual(1); + await expect(badge).not.toContainText("Long output"); + } finally { + await agent.cleanup(); + } + }); +} + +test("keeps tool headers reachable in an overflowing group", async ({ page }) => { + test.setTimeout(120_000); + const agent = await createOverviewAgent(page, "Overflowing overview tool group"); + try { + const gate = await holdStreamAfterFirstCompletedToolCall(page, agent.agentId); + await openOverviewAgent(page, agent); + await agent.client.sendAgentMessage(agent.agentId, "Inspect a large tool group."); + await gate.waitForFirstCompleted(); + gate.appendCompletedCalls(15); + const group = page.getByTestId("tool-call-group").first(); + await openToolDetails(group); + const badges = group.getByTestId("tool-call-badge"); + await expect(badges).toHaveCount(16); + await expect.poll(() => group.evaluate(hasScrolledToLatest)).toBe(true); + const first = badges.first(); + for (const action of ["expand", "collapse"]) { + await test.step(`${action} the first tool without moving its header`, async () => { + await first.scrollIntoViewIfNeeded(); + const headerTop = await topOf(first); + const frames = await toggleAndMeasureTool(first); + for (const frame of frames) expect(Math.abs(frame.top - headerTop)).toBeLessThanOrEqual(1); + }); + } + await test.step("follow the next appended tool", async () => { + gate.appendCompletedCalls(1); + await expect(badges).toHaveCount(17); + await expect.poll(() => group.evaluate(hasScrolledToLatest)).toBe(true); + }); + await test.step("reopen the group at its latest tool", async () => { + await openToolDetails(group); + await expect(badges).toHaveCount(0); + await openToolDetails(group); + await expect(badges).toHaveCount(17); + await expect.poll(() => group.evaluate(hasScrolledToLatest)).toBe(true); + }); + } finally { + await agent.cleanup(); + } +}); + +test("keeps expanded reasoning within the group viewport", async ({ page }) => { + test.setTimeout(120_000); + const agent = await createOverviewAgent( + page, + "Bounded grouped reasoning", + "collapseToolCalls", + false, + ); + try { + // Seed before opening so the fixture transforms complete snapshots, not token deltas. + await agent.client.sendAgentMessage(agent.agentId, "Inspect grouped reasoning."); + await agent.client.waitForAgentUpsert( + agent.agentId, + (snapshot) => snapshot.status === "idle", + 30_000, + ); + await provideLongToolDetails(page, provideLongReasoningDetail); + await openOverviewAgent(page, agent); + await scrollChatAwayFromBottom(page, { deltaY: -10_000, minDistanceFromBottom: 1 }); + const group = page.getByTestId("tool-call-group").first(); + await openToolDetails(group); + const thought = group.getByTestId("tool-call-badge").filter({ hasText: "Thinking" }).first(); + const frames = await toggleAndMeasureTool(thought); + const viewportHeight = await group.evaluate((node) => { + const scroll = Array.from(node.querySelectorAll("*")).find((child) => + ["auto", "scroll"].includes(getComputedStyle(child).overflowY), + ); + if (!scroll) throw new Error("Expected the group's scroll viewport"); + return scroll.getBoundingClientRect().height; + }); + for (const frame of frames) expect(frame.height).toBeLessThanOrEqual(viewportHeight); + await expect(thought).toContainText("Long reasoning 79"); + await openToolDetails(thought); + await expect(thought).not.toContainText("Long reasoning 79"); + } finally { + await agent.cleanup(); + } +}); diff --git a/packages/app/e2e/mobile/agent-device/native-inline-tool-scroll-preconditions.md b/packages/app/e2e/mobile/agent-device/native-inline-tool-scroll-preconditions.md new file mode 100644 index 0000000000..76068b074a --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-inline-tool-scroll-preconditions.md @@ -0,0 +1,28 @@ +# Inline tool detail scrolling on iPad + +Use a task-owned iPad Pro 11-inch (M5) simulator in portrait (834×1210 points), +with the development bundle already loaded and a connected isolated mock host. +Set Chat display to Collapse turns. Prepare a finished turn containing a tool +named `scroll_probe`, with unknown detail: `input` is 80 newline-separated +`input-line-N` lines (N=0…79), and `output` is `SCROLL_REACHED_OUTPUT`. + +Expand the turn, scroll chat to its start, and expand Scroll probe. The tool's +header must be at y=613…644 and its 400-point body below it. The fixed pan path +starts inside that body and stays inside it. Output starts below the cap. +These are replay preconditions, not asserted pixel sizes. Close other expanded +tools so the Scroll probe selector identifies this disclosure. + +Replay `native-inline-tool-scroll.ios.yaml --maestro` on that explicit simulator +through the existing mobile runner or agent-device. In Expo's development menu, +turn off Tools button, then dismiss the known notification entitlement toast +with its bottom-right close button. Their transparent accessibility windows +otherwise mark app text covered. Another overlay must fail the visibility +assertions. Pass `--platform ios` and the prepared session's `--state-dir` when +replaying in that session. + +The flow first asserts Input is visible and the output marker is not. After +panning it requires Output and its marker to be visible, then requires closing +the tool to hide its contents and reopening it to show Input again. Presence in +the accessibility tree is insufficient. A negative control with the passive +wrapper retained and only the detail's scrolling disabled must fail at Output +visibility. The browser disclosure suite checks tab navigation. diff --git a/packages/app/e2e/mobile/agent-device/native-inline-tool-scroll.ios.yaml b/packages/app/e2e/mobile/agent-device/native-inline-tool-scroll.ios.yaml new file mode 100644 index 0000000000..24d93ea95b --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-inline-tool-scroll.ios.yaml @@ -0,0 +1,28 @@ +appId: sh.paseo.debug +--- +- assertVisible: + id: workspace-tabs-scroll +- assertVisible: Scroll probe +- assertVisible: Input +- assertNotVisible: SCROLL_REACHED_OUTPUT +- repeat: + times: 7 + commands: + - swipe: + start: "600,850" + end: "600,670" + duration: 600 +- swipe: + start: "600,850" + end: "600,700" + duration: 600 +- assertVisible: Output +- assertVisible: SCROLL_REACHED_OUTPUT +- tapOn: + point: "600,628" +- assertNotVisible: Output +- assertNotVisible: Input +- tapOn: + point: "600,628" +- assertVisible: Input +- stopApp diff --git a/packages/app/src/agent-stream/disclosure.browser.test.tsx b/packages/app/src/agent-stream/disclosure.browser.test.tsx index 020e5d8e94..8ec7c545ee 100644 --- a/packages/app/src/agent-stream/disclosure.browser.test.tsx +++ b/packages/app/src/agent-stream/disclosure.browser.test.tsx @@ -4,6 +4,7 @@ import { within } from "@testing-library/dom"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { i18n as testI18n } from "@/i18n/i18next"; +import { ToolCallDetailsContent } from "@/components/tool-call-details"; import { ExpandableBadge } from "@/components/message"; import { page, userEvent } from "vitest/browser"; import { PlanCard } from "@/components/plan-card"; @@ -202,3 +203,87 @@ describe("tool badge file action", () => { expect(view().queryByText("File contents")).toBeNull(); }); }); + +const longDetail = { + type: "unknown" as const, + input: { text: "input\n".repeat(80) }, + output: { text: "output\n".repeat(80) }, +}; + +describe("inline tool detail height", () => { + it("caps the complete detail, including input, output and error, to its allowance", () => { + act(() => + root.render( + + + , + ), + ); + expect(container.getBoundingClientRect().height).toBeLessThanOrEqual(200); + expect(container.textContent).toContain("output"); + expect(container.textContent).toContain("error"); + }); +}); + +const longShellDetail = { + type: "shell" as const, + command: "echo command\n".repeat(80), + output: "output\n".repeat(80), +}; + +const longEditDetail = { + type: "edit" as const, + filePath: "example.txt", + oldString: "old line\n".repeat(80), + newString: "new line\n".repeat(80), +}; + +describe("capped tool scrolling", () => { + it.each([longShellDetail, longEditDetail])( + "gives a capped $type detail one vertical scroll owner", + (detail) => { + act(() => + root.render( + + + , + ), + ); + const verticalScrollers = Array.from(container.querySelectorAll("*")).filter((node) => + ["auto", "scroll"].includes(getComputedStyle(node).overflowY), + ); + expect(verticalScrollers).toHaveLength(1); + expect(container.getBoundingClientRect().height).toBeLessThanOrEqual(200); + }, + ); +}); + +function renderCopyOutput() { + return ; +} + +describe("tool detail interaction", () => { + it("keeps detail controls in the tab order", async () => { + function Badge() { + const [expanded, setExpanded] = React.useState(true); + const toggle = React.useCallback(() => setExpanded(!expanded), [expanded]); + return ( + + ); + } + act(() => root.render()); + const header = view().getByRole("button", { name: "Probe" }); + act(() => header.focus()); + await userEvent.keyboard("{Tab}"); + expect(document.activeElement).toBe(view().getByRole("button", { name: "Copy output" })); + }); +}); diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index 7ea2c7e5d9..9f71998a41 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -883,6 +883,7 @@ const AgentStreamViewComponent = forwardRef @@ -1375,6 +1376,7 @@ interface ThoughtSlotProps { isLastInSequence: boolean; defaultExpanded: boolean; standalone?: boolean; + maxDetailHeight?: number; } // Reasoning text is paced the same way assistant text is; see @/hooks/use-revealed-text. @@ -1386,6 +1388,7 @@ function ThoughtSlot({ isLastInSequence, defaultExpanded, standalone, + maxDetailHeight, }: ThoughtSlotProps) { const revealedText = useRevealedText(text, status === "ready" ? "complete" : "streaming"); return ( @@ -1398,6 +1401,7 @@ function ThoughtSlot({ isLastInSequence={isLastInSequence} defaultExpanded={defaultExpanded} standalone={standalone} + maxDetailHeight={maxDetailHeight} forceInline={defaultExpanded} /> ); diff --git a/packages/app/src/components/diff-viewer.tsx b/packages/app/src/components/diff-viewer.tsx index 8d14effdc6..e2b01dae08 100644 --- a/packages/app/src/components/diff-viewer.tsx +++ b/packages/app/src/components/diff-viewer.tsx @@ -15,7 +15,6 @@ const ScrollView = isWeb ? RNScrollView : GHScrollView; interface DiffViewerProps { diffLines: DiffLine[]; - maxHeight?: number; emptyLabel?: string; fillAvailableHeight?: boolean; } @@ -119,7 +118,6 @@ function DiffSegment({ export function DiffViewer({ diffLines, - maxHeight, emptyLabel, fillAvailableHeight = false, }: DiffViewerProps) { @@ -133,12 +131,8 @@ export function DiffViewer({ ); const outerScrollStyle = React.useMemo( - () => [ - styles.verticalScroll, - maxHeight !== undefined && inlineUnistylesStyle({ maxHeight }), - fillAvailableHeight && styles.fillHeight, - ], - [maxHeight, fillAvailableHeight], + () => [styles.verticalScroll, fillAvailableHeight && styles.fillHeight], + [fillAvailableHeight], ); const linesContainerStyle = React.useMemo( () => [ @@ -184,6 +178,9 @@ export function DiffViewer({ ); + // Capped tool details own vertical scrolling outside the diff. + if (!fillAvailableHeight) return horizontalScroll; + const content = ( ; onToggle?: () => void; onOpenFile?: () => void; - onDetailHoverChange?: (hovered: boolean) => void; renderDetails?: () => ReactNode; isLoading?: boolean; isError?: boolean; @@ -1887,7 +1886,6 @@ export const ExpandableBadge = memo(function ExpandableBadge({ isExpanded, onToggle, onOpenFile, - onDetailHoverChange, renderDetails, isLoading = false, isError = false, @@ -1913,11 +1911,6 @@ export const ExpandableBadge = memo(function ExpandableBadge({ }, []); const handlePressIn = useCallback(() => setIsPressed(true), []); const handlePressOut = useCallback(() => setIsPressed(false), []); - const handleDetailHoverIn = useCallback(() => onDetailHoverChange?.(true), [onDetailHoverChange]); - const handleDetailHoverOut = useCallback( - () => onDetailHoverChange?.(false), - [onDetailHoverChange], - ); const handleOpenFilePress = useCallback( (event: GestureResponderEvent) => { event.stopPropagation?.(); @@ -2207,14 +2200,9 @@ export const ExpandableBadge = memo(function ExpandableBadge({ ) : null} {detailContent ? ( - + {detailContent} - + ) : null} ); @@ -2234,7 +2222,6 @@ function areExpandableBadgePropsEqual(previous: ExpandableBadgeProps, next: Expa if (previous.testID !== next.testID) return false; if (previous.onToggle !== next.onToggle) return false; if (previous.onOpenFile !== next.onOpenFile) return false; - if (previous.onDetailHoverChange !== next.onDetailHoverChange) return false; if (previous.renderDetails !== next.renderDetails) return false; return true; } @@ -2252,7 +2239,6 @@ interface ToolCallProps { metadata?: Record; isLastInSequence?: boolean; disableOuterSpacing?: boolean; - onInlineDetailsHoverChange?: (hovered: boolean) => void; onInlineDetailsExpandedChange?: (expanded: boolean) => void; onOpenFilePath?: (filePath: string) => void; defaultExpanded?: boolean; @@ -2276,7 +2262,6 @@ export const ToolCall = memo(function ToolCall({ metadata, isLastInSequence = false, disableOuterSpacing, - onInlineDetailsHoverChange, onInlineDetailsExpandedChange, onOpenFilePath, defaultExpanded, @@ -2362,13 +2347,6 @@ export const ToolCall = memo(function ToolCall({ presentation.isLoadingDetails, ]); - useEffect(() => { - if (!onInlineDetailsHoverChange || !shouldRenderInline || isExpanded) { - return; - } - onInlineDetailsHoverChange(false); - }, [isExpanded, shouldRenderInline, onInlineDetailsHoverChange]); - useEffect(() => { if (!onInlineDetailsExpandedChange) { return; @@ -2435,7 +2413,6 @@ export const ToolCall = memo(function ToolCall({ isError={status === "failed"} isLastInSequence={isLastInSequence} disableOuterSpacing={disableOuterSpacing} - onDetailHoverChange={onInlineDetailsHoverChange} /> ); }, areToolCallPropsEqual); diff --git a/packages/app/src/components/tool-call-details.tsx b/packages/app/src/components/tool-call-details.tsx index 5e08f944df..4101e00036 100644 --- a/packages/app/src/components/tool-call-details.tsx +++ b/packages/app/src/components/tool-call-details.tsx @@ -5,6 +5,7 @@ import { ScrollView as RNScrollView, type StyleProp, type ViewStyle, + type ScrollViewProps, } from "react-native"; import { ScrollView as GHScrollView } from "react-native-gesture-handler"; import { StyleSheet } from "react-native-unistyles"; @@ -28,6 +29,25 @@ import { isWeb } from "@/constants/platform"; const ScrollView = isWeb ? RNScrollView : GHScrollView; +// A capped detail scrolls as a whole. Only full-height sheets need section scrollers. +function DetailSectionBody({ + fillAvailableHeight, + style, + contentContainerStyle, + children, + ...scrollProps +}: ScrollViewProps & { fillAvailableHeight: boolean }) { + const bodyStyle = useMemo(() => [style, contentContainerStyle], [style, contentContainerStyle]); + if (fillAvailableHeight) { + return ( + + {children} + + ); + } + return {children}; +} + // ---- Content Component ---- interface ToolCallDetailsContentProps { @@ -40,6 +60,7 @@ interface ToolCallDetailsContentProps { } interface DetailStyles { + fillAvailableHeight: boolean; sectionFillStyle: StyleProp; codeBlockFillStyle: StyleProp; codeVerticalScrollStyle: StyleProp; @@ -49,7 +70,6 @@ interface DetailStyles { jsonScrollErrorCombined: StyleProp; fullBleedContainerStyle: StyleProp; loadingContainerStyle: StyleProp; - resolvedMaxHeight: number | undefined; shouldFill: boolean; isFullBleed: boolean; } @@ -69,7 +89,6 @@ function resolveShouldFill( function useDetailStyles( detail: ToolCallDetail | undefined, - resolvedMaxHeight: number | undefined, fillAvailableHeight: boolean, ): DetailStyles { const isFullBleed = resolveIsFullBleed(detail); @@ -85,28 +104,14 @@ function useDetailStyles( [codeBlockStyle, shouldFill], ); const codeVerticalScrollStyle = useMemo( - () => [ - styles.codeVerticalScroll, - resolvedMaxHeight !== undefined && inlineUnistylesStyle({ maxHeight: resolvedMaxHeight }), - shouldFill && styles.fillHeight, - ], - [resolvedMaxHeight, shouldFill], + () => [styles.codeVerticalScroll, shouldFill && styles.fillHeight], + [shouldFill], ); const scrollAreaFillStyle = useMemo( - () => [ - styles.scrollArea, - resolvedMaxHeight !== undefined && inlineUnistylesStyle({ maxHeight: resolvedMaxHeight }), - shouldFill && styles.fillHeight, - ], - [resolvedMaxHeight, shouldFill], - ); - const scrollAreaStyle = useMemo( - () => [ - styles.scrollArea, - resolvedMaxHeight !== undefined && inlineUnistylesStyle({ maxHeight: resolvedMaxHeight }), - ], - [resolvedMaxHeight], + () => [styles.scrollArea, shouldFill && styles.fillHeight], + [shouldFill], ); + const scrollAreaStyle = useMemo(() => [styles.scrollArea], []); const jsonScrollCombined = styles.jsonScroll; const jsonScrollErrorCombined = [styles.jsonScroll, styles.jsonScrollError]; const fullBleedContainerStyle = useMemo( @@ -122,6 +127,7 @@ function useDetailStyles( ); return { + fillAvailableHeight, sectionFillStyle, codeBlockFillStyle, codeVerticalScrollStyle, @@ -131,7 +137,6 @@ function useDetailStyles( jsonScrollErrorCombined, fullBleedContainerStyle, loadingContainerStyle, - resolvedMaxHeight, shouldFill, isFullBleed, }; @@ -160,7 +165,8 @@ function ShellDetailSection({ command, output, ds }: ShellDetailProps) { return ( - - + ); @@ -196,11 +202,7 @@ function EditDetailSection({ diffLines, ds }: EditDetailProps) { {diffLines ? ( - + ) : null} @@ -228,7 +230,8 @@ function ScrollableTextSection({ [content, filePath], ); const body = ( - )} - + ); if (!wrapInSectionFill) return body; return {body}; @@ -258,7 +261,8 @@ interface FetchDetailProps { function FetchDetailSection({ url, result, ds }: FetchDetailProps) { return ( - - + ); } @@ -277,7 +281,8 @@ function FetchDetailSection({ url, result, ds }: FetchDetailProps) { function ScrollablePlainTextSection({ text, ds }: { text: string; ds: DetailStyles }) { return ( - {text} - + ); } @@ -304,7 +309,8 @@ function buildSearchSections(detail: SearchDetail, ds: DetailStyles): ReactNode[ if (detail.content) { out.push( - - + , ); } @@ -548,7 +554,8 @@ export function ToolCallDetailsContent({ }: ToolCallDetailsContentProps) { const { t } = useTranslation(); const resolvedMaxHeight = fillAvailableHeight ? undefined : (maxHeight ?? 300); - const ds = useDetailStyles(detail, resolvedMaxHeight, fillAvailableHeight); + // The allowance belongs to the whole disclosure, rather than each section. + const ds = useDetailStyles(detail, fillAvailableHeight); const diffLines = useDiffLines(detail); const sections: ReactNode[] = buildDetailSections(toolName, detail, diffLines, ds, t); @@ -564,6 +571,17 @@ export function ToolCallDetailsContent({ return {t("toolCallDetails.empty")}; } + if (resolvedMaxHeight !== undefined) { + return ( + + {sections} + + ); + } return {sections}; } diff --git a/packages/app/src/tool-calls/detail-level/overview/view.tsx b/packages/app/src/tool-calls/detail-level/overview/view.tsx index b05fbe1edd..825a4ba9aa 100644 --- a/packages/app/src/tool-calls/detail-level/overview/view.tsx +++ b/packages/app/src/tool-calls/detail-level/overview/view.tsx @@ -27,12 +27,8 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView onExpandedChange, children, }: OverviewGroupProps) { - const scrollRef = useRef(null); const isCompact = useIsCompactFormFactor(); const aggregateSummary = useOverviewSummaryLabel(group.summary); - const scrollToLatest = useCallback(() => { - scrollRef.current?.scrollToEnd({ animated: false }); - }, []); const hold = useDisclosureHold(); const toggle = useCallback(() => { const apply = () => onExpandedChange(group.run.id, !expanded); @@ -44,19 +40,8 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView onExpandedChange(group.run.id, false); }, [group.run.id, onExpandedChange]); const renderDetails = useCallback( - () => ( - - {children} - - ), - [children, scrollToLatest], + () => {children}, + [children, group.run.latest.id], ); if (isCompact) { @@ -93,6 +78,35 @@ export const OverviewToolCallGroupView = memo(function OverviewToolCallGroupView ); }); +function InlineGroupDetails({ + latestCallId, + children, +}: { + latestCallId: string; + children: ReactNode; +}) { + const scrollRef = useRef(null); + const lastRevealedCall = useRef(null); + const revealLatestCall = useCallback(() => { + // A disclosure changes height without appending a call. Keep the reader's place then. + if (lastRevealedCall.current === latestCallId) return; + lastRevealedCall.current = latestCallId; + scrollRef.current?.scrollToEnd({ animated: false }); + }, [latestCallId]); + return ( + + {children} + + ); +} + const styles = StyleSheet.create((theme) => ({ scroll: { maxHeight: TOOL_CALL_GROUP_MAX_HEIGHT, From 39db933e6b7462590023db49f03030370fc7857d Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 09:40:00 +0700 Subject: [PATCH 102/160] Keep submitted prompts scrolling down through existing momentum (#9806) * fix(app): preserve submit scroll through existing momentum A prompt sent during an active gesture requested the bottom, but the older gesture cancelled that request when momentum ended away. Honor the still-sticky pending request on release while allowing a newer gesture to take ownership. * fix(app): keep delayed navigation behind user scroll intent --- docs/agent-stream-disclosure.md | 6 ++- .../bottom-anchor-controller.test.ts | 50 +++++++++++++++++++ .../agent-stream/bottom-anchor-controller.ts | 11 ++-- 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/docs/agent-stream-disclosure.md b/docs/agent-stream-disclosure.md index 632398d484..ec320dc916 100644 --- a/docs/agent-stream-disclosure.md +++ b/docs/agent-stream-disclosure.md @@ -156,8 +156,10 @@ keeps following. Following resumes only for a gesture that ends within 1 px of the end, either when the finger lifts or when momentum stops. A release past the end counts: iOS bounces back to the end, and lines that -land during the bounce must keep scrolling in. A release anywhere short of the end stays detached -with the scroll-to-bottom pill, so the rows the user let go of never move. +land during the bounce must keep scrolling in. A release short of the end stays detached with the scroll-to-bottom pill unless you submitted +another prompt during that gesture. That submit requests the end after the gesture finishes; +a new drag after submitting takes ownership again. Rewind and tail-fetch completions do not +override a scroll away because they can arrive after the action that requested them. ### Draw distance diff --git a/packages/app/src/agent-stream/bottom-anchor-controller.test.ts b/packages/app/src/agent-stream/bottom-anchor-controller.test.ts index 12ff114521..eaa5846b51 100644 --- a/packages/app/src/agent-stream/bottom-anchor-controller.test.ts +++ b/packages/app/src/agent-stream/bottom-anchor-controller.test.ts @@ -394,6 +394,56 @@ describe("bottom anchor controller driver", () => { expect(harness.scrollAttempts).toHaveLength(0); }); + it("honors a submit made during a gesture when that gesture ends away", () => { + const harness = createDriverHarness({ isNearBottom: false }); + harness.driver.beginUserScroll(); + harness.driver.requestLocalAnchor({ agentId: "agent-1", reason: "message-sent" }); + harness.scheduler.flushAll(); + expect(harness.scrollAttempts).toEqual([]); + + harness.driver.endUserScroll({ isAtEnd: false }); + harness.scheduler.flushAll(); + + expect(harness.context.measurementState.offsetY).toBe( + harness.context.measurementState.contentHeight - + harness.context.measurementState.viewportHeight, + ); + expect(harness.driver.getSnapshot()).toMatchObject({ + mode: "sticky-bottom", + pendingRequest: null, + }); + }); + + it.each(["rewind", "jump-to-bottom"] as const)( + "lets scrolling away supersede a late %s request", + (reason) => { + const harness = createDriverHarness({ isNearBottom: false }); + harness.driver.beginUserScroll(); + harness.driver.requestLocalAnchor({ agentId: "agent-1", reason }); + harness.driver.endUserScroll({ isAtEnd: false }); + harness.scheduler.flushAll(); + + expect(harness.scrollAttempts).toEqual([]); + expect(harness.driver.getSnapshot()).toMatchObject({ + mode: "detached", + pendingRequest: null, + }); + }, + ); + + it("lets a new gesture supersede a submit requested during the previous gesture", () => { + const harness = createDriverHarness({ isNearBottom: false }); + harness.driver.beginUserScroll(); + harness.driver.requestLocalAnchor({ agentId: "agent-1", reason: "message-sent" }); + harness.driver.endUserScroll({ isAtEnd: false }); + harness.driver.beginUserScroll(); + harness.driver.endUserScroll({ isAtEnd: false }); + harness.scheduler.flushAll(); + + expect(harness.scrollAttempts).toEqual([]); + expect(harness.driver.getSnapshot()).toMatchObject({ mode: "detached", pendingRequest: null }); + }); + it("resumes following when a user scroll ends at the end", () => { const harness = createDriverHarness({ transportBehavior: { diff --git a/packages/app/src/agent-stream/bottom-anchor-controller.ts b/packages/app/src/agent-stream/bottom-anchor-controller.ts index f666481be8..30ba713f07 100644 --- a/packages/app/src/agent-stream/bottom-anchor-controller.ts +++ b/packages/app/src/agent-stream/bottom-anchor-controller.ts @@ -499,11 +499,16 @@ function createBottomAnchorControllerDriver( cancelPendingAttempt(); setModeInternal("detached"); }, - // Following resumes only for a gesture that ends at the end. Resuming from short of it would - // scroll the rows the finger just let go of, so a release above the end, or with output that - // arrived below it during the gesture, stays detached with the pill. + // A gesture ending short stays detached unless a newer prompt submission requested the end. + // Passive output must not move the rows the finger just let go of. endUserScroll(params) { isUserScrollActive = false; + // Submit arrives with the user's action; rewind and tail jumps can arrive after a fetch. + // A newer gesture would have detached again, so only a still-sticky submit owns release. + if (pendingRequest?.reason === "message-sent" && mode === "sticky-bottom") { + evaluate(false, "user_scroll_end"); + return; + } if (params.isAtEnd) { if (mode === "detached") { setModeInternal("sticky-bottom"); From 4f97abc62aadec13cb088c2eedf991a6a533db0a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 10:07:15 +0700 Subject: [PATCH 103/160] fix(app): align composer fullscreen controls with the text rail (#9821) Fullscreen controls retained a fixed toolbar overhang and aligned to the Send arrow inside its disc. Align their visible glyph edges with the text column independently of the toolbar geometry. --- packages/app/src/composer/input/input.tsx | 1 - packages/app/src/composer/input/presentation.tsx | 11 ++++------- packages/app/src/composer/input/state.test.ts | 16 +++++++++------- packages/app/src/composer/input/state.ts | 15 +++++---------- 4 files changed, 18 insertions(+), 25 deletions(-) diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 0153911627..3e4a8f5c6e 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -2346,7 +2346,6 @@ export const MessageInput = forwardRef( , [glyphSize], ); - // The toolbar row bleeds 6px past the input padding; the inline glyph sits on that edge. - const enterStyle = useMemo(() => [styles.enterButton, { right: -6 + railOffset }], [railOffset]); + // Fullscreen controls share the text rail; the toolbar disc owns its separate corner inset. + const enterStyle = useMemo(() => [styles.enterButton, { right: railOffset }], [railOffset]); const exitStyle = useMemo(() => [styles.iconButton, { marginRight: railOffset }], [railOffset]); return ( { }); describe("fullscreen glyph rail", () => { - it("nudges 16px fullscreen glyphs onto the Send arrow's ink edge", () => { - expect( - resolveGlyphRailOffset({ controlSize: 28, sendIconSize: 16, glyphIconSize: 16 }), - ).toBeCloseTo(4 / 3); - expect( - resolveGlyphRailOffset({ controlSize: 28, sendIconSize: 20, glyphIconSize: 16 }), - ).toBeCloseTo(1 / 6); + it.each([ + { controlSize: 28, glyphIconSize: 16 }, + { controlSize: 44, glyphIconSize: 20 }, + ])("puts the visible fullscreen edge on the text rail ($controlSize)", (geometry) => { + const offset = resolveGlyphRailOffset(geometry); + // Maximize2 and Minimize2 reach x21 in a 24-unit viewBox, with a 2-unit stroke. + const inkInset = + (geometry.controlSize - geometry.glyphIconSize) / 2 + (geometry.glyphIconSize * 2) / 24; + expect(offset + inkInset).toBeCloseTo(0); }); }); diff --git a/packages/app/src/composer/input/state.ts b/packages/app/src/composer/input/state.ts index 67c8030745..2fe2969401 100644 --- a/packages/app/src/composer/input/state.ts +++ b/packages/app/src/composer/input/state.ts @@ -234,21 +234,16 @@ export async function stopRealtimeVoice(ctx: StopRealtimeVoiceContext): Promise< } /** - * Offset that aligns a glyph's visible ink with the Send arrow's ink when both sit in - * equal controls on the same right rail. In Lucide's 24px viewBox ArrowUp ends at - * x19 while Maximize2/Minimize2 end at x21, so equal boxes leave the fullscreen - * glyphs visibly past the arrow. + * Put the fullscreen glyph's visible right edge on the text rail, letting its + * hit area extend into the padding. Both Lucide glyphs reach x21 of 24 and use + * the default 2-unit stroke (one viewBox unit beyond the path). */ export function resolveGlyphRailOffset(input: { controlSize: number; - sendIconSize: number; glyphIconSize: number; }): number { - const arrowInkInset = - (input.controlSize - input.sendIconSize) / 2 + (5 * input.sendIconSize) / 24; - const glyphInkInset = - (input.controlSize - input.glyphIconSize) / 2 + (3 * input.glyphIconSize) / 24; - return arrowInkInset - glyphInkInset; + const inkInset = (input.controlSize - input.glyphIconSize) / 2 + (2 * input.glyphIconSize) / 24; + return -inkInset; } export function resolveComposerSurfaceText( From ade3817a45f05325fd5929ba939de220bd90c236 Mon Sep 17 00:00:00 2001 From: Josh Bendavid Date: Mon, 16 Nov 2026 04:56:04 +0100 Subject: [PATCH 104/160] fix(server): fall back to the next socket directory when the bind is refused (#9214) A PASEO_HOME on AFS passes the socket directory checks, then refuses the Unix socket bind with EPERM, and the terminal worker failed to start. The worker now binds each eligible candidate in turn and moves on when the filesystem refuses the socket (EPERM, EACCES, EOPNOTSUPP, ENOTSUP). Other listen errors still fail the start. Fixes #9213 Co-authored-by: Claude Opus 5.5 --- docs/terminal-worker.md | 1 + .../src/terminal/terminal-worker-process.ts | 30 +++--- .../terminal-worker-socket-path.test.ts | 94 ++++++++++++++++++- .../terminal/terminal-worker-socket-path.ts | 84 +++++++++++++++-- 4 files changed, 184 insertions(+), 25 deletions(-) diff --git a/docs/terminal-worker.md b/docs/terminal-worker.md index d83dea9957..42e1f8cbc3 100644 --- a/docs/terminal-worker.md +++ b/docs/terminal-worker.md @@ -29,6 +29,7 @@ The worker writes `$PASEO_HOME/terminal-worker/.json` (owner-only) with its - Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them. - Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs. - Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-/` or `/tmp/paseo-/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded. +- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it. - A kill cleanup that cannot confirm every process gone writes `closing-.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it. - An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment. diff --git a/packages/server/src/terminal/terminal-worker-process.ts b/packages/server/src/terminal/terminal-worker-process.ts index c61ead0628..7e548552b0 100644 --- a/packages/server/src/terminal/terminal-worker-process.ts +++ b/packages/server/src/terminal/terminal-worker-process.ts @@ -19,7 +19,7 @@ import { type TerminalWorkerRecord, } from "./terminal-worker-record.js"; import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js"; -import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js"; +import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js"; import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, TERMINAL_WORKER_PROTOCOL_VERSION, @@ -700,23 +700,25 @@ function runWorker(argv: string[]): void { } async function start(): Promise { - const socketPath = resolveTerminalWorkerSocketPath({ + const { socketPath, listener } = await listenOnTerminalWorkerSocket({ paseoHome: args.paseoHome, workerPid: process.pid, recordId: args.recordId, + listen: (candidatePath) => { + if (process.platform !== "win32") { + rmSync(candidatePath, { force: true }); + } + const listening = createServer(handleConnection); + return new Promise((resolve, reject) => { + listening.once("error", reject); + listening.listen(candidatePath, () => { + listening.off("error", reject); + resolve(listening); + }); + }); + }, }); - if (process.platform !== "win32") { - rmSync(socketPath, { force: true }); - } - const listening = createServer(handleConnection); - await new Promise((resolve, reject) => { - listening.once("error", reject); - listening.listen(socketPath, () => { - listening.off("error", reject); - resolve(); - }); - }); - server = listening; + server = listener; if (process.platform !== "win32") { chmodSync(socketPath, PRIVATE_FILE_MODE); } diff --git a/packages/server/src/terminal/terminal-worker-socket-path.test.ts b/packages/server/src/terminal/terminal-worker-socket-path.test.ts index 6017177fcf..786f095886 100644 --- a/packages/server/src/terminal/terminal-worker-socket-path.test.ts +++ b/packages/server/src/terminal/terminal-worker-socket-path.test.ts @@ -1,10 +1,11 @@ import { afterEach, describe, expect, it } from "vitest"; import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"; -import { createServer } from "node:net"; +import { createServer, type Server } from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; import { isPlatform } from "../test-utils/platform.js"; import { + listenOnTerminalWorkerSocket, resolveTerminalWorkerSocketPath, TerminalWorkerSocketPathError, } from "./terminal-worker-socket-path.js"; @@ -25,7 +26,36 @@ function longHome(root: string): string { return home; } -afterEach(() => { +const openServers: Server[] = []; + +function listenFor(socketPath: string): Promise { + const server = createServer(); + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => { + openServers.push(server); + resolve(server); + }); + }); +} + +// Stands in for a filesystem that passes the directory checks but refuses AF_UNIX bind, as AFS +// does with EPERM. +function refuseBindUnder(directory: string, code: string) { + return (socketPath: string): Promise => { + if (socketPath.startsWith(directory + path.sep)) { + return Promise.reject( + Object.assign(new Error(`listen ${code}: ${socketPath}`), { code, syscall: "listen" }), + ); + } + return listenFor(socketPath); + }; +} + +afterEach(async () => { + await Promise.all( + openServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))), + ); for (const dir of temporaryDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } @@ -142,6 +172,66 @@ describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => { }); }); +describe.skipIf(isPlatform("win32"))("terminal worker socket listen", () => { + it("falls back to the next directory when the home's filesystem refuses the bind", async () => { + const home = makeDir("tw-b-", "/tmp"); + const tmpDir = makeDir("tw-t-", "/tmp"); + const homeSocketDirectory = path.join(home, "terminal-worker", "sock"); + const { socketPath, listener } = await listenOnTerminalWorkerSocket({ + paseoHome: home, + recordId: "test", + workerPid: 11, + tmpDir, + listen: refuseBindUnder(homeSocketDirectory, "EPERM"), + }); + expect(path.dirname(socketPath)).toBe(path.join(tmpDir, `paseo-${process.getuid!()}`)); + expect(listener.address()).toBe(socketPath); + }); + + it("throws a listen error that does not mean the filesystem refuses sockets", async () => { + const home = makeDir("tw-u-", "/tmp"); + const homeSocketDirectory = path.join(home, "terminal-worker", "sock"); + await expect( + listenOnTerminalWorkerSocket({ + paseoHome: home, + recordId: "test", + workerPid: 12, + tmpDir: makeDir("tw-t-", "/tmp"), + listen: refuseBindUnder(homeSocketDirectory, "EADDRINUSE"), + }), + ).rejects.toMatchObject({ code: "EADDRINUSE" }); + }); + + it("names every candidate's bind error when no directory accepts a socket", async () => { + const home = makeDir("tw-n-", "/tmp"); + const tmpDir = makeDir("tw-t-", "/tmp"); + let caught: unknown; + try { + await listenOnTerminalWorkerSocket({ + paseoHome: home, + recordId: "test", + workerPid: 13, + tmpDir, + listen: refuseBindUnder("", "EPERM"), + }); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError); + const rejected = (caught as TerminalWorkerSocketPathError).rejected; + expect(rejected.slice(0, 2)).toEqual([ + expect.objectContaining({ + path: expect.stringContaining(path.join(home, "terminal-worker", "sock")), + reason: "cannot bind a socket here (EPERM)", + }), + expect.objectContaining({ + path: expect.stringContaining(path.join(tmpDir, `paseo-${process.getuid!()}`)), + reason: "cannot bind a socket here (EPERM)", + }), + ]); + }); +}); + it("uses a separate socket for each record even when its pid is reused", () => { const paseoHome = makeDir("tw-id-"); const first = resolveTerminalWorkerSocketPath({ paseoHome, workerPid: 42, recordId: "old" }); diff --git a/packages/server/src/terminal/terminal-worker-socket-path.ts b/packages/server/src/terminal/terminal-worker-socket-path.ts index d9a153c598..0ad94a1ced 100644 --- a/packages/server/src/terminal/terminal-worker-socket-path.ts +++ b/packages/server/src/terminal/terminal-worker-socket-path.ts @@ -14,6 +14,9 @@ const SOCKET_PATH_BYTE_BUDGET: Partial> = { }; const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103; const OWNER_ONLY_MODE = 0o700; +// Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other +// network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM. +const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]); export interface TerminalWorkerSocketPathInput { paseoHome: string; @@ -24,6 +27,16 @@ export interface TerminalWorkerSocketPathInput { uid?: number; } +export interface TerminalWorkerSocketListenInput extends TerminalWorkerSocketPathInput { + /** Binds a fresh listener at the path, removing any stale socket there first. */ + listen: (socketPath: string) => Promise; +} + +export interface TerminalWorkerSocketListener { + socketPath: string; + listener: T; +} + export interface RejectedSocketCandidate { path: string; byteLength: number; @@ -36,7 +49,7 @@ export class TerminalWorkerSocketPathError extends Error { constructor(rejected: RejectedSocketCandidate[], budget: number) { super( [ - `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`, + `No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`, ...rejected.map( (candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`, ), @@ -57,18 +70,73 @@ export function terminalWorkerSocketId(paseoHome: string, workerPid: number): st * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX * tries $PASEO_HOME/terminal-worker/sock, then /paseo-, then /tmp/paseo-. * A shared root is never chmodded: an existing directory there is used only when it is a real - * directory owned by this user with mode 0700. + * directory owned by this user with mode 0700. It does not bind; the worker listens through + * `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket. */ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string { const platform = input.platform ?? process.platform; - const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId; if (platform === "win32") { - return `\\\\.\\pipe\\paseo-tw-${id}`; + return windowsPipePath(input); } + const budget = socketPathByteBudget(platform); + const rejected: RejectedSocketCandidate[] = []; + for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) { + return candidate.path; + } + throw new TerminalWorkerSocketPathError(rejected, budget); +} +/** + * Listens on the first candidate path that accepts a socket. A bind refused by the filesystem + * moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is. + */ +export async function listenOnTerminalWorkerSocket( + input: TerminalWorkerSocketListenInput, +): Promise> { + const { listen } = input; + const platform = input.platform ?? process.platform; + if (platform === "win32") { + const socketPath = windowsPipePath(input); + return { socketPath, listener: await listen(socketPath) }; + } + const budget = socketPathByteBudget(platform); + const rejected: RejectedSocketCandidate[] = []; + for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) { + try { + return { socketPath: candidate.path, listener: await listen(candidate.path) }; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error; + rejected.push({ + path: candidate.path, + byteLength: candidate.byteLength, + reason: `cannot bind a socket here (${code})`, + }); + } + } + throw new TerminalWorkerSocketPathError(rejected, budget); +} + +function windowsPipePath(input: TerminalWorkerSocketPathInput): string { + return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`; +} + +function socketFileId(input: TerminalWorkerSocketPathInput): string { + return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId; +} + +function socketPathByteBudget(platform: NodeJS.Platform): number { + return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET; +} + +/** Yields each candidate that fits the budget in an owner-only directory, in order. */ +function* eligibleUnixSocketPaths( + input: TerminalWorkerSocketPathInput, + budget: number, + rejected: RejectedSocketCandidate[], +): Generator<{ path: string; byteLength: number }> { const uid = input.uid ?? process.getuid?.() ?? 0; - const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET; - const fileName = `tw-${id}.sock`; + const fileName = `tw-${socketFileId(input)}.sock`; const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock"); const candidates: Array<{ directory: string; prepare: () => string | null }> = [ { @@ -87,7 +155,6 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI }), ]; - const rejected: RejectedSocketCandidate[] = []; const seen = new Set(); for (const candidate of candidates) { const socketPath = path.join(candidate.directory, fileName); @@ -108,9 +175,8 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI rejected.push({ path: socketPath, byteLength, reason: problem }); continue; } - return socketPath; + yield { path: socketPath, byteLength }; } - throw new TerminalWorkerSocketPathError(rejected, budget); } function prepareSharedRootDirectory(directory: string, uid: number): string | null { From d15190803a622e516cc521fe3220a1b98fcee253 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:55:28 +0000 Subject: [PATCH 105/160] Show Pi model names with slashes and underscores in full (#9823) * fix(pi): keep slashes and underscores in model display names Pi model labels were built as `${provider}/${name}` and then cut at the last `/`, so a free-text name such as "... ~60-70 tok/s, 52/56)" was shown as "56)". Underscores were also rewritten to spaces ("IQ3_S" -> "IQ3 S"). The compact model trigger in the app repeated the last-`/` cut. Build the Pi label from the model's own `name`/`id`: shorten only path-like values with no whitespace (OpenRouter reports names like "google/gemini-2.5-flash-lite"), and keep free-text names intact. The compact trigger now strips only a leading provider namespace. Co-Authored-By: Claude Opus 5.5 * test(pi): cover model labels through the catalog and drop stale ACP copies acp-agent.test.ts still imported transformPiModels, which the Pi label fix removed, so its modelTransformer test and a stale copy of the old Pi label tests failed. The modelTransformer test now supplies its own transformer, and the Pi label cases run through fetchCatalog with the reported model names instead of an exported helper. Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * fix(pi): keep colons inside free-text model names The vendor-prefix strip cut a free-text Pi name at its first ": ", so "Qwen3 IQ3_S (tail skip: on, 52/56)" showed as "on, 52/56)". Strip only when the text before ": " has no parenthesis or comma, which keeps OpenRouter's "Vendor: Model" names shortened. Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../composer/agent-controls/model-sheet.tsx | 6 +- .../src/composer/agent-controls/utils.test.ts | 17 ++++ .../app/src/composer/agent-controls/utils.ts | 6 ++ .../server/agent/providers/acp-agent.test.ts | 62 ++---------- .../server/agent/providers/pi/agent.test.ts | 99 ++++++++++++------- .../src/server/agent/providers/pi/agent.ts | 59 +++++------ 6 files changed, 120 insertions(+), 129 deletions(-) diff --git a/packages/app/src/composer/agent-controls/model-sheet.tsx b/packages/app/src/composer/agent-controls/model-sheet.tsx index c9da7d778e..95f25ddc4c 100644 --- a/packages/app/src/composer/agent-controls/model-sheet.tsx +++ b/packages/app/src/composer/agent-controls/model-sheet.tsx @@ -31,6 +31,7 @@ import { toolbarSlot, type ToolbarGlyphs, } from "@/components/ui/control-geometry"; +import { shortModelLabel } from "./utils"; const SNAP_POINTS = ["80%", "90%"]; const MODEL_LIST_TOP_INSET = 4; @@ -66,11 +67,6 @@ interface CompactModelSheetProps { children: ReactNode; } -function shortModelLabel(label: string): string { - const separatorIndex = label.lastIndexOf("/"); - return separatorIndex === -1 ? label : label.slice(separatorIndex + 1); -} - function resolveModelSheetProfileActions( onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined, onEditProfile: ((profileId: string) => void) | undefined, diff --git a/packages/app/src/composer/agent-controls/utils.test.ts b/packages/app/src/composer/agent-controls/utils.test.ts index ad8f6da983..35d4d89a10 100644 --- a/packages/app/src/composer/agent-controls/utils.test.ts +++ b/packages/app/src/composer/agent-controls/utils.test.ts @@ -4,6 +4,7 @@ import { getAgentControlHintKey, normalizeModelId, resolveAgentModelSelection, + shortModelLabel, } from "./utils"; describe("getAgentControlHintKey", () => { @@ -251,3 +252,19 @@ describe("resolveAgentModelSelection", () => { expect(selection.displayThinking).toBe("Max"); }); }); + +describe("shortModelLabel", () => { + it("drops a provider namespace", () => { + expect(shortModelLabel("openrouter/gpt-5.5")).toBe("gpt-5.5"); + expect(shortModelLabel("openrouter/google/gemini-2.5-flash")).toBe("gemini-2.5-flash"); + }); + + it("keeps slashes inside a display name", () => { + expect(shortModelLabel("DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)")).toBe( + "DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)", + ); + expect(shortModelLabel("llama-swap/DeepSeek V4.1 Flash (56/56)")).toBe( + "DeepSeek V4.1 Flash (56/56)", + ); + }); +}); diff --git a/packages/app/src/composer/agent-controls/utils.ts b/packages/app/src/composer/agent-controls/utils.ts index 26a5cabe5b..3e86a122c5 100644 --- a/packages/app/src/composer/agent-controls/utils.ts +++ b/packages/app/src/composer/agent-controls/utils.ts @@ -35,6 +35,12 @@ export function normalizeModelId(modelId: string | null | undefined): string | n return normalized; } +// Drops a provider namespace ("openrouter/gpt-5.5" -> "gpt-5.5") for the compact trigger. +// A namespace segment has no spaces, so slashes inside a display name ("52/56") survive. +export function shortModelLabel(label: string): string { + return label.replace(/^(?:[^\s/]+\/)+(?=\S)/, ""); +} + export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor { switch (featureId) { case FAST_MODE_FEATURE_ID: diff --git a/packages/server/src/server/agent/providers/acp-agent.test.ts b/packages/server/src/server/agent/providers/acp-agent.test.ts index 004e4cba93..748d2b462f 100644 --- a/packages/server/src/server/agent/providers/acp-agent.test.ts +++ b/packages/server/src/server/agent/providers/acp-agent.test.ts @@ -51,7 +51,6 @@ import { } from "./copilot-acp-agent.js"; import { GenericACPAgentClient } from "./generic-acp-agent.js"; import { parseKiroExtensionCommands } from "./kiro-acp-agent.js"; -import { transformPiModels } from "./pi/agent.js"; import type { AgentStreamEvent } from "../agent-sdk-types.js"; import type { AgentCapabilityFlags, @@ -2260,7 +2259,12 @@ describe("ACPAgentClient modelTransformer", () => { provider: "pi", logger: createTestLogger(), defaultCommand: ["test-acp"], - modelTransformer: transformPiModels, + modelTransformer: (models) => + models.map((model) => ({ + ...model, + label: model.label.split("/").at(-1) ?? model.label, + description: model.id, + })), }); await expect( @@ -2914,60 +2918,6 @@ describe("ACP providers advertise session listing", () => { }); }); -describe("transformPiModels", () => { - test("keeps slash-free labels unchanged", () => { - expect( - transformPiModels([ - { - provider: "pi", - id: "gpt-4.1-mini", - label: "GPT 4.1 Mini", - description: "Fast", - }, - ]), - ).toEqual([ - { - provider: "pi", - id: "gpt-4.1-mini", - label: "GPT 4.1 Mini", - description: "Fast", - }, - ]); - }); - - test("uses the last path segment as label and preserves existing descriptions", () => { - expect( - transformPiModels([ - { - provider: "pi", - id: "openrouter/openai/gpt-4.1-mini", - label: "openrouter/openai/gpt-4.1-mini", - description: undefined, - }, - { - provider: "pi", - id: "anthropic/claude-sonnet-4", - label: "anthropic/claude-sonnet-4", - description: "Balanced", - }, - ]), - ).toEqual([ - { - provider: "pi", - id: "openrouter/openai/gpt-4.1-mini", - label: "gpt-4.1-mini", - description: "openrouter/openai/gpt-4.1-mini", - }, - { - provider: "pi", - id: "anthropic/claude-sonnet-4", - label: "claude-sonnet-4", - description: "Balanced", - }, - ]); - }); -}); - describe("ACPAgentSession slash commands", () => { test("returns immediately for ACP sessions that do not wait for async command discovery", async () => { const session = new ACPAgentSession( diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index d152810a92..eab96283bf 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -19,12 +19,7 @@ import { pathToFileURL } from "node:url"; import { describe, expect, onTestFinished, test } from "vitest"; import type { AgentSession, AgentSessionConfig, AgentStreamEvent } from "../../agent-sdk-types.js"; -import { - PiProviderOptionsSchema, - PiRpcAgentClient, - PiRpcAgentSession, - transformPiModels, -} from "./agent.js"; +import { PiProviderOptionsSchema, PiRpcAgentClient, PiRpcAgentSession } from "./agent.js"; import { PiCliRuntime } from "./cli-runtime.js"; import { FakePi } from "./test-utils/fake-pi.js"; import { createPiExtensionHost } from "./extensions/index.js"; @@ -3970,35 +3965,73 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => { }); }); -describe("transformPiModels", () => { - test("normalizes labels that include the upstream provider prefix", () => { - expect( - transformPiModels([ - { - provider: "pi", - id: "openrouter/google/gemini-2.5-flash-lite", - label: "openrouter/google/gemini_2.5 flash lite", - }, - { - provider: "pi", - id: "openrouter/openai/gpt-5.5", - label: "openrouter/OpenAI: GPT-5.5", - }, - ]), - ).toEqual([ - { - provider: "pi", - id: "openrouter/google/gemini-2.5-flash-lite", - label: "gemini 2.5 flash lite", - description: "openrouter/google/gemini_2.5 flash lite", +describe("Pi catalog model labels", () => { + test.each([ + { + name: "keeps slashes and underscores inside a free-text model name", + model: { + provider: "llama-swap", + id: "s-q3fn(p-t)", + name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", }, - { - provider: "pi", - id: "openrouter/openai/gpt-5.5", - label: "GPT-5.5", - description: "openrouter/OpenAI: GPT-5.5", + label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", + }, + { + name: "keeps a free-text name that ends in a slash-separated word", + model: { + provider: "llama-swap", + id: "ds-strata-6", + name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", }, - ]); + label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", + }, + { + name: "keeps a colon inside a free-text model name", + model: { + provider: "llama-swap", + id: "qwen3-tail", + name: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + label: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + { + name: "drops the vendor prefix from an upstream model name", + model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" }, + label: "GPT-5.5", + }, + { + name: "shortens a path-like name to its last segment", + model: { + provider: "openrouter", + id: "google/gemini-2.5-flash-lite", + name: "google/gemini-2.5-flash-lite", + }, + label: "gemini-2.5-flash-lite", + }, + { + name: "falls back to the last segment of a path-like id", + model: { provider: "openrouter", id: "google/gemini_2.5-flash-lite" }, + label: "gemini 2.5-flash-lite", + }, + { + name: "falls back to an id with spaces when the name is blank", + model: { provider: "local", id: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", name: " " }, + label: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", + }, + ])("$name", async ({ model, label }) => { + const pi = new FakePi(); + pi.queueSessionSetup((session) => { + session.models = [model]; + }); + + const catalog = await createClient(pi).fetchCatalog({ + scope: "workspace", + cwd: "/workspace/project", + force: false, + }); + + expect(catalog.models.map((entry) => entry.label)).toEqual([label]); + expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`); }); }); diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index 60d745ea24..b5a887c112 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -313,34 +313,25 @@ interface PiSlashCommandInvocation { type AutoCompactMode = boolean | "toggle" | "unknown"; -function normalizePiModelLabel(label: string): string { - const normalizedLabel = label.trim().replace(/[_\s]+/g, " "); - const vendorSeparatorIndex = normalizedLabel.indexOf(": "); - if (vendorSeparatorIndex === -1) { - return normalizedLabel; +// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a +// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept. +function stripVendorPrefix(label: string): string { + const vendorSeparatorIndex = label.indexOf(": "); + if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) { + return label; } - - return normalizedLabel.slice(vendorSeparatorIndex + 2).trim(); + return label.slice(vendorSeparatorIndex + 2).trim(); } -export function transformPiModels(models: AgentModelDefinition[]): AgentModelDefinition[] { - return models.map((model) => { - if (!model.label.includes("/")) { - return model; - } - - const segments = model.label.split("/").filter((segment) => segment.length > 0); - const rawLabel = segments.at(-1); - if (!rawLabel) { - return model; - } - - return { - ...model, - label: normalizePiModelLabel(rawLabel), - description: model.description ?? model.label, - }; - }); +// A Pi model name is either a path ("google/gemini_2.5-flash", as OpenRouter reports it) or +// free text that can contain slashes and underscores ("IQ3_S ... 52/56"). Only shorten paths. +function piModelLabel(model: Pick): string { + const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim(); + if (/\s/.test(text)) { + return stripVendorPrefix(text); + } + const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text; + return stripVendorPrefix(lastSegment.replace(/_+/g, " ")); } function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel { @@ -1166,7 +1157,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti return { provider, id: `${model.provider}/${model.id}`, - label: `${model.provider}/${model.name ?? model.id}`, + label: piModelLabel(model), description: `${model.provider}/${model.id}`, metadata: { provider: model.provider, @@ -2817,15 +2808,13 @@ export class PiRpcAgentClient implements AgentClient { "get_state", () => catalogSession.getState(), ); - const models = transformPiModels( - piModels.map((model) => { - const mapped = mapPiModel(model, PI_PROVIDER); - const isConfigured = - model.provider === configuredModel?.provider && model.id === configuredModel?.id; - if (isConfigured) mapped.isDefault = true; - return mapped; - }), - ); + const models = piModels.map((model) => { + const mapped = mapPiModel(model, PI_PROVIDER); + const isConfigured = + model.provider === configuredModel?.provider && model.id === configuredModel?.id; + if (isConfigured) mapped.isDefault = true; + return mapped; + }); return { models, modes: [] }; } finally { context?.signal.removeEventListener("abort", handleAbort); From ee3a3ba8c525af3e3a9f2806bf65668622e7ae67 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:03:13 +0000 Subject: [PATCH 106/160] test(app): pick a new port when an isolated daemon loses its reserved one (#9815) The isolated host daemon helper reserves a port, releases it, and passes it to the daemon. Another process can bind it in between, and the daemon exits with EADDRINUSE. That failed a Playwright worker's own daemon in the e2eWorker fixture. The first start now reserves a fresh port and starts again when the daemon reports EADDRINUSE; restart() keeps the endpoint the app already knows. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../support/helpers/isolated-host-daemon.ts | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/app/e2e/support/helpers/isolated-host-daemon.ts b/packages/app/e2e/support/helpers/isolated-host-daemon.ts index dea61c3a37..3aab184cce 100644 --- a/packages/app/e2e/support/helpers/isolated-host-daemon.ts +++ b/packages/app/e2e/support/helpers/isolated-host-daemon.ts @@ -121,7 +121,7 @@ export async function startIsolatedHostDaemon( serverId: string, options: IsolatedHostDaemonOptions = {}, ): Promise { - const port = await getAvailableHostDaemonPort(); + let port = await getAvailableHostDaemonPort(); const metroPort = process.env.E2E_METRO_PORT; if (!metroPort) throw new Error("E2E_METRO_PORT is required to start an isolated host daemon"); @@ -231,8 +231,25 @@ export async function startIsolatedHostDaemon( } }; + // The reserved port is released before the daemon binds it, so another + // process can take it in between. Only the first start picks a new port: + // restart() keeps the endpoint the app already knows. + const startOnFreePort = async (): Promise => { + for (let attempt = 1; ; attempt += 1) { + try { + await spawnDaemon(); + return; + } catch (error) { + const lostPort = error instanceof Error && error.message.includes("EADDRINUSE"); + if (!lostPort || attempt === 3) throw error; + await stopDaemon(); + port = await getAvailableHostDaemonPort(); + } + } + }; + try { - await spawnDaemon(); + await startOnFreePort(); } catch (error) { await stopDaemon(); if (!options.preserveHome) { From e7e1b44ec8836f7d71d6c26cfa37bb196bfee525 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 13:10:33 +0700 Subject: [PATCH 107/160] chore(release): reconcile 0.16.0 metadata into main (#9833) --- CHANGELOG.md | 115 +++++++++++++----- CHANGELOG.zh-CN.md | 115 +++++++++++++----- .../android/en-US/changelogs/160001.txt | 5 + .../android/en-US/changelogs/160002.txt | 5 + .../android/en-US/changelogs/160003.txt | 5 + .../android/en-US/changelogs/160004.txt | 5 + nix/npm-deps.hash | 2 +- package-lock.json | 56 ++++----- package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 +- packages/client/package.json | 6 +- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 +- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 +- packages/website/package.json | 2 +- plugins/package.json | 2 +- 21 files changed, 248 insertions(+), 114 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/160001.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/160002.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/160003.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/160004.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index f2112e386a..92cf6a76c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,45 +1,102 @@ # Changelog -## 0.16.0-beta.2 - 2026-11-11 +## 0.16.0 - 2026-11-16 -- **Background tasks:** Paseo now shows the background tasks an agent is running, such as shells and monitors, above the composer, with a Stop button for each. Works with Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162) by [@fxlelouarn](https://github.com/fxlelouarn)) -- **Plugin sidebar views:** A plugin can replace the sidebar's content with its own layout of workspaces, agents, projects and terminals across every connected host. Pick the view per device under Settings → Sidebar; Paseo's sidebar header and footer stay in place. ([#8906](https://github.com/getpaseo/paseo/pull/8906)) -- **Plugin composer controls:** Plugins can add their own controls to the composer, and read and set its prompt, attachments, provider, model, mode and thinking. They can also put the cursor in any agent's composer, add items to New workspace, and store their own metadata on agents and workspaces. ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207)) -- **Faster diff loading:** Opening Changes shows the file tree right away while file contents load. Large diffs arrive in batches, so the rest of the app keeps responding while they load, and diffs take priority over the daemon's background worktree scans. ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243)) -- **Polish:** The chat stays still when a turn ends, and returning to a chat that has not changed shows it as it is with no refresh. Tool rows show their final title and icon from the first frame, the context window popover opens with usage already loaded, and sidebar hover cards open one at a time. ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175), [#9242](https://github.com/getpaseo/paseo/pull/9242), [#9248](https://github.com/getpaseo/paseo/pull/9248), [#9212](https://github.com/getpaseo/paseo/pull/9212), [#9071](https://github.com/getpaseo/paseo/pull/9071)) -- **Rebuilt mobile chat timeline:** The chat timeline on iOS and Android was rebuilt. Expanding or collapsing a turn summary, todo card or tool-call group keeps the line you tapped in place, and on Android so do Show more, Show less and plan cards. ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085)) -- **Keyboard shortcuts on mobile:** With a keyboard connected, iPad and Android now run the same shortcuts as desktop, including your custom bindings. Shortcut hints and Settings → Shortcuts appear when a keyboard is detected. Shortcuts also work in narrow desktop and browser windows. ([#8625](https://github.com/getpaseo/paseo/pull/8625) by [@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud)) -- **Touch-sized tablet controls:** On iPad and other touch-screen devices, the wide layout now has touch-sized buttons, rows and bars. The composer toolbar folds its controls into the model menu when space runs out, and swiping right on the workspace reveals a collapsed sidebar as an overlay. ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739) by [@zeyugao](https://github.com/zeyugao)) -- **Undo workspace archive:** Archiving a workspace in the app now shows a "Workspace archived" toast for six seconds. Undo, or Cmd/Ctrl+Z, restores the workspace with its tabs and agents. On desktop, sidebar workspace rows also get an archive button on hover. ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104)) -- **Fewer reconnects on return:** Returning to the app keeps a working connection, including one in the middle of a large response, and reconnects once when it has to. On a host with several saved connections, Paseo stays on the one that works. ([#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116)) +- **Background tasks:** See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635) by [@fxlelouarn](https://github.com/fxlelouarn)) +- **Built-in plugin gallery:** Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. ([#9752](https://github.com/getpaseo/paseo/pull/9752)) +- **Command center tabs:** Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. ([#9689](https://github.com/getpaseo/paseo/pull/9689)) +- **Plugin sidebar views:** Plugins can replace the sidebar with their own workspace and agent layout across connected hosts. Choose a view per device in Settings → Sidebar. ([#8906](https://github.com/getpaseo/paseo/pull/8906)) +- **Plugin composer controls:** Plugins can add composer controls, edit drafts and attachments, and change agent settings. They can also add New workspace items and save metadata on agents and workspaces. ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207), [#9734](https://github.com/getpaseo/paseo/pull/9734) by [@michaelmwu](https://github.com/michaelmwu)) +- **Arrange Usage cards:** Drag provider cards into your preferred order and turn off cards you do not want in the sidebar summary. Choose the host from Usage settings. ([#9660](https://github.com/getpaseo/paseo/pull/9660), [#9740](https://github.com/getpaseo/paseo/pull/9740), [#9748](https://github.com/getpaseo/paseo/pull/9748), [#9780](https://github.com/getpaseo/paseo/pull/9780)) +- **Quieter app reopening:** Returning to an unchanged chat no longer flashes “Updating messages.” Paseo keeps healthy connections open and recovers dropped connections when you return. After reconnecting, an up-to-date chat no longer shows an extra update toast. ([#9242](https://github.com/getpaseo/paseo/pull/9242), [#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116), [#9558](https://github.com/getpaseo/paseo/pull/9558) by [@adamcstephens](https://github.com/adamcstephens)) +- **Rebuilt mobile chat:** Expanding turn summaries, todo cards and tool groups keeps your reading position on iOS and Android. Sending during a scroll moves to the new prompt. ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085), [#9806](https://github.com/getpaseo/paseo/pull/9806), [#9693](https://github.com/getpaseo/paseo/pull/9693)) +- **Faster diff loading:** Changes shows the file tree before file contents finish loading. Large diffs load in batches and take priority over background worktree scans. ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243), [#9584](https://github.com/getpaseo/paseo/pull/9584)) +- **Faster composer menus:** Command and file suggestions open sooner in large lists and stay against the composer as it changes size. ([#9657](https://github.com/getpaseo/paseo/pull/9657), [#9647](https://github.com/getpaseo/paseo/pull/9647), [#9642](https://github.com/getpaseo/paseo/pull/9642)) +- **Keyboard shortcuts on mobile:** A connected keyboard gives iPad and Android the same shortcuts as desktop, including custom bindings. Shift+Tab in the iPad composer switches mode without typing a tab. ([#8625](https://github.com/getpaseo/paseo/pull/8625), [#9561](https://github.com/getpaseo/paseo/pull/9561) by [@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud)) +- **Touch-sized tablet controls:** Wide layouts on touch devices have larger buttons and rows. The composer folds controls into the model menu when space runs out. ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739) by [@zeyugao](https://github.com/zeyugao)) +- **Undo workspace archive:** Restore an archived workspace with Undo or Cmd/Ctrl+Z during the six-second toast. Paseo checks for unsaved files and unpushed commits before removing a worktree. ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104), [#9625](https://github.com/getpaseo/paseo/pull/9625), [#9753](https://github.com/getpaseo/paseo/pull/9753) by [@ragokan](https://github.com/ragokan)) ### Added -- Added a Change base picker in Changes for worktree workspaces, so diffs, the commit list and Git actions can use another branch ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934) by [@Myasuka](https://github.com/Myasuka)) -- Added links for issue and pull request references such as `#123` and `owner/repo#123` in agent replies, plans, the pull request panel and file previews, for GitHub, GitLab, Gitea, Forgejo and Codeberg ([#8636](https://github.com/getpaseo/paseo/pull/8636)) -- Added iPhone Duo layout support: workspace actions sit in the system vertical bar, and the sidebar and workspace split on either side of the fold ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901) by [@zeyugao](https://github.com/zeyugao)) +- Added a Change base picker for worktree diffs, commits and Git actions ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934) by [@Myasuka](https://github.com/Myasuka)) +- Added issue and pull request links that resolve SSH aliases and fork parent repositories ([#8636](https://github.com/getpaseo/paseo/pull/8636), [#9576](https://github.com/getpaseo/paseo/pull/9576)) +- Added an iPhone Duo layout with the sidebar and workspace on opposite sides of the fold ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901) by [@zeyugao](https://github.com/zeyugao)) - Added fx as a provider you can add from the provider catalog in Settings → Hosts → Providers ([#9160](https://github.com/getpaseo/paseo/pull/9160)) -- Added background agents: an agent or plugin can create a helper with `background: true` that opens no tab, sends no notification and stays out of the sidebar and default agent lists ([#8683](https://github.com/getpaseo/paseo/pull/8683)) +- Added background agents that stay out of tabs, notifications and default agent lists ([#8683](https://github.com/getpaseo/paseo/pull/8683)) - Added syntax highlighting for Terraform and HCL files (`.tf`, `.tfvars`, `.hcl`) ([#9106](https://github.com/getpaseo/paseo/pull/9106)) - Added `PASEO_WORKSPACE_ID` to each agent's environment so an agent can identify, rename or archive its own workspace ([#8939](https://github.com/getpaseo/paseo/pull/8939) by [@DTTerastar](https://github.com/DTTerastar)) +- Added plugin badges to sidebar workspace rows ([#7645](https://github.com/getpaseo/paseo/pull/7645) by [@jtomaszewski](https://github.com/jtomaszewski)) +- Added a Download button for files without a preview ([#9640](https://github.com/getpaseo/paseo/pull/9640)) +- Added Copilot premium-request usage and remaining quota to Usage ([#8489](https://github.com/getpaseo/paseo/pull/8489) by [@thisisryanswift](https://github.com/thisisryanswift)) ### Changed - Changed opening a workspace to restore the tab you left instead of jumping to the agent that needs attention ([#8935](https://github.com/getpaseo/paseo/pull/8935)) -- Changed question cards so picking an option no longer advances automatically; continue with Next or Submit ([#8525](https://github.com/getpaseo/paseo/pull/8525)) -- Changed the slash command menu to show loading and error states with Retry, and to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905)) -- Changed the workspace header and tabs to switch to compact controls when Explorer or a split pane narrows the workspace ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao)) +- Changed question cards to wait for Next or Submit after you select an option ([#8525](https://github.com/getpaseo/paseo/pull/8525)) +- Changed the slash command menu to stop selecting `/exit` by default ([#8905](https://github.com/getpaseo/paseo/pull/8905)) +- Changed workspace header controls to fit narrow split panes ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088) by [@zeyugao](https://github.com/zeyugao)) - Changed sending a message to a Pi agent whose process has exited to fail immediately with an instruction to reload the agent ([#8718](https://github.com/getpaseo/paseo/pull/8718)) - Changed Rename workspace in the sidebar on desktop and wide web layouts to edit the title in place instead of opening a dialog ([#9280](https://github.com/getpaseo/paseo/pull/9280)) -- Changed What's new and the website changelog to show a release's highlights first, with the full list behind Show all changes ([#9281](https://github.com/getpaseo/paseo/pull/9281)) +- Changed What's new to show highlights first, with the full list behind Show all changes ([#9281](https://github.com/getpaseo/paseo/pull/9281)) +- Changed Claude Bypass to approve execution requests from ask rules and hooks while keeping questions and plan review interactive ([#9760](https://github.com/getpaseo/paseo/pull/9760)) +- Changed Claude permission cards to show the reason supplied by the provider ([#3950](https://github.com/getpaseo/paseo/pull/3950) by [@codebutler](https://github.com/codebutler)) +- Changed the pull request pane so Activity can be resized or collapsed to give checks more space ([#9656](https://github.com/getpaseo/paseo/pull/9656)) +- Changed macOS desktop tab shortcuts to Cmd+Shift+[ and Cmd+Shift+] ([#7692](https://github.com/getpaseo/paseo/pull/7692) by [@jtomaszewski](https://github.com/jtomaszewski)) +- Changed Cmd/Ctrl+N on New workspace to open the project chooser without leaving the draft ([#9741](https://github.com/getpaseo/paseo/pull/9741)) +- Changed mobile Settings navigation to restore the sidebar where you left it ([#9641](https://github.com/getpaseo/paseo/pull/9641)) ### Fixed +- Fixed long tool details hiding their collapse header or preventing scrolling through their output ([#9770](https://github.com/getpaseo/paseo/pull/9770)) +- Fixed image previews briefly showing an error or a stretched image while loading ([#9698](https://github.com/getpaseo/paseo/pull/9698)) +- Fixed web and desktop chats jumping to the beginning when older history became virtualized ([#9664](https://github.com/getpaseo/paseo/pull/9664) by [@luoph](https://github.com/luoph)) +- Fixed older chat history requiring another mouse-wheel movement after reaching the top ([#9570](https://github.com/getpaseo/paseo/pull/9570)) +- Fixed losing code indentation and line breaks when copying a selection across part of a code block ([#9515](https://github.com/getpaseo/paseo/pull/9515) by [@michaelmwu](https://github.com/michaelmwu)) +- Fixed overlapping axis titles and clipped labels in Mermaid XY charts ([#9483](https://github.com/getpaseo/paseo/pull/9483) by [@FluidXin](https://github.com/FluidXin)) +- Fixed the iOS command menu staying open after tapping a command ([#9755](https://github.com/getpaseo/paseo/pull/9755)) +- Fixed retrying an edited agent draft after a failed start ([#9534](https://github.com/getpaseo/paseo/pull/9534) by [@michaelmwu](https://github.com/michaelmwu)) +- Fixed model profile buttons ignoring taps on Android tablets ([#9526](https://github.com/getpaseo/paseo/pull/9526) by [@moevis](https://github.com/moevis)) +- Fixed Settings losing scroll position and edits after appearance changes ([#9605](https://github.com/getpaseo/paseo/pull/9605)) +- Fixed unreadable selected rows in light plugin themes and barely visible highlights in Pure Black ([#9579](https://github.com/getpaseo/paseo/pull/9579) by [@nathansgreen](https://github.com/nathansgreen)) +- Fixed missing keyboard focus rings on header and toolbar icon buttons on web and desktop ([#9745](https://github.com/getpaseo/paseo/pull/9745) by [@junjzhang](https://github.com/junjzhang)) +- Fixed sidebar rows flashing in the wrong position after a drag on iOS and Android ([#9681](https://github.com/getpaseo/paseo/pull/9681)) +- Fixed desktop startup reporting failure while its daemon was still starting ([#9043](https://github.com/getpaseo/paseo/pull/9043) by [@magiclaw](https://github.com/magiclaw)) +- Fixed typed characters being lost while web and desktop terminals restored their screen ([#9533](https://github.com/getpaseo/paseo/pull/9533)) +- Fixed physical arrow keys failing in Android terminals and dropping the next typed character ([#9407](https://github.com/getpaseo/paseo/pull/9407) by [@moevis](https://github.com/moevis)) +- Fixed non-Git workspaces missing Archive workspace in the command center ([#9777](https://github.com/getpaseo/paseo/pull/9777) by [@andheiberg](https://github.com/andheiberg)) +- Fixed workspace scripts disappearing when a later configuration read timed out ([#9477](https://github.com/getpaseo/paseo/pull/9477) by [@dinhphieu](https://github.com/dinhphieu)) +- Fixed sidebar Usage hiding an account after its usage refresh failed ([#9594](https://github.com/getpaseo/paseo/pull/9594)) +- Fixed closed agents staying unread when their provider session no longer existed ([#9737](https://github.com/getpaseo/paseo/pull/9737) by [@luoph](https://github.com/luoph)) +- Fixed completion notifications showing an older reply after an autonomous agent turn ([#9793](https://github.com/getpaseo/paseo/pull/9793)) +- Fixed interrupting messages failing with "already has an active run" ([#9537](https://github.com/getpaseo/paseo/pull/9537) by [@michaelmwu](https://github.com/michaelmwu)) +- Fixed message retries being refused after a failure before delivery to the provider ([#9580](https://github.com/getpaseo/paseo/pull/9580) by [@tmad4000](https://github.com/tmad4000)) +- Fixed newly reopened agents losing their provider process on the next idle-cleanup sweep ([#8857](https://github.com/getpaseo/paseo/pull/8857) by [@fdkevin0](https://github.com/fdkevin0)) +- Fixed Claude session crons and /loop wakeups being lost to idle runtime cleanup ([#9744](https://github.com/getpaseo/paseo/pull/9744) by [@KronixDev](https://github.com/KronixDev)) +- Fixed forking from a reply when a tool started before it and finished afterward ([#9627](https://github.com/getpaseo/paseo/pull/9627) by [@ragokan](https://github.com/ragokan)) +- Fixed large Codex history pages stopping history loading when their individual items still fit ([#9432](https://github.com/getpaseo/paseo/pull/9432) by [@RockStone](https://github.com/RockStone)) +- Fixed OpenCode sessions failing to reconnect after a daemon restart when OpenCode used Bun ([#9653](https://github.com/getpaseo/paseo/pull/9653) by [@quickwind](https://github.com/quickwind)) +- Fixed provider refresh retaining OpenCode v1 after an upgrade to v2 ([#9593](https://github.com/getpaseo/paseo/pull/9593) by [@tkfka1](https://github.com/tkfka1)) +- Fixed OpenCode v2 failing to discover plugin tools available only to its session ([#9426](https://github.com/getpaseo/paseo/pull/9426) by [@dptsolutions](https://github.com/dptsolutions)) +- Fixed ACP models sharing the wrong thinking levels when the provider supplied levels per model ([#9717](https://github.com/getpaseo/paseo/pull/9717) by [@AlfredRR](https://github.com/AlfredRR), [@doskoi](https://github.com/doskoi)) +- Fixed failed ACP tools without output preventing conversation history from loading ([#9467](https://github.com/getpaseo/paseo/pull/9467) by [@Myasuka](https://github.com/Myasuka)) +- Fixed Pi and OMP tool calls with null optional arguments appearing as unknown tools ([#9506](https://github.com/getpaseo/paseo/pull/9506) by [@papag00se](https://github.com/papag00se)) +- Fixed imported OMP sessions saving a file path instead of their session ID ([#8854](https://github.com/getpaseo/paseo/pull/8854) by [@LiebeLee](https://github.com/LiebeLee)) +- Fixed cross-host child agents losing their caller's mode when both used the same provider ([#9512](https://github.com/getpaseo/paseo/pull/9512) by [@ortschun](https://github.com/ortschun)) +- Fixed plugin child agents changing from failed or canceled to completed when their session closed ([#8563](https://github.com/getpaseo/paseo/pull/8563) by [@hadan8977](https://github.com/hadan8977)) +- Fixed CLI commands acting on a different agent whose title matched a missing full agent ID ([#9680](https://github.com/getpaseo/paseo/pull/9680), [#9731](https://github.com/getpaseo/paseo/pull/9731) by [@ese111](https://github.com/ese111)) +- Fixed archive, detach and reload failing for agents omitted from the CLI listing ([#9726](https://github.com/getpaseo/paseo/pull/9726) by [@xunWhale](https://github.com/xunWhale)) +- Fixed `paseo agent wait` exiting successfully when no agent matched the ID ([#9782](https://github.com/getpaseo/paseo/pull/9782) by [@Eapp1e](https://github.com/Eapp1e)) +- Fixed voice mode failing to start when speech input and output both used OpenAI ([#9779](https://github.com/getpaseo/paseo/pull/9779) by [@Huyvux12](https://github.com/Huyvux12)) +- Fixed dictation hiding a stream error behind a 30-second delivery timeout ([#9784](https://github.com/getpaseo/paseo/pull/9784) by [@tieo](https://github.com/tieo)) +- Fixed plugin providers rejecting Review attachments in All mode ([#9590](https://github.com/getpaseo/paseo/pull/9590) by [@ese111](https://github.com/ese111)) +- Fixed plugin timeline writes accepting kinds that the app could not show ([#7677](https://github.com/getpaseo/paseo/pull/7677) by [@ragokan](https://github.com/ragokan)) +- Fixed the chat moving when a turn ended ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175)) +- Fixed Claude and OpenCode tool rows changing their title and icon as arguments arrived ([#9248](https://github.com/getpaseo/paseo/pull/9248)) +- Fixed the context window popover opening before usage was loaded ([#9212](https://github.com/getpaseo/paseo/pull/9212)) +- Fixed sidebar hover cards opening together ([#9071](https://github.com/getpaseo/paseo/pull/9071)) + - Fixed the working indicator disappearing when returning to a chat whose agent finished while you were away ([#9170](https://github.com/getpaseo/paseo/pull/9170)) -- Fixed chats with short collapsed turns opening with empty space until you scrolled ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083)) - Fixed Collapse turns hiding an earlier reply inside a later turn's summary line after an idle Claude, Codex or OpenCode agent was resumed ([#9098](https://github.com/getpaseo/paseo/pull/9098)) -- Fixed the missing space between a prompt and the reply or collapsed-turn summary line below it ([#9009](https://github.com/getpaseo/paseo/pull/9009)) -- Fixed a long user message showing without its fade and Show more for one frame when a chat opened ([#9302](https://github.com/getpaseo/paseo/pull/9302)) - Fixed Markdown tables showing as literal pipes when written directly below a paragraph with no blank line ([#8485](https://github.com/getpaseo/paseo/pull/8485) by [@ragokan](https://github.com/ragokan), [@suk-6](https://github.com/suk-6), [@thsrite](https://github.com/thsrite)) - Fixed linked badge images that share a line with text rendering as full-width blocks on web and desktop ([#8530](https://github.com/getpaseo/paseo/pull/8530)) - Fixed View diagram opening fullscreen instead of returning to the inline Mermaid diagram after View source ([#8932](https://github.com/getpaseo/paseo/pull/8932) by [@luoph](https://github.com/luoph)) @@ -47,21 +104,16 @@ - Fixed unsent composer text and attachments being deleted when an agent tab was closed ([#9079](https://github.com/getpaseo/paseo/pull/9079)) - Fixed pasting text with hyperlinks into the composer dropping the link URLs; links now paste as Markdown ([#8972](https://github.com/getpaseo/paseo/pull/8972)) - Fixed the composer losing focus after clicking Send with a mouse ([#9015](https://github.com/getpaseo/paseo/pull/9015)) -- Fixed the composer resting 50pt above the bottom edge on iPhone ([#8823](https://github.com/getpaseo/paseo/pull/8823) by [@zeyugao](https://github.com/zeyugao)) - Fixed Add host sending you to Settings from the sidebar and New workspace ([#8512](https://github.com/getpaseo/paseo/pull/8512)) - Fixed a failed agent's red dot and Failed grouping staying in the sidebar after opening the agent or choosing Mark as read ([#8831](https://github.com/getpaseo/paseo/pull/8831)) -- Fixed a workspace's unread indicator staying on after it was cleared while the agent's runtime was closed ([#9087](https://github.com/getpaseo/paseo/pull/9087)) - Fixed unarchiving a workspace not restoring the agents that were archived with it ([#9210](https://github.com/getpaseo/paseo/pull/9210)) - Fixed the context window popover closing by itself whenever the chat scrolled during a streaming reply ([#8742](https://github.com/getpaseo/paseo/pull/8742) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed the sidebar usage summary updating only when Usage was opened ([#7806](https://github.com/getpaseo/paseo/pull/7806) by [@ragokan](https://github.com/ragokan)) -- Fixed tooltips and menus above their trigger briefly covering it on Android when their content grew after opening ([#9247](https://github.com/getpaseo/paseo/pull/9247)) - Fixed History showing "Could not load history" after reloading the web app on the History screen ([#9029](https://github.com/getpaseo/paseo/pull/9029)) - Fixed section links in an HTML file preview replacing the preview with the Paseo app instead of scrolling within the file ([#8559](https://github.com/getpaseo/paseo/pull/8559) by [@3ae3ae](https://github.com/3ae3ae)) - Fixed Files Refresh leaving a newly created file hidden when its folder was collapsed during the refresh ([#8582](https://github.com/getpaseo/paseo/pull/8582) by [@hadan8977](https://github.com/hadan8977)) - Fixed the branch switcher showing "No branches found" while branches are still loading or after the request fails ([#8938](https://github.com/getpaseo/paseo/pull/8938)) - Fixed commit history showing a doubled slash, no rename status and no diff for a file moved up a directory ([#8509](https://github.com/getpaseo/paseo/pull/8509) by [@hadan8977](https://github.com/hadan8977)) -- Fixed a merged pull request disappearing from its workspace when the checkout was behind the pull request's head -- Fixed workspace Git watchers staying in fallback polling after a watcher setup timeout - Fixed abandoned connections staying open for up to 45 seconds after the web or desktop app reconnected ([#9067](https://github.com/getpaseo/paseo/pull/9067)) - Fixed a connection routed through another host closing with "The receiving client cannot keep up with host output" while fetching a very large timeline ([#9109](https://github.com/getpaseo/paseo/pull/9109)) - Fixed a connected host staying in error after it was updated to a supported version ([#8423](https://github.com/getpaseo/paseo/pull/8423) by [@DAnaeto](https://github.com/DAnaeto)) @@ -123,16 +175,21 @@ - Fixed a plugin the daemon terminated for an invalid message staying listed with no exit reported ([#9285](https://github.com/getpaseo/paseo/pull/9285) by [@Brandon168](https://github.com/Brandon168)) - Fixed ACP provider plugins dropping the token usage an agent reports in its prompt response ([#9396](https://github.com/getpaseo/paseo/pull/9396) by [@Myasuka](https://github.com/Myasuka)) - Fixed the published `@getpaseo/*` npm packages declaring no license; they now declare Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816) by [@mdlawson](https://github.com/mdlawson), [@ragokan](https://github.com/ragokan)) -- Fixed forking from an earlier reply failing with "This checkpoint changed after it was created" after a plugin updated one of its timeline cards ([#8746](https://github.com/getpaseo/paseo/pull/8746) by [@monarchmaisuriya](https://github.com/monarchmaisuriya)) - Fixed Collapse turns leaving a turn open, or folding to an earlier reply, when a plugin renders the final reply ([#8811](https://github.com/getpaseo/paseo/pull/8811) by [@geoqiao](https://github.com/geoqiao)) - Fixed plugin screens showing "This plugin surface is unavailable" while the plugin catalog is still loading after an app reload ([#8123](https://github.com/getpaseo/paseo/pull/8123) by [@vs-tahir](https://github.com/vs-tahir)) - Fixed the Workspaces list being pushed out of the mobile sidebar on short screens when plugins add many navigation items ([#8727](https://github.com/getpaseo/paseo/pull/8727) by [@jaredwang](https://github.com/jaredwang)) - Fixed timeline plugins not receiving the sender, event and original text on agent-message tool calls ([#8492](https://github.com/getpaseo/paseo/pull/8492) by [@RRD-dev](https://github.com/RRD-dev), [@luoph](https://github.com/luoph)) - Fixed plugin RPCs failing when their input or output schema uses a transform ([#8550](https://github.com/getpaseo/paseo/pull/8550)) +### Breaking + +- Removed the deprecated `agent.turn.after.timeline` SDK field, which always returned an empty list ([#9573](https://github.com/getpaseo/paseo/pull/9573) by [@jtomaszewski](https://github.com/jtomaszewski)) + ### Notes -- Background tasks, the Change base picker, archive undo, background agents, plugin subscriptions and fx need both the host and the app on this version +- Update both the host and app to use the plugin gallery, background tasks, Change base, archive undo, background agents, plugin subscriptions and fx +- Plugin authors reading `agent.turn.after.timeline` must use `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })` and filter entries by `event.turnId` +- Archive undo restores the workspace, not uncommitted files removed with its worktree ## 0.15.4 - 2026-11-10 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index a3f7fbfa3f..21b99a1345 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,45 +1,102 @@ # Changelog -## 0.16.0-beta.2 - 2026-11-11 +## 0.16.0 - 2026-11-16 -- **后台任务**:Paseo 现在会在 Composer 上方显示 Agent 正在运行的后台任务,例如 shell 和监视器,每项都带“停止”按钮。支持 Claude Code、Codex 和 OpenCode v2。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162),贡献者:[@fxlelouarn](https://github.com/fxlelouarn)) -- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏内容,展示所有已连接主机上的工作区、Agent、项目和终端。在“设置 → 侧边栏”中为每台设备选择视图;Paseo 的侧边栏页眉和页脚保持不变。 ([#8906](https://github.com/getpaseo/paseo/pull/8906)) -- **插件 Composer 控件**:插件可以向 Composer 添加自己的控件,并读取和设置其中的提示词、附件、Provider、模型、模式和思考强度。插件还可以把光标放到任意 Agent 的 Composer 中、向“新建工作区”添加条目,并在 Agent 和工作区上保存自己的元数据。 ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207)) -- **更快的 diff 加载**:打开“更改”时会立即显示文件树,文件内容随后加载。大型 diff 分批到达,加载期间应用的其他部分照常响应,并且 diff 优先于 daemon 的后台 worktree 扫描。 ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243)) -- **细节打磨**:一轮对话结束时聊天保持不动,返回没有变化的聊天时直接显示原样,无需刷新。工具行从第一帧起就显示最终标题和图标,上下文窗口浮层打开时用量已加载完成,侧边栏悬停卡片一次只打开一个。 ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175), [#9242](https://github.com/getpaseo/paseo/pull/9242), [#9248](https://github.com/getpaseo/paseo/pull/9248), [#9212](https://github.com/getpaseo/paseo/pull/9212), [#9071](https://github.com/getpaseo/paseo/pull/9071)) -- **重建移动端聊天时间线**:iOS 和 Android 上的聊天时间线已重建。展开或折叠轮次摘要、待办卡片或工具调用组时,你点按的那一行保持原位;在 Android 上,“显示更多”“收起”和计划卡片也是如此。 ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085)) -- **移动端键盘快捷键**:连接键盘后,iPad 和 Android 现在可使用与桌面端相同的快捷键,包括你自定义的绑定。检测到键盘时会显示快捷键提示和“设置 → 快捷键”。在较窄的桌面端和浏览器窗口中快捷键同样可用。 ([#8625](https://github.com/getpaseo/paseo/pull/8625),贡献者:[@jeroenfrenken](https://github.com/jeroenfrenken)、[@lstroud](https://github.com/lstroud)) -- **适合触控的平板控件**:在 iPad 和其他触屏设备上,宽屏布局现在使用适合触控尺寸的按钮、行和栏。Composer 工具栏在空间不足时会把控件收进模型菜单;在工作区上向右滑动,可将已折叠的侧边栏以浮层方式显示。 ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739),贡献者:[@zeyugao](https://github.com/zeyugao)) -- **撤销工作区归档**:在应用中归档工作区时,现在会显示“Workspace 已归档”提示,持续六秒。点击“撤销”或按 Cmd/Ctrl+Z 可恢复该工作区及其标签页和 Agent。在桌面端,侧边栏的工作区行在悬停时还会显示归档按钮。 ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104)) -- **返回时更少重连**:返回应用时会保留仍可用的连接,包括正在传输大型响应的连接,只在必要时重连一次。主机保存了多个连接时,Paseo 会留在可用的那个连接上。 ([#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116)) +- **后台任务**:在 Composer 上方查看并停止 Claude Code、Codex 和 OpenCode v2 的后台任务。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635),贡献者:[@fxlelouarn](https://github.com/fxlelouarn)) +- **内置插件库**:无需离开 Paseo,即可浏览、搜索和安装插件,并在同一页面管理插件设置和更新。 ([#9752](https://github.com/getpaseo/paseo/pull/9752)) +- **命令中心标签页**:在工作区、文件和操作之间切换,最近使用的工作区优先显示。搜索现在包含已归档工作区,还可匹配工作区内的 Agent 标题。 ([#9689](https://github.com/getpaseo/paseo/pull/9689)) +- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏,展示已连接主机上的工作区和 Agent。在“设置 → 侧边栏”中为每台设备选择视图。 ([#8906](https://github.com/getpaseo/paseo/pull/8906)) +- **插件 Composer 控件**:插件可以添加 Composer 控件、编辑草稿和附件,以及更改 Agent 设置。插件还可以添加“新建工作区”条目,并在 Agent 和工作区上保存元数据。 ([#8744](https://github.com/getpaseo/paseo/pull/8744), [#9209](https://github.com/getpaseo/paseo/pull/9209), [#9207](https://github.com/getpaseo/paseo/pull/9207), [#9734](https://github.com/getpaseo/paseo/pull/9734),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- **排列用量卡片**:拖动 Provider 卡片来调整顺序,并关闭不想在侧边栏摘要中显示的卡片。在用量设置中选择主机。 ([#9660](https://github.com/getpaseo/paseo/pull/9660), [#9740](https://github.com/getpaseo/paseo/pull/9740), [#9748](https://github.com/getpaseo/paseo/pull/9748), [#9780](https://github.com/getpaseo/paseo/pull/9780)) +- **返回应用时更少提示**:返回没有变化的聊天时,不再闪现“正在更新消息”。Paseo 会保留可用的连接,并在你返回时恢复断开的连接。重连后,已是最新状态的聊天也不再显示额外的更新提示。 ([#9242](https://github.com/getpaseo/paseo/pull/9242), [#8651](https://github.com/getpaseo/paseo/pull/8651), [#9086](https://github.com/getpaseo/paseo/pull/9086), [#8855](https://github.com/getpaseo/paseo/pull/8855), [#9116](https://github.com/getpaseo/paseo/pull/9116), [#9558](https://github.com/getpaseo/paseo/pull/9558),贡献者:[@adamcstephens](https://github.com/adamcstephens)) +- **重建移动端聊天**:在 iOS 和 Android 上展开轮次摘要、待办卡片和工具组时,阅读位置保持不变。滚动期间发送消息会移到新提示词处。 ([#8717](https://github.com/getpaseo/paseo/pull/8717), [#9085](https://github.com/getpaseo/paseo/pull/9085), [#9806](https://github.com/getpaseo/paseo/pull/9806), [#9693](https://github.com/getpaseo/paseo/pull/9693)) +- **更快的 diff 加载**:“更改”在文件内容加载完成前先显示文件树。大型 diff 分批加载,且优先于后台 worktree 扫描。 ([#8907](https://github.com/getpaseo/paseo/pull/8907), [#9241](https://github.com/getpaseo/paseo/pull/9241), [#9243](https://github.com/getpaseo/paseo/pull/9243), [#9584](https://github.com/getpaseo/paseo/pull/9584)) +- **更快的 Composer 菜单**:大型列表中的命令和文件建议更快打开,并随 Composer 尺寸变化保持贴合。 ([#9657](https://github.com/getpaseo/paseo/pull/9657), [#9647](https://github.com/getpaseo/paseo/pull/9647), [#9642](https://github.com/getpaseo/paseo/pull/9642)) +- **移动端键盘快捷键**:连接键盘后,iPad 和 Android 可使用与桌面端相同的快捷键,包括自定义绑定。在 iPad Composer 中按 Shift+Tab 会切换模式,不再输入制表符。 ([#8625](https://github.com/getpaseo/paseo/pull/8625), [#9561](https://github.com/getpaseo/paseo/pull/9561),贡献者:[@jeroenfrenken](https://github.com/jeroenfrenken), [@lstroud](https://github.com/lstroud)) +- **适合触控的平板控件**:触屏设备上的宽屏布局使用更大的按钮和行。空间不足时,Composer 会将控件收进模型菜单。 ([#8748](https://github.com/getpaseo/paseo/pull/8748), [#8885](https://github.com/getpaseo/paseo/pull/8885), [#8891](https://github.com/getpaseo/paseo/pull/8891), [#8909](https://github.com/getpaseo/paseo/pull/8909), [#9151](https://github.com/getpaseo/paseo/pull/9151), [#9238](https://github.com/getpaseo/paseo/pull/9238), [#8739](https://github.com/getpaseo/paseo/pull/8739),贡献者:[@zeyugao](https://github.com/zeyugao)) +- **撤销工作区归档**:在六秒提示期间,点击“撤销”或按 Cmd/Ctrl+Z 可恢复已归档的工作区。Paseo 在移除 worktree 前会检查未保存的文件和未推送的提交。 ([#8904](https://github.com/getpaseo/paseo/pull/8904), [#9104](https://github.com/getpaseo/paseo/pull/9104), [#9625](https://github.com/getpaseo/paseo/pull/9625), [#9753](https://github.com/getpaseo/paseo/pull/9753),贡献者:[@ragokan](https://github.com/ragokan)) ### 新增 -- 在“更改”中为 worktree 工作区新增基准分支选择器(Change base),diff、提交列表和 Git 操作可改用其他分支 ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934),贡献者:[@Myasuka](https://github.com/Myasuka)) -- 新增 Issue 和 PR 引用链接:Agent 回复、计划、PR 面板和文件预览中的 `#123`、`owner/repo#123` 等引用会链接到 GitHub、GitLab、Gitea、Forgejo 或 Codeberg ([#8636](https://github.com/getpaseo/paseo/pull/8636)) -- 新增 iPhone Duo 布局支持:工作区操作位于系统竖向栏中,侧边栏和工作区分列折痕两侧 ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901),贡献者:[@zeyugao](https://github.com/zeyugao)) +- 为 worktree 的 diff、提交和 Git 操作新增基准分支选择器(Change base) ([#8642](https://github.com/getpaseo/paseo/pull/8642), [#8934](https://github.com/getpaseo/paseo/pull/8934),贡献者:[@Myasuka](https://github.com/Myasuka)) +- 新增可解析 SSH 别名和 fork 上游仓库的 Issue 和 PR 链接 ([#8636](https://github.com/getpaseo/paseo/pull/8636), [#9576](https://github.com/getpaseo/paseo/pull/9576)) +- 新增 iPhone Duo 布局,侧边栏和工作区分列折痕两侧 ([#8741](https://github.com/getpaseo/paseo/pull/8741), [#8901](https://github.com/getpaseo/paseo/pull/8901),贡献者:[@zeyugao](https://github.com/zeyugao)) - 新增 fx Provider,可在“设置 → Hosts → 提供方”的 Provider 目录中添加 ([#9160](https://github.com/getpaseo/paseo/pull/9160)) -- 新增后台 Agent:Agent 或插件可通过 `background: true` 创建辅助 Agent,它不打开标签页、不发送通知,也不出现在侧边栏和默认 Agent 列表中 ([#8683](https://github.com/getpaseo/paseo/pull/8683)) +- 新增后台 Agent,不占用标签页、不发送通知,也不出现在默认 Agent 列表中 ([#8683](https://github.com/getpaseo/paseo/pull/8683)) - 新增 Terraform 和 HCL 文件(`.tf`、`.tfvars`、`.hcl`)的语法高亮 ([#9106](https://github.com/getpaseo/paseo/pull/9106)) - 在每个 Agent 的环境中新增 `PASEO_WORKSPACE_ID`,Agent 可据此识别、重命名或归档自己的工作区 ([#8939](https://github.com/getpaseo/paseo/pull/8939),贡献者:[@DTTerastar](https://github.com/DTTerastar)) +- 为侧边栏工作区行新增插件徽章 ([#7645](https://github.com/getpaseo/paseo/pull/7645),贡献者:[@jtomaszewski](https://github.com/jtomaszewski)) +- 为无法预览的文件新增“下载”按钮 ([#9640](https://github.com/getpaseo/paseo/pull/9640)) +- 在用量中新增 Copilot 高级请求用量和剩余额度 ([#8489](https://github.com/getpaseo/paseo/pull/8489),贡献者:[@thisisryanswift](https://github.com/thisisryanswift)) ### 变更 - 打开工作区时恢复你离开时的标签页,不再跳转到需要关注的 Agent ([#8935](https://github.com/getpaseo/paseo/pull/8935)) -- 问题卡片中选择选项后不再自动前进;请用“下一步”或“提交”继续 ([#8525](https://github.com/getpaseo/paseo/pull/8525)) -- 斜杠命令菜单现在显示加载和错误状态并提供“重试”,且不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905)) -- 文件浏览器(Explorer)或分屏使工作区变窄时,工作区页眉和标签页改用紧凑控件 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao)) +- 问题卡片在选择选项后等待点击“下一步”或“提交” ([#8525](https://github.com/getpaseo/paseo/pull/8525)) +- 斜杠命令菜单不再默认选中 `/exit` ([#8905](https://github.com/getpaseo/paseo/pull/8905)) +- 调整工作区页眉控件以适应较窄的分屏窗格 ([#8740](https://github.com/getpaseo/paseo/pull/8740), [#9088](https://github.com/getpaseo/paseo/pull/9088),贡献者:[@zeyugao](https://github.com/zeyugao)) - 向进程已退出的 Pi Agent 发送消息时立即失败,并提示重新加载该 Agent ([#8718](https://github.com/getpaseo/paseo/pull/8718)) - 在桌面端和宽屏网页布局中,侧边栏的“重命名 workspace”改为在原处编辑标题,不再打开对话框 ([#9280](https://github.com/getpaseo/paseo/pull/9280)) -- “更新内容”和网站更新日志改为先显示每个版本的亮点,完整列表收在“显示全部变更”之后 ([#9281](https://github.com/getpaseo/paseo/pull/9281)) +- “更新内容”先显示亮点,完整列表收在“显示全部变更”之后 ([#9281](https://github.com/getpaseo/paseo/pull/9281)) +- Claude Bypass 现在批准来自 ask 规则和钩子的执行请求,提问和计划审核仍保留交互 ([#9760](https://github.com/getpaseo/paseo/pull/9760)) +- Claude 权限卡片现在显示 Provider 提供的原因 ([#3950](https://github.com/getpaseo/paseo/pull/3950),贡献者:[@codebutler](https://github.com/codebutler)) +- PR 窗格中的“活动”可调整大小或折叠,为检查结果留出更多空间 ([#9656](https://github.com/getpaseo/paseo/pull/9656)) +- macOS 桌面端的标签页切换快捷键改为 Cmd+Shift+[ 和 Cmd+Shift+] ([#7692](https://github.com/getpaseo/paseo/pull/7692),贡献者:[@jtomaszewski](https://github.com/jtomaszewski)) +- 在“新建工作区”按 Cmd/Ctrl+N 会打开项目选择器,同时保留草稿 ([#9741](https://github.com/getpaseo/paseo/pull/9741)) +- 移动端设置导航现在恢复侧边栏之前的位置 ([#9641](https://github.com/getpaseo/paseo/pull/9641)) ### 修复 +- 修复较长的工具详情隐藏折叠标题或无法滚动查看输出的问题 ([#9770](https://github.com/getpaseo/paseo/pull/9770)) +- 修复图片预览加载时短暂显示错误或拉伸图片的问题 ([#9698](https://github.com/getpaseo/paseo/pull/9698)) +- 修复网页端和桌面端聊天在较早历史记录进入虚拟化后跳到开头的问题 ([#9664](https://github.com/getpaseo/paseo/pull/9664),贡献者:[@luoph](https://github.com/luoph)) +- 修复滚动到顶部后仍需再次滚动鼠标滚轮才能加载更早聊天记录的问题 ([#9570](https://github.com/getpaseo/paseo/pull/9570)) +- 修复跨越部分代码块复制选区时丢失缩进和换行的问题 ([#9515](https://github.com/getpaseo/paseo/pull/9515),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- 修复 Mermaid XY 图表的轴标题重叠和标签被裁切的问题 ([#9483](https://github.com/getpaseo/paseo/pull/9483),贡献者:[@FluidXin](https://github.com/FluidXin)) +- 修复 iOS 上点击命令后命令菜单仍保持打开的问题 ([#9755](https://github.com/getpaseo/paseo/pull/9755)) +- 修复 Agent 启动失败后无法重试已编辑草稿的问题 ([#9534](https://github.com/getpaseo/paseo/pull/9534),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- 修复 Android 平板上模型配置按钮不响应点按的问题 ([#9526](https://github.com/getpaseo/paseo/pull/9526),贡献者:[@moevis](https://github.com/moevis)) +- 修复更改外观后设置页面丢失滚动位置和编辑内容的问题 ([#9605](https://github.com/getpaseo/paseo/pull/9605)) +- 修复浅色插件主题中选中行难以阅读、Pure Black 中高亮几乎不可见的问题 ([#9579](https://github.com/getpaseo/paseo/pull/9579),贡献者:[@nathansgreen](https://github.com/nathansgreen)) +- 修复网页端和桌面端页眉及工具栏图标按钮缺少键盘焦点框的问题 ([#9745](https://github.com/getpaseo/paseo/pull/9745),贡献者:[@junjzhang](https://github.com/junjzhang)) +- 修复 iOS 和 Android 上拖动后侧边栏行短暂出现在错误位置的问题 ([#9681](https://github.com/getpaseo/paseo/pull/9681)) +- 修复桌面端在 daemon 仍启动时报告启动失败的问题 ([#9043](https://github.com/getpaseo/paseo/pull/9043),贡献者:[@magiclaw](https://github.com/magiclaw)) +- 修复网页端和桌面端终端恢复画面时丢失输入字符的问题 ([#9533](https://github.com/getpaseo/paseo/pull/9533)) +- 修复 Android 终端中实体方向键失效并丢失下一个输入字符的问题 ([#9407](https://github.com/getpaseo/paseo/pull/9407),贡献者:[@moevis](https://github.com/moevis)) +- 修复非 Git 工作区在命令中心缺少“归档工作区”的问题 ([#9777](https://github.com/getpaseo/paseo/pull/9777),贡献者:[@andheiberg](https://github.com/andheiberg)) +- 修复后续配置读取超时后工作区脚本消失的问题 ([#9477](https://github.com/getpaseo/paseo/pull/9477),贡献者:[@dinhphieu](https://github.com/dinhphieu)) +- 修复账号用量刷新失败后侧边栏用量隐藏该账号的问题 ([#9594](https://github.com/getpaseo/paseo/pull/9594)) +- 修复 Provider 会话已不存在时,已关闭 Agent 仍保持未读的问题 ([#9737](https://github.com/getpaseo/paseo/pull/9737),贡献者:[@luoph](https://github.com/luoph)) +- 修复 Agent 自主运行一轮后完成通知显示旧回复的问题 ([#9793](https://github.com/getpaseo/paseo/pull/9793)) +- 修复中断消息因“already has an active run”而失败的问题 ([#9537](https://github.com/getpaseo/paseo/pull/9537),贡献者:[@michaelmwu](https://github.com/michaelmwu)) +- 修复消息在交给 Provider 前失败后无法重试的问题 ([#9580](https://github.com/getpaseo/paseo/pull/9580),贡献者:[@tmad4000](https://github.com/tmad4000)) +- 修复刚重新打开的 Agent 在下一次空闲清理时失去 Provider 进程的问题 ([#8857](https://github.com/getpaseo/paseo/pull/8857),贡献者:[@fdkevin0](https://github.com/fdkevin0)) +- 修复空闲运行时清理导致 Claude 会话 cron 和 /loop 唤醒丢失的问题 ([#9744](https://github.com/getpaseo/paseo/pull/9744),贡献者:[@KronixDev](https://github.com/KronixDev)) +- 修复工具在回复之前开始、之后结束时无法从该回复分叉的问题 ([#9627](https://github.com/getpaseo/paseo/pull/9627),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复大型 Codex 历史页面在单个条目仍符合大小限制时阻断历史加载的问题 ([#9432](https://github.com/getpaseo/paseo/pull/9432),贡献者:[@RockStone](https://github.com/RockStone)) +- 修复 OpenCode 使用 Bun 时,daemon 重启后会话无法重新连接的问题 ([#9653](https://github.com/getpaseo/paseo/pull/9653),贡献者:[@quickwind](https://github.com/quickwind)) +- 修复 OpenCode 升级到 v2 后刷新 Provider 仍保留 v1 的问题 ([#9593](https://github.com/getpaseo/paseo/pull/9593),贡献者:[@tkfka1](https://github.com/tkfka1)) +- 修复 OpenCode v2 无法发现仅对其会话可用的插件工具的问题 ([#9426](https://github.com/getpaseo/paseo/pull/9426),贡献者:[@dptsolutions](https://github.com/dptsolutions)) +- 修复 ACP Provider 按模型提供思考等级时,模型共用错误等级的问题 ([#9717](https://github.com/getpaseo/paseo/pull/9717),贡献者:[@AlfredRR](https://github.com/AlfredRR), [@doskoi](https://github.com/doskoi)) +- 修复没有输出的失败 ACP 工具阻止对话历史加载的问题 ([#9467](https://github.com/getpaseo/paseo/pull/9467),贡献者:[@Myasuka](https://github.com/Myasuka)) +- 修复带有 null 可选参数的 Pi 和 OMP 工具调用显示为未知工具的问题 ([#9506](https://github.com/getpaseo/paseo/pull/9506),贡献者:[@papag00se](https://github.com/papag00se)) +- 修复导入 OMP 会话时保存文件路径而非会话 ID 的问题 ([#8854](https://github.com/getpaseo/paseo/pull/8854),贡献者:[@LiebeLee](https://github.com/LiebeLee)) +- 修复跨主机子 Agent 与调用者使用相同 Provider 时丢失调用者模式的问题 ([#9512](https://github.com/getpaseo/paseo/pull/9512),贡献者:[@ortschun](https://github.com/ortschun)) +- 修复插件子 Agent 在会话关闭时从失败或已取消变为已完成的问题 ([#8563](https://github.com/getpaseo/paseo/pull/8563),贡献者:[@hadan8977](https://github.com/hadan8977)) +- 修复完整 Agent ID 不存在时,CLI 命令误操作标题与该 ID 相同的其他 Agent 的问题 ([#9680](https://github.com/getpaseo/paseo/pull/9680), [#9731](https://github.com/getpaseo/paseo/pull/9731),贡献者:[@ese111](https://github.com/ese111)) +- 修复无法归档、分离或重新加载未出现在 CLI 列表中的 Agent 的问题 ([#9726](https://github.com/getpaseo/paseo/pull/9726),贡献者:[@xunWhale](https://github.com/xunWhale)) +- 修复 `paseo agent wait` 在没有 Agent 匹配 ID 时仍成功退出的问题 ([#9782](https://github.com/getpaseo/paseo/pull/9782),贡献者:[@Eapp1e](https://github.com/Eapp1e)) +- 修复语音输入和输出都使用 OpenAI 时无法启动语音模式的问题 ([#9779](https://github.com/getpaseo/paseo/pull/9779),贡献者:[@Huyvux12](https://github.com/Huyvux12)) +- 修复听写流错误被 30 秒交付超时掩盖的问题 ([#9784](https://github.com/getpaseo/paseo/pull/9784),贡献者:[@tieo](https://github.com/tieo)) +- 修复插件 Provider 在 All 模式下拒绝 Review 附件的问题 ([#9590](https://github.com/getpaseo/paseo/pull/9590),贡献者:[@ese111](https://github.com/ese111)) +- 修复插件时间线写入接受应用无法显示的类型的问题 ([#7677](https://github.com/getpaseo/paseo/pull/7677),贡献者:[@ragokan](https://github.com/ragokan)) +- 修复一轮结束时聊天位置移动的问题 ([#8944](https://github.com/getpaseo/paseo/pull/8944), [#9175](https://github.com/getpaseo/paseo/pull/9175)) +- 修复 Claude 和 OpenCode 工具行随参数到达而更改标题和图标的问题 ([#9248](https://github.com/getpaseo/paseo/pull/9248)) +- 修复用量加载前上下文窗口浮层提前打开的问题 ([#9212](https://github.com/getpaseo/paseo/pull/9212)) +- 修复多个侧边栏悬停卡片同时打开的问题 ([#9071](https://github.com/getpaseo/paseo/pull/9071)) + - 修复 Agent 在你离开期间完成后,返回聊天时工作指示器消失的问题 ([#9170](https://github.com/getpaseo/paseo/pull/9170)) -- 修复包含较短折叠轮次的聊天打开时留有空白、需滚动后才填满的问题 ([#8358](https://github.com/getpaseo/paseo/pull/8358), [#9083](https://github.com/getpaseo/paseo/pull/9083)) - 修复空闲的 Claude、Codex 或 OpenCode Agent 恢复后,“折叠轮次”把较早的回复藏进后一轮摘要行的问题 ([#9098](https://github.com/getpaseo/paseo/pull/9098)) -- 修复提示词与其下方的回复或折叠轮次摘要行之间缺少间距的问题 ([#9009](https://github.com/getpaseo/paseo/pull/9009)) -- 修复聊天打开时,较长的用户消息有一帧不显示渐隐效果和“展开”的问题 ([#9302](https://github.com/getpaseo/paseo/pull/9302)) - 修复紧跟在段落之后、中间没有空行的 Markdown 表格显示为原始竖线的问题 ([#8485](https://github.com/getpaseo/paseo/pull/8485),贡献者:[@ragokan](https://github.com/ragokan)、[@suk-6](https://github.com/suk-6)、[@thsrite](https://github.com/thsrite)) - 修复网页版和桌面端中与文字同行的带链接徽章图片被渲染成整行宽度的问题 ([#8530](https://github.com/getpaseo/paseo/pull/8530)) - 修复“查看源码”后点击“查看图表”会打开全屏、而不是回到内联 Mermaid 图表的问题 ([#8932](https://github.com/getpaseo/paseo/pull/8932),贡献者:[@luoph](https://github.com/luoph)) @@ -47,21 +104,16 @@ - 修复关闭 Agent 标签页时未发送的 Composer 文本和附件被删除的问题 ([#9079](https://github.com/getpaseo/paseo/pull/9079)) - 修复向 Composer 粘贴带超链接的文本时丢失链接地址的问题;链接现在以 Markdown 形式粘贴 ([#8972](https://github.com/getpaseo/paseo/pull/8972)) - 修复用鼠标点击“发送”后 Composer 失去焦点的问题 ([#9015](https://github.com/getpaseo/paseo/pull/9015)) -- 修复 iPhone 上 Composer 停在距底部边缘 50pt 处的问题 ([#8823](https://github.com/getpaseo/paseo/pull/8823),贡献者:[@zeyugao](https://github.com/zeyugao)) - 修复从侧边栏和“新建工作区”点击“添加主机”会跳转到“设置”的问题 ([#8512](https://github.com/getpaseo/paseo/pull/8512)) - 修复打开失败的 Agent 或选择 Mark as read 后,其红点和“失败”分组仍留在侧边栏的问题 ([#8831](https://github.com/getpaseo/paseo/pull/8831)) -- 修复在 Agent 运行时已关闭的情况下清除未读后,工作区的未读指示仍然亮着的问题 ([#9087](https://github.com/getpaseo/paseo/pull/9087)) - 修复取消归档工作区时未恢复随之归档的 Agent 的问题 ([#9210](https://github.com/getpaseo/paseo/pull/9210)) - 修复流式回复期间聊天一滚动上下文窗口浮层就自行关闭的问题 ([#8742](https://github.com/getpaseo/paseo/pull/8742),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复侧边栏用量摘要只在打开“使用情况”时才更新的问题 ([#7806](https://github.com/getpaseo/paseo/pull/7806),贡献者:[@ragokan](https://github.com/ragokan)) -- 修复 Android 上位于触发元素上方的提示和菜单在打开后内容变多时短暂盖住触发元素的问题 ([#9247](https://github.com/getpaseo/paseo/pull/9247)) - 修复在“历史”页面刷新网页版后显示“无法加载历史”的问题 ([#9029](https://github.com/getpaseo/paseo/pull/9029)) - 修复 HTML 文件预览中的章节链接把预览替换成 Paseo 应用、而不是在文件内滚动的问题 ([#8559](https://github.com/getpaseo/paseo/pull/8559),贡献者:[@3ae3ae](https://github.com/3ae3ae)) - 修复“文件”刷新期间文件夹处于折叠状态时,新建的文件一直不显示的问题 ([#8582](https://github.com/getpaseo/paseo/pull/8582),贡献者:[@hadan8977](https://github.com/hadan8977)) - 修复分支仍在加载或请求失败时,分支切换器显示“没有找到分支。”的问题 ([#8938](https://github.com/getpaseo/paseo/pull/8938)) - 修复文件被移到上一级目录时,提交历史显示双斜杠、没有重命名状态也没有 diff 的问题 ([#8509](https://github.com/getpaseo/paseo/pull/8509),贡献者:[@hadan8977](https://github.com/hadan8977)) -- 修复检出落后于 PR 头部时,已合并的 PR 从其工作区中消失的问题 -- 修复工作区 Git 监视器在设置超时后一直停留在回退轮询的问题 - 修复网页版或桌面端重连后,被放弃的连接最多保持打开 45 秒的问题 ([#9067](https://github.com/getpaseo/paseo/pull/9067)) - 修复通过另一台主机路由的连接在获取超大时间线时以“The receiving client cannot keep up with host output”关闭的问题 ([#9109](https://github.com/getpaseo/paseo/pull/9109)) - 修复已连接的主机在更新到受支持的版本后仍停留在错误状态的问题 ([#8423](https://github.com/getpaseo/paseo/pull/8423),贡献者:[@DAnaeto](https://github.com/DAnaeto)) @@ -123,16 +175,21 @@ - 修复 daemon 因无效消息终止插件后,该插件仍留在列表中且未报告退出的问题 ([#9285](https://github.com/getpaseo/paseo/pull/9285),贡献者:[@Brandon168](https://github.com/Brandon168)) - 修复 ACP Provider 插件丢弃 Agent 在提示词响应中报告的 token 用量的问题 ([#9396](https://github.com/getpaseo/paseo/pull/9396),贡献者:[@Myasuka](https://github.com/Myasuka)) - 修复已发布的 `@getpaseo/*` npm 包未声明许可证的问题;现在声明为 Apache-2.0 ([#7816](https://github.com/getpaseo/paseo/pull/7816),贡献者:[@mdlawson](https://github.com/mdlawson)、[@ragokan](https://github.com/ragokan)) -- 修复插件更新了自己的某张时间线卡片后,从较早的回复分叉因“This checkpoint changed after it was created”失败的问题 ([#8746](https://github.com/getpaseo/paseo/pull/8746),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya)) - 修复由插件渲染最终回复时,“折叠轮次”让轮次保持展开或折叠到较早回复的问题 ([#8811](https://github.com/getpaseo/paseo/pull/8811),贡献者:[@geoqiao](https://github.com/geoqiao)) - 修复应用刷新后插件目录仍在加载时,插件页面显示“This plugin surface is unavailable”的问题 ([#8123](https://github.com/getpaseo/paseo/pull/8123),贡献者:[@vs-tahir](https://github.com/vs-tahir)) - 修复插件添加了许多导航项时,矮屏上的工作区列表被挤出移动端侧边栏的问题 ([#8727](https://github.com/getpaseo/paseo/pull/8727),贡献者:[@jaredwang](https://github.com/jaredwang)) - 修复时间线插件在 Agent 消息工具调用上收不到发送方、事件和原始文本的问题 ([#8492](https://github.com/getpaseo/paseo/pull/8492),贡献者:[@RRD-dev](https://github.com/RRD-dev)、[@luoph](https://github.com/luoph)) - 修复输入或输出 schema 使用 transform 时插件 RPC 失败的问题 ([#8550](https://github.com/getpaseo/paseo/pull/8550)) +### 破坏性变更 + +- 移除已弃用且始终返回空列表的 `agent.turn.after.timeline` SDK 字段 ([#9573](https://github.com/getpaseo/paseo/pull/9573),贡献者:[@jtomaszewski](https://github.com/jtomaszewski)) + ### 说明 -- 后台任务、基准分支选择器、归档撤销、后台 Agent、插件订阅和 fx 需要主机和应用都更新到此版本 +- 使用插件库、后台任务、Change base、归档撤销、后台 Agent、插件订阅和 fx 时,请同时更新主机和应用 +- 读取 `agent.turn.after.timeline` 的插件作者必须改用 `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })`,并按 `event.turnId` 筛选条目 +- 归档撤销会恢复工作区,但不会恢复随 worktree 一起移除的未提交文件 ## 0.15.4 - 2026-11-10 diff --git a/fastlane/metadata/android/en-US/changelogs/160001.txt b/fastlane/metadata/android/en-US/changelogs/160001.txt new file mode 100644 index 0000000000..577491d569 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160001.txt @@ -0,0 +1,5 @@ +- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. +- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. +- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/160002.txt b/fastlane/metadata/android/en-US/changelogs/160002.txt new file mode 100644 index 0000000000..577491d569 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160002.txt @@ -0,0 +1,5 @@ +- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. +- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. +- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/160003.txt b/fastlane/metadata/android/en-US/changelogs/160003.txt new file mode 100644 index 0000000000..577491d569 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160003.txt @@ -0,0 +1,5 @@ +- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. +- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. +- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/160004.txt b/fastlane/metadata/android/en-US/changelogs/160004.txt new file mode 100644 index 0000000000..577491d569 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160004.txt @@ -0,0 +1,5 @@ +- Background tasks: See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. +- Built-in plugin gallery: Browse, search and install plugins without leaving Paseo. Manage their settings and updates from the same page. +- Command center tabs: Switch between Workspaces, Files and Actions, with recent workspaces shown first. Search now includes archived workspaces and matches agent titles within their workspace. + +Full notes: https://paseo.sh/changelog diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 22080158c6..68dd307a19 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-e6BNeOJvy1uyDe/XW9hdr7NBgJ+t9tlNum5oLNefREI= +sha256-alhf4ULeJ7n8sfgnxsX8Ugw40GB7jz0u9R/3/MOveIw= diff --git a/package-lock.json b/package-lock.json index fcfe3e0eed..4dbb6d3eb4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.16.0-beta.2", + "version": "0.16.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.16.0-beta.2", + "version": "0.16.0", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37468,7 +37468,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.16.0-beta.2", + "version": "0.16.0", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39637,13 +39637,13 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", - "@getpaseo/server": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/protocol": "0.16.0", + "@getpaseo/server": "0.16.0", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -39890,11 +39890,11 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { - "@getpaseo/protocol": "0.16.0-beta.2", - "@getpaseo/relay": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0", + "@getpaseo/relay": "0.16.0", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -39906,7 +39906,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40149,7 +40149,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40195,7 +40195,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "@codemirror/language": "6.12.4", @@ -40225,7 +40225,7 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", @@ -40233,8 +40233,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/protocol": "0.16.0", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40244,8 +40244,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/protocol": "0.16.0", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40267,7 +40267,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "semver": "^7.8.5", @@ -40295,7 +40295,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "@noble/ciphers": "^2.4.0", @@ -40517,17 +40517,17 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/highlight": "0.16.0-beta.2", - "@getpaseo/plugin": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", - "@getpaseo/relay": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/highlight": "0.16.0", + "@getpaseo/plugin": "0.16.0", + "@getpaseo/protocol": "0.16.0", + "@getpaseo/relay": "0.16.0", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41474,7 +41474,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.16.0-beta.2", + "version": "0.16.0", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43084,7 +43084,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0-beta.2", + "version": "0.16.0", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 3723a8f4ad..1f75dabfe3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.16.0-beta.2", + "version": "0.16.0", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index 62f1f65ba4..7b41060dda 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.16.0-beta.2", + "version": "0.16.0", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index 915581ad32..b930245d22 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Paseo CLI - control your AI coding agents from the command line", "license": "Apache-2.0", "bin": { @@ -29,9 +29,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", - "@getpaseo/server": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/protocol": "0.16.0", + "@getpaseo/server": "0.16.0", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index 862157ccab..79dbeba87f 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Paseo client SDK package", "license": "Apache-2.0", "files": [ @@ -49,8 +49,8 @@ "measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts" }, "dependencies": { - "@getpaseo/protocol": "0.16.0-beta.2", - "@getpaseo/relay": "0.16.0-beta.2", + "@getpaseo/protocol": "0.16.0", + "@getpaseo/relay": "0.16.0", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 20c36da260..13c5853a08 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.16.0-beta.2", + "version": "0.16.0", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 85a6a9313e..48768d5ba9 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 67ad30a5ca..9b86990ee6 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.16.0-beta.2", + "version": "0.16.0", "license": "Apache-2.0", "files": [ "dist", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 97644d8303..89754fa032 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Paseo plugin SDK package", "license": "Apache-2.0", "files": [ @@ -78,8 +78,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/protocol": "0.16.0", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -89,8 +89,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/protocol": "0.16.0", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 4c3738ba21..7b2ac77239 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Paseo shared protocol schemas and wire types", "license": "Apache-2.0", "files": [ diff --git a/packages/relay/package.json b/packages/relay/package.json index 1c8bdf3d6e..34876b8756 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Paseo relay for bridging daemon and client connections", "license": "Apache-2.0", "files": [ diff --git a/packages/server/package.json b/packages/server/package.json index a73beba2fd..58adbd86fa 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.16.0-beta.2", + "version": "0.16.0", "description": "Paseo backend server", "license": "Apache-2.0", "files": [ @@ -109,11 +109,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.246", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0-beta.2", - "@getpaseo/highlight": "0.16.0-beta.2", - "@getpaseo/plugin": "0.16.0-beta.2", - "@getpaseo/protocol": "0.16.0-beta.2", - "@getpaseo/relay": "0.16.0-beta.2", + "@getpaseo/client": "0.16.0", + "@getpaseo/highlight": "0.16.0", + "@getpaseo/plugin": "0.16.0", + "@getpaseo/protocol": "0.16.0", + "@getpaseo/relay": "0.16.0", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 01b96c2cd1..7bdeba45b9 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.16.0-beta.2", + "version": "0.16.0", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index c31af5c7e7..158d533844 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0-beta.2", + "version": "0.16.0", "private": true, "type": "module", "scripts": { From fa8ba1bd3b549845c1936b8c5072e210b0db1ebd Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:46:25 +0000 Subject: [PATCH 108/160] test(terminal): wait for the live worker's socket before reaping (#9835) The reaper signals a worker only after its socket accepts. The two "cannot be opened for a moment" tests spawned a listening worker and reaped without waiting for the listen, so on a loaded runner the reaper found no socket, left the worker alive, and the test failed after waitUntilGone's 5s deadline. Spawn the worker through a helper that resolves once the socket is listening, as the other socket tests in this file already do. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../terminal/terminal-worker-reaper.test.ts | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/server/src/terminal/terminal-worker-reaper.test.ts b/packages/server/src/terminal/terminal-worker-reaper.test.ts index ef8d4fe487..753db72e0a 100644 --- a/packages/server/src/terminal/terminal-worker-reaper.test.ts +++ b/packages/server/src/terminal/terminal-worker-reaper.test.ts @@ -577,20 +577,27 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { // chmod cannot make a file unreadable to root. describe.skipIf(process.getuid?.() === 0)("a record that cannot be opened for a moment", () => { - it("still ends a live worker it names, then retires the record", async () => { - const home = makeHome(); + // The reaper signals a worker only once its socket accepts, so wait for the listen. + async function spawnListeningWorker(socketPath: string): Promise { const worker = spawn( process.execPath, [ "-e", - `require("node:net").createServer(() => {}).listen(${JSON.stringify(path.join(home, "live-record-under-test.sock"))});setInterval(() => {}, 1e9)`, + `require("node:net").createServer(() => {}).listen(${JSON.stringify(socketPath)}, () => process.stdout.write("listening\\n"));setInterval(() => {}, 1e9)`, "--", "--paseo-terminal-worker", "record-under-test", ], - { detached: true, stdio: "ignore" }, + { detached: true, stdio: ["ignore", "pipe", "ignore"] }, ); children.push(worker); + await new Promise((resolve) => worker.stdout!.once("data", resolve)); + return worker; + } + + it("still ends a live worker it names, then retires the record", async () => { + const home = makeHome(); + const worker = await spawnListeningWorker(path.join(home, "live-record-under-test.sock")); const recordPath = writeRecord(home, { pid: worker.pid!, socketPath: path.join(home, "live-record-under-test.sock"), @@ -632,18 +639,7 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => { it("still reports a record that stays unreadable, and signals nothing it names", async () => { const home = makeHome(); - const worker = spawn( - process.execPath, - [ - "-e", - `require("node:net").createServer(() => {}).listen(${JSON.stringify(path.join(home, "live-record-under-test.sock"))});setInterval(() => {}, 1e9)`, - "--", - "--paseo-terminal-worker", - "record-under-test", - ], - { detached: true, stdio: "ignore" }, - ); - children.push(worker); + const worker = await spawnListeningWorker(path.join(home, "live-record-under-test.sock")); const recordPath = writeRecord(home, { pid: worker.pid!, socketPath: path.join(home, "live-record-under-test.sock"), From e19980a6c9ca04bea95ee286ac87c55c9d1ef8a3 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 15:06:24 +0700 Subject: [PATCH 109/160] Dismiss chat errors and identify timed-out requests (#9837) * fix(app): dismiss chat errors and identify timed-out requests * test(client): assert subscription timeout codes * refactor(app): keep toast errors on the existing string boundary * test(app): remove redundant toast duration coverage --- packages/app/src/panels/agent-panel.tsx | 2 +- packages/client/src/connection.test.ts | 2 +- packages/client/src/daemon-client.test.ts | 62 ++++++++++++++++++----- packages/client/src/daemon-client.ts | 7 ++- 4 files changed, 57 insertions(+), 16 deletions(-) diff --git a/packages/app/src/panels/agent-panel.tsx b/packages/app/src/panels/agent-panel.tsx index cf582a99f5..709281ed7d 100644 --- a/packages/app/src/panels/agent-panel.tsx +++ b/packages/app/src/panels/agent-panel.tsx @@ -762,7 +762,7 @@ function ChatAgentContent({ }); const reportAttentionError = useCallback( (error: unknown) => { - toastApi.show(String(error), { variant: "error", durationMs: null }); + toastApi.error(toErrorMessage(error)); }, [toastApi], ); diff --git a/packages/client/src/connection.test.ts b/packages/client/src/connection.test.ts index ef326bf516..50622779e8 100644 --- a/packages/client/src/connection.test.ts +++ b/packages/client/src/connection.test.ts @@ -449,7 +449,7 @@ test("a timed-out subscription rejects and cannot replay on reconnect", async () h.open(); await connecting; const observation = h.client.observeAgents({ timeout: 10 }); - await expect(observation.ready).rejects.toThrow(/timed out|timeout/i); + await expect(observation.ready).rejects.toMatchObject({ code: "DAEMON_REQUEST_TIMEOUT" }); await observation.release(); const reconnecting = h.client.connect(); h.open(); diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 057e6550c8..af1f2edd1f 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1492,7 +1492,7 @@ test("keeps the transport connected when a session RPC ping times out", async () await connectPromise; expect(client.getConnectionState().status).toBe("connected"); - await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("Timeout waiting for message"); + await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("No response to ping after"); expect(client.getConnectionState().status).toBe("connected"); }); @@ -1541,7 +1541,9 @@ test("bounds the wait for push token revocation", async () => { await connectPromise; const revocation = client.unregisterPushToken("ExponentPushToken[test-device]"); - const rejection = expect(revocation).rejects.toThrow("Timeout waiting for message (2000ms)"); + const rejection = expect(revocation).rejects.toThrow( + "No response to push.unregister.request after 2000ms", + ); await vi.advanceTimersByTimeAsync(1_999); expect(client.getConnectionState().status).toBe("connected"); @@ -1550,6 +1552,30 @@ test("bounds the wait for push token revocation", async () => { expect(client.getConnectionState().status).toBe("connected"); }); +test("identifies the request when marking an agent as read times out", async () => { + useHeartbeatClock(); + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "clsk_attention_timeout", + reconnect: { enabled: false }, + transportFactory: () => transport.transport, + }); + clients.push(client); + const connected = client.connect(); + transport.triggerOpen(); + await connected; + + const outcome = client.clearAgentAttention("agent-1").catch((error: unknown) => error); + await vi.advanceTimersByTimeAsync(60_000); + expect(await outcome).toMatchObject({ + name: "DaemonConnectionError", + code: "DAEMON_REQUEST_TIMEOUT", + message: "No response to clear_agent_attention after 60000ms", + }); + expect(client.isConnected).toBe(true); +}); + test("defaults session RPC waiters to sixty seconds", async () => { useHeartbeatClock(); const logger = createMockLogger(); @@ -1594,7 +1620,7 @@ test("defaults session RPC waiters to sixty seconds", async () => { expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (60000ms)"); + await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms"); }); test("honors explicit fetchAgent timeout below the session RPC default", async () => { @@ -1642,7 +1668,7 @@ test("honors explicit fetchAgent timeout below the session RPC default", async ( expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (5000ms)"); + await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 5000ms"); }); test("preserves legacy fetchAgent id overload", async () => { @@ -1806,7 +1832,9 @@ test("honors explicit fetchAgentTimeline timeout below the session RPC default", expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (2000ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to fetch_agent_timeline_request after 2000ms", + ); }); test("lists the full agent prompt index", async () => { @@ -1899,7 +1927,7 @@ test("honors explicit fetchAgents timeout below the session RPC default", async expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1200ms)"); + await expect(responsePromise).rejects.toThrow("No response to fetch_agents_request after 1200ms"); }); test("honors explicit shutdownServer timeout below the session RPC default", async () => { @@ -1945,7 +1973,9 @@ test("honors explicit shutdownServer timeout below the session RPC default", asy expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to shutdown_server_request after 1500ms", + ); }); test("honors explicit getDaemonStatus timeout below the session RPC default", async () => { @@ -1991,7 +2021,9 @@ test("honors explicit getDaemonStatus timeout below the session RPC default", as expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to daemon.get_status.request after 1500ms", + ); }); test("honors explicit getDaemonPairingOffer timeout below the session RPC default", async () => { @@ -2037,7 +2069,9 @@ test("honors explicit getDaemonPairingOffer timeout below the session RPC defaul expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)"); + await expect(responsePromise).rejects.toThrow( + "No response to daemon.get_pairing_offer.request after 1500ms", + ); }); test("gates config reload on the daemon capability", async () => { @@ -2443,7 +2477,9 @@ test("keeps enable and disable inside the session RPC deadline", async () => { expect(settled).toBe(false); await vi.advanceTimersByTimeAsync(1); - await expect(pending).rejects.toThrow("Timeout waiting for message (60000ms)"); + await expect(pending).rejects.toThrow( + `No response to plugin.${action}.request after 60000ms`, + ); } } finally { vi.useRealTimers(); @@ -8619,7 +8655,9 @@ test("usage request timeout detaches its update listener", async () => { const result = client.listUsageReports({ requestId: "timeout-usage" }, (report) => updates.push(report), ); - const rejected = expect(result).rejects.toThrow("Timeout waiting for message (60000ms)"); + const rejected = expect(result).rejects.toThrow( + "No response to usage.list_reports.request after 60000ms", + ); await vi.advanceTimersByTimeAsync(60_001); await rejected; mock.triggerMessage( @@ -9403,7 +9441,7 @@ test("RPC deadlines remain active while a preceding frame waits for drain", asyn blocked = true; const first = client.sendHostFrame("route", new Uint8Array([1])); try { - await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("Timeout waiting for message"); + await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("No response to ping after"); expect(client.isConnected).toBe(true); } finally { drain(); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 6ab5e64f32..7843e59e60 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -1023,6 +1023,7 @@ interface WaitHandle { interface WaitOptions { skipQueue?: boolean; requestId?: string; + requestType?: SessionInboundMessage["type"]; } interface CorrelatedResponseIdentity { @@ -2359,7 +2360,7 @@ export class DaemonClient { return { kind: "ok", value }; }, timeout, - { ...params.options, requestId: params.requestId }, + { ...params.options, requestId: params.requestId, requestType: params.message.type }, ); // The response deadline still applies while the transport waits for drain. @@ -8107,7 +8108,9 @@ export class DaemonClient { ): WaitHandle { // Capture stack trace at call site, not inside setTimeout const timeoutError = new DaemonConnectionError( - `Timeout waiting for message (${timeout}ms)`, + options?.requestType + ? `No response to ${options.requestType} after ${timeout}ms` + : `Timeout waiting for message (${timeout}ms)`, "DAEMON_REQUEST_TIMEOUT", ); From 41c294c7855f3d864337b8628513bf00ece0a644 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 16:02:47 +0700 Subject: [PATCH 110/160] Queue agent messages until the current turn ends (#9757) * fix(server): queue agent messages until the current turn ends Steering refusal could replace a running turn and cancel compaction. Hold agent-originated messages and notifications together until the recipient settles, retaining explicit interruption and acknowledging finish subscriptions only after dispatch succeeds. * fix(server): wake queued delivery at turn and permission checkpoints A pending follow-up must not hide the permission needed to finish the current turn. Wake ready batches on recipient state changes, let completion waits report permission checkpoints, and preserve admission order and session-mode boundaries when busy dispatches retry. * fix(server): publish autonomous readiness after run settlement Idle snapshots emitted while the autonomous run record still existed could not wake queued delivery. Publish terminal state after clearing that run, and keep already debounced busy retries ready for the next turn boundary. * fix(server): apply queued modes only after run admission Preparing a later mode group could change the running turn before busy admission rejected it. Carry the requested mode into the reserved run and apply it immediately before provider startup, leaving earlier and concurrently started turns untouched. * fix(server): keep later mode groups queued until turn end Dispatching every mode group at once prepared later modes against the preceding turn. Keep later groups pending and reject busy sends before changing mode, leaving mode validation outside run startup. * fix(server): deliver provider commands during queued turns Offer waiting messages individually through the provider-owned out-of-band path while a recipient runs. Recognized commands retain their existing behavior, while ordinary messages keep waiting without starting their dispatch observers. * fix(server): offer queued commands once while running Remember provider declines so timer retries do not repeat side effects or reinterpret a waiting message after provider state changes. * fix(server): defer commands that request a session mode An explicit mode belongs to a later turn. Keep those commands on the normal idle dispatch path so an out-of-band offer cannot ignore the requested mode or change the running turn. --- docs/agent-lifecycle.md | 5 +- packages/cli/src/commands/agent/send.ts | 4 +- packages/client/src/daemon-client.ts | 2 +- .../src/server/agent/agent-manager.test.ts | 266 ++++++++- .../server/src/server/agent/agent-manager.ts | 16 +- .../agent/agent-messages/delivery.test.ts | 554 +++++++++++++++++- .../server/agent/agent-messages/delivery.ts | 216 ++++++- .../server/src/server/agent/agent-prompt.ts | 17 +- .../finish-subscriptions.test.ts | 23 + .../agent/finish-subscriptions/index.ts | 4 +- .../src/server/agent/host-operations/index.ts | 2 +- .../src/server/agent/mcp-server.test.ts | 293 ++++----- .../src/server/agent/tools/paseo-tools.ts | 8 +- .../peer-message-permissions.test.ts | 2 +- .../src/server/test-utils/agent-messages.ts | 29 +- .../server/src/server/websocket-server.ts | 18 +- skills/paseo/SKILL.md | 2 +- 17 files changed, 1253 insertions(+), 208 deletions(-) diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index dea6c68255..d5eeed4d5c 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -150,12 +150,13 @@ Users can also detach an existing subagent from the subagents track. Detach is d `notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback. -Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches. +Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches. The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued -admission within their original timeout and cancellation scope. +admission within their original timeout and cancellation scope, and return permission checkpoints +while messages are waiting. Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses diff --git a/packages/cli/src/commands/agent/send.ts b/packages/cli/src/commands/agent/send.ts index acdea38507..9a0bc465b7 100644 --- a/packages/cli/src/commands/agent/send.ts +++ b/packages/cli/src/commands/agent/send.ts @@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command { .addOption( new Option( "--behavior ", - "Active-turn behavior (agent default: steer; otherwise: interrupt)", + "Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)", ).choices(["interrupt", "steer"]), ) .option("--no-wait", "Return immediately without waiting for completion"); @@ -218,7 +218,7 @@ export async function runSendCommand( status: receipt.deliveryStatus ?? "sent", message: receipt.deliveryStatus === "queued" - ? "Message queued for delivery after two quiet seconds" + ? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested" : "Message sent, not waiting for completion", }, schema: agentSendSchema, diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 7843e59e60..e677fbe3b0 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -483,7 +483,7 @@ export interface SendMessageOptions { sourceAgentServerId?: string; sessionMode?: string; messageId?: string; - /** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */ + /** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */ activeTurnBehavior?: ActiveTurnBehavior; images?: Array<{ data: string; mimeType: string }>; attachments?: SendAgentMessageRequest["attachments"]; diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 4c592d5387..a27ad9013e 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -26,7 +26,8 @@ import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js" import type { ProviderOptions } from "@getpaseo/protocol/agent-types"; import { projectTimelineRows } from "./timeline-projection.js"; import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; -import { startAgentRun } from "./agent-prompt.js"; +import { createAgentMessageDelivery } from "./agent-messages/index.js"; +import { AgentTurnBusyError, sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js"; import { StaleProviderSessionError } from "./stale-provider-session-error.js"; import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js"; import type { StoredAgentRecord } from "./agent-storage.js"; @@ -12345,11 +12346,18 @@ test("authoritative timeline records a daemon-handled submitted prompt before it test("tryRunOutOfBand gives providers the command another agent sent, not its envelope", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-agent-out-of-band-")); const seenPrompts: AgentPromptInput[] = []; + const acceptanceOrder: string[] = []; class SlashCommandSession extends TestAgentSession { override tryHandleOutOfBand(prompt: AgentPromptInput) { seenPrompts.push(prompt); - return prompt === "/handled" ? { run: async () => {} } : null; + return prompt === "/handled" + ? { + run: async () => { + acceptanceOrder.push("run"); + }, + } + : null; } } const client = new (class extends TestAgentClient { @@ -12364,12 +12372,22 @@ test("tryRunOutOfBand gives providers the command another agent sent, not its en try { const fromAgent = prepareAgentMessage("/handled", { kind: "agent-message", agentId: "sender" }); - expect(await manager.tryRunOutOfBand(agent.id, fromAgent.prompt)).toBe(true); + expect( + await manager.tryRunOutOfBand(agent.id, fromAgent.prompt, undefined, () => { + acceptanceOrder.push("accepted"); + }), + ).toBe(true); + await vi.waitFor(() => expect(acceptanceOrder).toEqual(["accepted", "run"])); expect(seenPrompts).toEqual(["/handled"]); // A human who pastes an envelope gets it quoted, and it stays a plain prompt. const pasted = prepareAgentMessage(String(fromAgent.prompt)); - expect(await manager.tryRunOutOfBand(agent.id, pasted.prompt)).toBe(false); + expect( + await manager.tryRunOutOfBand(agent.id, pasted.prompt, undefined, () => { + acceptanceOrder.push("unexpected"); + }), + ).toBe(false); + expect(acceptanceOrder).toEqual(["accepted", "run"]); expect(seenPrompts.at(-1)).toBe(pasted.prompt); } finally { await manager.closeAgent(agent.id); @@ -14568,3 +14586,243 @@ test("idle cleanup gives a newly restored runtime a fresh idle window while keep expect((await h.sweep({ now: h.later(61) })).collected).toHaveLength(1); expect(h.closes).toBe(closesBeforeRestore + 1); }); + +test.each([ + ["supported", "turn_completed"], + ["supported", "turn_canceled"], + ["supported", "turn_failed"], + ["unsupported", "turn_completed"], + ["unsupported", "turn_canceled"], + ["unsupported", "turn_failed"], +] as const)( + "queued delivery after %s provider %s never steers or interrupts", + async (support, ending) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-queued-terminal-")); + const session = + support === "supported" + ? new SteeringTestSession({ provider: "codex", cwd: workdir }) + : new UnsupportedSteeringSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ clients: { codex: client }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + let tick = () => {}; + const delivery = createAgentMessageDelivery({ + isRunning: (id) => manager.hasInFlightRun(id), + subscribe: (notify) => + manager.subscribe( + (event) => { + if (event.type === "agent_state") notify(event.agent.id); + }, + { replayState: false }, + ), + schedule: (_delay, callback) => { + tick = callback; + return () => {}; + }, + dispatch: async (request) => + ( + await startAgentRun(manager, agent.id, request.prompt, logger, { + idleOnly: request.idleOnly, + replaceRunning: true, + activeTurnBehavior: request.activeTurnBehavior, + }) + ).disposition, + onError: (error) => { + throw error; + }, + }); + const providerStarted = new Promise((resolve) => { + const unsubscribe = session.subscribe((event) => { + if (event.type === "turn_started") { + unsubscribe(); + resolve(); + } + }); + }); + try { + await startAgentRun(manager, agent.id, "original", logger); + await manager.waitForAgentRunStart(agent.id); + const receipt = delivery.enqueue({ + recipientId: agent.id, + prompt: "queued", + source: { kind: "agent-message", agentId: "child" }, + }); + tick(); + expect(session.startCount).toBe(1); + expect(session.interruptCount).toBe(0); + const turnId = support === "supported" ? "active-turn-1" : "unsupported-turn-1"; + await providerStarted; + session.pushEvent({ + type: ending, + provider: "codex", + turnId, + ...(ending === "turn_failed" ? { error: "test failure" } : {}), + } as AgentStreamEvent); + await receipt.dispatched; + await manager.waitForAgentRunStart(agent.id); + expect(session.startCount).toBe(2); + expect(session.interruptCount).toBe(0); + } finally { + await delivery.close(); + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)( + "an autonomous %s publishes readiness after settling its run", + async (ending) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-autonomous-delivery-")); + const session = new SteeringTestSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ clients: { codex: client }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + let tick = () => {}; + const settledStates: boolean[] = []; + const delivery = createAgentMessageDelivery({ + isRunning: (id) => manager.hasInFlightRun(id), + subscribe: (notify) => + manager.subscribe( + (event) => { + if (event.type !== "agent_state") return; + if (event.agent.lifecycle !== "running") + settledStates.push(manager.hasInFlightRun(agent.id)); + notify(event.agent.id); + }, + { agentId: agent.id, replayState: false }, + ), + schedule: (_delay, callback) => { + tick = callback; + return () => {}; + }, + dispatch: async (request) => + ( + await startAgentRun(manager, agent.id, request.prompt, logger, { + idleOnly: request.idleOnly, + }) + ).disposition, + onError: (error) => { + throw error; + }, + }); + try { + session.pushEvent({ type: "turn_started", provider: "codex", turnId: "autonomous" }); + await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true)); + delivery.enqueue({ + recipientId: agent.id, + prompt: "queued report", + source: { kind: "agent-message", agentId: "child" }, + }); + tick(); + expect(session.startCount).toBe(0); + session.pushEvent({ + type: ending, + provider: "codex", + turnId: "autonomous", + ...(ending === "turn_failed" ? { error: "test failure" } : {}), + } as AgentStreamEvent); + await new Promise((resolve) => setImmediate(resolve)); + expect(settledStates).toEqual([false]); + expect(session.startCount).toBe(1); + } finally { + await delivery.close(); + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test("an idle-only prompt rejects a busy recipient before changing its mode", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-queued-mode-")); + class ModeSession extends SteeringTestSession { + mode = "plan"; + applied: string[] = []; + startedModes: string[] = []; + override async setMode(mode?: string) { + if (!mode) throw new Error("Mode required"); + this.mode = mode; + this.applied.push(mode); + } + override async getCurrentMode() { + return this.mode; + } + override async startTurn(prompt: AgentPromptInput) { + this.startedModes.push(this.mode); + return super.startTurn(prompt); + } + } + const session = new ModeSession({ provider: "codex", cwd: workdir }); + const client = new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + await manager.setAgentMode(agent.id, "plan"); + session.applied.length = 0; + const providerStarted = new Promise((resolve) => { + const unsubscribe = session.subscribe((event) => { + if (event.type === "turn_started") { + unsubscribe(); + resolve(); + } + }); + }); + const startOther = async () => { + await startAgentRun(manager, agent.id, "other turn", logger); + await manager.waitForAgentRunStart(agent.id); + }; + try { + await startOther(); + await expect( + sendPreparedPromptToAgent({ + agentManager: manager, + agentStorage: storage, + agentId: agent.id, + prompt: "queued follow-up", + sessionMode: "full-access", + idleOnly: true, + logger, + }), + ).rejects.toBeInstanceOf(AgentTurnBusyError); + expect(session.mode).toBe("plan"); + expect(session.applied).toEqual([]); + expect(session.startedModes).toEqual(["plan"]); + await providerStarted; + session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" }); + await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false)); + await sendPreparedPromptToAgent({ + agentManager: manager, + agentStorage: storage, + agentId: agent.id, + prompt: "queued follow-up", + sessionMode: "full-access", + idleOnly: true, + logger, + }); + await manager.waitForAgentRunStart(agent.id); + expect(session.mode).toBe("full-access"); + expect(session.applied).toEqual(["full-access"]); + expect(session.startedModes).toEqual(["plan", "full-access"]); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 81d25be675..096bd3aa65 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -1117,6 +1117,10 @@ export class AgentManager { return new Date(nextMs).toISOString(); } + hasPendingPermissions(agentId: string): boolean { + return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0; + } + hasInFlightRun(agentId: string): boolean { const agent = this.agents.get(agentId); if (!agent) { @@ -3030,6 +3034,7 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + onAccepted?: () => void, ): Promise { if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) { await this.waitForAgentClose(agentId); @@ -3049,6 +3054,7 @@ export class AgentManager { if (!handler) { return false; } + onAccepted?.(); this.touchUpdatedAt(agent); if (options?.clientMessageId) { this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted"); @@ -5121,6 +5127,9 @@ export class AgentManager { this.runs.settleTerminalRun(agent.id, eventTurnId); if (isForegroundEvent) { this.finalizeForegroundTurn(agent, eventTurnId); + } else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) { + // Publish autonomous readiness only after the tracked run has settled. + this.emitState(agent); } } @@ -5390,7 +5399,6 @@ export class AgentManager { !agent.pendingReplacement ) { (agent as ActiveManagedAgent).lifecycle = "idle"; - this.emitState(agent); } void this.refreshRuntimeInfo(agent); } @@ -5431,9 +5439,6 @@ export class AgentManager { options, ); this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed"); - if (!isForegroundEvent && !agent.activeForegroundTurnId) { - this.emitState(agent); - } } private onStreamTurnCanceled(params: { @@ -5467,9 +5472,6 @@ export class AgentManager { } agent.lastError = undefined; this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted"); - if (!isForegroundEvent && !agent.activeForegroundTurnId) { - this.emitState(agent); - } } private onStreamTurnStarted(params: { diff --git a/packages/server/src/server/agent/agent-messages/delivery.test.ts b/packages/server/src/server/agent/agent-messages/delivery.test.ts index bbe3d4fb3d..0225bc2435 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.test.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.test.ts @@ -1,3 +1,4 @@ +import { AgentTurnBusyError } from "../agent-prompt.js"; import { expect, test } from "vitest"; import { createAgentMessageDelivery, parseAgentMessages } from "./index.js"; import type { AgentPromptInput } from "../agent-sdk-types.js"; @@ -117,7 +118,6 @@ test("explicit interrupt and conflicting session modes retain ordered dispatch b const delivery = createAgentMessageDelivery({ dispatch: async (request) => { sent.push(request); - request.onDispatch("steered"); return "steered"; }, onError: (error) => { @@ -313,3 +313,555 @@ test("runtime safety sees queued messages until provider dispatch settles", asyn await delivery.close(); expect(delivery.hasPending("parent")).toBe(false); }); + +test("messages wait across quiet windows and batch after the recipient turn ends", async () => { + const clock = createClock(); + let running = true; + const sent: Array = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + dispatch: async (request) => { + sent.push(request.messageIds); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const source = { kind: "agent-message" as const, agentId: "child" }; + const report = delivery.enqueue({ + recipientId: "parent", + messageId: "report", + source, + prompt: "report", + }); + clock.advance(2000); + await Promise.resolve(); + expect(sent).toEqual([]); + clock.advance(13000); + const finish = delivery.enqueue({ + recipientId: "parent", + messageId: "finish", + source: { kind: "agent-notification", agentId: "child", event: "finished" }, + prompt: "finished", + activeTurnBehavior: "steer", + }); + clock.advance(2000); + await Promise.resolve(); + expect(sent).toEqual([]); + running = false; + clock.advance(2000); + await Promise.all([report.dispatched, finish.dispatched]); + expect(sent).toEqual([["report", "finish"]]); + await delivery.close(); +}); + +test("a turn starting during dispatch preparation keeps receipts queued and joins later arrivals", async () => { + const clock = createClock(); + let busy = true; + const sent: Array = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + dispatch: async (request) => { + if (busy) throw new AgentTurnBusyError("concurrent turn"); + sent.push(request.messageIds); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "report", + }; + const first = delivery.enqueue({ ...message, messageId: "first" }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + expect(delivery.hasPending("parent")).toBe(true); + const second = delivery.enqueue({ ...message, messageId: "second" }); + busy = false; + clock.advance(2000); + await Promise.all([first.dispatched, second.dispatched]); + expect(sent).toEqual([["first", "second"]]); + await delivery.close(); +}); + +test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => { + const clock = createClock(); + const sent: Array = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + dispatch: async (request) => { + sent.push(request.messageIds); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "report", + }; + delivery.enqueue({ ...message, messageId: "wait" }); + const interrupt = delivery.enqueue({ + ...message, + messageId: "interrupt", + activeTurnBehavior: "interrupt", + }); + clock.advance(2000); + await interrupt.dispatched; + expect(sent).toEqual([["interrupt"]]); + expect(delivery.hasPending("parent")).toBe(true); + await delivery.close(); + expect(sent).toEqual([["interrupt"], ["wait"]]); +}); + +test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => { + const clock = createClock(); + let release!: () => void; + const preparing = new Promise((resolve) => { + release = resolve; + }); + const modes: boolean[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + dispatch: async (request) => { + modes.push(request.idleOnly); + if (request.idleOnly) { + await preparing; + throw new AgentTurnBusyError("busy"); + } + return "turn_started"; + }, + onError: () => {}, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "report", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + const closing = delivery.close(); + release(); + await closing; + await expect(receipt.dispatched).resolves.toBe("turn_started"); + expect(modes).toEqual([true, false]); +}); + +test("conflicting modes dispatch on separate turn ends without changing the active turn mode", async () => { + const clock = createClock(); + let busy = false; + let mode = "initial"; + let wake!: (recipientId: string) => void; + const sent: Array<{ ids: readonly string[]; mode?: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => busy, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + dispatch: async (request) => { + // Mode preparation precedes run admission in the real dispatcher. + mode = request.sessionMode ?? mode; + if (busy) throw new AgentTurnBusyError("concurrent turn"); + sent.push({ ids: request.messageIds, mode }); + busy = true; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "message", + }; + const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" }); + const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" }); + clock.advance(2000); + await a.dispatched; + await new Promise((resolve) => setImmediate(resolve)); + expect(mode).toBe("plan"); + expect(sent).toEqual([{ ids: ["A"], mode: "plan" }]); + busy = false; + wake("parent"); + await b.dispatched; + expect(mode).toBe("default"); + expect(sent).toEqual([ + { ids: ["A"], mode: "plan" }, + { ids: ["B"], mode: "default" }, + ]); + await delivery.close(); +}); + +test("interrupts retain separate mode choices while the recipient is busy", async () => { + const clock = createClock(); + const sent: Array<{ ids: readonly string[]; mode?: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + dispatch: async (request) => { + sent.push({ ids: request.messageIds, mode: request.sessionMode }); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + prompt: "message", + activeTurnBehavior: "interrupt" as const, + }; + const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" }); + const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" }); + clock.advance(2000); + await Promise.all([a.dispatched, b.dispatched]); + expect(sent).toEqual([ + { ids: ["A"], mode: "plan" }, + { ids: ["B"], mode: "default" }, + ]); + await delivery.close(); +}); + +test("a settled-turn event releases a ready batch without waiting for the next timer sample", async () => { + const clock = createClock(); + let running = true; + let settled: (id: string) => void = () => {}; + let subscribed = true; + const sent: string[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + settled = listener; + return () => { + subscribed = false; + }; + }, + dispatch: async (request) => { + sent.push(request.recipientId); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + delivery.enqueue({ + recipientId: "parent", + prompt: "report", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + expect(sent).toEqual([]); + running = false; + settled("parent"); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent).toEqual(["parent"]); + running = true; + await delivery.close(); + expect(subscribed).toBe(false); +}); + +test.each([false, true])( + "completion waits report permission checkpoints without draining messages (initial: %s)", + async (initial) => { + const clock = createClock(); + let permission = initial; + let changed: (id: string) => void = () => {}; + let reported = false; + let sent = 0; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + hasPendingPermission: () => permission, + subscribe: (listener) => { + changed = listener; + return () => {}; + }, + dispatch: async () => { + sent++; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + delivery.enqueue({ + recipientId: "child", + prompt: "follow up", + source: { kind: "agent-message", agentId: "parent" }, + }); + const wait = delivery.waitForDispatch("child", new AbortController().signal).then(() => { + reported = true; + return undefined; + }); + permission = true; + changed("child"); + await new Promise((resolve) => setImmediate(resolve)); + expect(reported).toBe(true); + expect(sent).toBe(0); + expect(delivery.hasPending("child")).toBe(true); + await wait; + await delivery.close(); + }, +); + +test("a busy admission retry stays ready for the next settled-turn event", async () => { + const clock = createClock(); + let running = false; + let raced = true; + let notify: (id: string) => void = () => {}; + const sent: string[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + notify = listener; + return () => {}; + }, + dispatch: async (request) => { + if (raced) { + running = true; + throw new AgentTurnBusyError("next turn started"); + } + sent.push(request.recipientId); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + delivery.enqueue({ + recipientId: "parent", + prompt: "report", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + raced = false; + running = false; + notify("parent"); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent).toEqual(["parent"]); + await delivery.close(); +}); + +test("out-of-band acceptance owns callbacks and receipts; a failed attempt does not block waiting messages", async () => { + const clock = createClock(); + let running = true; + let wake!: (recipientId: string) => void; + const callbacks: string[] = []; + const sent: string[] = []; + const errors: unknown[] = []; + const failure = new Error("recipient could not load"); + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + tryRunOutOfBand: async (request, onAccepted) => { + const text = parseAgentMessages(String(request.prompt))[0]!.text; + if (text === "failure") throw failure; + if (text !== "/handled") return false; + onAccepted(); + callbacks.push("command ran"); + return true; + }, + dispatch: async (request) => { + sent.push(...parseAgentMessages(String(request.prompt)).map((message) => message.text)); + return "turn_started"; + }, + onError: (error) => { + errors.push(error); + }, + }); + const message = { + recipientId: "parent", + source: { kind: "agent-message" as const, agentId: "child" }, + }; + const ordinary = delivery.enqueue({ + ...message, + prompt: "ordinary", + beforeDispatch: () => { + callbacks.push("ordinary"); + }, + }); + const failed = delivery.enqueue({ + ...message, + prompt: "failure", + beforeDispatch: () => { + callbacks.push("failure"); + }, + }); + const command = delivery.enqueue({ + ...message, + prompt: "/handled", + beforeDispatch: () => { + callbacks.push("command accepted"); + }, + onDispatch: (disposition) => { + callbacks.push(disposition); + }, + }); + clock.advance(2000); + await expect(failed.dispatched).rejects.toBe(failure); + await expect(command.dispatched).resolves.toBe("out_of_band"); + expect(errors).toEqual([failure]); + expect(callbacks).toEqual(["command accepted", "command ran", "out_of_band"]); + expect(sent).toEqual([]); + running = false; + wake("parent"); + await ordinary.dispatched; + expect(callbacks.at(-1)).toBe("ordinary"); + expect(sent).toEqual(["ordinary"]); + await delivery.close(); +}); + +test("shutdown waits for an in-flight out-of-band attempt and drains its unhandled message", async () => { + const clock = createClock(); + let release!: () => void; + let attempted!: () => void; + const started = new Promise((resolve) => { + attempted = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const dispatched: boolean[] = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => true, + tryRunOutOfBand: async () => { + attempted(); + await gate; + return false; + }, + dispatch: async (request) => { + dispatched.push(request.idleOnly); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "ordinary", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await started; + const closing = delivery.close(); + release(); + await closing; + await expect(receipt.dispatched).resolves.toBe("turn_started"); + expect(dispatched).toEqual([false]); +}); + +test("a declined out-of-band message is offered once across running-turn retries", async () => { + const clock = createClock(); + let running = true; + let accepts = false; + let offers = 0; + let dispatched = 0; + let wake!: (recipientId: string) => void; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + tryRunOutOfBand: async (_request, onAccepted) => { + offers++; + if (accepts) onAccepted(); + return accepts; + }, + dispatch: async () => { + dispatched++; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "message", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + expect(offers).toBe(1); + // A later provider state change does not reinterpret a declined message. + accepts = true; + for (let retry = 0; retry < 3; retry++) { + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + } + expect(offers).toBe(1); + expect(dispatched).toBe(0); + running = false; + wake("parent"); + await receipt.dispatched; + expect(dispatched).toBe(1); + await delivery.close(); +}); + +test("a command with an explicit mode waits for turn end without an out-of-band offer", async () => { + const clock = createClock(); + let running = true; + let offers = 0; + let wake!: (recipientId: string) => void; + const dispatched: Array<{ prompt: AgentPromptInput; sessionMode?: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + wake = listener; + return () => {}; + }, + tryRunOutOfBand: async (_request, onAccepted) => { + offers++; + onAccepted(); + return true; + }, + dispatch: async (request) => { + dispatched.push(request); + return "out_of_band"; + }, + onError: (error) => { + throw error; + }, + }); + const receipt = delivery.enqueue({ + recipientId: "parent", + prompt: "/handled", + sessionMode: "plan", + source: { kind: "agent-message", agentId: "child" }, + }); + clock.advance(2000); + await new Promise((resolve) => setImmediate(resolve)); + expect(offers).toBe(0); + expect(dispatched).toEqual([]); + running = false; + wake("parent"); + await receipt.dispatched; + expect(dispatched).toHaveLength(1); + expect(dispatched[0]!.sessionMode).toBe("plan"); + expect(parseAgentMessages(String(dispatched[0]!.prompt))![0]!.text).toBe("/handled"); + await delivery.close(); +}); diff --git a/packages/server/src/server/agent/agent-messages/delivery.ts b/packages/server/src/server/agent/agent-messages/delivery.ts index f26d83ec50..2852b7f04b 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.ts @@ -1,4 +1,4 @@ -import type { PromptDispatchDisposition } from "../agent-prompt.js"; +import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js"; import { randomUUID } from "node:crypto"; import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js"; import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js"; @@ -21,6 +21,8 @@ interface Receipt { dispatched: Promise; } interface Admitted extends Message { + sequence: number; + outOfBandDeclined: boolean; receipt: Receipt; resolve(disposition: PromptDispatchDisposition): void; reject(error: unknown): void; @@ -30,12 +32,18 @@ interface DispatchRequest { messageIds: readonly string[]; prompt: AgentPromptInput; activeTurnBehavior: "steer" | "interrupt"; + idleOnly: boolean; sessionMode?: string; clearPendingPermissions: boolean; unarchive: boolean; - onDispatch(disposition: PromptDispatchDisposition): void; } interface Dependencies { + /** Includes admitted starts and provider turns, including compaction. */ + isRunning?: (recipientId: string) => boolean; + hasPendingPermission?: (recipientId: string) => boolean; + /** Notify when recipient state changes; admission still checks whether it is idle. */ + subscribe?: (listener: (recipientId: string) => void) => () => void; + tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise; dispatch(request: DispatchRequest): Promise; onError(error: unknown, request: DispatchRequest): void; /** Return a cancellation function. Production uses the daemon's event loop. */ @@ -47,7 +55,7 @@ export interface AgentMessageDelivery { hasPending(recipientId: string): boolean; /** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */ close(): Promise; - /** Existing completion waits include agent messages admitted before the wait. */ + /** Completion waits include admitted messages, but return at permission checkpoints. */ waitForDispatch(recipientId: string, signal: AbortSignal): Promise; } @@ -59,12 +67,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes const timer = setTimeout(callback, delayMs); return () => clearTimeout(timer); }); - const pending = new Map(); + const pending = new Map(); const dispatching = new Map>(); + const receipts = new Map>(); + let sequence = 0; let closed = false; let closing: Promise | undefined; - function dispatch(recipientId: string, messages: Admitted[]): void { + function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest { const prompts = messages.map( (message) => prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt, @@ -74,39 +84,55 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes : prompts.flatMap((entry): AgentPromptContentBlock[] => typeof entry === "string" ? [{ type: "text", text: entry }] : entry, ); - const request: DispatchRequest = { + return { recipientId, + idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt", messageIds: messages.map((message) => message.receipt.messageId), prompt, activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer", sessionMode: messages.find((message) => message.sessionMode)?.sessionMode, clearPendingPermissions: messages.some((message) => message.clearPendingPermissions), unarchive: messages.some((message) => message.unarchive !== false), - onDispatch: (disposition) => { + }; + } + + function dispatch(recipientId: string, messages: Admitted[]): void { + const request = requestFor(recipientId, messages); + queueDispatch(recipientId, async () => { + try { + for (const message of messages) message.beforeDispatch?.(); + let disposition: PromptDispatchDisposition; + try { + disposition = await dependencies.dispatch(request); + } catch (error) { + if (!(error instanceof AgentTurnBusyError) || !closed) throw error; + // Shutdown drains admitted messages before closing the recipients. + disposition = await dependencies.dispatch({ ...request, idleOnly: false }); + } for (const message of messages) { try { message.onDispatch?.(disposition); } catch (error) { dependencies.onError(error, request); } + message.resolve(disposition); } - }, - }; + return undefined; + } catch (error) { + if (error instanceof AgentTurnBusyError && !closed) { + requeue(recipientId, messages); + return; + } + for (const message of messages) message.reject(error); + dependencies.onError(error, request); + throw error; + } + }); + } + + function queueDispatch(recipientId: string, operation: () => Promise): void { const previous = dispatching.get(recipientId) ?? Promise.resolve(); - const dispatched = previous - .catch(() => undefined) - .then(async () => { - try { - for (const message of messages) message.beforeDispatch?.(); - const disposition = await dependencies.dispatch(request); - for (const message of messages) message.resolve(disposition); - return undefined; - } catch (error) { - for (const message of messages) message.reject(error); - dependencies.onError(error, request); - throw error; - } - }); + const dispatched = previous.catch(() => undefined).then(operation); dispatching.set(recipientId, dispatched); void dispatched .finally(() => { @@ -115,30 +141,121 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes .catch(() => undefined); } + function requeue(recipientId: string, messages: Admitted[]): void { + const entry = pending.get(recipientId) ?? { + messages: [], + ready: true, + cancel: () => {}, + }; + entry.cancel(); + entry.messages.push(...messages); + entry.messages.sort((a, b) => a.sequence - b.sequence); + entry.cancel = schedule(2000, () => flush(recipientId)); + pending.set(recipientId, entry); + } + function flush(recipientId: string): void { const entry = pending.get(recipientId); if (!entry) return; - pending.delete(recipientId); + entry.ready = true; entry.cancel(); + if (!closed && dependencies.isRunning?.(recipientId)) { + const interrupts = entry.messages.filter( + (message) => message.activeTurnBehavior === "interrupt", + ); + entry.messages = entry.messages.filter( + (message) => message.activeTurnBehavior !== "interrupt", + ); + if (interrupts.length) dispatchGroups(recipientId, interrupts); + if (entry.messages.length && dependencies.tryRunOutOfBand) { + pending.delete(recipientId); + offerOutOfBand(recipientId, entry.messages); + } else if (entry.messages.length) { + entry.cancel = schedule(2000, () => flush(recipientId)); + } else { + pending.delete(recipientId); + } + return; + } + pending.delete(recipientId); + dispatchGroups(recipientId, entry.messages); + } + + function offerOutOfBand(recipientId: string, messages: Admitted[]): void { + queueDispatch(recipientId, async () => { + const waiting: Admitted[] = []; + for (const message of messages) { + if ( + message.outOfBandDeclined || + message.sessionMode !== undefined || + closed || + !dependencies.isRunning?.(recipientId) + ) { + waiting.push(message); + continue; + } + const request = requestFor(recipientId, [message]); + try { + const accepted = await dependencies.tryRunOutOfBand!(request, () => + message.beforeDispatch?.(), + ); + if (!accepted) { + message.outOfBandDeclined = true; + waiting.push(message); + continue; + } + try { + message.onDispatch?.("out_of_band"); + } catch (error) { + dependencies.onError(error, request); + } + message.resolve("out_of_band"); + } catch (error) { + message.reject(error); + dependencies.onError(error, request); + } + } + if (waiting.length) requeue(recipientId, waiting); + if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))) + flush(recipientId); + }); + } + + function dispatchGroups(recipientId: string, messages: Admitted[]): void { + const groups: Admitted[][] = []; let group: Admitted[] = []; let mode: string | undefined; - for (const message of entry.messages) { + for (const message of messages) { // Explicitly conflicting send options require separate, ordered dispatches. if ( group.length && ((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") || (mode && message.sessionMode && mode !== message.sessionMode)) ) { - dispatch(recipientId, group); + groups.push(group); group = []; mode = undefined; } group.push(message); mode ??= message.sessionMode; } - if (group.length) dispatch(recipientId, group); + if (group.length) groups.push(group); + let started = false; + for (const batch of groups) { + if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") { + requeue(recipientId, batch); + } else { + dispatch(recipientId, batch); + started = true; + } + } } + const unsubscribe = dependencies.subscribe?.((recipientId) => { + if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)) + flush(recipientId); + }); + return { hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId), enqueue(message) { @@ -155,17 +272,47 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes messageId: message.messageId ?? randomUUID(), dispatched, }; - const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} }; + const owned = receipts.get(message.recipientId) ?? new Set(); + owned.add(receipt); + receipts.set(message.recipientId, owned); + void dispatched + .finally(() => { + owned.delete(receipt); + if (!owned.size) receipts.delete(message.recipientId); + }) + .catch(() => undefined); + const entry = pending.get(message.recipientId) ?? { + messages: [], + ready: false, + cancel: () => {}, + }; entry.cancel(); - entry.messages.push({ ...message, receipt, resolve, reject }); + entry.ready = false; + entry.messages.push({ + ...message, + receipt, + resolve, + reject, + sequence: sequence++, + outOfBandDeclined: false, + }); entry.cancel = schedule(2000, () => flush(message.recipientId)); pending.set(message.recipientId, entry); return receipt; }, async waitForDispatch(recipientId, signal) { signal.throwIfAborted(); - const admitted = - pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? []; + const admitted = Array.from(receipts.get(recipientId) ?? [], (receipt) => receipt.dispatched); + let unsubscribePermission: (() => void) | undefined; + const permission = new Promise((resolve) => { + const check = () => { + if (dependencies.hasPendingPermission?.(recipientId)) resolve(); + }; + unsubscribePermission = dependencies.subscribe?.((agentId) => { + if (agentId === recipientId) check(); + }); + check(); + }); let aborted!: () => void; const cancellation = new Promise((_resolve, reject) => { aborted = () => reject(new DOMException("Wait aborted", "AbortError")); @@ -175,17 +322,22 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes await Promise.race([ Promise.all([dispatching.get(recipientId), ...admitted]), cancellation, + permission, ]); } finally { signal.removeEventListener("abort", aborted); + unsubscribePermission?.(); } }, close() { if (closing) return closing; closed = true; + unsubscribe?.(); for (const recipientId of pending.keys()) flush(recipientId); // Each failure is reported and rejects its receipts; shutdown still drains other recipients. - closing = Promise.allSettled(dispatching.values()).then(() => undefined); + closing = Promise.allSettled( + [...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)), + ).then(() => undefined); return closing; }, }; diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index d178c72f6c..f23a549491 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -23,7 +23,10 @@ export type AgentRunController = Pick< reloadAgentSession(agentId: string): Promise; }; +export class AgentTurnBusyError extends Error {} + export interface StartAgentRunOptions { + idleOnly?: boolean; /** Called after selecting the run, before consuming its events. */ onDispatch?: (disposition: PromptDispatchDisposition) => void; replaceRunning?: boolean; @@ -136,7 +139,12 @@ async function startAgentRunInner( options?: StartAgentRunOptions, ): Promise<{ disposition: PromptDispatchDisposition }> { const snapshot = agentManager.getAgent(agentId); - const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options); + const steered = options?.idleOnly + ? null + : await steerOrReplaceActiveRun(agentManager, agentId, prompt, options); + if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) { + throw new AgentTurnBusyError(`Agent ${agentId} is running`); + } if (steered?.disposition === "steered") { options?.onDispatch?.("steered"); return steered; @@ -210,6 +218,7 @@ export async function unarchiveAgentState( } export interface SendPromptToAgentParams { + idleOnly?: boolean; /** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */ beforeDispatch?: () => Promise; onDispatch?: StartAgentRunOptions["onDispatch"]; @@ -355,13 +364,17 @@ export async function sendPreparedPromptToAgent( throw error; } + if (params.idleOnly && params.agentManager.hasInFlightRun(params.agentId)) { + throw new AgentTurnBusyError(`Agent ${params.agentId} is running`); + } if (params.sessionMode) { await params.agentManager.setAgentMode(params.agentId, params.sessionMode); } await params.beforeDispatch?.(); return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, { - replaceRunning: true, + replaceRunning: !params.idleOnly, + idleOnly: params.idleOnly, onDispatch: params.onDispatch, activeTurnBehavior: params.activeTurnBehavior, clearPendingPermissions: params.clearPendingPermissions, diff --git a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts index 9e18f87948..acd44998b5 100644 --- a/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts +++ b/packages/server/src/server/agent/finish-subscriptions/finish-subscriptions.test.ts @@ -498,3 +498,26 @@ test("finish recovery protects callers before durable intent has loaded", async expect(recovered.hasPendingForCaller("parent")).toBe(true); expect(recovered.hasPendingForCaller("unrelated")).toBe(false); }); + +test("an undispatched follow-up does not block the running child's permission notification", async () => { + const state = await scenario(); + await state.service.register(intent); + await until(() => state.observation.waits.length === 1); + await state.service.register(intent, true); + const result = outcome("running"); + result.status = "permission"; + result.final!.pendingPermissions = [ + { + id: "approval", + provider: "codex", + name: "Bash", + kind: "tool", + input: { command: "run tests" }, + } as NonNullable["pendingPermissions"][number], + ]; + state.observation.waits[0]!.result.resolve(result); + await until(() => state.delivery.prompts.length === 1); + expect(state.delivery.prompts[0]).toContain("needs permission"); + expect(state.delivery.prompts[0]).toContain("approval"); + expect(await state.store.list()).toHaveLength(2); +}); diff --git a/packages/server/src/server/agent/finish-subscriptions/index.ts b/packages/server/src/server/agent/finish-subscriptions/index.ts index 22324f0ecc..226ed5af51 100644 --- a/packages/server/src/server/agent/finish-subscriptions/index.ts +++ b/packages/server/src/server/agent/finish-subscriptions/index.ts @@ -267,7 +267,9 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio continue; } if (signal.aborted) return; - await decisions(group); + // A queued follow-up cannot start until the current permission is answered. + // Its pending registration must not hold the running turn's checkpoint. + if (pending.status !== "permission" || watch.pending) await decisions(group); if (signal.aborted) return; if (await suppressed(record, pending)) { await remove(watch); diff --git a/packages/server/src/server/agent/host-operations/index.ts b/packages/server/src/server/agent/host-operations/index.ts index 961ba10f88..93b7ad2233 100644 --- a/packages/server/src/server/agent/host-operations/index.ts +++ b/packages/server/src/server/agent/host-operations/index.ts @@ -298,7 +298,7 @@ export function createHostResolver(input: { status: agent.status, guidance: receipt.deliveryStatus === "queued" - ? "Queued for delivery after two quiet seconds. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false." + ? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false." : "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.", }); }, diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 6d267ff53a..679f4d04db 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -172,11 +172,12 @@ function registeredTool( async function invokeToolWithParsedInput( tool: RegisteredMcpToolWithHandler, input: Record, + awaitDispatch = true, ) { const parsed = await tool.inputSchema.safeParseAsync(input); expect(parsed.success).toBe(true); const response = await tool.handler(parsed.data); - if (response.structuredContent.deliveryStatus === "queued") { + if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") { await toolDeliveries .get(tool)! .waitForDispatch(input.agentId as string, new AbortController().signal); @@ -274,6 +275,7 @@ function buildAgentManagerSpies() { effectiveOptionsFor: (_provider: string, own?: Record) => own ?? {}, reloadStalePluginSession: async () => {}, hasInFlightRun: vi.fn().mockReturnValue(false), + hasPendingPermissions: () => false, steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }), tryRunOutOfBand: vi.fn().mockReturnValue(false), subscribe: vi.fn().mockReturnValue(() => {}), @@ -623,6 +625,12 @@ class FakeBrowserToolsBroker { } class BoundaryAgentManagerFake { + subscribe() { + return () => {}; + } + hasPendingPermissions() { + return false; + } public getPluginTools(): [] { return []; } @@ -877,8 +885,9 @@ function createPaseoWorktreeForMcpTest(options: { async function createAgentMcpServer( options: Parameters[0], subscriptionStore?: FinishSubscriptionStore, + schedule?: (delayMs: number, callback: () => void) => () => void, ) { - const messages = createTestAgentMessages(options); + const messages = createTestAgentMessages({ ...options, schedule }); const records = new Map(); const subscriptions = createFinishSubscriptions({ store: subscriptionStore ?? { @@ -3677,15 +3686,15 @@ class HeldTurnAgentClient implements AgentClient { describe("send_agent_prompt MCP tool", () => { it.each([ - { agentScoped: true, behavior: undefined, available: true, steered: true }, - { agentScoped: true, behavior: "interrupt", available: true, steered: false }, - { agentScoped: true, behavior: "steer", available: true, steered: true }, - { agentScoped: false, behavior: undefined, available: true, steered: false }, - { agentScoped: false, behavior: "steer", available: true, steered: true }, - { agentScoped: true, behavior: undefined, available: false, steered: false }, + { agentScoped: true, behavior: undefined, available: true }, + { agentScoped: true, behavior: "interrupt", available: true }, + { agentScoped: true, behavior: "steer", available: true }, + { agentScoped: false, behavior: undefined, available: true }, + { agentScoped: false, behavior: "steer", available: true }, + { agentScoped: true, behavior: undefined, available: false }, ] as const)( "dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available", - async ({ agentScoped, behavior, available, steered }) => { + async ({ agentScoped, behavior, available }) => { const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); const storage = new AgentStorage(join(workdir, "agents"), logger); const client = new HeldTurnAgentClient("codex", true, { @@ -3717,18 +3726,33 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, }); const originalTurn = manager.getAgent(child.id)!.activeTurnId; - const response = await invokeToolWithParsedInput(tool, { - agentId: child.id, - prompt: "New message", - notifyOnFinish: false, - ...(behavior ? { activeTurnBehavior: behavior } : {}), - }); + const queued = agentScoped && behavior !== "interrupt"; + const steered = !agentScoped && behavior === "steer"; + const response = await invokeToolWithParsedInput( + tool, + { + agentId: child.id, + prompt: "New message", + notifyOnFinish: false, + ...(behavior ? { activeTurnBehavior: behavior } : {}), + }, + !queued, + ); expect(response.structuredContent).toMatchObject({ success: true, ...(agentScoped ? { deliveryStatus: "queued" } : { disposition: steered ? "steered" : "turn_started" }), }); + if (queued) { + expect(client.sessions[1]!.prompts).toHaveLength(1); + expect(client.sessions[1]!.steeredPrompts).toEqual([]); + expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn); + client.sessions[1]!.finishTurn(); + await serverDeliveries + .get(server)! + .waitForDispatch(child.id, new AbortController().signal); + } expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2); expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0); expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered); @@ -3740,18 +3764,16 @@ describe("send_agent_prompt MCP tool", () => { it.each([ { rejected: false, priorNotification: false }, - { rejected: true, priorNotification: false }, { rejected: false, priorNotification: true }, + { rejected: true, priorNotification: false }, + { rejected: true, priorNotification: true }, ])( - "buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)", + "keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)", async ({ rejected, priorNotification }) => { - const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); + const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-")); const storage = new AgentStorage(join(workdir, "agents"), logger); - const client = new HeldTurnAgentClient("codex", true, { - steerResult: "accepted", - finishDuringSteer: true, - rejectSteer: rejected, - }); + const options: HeldTurnOptions = {}; + const client = new HeldTurnAgentClient("codex", true, options); const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); let mcpClient: Client | undefined; try { @@ -3773,104 +3795,47 @@ describe("send_agent_prompt MCP tool", () => { logger, }); mcpClient = await connectInMemoryMcpClient(server); - const send = (input: Record) => - sendMcpAndAwaitDispatch(mcpClient!, server, input); - await send({ + await sendMcpAndAwaitDispatch(mcpClient, server, { agentId: child.id, prompt: "Original work", notifyOnFinish: priorNotification, }); - const sending = send({ - agentId: child.id, - prompt: "New message", - notifyOnFinish: true, + const session = client.sessions[1]!; + const release = session.holdTurnStart(); + options.finishTurnsDuringStart = true; + if (rejected) session.rejectNextTurnStart(new Error("Start rejected")); + const response = await mcpClient.callTool({ + name: "send_agent_prompt", + arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true }, }); - if (rejected) { - await expect(sending).rejects.toThrow("Steer rejected"); - // Flush asynchronous notification work before checking that a rejected - // dispatch did not notify. Then prove a later successful send still can. - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(client.sessions[0]!.prompts).toHaveLength(0); - await send({ - agentId: child.id, - prompt: "Retry after rejection", + expect(response.structuredContent).toMatchObject({ + success: true, + deliveryStatus: "queued", + }); + const dispatch = serverDeliveries + .get(server)! + .waitForDispatch(child.id, new AbortController().signal); + const rejectedDispatch = rejected + ? expect(dispatch).rejects.toThrow("Start rejected") + : null; + expect(client.sessions[0]!.prompts).toHaveLength(0); + session.finishTurn(); + await vi.waitFor(() => expect(session.prompts).toHaveLength(2)); + expect(client.sessions[0]!.prompts).toHaveLength(0); + release(); + if (rejectedDispatch) await rejectedDispatch; + else await dispatch; + if (!rejected || priorNotification) { + await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), { + timeout: 5000, + }); + expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({ + source: { kind: "agent-notification", agentId: child.id, event: "finished" }, }); - client.sessions[1]!.finishTurn(); } else { - const response = await sending; - expect(response.structuredContent).toMatchObject({ - success: true, - deliveryStatus: "queued", - }); - } - await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1)); - expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({ - source: { kind: "agent-notification", agentId: child.id, event: "finished" }, - }); - } finally { - await mcpClient?.close(); - await removeAgentStateDir(manager, storage, workdir); - } - }, - ); - - it.each([false, true])( - "preserves the original notification after rejection (completion during send: %s)", - async (finishDuringSteer) => { - const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); - const storage = new AgentStorage(join(workdir, "agents"), logger); - const client = new HeldTurnAgentClient("codex", true, { - steerResult: "accepted", - finishDuringSteer, - rejectSteer: true, - }); - const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); - let mcpClient: Client | undefined; - try { - const parent = await manager.createAgent( - { provider: "codex", cwd: existingCwd }, - undefined, - { - workspaceId: "wks_parent", - }, - ); - const child = await manager.createAgent( - { provider: "codex", cwd: existingCwd }, - undefined, - { - workspaceId: "wks_parent", - }, - ); - const server = await createAgentMcpServer({ - agentManager: manager, - agentStorage: storage, - callerAgentId: parent.id, - providerSnapshotManager: createOpenCodeManager().manager, - logger, - }); - mcpClient = await connectInMemoryMcpClient(server); - const send = (input: Record) => - sendMcpAndAwaitDispatch(mcpClient!, server, input); - await send({ - agentId: child.id, - prompt: "Original work", - notifyOnFinish: true, - }); - const sending = send({ - agentId: child.id, - prompt: "New message", - notifyOnFinish: true, - }); - await expect(sending).rejects.toThrow("Steer rejected"); - if (!finishDuringSteer) { - await new Promise((resolve) => setTimeout(resolve, 50)); + await serverSubscriptions.get(server)!.close(); expect(client.sessions[0]!.prompts).toHaveLength(0); - client.sessions[1]!.finishTurn(); } - await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1)); - expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({ - source: { kind: "agent-notification", agentId: child.id, event: "finished" }, - }); } finally { await mcpClient?.close(); await removeAgentStateDir(manager, storage, workdir); @@ -4012,7 +3977,7 @@ describe("send_agent_prompt MCP tool", () => { const response = await tool.handler(parsed.data as Record); expect(response.structuredContent).toMatchObject({ deliveryStatus: "queued" }); - expect(spies.agentManager.subscribe).not.toHaveBeenCalled(); + expect(serverSubscriptionRecords.get(server)!.size).toBe(1); await serverDeliveries .get(server)! .waitForDispatch("child-agent", new AbortController().signal); @@ -4053,7 +4018,7 @@ describe("send_agent_prompt MCP tool", () => { await tool.handler(parsed.data as Record); - expect(spies.agentManager.subscribe).not.toHaveBeenCalled(); + expect(serverSubscriptionRecords.get(server)!.size).toBe(0); expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled(); }); @@ -4096,7 +4061,7 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, }); - expect(spies.agentManager.subscribe).not.toHaveBeenCalled(); + expect(serverSubscriptionRecords.get(server)!.size).toBe(0); expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled(); }); @@ -4220,11 +4185,15 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, }); if (scenario !== "startup_failure") { - const response = await invokeToolWithParsedInput(tool, { - agentId: child.id, - prompt: "/side-command", - activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer", - }); + const response = await invokeToolWithParsedInput( + tool, + { + agentId: child.id, + prompt: "/side-command", + activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer", + }, + scenario !== "out_of_band", + ); expect(response.structuredContent).toMatchObject({ success: true, deliveryStatus: "queued", @@ -4236,6 +4205,9 @@ describe("send_agent_prompt MCP tool", () => { }); expect(parentClient.sessions[0]!.prompts).toHaveLength(0); childClient.sessions[0]!.finishTurn("Ongoing task done"); + await serverDeliveries + .get(server)! + .waitForDispatch(child.id, new AbortController().signal); await vi.waitFor(() => { expect(parentClient.sessions[0]!.prompts).toHaveLength(1); expect(parentClient.sessions[0]!.prompts[0]).toContain("finished."); @@ -4243,7 +4215,11 @@ describe("send_agent_prompt MCP tool", () => { } else { childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start")); await expect( - invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }), + invokeToolWithParsedInput(tool, { + agentId: child.id, + prompt: "Replacement task", + activeTurnBehavior: "interrupt", + }), ).rejects.toThrow("Requested turn could not start"); // A later real turn must not inherit a subscription from the rejected dispatch. await invokeToolWithParsedInput(tool, { @@ -4354,6 +4330,7 @@ describe("send_agent_prompt MCP tool", () => { const sent = await invokeToolWithParsedInput(registeredTool(server, "send_agent_prompt"), { agentId: childId, prompt: "Stop and reply instead", + activeTurnBehavior: "interrupt", }); expect(sent.structuredContent).toMatchObject({ success: true, @@ -4517,7 +4494,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => { const logger = createTestLogger(); const existingCwd = process.cwd(); - async function setupOmpChild() { + async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) { const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-")); const storage = new AgentStorage(join(workdir, "agents"), logger); const parentClient = new HeldTurnAgentClient("claude", false); @@ -4545,13 +4522,17 @@ describe("send_agent_prompt MCP tool to an OMP child", () => { undefined, { workspaceId: "wks_parent" }, ); - const server = await createAgentMcpServer({ - agentManager, - agentStorage: storage, - callerAgentId: parent.id, - providerSnapshotManager: createOpenCodeManager().manager, - logger, - }); + const server = await createAgentMcpServer( + { + agentManager, + agentStorage: storage, + callerAgentId: parent.id, + providerSnapshotManager: createOpenCodeManager().manager, + logger, + }, + undefined, + schedule, + ); return { agentManager, storage, @@ -4581,37 +4562,63 @@ describe("send_agent_prompt MCP tool to an OMP child", () => { { command: "follow-up", streamingBehavior: "followUp" }, { command: "steer", streamingBehavior: "steer" }, ] as const)( - "delivers /$command into a turn OMP started on its own, without aborting it", + "delivers /$command to a running OMP child while ordinary messages in the same quiet window wait", async ({ command, streamingBehavior }) => { - const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } = - await setupOmpChild(); + let flush!: () => void; + const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild( + (_delay, callback) => { + flush = callback; + return () => {}; + }, + ); try { ompSession.beginTurn(); ompSession.streamAssistantText("background job finished, working on it"); await vi.waitFor(() => { expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/); }); - - const response = await invokeToolWithParsedInput(tool, { - agentId: childId, - prompt: `/${command} then summarize the logs`, - }); - - expect(response.structuredContent).toMatchObject({ - success: true, - deliveryStatus: "queued", - status: "running", + const activeTurnId = agentManager.getAgent(childId)?.activeTurnId; + const delivery = toolDeliveries.get(tool)!; + let ordinaryBeforeDispatch = 0; + const ordinary = delivery.enqueue({ + recipientId: childId, + source: { kind: "agent-message", agentId: "parent" }, + prompt: "ordinary follow-up", + beforeDispatch: () => { + ordinaryBeforeDispatch++; + }, }); + const response = await invokeToolWithParsedInput( + tool, + { + agentId: childId, + prompt: `/${command} then summarize the logs`, + }, + false, + ); + flush(); await vi.waitFor(() => { expect(ompSession.prompts).toEqual([ { message: "then summarize the logs", imageCount: 0, streamingBehavior }, ]); }); + expect(ordinaryBeforeDispatch).toBe(0); + expect(agentManager.getAgent(childId)?.activeTurnId).toBe(activeTurnId); + expect(response.structuredContent).toMatchObject({ + success: true, + deliveryStatus: "queued", + status: "running", + }); expect(ompSession.abortRequested).toBe(false); expect(agentManager.getAgent(childId)?.lifecycle).toBe("running"); ompSession.finishTurn(); - await expectOneFinishNotification(agentManager, parentClient, childId); + await ordinary.dispatched; + expect(ordinaryBeforeDispatch).toBe(1); + expect(ompSession.prompts).toHaveLength(2); + expect(ompSession.prompts[1]!.message).toContain("ordinary follow-up"); + ompSession.beginTurn(); + ompSession.finishTurn(); } finally { await removeAgentStateDir(agentManager, storage, workdir); } diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 1107ad5e9d..1f22079bfa 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -1281,7 +1281,7 @@ function createToolCatalog( .strict(); const commonSendAgentPromptInputSchema = { activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe( - 'How to send into a running turn: "steer" joins it, falling back to interrupt when unavailable; "interrupt" replaces it. Defaults to steer for agent callers and interrupt otherwise.', + 'Agent callers: "steer" (default) waits until the current turn ends; "interrupt" replaces it. Human callers: "steer" joins the turn, falling back to interrupt; default is interrupt.', ), agentId: z.string(), prompt: z.string(), @@ -1968,7 +1968,7 @@ function createToolCatalog( { title: "Send agent prompt", description: - "Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient. Completion reports include the target’s last response by default. Paseo supplies caller identity.", + "Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient and waits for the current turn to end unless interrupt is requested. Completion reports include the target’s last response by default. Paseo supplies caller identity.", inputSchema: sendAgentPromptInputSchema, outputSchema: { success: z.boolean(), @@ -2045,8 +2045,8 @@ function createToolCatalog( messageId: receipt.messageId, status: agentManager.getAgent(agentId)?.lifecycle ?? "idle", guidance: notifying - ? `Queued for delivery after two quiet seconds. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}` - : "Queued for delivery after two quiet seconds; provider dispatch has not occurred.", + ? `Queued for delivery after two quiet seconds and the current turn ends. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}` + : "Queued for delivery after two quiet seconds and the current turn ends; provider dispatch has not occurred.", }, }; } diff --git a/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts b/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts index bc2803a65e..a8cc2c2379 100644 --- a/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts +++ b/packages/server/src/server/daemon-e2e/peer-message-permissions.test.ts @@ -95,7 +95,7 @@ test("an agent-sourced steer leaves the question pending and answerable", async await client.sendAgentMessage(recipient.id, "Peer status check", { sourceAgentId: sender.id, }); - // The public wait includes admitted message delivery before reporting permission status. + // Permission checkpoints are reported while the peer message waits for turn end. const waiting = await client.waitForFinish(recipient.id); expect(waiting.status).toBe("permission"); expect(waiting.final?.pendingPermissions).toMatchObject([ diff --git a/packages/server/src/server/test-utils/agent-messages.ts b/packages/server/src/server/test-utils/agent-messages.ts index b69da1f1c8..ce188fbfd8 100644 --- a/packages/server/src/server/test-utils/agent-messages.ts +++ b/packages/server/src/server/test-utils/agent-messages.ts @@ -12,12 +12,31 @@ export function createTestAgentMessages(params: { agentManager: AgentManager; agentStorage: AgentStorage; logger: Logger; + schedule?: (delayMs: number, callback: () => void) => () => void; }) { return createAgentMessageDelivery({ - schedule: (_delay, callback) => { - const timer = setTimeout(callback, 0); - return () => clearTimeout(timer); - }, + tryRunOutOfBand: (request, onAccepted) => + params.agentManager.tryRunOutOfBand( + request.recipientId, + request.prompt, + { clientMessageId: request.messageIds[0] }, + onAccepted, + ), + isRunning: (agentId) => params.agentManager.hasInFlightRun(agentId), + hasPendingPermission: (agentId) => params.agentManager.hasPendingPermissions(agentId), + subscribe: (notify) => + params.agentManager.subscribe( + (event) => { + if (event.type === "agent_state") notify(event.agent.id); + }, + { replayState: false }, + ), + schedule: + params.schedule ?? + ((_delay, callback) => { + const timer = setTimeout(callback, 0); + return () => clearTimeout(timer); + }), dispatch: async (request) => { const result = await sendPreparedPromptToAgent({ ...params, @@ -26,8 +45,8 @@ export function createTestAgentMessages(params: { sessionMode: request.sessionMode, unarchive: request.unarchive, activeTurnBehavior: request.activeTurnBehavior, + idleOnly: request.idleOnly, clearPendingPermissions: request.clearPendingPermissions, - onDispatch: request.onDispatch, runOptions: { clientMessageId: request.messageIds[0] }, }); if (result.disposition === "turn_started") diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index cbbdd9685d..793b8041e4 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -728,6 +728,22 @@ export class VoiceAssistantWebSocketServer { this.agentManager = agentManager; this.agentStorage = agentStorage; this.agentMessages = createAgentMessageDelivery({ + tryRunOutOfBand: (request, onAccepted) => + agentManager.tryRunOutOfBand( + request.recipientId, + request.prompt, + { clientMessageId: request.messageIds[0] }, + onAccepted, + ), + isRunning: (agentId) => agentManager.hasInFlightRun(agentId), + hasPendingPermission: (agentId) => agentManager.hasPendingPermissions(agentId), + subscribe: (notify) => + agentManager.subscribe( + (event) => { + if (event.type === "agent_state") notify(event.agent.id); + }, + { replayState: false }, + ), dispatch: async (batch) => { const { disposition } = await sendPreparedPromptToAgent({ agentManager, @@ -735,11 +751,11 @@ export class VoiceAssistantWebSocketServer { agentId: batch.recipientId, prompt: batch.prompt, activeTurnBehavior: batch.activeTurnBehavior, + idleOnly: batch.idleOnly, sessionMode: batch.sessionMode, clearPendingPermissions: batch.clearPendingPermissions, unarchive: batch.unarchive, runOptions: { clientMessageId: batch.messageIds[0] }, - onDispatch: batch.onDispatch, logger: this.logger, }); if (disposition === "turn_started") diff --git a/skills/paseo/SKILL.md b/skills/paseo/SKILL.md index cb08f49aa4..f3dce11ef7 100644 --- a/skills/paseo/SKILL.md +++ b/skills/paseo/SKILL.md @@ -84,7 +84,7 @@ Detach is an explicit user action in the subagents track, not an agent tool. A c Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false` when you want explicit reporting or no completion callback. -**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. Set `activeTurnBehavior` to `steer` or `interrupt` to override the default. Steering falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver after two quiet seconds. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback. +**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. For agent-scoped calls, `steer` waits until the recipient's current turn ends, and only `interrupt` stops a running turn. For top-level calls, `steer` joins the running turn and falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver together after two quiet seconds, or after the recipient's turn ends if it is running. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback. **`update_agent`** — `{ agentId, name?, labels?, settings? }`. Use `settings` for runtime changes on an existing agent: `modeId`, `model`, `thinkingOptionId`, and provider-specific `features`. For Codex fast mode, pass `settings: { features: { "fast_mode": true } }`. From 33259746db2fa85dc69a5b756824834e2f8cb95f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:10:01 +0000 Subject: [PATCH 111/160] Stop timed-out watcher setups from rescanning large repos every 5 minutes (#9828) * fix(server): abort timed-out watcher setups and back off their retries A watcher subscription that missed WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS was abandoned but its startup scan kept walking the tree to completion, and recovery retried every five minutes forever, repeating the full scan each time. On a CPU-starved host that kept dozens of directories rescanning. - FileObserver.subscribe accepts an abort signal that stops the startup scan and rejects; WorkspaceGit aborts setups at the deadline and on dispose. - Consecutive setup timeouts extend the recovery delay past the 5-minute ladder cap, doubling up to one hour; an accepted subscription resets it. Degraded polling keeps its 5-60 s cadence meanwhile. Co-Authored-By: Claude Opus 5.5 * fix(file-observer): keep an aborted observation's backend from starting Aborting a subscription closes its observation, which can happen while start() is still reading the root. The backend then started after its close had finished, and the native backend opened a root watcher that nothing would close. Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * test(file-observer): abort a subscription mid-scan in the abort test The test aborted before the backend started, so it passed with the abort listener removed. A tree past the Linux directory limit makes a scan that keeps walking fail on the limit instead of rejecting with the reason. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Spencer Shulem Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com> --- docs/file-observation.md | 2 +- .../src/server/file-observer/index.test.ts | 33 +++++ .../server/src/server/file-observer/index.ts | 16 ++- .../internal/observation.test.ts | 46 +++++++ .../file-observer/internal/observation.ts | 3 + .../workspace-git-service.primitive.test.ts | 1 + .../src/server/workspace-git-service.test.ts | 113 ++++++++++++++++++ .../src/server/workspace-git-service.ts | 44 ++++++- 8 files changed, 251 insertions(+), 7 deletions(-) create mode 100644 packages/server/src/server/file-observer/internal/observation.test.ts diff --git a/docs/file-observation.md b/docs/file-observation.md index c2e68d83a9..3e044b21af 100644 --- a/docs/file-observation.md +++ b/docs/file-observation.md @@ -6,7 +6,7 @@ Do not replace the Linux implementation with `fs.watch({ recursive: true })`. No Closing an observation must remain safe after its root is renamed or removed. Workspace archive removes owned worktrees while releasing observation references, so teardown cannot assume the watched path still exists. -`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. +`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. `subscribe()` accepts an abort signal; aborting it before it resolves stops the startup scan and rejects. WorkspaceGit aborts every subscription that misses its setup deadline, because an abandoned scan otherwise keeps walking the tree. A timed-out directory retries on the recovery ladder (30 seconds doubling to five minutes), and each consecutive timeout keeps doubling the delay up to one hour. Under sustained CPU load the next scan misses the deadline too, and each attempt repeats the full scan. An accepted subscription resets the timeout streak. Degraded polling keeps its own cadence throughout. Linux topology repair is trailing-debounced and scoped to the renamed path. A file rename needs one classification stat; a new or moved directory scans only its subtree. Full-tree scans are reserved for startup and ignore-set replacement. A subscription reports changes after `subscribe()` resolves, not the files that already existed. macOS FSEvents can still replay writes made moments before the stream started. Consumers read their initial state after `subscribe()` resolves; WorkspaceGit re-reads its checkout once observation setup completes, because its first refresh runs in parallel with setup. The Linux startup scan therefore emits nothing; only a scoped reconciliation of new topology reports files found before their directory's watcher was installed. Startup creates made every cold diff compute and discard a first revision. Benchmark startup cost with pre-populated trees. diff --git a/packages/server/src/server/file-observer/index.test.ts b/packages/server/src/server/file-observer/index.test.ts index c30e294817..92cb5bced4 100644 --- a/packages/server/src/server/file-observer/index.test.ts +++ b/packages/server/src/server/file-observer/index.test.ts @@ -327,6 +327,39 @@ test("unsubscribe cancels reconciliation queued by a write burst", async () => { expect(callback).toHaveBeenCalledTimes(callsAtClose); }, 20_000); +test("aborting a pending subscription stops its startup scan and rejects", async () => { + const root = await createRoot(); + // More directories than the Linux backend watches: a scan that keeps walking after the abort + // fails on the directory limit instead of rejecting with the abort reason. + await Promise.all( + Array.from({ length: 80 }, (_, outer) => + Promise.all( + Array.from({ length: 70 }, (__, inner) => + mkdir(join(root, `dir-${outer}`, `nested-${inner}`), { recursive: true }), + ), + ), + ), + ); + const observer = createObserver(); + const controller = new AbortController(); + const reason = new Error("setup deadline passed"); + const callback = vi.fn(); + + const subscription = observer.subscribe(root, callback, { signal: controller.signal }); + await new Promise((resolve) => setTimeout(resolve, 10)); + controller.abort(reason); + + await expect(subscription).rejects.toBe(reason); + expect(observer.getDiagnostics()).toMatchObject({ + activeObservationCount: 0, + nativeHandleCount: 0, + pendingReconciliationWorkCount: 0, + }); + await writeFile(join(root, "dir-0", "after-abort.txt"), "late"); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(callback).not.toHaveBeenCalled(); +}, 20_000); + test("aggregate diagnostics return to their lifecycle baseline", async () => { const root = await createRoot(); const observer = createObserver(); diff --git a/packages/server/src/server/file-observer/index.ts b/packages/server/src/server/file-observer/index.ts index 05c9fdac50..14c7af57d1 100644 --- a/packages/server/src/server/file-observer/index.ts +++ b/packages/server/src/server/file-observer/index.ts @@ -14,6 +14,8 @@ export interface FileChange { export interface FileObserverOptions { ignore?: string[]; + // Aborting before `subscribe()` resolves stops the startup scan and rejects with the reason. + signal?: AbortSignal; } export type FileObserverCallback = (error: Error | null, events: FileChange[]) => void; @@ -105,7 +107,19 @@ class FileObserverService implements FileObserver { createBackend: this.createBackend, onClosed: () => state.observations.delete(observation), }); - await observation.start(); + const { signal } = options; + signal?.throwIfAborted(); + const abort = () => void observation.close(); + signal?.addEventListener("abort", abort, { once: true }); + try { + await observation.start(); + } finally { + signal?.removeEventListener("abort", abort); + } + if (signal?.aborted) { + await observation.close(); + throw signal.reason; + } if (this.closePromise) { await observation.close(); throw new Error("File observer is closed"); diff --git a/packages/server/src/server/file-observer/internal/observation.test.ts b/packages/server/src/server/file-observer/internal/observation.test.ts new file mode 100644 index 0000000000..f27809e871 --- /dev/null +++ b/packages/server/src/server/file-observer/internal/observation.test.ts @@ -0,0 +1,46 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { createFileObserver } from "../index.js"; +import { createNativeRecursiveBackend } from "./native-recursive.js"; +import { createManagedObservation } from "./observation.js"; +import { createObserverPaths } from "./paths.js"; + +// Aborting a subscription closes its observation while start() may still be +// reading the root, before the backend has started. +test("closing an observation before its backend starts leaves no native watcher open", async () => { + const root = await mkdtemp(join(tmpdir(), "observation-close-")); + const paths = createObserverPaths(process.platform); + let openWatchers = 0; + const observation = createManagedObservation({ + root, + callback: () => {}, + options: {}, + paths, + metrics: createFileObserver().getDiagnostics(), + createBackend: (host) => + createNativeRecursiveBackend(host, paths, () => { + openWatchers += 1; + let open = true; + return { + close: () => { + if (open) openWatchers -= 1; + open = false; + }, + on: () => {}, + }; + }), + onClosed: () => {}, + }); + try { + const started = observation.start(); + const closed = observation.close(); + await started; + await closed; + + expect(openWatchers).toBe(0); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/server/src/server/file-observer/internal/observation.ts b/packages/server/src/server/file-observer/internal/observation.ts index f0c27a504a..ee91a7c67d 100644 --- a/packages/server/src/server/file-observer/internal/observation.ts +++ b/packages/server/src/server/file-observer/internal/observation.ts @@ -69,6 +69,9 @@ class Observation implements ManagedObservation, ObservationHost { if (!rootStats.isDirectory()) { throw new Error(`File observation requires a directory: ${this.root}`); } + // An aborted subscription can close the observation while the root is being read; the backend + // must not start after its close has already finished. + if (!this.isActive()) return; try { await this.backend.start(); } catch (error) { diff --git a/packages/server/src/server/workspace-git-service.primitive.test.ts b/packages/server/src/server/workspace-git-service.primitive.test.ts index 7502c0ba30..b969c7315c 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -2195,6 +2195,7 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => { expect(subscribe).toHaveBeenCalledTimes(1); expect(subscribe).toHaveBeenCalledWith(repoDir, expect.any(Function), { ignore: [join(repoDir, ".git"), ignoredRoot], + signal: expect.any(AbortSignal), }); subscription.unsubscribe(); diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index d2cc4e0484..8349977f92 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -477,6 +477,56 @@ async function advanceThroughWorkingTreeRecoveryAttempts( } } +// Stalls every subscription for `watchPath` the way a CPU-starved startup scan does, until the +// service aborts it at the subscribe deadline. Other paths subscribe immediately. +function createStallingWatchSetup(watchPath: string) { + const signals: AbortSignal[] = []; + let acceptNext = false; + let acceptedCallback: WatchCallback | null = null; + const subscribe = vi.fn( + async (directory: string, callback: WatchCallback, options?: { signal?: AbortSignal }) => { + if (directory !== watchPath) { + return createAsyncSubscription(); + } + const signal = options?.signal ?? new AbortController().signal; + signals.push(signal); + if (acceptNext) { + acceptNext = false; + acceptedCallback = callback; + return createAsyncSubscription(); + } + return new Promise>((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }, + ); + return { + subscribe, + signals, + acceptNextAttempt() { + acceptNext = true; + }, + failAcceptedWatcher() { + acceptedCallback?.(new Error("accepted watcher stopped"), []); + }, + async expectAttemptAbortedAtDeadline() { + const signal = signals.at(-1); + expect(signal?.aborted).toBe(false); + await vi.advanceTimersByTimeAsync(WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS); + expect(signal?.aborted).toBe(true); + expect(signal?.reason).toMatchObject({ name: "WorkspaceGitWatcherSubscriptionTimeoutError" }); + }, + async expectNextAttemptAfter(delayMs: number, service: WorkspaceGitServiceImpl) { + const attempts = signals.length; + await vi.advanceTimersByTimeAsync(delayMs - 1); + await waitForRefreshesToSettle(service); + expect(signals).toHaveLength(attempts); + await vi.advanceTimersByTimeAsync(1); + await settle(() => expect(signals).toHaveLength(attempts + 1)); + }, + }; +} + describe("WorkspaceGitServiceImpl", () => { beforeEach(() => { vi.useFakeTimers(); @@ -1573,6 +1623,7 @@ describe("WorkspaceGitServiceImpl", () => { expect(subscribe).toHaveBeenCalledTimes(1); expect(subscribe).toHaveBeenCalledWith(REPO_CWD, expect.any(Function), { ignore: [join(REPO_CWD, ".git")], + signal: expect.any(AbortSignal), }); subscription.unsubscribe(); @@ -1648,6 +1699,67 @@ describe("WorkspaceGitServiceImpl", () => { 15_000, ); + test.each(["repository metadata", "working tree"])( + "aborts each timed-out %s watcher setup and backs retries off toward an hour", + async (kind) => { + const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD; + const setup = createStallingWatchSetup(watchPath); + const getCheckoutStatus = vi.fn(async (cwd: string) => createCheckoutStatus(cwd)); + const service = createService({ subscribe: setup.subscribe, getCheckoutStatus }); + const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn()); + try { + await settle(() => expect(setup.signals).toHaveLength(1)); + await setup.expectAttemptAbortedAtDeadline(); + await waitForObservationToSettle(service, 1); + for (const delayMs of [ + 30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_920_000, 3_600_000, + ]) { + await setup.expectNextAttemptAfter(delayMs, service); + await setup.expectAttemptAbortedAtDeadline(); + } + // Degraded polling keeps the checkout fresh while the watcher waits out an hour. + const readsBeforeCappedWait = getCheckoutStatus.mock.calls.length; + await setup.expectNextAttemptAfter(3_600_000, service); + expect(getCheckoutStatus.mock.calls.length).toBeGreaterThanOrEqual( + readsBeforeCappedWait + 59, + ); + } finally { + subscription.unsubscribe(); + await service.dispose(); + } + }, + 30_000, + ); + + test.each(["repository metadata", "working tree"])( + "an accepted %s watcher subscription resets the setup-timeout backoff", + async (kind) => { + const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD; + const setup = createStallingWatchSetup(watchPath); + const service = createService({ subscribe: setup.subscribe }); + const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn()); + try { + await settle(() => expect(setup.signals).toHaveLength(1)); + await setup.expectAttemptAbortedAtDeadline(); + for (const delayMs of [30_000, 60_000, 120_000, 240_000, 480_000]) { + await setup.expectNextAttemptAfter(delayMs, service); + await setup.expectAttemptAbortedAtDeadline(); + } + setup.acceptNextAttempt(); + await setup.expectNextAttemptAfter(960_000, service); + setup.failAcceptedWatcher(); + // The ordinary recovery ladder's ceiling applies again, not the 32-minute timeout step. + await setup.expectNextAttemptAfter(300_000, service); + await setup.expectAttemptAbortedAtDeadline(); + await setup.expectNextAttemptAfter(300_000, service); + } finally { + subscription.unsubscribe(); + await service.dispose(); + } + }, + 30_000, + ); + test.each(["repository metadata", "working tree"])( "ignores expired %s watcher callbacks after recovery", async (kind) => { @@ -1873,6 +1985,7 @@ describe("WorkspaceGitServiceImpl", () => { expect(subscription.repoRoot).toBeNull(); expect(subscribe).toHaveBeenCalledWith(plainCwd, expect.any(Function), { ignore: [join(plainCwd, ".git")], + signal: expect.any(AbortSignal), }); expect(vi.getTimerCount()).toBe(1); diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index 60c868f1b3..93b5982b36 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -123,6 +123,11 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30_000; // restart, which kills running agents. Back off, but keep trying. const WATCH_RECOVERY_MAX_DELAY_MS = 300_000; const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4; +// A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the +// next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore +// keep doubling the recovery delay past the ladder cap, up to an hour. +const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3_600_000; +const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7; // Auxiliary reads may reuse cached values within this window; snapshots do not expire on read. const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15_000; // Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it. @@ -574,6 +579,10 @@ interface WatchRecoveryState { // use (SMB/NFS, Docker virtiofs, some FUSE) resets the ladder on every // attempt and the backoff never engages. establishedAt: number | null; + // Setup attempts that hit WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS since the last accepted + // subscription. Reset on acceptance: finishing the startup scan in time is the proof that + // the next attempt is affordable. + setupTimeoutCount: number; } function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { @@ -1519,7 +1528,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { fallbackPolling: false, fallbackPollTimer: null, fallbackPollQuietTickCount: 0, - recovery: { attemptCount: 0, timer: null, establishedAt: null }, + recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 }, listeners: new Set(), closed: false, }; @@ -1549,9 +1558,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { let removeAbortListener = () => {}; let unsubscribePromise: Promise | null = null; let subscriptionPromise: Promise; + // Abandoning the race is not enough: the observer's startup scan would keep walking the + // tree after the deadline. Abort it so a timed-out attempt stops costing CPU. + const setupController = new AbortController(); try { subscriptionPromise = this.deps - .subscribe(watchPath, callback, options) + .subscribe(watchPath, callback, { ...options, signal: setupController.signal }) .finally(onSubscribeSettled); } catch (error) { onSubscribeSettled(); @@ -1570,12 +1582,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { const timeoutPromise = new Promise((_resolve, reject) => { timeout = setTimeout(() => { outcome = "expired"; - reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath)); + const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath); + setupController.abort(error); + reject(error); }, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS); }); const disposalPromise = new Promise((_resolve, reject) => { const rejectForDisposal = () => { outcome = "expired"; + setupController.abort(signal.reason); reject(signal.reason); }; if (signal.aborted) { @@ -1710,6 +1725,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { // `scheduleWorkingTreeWatchRecovery` only resets the ladder once this // one has survived long enough to prove itself durable. target.recovery.establishedAt = this.deps.now().getTime(); + target.recovery.setupTimeoutCount = 0; if (options?.replaceFallback && target.repoRoot !== null) { target.fallbackPolling = false; if (target.fallbackPollTimer) { @@ -1730,6 +1746,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { { err: error, cwd: target.cwd }, "Failed to start working tree watcher; using degraded polling", ); + this.noteWatchSetupFailure(target.recovery, error); if (!options?.replaceFallback) { this.startWorkingTreeWatchFallback(target, "watcher_setup_failed"); } @@ -1952,11 +1969,26 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { } recovery.establishedAt = null; recovery.attemptCount += 1; - return Math.min( + const ladderDelayMs = Math.min( WATCH_RECOVERY_BASE_DELAY_MS * 2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS), WATCH_RECOVERY_MAX_DELAY_MS, ); + if (recovery.setupTimeoutCount === 0) { + return ladderDelayMs; + } + const setupTimeoutDelayMs = Math.min( + WATCH_RECOVERY_BASE_DELAY_MS * + 2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS), + WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS, + ); + return Math.max(ladderDelayMs, setupTimeoutDelayMs); + } + + private noteWatchSetupFailure(recovery: WatchRecoveryState, error: unknown): void { + if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) { + recovery.setupTimeoutCount += 1; + } } private scheduleWorkingTreeWatchRecovery(target: WorkingTreeWatchTarget): void { @@ -2430,7 +2462,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { fallbackPolling: false, fallbackPollTimer: null, fallbackPollQuietTickCount: 0, - recovery: { attemptCount: 0, timer: null, establishedAt: null }, + recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 }, intervalId: null, fetchInFlight: false, bufferedFetchMetadataEvents: [], @@ -2580,6 +2612,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { // subscribe success alone, only record when this subscription was // established. target.recovery.establishedAt = this.deps.now().getTime(); + target.recovery.setupTimeoutCount = 0; if (options?.replaceFallback) { target.fallbackPolling = false; if (target.fallbackPollTimer) { @@ -2603,6 +2636,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { { err: error, repoGitRoot: target.repoGitRoot }, "Failed to start repository metadata watcher; using degraded polling", ); + this.noteWatchSetupFailure(target.recovery, error); if (!options?.replaceFallback) { this.startRepoMetadataFallback(target); } From d49991318f088623155231a1e293d4efc7b3cade Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:48:23 +0000 Subject: [PATCH 112/160] fix(server): see same-size edits saved in the tick a file was staged (#9854) The private index snapshot behind index and All changes comparisons was a fresh copy, newer than every entry, so Git skipped its same-timestamp content check and a same-size save made right after staging read as unchanged. The copy now keeps the source index's mtime, rounded down to the second. Closes #9827 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- packages/server/src/server/diff/git.test.ts | 63 ++++++++++++++++++++- packages/server/src/utils/checkout-git.ts | 9 +++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/packages/server/src/server/diff/git.test.ts b/packages/server/src/server/diff/git.test.ts index 5c77f80e45..d84214d7a2 100644 --- a/packages/server/src/server/diff/git.test.ts +++ b/packages/server/src/server/diff/git.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { mkdtemp, writeFile, rm, readFile, lstat } from "node:fs/promises"; +import { mkdtemp, writeFile, rm, readFile, lstat, utimes } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { expect, test } from "vitest"; @@ -107,6 +107,67 @@ test("supports empty trees, unborn HEAD, staged and unstaged comparisons", async } }); +test.each([ + { name: "index to working tree", base: { kind: "index" } as const }, + { + name: "commit to working tree with a file removed from the index", + base: { kind: "rev", rev: "HEAD" } as const, + }, +])("$name sees a same-size edit saved in the timestamp tick it was staged", async ({ base }) => { + const cwd = await mkdtemp(join(tmpdir(), "diff-racy-index-")); + const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const file = join(cwd, "x.ts"); + const indexPath = join(cwd, ".git", "index"); + const tick = new Date("2026-01-01T00:00:00Z"); + try { + git("init", "-b", "main"); + git("config", "user.email", "test@example.com"); + git("config", "user.name", "Test"); + // Only mtime, size, and inode tell this edit apart; ctime always moves. + git("config", "core.trustctime", "false"); + await writeFile(file, "const value = 1;\n"); + await writeFile(join(cwd, "y.ts"), "const kept = 1;\n"); + git("add", "."); + git("-c", "commit.gpgsign=false", "commit", "-m", "base"); + await writeFile(file, "const value = 2;\n"); + await utimes(file, tick, tick); + git("add", "x.ts"); + if (base.kind === "rev") { + git("-c", "commit.gpgsign=false", "commit", "-m", "staged"); + // A file on disk and in the base commit but absent from the index + // selects the private index for commit to working tree comparisons. + git("rm", "--cached", "y.ts"); + } + // The index is written in the tick the file was staged, and the file is + // saved again with the same size within that tick. + await utimes(indexPath, tick, tick); + await writeFile(file, "const value = 3;\n"); + await utimes(file, tick, tick); + expect(git("diff", "--name-only")).toBe("x.ts"); + const originalIndex = await readFile(indexPath); + const originalMtime = (await lstat(indexPath, { bigint: true })).mtimeNs; + + const comparison = await listComparison({ + cwd, + base, + head: { kind: "worktree" }, + highlight: false, + }); + expect(comparison.files.map((entry) => entry.entry.path)).toEqual(["x.ts"]); + const record = await readBody(comparison); + expect(record.body.hunks[0].lines).toEqual([ + { type: "header", content: "@@ -1 +1 @@" }, + { type: "remove", content: "const value = 2;" }, + { type: "add", content: "const value = 3;" }, + ]); + await comparison.close(); + expect(await readFile(indexPath)).toEqual(originalIndex); + expect((await lstat(indexPath, { bigint: true })).mtimeNs).toBe(originalMtime); + } finally { + await rm(cwd, { recursive: true, force: true }); + } +}); + test("lists oversized untracked files without treating their truncated contents as additions", async () => { const cwd = await mkdtemp(join(tmpdir(), "diff-large-file-")); const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index 2738f184d9..c817ed5e9b 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -6,6 +6,7 @@ import { stat as statFile, mkdtemp, copyFile, + utimes, realpath, access, rm, @@ -3665,6 +3666,12 @@ export async function prepareAllChangesIndex(cwd: string, baseRef: string) { // write-tree rewrites its index. A private snapshot prevents an index read from // invalidating the observation that requested it. +// +// Git re-reads a file whose stat matches its index entry only when the entry is +// not older than the index file ("racy git"). A fresh copy would be newer than +// every entry, so a same-size edit made in the tick the index was written would +// read as unchanged. The copy takes the source's mtime, read before copying and +// rounded down to the second, so it is never later than the source. export async function snapshotComparisonIndex(cwd: string) { const directory = await mkdtemp(resolve(tmpdir(), "paseo-comparison-index-")); const indexFile = resolve(directory, "index"); @@ -3676,7 +3683,9 @@ export async function snapshotComparisonIndex(cwd: string) { const source = resolveGitRevParsePath(cwd, index.stdout); if (!source) throw new Error("Git did not return an index path"); try { + const { atime, mtimeMs } = await statFile(source); await copyFile(source, indexFile); + await utimes(indexFile, atime, Math.floor(mtimeMs / 1000)); } catch (error) { if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error; await runGitCommand(["read-tree", "--empty"], { From a302e65c853b9a0773ef4cf37074ec9670e6b794 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:54:34 +0000 Subject: [PATCH 113/160] fix(omp): show model names with slashes and underscores in full (#9836) OMP model labels were built as `${provider}/${name}` and then cut at the last `/`, so a free-text name such as "... ~60-70 tok/s on 0.2.10, 52/56)" showed as "56)". Underscores were rewritten to spaces ("IQ3_S" -> "IQ3 S"), and a colon inside the name cut everything before it. Pi had the same bug, fixed in #9823. Move that label rule into a shared model-label module and use it for both providers: free-text names are kept, path-like names are shortened to their last segment, and a "Vendor: " prefix is dropped only when it is a prefix. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/providers/model-label.ts | 21 ++++++ .../server/agent/providers/omp/agent.test.ts | 66 +++++++++++++++++++ .../src/server/agent/providers/omp/agent.ts | 43 ++---------- .../agent/providers/omp/map-omp-model.test.ts | 2 +- .../agent/providers/omp/map-omp-model.ts | 3 +- .../src/server/agent/providers/pi/agent.ts | 24 +------ 6 files changed, 97 insertions(+), 62 deletions(-) create mode 100644 packages/server/src/server/agent/providers/model-label.ts diff --git a/packages/server/src/server/agent/providers/model-label.ts b/packages/server/src/server/agent/providers/model-label.ts new file mode 100644 index 0000000000..952a9957a9 --- /dev/null +++ b/packages/server/src/server/agent/providers/model-label.ts @@ -0,0 +1,21 @@ +// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a +// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept. +function stripVendorPrefix(label: string): string { + const vendorSeparatorIndex = label.indexOf(": "); + if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) { + return label; + } + return label.slice(vendorSeparatorIndex + 2).trim(); +} + +// The label Pi and OMP show for a model from their catalogs. A model name is either a path +// ("google/gemini_2.5-flash", as OpenRouter reports it) or free text that can contain slashes +// and underscores ("IQ3_S ... 52/56"). Only paths are shortened. +export function modelDisplayLabel(model: { id: string; name?: string }): string { + const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim(); + if (/\s/.test(text)) { + return stripVendorPrefix(text); + } + const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text; + return stripVendorPrefix(lastSegment.replace(/_+/g, " ")); +} diff --git a/packages/server/src/server/agent/providers/omp/agent.test.ts b/packages/server/src/server/agent/providers/omp/agent.test.ts index 832bd208a8..6201e25e66 100644 --- a/packages/server/src/server/agent/providers/omp/agent.test.ts +++ b/packages/server/src/server/agent/providers/omp/agent.test.ts @@ -1855,3 +1855,69 @@ test("closing OMP during image conversion rejects its pending start", async () = await session.close(); await rejected; }); + +describe("OMP catalog model labels", () => { + test.each([ + { + name: "keeps slashes and underscores inside a free-text model name", + model: { + provider: "llama-swap", + id: "s-q3fn(p-t)", + name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", + }, + label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)", + }, + { + name: "keeps a free-text name that ends in a slash-separated word", + model: { + provider: "llama-swap", + id: "ds-strata-6", + name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", + }, + label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)", + }, + { + name: "keeps a colon inside a free-text model name", + model: { + provider: "llama-swap", + id: "qwen3-tail", + name: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + label: "Qwen3 IQ3_S (tail skip: on, 52/56)", + }, + { + name: "keeps an OMP catalog name as it is", + model: { + provider: "openrouter", + id: "anthropic/claude-opus-4.1:batch", + name: "Claude Opus 4.1 (batch)", + }, + label: "Claude Opus 4.1 (batch)", + }, + { + name: "drops the vendor prefix from an upstream model name", + model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" }, + label: "GPT-5.5", + }, + { + name: "falls back to the last segment of a path-like id", + model: { provider: "pioneer", id: "canada-quant/glm_5.2" }, + label: "glm 5.2", + }, + ])("$name", async ({ model, label }) => { + const runtime = new FakeOmp(); + runtime.queueSessionSetup((session) => { + session.models = [model]; + }); + const client = new OmpAgentClient({ logger: createTestLogger(), runtime }); + + const catalog = await client.fetchCatalog({ + scope: "workspace", + cwd: "/workspace/project", + force: false, + }); + + expect(catalog.models.map((entry) => entry.label)).toEqual([label]); + expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`); + }); +}); diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index d10692ca6f..3d4cce0ff8 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -15,7 +15,6 @@ import { type AgentLaunchContext, type AgentMetadata, type AgentMode, - type AgentModelDefinition, type AgentPermissionRequest, type AgentPermissionResponse, type AgentProviderNotice, @@ -252,36 +251,6 @@ interface OmpSlashCommandInvocation { type AutoCompactMode = boolean | "toggle" | "unknown"; -function normalizeOmpModelLabel(label: string): string { - const normalizedLabel = label.trim().replace(/[_\s]+/g, " "); - const vendorSeparatorIndex = normalizedLabel.indexOf(": "); - if (vendorSeparatorIndex === -1) { - return normalizedLabel; - } - - return normalizedLabel.slice(vendorSeparatorIndex + 2).trim(); -} - -export function transformOmpModels(models: AgentModelDefinition[]): AgentModelDefinition[] { - return models.map((model) => { - if (!model.label.includes("/")) { - return model; - } - - const segments = model.label.split("/").filter((segment) => segment.length > 0); - const rawLabel = segments.at(-1); - if (!rawLabel) { - return model; - } - - return { - ...model, - label: normalizeOmpModelLabel(rawLabel), - description: model.description ?? model.label, - }; - }); -} - function isOmpThinkingLevel(value: string | null | undefined): value is OmpThinkingLevel { return ( value === "off" || @@ -2571,13 +2540,11 @@ export class OmpAgentClient implements AgentClient { }); if (!runtimeSession) throw new Error("OMP catalog runtime did not start"); const catalogSession = runtimeSession; - const models = transformOmpModels( - ( - await runProviderRefreshActivity(context, "get_available_models", () => - catalogSession.getAvailableModels(null), - ) - ).map((model) => mapOmpModel(model, this.provider)), - ); + const models = ( + await runProviderRefreshActivity(context, "get_available_models", () => + catalogSession.getAvailableModels(null), + ) + ).map((model) => mapOmpModel(model, this.provider)); return { models, modes: [...OMP_MODES] }; } finally { context?.signal.removeEventListener("abort", handleAbort); diff --git a/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts b/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts index da86a38ba7..b68fd74697 100644 --- a/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts +++ b/packages/server/src/server/agent/providers/omp/map-omp-model.test.ts @@ -164,7 +164,7 @@ describe("mapOmpModel thinking options", () => { expect(result.provider).toBe("omp"); expect(result.id).toBe("pioneer/canada-quant/glm-5.2"); - expect(result.label).toBe("pioneer/GLM-5.2"); + expect(result.label).toBe("GLM-5.2"); expect(result.metadata).toEqual({ provider: "pioneer", modelId: "canada-quant/glm-5.2" }); }); }); diff --git a/packages/server/src/server/agent/providers/omp/map-omp-model.ts b/packages/server/src/server/agent/providers/omp/map-omp-model.ts index 094b1adf35..69bcefed18 100644 --- a/packages/server/src/server/agent/providers/omp/map-omp-model.ts +++ b/packages/server/src/server/agent/providers/omp/map-omp-model.ts @@ -3,6 +3,7 @@ import type { AgentProvider, AgentSelectOption, } from "../../agent-sdk-types.js"; +import { modelDisplayLabel } from "../model-label.js"; import type { OmpModel, OmpThinkingLevel } from "./rpc-types.js"; export const DEFAULT_OMP_THINKING_LEVEL: OmpThinkingLevel = "medium"; @@ -43,7 +44,7 @@ export function mapOmpModel(model: OmpModel, provider: AgentProvider): AgentMode return { provider, id: `${model.provider}/${model.id}`, - label: `${model.provider}/${model.name ?? model.id}`, + label: modelDisplayLabel(model), description: `${model.provider}/${model.id}`, metadata: { provider: model.provider, diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index b5a887c112..b158882269 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -83,6 +83,7 @@ import { listPiImportableSessions, readPiImportSessionConfig, } from "./session-descriptor.js"; +import { modelDisplayLabel } from "../model-label.js"; import type { PiRuntime, PiRuntimeSession, PiStartSessionInput } from "./runtime.js"; import type { PiAgentSessionEvent, @@ -313,27 +314,6 @@ interface PiSlashCommandInvocation { type AutoCompactMode = boolean | "toggle" | "unknown"; -// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a -// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept. -function stripVendorPrefix(label: string): string { - const vendorSeparatorIndex = label.indexOf(": "); - if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) { - return label; - } - return label.slice(vendorSeparatorIndex + 2).trim(); -} - -// A Pi model name is either a path ("google/gemini_2.5-flash", as OpenRouter reports it) or -// free text that can contain slashes and underscores ("IQ3_S ... 52/56"). Only shorten paths. -function piModelLabel(model: Pick): string { - const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim(); - if (/\s/.test(text)) { - return stripVendorPrefix(text); - } - const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text; - return stripVendorPrefix(lastSegment.replace(/_+/g, " ")); -} - function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel { return ( value === "off" || @@ -1157,7 +1137,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti return { provider, id: `${model.provider}/${model.id}`, - label: piModelLabel(model), + label: modelDisplayLabel(model), description: `${model.provider}/${model.id}`, metadata: { provider: model.provider, From 3d30aaec426d8b1ecc76214c41e2be0ab194f173 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Mon, 16 Nov 2026 17:10:14 +0700 Subject: [PATCH 114/160] Allow plugins to append agent instructions (#9781) * feat(plugins): append agent instructions on session open Recompute plugin instructions for each launch so changes apply on reopen without changing saved agent configuration. * test(providers): verify plugin instructions on reopen * fix(codex): refresh instructions from restored collaboration mode A resumed thread can retain its prior collaboration instructions when the mode catalog is unavailable. Rebuild those instructions from the current launch before the next turn. * fix(plugins): keep launch instructions out of agent records Provider persistence handles can contain launch configuration. Strip transient instructions before saving and projecting handles. * fix(codex): preserve built-in collaboration instructions Pass agent instructions through the thread configuration so Codex can apply its own Plan and Default mode instructions. * fix(opencode): preserve instructions when reading history History-only opens do not apply current plugin contributions, so they must not clear the native session instruction entry. * fix(codex): retain instructions after rewinding A rewind forks the native thread, which does not inherit its parent launch instructions. Pass the current instructions to the fork. * Deliver updated instructions to Codex threads * Cover Codex snapshots after rewind * Persist provider state when reopening agents * Limit resume persistence refresh to providers that need it --- packages/plugin/src/server/lifecycle.ts | 2 + .../src/server/agent/agent-manager.test.ts | 108 +++++++ .../server/src/server/agent/agent-manager.ts | 22 +- .../server/agent/agent-projections.test.ts | 5 + .../src/server/agent/agent-projections.ts | 3 + .../src/server/agent/agent-sdk-types.ts | 6 + .../src/server/agent/plugin-provider.ts | 9 +- .../src/server/agent/provider-registry.ts | 3 + .../agent/providers/claude/agent.env.test.ts | 50 ++++ .../server/agent/providers/claude/agent.ts | 12 +- .../codex-app-server-agent.local.e2e.test.ts | 93 +++++- .../providers/codex-app-server-agent.test.ts | 282 +++++++++++++++++- .../agent/providers/codex-app-server-agent.ts | 108 +++++-- .../providers/codex/instruction-snapshot.ts | 69 +++++ .../server/agent/providers/codex/rewind.ts | 2 + .../codex/test-utils/fake-app-server.ts | 3 +- .../src/server/agent/providers/omp/agent.ts | 7 +- .../server/agent/providers/opencode-agent.ts | 4 + .../providers/opencode/runtime-client.ts | 4 +- .../opencode/test-utils/v2-harness.ts | 13 +- .../agent/providers/opencode/v2/agent.test.ts | 48 +++ .../agent/providers/opencode/v2/agent.ts | 13 +- .../agent/providers/opencode/v2/session.ts | 11 +- .../server/agent/providers/pi/agent.test.ts | 10 +- .../src/server/agent/providers/pi/agent.ts | 9 +- .../server/src/server/agent/system-prompt.ts | 12 + .../src/server/plugins/lifecycle.e2e.test.ts | 39 ++- .../server/plugins/lifecycle/handlers.test.ts | 43 ++- .../src/server/plugins/lifecycle/index.ts | 15 +- .../agent-configuration/index.server.ts | 4 + public-docs/plugins/hooks.md | 49 +-- public-docs/plugins/hooks.zh-CN.md | 49 +-- 32 files changed, 1008 insertions(+), 99 deletions(-) create mode 100644 packages/server/src/server/agent/providers/codex/instruction-snapshot.ts diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index f1ee1a9790..cedc2e3019 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -88,6 +88,8 @@ export interface PluginSessionOpenRequest { readonly background: boolean; readonly labels: Readonly>; readonly metadata: Readonly>; + /** Instructions appended for this open; not saved on the agent. */ + appendSystemPrompt?: string[]; tools: AgentToolDefinition[]; env: Record; mcpServers: NonNullable; diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index a27ad9013e..2525b42b27 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -674,6 +674,48 @@ async function startAndSteerThroughManager( return { manager, agentId: agent.id, workdir }; } +test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-")); + const harness = new V2Harness(); + harness.info.location.directory = workdir; + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new OpenCodeV2AgentClient({ logger, runtime: harness.runtime }); + const manager = new AgentManager({ + clients: { opencode: client }, + registry: storage, + logger, + appendSystemPrompt: "Daemon instruction", + pluginLifecycle: { + emit: () => {}, + before: async (name, request) => + name === "agent.open.before" + ? { ...request, appendSystemPrompt: ["Plugin instruction"] } + : request, + }, + }); + const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + expect(harness.instructions.get("paseo")).toBe("Daemon instruction\n\nPlugin instruction"); + await manager.flush(); + const record = await storage.get(agent.id); + expect(record?.persistence?.metadata).not.toHaveProperty("pluginAppendSystemPrompt"); + expect(record?.persistence?.metadata).not.toHaveProperty("daemonAppendSystemPrompt"); + const live = manager.getAgent(agent.id)!; + expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty( + "pluginAppendSystemPrompt", + ); + expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty( + "daemonAppendSystemPrompt", + ); + } finally { + await manager.closeAgent(agent.id); + await client.shutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("stops an OpenCode execution already active when its conversation is reopened", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-opencode-resume-")); onTestFinished(() => rmSync(workdir, { recursive: true, force: true })); @@ -14826,3 +14868,69 @@ test("an idle-only prompt rejects a busy recipient before changing its mode", as rmSync(workdir, { recursive: true, force: true }); } }); + +test("plugin instructions are recomputed for each launch without changing saved config", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-prompt-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new TestAgentClient(); + let additions = ["Plugin one", "Plugin two"]; + const manager = new AgentManager({ + clients: { codex: client }, + registry: storage, + logger, + appendSystemPrompt: "Daemon", + pluginLifecycle: { + emit: () => {}, + before: async (name, request) => + name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request, + }, + }); + const snapshot = await manager.createAgent( + { provider: "codex", cwd: workdir, systemPrompt: "Saved" }, + undefined, + { workspaceId: undefined }, + ); + expect(client.createdConfigs[0]).toMatchObject({ + systemPrompt: "Saved", + daemonAppendSystemPrompt: "Daemon", + pluginAppendSystemPrompt: ["Plugin one", "Plugin two"], + }); + expect(snapshot.config.systemPrompt).toBe("Saved"); + expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved"); + const handle: AgentPersistenceHandle = { + provider: "codex", + sessionId: "prompt-session", + metadata: { provider: "codex", cwd: workdir, systemPrompt: "Saved" }, + }; + await manager.closeAgent(snapshot.id); + await manager.resumeAgentFromPersistence( + handle, + { cwd: workdir, systemPrompt: "Saved" }, + snapshot.id, + ); + expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual([ + "Plugin one", + "Plugin two", + ]); + additions = ["Changed"]; + await manager.closeAgent(snapshot.id); + await manager.resumeAgentFromPersistence( + handle, + { cwd: workdir, systemPrompt: "Saved" }, + snapshot.id, + ); + expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Changed"]); + additions = ["Refreshed"]; + await manager.reloadAgentSession(snapshot.id); + expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Refreshed"]); + additions = []; + await manager.closeAgent(snapshot.id); + await manager.resumeAgentFromPersistence( + handle, + { cwd: workdir, systemPrompt: "Saved" }, + snapshot.id, + ); + expect(client.resumeOverrides.at(-1)?.systemPrompt).toBe("Saved"); + expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon"); + expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved"); +}); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 096bd3aa65..cfd43b2cb5 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -634,7 +634,12 @@ function normalizePersistenceForConfig( if (!handle) { return null; } - const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {}; + const { + mcpServers: _launchMcpServers, + pluginAppendSystemPrompt: _pluginAppendSystemPrompt, + daemonAppendSystemPrompt: _daemonAppendSystemPrompt, + ...metadata + } = handle.metadata ?? {}; return { ...handle, metadata: { @@ -1731,7 +1736,10 @@ export class AgentManager { ...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}), workspaceId, launchEnv, - persistence: handle, + persistence: + purpose === "interactive" && session.persistenceUpdatedOnResume + ? (session.describePersistence() ?? handle) + : handle, restoring: true, }); } @@ -6181,6 +6189,7 @@ export class AgentManager { // A plugin changing during this open must still make the resulting session stale. const generation = this.sessionOpenGeneration; this.detachPluginTools(agentId); + let appendSystemPrompt: string[] | undefined; let mcpServers: AgentSessionConfig["mcpServers"]; let mcpServerOwners: Record | undefined; if (this.pluginLifecycle) { @@ -6202,12 +6211,14 @@ export class AgentManager { env = transformed.env; if (request.purpose === "interactive") { this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]); + appendSystemPrompt = transformed.appendSystemPrompt; mcpServers = transformed.mcpServers; mcpServerOwners = transformed.mcpServerOwners; } } const context: AgentLaunchContext = { agentId, + ...pluginPromptContext(appendSystemPrompt), mcpServers, mcpServerOwners, env: { @@ -6254,6 +6265,7 @@ export class AgentManager { throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`); } } + launchConfig = { ...launchConfig, pluginAppendSystemPrompt: launchContext.appendSystemPrompt }; const merged = Object.keys(launchContext.mcpServers ?? {}).length > 0 ? { @@ -6391,3 +6403,9 @@ export function commandMayHaveChangedExternalState(command: string): boolean { /\bgit\s+fetch\b/.test(normalized) ); } + +function pluginPromptContext( + appendSystemPrompt: string[] | undefined, +): Pick { + return appendSystemPrompt?.length ? { appendSystemPrompt } : {}; +} diff --git a/packages/server/src/server/agent/agent-projections.test.ts b/packages/server/src/server/agent/agent-projections.test.ts index 5e4fa77eab..5be66c4b61 100644 --- a/packages/server/src/server/agent/agent-projections.test.ts +++ b/packages/server/src/server/agent/agent-projections.test.ts @@ -337,6 +337,7 @@ describe("toAgentPayload", () => { nativeHandle: { id: "native" } as unknown, metadata: { restored: new Date("2025-03-01T00:00:00.000Z"), + paseoInstructionReceipt: { threadId: "persist-99", digest: "internal-digest" }, empty: {}, mcpServers: { hub: { @@ -387,6 +388,8 @@ describe("toAgentPayload", () => { sessionId: "persist-stored", metadata: { conversationId: "conversation-stored", + pluginAppendSystemPrompt: ["plugin instruction"], + daemonAppendSystemPrompt: "daemon instruction", mcpServers: { hub: { type: "http", @@ -402,6 +405,8 @@ describe("toAgentPayload", () => { expect(record.persistence?.metadata).toEqual({ conversationId: "conversation-stored", + pluginAppendSystemPrompt: ["plugin instruction"], + daemonAppendSystemPrompt: "daemon instruction", mcpServers: { hub: { type: "http", diff --git a/packages/server/src/server/agent/agent-projections.ts b/packages/server/src/server/agent/agent-projections.ts index 09d9461858..60d7f3ba4e 100644 --- a/packages/server/src/server/agent/agent-projections.ts +++ b/packages/server/src/server/agent/agent-projections.ts @@ -495,6 +495,9 @@ function projectPersistenceHandleForWire( return projected; } delete projected.metadata.mcpServers; + delete projected.metadata.pluginAppendSystemPrompt; + delete projected.metadata.daemonAppendSystemPrompt; + delete projected.metadata.paseoInstructionReceipt; if (Object.keys(projected.metadata).length === 0) { delete projected.metadata; } diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 0267876d0d..1f081885ce 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -621,6 +621,8 @@ export interface AgentSessionConfig { * persisted into agent config so daemon setting changes apply cleanly. */ daemonAppendSystemPrompt?: string; + /** Plugin instructions for this launch; never persisted. */ + pluginAppendSystemPrompt?: string[]; modeId?: string; model?: string; thinkingOptionId?: string; @@ -636,6 +638,8 @@ export interface AgentSessionConfig { } export interface AgentLaunchContext { + /** Launch-only instructions contributed by plugins. */ + appendSystemPrompt?: string[]; /** Launch-only plugin MCP servers and their owners; never persisted. */ mcpServers?: Record; mcpServerOwners?: Record; @@ -688,6 +692,8 @@ export interface AgentUsageSession { } export interface AgentSession { + /** Persist the session's current handle immediately after an interactive resume. */ + readonly persistenceUpdatedOnResume?: boolean; usageSession?(): AgentUsageSession | null; readonly provider: AgentProvider; readonly id: string | null; diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 480d9deec7..3b64f7c9f9 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1949,7 +1949,11 @@ function mapSessionConfig( return { cwd: config.cwd, env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }), - systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt), + systemPrompt: combineSystemPrompts( + config.systemPrompt, + config.daemonAppendSystemPrompt, + ...(config.pluginAppendSystemPrompt ?? []), + ), mcpServers: { ...config.mcpServers }, toolPolicy: config.toolPolicy ? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) } @@ -1968,8 +1972,9 @@ function mapSessionConfig( function combineSystemPrompts( systemPrompt: string | undefined, daemonPrompt: string | undefined, + ...pluginPrompts: string[] ): string | undefined { - const parts = [systemPrompt, daemonPrompt].filter( + const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter( (value): value is string => typeof value === "string" && value.trim().length > 0, ); return parts.length > 0 ? parts.join("\n\n") : undefined; diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index 2449b9a90b..b671eb0fab 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -448,6 +448,9 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession get initialTimeline() { return inner.initialTimeline; }, + get persistenceUpdatedOnResume() { + return inner.persistenceUpdatedOnResume; + }, get controls() { return inner.controls; }, diff --git a/packages/server/src/server/agent/providers/claude/agent.env.test.ts b/packages/server/src/server/agent/providers/claude/agent.env.test.ts index 6d268e932c..b4db648b9f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.env.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.env.test.ts @@ -153,6 +153,56 @@ describe("Claude SDK env", () => { } }); + test("resume uses current plugin instructions and excludes them from persistence", async () => { + const prompts: unknown[] = []; + const queryFactory = ({ options }: ClaudeQueryInput) => { + prompts.push(options.systemPrompt); + return createQueryMock([ + { + type: "system", + subtype: "init", + session_id: "persisted-session", + permissionMode: "default", + model: "opus", + }, + { type: "assistant", message: { content: "done" } }, + { + type: "result", + subtype: "success", + usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 }, + total_cost_usd: 0, + }, + ]); + }; + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const first = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + pluginAppendSystemPrompt: ["Plugin instructions"], + }); + await first.run("first"); + const handle = first.describePersistence()!; + expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt"); + await first.close(); + const resumed = await client.resumeSession(handle, { + cwd: process.cwd(), + pluginAppendSystemPrompt: undefined, + }); + try { + await resumed.run("after disable"); + expect(prompts).toEqual([ + { type: "preset", preset: "claude_code", append: "Plugin instructions" }, + { type: "preset", preset: "claude_code", append: "" }, + ]); + } finally { + await resumed.close(); + } + }); + test("forwards launch-context env through Claude resume env", async () => { let capturedEnv: Record | undefined; const launchContext: AgentLaunchContext = { diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 8bafb4e1e1..c33a2e6593 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -3044,7 +3044,11 @@ class ClaudeAgentSession implements AgentSession { if (!this.claudeSessionId) { return null; } - const { providerOptions: _providerOptions, ...persistedConfig } = this.config; + const { + providerOptions: _providerOptions, + pluginAppendSystemPrompt: _pluginAppendSystemPrompt, + ...persistedConfig + } = this.config; this.persistence = { provider: "claude", sessionId: this.claudeSessionId, @@ -3712,7 +3716,11 @@ class ClaudeAgentSession implements AgentSession { private buildAppendedSystemPrompt(): string { return ( - composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt) ?? "" + composeSystemPromptParts( + this.config.systemPrompt, + this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), + ) ?? "" ); } diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts index 77c36b4fd0..236dfe469a 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.local.e2e.test.ts @@ -22,6 +22,18 @@ function isCodexInstalled(): boolean { } } +function supportsInstructionSnapshots(): boolean { + try { + const match = execFileSync("codex", ["--version"], { encoding: "utf8" }).match( + /(\d+)\.(\d+)\.(\d+)/, + ); + if (!match) return false; + return Number(match[1]) > 0 || Number(match[2]) >= 121; + } catch { + return false; + } +} + function sse(events: unknown[]): string { return events .map((event) => { @@ -133,7 +145,7 @@ async function startMockResponsesServer(sequence: string[]): Promise<{ }> { const requestBodies: string[] = []; let index = 0; - const server = createServer((req, res) => { + const server = createServer({ maxHeaderSize: 1024 * 1024 }, (req, res) => { const chunks: Buffer[] = []; req.on("data", (chunk) => chunks.push(Buffer.from(chunk))); req.on("end", () => { @@ -221,6 +233,85 @@ function waitForEvent(params: { } describe("Codex app-server provider (local e2e)", () => { + test.runIf(supportsInstructionSnapshots())( + "delivers changed and removed instructions to the model across process restarts", + async () => { + const artifactDir = path.resolve(process.cwd(), "../../.artifacts"); + mkdirSync(artifactDir, { recursive: true }); + const cwd = mkdtempSync(path.join(artifactDir, "codex-snapshot-cwd-")); + const codexHome = mkdtempSync(path.join(artifactDir, "codex-snapshot-home-")); + const server = await startMockResponsesServer([]); + const client = new CodexAppServerAgentClient(createTestLogger()); + const base = { provider: "codex" as const, cwd, modeId: "auto", model: "mock-model" }; + const launch = { env: { CODEX_HOME: codexHome } }; + const run = async (session: Awaited>) => { + const finished = waitForEvent({ + session, + timeoutMs: 20_000, + label: "turn completion", + predicate: ( + event, + ): event is Extract< + AgentStreamEvent, + { type: "turn_completed" | "turn_failed" | "turn_canceled" } + > => + event.type === "turn_completed" || + event.type === "turn_failed" || + event.type === "turn_canceled", + }); + await session.startTurn("continue"); + const result = await finished; + if (result.type !== "turn_completed") throw new Error(JSON.stringify(result)); + const handle = session.describePersistence(); + if (!handle) throw new Error("Expected persisted Codex thread"); + await session.close(); + return handle; + }; + try { + writeMockCodexConfig(codexHome, server.url); + let handle = await run( + await client.createSession( + { ...base, pluginAppendSystemPrompt: ["old snapshot"] }, + launch, + ), + ); + expect(server.requestBodies.at(-1)).toContain("old snapshot"); + expect(server.requestBodies.at(-1)).not.toContain("paseo_instruction_snapshot"); + handle = await run( + await client.resumeSession( + handle, + { ...base, pluginAppendSystemPrompt: ["new snapshot"] }, + launch, + ), + ); + expect(server.requestBodies.at(-1)).toContain("new snapshot"); + expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2); + handle = await run( + await client.resumeSession( + handle, + { ...base, pluginAppendSystemPrompt: ["new snapshot"] }, + launch, + ), + ); + expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2); + await run( + await client.resumeSession( + handle, + { ...base, pluginAppendSystemPrompt: undefined }, + launch, + ), + ); + expect(server.requestBodies.at(-1)).toContain('\\"instructions\\":\\"\\"'); + expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(4); + } finally { + await server.close(); + rmSync(cwd, { recursive: true, force: true }); + rmSync(codexHome, { recursive: true, force: true }); + } + }, + 60_000, + ); + test.runIf(isCodexInstalled())( "concurrent import scans initialize successfully in a fresh shared Codex home", async () => { diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 0b8ca8ea5a..c537a50d33 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -7,6 +7,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { PassThrough } from "node:stream"; import { fileURLToPath } from "node:url"; +import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js"; import type { AgentClient, @@ -100,6 +101,7 @@ import { import { createTestLogger } from "../../../test-utils/test-logger.js"; import { asInternals as castInternals, createStub } from "../../test-utils/class-mocks.js"; import { AgentManager } from "../agent-manager.js"; +import { AgentStorage } from "../agent-storage.js"; import { buildProviderRegistry } from "../provider-registry.js"; interface CollaborationModeRecord { @@ -173,6 +175,9 @@ function createSession( ) as CodexTestSession; session.connectionState = "connected"; session.currentThreadId = "test-thread"; + castInternals<{ instructionSnapshot: { recordNewThread(id: string): void } }>( + session, + ).instructionSnapshot.recordNewThread("test-thread"); session.activeForegroundTurnId = "test-turn"; return session; } @@ -683,7 +688,7 @@ function codexAgentItem(text: string) { // An AgentManager over a real Codex provider whose every spawn gets a fresh fake // app-server serving `threads` from thread/read. -function createReopenableCodexAgent(threads: Record) { +function createReopenableCodexAgent(threads: Record, registry?: AgentStorage) { const appServers: FakeCodexAppServer[] = []; const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, { appServerProcess: createFakeCodexAppServerProcess(() => { @@ -715,7 +720,11 @@ function createReopenableCodexAgent(threads: Record) { }, resumeSession: (...args) => provider.resumeSession(...args), }; - const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() }); + const manager = new AgentManager({ + clients: { codex: client }, + registry, + logger: createTestLogger(), + }); const agentId = "00000000-0000-4000-8000-000000000001"; const handle = { provider: "codex", sessionId: "saved-thread" }; const config = createConfig({ cwd: process.cwd() }); @@ -728,6 +737,9 @@ function createReopenableCodexAgent(threads: Record) { return { manager, agentId, + handle, + config, + appServers, latestAppServer: () => appServers[appServers.length - 1], threadMethods: (index: number) => appServers[index] @@ -1406,6 +1418,216 @@ describe("Codex app-server provider", () => { } }); + test("reopening drops disabled plugin instructions and starts with fresh collaboration settings", async () => { + const modes = { + data: [ + { + name: "Code", + mode: "default", + model: null, + reasoning_effort: null, + }, + ], + }; + const firstServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes }); + const first = await createProviderWithFakeAppServer(firstServer).createSession( + createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }), + ); + await first.startTurn("first"); + const firstTurn = await firstServer.waitForTurnStart(); + expect( + firstServer.requests().find((request) => request.method === "thread/start")?.params, + ).toMatchObject({ developerInstructions: "Plugin instructions" }); + expect(firstTurn).toMatchObject({ + collaborationMode: { + settings: { developer_instructions: null }, + }, + }); + const started = waitForNextEvent(first, "thread_started"); + firstServer.startsTurn({ threadId: "thread-1" }); + await started; + const handle = first.describePersistence()!; + expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt"); + await first.close(); + + const secondServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes }); + const resumed = await createProviderWithFakeAppServer(secondServer).resumeSession(handle, { + pluginAppendSystemPrompt: undefined, + }); + try { + const resume = secondServer.requests().find((request) => request.method === "thread/resume"); + expect(resume?.params).not.toHaveProperty("developerInstructions"); + await resumed.startTurn("after disable"); + const secondTurn = await secondServer.waitForTurnStart(); + expect(secondTurn).not.toHaveProperty("developerInstructions"); + expect(secondTurn).toMatchObject({ + collaborationMode: { settings: { developer_instructions: null } }, + }); + firstServer.assertNoErrors(); + secondServer.assertNoErrors(); + } finally { + await resumed.close(); + } + }); + + test("reopen injects current instructions once, including an explicit empty snapshot", async () => { + const handlers = { + initialize: () => ({ userAgent: "codex/0.165.0" }), + "thread/inject_items": () => ({}), + }; + const firstServer = createFakeCodexAppServer(handlers); + const first = await createProviderWithFakeAppServer(firstServer).createSession( + createConfig({ pluginAppendSystemPrompt: ["Old plugin"] }), + ); + await first.startTurn("first"); + const started = waitForNextEvent(first, "thread_started"); + firstServer.startsTurn({ threadId: "thread-1" }); + await started; + expect( + firstServer.requests().filter((request) => request.method === "thread/inject_items"), + ).toEqual([]); + const original = first.describePersistence()!; + expect(original.metadata).toHaveProperty("paseoInstructionReceipt"); + await first.close(); + + const changedServer = createFakeCodexAppServer(handlers); + const changed = await createProviderWithFakeAppServer(changedServer).resumeSession(original, { + pluginAppendSystemPrompt: ["New plugin"], + }); + const injected = changedServer + .requests() + .filter((request) => request.method === "thread/inject_items"); + expect(injected).toHaveLength(1); + expect(JSON.stringify(injected[0]?.params)).toContain("New plugin"); + const changedHandle = changed.describePersistence()!; + expect(changedHandle.metadata?.paseoInstructionReceipt).not.toEqual( + original.metadata?.paseoInstructionReceipt, + ); + await changed.close(); + + const sameServer = createFakeCodexAppServer(handlers); + const same = await createProviderWithFakeAppServer(sameServer).resumeSession(changedHandle, { + pluginAppendSystemPrompt: ["New plugin"], + }); + expect( + sameServer.requests().filter((request) => request.method === "thread/inject_items"), + ).toEqual([]); + await same.close(); + + const emptyServer = createFakeCodexAppServer(handlers); + const empty = await createProviderWithFakeAppServer(emptyServer).resumeSession(changedHandle, { + pluginAppendSystemPrompt: undefined, + }); + const removal = emptyServer + .requests() + .filter((request) => request.method === "thread/inject_items"); + expect(removal).toHaveLength(1); + expect(JSON.stringify(removal[0]?.params)).toContain('\\"instructions\\":\\"\\"'); + await empty.close(); + }); + + test("requires a compatible Codex version before creating a thread with plugin instructions", async () => { + const appServer = createFakeCodexAppServer({ + initialize: () => ({ userAgent: "codex/0.120.0" }), + }); + await expect( + createProviderWithFakeAppServer(appServer).createSession( + createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }), + ), + ).rejects.toThrow("Update Codex to 0.121.0 or newer"); + }); + + test("retries an instruction snapshot when injection fails", async () => { + const snapshot = new CodexInstructionSnapshot("current", undefined); + const request = vi + .fn() + .mockRejectedValueOnce(new Error("connection lost")) + .mockResolvedValue({}); + await expect(snapshot.apply("thread-1", request, true)).rejects.toThrow("connection lost"); + expect(snapshot.describe("thread-1")).toBeUndefined(); + await snapshot.apply("thread-1", request, true); + expect(snapshot.describe("thread-1")).toEqual({ + threadId: "thread-1", + digest: expect.any(String), + }); + await snapshot.apply("thread-1", request, true); + expect(request).toHaveBeenCalledTimes(2); + }); + + test("keeps built-in Plan instructions while sending plugin instructions to the thread", async () => { + const appServer = createFakeCodexAppServer({ + "collaborationMode/list": () => ({ + data: [ + { name: "Plan", mode: "plan", model: null, reasoning_effort: "medium" }, + { name: "Default", mode: "default", model: null, reasoning_effort: null }, + ], + }), + }); + const session = await createProviderWithFakeAppServer(appServer).createSession( + createConfig({ + pluginAppendSystemPrompt: ["Plugin instructions"], + providerOptions: { plan_mode: true }, + }), + ); + try { + await session.startTurn("make a plan"); + const start = appServer.requests().find((request) => request.method === "thread/start"); + expect(start?.params).toMatchObject({ developerInstructions: "Plugin instructions" }); + expect(await appServer.waitForTurnStart()).toMatchObject({ + collaborationMode: { mode: "plan", settings: { developer_instructions: null } }, + }); + expect( + appServer.requests().find((request) => request.method === "turn/start")?.params, + ).not.toHaveProperty("developerInstructions"); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }); + + test.each([ + { instructions: undefined, expected: undefined }, + { instructions: ["Current plugin"], expected: "Current plugin" }, + ])( + "rebuilds restored instructions with an unavailable collaboration catalog: $expected", + async ({ instructions, expected }) => { + const appServer = createFakeCodexAppServer({ + "collaborationMode/list": () => ({ data: [] }), + "thread/resume": () => ({ + thread: { id: "saved-thread" }, + collaborationMode: { + mode: "default", + settings: { + model: "gpt-5.4", + reasoning_effort: "medium", + developer_instructions: "Old plugin", + }, + }, + }), + }); + const session = await createProviderWithFakeAppServer(appServer).resumeSession( + { sessionId: "saved-thread" }, + { pluginAppendSystemPrompt: instructions }, + ); + try { + const resume = appServer.requests().find((request) => request.method === "thread/resume"); + if (expected) expect(resume?.params).toMatchObject({ developerInstructions: expected }); + else expect(resume?.params).not.toHaveProperty("developerInstructions"); + await session.startTurn("after reopen"); + const turn = await appServer.waitForTurnStart(); + expect(turn).toMatchObject({ + collaborationMode: { + mode: "default", + settings: { model: "gpt-5.4", developer_instructions: null }, + }, + }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }, + ); + test("keeps the default effort when a session without one is resumed after a restart", async () => { const beforeRestart = createFakeCodexAppServer(); const firstSession = await createProviderWithFakeAppServer(beforeRestart).createSession( @@ -2285,7 +2507,12 @@ describe("Codex app-server provider", () => { ]); // Background terminal observation is independent of conversation history loading. const historyMethods = (index: number) => - codex.threadMethods(index).filter((method) => method !== "thread/backgroundTerminals/list"); + codex + .threadMethods(index) + .filter( + (method) => + method !== "thread/backgroundTerminals/list" && method !== "thread/inject_items", + ); expect(historyMethods(0)).toEqual([ "thread/loaded/list", "thread/resume", @@ -2299,6 +2526,34 @@ describe("Codex app-server provider", () => { } }); + test("persists an acknowledged instruction snapshot before a turn on repeated opens", async () => { + const artifactDir = path.resolve(process.cwd(), "../../.artifacts"); + mkdirSync(artifactDir, { recursive: true }); + const dir = await mkdtemp(path.join(artifactDir, "codex-receipt-")); + const storage = new AgentStorage(dir, createTestLogger()); + const codex = createReopenableCodexAgent({}, storage); + try { + let handle = codex.handle; + for (let i = 0; i < 3; i++) { + await codex.manager.resumeAgentFromPersistence(handle, codex.config, codex.agentId); + await storage.flush(); + const saved = await storage.get(codex.agentId); + expect(saved?.persistence?.metadata?.paseoInstructionReceipt).toEqual(expect.any(Object)); + handle = saved!.persistence!; + await codex.manager.closeAgent(codex.agentId); + } + expect( + codex.appServers + .flatMap((server) => server.requests()) + .filter((request) => request.method === "thread/inject_items"), + ).toHaveLength(1); + } finally { + if (codex.manager.getAgent(codex.agentId)) await codex.manager.closeAgent(codex.agentId); + await storage.flush(); + rmSync(dir, { recursive: true, force: true }); + } + }); + test("rewinds an agent reopened without reading its Codex history", async () => { const firstTurn = { id: "turn-1", @@ -2818,6 +3073,9 @@ describe("Codex app-server provider", () => { const session = new CodexAppServerAgentSession( createConfig({ cwd: "/workspace/project", + systemPrompt: "Agent instructions", + daemonAppendSystemPrompt: "Daemon instructions", + pluginAppendSystemPrompt: ["Plugin instructions"], mcpServers: { paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" }, }, @@ -2849,6 +3107,24 @@ describe("Codex app-server provider", () => { await session.revertConversation({ messageId: "codex-first" }); + const forkRequest = appServer.requests().find((request) => request.method === "thread/fork"); + expect(forkRequest?.params).toMatchObject({ + developerInstructions: "Agent instructions\n\nDaemon instructions\n\nPlugin instructions", + }); + const rewindRequests = appServer + .requests() + .filter((request) => + ["thread/fork", "thread/rollback", "thread/inject_items"].includes( + String(request.method), + ), + ); + expect(rewindRequests.map((request) => request.method)).toEqual( + historyMode === "legacy" + ? ["thread/fork", "thread/rollback", "thread/inject_items"] + : ["thread/fork", "thread/inject_items"], + ); + expect(rewindRequests.at(-1)?.params).toMatchObject({ threadId: "forked-thread" }); + expect(JSON.stringify(rewindRequests.at(-1)?.params)).toContain("Plugin instructions"); const forkConfigs = appServer .requests() .filter((request) => request.method === "thread/fork") diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index bb7faab9e0..de835eca49 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -55,7 +55,8 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { z } from "zod"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; -import { composeSystemPromptParts } from "../system-prompt.js"; +import { composeAgentSystemPrompt } from "../system-prompt.js"; +import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js"; import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js"; import { fileChangesToPreview, @@ -3591,9 +3592,12 @@ interface ConsumedRootCompaction { export class CodexAppServerAgentSession implements AgentSession { readonly provider = CODEX_PROVIDER; readonly capabilities = CODEX_APP_SERVER_CAPABILITIES; + readonly persistenceUpdatedOnResume = true; private readonly logger: Logger; private readonly config: AgentSessionConfig; + private readonly instructionSnapshot: CodexInstructionSnapshot; + private supportsInstructionSnapshots = false; private readonly asyncQuestions: CodexAsyncQuestions; private readonly codexHome: string; private currentMode: string; @@ -3706,6 +3710,13 @@ export class CodexAppServerAgentSession implements AgentSession { reasoning_effort?: string | null; developer_instructions?: string | null; }> = []; + private restoredCollaborationMode: { + name: string; + mode: string; + model: string; + reasoning_effort: string | null; + developer_instructions?: never; + } | null = null; private resolvedCollaborationMode: { mode: string; settings: Record; @@ -3751,6 +3762,10 @@ export class CodexAppServerAgentSession implements AgentSession { this.providerOptions = validateProviderOptions("codex", CodexProviderOptionsSchema, config.providerOptions) ?? {}; this.config = config; + this.instructionSnapshot = new CodexInstructionSnapshot( + composeAgentSystemPrompt(config), + resumeHandle?.metadata?.paseoInstructionReceipt, + ); this.harnessEnvironment = deps.environment ?? buildCodexAppServerEnv(); this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions); this.codexHome = deps.codexHome ?? resolveCodexHomeDir(process.env); @@ -3837,9 +3852,17 @@ export class CodexAppServerAgentSession implements AgentSession { this.registerRequestHandlers(); try { - this.threadRollbackAvailable = codexServerHasThreadRollback( - toObjectRecord(initialized)?.userAgent, - ); + const userAgent = toObjectRecord(initialized)?.userAgent; + this.threadRollbackAvailable = codexServerHasThreadRollback(userAgent); + this.supportsInstructionSnapshots = + typeof userAgent === "string" && codexVersionAtLeast(userAgent, [0, 121, 0]); + if ( + !this.currentThreadId && + this.config.pluginAppendSystemPrompt?.length && + !this.supportsInstructionSnapshots + ) { + throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates."); + } this.speedModels = CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? []; @@ -4037,18 +4060,17 @@ export class CodexAppServerAgentSession implements AgentSession { settings: Record; name: string; } | null { - const match = this.findCollaborationMode(this.planModeEnabled ? "plan" : "code"); + const match = + this.findCollaborationMode(this.planModeEnabled ? "plan" : "code") ?? + this.restoredCollaborationMode; if (!match) return null; const settings: Record = {}; if (match.model) settings.model = match.model; if (match.reasoning_effort) settings.reasoning_effort = match.reasoning_effort; - const developerInstructions = composeSystemPromptParts( - match.developer_instructions, - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); - if (developerInstructions) settings.developer_instructions = developerInstructions; + // Codex applies thread instructions separately. Null asks it to supply the + // built-in collaboration mode instructions instead of replacing them. + settings.developer_instructions = match.developer_instructions ?? null; if (this.config.model) settings.model = this.config.model; const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId); if (thinkingOptionId) settings.reasoning_effort = thinkingOptionId; @@ -4308,10 +4330,7 @@ export class CodexAppServerAgentSession implements AgentSession { // the unnamespaced key emitted by earlier Paseo versions. params.modelProvider = this.deps.customCodexConfig.model_provider; } - const developerInstructions = composeSystemPromptParts( - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); + const developerInstructions = composeAgentSystemPrompt(this.config); if (developerInstructions) { params.developerInstructions = developerInstructions; } @@ -4322,11 +4341,11 @@ export class CodexAppServerAgentSession implements AgentSession { try { const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {})); const ids = Array.isArray(loaded?.data) ? loaded.data : []; - if (ids.includes(this.currentThreadId)) { - return; + if (!ids.includes(this.currentThreadId)) { + const response = await this.client.request("thread/resume", params); + this.rememberResolvedSandboxPolicy(response); + this.rememberRestoredCollaborationMode(response); } - const response = await this.client.request("thread/resume", params); - this.rememberResolvedSandboxPolicy(response); } catch (error) { const threadId = this.currentThreadId; const message = error instanceof Error ? error.message : String(error); @@ -4340,12 +4359,34 @@ export class CodexAppServerAgentSession implements AgentSession { } const response = await this.client.request("thread/resume", params); this.rememberResolvedSandboxPolicy(response); + this.rememberRestoredCollaborationMode(response); this.logger.info({ threadId }, "Unarchived Codex thread to restore active Paseo agent"); - return; + } else { + this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread"); + throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error }); } - this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread"); - throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error }); } + await this.instructionSnapshot.apply( + this.currentThreadId, + this.client.request.bind(this.client), + this.supportsInstructionSnapshots, + ); + } + + private rememberRestoredCollaborationMode(response: unknown): void { + const mode = toObjectRecord(toObjectRecord(response)?.collaborationMode); + const settings = toObjectRecord(mode?.settings); + if (typeof mode?.mode !== "string" || typeof settings?.model !== "string") return; + // The resumed mode can contain instructions from a previous launch. Keep its + // identity and model, and let Codex restore the built-in mode instructions. + this.restoredCollaborationMode = { + name: mode.mode, + mode: mode.mode, + model: settings.model, + reasoning_effort: + typeof settings.reasoning_effort === "string" ? settings.reasoning_effort : null, + }; + this.refreshResolvedCollaborationMode(); } private parseSlashCommandInput(text: string): { commandName: string; args?: string } | null { @@ -4461,13 +4502,7 @@ export class CodexAppServerAgentSession implements AgentSession { if (options?.outputSchema) { params.outputSchema = normalizeCodexOutputSchema(options.outputSchema); } - const developerInstructions = composeSystemPromptParts( - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); - if (developerInstructions) { - params.developerInstructions = developerInstructions; - } + const developerInstructions = composeAgentSystemPrompt(this.config); const codexConfig = this.buildCodexInnerConfig(); if (codexConfig) { params.config = codexConfig; @@ -5226,6 +5261,9 @@ export class CodexAppServerAgentSession implements AgentSession { systemPrompt: this.config.systemPrompt, mcpServers: this.config.mcpServers, asyncQuestions: this.asyncQuestions.serialize(), + ...(this.instructionSnapshot.describe(threadId) + ? { paseoInstructionReceipt: this.instructionSnapshot.describe(threadId) } + : {}), }, }; } @@ -5256,9 +5294,15 @@ export class CodexAppServerAgentSession implements AgentSession { model: this.config.model ?? null, serviceTier: this.serviceTier, config: this.buildCodexInnerConfig(), + developerInstructions: composeAgentSystemPrompt(this.config), userMessageTurns: this.codexUserMessageTurns(), threadRollbackAvailable: this.threadRollbackAvailable, setThreadId: async (threadId) => { + await this.instructionSnapshot.apply( + threadId, + this.client!.request.bind(this.client), + this.supportsInstructionSnapshots, + ); this.currentThreadId = threadId; // Codex writes a forked thread's rollout when it forks it, even before any turn. this.savedThreadId = threadId; @@ -5792,6 +5836,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.cachedRuntimeInfo = null; } this.currentThreadId = threadId; + this.instructionSnapshot.recordNewThread(threadId); } private buildThreadStartRequest(model: string): { @@ -5803,10 +5848,7 @@ export class CodexAppServerAgentSession implements AgentSession { const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined; const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined; const innerConfig = this.buildCodexInnerConfig(); - const developerInstructions = composeSystemPromptParts( - this.config.systemPrompt, - this.config.daemonAppendSystemPrompt, - ); + const developerInstructions = composeAgentSystemPrompt(this.config); const params: Record = { model, cwd: this.config.cwd ?? null, diff --git a/packages/server/src/server/agent/providers/codex/instruction-snapshot.ts b/packages/server/src/server/agent/providers/codex/instruction-snapshot.ts new file mode 100644 index 0000000000..848c4ab1f6 --- /dev/null +++ b/packages/server/src/server/agent/providers/codex/instruction-snapshot.ts @@ -0,0 +1,69 @@ +import { createHash } from "node:crypto"; +import { CodexAppServerRpcError } from "./app-server-transport.js"; + +/** The receipt records only which snapshot was delivered to a particular native thread. */ +interface InstructionReceipt { + threadId: string; + digest: string; +} + +function readReceipt(value: unknown): InstructionReceipt | null { + if (!value || typeof value !== "object") return null; + const receipt = value as Record; + if (typeof receipt.threadId !== "string" || typeof receipt.digest !== "string") return null; + if (!/^[a-f0-9]{64}$/.test(receipt.digest)) return null; + return { threadId: receipt.threadId, digest: receipt.digest }; +} + +export class CodexInstructionSnapshot { + private receipt: InstructionReceipt | null; + private readonly digest: string; + + constructor( + private readonly instructions: string | undefined, + receipt: unknown, + ) { + this.receipt = readReceipt(receipt); + this.digest = createHash("sha256") + .update(JSON.stringify({ version: 1, instructions: instructions ?? "" })) + .digest("hex"); + } + + /** A new thread receives its first snapshot through thread/start. */ + recordNewThread(threadId: string): void { + this.receipt = { threadId, digest: this.digest }; + } + + describe(threadId: string): InstructionReceipt | undefined { + return this.receipt?.threadId === threadId ? { ...this.receipt } : undefined; + } + + async apply( + threadId: string, + request: (method: string, params: unknown) => Promise, + supported: boolean, + ): Promise { + if (this.receipt?.threadId === threadId && this.receipt.digest === this.digest) return; + if (!supported) + throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates."); + const snapshot = JSON.stringify({ version: 1, instructions: this.instructions ?? "" }); + const text = + "This is the complete current set of Paseo-supplied instructions. It supersedes all earlier Paseo-supplied instructions in the conversation, including earlier snapshots. An empty instruction string means there are no current Paseo-supplied instructions. Provider and collaboration instructions remain in effect.\n\n" + + snapshot + + ""; + try { + await request("thread/inject_items", { + threadId, + items: [{ type: "message", role: "developer", content: [{ type: "input_text", text }] }], + }); + } catch (error) { + if (error instanceof CodexAppServerRpcError && error.code === -32601) { + throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.", { + cause: error, + }); + } + throw error; + } + this.receipt = { threadId, digest: this.digest }; + } +} diff --git a/packages/server/src/server/agent/providers/codex/rewind.ts b/packages/server/src/server/agent/providers/codex/rewind.ts index a22931b92b..bdff3c0c5d 100644 --- a/packages/server/src/server/agent/providers/codex/rewind.ts +++ b/packages/server/src/server/agent/providers/codex/rewind.ts @@ -49,6 +49,7 @@ export async function revertCodexConversation(input: { model?: string | null; serviceTier?: string | null; config?: Record | null; + developerInstructions?: string; userMessageTurns: CodexUserMessageTurnIndex; threadRollbackAvailable: boolean; setThreadId: (threadId: string) => void | Promise; @@ -76,6 +77,7 @@ export async function revertCodexConversation(input: { model: input.model ?? null, serviceTier: input.serviceTier ?? null, ...(input.config ? { config: input.config } : {}), + ...(input.developerInstructions ? { developerInstructions: input.developerInstructions } : {}), // Paseo re-reads the rewound thread through paged history, not the fork reply. excludeTurns: true, persistExtendedHistory: true, diff --git a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts index 2aee26894c..69448af846 100644 --- a/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts +++ b/packages/server/src/server/agent/providers/codex/test-utils/fake-app-server.ts @@ -171,7 +171,7 @@ export function createFakeCodexAppServer( const child = createCodexAppServerChildProcess(); const recordedRollbacks: JsonObject[] = []; const responseHandlers: Record = { - initialize: () => ({}), + initialize: () => ({ userAgent: "codex/0.150.0" }), "collaborationMode/list": () => ({ data: [] }), "config/read": () => ({ config: {} }), getUserSavedConfig: () => ({ config: {} }), @@ -189,6 +189,7 @@ export function createFakeCodexAppServer( "thread/loaded/list": () => ({ data: [] }), "thread/backgroundTerminals/list": () => ({ data: [], nextCursor: null }), "thread/resume": () => ({}), + "thread/inject_items": () => ({}), "turn/start": () => ({}), "thread/fork": (params) => ({ thread: { diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index 3d4cce0ff8..292377a193 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -435,6 +435,7 @@ function buildResumeStartInput(input: { systemPrompt: composeSystemPromptParts( input.resumeConfig.config.systemPrompt, input.resumeConfig.config.daemonAppendSystemPrompt, + ...(input.resumeConfig.config.pluginAppendSystemPrompt ?? []), ), }; } @@ -2339,7 +2340,11 @@ export class OmpAgentClient implements AgentClient { noSession: config.internal === true, modeId: launchMode.modeId, extraArgs: launchMode.extraArgs, - systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt), + systemPrompt: composeSystemPromptParts( + config.systemPrompt, + config.daemonAppendSystemPrompt, + ...(config.pluginAppendSystemPrompt ?? []), + ), env: launchContext?.env, }; const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession( diff --git a/packages/server/src/server/agent/providers/opencode-agent.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index 85c32e978f..e702fc6d86 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -30,6 +30,7 @@ import { type AgentDraftControls, type AgentOptionControl, type AgentLaunchContext, + type AgentResumeSessionOptions, type AgentMode, type AgentModelDefinition, type AgentPermissionAction, @@ -1521,6 +1522,7 @@ export class OpenCodeAgentClient implements AgentClient { handle: AgentPersistenceHandle, overrides?: Partial, launchContext?: AgentLaunchContext, + _options?: AgentResumeSessionOptions, ): Promise { const metadata = (handle.metadata ?? {}) as Partial; const cwd = overrides?.cwd ?? metadata.cwd; @@ -3692,6 +3694,7 @@ class OpenCodeAgentSession implements AgentSession { const systemPrompt = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), ); const model = this.parseModel(this.config.model); const effectiveMode = resolveOpenCodeRuntimeAgentId(this.currentMode); @@ -4029,6 +4032,7 @@ class OpenCodeAgentSession implements AgentSession { const systemPrompt = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), ); const promptResponse = await this.client.session.promptAsync({ sessionID: this.sessionId, diff --git a/packages/server/src/server/agent/providers/opencode/runtime-client.ts b/packages/server/src/server/agent/providers/opencode/runtime-client.ts index d10bb9953d..25447db718 100644 --- a/packages/server/src/server/agent/providers/opencode/runtime-client.ts +++ b/packages/server/src/server/agent/providers/opencode/runtime-client.ts @@ -4,6 +4,7 @@ import type { AgentSessionConfig, AgentLaunchContext, AgentCreateSessionOptions, + AgentResumeSessionOptions, AgentPersistenceHandle, FetchCatalogOptions, ProviderRefreshContext, @@ -149,9 +150,10 @@ export class OpenCodeRuntimeClient implements AgentClient { handle: AgentPersistenceHandle, config?: Partial, launch?: AgentLaunchContext, + options?: AgentResumeSessionOptions, ) { const client = await this.client(); - const session = await client.resumeSession(handle, config, launch); + const session = await client.resumeSession(handle, config, launch, options); return client === this.legacy ? session : withOpenCodeRuntimeNotice(session, 2, handle); } async fetchCatalog(options: FetchCatalogOptions, context?: ProviderRefreshContext) { diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts index 66ee191707..46ec3d7d15 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-harness.ts @@ -28,6 +28,7 @@ export class V2Harness { readonly prompts: string[] = []; readonly environments: Array<{ sessionID: string; variables: Record }> = []; readonly mcpAdds: string[] = []; + readonly instructions = new Map(); releases = 0; active = false; activeReads = 0; @@ -153,7 +154,17 @@ export class V2Harness { environment: async (input) => { this.environments.push(input); }, - instructions: { entry: { list: unexpected, put: unexpected, remove: unexpected } }, + instructions: { + entry: { + list: async () => [...this.instructions].map(([key, value]) => ({ key, value })), + put: async ({ key, value }) => { + this.instructions.set(key, String(value)); + }, + remove: async ({ key }) => { + this.instructions.delete(key); + }, + }, + }, prompt: async (input, options) => { const before = this.executions.length; await this.prompt(input, options); diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts index 58e9ffaefb..e8ec8eac81 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts @@ -17,6 +17,54 @@ function terminalEvents(events: AgentStreamEvent[]) { } describe("OpenCode v2 session lifecycle", () => { + test("reopening replaces and removes plugin instructions", async () => { + const harness = new V2Harness(); + const client = new OpenCodeV2AgentClient({ + logger: createTestLogger(), + runtime: harness.runtime, + }); + const created = await client.createSession({ + provider: "opencode", + cwd: "/tmp/project", + pluginAppendSystemPrompt: ["first"], + }); + expect(harness.instructions.get("paseo")).toBe("first"); + const handle = created.describePersistence()!; + await created.close(); + const resumed = await client.resumeSession(handle, { + cwd: "/tmp/project", + pluginAppendSystemPrompt: ["changed"], + }); + expect(harness.instructions.get("paseo")).toBe("changed"); + await resumed.close(); + const cleared = await client.resumeSession(handle, { + cwd: "/tmp/project", + pluginAppendSystemPrompt: undefined, + }); + expect(harness.instructions.has("paseo")).toBe(false); + await cleared.close(); + }); + + test("opening history does not change an existing session instruction", async () => { + const harness = new V2Harness(); + harness.instructions.set("paseo", "Existing plugin instruction"); + const client = new OpenCodeV2AgentClient({ + logger: createTestLogger(), + runtime: harness.runtime, + }); + const session = await client.resumeSession( + { provider: "opencode", sessionId: "session", metadata: { cwd: "/tmp/project" } }, + { cwd: "/tmp/project" }, + undefined, + { purpose: "history" }, + ); + try { + expect(harness.instructions.get("paseo")).toBe("Existing plugin instruction"); + } finally { + await session.close(); + } + }); + test("refreshes the existing location before reading a forced catalog", async () => { const harness = new V2Harness(); const refreshed: string[] = []; diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.ts index 44b4647955..d7139c097c 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.ts @@ -17,6 +17,7 @@ import type { AgentCapabilityFlags, AgentClient, AgentCreateSessionOptions, + AgentResumeSessionOptions, AgentDraftControls, AgentLaunchContext, AgentPersistenceHandle, @@ -131,6 +132,7 @@ export class OpenCodeV2AgentClient implements AgentClient { handle: AgentPersistenceHandle, overrides?: Partial, launch?: AgentLaunchContext, + options?: AgentResumeSessionOptions, ): Promise { const cwd = overrides?.cwd ?? handle.metadata?.cwd; if (typeof cwd !== "string") @@ -151,7 +153,14 @@ export class OpenCodeV2AgentClient implements AgentClient { sessionID: handle.nativeHandle ?? handle.sessionId, }); await applyResumeOverrides(connection.client, info, overrides); - return await this.attach(connection, info, config, launch, true); + return await this.attach( + connection, + info, + config, + launch, + true, + options?.purpose === "history", + ); } catch (error) { await connection.release(); throw error; @@ -163,6 +172,7 @@ export class OpenCodeV2AgentClient implements AgentClient { config: AgentSessionConfig, launch: AgentLaunchContext | undefined, persist: boolean, + historyOnly = false, ) { const acquire = () => this.runtime.acquire( @@ -209,6 +219,7 @@ export class OpenCodeV2AgentClient implements AgentClient { bindChild, acquire, moved, + historyOnly, ); try { await session.initialize( diff --git a/packages/server/src/server/agent/providers/opencode/v2/session.ts b/packages/server/src/server/agent/providers/opencode/v2/session.ts index 1724bacbe7..dcd59b67f3 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session.ts @@ -75,6 +75,7 @@ export class OpenCodeV2Session implements AgentSession { bindChild?: (id: string) => void, private readonly acquire?: () => Promise, private readonly moved?: (connection: V2Connection) => void, + private readonly historyOnly = false, ) { this.background = new OpenCodeBackgroundInventory({ id: info.id, @@ -193,16 +194,24 @@ export class OpenCodeV2Session implements AgentSession { }); await this.awaitMcp(server); } + if (this.historyOnly) return; const system = composeSystemPromptParts( this.config.systemPrompt, this.config.daemonAppendSystemPrompt, + ...(this.config.pluginAppendSystemPrompt ?? []), ); - if (system) + if (system) { await this.client.session.instructions.entry.put({ sessionID: this.id, key: "paseo", value: system, }); + } else { + const entries = await this.client.session.instructions.entry.list({ sessionID: this.id }); + if (entries.some((entry) => entry.key === "paseo")) { + await this.client.session.instructions.entry.remove({ sessionID: this.id, key: "paseo" }); + } + } } private async startStream() { let ready!: () => void; diff --git a/packages/server/src/server/agent/providers/pi/agent.test.ts b/packages/server/src/server/agent/providers/pi/agent.test.ts index eab96283bf..30f06c5648 100644 --- a/packages/server/src/server/agent/providers/pi/agent.test.ts +++ b/packages/server/src/server/agent/providers/pi/agent.test.ts @@ -1887,6 +1887,7 @@ describe("PiRpcAgentSession", () => { createConfig({ systemPrompt: "Agent prompt", daemonAppendSystemPrompt: "Daemon prompt", + pluginAppendSystemPrompt: ["Plugin one", "Plugin two"], }), ); @@ -1905,7 +1906,9 @@ describe("PiRpcAgentSession", () => { await expect( applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"), - ).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt"); + ).resolves.toBe( + "Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two", + ); await session.close(); }); @@ -1928,6 +1931,7 @@ describe("PiRpcAgentSession", () => { }, { daemonAppendSystemPrompt: "Daemon prompt", + pluginAppendSystemPrompt: ["Plugin one", "Plugin two"], }, ); @@ -1951,7 +1955,9 @@ describe("PiRpcAgentSession", () => { ]); await expect( applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"), - ).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt"); + ).resolves.toBe( + "Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two", + ); }); test("updates model and thinking through Pi runtime commands", async () => { diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index b158882269..1ef5d0ec21 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -52,7 +52,7 @@ import { type ResolvedProviderLaunch, } from "../../provider-launch-config.js"; import { renderPromptAttachmentAsText } from "../../prompt-attachments.js"; -import { composeSystemPromptParts } from "../../system-prompt.js"; +import { composeAgentSystemPrompt } from "../../system-prompt.js"; import { buildBinaryDiagnosticRows, buildCommandResolutionDiagnosticRows, @@ -2601,7 +2601,7 @@ export class PiRpcAgentClient implements AgentClient { const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime); const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null; const paseoExtension = createPiPaseoExtensionFile({ - systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt), + systemPrompt: composeAgentSystemPrompt(config), mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined, }); let runtimeSession: PiRuntimeSession; @@ -2670,10 +2670,7 @@ export class PiRpcAgentClient implements AgentClient { ); const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null; const paseoExtension = createPiPaseoExtensionFile({ - systemPrompt: composeSystemPromptParts( - resumeConfig.config.systemPrompt, - resumeConfig.config.daemonAppendSystemPrompt, - ), + systemPrompt: composeAgentSystemPrompt(resumeConfig.config), mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined, }); const tempFiles = mcpConfigFile ? [mcpConfigFile, paseoExtension] : [paseoExtension]; diff --git a/packages/server/src/server/agent/system-prompt.ts b/packages/server/src/server/agent/system-prompt.ts index 2aafc3759b..5dff1e6602 100644 --- a/packages/server/src/server/agent/system-prompt.ts +++ b/packages/server/src/server/agent/system-prompt.ts @@ -8,3 +8,15 @@ export function composeSystemPromptParts( return prompt.length > 0 ? prompt : undefined; } + +export function composeAgentSystemPrompt(config: { + systemPrompt?: string; + daemonAppendSystemPrompt?: string; + pluginAppendSystemPrompt?: string[]; +}): string | undefined { + return composeSystemPromptParts( + config.systemPrompt, + config.daemonAppendSystemPrompt, + ...(config.pluginAppendSystemPrompt ?? []), + ); +} diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index d08089ad3d..aab2a9bd15 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -527,13 +527,25 @@ test("agent creation hooks change the provider and environment before the sessio }); server.addHook("agent.open.before", async ({ request }) => { console.log(JSON.stringify({ hook: "agent.open.before", request })); - return { ...request, env: { ...request.env, HOOK_OPEN: "opened" } }; + return { ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Plugin instructions"], env: { ...request.env, HOOK_OPEN: "opened" } }; }); server.addHook("agent.create.after", async (event) => { console.log(JSON.stringify({ hook: "agent.create.after", event })); });`, reportOpen: true, }); + const extraPlugin = path.join(directory, "extra-plugin"); + await mkdir(extraPlugin); + await writeFile( + path.join(extraPlugin, "paseo-plugin.json"), + JSON.stringify({ id: "a-prompt", requirements: { paseo: ">=0.8.0" } }), + ); + const writePrompt = (prompt: string) => + writeFile( + path.join(extraPlugin, "index.server.ts"), + `export default function contribute(server) { server.addHook("agent.open.before", async ({ request }) => ({ ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), ${JSON.stringify(prompt)}] })); return () => {}; }`, + ); + await writePrompt("First plugin"); const daemon = await createTestPaseoDaemon(); const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); try { @@ -541,15 +553,17 @@ test("agent creation hooks change the provider and environment before the sessio await client.fetchAgents({ subscribe: {} }); await client.patchDaemonConfig({ pluginsEnabled: true }); await client.installDirectoryPlugin(pluginDirectory); + await client.installDirectoryPlugin(extraPlugin); const agent = await client.createAgent({ provider: "claude", cwd: directory, title: "Hook test", + systemPrompt: "Saved instructions", }); expect(agent.provider).toBe(PROVIDER_ID); expect(await daemon.daemon.agentStorage.get(agent.id)).toMatchObject({ provider: PROVIDER_ID, - config: { model: "shutdown-model" }, + config: { model: "shutdown-model", systemPrompt: "Saved instructions" }, }); await expect .poll(async () => { @@ -569,13 +583,32 @@ test("agent creation hooks change the provider and environment before the sessio }, { hook: "provider.open", - config: { env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" } }, + config: { + env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" }, + systemPrompt: "Saved instructions\n\nFirst plugin\n\nPlugin instructions", + }, }, { hook: "agent.create.after", event: { agent: { id: agent.id, provider: PROVIDER_ID } }, }, ]); + await writePrompt("Changed plugin"); + await client.reloadPlugin("a-prompt"); + await daemon.daemon.agentManager.reloadAgentSession(agent.id); + await client.disablePlugin("a-prompt"); + await daemon.daemon.agentManager.reloadAgentSession(agent.id); + const opens = (await client.getPluginLogs("shutdown-provider-plugin")) + .filter((entry) => entry.message.startsWith('{"hook":"provider.open"')) + .map((entry) => JSON.parse(entry.message).config.systemPrompt); + expect(opens).toEqual([ + "Saved instructions\n\nFirst plugin\n\nPlugin instructions", + "Saved instructions\n\nChanged plugin\n\nPlugin instructions", + "Saved instructions\n\nPlugin instructions", + ]); + expect((await daemon.daemon.agentStorage.get(agent.id))?.config?.systemPrompt).toBe( + "Saved instructions", + ); await client.archiveAgent(agent.id); } finally { await client.close(); diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index bf7526ba1d..6ff3361f22 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -228,7 +228,9 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }, { background: }, paseo, ), - ).rejects.toThrow("agent.open.before hooks can only change env, tools, and mcpServers"); + ).rejects.toThrow( + "agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt", + ); }, ); @@ -357,3 +359,42 @@ test("checkout-branch hooks reject a branch-off baseRef", async () => { validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }), ).rejects.toThrow(/baseRef/); }); + +test("session-open instructions compose, survive old hooks, and are ignored for history", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "first"], + })); + hooks.addHook("agent.open.before", async ({ request }) => { + const { appendSystemPrompt: _ignored, ...oldRequest } = request; + return oldRequest; + }); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "second"], + })); + const input = { + agentId: "agent", + workspaceId: null, + provider: "codex", + cwd: "/project", + reason: "resume", + purpose: "interactive", + env: {}, + title: null, + labels: {}, + metadata: {}, + tools: [], + mcpServers: {}, + }; + const interactive = await hooks.invoke("interactive", "agent.open.before", input, paseo); + expect(interactive).toMatchObject({ appendSystemPrompt: ["first", "second"] }); + const history = await hooks.invoke( + "history", + "agent.open.before", + { ...input, purpose: "history" }, + paseo, + ); + expect(history).not.toHaveProperty("appendSystemPrompt"); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index b291bf3723..46e2a87d66 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -108,6 +108,7 @@ const beforeSchemas = { labels: z.record(z.string(), z.string()), // Optional so a plugin that returns its own object keeps working; omitted means unchanged. metadata: z.record(z.string(), z.custom()).optional(), + appendSystemPrompt: z.array(z.string()).optional(), tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(), @@ -248,9 +249,18 @@ export async function validateBeforeResult { ## agent.open.before -Receives `{ request }`; only `env`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. +Receives `{ request }`; only `env`, `appendSystemPrompt`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. Do not await a write to the agent being opened: `setMetadata`, `setLabels`, or an option, model, thinking or mode change. The write waits for the open to finish, the open waits for your hook, so the hook times out and the open fails. Start the write without awaiting it; it runs right after the open: @@ -329,6 +329,19 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { | `purpose` | `interactive`, `history` | | `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | +### Append instructions on every session opening + +```ts +server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Follow the team engineering guide."], +})); +``` + +Instructions follow the saved agent prompt and daemon instructions, in plugin order. They are not saved in the agent configuration and are ignored for history opens. Reload the plugin after changing its data to apply new instructions on the next reopen. Running turns continue; removing an instruction does not remove conversation history. Internal agents also receive these instructions. The ACP adapter does not send system instructions to its providers. Plugin providers receive the composed prompt, but must apply it themselves. + +Codex instruction updates require Codex 0.121.0 or newer with a recognizable version reported by the app server. Source builds reporting `0.0.0` must use a versioned build. Paseo adds a current instruction snapshot to existing threads; earlier snapshots remain in the conversation. A crash during an update or rewinding a thread can repeat a snapshot. + ### Inject environment variables on every session opening ```ts diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index af6c66bd7b..5bdb94a61b 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -29,7 +29,7 @@ export default function contribute(server: PluginServerContext) { 所有处理函数都必须为异步函数。轮次完成包括成功、失败和取消,请查看 `outcome`。权限完成包括所有处理结果,请查看 `resolution`。 -创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 +创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 `worktree.create.after` 在工作区注册前运行,随后是 `workspace.create.after`,两者都早于第一个 Agent 的 `agent.create.before` / `agent.open.before`。 @@ -47,22 +47,22 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 ## 钩子一览 {#hooks} -| 钩子 | 等待 | 载荷 | 可修改 | -| ------------------------- | ---- | ----------------------------------------- | ------------------------------------------ | -| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | -| `workspace.create.after` | 否 | `{ workspace }` | | -| `workspace.archive.after` | 否 | `{ workspace }` | | -| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | -| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | -| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | -| `agent.create.after` | 否 | `{ agent }` | | -| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`tools`、`mcpServers` | -| `agent.close.after` | 否 | `{ agent }` | | -| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | -| `agent.turn.before` | 否 | `{ agent, turnId }` | | -| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | 否 | `{ agent, request }` | | -| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| 钩子 | 等待 | 载荷 | 可修改 | +| ------------------------- | ---- | ----------------------------------------- | --------------------------------------------------------------- | +| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | +| `workspace.create.after` | 否 | `{ workspace }` | | +| `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | +| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | +| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | +| `agent.create.after` | 否 | `{ agent }` | | +| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers` | +| `agent.close.after` | 否 | `{ agent }` | | +| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | +| `agent.turn.before` | 否 | `{ agent, turnId }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | 否 | `{ agent, request }` | | +| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | ## 共享载荷 {#shared-payloads} @@ -279,7 +279,7 @@ server.addHook("agent.create.after", async ({ agent }) => { ## agent.open.before {#agentopenbefore} -收到 `{ request }`,只能修改 `env`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 +收到 `{ request }`,只能修改 `env`、`appendSystemPrompt`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 不要 await 对正在打开的 Agent 的写入,例如 `setMetadata`。该写入要等打开完成,而打开在等你的钩子,结果钩子超时,打开失败。启动写入但不要 await,它会在打开完成后立即执行: @@ -325,6 +325,19 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { | `purpose` | `interactive`、`history` | | `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | +### 在每次打开会话时追加指令 {#append-instructions-on-every-session-opening} + +```ts +server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Follow the team engineering guide."], +})); +``` + +插件指令按插件顺序追加在已保存的 Agent 提示词和 daemon 指令之后。指令不会保存到 Agent 配置中,读取历史时也会忽略这些指令。插件数据更改后,重新加载插件以在下次重新打开会话时应用新指令。正在运行的轮次会继续。移除指令不会删除对话历史。内部 Agent 也会收到这些指令。ACP 适配器不会向 Provider 发送系统指令。插件 Provider 会收到组合后的提示词,但需要自行应用。 + +更新 Codex 指令需要 Codex 0.121.0 或更新版本,且 app server 报告的版本必须可识别。版本显示为 `0.0.0` 的源码构建需要换用带版本号的构建。Paseo 会向现有会话添加当前指令快照;之前的快照仍保留在对话中。更新期间发生崩溃或回退会话时,快照可能重复。 + ### 在每次打开会话时注入环境变量 {#inject-environment-variables-on-every-session-opening} ```ts From be92e85a4e2cf39f463a4c3ba86ed9292be9852f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:02:51 +0000 Subject: [PATCH 115/160] fix(server): return only the newest reply as the last message after a restart (#9846) After a daemon restart, an agent's timeline is rebuilt from provider history, and those rows have no turn id. A reply the agent starts on its own, such as Claude waking after a background subagent, follows the previous reply with no user message between them, so the last assistant message lookup joined the two and wait results and finish notifications returned the old reply with the new one appended. The timeline projection already treats a message id change as a new message. Share that rule with the lookup, so both decide which rows are chunks of one message the same way. Closes #9814 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/agent-manager.test.ts | 27 ++++++++++++++++++ .../server/src/server/agent/agent-manager.ts | 20 ++++--------- .../src/server/agent/timeline-projection.ts | 28 ++++++++++++------- 3 files changed, 51 insertions(+), 24 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 2525b42b27..352391108f 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -13592,6 +13592,33 @@ test("the last assistant message is the newest turn's reply, not joined to the p } }); +test("the last assistant message read from rebuilt history is the newest reply, not joined to the one before it", async () => { + // Rows replayed from provider history have no turn id. A reply the agent starts on its own, + // such as Claude waking after a background subagent, follows the previous reply with no user + // message between them; only their message ids tell them apart. + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-last-reply-")); + const codex = fakeCodexEmitting({ + historyItems: [ + { type: "user_message", text: "Start a background task.", messageId: "user-1" }, + { type: "assistant_message", text: "Started it, ", messageId: "message-1" }, + { type: "assistant_message", text: "I will report back.", messageId: "message-1" }, + { type: "assistant_message", text: "The task finished.", messageId: "message-2" }, + ], + }); + const manager = new AgentManager({ clients: { codex }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + try { + await manager.hydrateTimelineFromProvider(agent.id, { force: true }); + + expect(await manager.getLastAssistantMessage(agent.id)).toBe("The task finished."); + } finally { + await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("reads the last durable assistant response without loading a stored-only child", async () => { const store = new RecordingTimelineStore(); await store.appendCommitted("stored-child", { diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index cfd43b2cb5..ece45289e2 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3,7 +3,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js"; import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js"; -import { projectTimelineRows } from "./timeline-projection.js"; +import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js"; import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js"; import { applyRecordPatch } from "../record-patch.js"; @@ -4072,24 +4072,16 @@ export class AgentManager { private getLastAssistantMessageSegmentFromTimeline( timeline: readonly Pick[], ): { text: string; startsAtBeginning: boolean } | null { - // Collect the last contiguous assistant messages of one turn (Claude streams chunks). - // A turn the provider starts on its own has no user message before its reply. + // Collect the chunks of the last assistant message (Claude streams chunks). A turn the + // provider starts on its own has no user message before its reply. const chunks: string[] = []; - let replyTurnId: string | undefined; let startsAtBeginning = false; for (let i = timeline.length - 1; i >= 0; i--) { - const { item, turnId } = timeline[i]; - if (item.type !== "assistant_message") { - if (chunks.length) { - break; - } - continue; - } - if (chunks.length === 0) { - replyTurnId = turnId; - } else if (turnId !== replyTurnId) { + const { item } = timeline[i]; + if (chunks.length > 0 && !continuesAssistantMessage(timeline[i], timeline[i + 1])) { break; } + if (item.type !== "assistant_message") continue; chunks.push(item.text); startsAtBeginning = i === 0; } diff --git a/packages/server/src/server/agent/timeline-projection.ts b/packages/server/src/server/agent/timeline-projection.ts index bd5357e581..905748d752 100644 --- a/packages/server/src/server/agent/timeline-projection.ts +++ b/packages/server/src/server/agent/timeline-projection.ts @@ -241,6 +241,23 @@ function mergeReasoningChunks(entries: readonly WorkingEntry[]): WorkingEntry[] return output; } +/** + * Whether `next`, the row right after `previous`, is another chunk of the same assistant + * message. A turn id or message id change starts a new message, which matters where rows + * replayed from provider history carry no turn id. + */ +export function continuesAssistantMessage( + previous: Pick, + next: Pick, +): boolean { + return ( + previous.item.type === "assistant_message" && + next.item.type === "assistant_message" && + previous.turnId === next.turnId && + (next.item.messageId === undefined || next.item.messageId === previous.item.messageId) + ); +} + function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] { const output: WorkingEntry[] = []; @@ -248,10 +265,8 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] const previous = output[output.length - 1]; const shouldMerge = previous && - previous.item.type === "assistant_message" && - entry.item.type === "assistant_message" && previous.seqEnd + 1 === entry.seqStart && - previous.turnId === entry.turnId; + continuesAssistantMessage(previous, entry); if (!shouldMerge || !previous) { output.push(entry); @@ -262,13 +277,6 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] { type: "assistant_message" } >; const entryAssistant = entry.item as Extract; - if ( - entryAssistant.messageId !== undefined && - previousAssistant.messageId !== entryAssistant.messageId - ) { - output.push(entry); - continue; - } const collapsedKinds = new Set([ ...previous.collapsed, From 8522d18ed816dcb6f7840c43a1b3880b593bfb08 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:04:46 +0000 Subject: [PATCH 116/160] Keep Claude signed in when model discovery runs during a token refresh (#9855) * Let Claude model discovery finish a token refresh instead of killing it Model discovery stopped waiting after 5 s by aborting the SDK query and tree-killing the CLI. A CLI that is still refreshing an expired OAuth token at that moment has already rotated the refresh token, so the kill leaves only the revoked token on disk and logs the user out. The 5 s limit now only bounds the wait. A CLI that has not answered gets its input ended and exits on its own; it is tree-killed only after a 60 s grace period or when the daemon shuts down. Fixes #9314 * fix(server): let Claude model discovery finish a token refresh after it answers Claude Code answers the model list before its startup token refresh has saved the rotated refresh token. Discovery killed the CLI right after the answer, so a refresh still in flight left the revoked token on disk and every later Claude session failed until /login. Discovery now ends the CLI's input and lets it exit on its own whether or not it answered, with the existing grace period and shutdown kill as the bound. Co-authored-by: daysun-k <8309193+daysun-k@users.noreply.github.com> --------- Co-authored-by: daysun-k <8309193+daysun-k@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../server/agent/providers/claude/agent.ts | 6 +- .../agent/providers/claude/model-discovery.ts | 80 +++++++++-- .../agent/providers/claude/models.test.ts | 124 ++++++++++++++++++ 3 files changed, 196 insertions(+), 14 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index c33a2e6593..5c829801d5 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -83,7 +83,7 @@ import { type ClaudeProviderOptions, } from "./options.js"; import { renderPromptAttachmentAsText } from "../../prompt-attachments.js"; -import { discoverClaudeModels } from "./model-discovery.js"; +import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js"; import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js"; import { findSteeredMessageParent, @@ -1751,6 +1751,10 @@ export class ClaudeAgentClient implements AgentClient { }; } + async shutdown(): Promise { + await killExitingClaudeModelDiscoveries(); + } + async resolveDefaultModeId({ env: launchEnv }: ResolveAgentDefaultModeInput): Promise { return claudeModeCatalog(this.buildProviderEnv(launchEnv)).defaultModeId; } diff --git a/packages/server/src/server/agent/providers/claude/model-discovery.ts b/packages/server/src/server/agent/providers/claude/model-discovery.ts index d74898472b..674a61982e 100644 --- a/packages/server/src/server/agent/providers/claude/model-discovery.ts +++ b/packages/server/src/server/agent/providers/claude/model-discovery.ts @@ -6,6 +6,10 @@ import type { ProviderRuntimeSettings } from "../../provider-launch-config.js"; import { terminateWithTreeKill } from "../../../../utils/tree-kill.js"; import { claudeQuery, type ClaudeQueryInput, type ClaudeQueryContext } from "./query.js"; +const DISCOVERY_WAIT_MS = 5_000; +// Long enough for the CLI to finish an OAuth token refresh it started before the wait ended. +const DISCOVERY_EXIT_GRACE_MS = 60_000; + interface ClaudeModelDiscoveryOptions { resolveBinary: () => Promise; runtimeSettings?: ProviderRuntimeSettings; @@ -18,19 +22,24 @@ type OpenDiscoveryQuery = ( context: ClaudeQueryContext, ) => Pick; +type DiscoveryQuery = ReturnType; + +// Discovery processes left to exit on their own after their caller stopped waiting. +const exitingDiscoveries = new Map Promise>(); + // The curated catalog survives a failed or slow probe. This process never receives // a prompt and must not persist a session or launch user MCP servers/hooks. export async function discoverClaudeModels( options: ClaudeModelDiscoveryOptions, openQuery: OpenDiscoveryQuery = claudeQuery, ): Promise { - const controller = new AbortController(); + const waitController = new AbortController(); const signal = options.signal - ? AbortSignal.any([options.signal, controller.signal]) - : controller.signal; + ? AbortSignal.any([options.signal, waitController.signal]) + : waitController.signal; const timer = setTimeout( - () => controller.abort(new Error("Claude model discovery timed out")), - 5_000, + () => waitController.abort(new Error("Claude model discovery timed out")), + DISCOVERY_WAIT_MS, ); let endInput!: () => void; const ended = new Promise((resolve) => { @@ -46,7 +55,7 @@ export async function discoverClaudeModels( }; }, }; - let query: ReturnType | undefined; + let query: DiscoveryQuery | undefined; let child: ChildProcess | undefined; try { signal.throwIfAborted(); @@ -64,7 +73,8 @@ export async function discoverClaudeModels( strictMcpConfig: true, settingSources: ["user"], settings: { disableAllHooks: true }, - abortController: controller, + // No abortController: the SDK kills the process when it aborts, and the end of + // the wait must not. }, }, { @@ -78,12 +88,56 @@ export async function discoverClaudeModels( } finally { clearTimeout(timer); endInput(); - try { - query?.close(); - } finally { - if (child) { - await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 }); - } + if (query && child && !hasExited(child)) { + // The CLI may be refreshing an expired OAuth token, even after it has answered. + // Claude Code rotates the refresh token before saving the new pair, so killing it now + // leaves a revoked token on disk and logs the user out (#9314). With its input ended + // it exits once that work is done; the grace period and daemon shutdown bound the wait. + letDiscoveryExit(query, child); + } else { + await retireDiscovery(query, child); } } } + +/** Kills discovery processes still exiting after their wait ended. Called on daemon shutdown. */ +export async function killExitingClaudeModelDiscoveries(): Promise { + await Promise.all(Array.from(exitingDiscoveries.values(), (kill) => kill())); +} + +function letDiscoveryExit(query: DiscoveryQuery, child: ChildProcess): void { + function forget(): void { + clearTimeout(graceTimer); + child.off("exit", onExit); + exitingDiscoveries.delete(child); + } + function onExit(): void { + forget(); + query.close(); + } + async function kill(): Promise { + forget(); + await retireDiscovery(query, child); + } + const graceTimer = setTimeout(() => void kill(), DISCOVERY_EXIT_GRACE_MS); + graceTimer.unref(); + child.once("exit", onExit); + exitingDiscoveries.set(child, kill); +} + +async function retireDiscovery( + query: DiscoveryQuery | undefined, + child: ChildProcess | undefined, +): Promise { + try { + query?.close(); + } finally { + if (child) { + await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 }); + } + } +} + +function hasExited(child: ChildProcess): boolean { + return child.exitCode !== null || child.signalCode !== null; +} diff --git a/packages/server/src/server/agent/providers/claude/models.test.ts b/packages/server/src/server/agent/providers/claude/models.test.ts index 1287fd6335..d9a7ddc98d 100644 --- a/packages/server/src/server/agent/providers/claude/models.test.ts +++ b/packages/server/src/server/agent/providers/claude/models.test.ts @@ -1,3 +1,4 @@ +import { ChildProcess } from "node:child_process"; import * as fs from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; @@ -1173,4 +1174,127 @@ describe("Claude model discovery process", () => { await expect(result).rejects.toBe(failure); expect(closed).toBe(true); }); + + describe("when the CLI is still starting up at the deadline", () => { + // Without a pid, terminateWithTreeKill signals the child directly instead of a real tree. + class StartingClaudeProcess extends ChildProcess { + readonly signals: string[] = []; + override kill(signal?: NodeJS.Signals | number): boolean { + this.signals.push(String(signal)); + this.emit("exit", null, signal); + return true; + } + exitOnItsOwn(): void { + this.emit("exit", 0, null); + } + } + + interface StalledDiscoveryState { + closed: boolean; + inputEnded: boolean; + } + + async function recordInputEnd( + prompt: AsyncIterable, + state: StalledDiscoveryState, + ): Promise { + await prompt[Symbol.asyncIterator]().next(); + state.inputEnded = true; + } + + // By default the CLI never answers: an expired OAuth token is refreshed first. + function startStalledDiscovery( + supportedModels: () => Promise = () => new Promise(() => {}), + ) { + const child = new StartingClaudeProcess(); + const state: StalledDiscoveryState = { closed: false, inputEnded: false }; + const result = discoverClaudeModels( + { resolveBinary: async () => "/claude", env: {} }, + (input, context) => { + if (typeof input.prompt === "string") throw new Error("unexpected inference prompt"); + void recordInputEnd(input.prompt, state); + context.onChildProcess?.(child); + return { + supportedModels, + close: () => { + state.closed = true; + }, + }; + }, + ); + return { child, state, result }; + } + + afterEach(() => { + vi.useRealTimers(); + }); + + it("stops waiting at the limit but lets the CLI finish instead of killing it", async () => { + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(); + const settled = expect(result).rejects.toThrow("Claude model discovery timed out"); + + await vi.advanceTimersByTimeAsync(5_000); + await settled; + expect(state.inputEnded).toBe(true); + expect(child.signals).toEqual([]); + expect(state.closed).toBe(false); + + await vi.advanceTimersByTimeAsync(59_999); + expect(child.signals).toEqual([]); + + await vi.advanceTimersByTimeAsync(1); + expect(child.signals).toEqual(["SIGTERM"]); + expect(state.closed).toBe(true); + }); + + async function answerAtOnce(): Promise { + return []; + } + + it("lets the CLI finish after it answers instead of killing it", async () => { + // The CLI answers supportedModels() before its startup token refresh has saved the + // rotated refresh token, so a kill right after the answer also logs the user out. + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(answerAtOnce); + await expect(result).resolves.toEqual([]); + await vi.advanceTimersByTimeAsync(0); + expect(state.inputEnded).toBe(true); + expect(child.signals).toEqual([]); + + await vi.advanceTimersByTimeAsync(1_000); + child.exitOnItsOwn(); + expect(state.closed).toBe(true); + await vi.advanceTimersByTimeAsync(120_000); + expect(child.signals).toEqual([]); + }); + + it("never signals a CLI that exits on its own during the grace period", async () => { + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(); + const settled = expect(result).rejects.toThrow("Claude model discovery timed out"); + await vi.advanceTimersByTimeAsync(5_000); + await settled; + + await vi.advanceTimersByTimeAsync(2_000); + child.exitOnItsOwn(); + expect(state.closed).toBe(true); + + await vi.advanceTimersByTimeAsync(120_000); + expect(child.signals).toEqual([]); + }); + + it("tree-kills a still-running CLI when the daemon shuts down", async () => { + vi.useFakeTimers(); + const { child, state, result } = startStalledDiscovery(); + const settled = expect(result).rejects.toThrow("Claude model discovery timed out"); + await vi.advanceTimersByTimeAsync(5_000); + await settled; + expect(child.signals).toEqual([]); + + await new ClaudeAgentClient({ logger: createTestLogger() }).shutdown(); + expect(child.signals).toEqual(["SIGTERM"]); + expect(state.closed).toBe(true); + }); + }); }); From 5a78c1cd16b57a33417809ed474bdb3a30f455f1 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:01:00 +0000 Subject: [PATCH 117/160] Let idle cleanup release Codex chats opened only to read history (#9859) A Codex session opened to read history reads the thread and disposes its app-server right away, but canStopRuntime() vetoed it because it had no client. Idle cleanup then kept every such chat loaded in the daemon. Closes #9804 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../providers/codex-app-server-agent.test.ts | 30 +++++++++++++++++++ .../agent/providers/codex-app-server-agent.ts | 2 ++ 2 files changed, 32 insertions(+) diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index c537a50d33..36985c4af3 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -2437,6 +2437,36 @@ describe("Codex app-server provider", () => { appServer.assertNoErrors(); }); + test("lets idle cleanup release a session opened only to read its history", async () => { + let spawns = 0; + const appServer = createFakeCodexAppServer({ + "thread/resume": () => + Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))), + "thread/read": () => ({ thread: { turns: [] } }), + }); + const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, { + appServerProcess: createFakeCodexAppServerProcess(() => { + spawns += 1; + return appServer.child; + }), + }); + const internals = castInternals<{ + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + }>(provider); + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + + const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, { + purpose: "history", + }); + + expect(await session.canStopRuntime!()).toBe(true); + expect(spawns).toBe(1); + await session.close(); + appServer.assertNoErrors(); + }); + test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => { const threadRequests: string[] = []; let resumeAttempts = 0; diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index de835eca49..0e0be1042c 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -5385,6 +5385,8 @@ export class CodexAppServerAgentSession implements AgentSession { } async canStopRuntime(): Promise { + // A history session released its app-server once it read the thread, so nothing runs. + if (this.connectionState === "history-ready") return true; if ( !this.client || this.client.hasPendingRequests() || From a8cadae0eecc05766f58ea8b18f6a7d50d9f15d8 Mon Sep 17 00:00:00 2001 From: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:01:03 +0000 Subject: [PATCH 118/160] fix(app): keep saved hosts when one entry can't be read (#9847) The host registry was parsed with a strict array schema, so one host or connection this build couldn't read failed the whole array. The loader then removed @paseo:daemon-registry, and every saved host and password with it. That happens after a downgrade, or once a newer build saves a connection kind this build doesn't know. - Hosts and connections are read one at a time. One this build can't read is skipped, and the other hosts load. - Skipped entries are written back on every save, so the build that wrote them still finds them. Removing a host also drops what this build couldn't read for it. - A value that isn't a JSON array is copied to @paseo:daemon-registry:unreadable instead of being removed. - The stored-password migration still moves a connection password to its host when that host also has an unreadable connection. --- docs/data-model.md | 10 ++ .../e2e/browser/saved-host-registry.spec.ts | 106 +++++++++++++ packages/app/src/runtime/host-runtime.test.ts | 145 ++++++++++++++++++ packages/app/src/runtime/host-runtime.ts | 65 ++++---- .../app/src/types/host-connection.test.ts | 74 +++++++++ packages/app/src/types/host-connection.ts | 115 ++++++++++++-- 6 files changed, 474 insertions(+), 41 deletions(-) create mode 100644 packages/app/e2e/browser/saved-host-registry.spec.ts diff --git a/docs/data-model.md b/docs/data-model.md index aa0f201ce6..ff77593e5d 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision. +### Saved hosts + +**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles. + +Every app build on a device shares this key, including an older build after a downgrade and a newer +one that saves a connection kind this build doesn't know. The key holds every saved host and its +password, so never remove it. Read each host and connection on its own, skip the ones this build +can't read, and write them back on every save. A value that isn't a JSON array is copied to +`@paseo:daemon-registry:unreadable` before the next save overwrites it. + ### Draft Store **AsyncStorage key:** `paseo-drafts` (version 2) diff --git a/packages/app/e2e/browser/saved-host-registry.spec.ts b/packages/app/e2e/browser/saved-host-registry.spec.ts new file mode 100644 index 0000000000..80162d60b5 --- /dev/null +++ b/packages/app/e2e/browser/saved-host-registry.spec.ts @@ -0,0 +1,106 @@ +import { expect, type Page } from "@playwright/test"; +import { test } from "../support/fixtures"; +import { gotoAppShell, openSettings } from "../support/helpers/app"; +import { renameHostFromSettings } from "../support/helpers/hosts"; +import { getServerId } from "../support/helpers/server-id"; +import { openHostSection, selectSettingsHost } from "../support/helpers/settings"; + +const REGISTRY_KEY = "@paseo:daemon-registry"; +const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce"; +const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once"; + +// What a build with a connection kind this one doesn't know leaves in the registry: an extra +// connection on a host this build can reach, and a host reached only through it. +const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" }; +const UNKNOWN_HOST = { + serverId: "srv_e2e_unknown_connection_host", + label: "Unknown connection host", + connections: [{ id: "future:roof", type: "futureKind", address: "roof" }], + preferredConnectionId: "future:roof", +}; +const OFFLINE_HOST = { + serverId: "srv_e2e_saved_offline_host", + label: "Saved offline host", + password: "e2e-fake-password", + connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }], + preferredConnectionId: "direct:127.0.0.1:59999", +}; + +interface StoredHost { + serverId: string; + label?: string; + password?: string; + connections: unknown[]; +} + +async function addUnreadableEntriesAndReload(page: Page): Promise { + await page.evaluate( + ({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => { + const nonce = localStorage.getItem(keys.nonce); + if (!nonce) { + throw new Error("Expected the e2e seed nonce before overriding the host registry."); + } + const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]"); + registry + .find((host) => host.serverId === primaryServerId) + ?.connections.push(unknownConnection); + registry.push(offlineHost, unknownHost); + localStorage.setItem(keys.registry, JSON.stringify(registry)); + localStorage.setItem(keys.disableSeedOnce, nonce); + }, + { + keys: { + registry: REGISTRY_KEY, + nonce: SEED_NONCE_KEY, + disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY, + }, + primaryServerId: getServerId(), + unknownConnection: UNKNOWN_CONNECTION, + offlineHost: OFFLINE_HOST, + unknownHost: UNKNOWN_HOST, + }, + ); + await page.reload(); +} + +async function readStoredRegistry(page: Page): Promise { + return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY); +} + +async function readStoredHost(page: Page, serverId: string): Promise { + return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId); +} + +test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({ + page, +}) => { + await gotoAppShell(page); + await addUnreadableEntriesAndReload(page); + + await test.step("both readable hosts are listed", async () => { + await page.getByTestId("sidebar-hosts-trigger").click(); + await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible(); + await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible(); + await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0); + await page.keyboard.press("Escape"); + }); + + await test.step("renaming a host keeps its password and the entries it can't read", async () => { + await openSettings(page); + await selectSettingsHost(page, OFFLINE_HOST.serverId); + await openHostSection(page, OFFLINE_HOST.serverId, "host"); + await renameHostFromSettings(page, "Renamed offline host"); + + await expect + .poll(() => readStoredHost(page, OFFLINE_HOST.serverId)) + .toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password }); + const stored = await readStoredRegistry(page); + expect(stored?.map((host) => host.serverId)).toEqual([ + getServerId(), + OFFLINE_HOST.serverId, + UNKNOWN_HOST.serverId, + ]); + expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION); + expect(stored?.[2]).toEqual(UNKNOWN_HOST); + }); +}); diff --git a/packages/app/src/runtime/host-runtime.test.ts b/packages/app/src/runtime/host-runtime.test.ts index 1981a68975..fa4520e62e 100644 --- a/packages/app/src/runtime/host-runtime.test.ts +++ b/packages/app/src/runtime/host-runtime.test.ts @@ -2256,6 +2256,59 @@ describe("HostRuntimeController", () => { }); }); +const REGISTRY_KEY = "@paseo:daemon-registry"; +const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" }; +const directA: HostConnection = { + id: "direct:lan-a:6767", + type: "directTcp", + endpoint: "lan-a:6767", +}; +const directB: HostConnection = { + id: "direct:lan-b:6767", + type: "directTcp", + endpoint: "lan-b:6767", +}; +// What a build with a connection kind this one doesn't know leaves behind: an extra connection +// on a host this build can reach, and a host reached only through it. +const storedWithUnreadableEntries = [ + { + ...makeHost({ serverId: "srv_a", password: "secret-a" }), + connections: [futureConnection, directA], + }, + makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }), + { serverId: "srv_future", label: "future host", connections: [futureConnection] }, +]; + +async function bootWithRegistry(registry: string): Promise<{ + store: HostRuntimeStore; + storage: HostRuntimeStorage; +}> { + const storage = createMemoryHostRuntimeStorage({ + [REGISTRY_KEY]: registry, + "@paseo:e2e": "1", + }); + const store = new HostRuntimeStore({ + storage, + deps: { + createClient: () => new FakeDaemonClient() as unknown as DaemonClient, + connectToDaemon: async ({ host }) => ({ + client: makeConnectedProbeClient(5) as unknown as DaemonClient, + serverId: host.serverId, + hostname: host.label ?? null, + }), + getClientId: async () => "cid_test_runtime", + }, + revokePushNotifications: async () => undefined, + }); + await store.boot(); + return { store, storage }; +} + +async function readRegistry(storage: HostRuntimeStorage): Promise { + const raw = await storage.getItem(REGISTRY_KEY); + return raw === null ? null : JSON.parse(raw); +} + describe("HostRuntimeStore", () => { function gatewayRecoveryFixture() { const parent = new FakeDaemonClient(); @@ -2686,6 +2739,98 @@ describe("HostRuntimeStore", () => { session.clearSession(host.serverId); }); + it("keeps readable hosts when the registry holds entries this build can't read", async () => { + const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries)); + + expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([ + ["srv_a", "secret-a"], + ["srv_b", "secret-b"], + ]); + expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([ + directA.id, + ]); + expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries); + + store.syncHosts([]); + }); + + it("keeps the entries it can't read when it saves the registry", async () => { + const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries)); + + await store.renameHost("srv_b", "renamed"); + + expect(await readRegistry(storage)).toMatchObject([ + { + serverId: "srv_a", + password: "secret-a", + connections: [{ id: directA.id }, futureConnection], + }, + { serverId: "srv_b", password: "secret-b", label: "renamed" }, + storedWithUnreadableEntries[2], + ]); + + store.syncHosts([]); + }); + + it("moves a stored connection password to its host and keeps the connection it can't read", async () => { + const { store, storage } = await bootWithRegistry( + JSON.stringify([ + { + serverId: "srv_legacy", + connections: [ + { type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" }, + futureConnection, + ], + }, + ]), + ); + + expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([ + ["srv_legacy", "old-secret"], + ]); + await vi.waitFor(async () => + expect(await readRegistry(storage)).toMatchObject([ + { serverId: "srv_legacy", password: "old-secret" }, + ]), + ); + expect(await readRegistry(storage)).toMatchObject([ + { connections: [{ ...directA, useTls: false }, futureConnection] }, + ]); + const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>; + expect(written?.connections[0]).not.toHaveProperty("password"); + + store.syncHosts([]); + }); + + it("forgets an entry it can't read once that host is paired again and removed", async () => { + const { store, storage } = await bootWithRegistry( + JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]), + ); + expect(store.getHosts()).toEqual([]); + + await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint }); + await vi.waitFor(async () => + expect(await readRegistry(storage)).toMatchObject([ + { serverId: "srv_future", connections: [{ id: directA.id }] }, + ]), + ); + + await store.removeHost("srv_future"); + expect(await readRegistry(storage)).toEqual([]); + + store.syncHosts([]); + }); + + it("copies a registry that isn't JSON aside instead of deleting it", async () => { + const { store, storage } = await bootWithRegistry("{not json"); + + expect(store.getHosts()).toEqual([]); + expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json"); + expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json"); + + store.syncHosts([]); + }); + it("marks the host registry loaded after boot reads storage", async () => { const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON; process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint"; diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index b2d6871f0c..f883c19b65 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -17,14 +17,16 @@ import { import { connectionFromListen, createRemoteSshHostConnection, - normalizeStoredHostProfile, + forgetUnreadableHost, pinRelayProtectedSecurityInProfiles, + readHostRegistry, upsertHostConnectionInProfiles, registryHasConnection, relayConnectionFromOffer, - StoredHostRegistrySchema, + writeHostRegistry, type HostConnection, type HostProfile, + type UnreadableHostEntries, } from "@/types/host-connection"; import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance"; import { @@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform"; import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection"; import { getOrCreateClientId } from "@/utils/client-id"; import { z } from "zod"; -import { readValidatedJson, readValidatedString } from "@/storage/validated-storage"; +import { readValidatedString } from "@/storage/validated-storage"; import { selectBestConnection, type ConnectionCandidate, @@ -1692,6 +1694,7 @@ export class HostRuntimeStore { private hostListVersion = 0; private hostRegistryLoaded = false; private hosts: HostProfile[] = []; + private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() }; private hostAppearanceMutationTail: Promise = Promise.resolve(); private hostRegistryStatus: HostRegistryStatus = "loading"; private deps: HostRuntimeControllerDeps; @@ -1799,32 +1802,17 @@ export class HostRuntimeStore { let shouldPersistHosts = false; let profiles: HostProfile[] = []; try { - const stored = await readValidatedJson( - this.storage, - REGISTRY_STORAGE_KEY, - StoredHostRegistrySchema, - ); + const stored = await this.readStoredRegistry(); if (stored) { - const normalizedProfiles: HostProfile[] = []; - for (const entry of stored) { - const profile = normalizeStoredHostProfile(entry); - if (!profile) { - await this.storage.removeItem(REGISTRY_STORAGE_KEY); - normalizedProfiles.length = 0; - break; - } - // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration. - if ( - entry.connections.some( - (connection) => connection.type === "directTcp" && connection.password, - ) - ) { - shouldPersistHosts = true; - } - normalizedProfiles.push(profile); + // An entry this build can't read skips only that host or connection, and stays stored. + const registry = readHostRegistry(stored); + this.unreadableHosts = registry.unreadable; + // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration. + if (registry.movedConnectionPassword) { + shouldPersistHosts = true; } - profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId)); - if (profiles.length !== normalizedProfiles.length) { + profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId)); + if (profiles.length !== registry.hosts.length) { shouldPersistHosts = true; } } @@ -2320,6 +2308,7 @@ export class HostRuntimeStore { async removeHost(serverId: string): Promise { await this.revokePushNotifications({ client: this.getClient(serverId), serverId }); const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId); + this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId); this.setHostsAndSync(remaining); await this.persistHosts(); } @@ -2408,7 +2397,27 @@ export class HostRuntimeStore { } private async persistHosts(hosts = this.hosts): Promise { - await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts)); + await this.storage.setItem( + REGISTRY_STORAGE_KEY, + JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)), + ); + } + + /** + * Reads the stored registry without removing it. A value that isn't a JSON array is copied to + * `:unreadable` first, because the next save overwrites the key. + */ + private async readStoredRegistry(): Promise { + const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY); + if (raw === null) return null; + try { + const value: unknown = JSON.parse(raw); + if (Array.isArray(value)) return value; + } catch { + // Not JSON: copied aside below. + } + await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw); + return null; } private emitHostList(): void { diff --git a/packages/app/src/types/host-connection.test.ts b/packages/app/src/types/host-connection.test.ts index 8d7fb87b35..36c652ccab 100644 --- a/packages/app/src/types/host-connection.test.ts +++ b/packages/app/src/types/host-connection.test.ts @@ -5,9 +5,11 @@ import { normalizeStoredHostProfile, orderHostsLocalFirst, pinRelayProtectedSecurityInProfiles, + readHostRegistry, relayConnectionFromOffer, resolveActiveHostServerId, upsertHostConnectionInProfiles, + writeHostRegistry, type HostConnection, type HostProfile, } from "./host-connection"; @@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => { expect(profile?.connections[0]).not.toHaveProperty("password"); }); + it("drops a connection kind this build doesn't know and keeps the host", () => { + const profile = normalizeStoredHostProfile({ + serverId: "srv_mixed", + password: "secret", + connections: [ + { id: "future:1", type: "futureKind", address: "future.example.com" }, + { id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true }, + { id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" }, + ], + preferredConnectionId: "direct:remote:6767", + }); + + expect(profile?.password).toBe("secret"); + expect(profile?.connections).toEqual([ + { id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false }, + ]); + expect(profile?.preferredConnectionId).toBe("direct:remote:6767"); + }); + it("preserves legacy relay ids when TLS is absent", () => { const profile = normalizeStoredHostProfile({ serverId: "srv_relay", @@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => { }); }); +describe("readHostRegistry and writeHostRegistry", () => { + const direct: HostConnection = { + id: "direct:lan:6767", + type: "directTcp", + endpoint: "lan:6767", + useTls: false, + }; + const future = { id: "future:1", type: "futureKind", address: "future.example.com" }; + + it("writes back every entry it could not read", () => { + const unreadableHost = { serverId: "srv_future", connections: [future] }; + const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 }; + const stored = [ + { ...makeHost("srv_a"), connections: [direct, future] }, + unreadableHost, + hostWithFutureField, + "not a host", + ]; + + const { hosts, unreadable } = readHostRegistry(stored); + expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]); + expect(hosts[0]?.connections).toEqual([direct]); + + expect(writeHostRegistry(hosts, unreadable)).toEqual([ + { ...hosts[0], connections: [direct, future] }, + unreadableHost, + hostWithFutureField, + "not a host", + ]); + }); + + it("writes a host saved again by this build in place of the entry it could not read", () => { + const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]); + expect(hosts).toEqual([]); + + const saved = { ...makeHost("srv_a"), connections: [direct] }; + expect(writeHostRegistry([saved], unreadable)).toEqual([saved]); + }); + + it("moves a stored direct TCP password to its host next to a connection it can't read", () => { + const registry = readHostRegistry([ + { + serverId: "srv_legacy", + connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }], + }, + ]); + + expect(registry.movedConnectionPassword).toBe(true); + expect(registry.hosts[0]?.password).toBe("old-secret"); + expect(registry.hosts[0]?.connections).toEqual([direct]); + }); +}); + describe("createRemoteSshHostConnection", () => { it("keeps optional SSH settings absent", () => { expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({ diff --git a/packages/app/src/types/host-connection.ts b/packages/app/src/types/host-connection.ts index e7449b9a67..d830955118 100644 --- a/packages/app/src/types/host-connection.ts +++ b/packages/app/src/types/host-connection.ts @@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({ label: z.string().optional(), appearance: HostAppearanceSchema.optional(), lifecycle: z.strictObject({}).optional(), - connections: z.array(StoredHostConnectionSchema).min(1), + // Read one by one, so a connection kind another build wrote skips only that connection. + connections: z.array(z.unknown()).min(1), preferredConnectionId: z.string().nullable().optional(), createdAt: z.string().datetime({ offset: true }).optional(), updatedAt: z.string().datetime({ offset: true }).optional(), }); -export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema); type StoredHostConnection = z.infer; function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null { @@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec } export function normalizeStoredHostProfile(entry: unknown): HostProfile | null { + return readStoredHost(entry)?.profile ?? null; +} + +interface StoredHostRead { + profile: HostProfile; + unreadableConnections: unknown[]; + movedConnectionPassword: boolean; +} + +function readStoredHost(entry: unknown): StoredHostRead | null { const result = StoredHostProfileSchema.safeParse(entry); if (!result.success) { return null; } const record = result.data; const serverId = record.serverId; + const storedConnections: StoredHostConnection[] = []; + const unreadableConnections: unknown[] = []; + for (const stored of record.connections) { + const parsed = StoredHostConnectionSchema.safeParse(stored); + if (parsed.success) storedConnections.push(parsed.data); + else unreadableConnections.push(stored); + } // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated. - const legacyPassword = record.connections.find( + const legacyPassword = storedConnections.find( (connection) => connection.type === "directTcp" && connection.password, ); const password = record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined); - const connections = record.connections + const connections = storedConnections .map((connection) => normalizeStoredConnection(connection)) .filter((connection): connection is HostConnection => connection !== null); if (connections.length === 0) { @@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null { : (connections[0]?.id ?? null); return { - serverId, - ...(password ? { password } : {}), - label, - appearance: record.appearance ?? defaultHostAppearance(), - lifecycle: defaultLifecycle(), - connections, - preferredConnectionId, - createdAt: record.createdAt ?? now, - updatedAt: record.updatedAt ?? now, + profile: { + serverId, + ...(password ? { password } : {}), + label, + appearance: record.appearance ?? defaultHostAppearance(), + lifecycle: defaultLifecycle(), + connections, + preferredConnectionId, + createdAt: record.createdAt ?? now, + updatedAt: record.updatedAt ?? now, + }, + unreadableConnections, + movedConnectionPassword: legacyPassword !== undefined, }; } +/** + * Stored registry entries this build can't read, such as a connection kind added by a newer + * build. `writeHostRegistry` writes them back so that build still finds them. + */ +export interface UnreadableHostEntries { + hosts: unknown[]; + connectionsByServerId: Map; +} + +export function readHostRegistry(stored: unknown[]): { + hosts: HostProfile[]; + unreadable: UnreadableHostEntries; + // COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration. + movedConnectionPassword: boolean; +} { + const hosts: HostProfile[] = []; + const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() }; + let movedConnectionPassword = false; + for (const entry of stored) { + const read = readStoredHost(entry); + if (!read) { + unreadable.hosts.push(entry); + continue; + } + hosts.push(read.profile); + if (read.unreadableConnections.length > 0) { + unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections); + } + movedConnectionPassword ||= read.movedConnectionPassword; + } + return { hosts, unreadable, movedConnectionPassword }; +} + +export function writeHostRegistry( + hosts: HostProfile[], + unreadable: UnreadableHostEntries, +): unknown[] { + const savedServerIds = new Set(hosts.map((host) => host.serverId)); + const written: unknown[] = hosts.map((host) => { + const kept = unreadable.connectionsByServerId.get(host.serverId); + return kept ? { ...host, connections: [...host.connections, ...kept] } : host; + }); + for (const entry of unreadable.hosts) { + // A host this build saved again replaces the entry it couldn't read. + const serverId = readStoredServerId(entry); + if (serverId === null || !savedServerIds.has(serverId)) written.push(entry); + } + return written; +} + +/** Drops the entries this build couldn't read for a host you removed. */ +export function forgetUnreadableHost( + unreadable: UnreadableHostEntries, + serverId: string, +): UnreadableHostEntries { + const connectionsByServerId = new Map(unreadable.connectionsByServerId); + connectionsByServerId.delete(serverId); + return { + hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId), + connectionsByServerId, + }; +} + +function readStoredServerId(entry: unknown): string | null { + if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null; + return typeof entry.serverId === "string" ? entry.serverId.trim() : null; +} + export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean { return host.connections.some((existing) => hostConnectionEquals(existing, connection)); } From 6eb94611b339529bf3f0b6af092244813655109e Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:03:02 +0000 Subject: [PATCH 119/160] test(e2e): wait for the isolated daemon itself, not any listener on its port (#9863) * test(e2e): wait for the isolated daemon itself, not any listener on its port The helper reserves a port, releases it, and starts the daemon on it. If another process takes the port in between, the daemon exits with EADDRINUSE, but the readiness probe already succeeded against the other listener. The worker fixture then reported the daemon as started and its seed client retried a dead endpoint until the 60s fixture timeout. Readiness now requires /api/status on the port to report this daemon's server id, so the probe keeps waiting, sees the EADDRINUSE exit, and the existing retry moves to a fresh port. * test(e2e): authenticate the readiness probe with the daemon's local credential A password with spaces cannot travel as an HTTP bearer, so the status probe of a password-protected daemon stayed 401. The daemon writes a local credential into its home before listening and /api/status accepts it, as the CLI's local status does. --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../support/helpers/isolated-host-daemon.ts | 52 +++++++++++++------ 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/packages/app/e2e/support/helpers/isolated-host-daemon.ts b/packages/app/e2e/support/helpers/isolated-host-daemon.ts index 3aab184cce..30b2364286 100644 --- a/packages/app/e2e/support/helpers/isolated-host-daemon.ts +++ b/packages/app/e2e/support/helpers/isolated-host-daemon.ts @@ -6,7 +6,7 @@ import { type ChildProcess, type SpawnOptions, } from "node:child_process"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import net from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -59,7 +59,17 @@ export async function getAvailableHostDaemonPort(): Promise { return port; } -async function waitForServer(port: number, child: ChildProcess): Promise { +/** + * Resolves once this daemon answers on its port. An open TCP port is not + * enough: the port is released before the daemon binds it, and whatever takes + * it in between also accepts connections while the daemon exits with + * EADDRINUSE. Only the daemon's own status reports its server id. + */ +async function waitForServer( + port: number, + child: ChildProcess, + identity: { serverId: string; paseoHome: string }, +): Promise { const deadline = Date.now() + 90_000; let lastError: unknown = null; @@ -70,22 +80,13 @@ async function waitForServer(port: number, child: ChildProcess): Promise { ); } try { - await new Promise((resolve, reject) => { - const socket = net.connect(port, "127.0.0.1", () => { - socket.end(); - resolve(); - }); - socket.setTimeout(1_000, () => { - socket.destroy(); - reject(new Error(`Connection timed out to isolated daemon port ${port}`)); - }); - socket.on("error", reject); - }); - return; + const serverId = await readServerId(port, identity.paseoHome); + if (serverId === identity.serverId) return; + lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`); } catch (error) { lastError = error; - await new Promise((resolve) => setTimeout(resolve, 100)); } + await new Promise((resolve) => setTimeout(resolve, 100)); } throw new Error( @@ -95,6 +96,25 @@ async function waitForServer(port: number, child: ChildProcess): Promise { ); } +/** + * Reads the server id from the daemon's status route. The route needs a bearer + * on a password-protected daemon; the daemon accepts the local credential it + * writes into its home before listening, as the CLI does for local status. + */ +async function readServerId(port: number, paseoHome: string): Promise { + const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then( + (token) => token.trim(), + () => null, + ); + const response = await fetch(`http://127.0.0.1:${port}/api/status`, { + headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {}, + signal: AbortSignal.timeout(1_000), + }); + if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`); + const status = (await response.json()) as { serverId?: unknown }; + return String(status.serverId); +} + function withMutableRelay( config: NonNullable, relay: NonNullable, @@ -221,7 +241,7 @@ export async function startIsolatedHostDaemon( }); try { - await waitForServer(port, spawned); + await waitForServer(port, spawned, { serverId, paseoHome }); return spawned; } catch (error) { throw new Error( From c2a24ae81e6f2f91abb84854c2046556355f780b Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:48:36 +0000 Subject: [PATCH 120/160] test(e2e): wait for a plugin modal sheet to settle before using the pointer (#9884) On compact layouts the sheet holds below the viewport and then slides up, so the Horizontal tab hover could resolve its point mid-slide and the wheel landed on the rows below the tabs. openExample now waits for the title to stop moving. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/app/e2e/browser/plugin-modal-body.spec.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/app/e2e/browser/plugin-modal-body.spec.ts b/packages/app/e2e/browser/plugin-modal-body.spec.ts index 33be8a5c40..1da47e7523 100644 --- a/packages/app/e2e/browser/plugin-modal-body.spec.ts +++ b/packages/app/e2e/browser/plugin-modal-body.spec.ts @@ -2,10 +2,15 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture"; import { expect, test as base, type Page } from "../support/fixtures"; import { gotoAppShell } from "../support/helpers/app"; import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace"; +import { waitForSettledPosition } from "../support/helpers/sheet-layout"; async function openExample(page: Page, example: string) { await page.getByRole("button", { name: `Open ${example}`, exact: true }).click(); - await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible(); + const title = page.getByText(`Modal example: ${example}`, { exact: true }); + await expect(title).toBeVisible(); + // A compact sheet holds below the viewport and then slides up, so a pointer placed before it + // stops lands on whatever slides under it. + await waitForSettledPosition(title); } async function closeExample(page: Page) { From b95f1bbf3152e688584d3ad00358b65d7ac78bcd Mon Sep 17 00:00:00 2001 From: Angus Buick <55269277+angusb93@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:58:48 +0000 Subject: [PATCH 121/160] fix(app): draw the Add host text fields as inputs again (#9864) (#9865) AdaptiveTextInput wraps its input with withUnistyles, and the pairing link and direct connection modals wrapped AdaptiveTextInput a second time. On web each wrapper is a display: contents element whose style lands on its direct child, so the outer style landed on the inner wrapper and the input lost its border, background and padding. Drop the outer wrapper, AdaptiveTextInput already themes the placeholder colour. Also give the host password field a placeholder and focus it when pairing asks for a password. --- .../e2e/browser/settings-host-page.spec.ts | 20 +++++++++++++++++++ packages/app/e2e/support/helpers/settings.ts | 8 ++++++++ .../add-host/internal/add-host-modal.tsx | 12 ++++------- .../add-host/internal/pair-link-modal.tsx | 10 ++++------ 4 files changed, 36 insertions(+), 14 deletions(-) diff --git a/packages/app/e2e/browser/settings-host-page.spec.ts b/packages/app/e2e/browser/settings-host-page.spec.ts index 4ada0c7fac..7644e3c0e3 100644 --- a/packages/app/e2e/browser/settings-host-page.spec.ts +++ b/packages/app/e2e/browser/settings-host-page.spec.ts @@ -33,6 +33,8 @@ import { expectNoHostPasswordControls, removeHostFromHostPage, addDirectHostFromSettings, + expectAddHostFieldDrawnAsInput, + selectHostConnectionType, expectHostOnlineWithoutError, expectIdleAgentRelease, editRestartRecoveryPrompt, @@ -307,6 +309,24 @@ async function closeAddHostAndChangeTheme(page: import("@playwright/test").Page) await page.keyboard.press("Control+Alt+t"); } +test("Add host draws its text fields as bordered inputs", async ({ page }) => { + await gotoAppShell(page); + + await test.step("the pairing link field", async () => { + await openSidebarAddHost(page); + await selectHostConnectionType(page, "relay"); + await expectAddHostFieldDrawnAsInput(page, "pair-link-input"); + await page.getByTestId("pair-link-cancel").click(); + }); + + await test.step("the direct connection fields", async () => { + await selectHostConnectionType(page, "direct"); + await expectAddHostFieldDrawnAsInput(page, "direct-host-input"); + await expectAddHostFieldDrawnAsInput(page, "direct-port-input"); + await expectAddHostFieldDrawnAsInput(page, "direct-password-input"); + }); +}); + test("sidebar Add host completes without navigating", async ({ page }) => { await gotoAppShell(page); await expect(page).toHaveURL(/\/open-project$/); diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index ee5aae1f42..303114925c 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -223,6 +223,14 @@ export async function addDirectHostFromSettings( await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 }); } +export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string): Promise { + const field = page.getByTestId(testId); + await expect(field).toBeVisible(); + await expect(field).toHaveCSS("border-top-width", "1px"); + await expect(field).not.toHaveCSS("padding-left", "0px"); + await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)"); +} + export async function toggleHostAdvanced(page: Page): Promise { await page.getByTestId("direct-host-advanced-toggle").click(); } diff --git a/packages/app/src/hosts/add-host/internal/add-host-modal.tsx b/packages/app/src/hosts/add-host/internal/add-host-modal.tsx index 5379e5f4bd..f9ea7a2f86 100644 --- a/packages/app/src/hosts/add-host/internal/add-host-modal.tsx +++ b/packages/app/src/hosts/add-host/internal/add-host-modal.tsx @@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod {t("pairing.direct.fields.host")} - {t("pairing.direct.fields.port")} - {t("pairing.direct.fields.password")} - {t("pairing.direct.advanced.label")} {isAdvancedOpen ? ( - ({ const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted })); const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted })); - -const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, -})); diff --git a/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx b/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx index f817bdc5cf..02653010ba 100644 --- a/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx +++ b/packages/app/src/hosts/add-host/internal/pair-link-modal.tsx @@ -212,7 +212,7 @@ function PairLinkModalContent({ {t("pairing.link.label")} - {t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })} - @@ -275,7 +277,3 @@ function PairLinkModalContent({ } const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground })); - -const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, -})); From 791bbd35969d56f5eb1fe46a992d7de957442644 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:04:19 +0000 Subject: [PATCH 122/160] fix(app): keep preview tab identities unique across split panes (#9888) * fix(app): keep preview tab identities unique across split panes Reserve existing pane and sheet IDs when allocating a new instance, including tabs opened by reconciliation. Keep menu-hosted sheet identities stable across layout changes. Repair duplicate IDs in saved layouts without discarding tabs, state, or pane focus. Resolve file navigation by target rather than an ID retained from a previous preview. * fix(app): open a listed subagent as its own agent tab A subagent opened in place of the compact subagent list got a random instance id, so "Open as tab" created a tab that no longer carried the subagent's agent tab id. The in-place sheet now starts from the subagent's own tab id, still checked against occupied ids and kept stable across layout updates. Co-authored-by: Kosmo CHE <108672813+KosmoCHE@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Kosmo CHE Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Kosmo CHE <108672813+KosmoCHE@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../workspace/workspace-pane-state.test.ts | 73 +++++++ .../screens/workspace/workspace-pane-state.ts | 19 +- .../src/stores/workspace-layout-actions.ts | 88 +++++++- .../app/src/stores/workspace-layout-ids.ts | 16 ++ .../workspace-layout-persistence.test.ts | 78 +++++++ .../src/stores/workspace-layout-store.test.ts | 198 ++++++++++++++++++ .../app/src/stores/workspace-layout-store.ts | 61 ++++-- packages/app/src/subagents/sheet-tab.test.tsx | 82 ++++++++ packages/app/src/subagents/sheet-tab.ts | 13 +- 9 files changed, 583 insertions(+), 45 deletions(-) diff --git a/packages/app/src/screens/workspace/workspace-pane-state.test.ts b/packages/app/src/screens/workspace/workspace-pane-state.test.ts index 778d8fded2..71a557a67c 100644 --- a/packages/app/src/screens/workspace/workspace-pane-state.test.ts +++ b/packages/app/src/screens/workspace/workspace-pane-state.test.ts @@ -106,6 +106,79 @@ describe("workspace-pane-state", () => { }); }); + it("does not locate a file by an id retained from a previous target", () => { + const layout: WorkspaceLayout = { + root: { + kind: "pane", + pane: { + id: "main", + tabIds: ["file_/repo/a.ts", "agent_agent-a"], + focusedTabId: "agent_agent-a", + }, + }, + focusedPaneId: "main", + }; + const tabs = [ + createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }), + createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }), + ]; + const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" }; + + expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({ + kind: "split-side-pane", + paneId: "main", + }); + expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe( + "agent_agent-a", + ); + }); + + it("matches a retained file instance when only the requested line range differs", () => { + const pane = { + id: "main", + tabIds: ["retained-file", "agent_agent-a"], + focusedTabId: "agent_agent-a", + }; + const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" }; + const tabs = [ + createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }), + createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }), + ]; + const target: WorkspaceTab["target"] = { + kind: "file", + path: "/repo/a.ts", + lineStart: 12, + lineEnd: 20, + }; + + expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({ + kind: "open-in-source", + }); + expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe( + "retained-file", + ); + }); + + it("prefers an exact file navigation target over another instance of the same resource", () => { + const pane = { + id: "main", + tabIds: ["first", "second"], + focusedTabId: "first", + }; + const tabs = [ + createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }), + createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }), + ]; + + expect( + deriveWorkspacePaneState({ + pane, + tabs, + preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 }, + }).activeTabId, + ).toBe("second"); + }); + it("resolves side file opens to an existing file tab", () => { const layout: WorkspaceLayout = { root: { diff --git a/packages/app/src/screens/workspace/workspace-pane-state.ts b/packages/app/src/screens/workspace/workspace-pane-state.ts index b188865eeb..2c782ac132 100644 --- a/packages/app/src/screens/workspace/workspace-pane-state.ts +++ b/packages/app/src/screens/workspace/workspace-pane-state.ts @@ -5,12 +5,9 @@ import { } from "@/stores/workspace-layout-store"; import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model"; import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types"; -import { - buildDeterministicWorkspaceTabId, - normalizeWorkspaceTabTarget, - workspaceTabTargetsEqual, -} from "@/workspace-tabs/identity"; +import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity"; import { findAdjacentPane } from "@/utils/split-navigation"; +import { panelResourceKey } from "@/panels/panel-manifest"; export interface WorkspaceDerivedTab { descriptor: WorkspaceTabDescriptor; @@ -124,8 +121,10 @@ function getActiveTabId(input: { } const matchingTab = input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ?? - null; - return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget); + input.tabs.find( + (tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget), + ); + return matchingTab?.descriptor.tabId ?? null; })(); if (preferredTabId && input.openTabIds.has(preferredTabId)) { @@ -211,10 +210,8 @@ export function resolveSideFileOpenPlacement(input: { tabs: WorkspaceTab[]; target: WorkspaceTabTarget; }): WorkspaceSideFileOpenPlacement { - const targetTabId = buildDeterministicWorkspaceTabId(input.target); - const existingTab = input.tabs.find( - (tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target), - ); + const targetKey = panelResourceKey(input.target); + const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey); if (existingTab) { return { kind: "open-in-source" }; } diff --git a/packages/app/src/stores/workspace-layout-actions.ts b/packages/app/src/stores/workspace-layout-actions.ts index cd727a6915..384aa725b2 100644 --- a/packages/app/src/stores/workspace-layout-actions.ts +++ b/packages/app/src/stores/workspace-layout-actions.ts @@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model"; import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants"; import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest"; -import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids"; +import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids"; import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids"; import { buildDeterministicWorkspaceTabId, @@ -137,6 +137,8 @@ interface OpenTabInLayoutInput { placement: WorkspaceTabPlacement; /** Required so a new caller cannot silently opt out of Explorer placement rules. */ explorerSidebarPaneId: string | null; + /** Live sheets share the workspace's panel-instance namespace with its tabs. */ + reservedTabIds?: ReadonlySet; } interface CreateTabInLayoutInput extends OpenTabInLayoutInput { @@ -261,6 +263,7 @@ interface ReorderPaneTabsInLayoutInput { export interface WorkspaceTabReconcileState { layout: WorkspaceLayout; + reservedTabIds?: ReadonlySet; pinnedAgentIds?: ReadonlySet | null; hiddenAgentIds?: ReadonlySet | null; explorerSidebarPaneId: string | null; @@ -398,15 +401,11 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] { if (!Array.isArray(input)) { return []; } + // Preserve colliding entries until the whole layout can assign each an identity. const next: WorkspaceTab[] = []; - const seen = new Set(); for (const value of input) { const tab = normalizeWorkspaceTab(value); - if (!tab || seen.has(tab.tabId)) { - continue; - } - seen.add(tab.tabId); - next.push(tab); + if (tab) next.push(tab); } return next; } @@ -1022,13 +1021,65 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern }; } +function repairDuplicateTabIds(root: SplitNodeInternal): { + root: SplitNodeInternal; + ambiguousIds: ReadonlySet; +} { + const keepers = new Map(); + const ambiguousIds = new Set(); + for (const tab of collectAllTabs(root)) { + const keeper = keepers.get(tab.tabId); + if (!keeper) { + keepers.set(tab.tabId, tab); + continue; + } + ambiguousIds.add(tab.tabId); + if ( + buildDeterministicWorkspaceTabId(tab.target) === tab.tabId && + buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId + ) { + keepers.set(tab.tabId, tab); + } + } + if (ambiguousIds.size === 0) return { root, ambiguousIds }; + + // Reserve every original id before assigning replacements, including hidden panes. + const occupiedIds = new Set(keepers.keys()); + function repair(node: SplitNodeInternal): SplitNodeInternal { + if (node.kind === "group") { + return { ...node, group: { ...node.group, children: node.group.children.map(repair) } }; + } + const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId); + const focusedTab = + focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0]; + let focusedTabId = node.pane.focusedTabId; + const tabs = node.pane.tabs.map((tab) => { + if (keepers.get(tab.tabId) === tab) return tab; + const tabId = allocateWorkspaceTabId( + buildDeterministicWorkspaceTabId(tab.target), + occupiedIds, + ); + occupiedIds.add(tabId); + if (tab === focusedTab) focusedTabId = tabId; + return { ...tab, tabId }; + }); + return { + ...node, + pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId }, + }; + } + return { root: repair(root), ambiguousIds }; +} + export function normalizeLayout(layout: unknown): WorkspaceLayout { if (!layout || typeof layout !== "object") { return createDefaultLayout(); } const rawLayout = layout as WorkspaceLayout; - const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root); + const { root, ambiguousIds } = repairDuplicateTabIds( + normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root), + ); const focusedPaneId = rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId); const resolvedFocusedPaneId = @@ -1047,7 +1098,16 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout { openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)), }); - return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout; + if (parentTabIdByTabId) { + // A duplicated id cannot identify either end of a parent relationship unambiguously. + for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) { + if (ambiguousIds.has(childId) || ambiguousIds.has(parentId)) + delete parentTabIdByTabId[childId]; + } + if (Object.keys(parentTabIdByTabId).length > 0) + return { ...normalizedLayout, parentTabIdByTabId }; + } + return normalizedLayout; } export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null { @@ -1364,7 +1424,9 @@ function insertNewTabIntoPane( return null; } - const tabId = input.createTabId(); + const occupiedIds = new Set(input.reservedTabIds); + for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId); + const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds); const nextTab: WorkspaceTab = { tabId, target: input.target, @@ -2284,6 +2346,7 @@ function openEntityTabWithoutFocusing(input: { layout: WorkspaceLayout; target: WorkspaceTabTarget; explorerSidebarPaneId: string | null; + reservedTabIds: ReadonlySet | undefined; }): WorkspaceLayout { return ( insertNewTabIntoPane({ @@ -2292,6 +2355,7 @@ function openEntityTabWithoutFocusing(input: { now: Date.now(), placement: AMBIENT_PLACEMENT, explorerSidebarPaneId: input.explorerSidebarPaneId, + reservedTabIds: input.reservedTabIds, createTabId: () => buildDeterministicWorkspaceTabId(input.target), focus: false, })?.layout ?? input.layout @@ -2382,6 +2446,7 @@ function addMissingEntityTabs(input: { hasActivePendingTerminalCreate: boolean; hasActivePendingDraftCreate: boolean; explorerSidebarPaneId: string | null; + reservedTabIds: ReadonlySet | undefined; }): WorkspaceLayout { const { autoOpenAgentIds, @@ -2412,6 +2477,7 @@ function addMissingEntityTabs(input: { layout: nextLayout, target: { kind: "agent", agentId }, explorerSidebarPaneId, + reservedTabIds: input.reservedTabIds, }); currentAgentIds.add(agentId); } @@ -2426,6 +2492,7 @@ function addMissingEntityTabs(input: { layout: nextLayout, target: { kind: "terminal", terminalId }, explorerSidebarPaneId, + reservedTabIds: input.reservedTabIds, }); currentTerminalIds.add(terminalId); } @@ -2525,6 +2592,7 @@ export function reconcileWorkspaceTabs( hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false, hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false, explorerSidebarPaneId: state.explorerSidebarPaneId, + reservedTabIds: state.reservedTabIds, }); if (reconciledFocusedTabId) { diff --git a/packages/app/src/stores/workspace-layout-ids.ts b/packages/app/src/stores/workspace-layout-ids.ts index ce4009a2be..f325481af8 100644 --- a/packages/app/src/stores/workspace-layout-ids.ts +++ b/packages/app/src/stores/workspace-layout-ids.ts @@ -11,6 +11,22 @@ function createRandomIdValue(): string { : `${Date.now()}-${Math.random().toString(16).slice(2)}`; } +export function createWorkspaceTabInstanceId(): string { + return `tab_${createRandomIdValue()}`; +} + +/** A resource-derived id may still belong to a preview slot showing another target. */ +export function allocateWorkspaceTabId( + preferredId: string, + occupiedIds: ReadonlySet, +): string { + let tabId = preferredId; + for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) { + tabId = `${preferredId}:${suffix}`; + } + return tabId; +} + export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = { createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`, createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`, diff --git a/packages/app/src/stores/workspace-layout-persistence.test.ts b/packages/app/src/stores/workspace-layout-persistence.test.ts index 47c4ab81da..1c472400ac 100644 --- a/packages/app/src/stores/workspace-layout-persistence.test.ts +++ b/packages/app/src/stores/workspace-layout-persistence.test.ts @@ -59,6 +59,84 @@ it("skips unchanged reconciliations and immediately saves real layout changes", ); }); +it("hydrates a saved preview collision and persists the repaired identities", async () => { + const workspaceKey = "server:workspace"; + const duplicateId = "file_a.ts"; + const values = new Map([ + [ + "workspace-layout-state", + JSON.stringify({ + version: 2, + state: { + layoutByWorkspace: { + [workspaceKey]: { + root: { + kind: "group", + group: { + id: "split", + direction: "horizontal", + sizes: [0.5, 0.5], + children: [ + { id: "main", path: "b.ts" }, + { id: "right", path: "a.ts" }, + ].map(({ id, path }) => ({ + kind: "pane", + pane: { + id, + tabIds: [duplicateId], + focusedTabId: duplicateId, + tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }], + }, + })), + }, + }, + focusedPaneId: "right", + }, + }, + }, + }), + ], + ]); + const storage: StateStorage = { + getItem: (name) => values.get(name) ?? null, + setItem: (name, value) => { + values.set(name, value); + }, + removeItem: (name) => { + values.delete(name); + }, + }; + const store = createWorkspaceLayoutStore(undefined, storage); + await store.persist.rehydrate(); + const layout = store.getState().layoutByWorkspace[workspaceKey]; + const tabs = collectAllTabs(layout.root); + + expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([ + "file_b.ts", + "file_a.ts", + ]); + expect( + deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target, + ).toEqual({ + kind: "file", + path: "b.ts", + }); + expect( + deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target, + ).toEqual({ + kind: "file", + path: "a.ts", + }); + store.getState().focusTab(workspaceKey, "file_b.ts"); + expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main"); + + const reloaded = createWorkspaceLayoutStore(undefined, storage); + await reloaded.persist.rehydrate(); + expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual( + store.getState().layoutByWorkspace[workspaceKey], + ); +}); + it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => { const values = new Map(); const storage: StateStorage = { diff --git a/packages/app/src/stores/workspace-layout-store.test.ts b/packages/app/src/stores/workspace-layout-store.test.ts index 6bb930334a..678f9f5ab6 100644 --- a/packages/app/src/stores/workspace-layout-store.test.ts +++ b/packages/app/src/stores/workspace-layout-store.test.ts @@ -906,6 +906,91 @@ describe("workspace-layout-store actions", () => { ).toEqual(override); }); + it("keeps reused file tabs unique and focuses the matching split pane", () => { + const workspaceKey = createWorkspaceKey(); + const store = workspaceLayoutStore.getState(); + const firstTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + })!; + store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" }); + const rightPaneId = store.splitPaneEmpty(workspaceKey, { + targetPaneId: "main", + position: "right", + }); + if (!rightPaneId) throw new Error("Expected a right split pane"); + const rightTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + placement: { mode: "pane", paneId: rightPaneId }, + })!; + + store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/b.ts" }, + intent: "reveal", + }); + store.focusTab(workspaceKey, rightTabId); + + const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey]; + const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file"); + expect({ + fileTabCount: fileTabs.length, + uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size, + fileTargets: fileTabs.map((tab) => tab.target), + focusedPaneId: layout.focusedPaneId, + }).toEqual({ + fileTabCount: 2, + uniqueFileTabCount: 2, + fileTargets: [ + { kind: "file", path: "src/b.ts" }, + { kind: "file", path: "src/a.ts" }, + ], + focusedPaneId: rightPaneId, + }); + }); + + it("allocates distinct ids across retained tabs, sheets, and background opens", () => { + const workspaceKey = createWorkspaceKey(); + const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds); + const store = layoutStore.getState(); + const fileTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + })!; + store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" }); + layoutStore.setState({ layoutMode: "compact" }); + const sheetTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "reveal", + })!; + const selectedSheet = selectSheetTab(layoutStore.getState(), { + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + }); + expect(selectedSheet?.tab.tabId).toBe(sheetTabId); + const backgroundTabId = store.openTab({ + workspaceKey, + target: { kind: "file", path: "src/a.ts" }, + intent: "background", + })!; + + expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3); + expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1); + expect( + collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root) + .filter((tab) => tab.target.kind === "file") + .map((tab) => tab.target), + ).toEqual([ + { kind: "file", path: "src/b.ts" }, + { kind: "file", path: "src/a.ts" }, + ]); + }); + it("keeps the tab instance when a panel receives a same-kind replacement", () => { const workspaceKey = createWorkspaceKey(); const store = workspaceLayoutStore.getState(); @@ -3200,6 +3285,75 @@ describe("workspace-layout-store actions", () => { ]); }); + it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => { + const file = (tabId: string, path: string) => ({ + tabId, + target: { kind: "file", path }, + createdAt: 1, + state: { treeVisible: true, treeWidth: 280 }, + }); + const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")]; + const rightTabs = [ + file("file_a.ts", "a.ts"), + file("file_b.ts", "b.ts"), + file("file_b.ts:2", "b.ts"), + file("child", "child.ts"), + file("parent", "parent.ts"), + ]; + const layout = normalizeLayout({ + root: { + kind: "group", + group: { + id: "root", + direction: "horizontal", + sizes: [0.4, 0.6], + children: [ + { + kind: "pane", + pane: { + id: "main", + tabs: leftTabs, + tabIds: leftTabs.map((tab) => tab.tabId), + focusedTabId: "file_a.ts", + }, + }, + { + kind: "pane", + pane: { + id: "right", + tabs: rightTabs, + tabIds: rightTabs.map((tab) => tab.tabId), + focusedTabId: "file_a.ts", + hidden: true, + }, + }, + ], + }, + }, + focusedPaneId: "main", + parentTabIdByTabId: { + "file_a.ts": "parent", + "file_b.ts": "file_a.ts", + child: "parent", + }, + }); + const tabs = collectAllTabs(layout.root); + + expect(tabs).toHaveLength(7); + expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7); + expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" }); + expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" }); + expect(tabs.slice(2)).toEqual(rightTabs); + expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]); + expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3"); + expect(findPaneById(layout.root, "right")).toMatchObject({ + hidden: true, + focusedTabId: "file_a.ts", + }); + expect(layout.parentTabIdByTabId).toEqual({ child: "parent" }); + expect(normalizeLayout(layout)).toEqual(layout); + }); + it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => { const tabs = [ { @@ -5110,6 +5264,50 @@ describe("compact workspace sheet", () => { expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]); }); + it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => { + seedAgents([ + { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" }, + { id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" }, + ]); + const store = createCompactStore(); + store.getState().openTab({ + workspaceKey, + target: { kind: "agent", agentId: "child-a" }, + intent: "reveal", + }); + const sheetId = requireTopSheet(store).tab.tabId; + store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" }); + seedAgents([ + { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" }, + { id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" }, + ]); + + store.getState().reconcileTabs(workspaceKey, { + agentsHydrated: true, + terminalsHydrated: true, + activeAgentIds: ["root", "child-a", "child-b"], + autoOpenAgentIds: ["child-a"], + knownTerminalIds: ["term-1"], + standaloneTerminalIds: ["term-1"], + }); + const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find( + (candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a", + ); + if (!tab) throw new Error("Expected the root agent's tab"); + expect(tab.tabId).not.toBe(sheetId); + + store.getState().closeTab(workspaceKey, tab.tabId); + expect(requireTopSheet(store).tab).toMatchObject({ + tabId: sheetId, + target: { kind: "agent", agentId: "child-b" }, + }); + expect( + collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root), + ).not.toContainEqual(tab); + }); + it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => { seedAgents([ { id: "root", parentAgentId: null, workspaceId: "sheet-ws" }, diff --git a/packages/app/src/stores/workspace-layout-store.ts b/packages/app/src/stores/workspace-layout-store.ts index 3e0d14ba6b..f0f6cc308b 100644 --- a/packages/app/src/stores/workspace-layout-store.ts +++ b/packages/app/src/stores/workspace-layout-store.ts @@ -7,6 +7,8 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage" import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model"; import { + allocateWorkspaceTabId, + createWorkspaceTabInstanceId, defaultWorkspaceLayoutIds, type WorkspaceLayoutIdSource, } from "@/stores/workspace-layout-ids"; @@ -431,14 +433,6 @@ function trimNonEmpty(value: string | null | undefined): string | null { return trimmed.length > 0 ? trimmed : null; } -function createWorkspaceTabInstanceId(): string { - const value = - typeof globalThis.crypto?.randomUUID === "function" - ? globalThis.crypto.randomUUID() - : `${Date.now()}-${Math.random().toString(16).slice(2)}`; - return `tab_${value}`; -} - function addAgentIdToWorkspaceSet( state: Record>, workspaceKey: string, @@ -531,7 +525,10 @@ export function selectExplorerSidebarPaneId( */ export function selectSheetTab( state: Pick, - input: Pick, + input: Pick & { + /** A host outside the sheet stack owns its instance identity. */ + preferredTabId?: string; + }, ): SheetTab | null { const workspaceKey = trimNonEmpty(input.workspaceKey); const target = normalizeWorkspaceTabTarget(input.target); @@ -539,9 +536,14 @@ export function selectSheetTab( const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal"); if (!policy) return null; return placeTargetInSheet({ - kept: undefined, + occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey), + kept: input.preferredTabId + ? undefined + : getSheets(state, workspaceKey).find( + (sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target), + ), target, - intent: "reveal", + createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target), policy, parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId), state: undefined, @@ -638,6 +640,7 @@ function getOpenTabPlacement( layout: WorkspaceLayout; placement: WorkspaceTabPlacement; explorerSidebarPaneId: string | null; + reservedTabIds: Set; } { const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey); const explorerSidebarPaneId = resolveExplorerSidebarPaneId( @@ -670,6 +673,7 @@ function getOpenTabPlacement( layout, placement: resolvedPlacement, explorerSidebarPaneId, + reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)), }; } @@ -815,11 +819,23 @@ function resolveOpenParentTabId( return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId; } +function collectWorkspaceTabIds( + state: Pick, + workspaceKey: string, +): Set { + const layout = state.layoutByWorkspace[workspaceKey]; + return new Set([ + ...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []), + ...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId), + ]); +} + function placeTargetInSheet(input: { + occupiedTabIds: ReadonlySet; /** The sheet whose tab the target keeps, if any. */ kept: SheetTab | undefined; target: WorkspaceTabTarget; - intent: WorkspaceTabOpenIntent; + createTabId: () => string; policy: CompactSheetPolicy; parentTabId: string | null; state: JsonValue | undefined; @@ -829,10 +845,7 @@ function placeTargetInSheet(input: { } return { tab: { - tabId: - input.intent === "reveal" - ? buildDeterministicWorkspaceTabId(input.target) - : createWorkspaceTabInstanceId(), + tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds), target: input.target, createdAt: Date.now(), ...(input.state !== undefined ? { state: input.state } : {}), @@ -853,6 +866,7 @@ function promoteSheetToTab( ): { tabId: string; patch: Partial } | null { const { tab } = sheet; const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT); + placement.reservedTabIds.delete(tab.tabId); const input = { ...placement, target: tab.target, @@ -1122,9 +1136,13 @@ export function createWorkspaceLayoutStore( const sheets = getSheets(get(), normalizedWorkspaceKey); const { keptIndex } = sheetPlacement; const sheet = placeTargetInSheet({ + occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey), kept: keptIndex === null ? undefined : sheets[keptIndex], target: normalizedTarget, - intent: input.intent, + createTabId: () => + input.intent === "reveal" + ? buildDeterministicWorkspaceTabId(normalizedTarget) + : createWorkspaceTabInstanceId(), policy: sheetPlacement.policy, parentTabId, state: input.state, @@ -1706,9 +1724,14 @@ export function createWorkspaceLayoutStore( explorerSidebarPaneId, rawLayout.focusedPaneId, ); + const sheets = getSheets(state, normalizedWorkspaceKey); + const fittingSheets = sheets.filter( + (sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot), + ); const nextState = reconcileWorkspaceTabs( { layout: currentLayout, + reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)), pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null, hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null, explorerSidebarPaneId, @@ -1730,10 +1753,6 @@ export function createWorkspaceLayoutStore( ); } } - const sheets = getSheets(state, normalizedWorkspaceKey); - const fittingSheets = sheets.filter( - (sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot), - ); const sheetAgentGone = fittingSheets.length !== sheets.length; if ( state.layoutByWorkspace[normalizedWorkspaceKey] && diff --git a/packages/app/src/subagents/sheet-tab.test.tsx b/packages/app/src/subagents/sheet-tab.test.tsx index c8e0ab7f13..ab57ab9082 100644 --- a/packages/app/src/subagents/sheet-tab.test.tsx +++ b/packages/app/src/subagents/sheet-tab.test.tsx @@ -138,6 +138,88 @@ describe("useSubagentSheetTab", () => { expect(result.current?.tab.tabId).toBe(tabId); }); + it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => { + const row = seedParentWithChild(); + const store = useWorkspaceLayoutStore.getState(); + const reusedId = store.openTab({ + workspaceKey, + target: { kind: "agent", agentId: "child" }, + intent: "reveal", + asTab: true, + }); + if (!reusedId) throw new Error("Expected a child tab"); + store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" }); + store.setLayoutMode("compact"); + const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row)); + const sheetId = result.current?.tab.tabId; + expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" }); + expect(sheetId).not.toBe(reusedId); + + act(() => { + store.reconcileTabs(workspaceKey, { + agentsHydrated: true, + terminalsHydrated: true, + activeAgentIds: ["parent", "child"], + autoOpenAgentIds: [], + knownTerminalIds: [], + standaloneTerminalIds: [], + }); + }); + expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId); + expect(result.current?.tab.tabId).toBe(sheetId); + expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" }); + }); + + it("promotes a menu sheet to the subagent's own tab", () => { + const row = seedParentWithChild(); + const store = useWorkspaceLayoutStore.getState(); + store.setLayoutMode("compact"); + const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row)); + const sheet = result.current; + if (!sheet) throw new Error("Expected a menu sheet"); + + let promotedId: string | null = null; + act(() => { + promotedId = store.openTabInFront(workspaceKey, sheet); + }); + expect(promotedId).toBe("agent_child"); + expect( + store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"), + ).toEqual([ + expect.objectContaining({ + tabId: "agent_child", + target: { kind: "agent", agentId: "child" }, + }), + ]); + }); + + it("does not reuse a menu id retained by a promoted tab showing another target", () => { + const row = seedParentWithChild(); + const store = useWorkspaceLayoutStore.getState(); + store.setLayoutMode("compact"); + const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row)); + const sheet = result.current; + if (!sheet) throw new Error("Expected a menu sheet"); + act(() => { + store.openTabInFront(workspaceKey, sheet); + }); + expect(result.current).toBeNull(); + + act(() => { + store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" }); + }); + expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" }); + expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId); + expect( + store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"), + ).toEqual([ + expect.objectContaining({ + tabId: sheet.tab.tabId, + target: { kind: "agent", agentId: "other" }, + }), + ]); + }); + it("hands a re-rendered row the same sheet", () => { const row = seedParentWithChild(); useWorkspaceLayoutStore.getState().setLayoutMode("compact"); diff --git a/packages/app/src/subagents/sheet-tab.ts b/packages/app/src/subagents/sheet-tab.ts index c81be94ced..783d81bc5d 100644 --- a/packages/app/src/subagents/sheet-tab.ts +++ b/packages/app/src/subagents/sheet-tab.ts @@ -4,6 +4,7 @@ import { useWorkspaceLayoutStore, type SheetTab, } from "@/stores/workspace-layout-store"; +import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity"; import type { WorkspaceTabTarget } from "@/workspace-tabs/model"; import type { SubagentRow } from "./select"; @@ -32,6 +33,9 @@ export function useSubagentSheetTab( const sheets = useWorkspaceLayoutStore((state) => workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined, ); + // Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening + // it as a tab lands on that id, and keeps the id it was given across layout updates. + const tabIds = useMemo(() => new Map(), []); return useMemo(() => { // One answer per row until the state it reads changes, so a re-render of the list hands an // open sheet the same tab rather than a fresh one. @@ -43,16 +47,19 @@ export function useSubagentSheetTab( layoutByWorkspace: layout ? { [workspaceKey]: layout } : {}, sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {}, }; - const key = `${row.kind}:${row.id}`; + const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]); const known = answers.get(key); if (known !== undefined) return known; + const target = subagentRowTarget(row); const sheet = selectSheetTab(state, { workspaceKey, - target: subagentRowTarget(row), + target, parentTabId, + preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target), }); + if (sheet) tabIds.set(key, sheet.tab.tabId); answers.set(key, sheet); return sheet; }; - }, [layout, layoutMode, parentTabId, sheets, workspaceKey]); + }, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]); } From 6ef188416f0507cd20ee18d4d34ab116b8826b06 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:04:29 +0000 Subject: [PATCH 123/160] test(e2e): start the plugin modal settle check once the sheet is in view (#9889) The compact sheet holds below the viewport for a few frames before it slides up. On a slow runner two settle reads 100 ms apart can both land in that hold. Waiting for the title to enter the viewport first means the settle check only starts once the slide has begun. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/app/e2e/browser/plugin-modal-body.spec.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/app/e2e/browser/plugin-modal-body.spec.ts b/packages/app/e2e/browser/plugin-modal-body.spec.ts index 1da47e7523..1ce525269b 100644 --- a/packages/app/e2e/browser/plugin-modal-body.spec.ts +++ b/packages/app/e2e/browser/plugin-modal-body.spec.ts @@ -7,9 +7,10 @@ import { waitForSettledPosition } from "../support/helpers/sheet-layout"; async function openExample(page: Page, example: string) { await page.getByRole("button", { name: `Open ${example}`, exact: true }).click(); const title = page.getByText(`Modal example: ${example}`, { exact: true }); - await expect(title).toBeVisible(); // A compact sheet holds below the viewport and then slides up, so a pointer placed before it - // stops lands on whatever slides under it. + // stops lands on whatever slides under it. The settle check starts once the slide has begun; + // two equal reads during the hold would otherwise count as settled. + await expect(title).toBeInViewport(); await waitForSettledPosition(title); } From 3a7e216b7dc48496a6f7bb0ef26d47ad5d85309f Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:45:26 +0000 Subject: [PATCH 124/160] test(server): read the latest event when checking a removed file on macOS (#9898) macOS FSEvents can replay the file's pre-subscription write as a create after the observer starts. The test read the first event for the path, so it stayed on that create after the delete arrived in a later batch. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/server/src/server/file-observer/index.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/file-observer/index.test.ts b/packages/server/src/server/file-observer/index.test.ts index 92cb5bced4..cf481b6e0a 100644 --- a/packages/server/src/server/file-observer/index.test.ts +++ b/packages/server/src/server/file-observer/index.test.ts @@ -193,10 +193,11 @@ test("classifies a removed file as deleted", async () => { }); await rm(target); - // Native recursive delivery can be coalesced before the backend's deletion audit. - // Assert eventual classification without imposing Vitest's one-second default. + // macOS FSEvents can replay the write above as a create after the subscription starts, + // so the delete is the latest event for the path, not the first. Native recursive delivery + // can also be coalesced before the backend's deletion audit, hence the longer timeout. await expect - .poll(() => events.find((event) => event.path === target)?.type, { timeout: 10_000 }) + .poll(() => events.findLast((event) => event.path === target)?.type, { timeout: 10_000 }) .toBe("delete"); await subscription.unsubscribe(); }); From 038a9ca00dc5c7b85b075f561b40a6770421755a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:03:40 +0000 Subject: [PATCH 125/160] fix(opencode): clear a question that a new message replaces (#9891) With the default send setting, a message sent while an OpenCode agent waits on a question steers the turn, and Paseo rejects the question in OpenCode. The OpenCode session dropped the question from its own list without reporting it resolved, so the agent manager and the app kept showing it. Answering or dismissing it then failed with "No pending permission request", and the prompt could not be closed. The session now reports permission_resolved whenever OpenCode accepts a reply, rejection, or answer, as the other providers do. Fixes #9879 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../agent/providers/opencode-agent.test.ts | 36 ++++++++ .../server/agent/providers/opencode-agent.ts | 26 +++--- ...ncode-question-superseded.real.e2e.test.ts | 87 +++++++++++++++++++ 3 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts diff --git a/packages/server/src/server/agent/providers/opencode-agent.test.ts b/packages/server/src/server/agent/providers/opencode-agent.test.ts index 8b8b0d491d..c0c16a15d0 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.test.ts @@ -2477,6 +2477,42 @@ describe("OpenCode adapter startTurn error handling", () => { await session.close(); }); + test("reports a question rejected by a human steer as resolved", async () => { + const { parent: session, openCode } = await createParentSession("ses_steer_question"); + openCode.sessionPromptAsyncEvents = []; + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + const { turnId } = await session.startTurn("first"); + openCode.emitEvent({ + type: "question.asked", + properties: { + id: "question-steer", + sessionID: "ses_steer_question", + questions: [{ question: "Which color?", header: "Color", options: [] }], + }, + }); + await vi.waitFor(() => expect(session.getPendingPermissions()).toHaveLength(1)); + + await expect( + session.steerActiveTurn?.("never mind", { + expectedTurnId: turnId, + clearPendingPermissions: true, + }), + ).resolves.toEqual({ status: "accepted" }); + + expect(openCode.calls.questionReject).toContainEqual( + expect.objectContaining({ requestID: "question-steer" }), + ); + expect(events).toContainEqual( + expect.objectContaining({ + type: "permission_resolved", + requestId: "question-steer", + resolution: expect.objectContaining({ behavior: "deny" }), + }), + ); + await session.close(); + }); + test("keeps multiple native steers correlated in admission order", async () => { const { parent: session, openCode } = await createParentSession("ses_native_steer_fifo"); openCode.sessionPromptAsyncEvents = []; diff --git a/packages/server/src/server/agent/providers/opencode-agent.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index e702fc6d86..daf3156e30 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -5049,22 +5049,24 @@ class OpenCodeAgentSession implements AgentSession { answers, }); } - - this.pendingPermissions.delete(requestId); - this.pendingPermissionDirectories.delete(requestId); - return; + } else { + const reply = resolveOpenCodePermissionReply(response); + await this.client.permission.reply({ + requestID: requestId, + directory, + reply, + message: response.behavior === "deny" ? response.message : undefined, + }); } - const reply = resolveOpenCodePermissionReply(response); - await this.client.permission.reply({ - requestID: requestId, - directory, - reply, - message: response.behavior === "deny" ? response.message : undefined, - }); - this.pendingPermissions.delete(requestId); this.pendingPermissionDirectories.delete(requestId); + this.notifySubscribers({ + type: "permission_resolved", + provider: "opencode", + requestId, + resolution: response, + }); } describePersistence(): AgentPersistenceHandle | null { diff --git a/packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts new file mode 100644 index 0000000000..3a5594725b --- /dev/null +++ b/packages/server/src/server/daemon-e2e/opencode-question-superseded.real.e2e.test.ts @@ -0,0 +1,87 @@ +import { beforeAll, beforeEach, describe, test, expect } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; + +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { + canRunRealProvider, + createRealProviderClients, + getRealProviderConfig, +} from "./real-provider-test-config.js"; + +async function readStatusAndPendingIds( + client: DaemonClient, + agentId: string, +): Promise<{ status: string; pendingIds: string[] }> { + const fetched = await client.fetchAgent(agentId); + const snapshot = fetched!.agent; + const pendingIds = (snapshot.pendingPermissions ?? []).map((pending) => pending.id); + return { status: snapshot.status, pendingIds }; +} + +describe("daemon E2E (real opencode) - a message sent instead of answering a question", () => { + let canRun = false; + + beforeAll(async () => { + canRun = await canRunRealProvider("opencode"); + }); + + beforeEach((context) => { + if (!canRun) { + context.skip(); + } + }); + + test("removes the superseded question from the pending list", async () => { + const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-opencode-question-")); + const logger = pino({ level: "silent" }); + const daemon = await createTestPaseoDaemon({ + agentClients: createRealProviderClients(["opencode"], logger), + logger, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + + try { + const agent = await client.createAgent({ + ...getRealProviderConfig("opencode"), + cwd, + title: "OpenCode superseded question", + }); + + await client.sendMessage( + agent.id, + [ + "Use the question tool to ask me exactly one clarifying question:", + "What color should the button be?", + "Wait for my answer before doing anything else.", + ].join(" "), + ); + await client.waitForAgentUpsert( + agent.id, + (snapshot) => snapshot.pendingPermissions?.[0]?.kind === "question", + 120_000, + ); + + // The app sends with the default send setting, which steers the running turn. + await client.sendMessage(agent.id, "Never mind the question. Reply with the word done.", { + activeTurnBehavior: "steer", + }); + // OpenCode rejects the question and runs the steer message to completion. + await expect + .poll(() => readStatusAndPendingIds(client, agent.id), { + timeout: 120_000, + interval: 1_000, + }) + .toEqual({ status: "idle", pendingIds: [] }); + } finally { + await client.close().catch(() => undefined); + await daemon.close(); + rmSync(cwd, { recursive: true, force: true }); + } + }, 300_000); +}); From 73c22f7917a541c54f9600f413106e2bbf0b682e Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:59:03 +0000 Subject: [PATCH 126/160] Keep desktop workspaces reachable when sidebar navigation overflows (#9903) * fix(app): keep desktop workspaces reachable when sidebar navigation overflows Apply the mobile cap from #8727 to DesktopSidebar: the navigation rows scroll inside a viewport capped at half the sidebar, so plugin rows no longer push the Workspaces list out of a short window. The viewport sits outside the titlebar drag area and opts out of app regions, since Electron does not clip app-region rects to scroll viewports. Co-Authored-By: Claude Opus 5.5 * fix(app): keep the sidebar drag strip on Windows and Linux Moving the desktop navigation rows into a scroll viewport left the sidebar's drag overlay in an empty container when the window controls sit top-right, so Windows and Linux lost every window-drag surface in the sidebar. The strip above the navigation now carries the drag overlay there, and the rows start flush below it. Refs #9872 Co-authored-by: Alex Tong Co-Authored-By: Claude Opus 5.5 * refactor(app): share the window-content marker from the drag-region module Co-Authored-By: Claude Opus 5.5 * refactor(app): share one nav scroller between the mobile and desktop sidebars The desktop sidebar's capped nav viewport was a plain ScrollView on every platform, so on tablets it did not join the overlay's close swipe the way the mobile nav block and the workspace list do. Both sidebars now render SidebarNavScroll, which owns the 50% cap, the native gesture-handler branch linked to the close gesture, the divider, and the web window-content marker. Co-Authored-By: Claude Opus 5.5 * fix(app): drop the empty nav divider and drag strip when every top item is hidden With every top navigation item turned off, the desktop sidebar now starts at the Workspaces section again, as on main: no 1px divider and no 8px drag strip above it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Alex Tong Co-authored-by: Claude Opus 5.5 Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../e2e/browser/plugin-sidebar-items.spec.ts | 29 ++++ .../e2e/browser/sidebar-nav-settings.spec.ts | 4 + .../desktop/titlebar-drag-region.tsx | 7 + packages/app/src/components/left-sidebar.tsx | 132 ++++++++++++------ .../components/sidebar/sidebar-nav-rows.tsx | 9 +- .../app/src/screens/open-project-screen.tsx | 3 +- .../e2e/sidebar-nav-drag-region.spec.ts | 64 +++++++++ 7 files changed, 201 insertions(+), 47 deletions(-) create mode 100644 packages/desktop/e2e/sidebar-nav-drag-region.spec.ts diff --git a/packages/app/e2e/browser/plugin-sidebar-items.spec.ts b/packages/app/e2e/browser/plugin-sidebar-items.spec.ts index e91b6a55da..3acf19a860 100644 --- a/packages/app/e2e/browser/plugin-sidebar-items.spec.ts +++ b/packages/app/e2e/browser/plugin-sidebar-items.spec.ts @@ -208,6 +208,35 @@ test.describe("Plugin sidebar items", () => { }); }); + test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({ + page, + }) => { + await page.setViewportSize({ width: 1280, height: 480 }); + await gotoAppShell(page); + await expect(botRow(page, "status")).toBeAttached(); + const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`); + await expect(workspace).toBeInViewport({ ratio: 1 }); + await expect(botRow(page, "status")).not.toBeInViewport(); + + await test.step("navigation stays within half the sidebar", async () => { + const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll")); + expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1); + }); + + await test.step("scrolling navigation reaches its last row without moving workspaces", async () => { + const before = await boxOf(workspace); + await visibleTestId(page, "sidebar-global-new-workspace").hover(); + await page.mouse.wheel(0, 800); + await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 }); + await expect(workspace).toBeInViewport({ ratio: 1 }); + expect((await boxOf(workspace)).y).toBe(before.y); + await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled"); + await botRow(page, "status").click(); + await expect(page.getByText("Bot status details", { exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Close bot status", exact: true }).click(); + }); + }); + test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => { await page.setViewportSize(WIDE); await gotoWorkspace(page, workspaceId); diff --git a/packages/app/e2e/browser/sidebar-nav-settings.spec.ts b/packages/app/e2e/browser/sidebar-nav-settings.spec.ts index 618d44729c..005d64c341 100644 --- a/packages/app/e2e/browser/sidebar-nav-settings.spec.ts +++ b/packages/app/e2e/browser/sidebar-nav-settings.spec.ts @@ -110,6 +110,7 @@ test.describe("Sidebar items in Appearance settings", () => { await test.step("the sidebar starts in the default order", async () => { await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]); + await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1); }); await test.step("the Sidebar section lists every item in the same order", async () => { @@ -195,6 +196,9 @@ test.describe("Sidebar items in Appearance settings", () => { await expectSidebarItemHidden(page, "history"); await expectSidebarItemHidden(page, "search"); await expectSidebarItemHidden(page, "schedules"); + // Nothing is left above the Workspaces section: no drag strip, no empty divider. + await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0); + await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0); }); }); diff --git a/packages/app/src/components/desktop/titlebar-drag-region.tsx b/packages/app/src/components/desktop/titlebar-drag-region.tsx index da115c7349..e39e211bf1 100644 --- a/packages/app/src/components/desktop/titlebar-drag-region.tsx +++ b/packages/app/src/components/desktop/titlebar-drag-region.tsx @@ -17,6 +17,13 @@ import { isNative } from "@/constants/platform"; * On macOS, Electron handles edge resize natively. */ +/** + * Marks a scroll viewport as window content: it and its descendants emit no window + * regions, because Electron does not clip app-region rects to scroll viewports. + * See the `[data-window-content]` rule in public/index.html. + */ +export const WINDOW_CONTENT_DATASET = { "window-content": "" }; + export const titlebarDragSurfaceStyle: React.CSSProperties = { cursor: "default", // @ts-expect-error — WebkitAppRegion is not in CSSProperties diff --git a/packages/app/src/components/left-sidebar.tsx b/packages/app/src/components/left-sidebar.tsx index 38b01fd334..55874b0fb1 100644 --- a/packages/app/src/components/left-sidebar.tsx +++ b/packages/app/src/components/left-sidebar.tsx @@ -9,7 +9,16 @@ import { type LucideIcon, } from "lucide-react-native"; import { useTranslation } from "react-i18next"; -import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react"; +import { + memo, + useCallback, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, + type RefObject, +} from "react"; import { Pressable, ScrollView, @@ -19,12 +28,19 @@ import { View, type LayoutChangeEvent, } from "react-native"; -import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler"; +import { + Gesture, + type GestureType, + ScrollView as GHScrollView, +} from "react-native-gesture-handler"; import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated"; import { scheduleOnRN } from "react-native-worklets"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region"; +import { + TitlebarDragRegion, + WINDOW_CONTENT_DATASET, +} from "@/components/desktop/titlebar-drag-region"; import { SidebarCloseButton } from "@/components/headers/sidebar-close-button"; import { resolveDesktopSidebarInsetLeft, @@ -39,7 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker"; import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu"; import { SidebarSeparator } from "@/components/sidebar/sidebar-separator"; import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region"; -import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows"; +import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows"; import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight"; import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu"; import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu"; @@ -622,29 +638,7 @@ function MobileSidebar({ > - {platformIsNative ? ( - - {navRows} - - ) : ( - - {navRows} - - )} - + {navRows} @@ -689,6 +683,47 @@ function MobileSidebar({ ); } +interface SidebarNavScrollProps { + closeGestureRef: RefObject; + /** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */ + windowContent?: boolean; + children: ReactNode; +} + +// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the +// divider below it. The divider is a sibling because Unistyles does not patch the +// gesture-handler ScrollView. +function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) { + return ( + <> + {platformIsNative ? ( + + {children} + + ) : ( + + {children} + + )} + + + ); +} + function DesktopSidebar({ theme, workspaceGroups, @@ -809,12 +844,14 @@ function DesktopSidebar({ ], [insetsTop, insets.bottom, insets.left, overlay, divisionLayout], ); - // Below the window controls' row, or in the top band's place, the first row starts flush. const inTopBand = useTopBand() !== null; - const sidebarHeaderGroupStyle = useMemo( - () => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush], - [ownsTopLeft, inTopBand], - ); + // Windows and Linux draw their window controls top-right, so the sidebar has no chrome + // row there. The strip above the scrolling rows is then its window drag surface. + const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL); + // With every top item hidden the sidebar starts at the Workspaces section, as before the + // nav scroller existed: no strip above it and no divider below it. + const hasNavRows = useVisibleSidebarNavItems().length > 0; + const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand; return ( - {ownsTopLeft || DEV_BUILD_LABEL ? ( + {showsChromeRow ? ( {DEV_BUILD_LABEL ? ( @@ -842,11 +879,21 @@ function DesktopSidebar({ ) : null} - ) : ( - - )} - + ) : null} + {showsDragStrip ? ( + + + + ) : null} + {/* The drag overlay stays above this viewport: Electron does not clip + app-region rects to scroll viewports, so a scrolled-out row would + still claim its no-drag rect. */} + {hasNavRows ? ( + + + + ) : null} @@ -935,19 +982,18 @@ const staticStyles = RNStyleSheet.create({ }); const styles = StyleSheet.create((theme) => ({ + // The rows start flush: the chrome row, drag strip, or top band above them gives the inset. sidebarHeaderGroup: { - paddingTop: theme.spacing[2], gap: 2, paddingBottom: theme.spacing[1.5], - borderBottomWidth: 1, - borderBottomColor: theme.colors.border, }, - sidebarHeaderGroupFlush: { - paddingTop: 0, + desktopDragStrip: { + position: "relative", + height: theme.spacing[2], }, // The nav block caps at half the sidebar; a long item list scrolls inside the // cap instead of crowding the workspace list off a short screen. - mobileNavScroll: { + navScroll: { flexGrow: 0, flexShrink: 1, maxHeight: "50%", diff --git a/packages/app/src/components/sidebar/sidebar-nav-rows.tsx b/packages/app/src/components/sidebar/sidebar-nav-rows.tsx index 0f7e8c24ca..88693752dd 100644 --- a/packages/app/src/components/sidebar/sidebar-nav-rows.tsx +++ b/packages/app/src/components/sidebar/sidebar-nav-rows.tsx @@ -35,14 +35,19 @@ interface SidebarNavRowsProps extends SidebarNavRowProps { firstRowTrailing?: ReactNode; } +/** The top-level items the user keeps visible, in display order. */ +export function useVisibleSidebarNavItems() { + const { items } = useSidebarNavItems("header"); + return useMemo(() => items.filter((item) => item.visible), [items]); +} + /** * Top-level sidebar navigation, ordered and filtered by the user's * `sidebarNavItems` preference. Renders nothing — not even the bordered group * wrapper — when every item is hidden and there is no `firstRowTrailing`. */ export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) { - const { items } = useSidebarNavItems("header"); - const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]); + const visibleItems = useVisibleSidebarNavItems(); const groupRef = useRef(null); if (visibleItems.length === 0 && !firstRowTrailing) return null; diff --git a/packages/app/src/screens/open-project-screen.tsx b/packages/app/src/screens/open-project-screen.tsx index 4fcbb4d2fc..0f55a9eeb3 100644 --- a/packages/app/src/screens/open-project-screen.tsx +++ b/packages/app/src/screens/open-project-screen.tsx @@ -21,8 +21,7 @@ import { import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; import { PairDeviceModal } from "@/desktop/components/pair-device-modal"; import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; - -const WINDOW_CONTENT_DATASET = { "window-content": "" }; +import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region"; export function OpenProjectScreen() { const { t } = useTranslation(); diff --git a/packages/desktop/e2e/sidebar-nav-drag-region.spec.ts b/packages/desktop/e2e/sidebar-nav-drag-region.spec.ts new file mode 100644 index 0000000000..18e1e7c91b --- /dev/null +++ b/packages/desktop/e2e/sidebar-nav-drag-region.spec.ts @@ -0,0 +1,64 @@ +import type { Page } from "@playwright/test"; +import { test, expect } from "../../app/e2e/support/fixtures"; +import { gotoAppShell } from "../../app/e2e/support/helpers/app"; + +// Windows and Linux draw their window controls top-right, so the desktop sidebar has no +// chrome row of its own. Its window-drag surface is the strip above the navigation rows. +const CUSTOM_CHROME_HOSTS = [ + { platform: "linux", windowChromeMode: "custom-linux" }, + { platform: "win32", windowChromeMode: "custom-windows" }, +] as const; + +async function installDesktopHost( + page: Page, + host: (typeof CUSTOM_CHROME_HOSTS)[number], +): Promise { + await page.addInitScript((desktopHost) => { + window.paseoDesktop = { + ...desktopHost, + events: { on: () => () => {} }, + invoke: async (command: string) => { + if (command === "get_desktop_settings") { + return { + releaseChannel: "stable", + daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true }, + }; + } + return null; + }, + }; + }, host); +} + +async function sidebarDragGeometry(page: Page) { + const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first(); + await expect(navScroll).toBeVisible(); + return navScroll.evaluate((node) => { + const nav = node.getBoundingClientRect(); + const dragRegions = []; + for (const element of document.querySelectorAll("*")) { + if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue; + const rect = element.getBoundingClientRect(); + const overSidebar = rect.left < nav.right && rect.right > nav.left; + if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom }); + } + return { navTop: nav.top, navBottom: nav.bottom, dragRegions }; + }); +} + +for (const host of CUSTOM_CHROME_HOSTS) { + test.describe(`Desktop sidebar on ${host.platform}`, () => { + test.use({ viewport: { width: 1280, height: 480 } }); + + test("keeps a window drag strip above the scrolling navigation", async ({ page }) => { + await installDesktopHost(page, host); + await gotoAppShell(page); + + const geometry = await sidebarDragGeometry(page); + expect(geometry.dragRegions).not.toEqual([]); + for (const region of geometry.dragRegions) { + expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1); + } + }); + }); +} From 8f3752ecb9a5239ae767bde03dde73c45eb7e6b3 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:36:12 +0000 Subject: [PATCH 127/160] test(app): wait for a label filter row to be laid out before measuring it (#9922) The workspace-labels journey measured the Urgent filter row right after opening the label filter page. While the page is still coming in, the row has no box yet, and the measuring helper threw inside expect.poll, which ends the poll instead of retrying it. An element with no box now counts as not settled, and the helper returns the box it settled on instead of measuring a second time. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../app/e2e/browser/workspace-labels.spec.ts | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/packages/app/e2e/browser/workspace-labels.spec.ts b/packages/app/e2e/browser/workspace-labels.spec.ts index 71dcc755ae..6712d1fd40 100644 --- a/packages/app/e2e/browser/workspace-labels.spec.ts +++ b/packages/app/e2e/browser/workspace-labels.spec.ts @@ -73,35 +73,36 @@ function labelRow(page: import("@playwright/test").Page, name: string) { return page.getByTestId(`workspace-label-picker-row-${name}`); } -async function box(locator: import("@playwright/test").Locator) { - const measured = await locator.boundingBox(); - if (!measured) throw new Error("expected a visible element to measure"); - return measured; -} - async function size(locator: import("@playwright/test").Locator) { - await settled(locator); - const { width, height } = await box(locator); + const { width, height } = await settled(locator); return { width, height }; } /** - * Waits until an element stops moving. + * Waits until an element is on screen and stops moving, and returns where it settled. * * The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail * measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls - * would take its two halves from two different frames. + * would take its two halves from two different frames. A row that has not been laid out yet has + * no box at all; that is not settled either, so the poll keeps waiting instead of failing. */ async function settled(locator: import("@playwright/test").Locator) { - let previous = ""; + const last: { box: Awaited>; key: string | null } = { + box: null, + key: null, + }; await expect .poll(async () => { - const current = JSON.stringify(await box(locator)); - const stable = current === previous; - previous = current; + const current = await locator.boundingBox(); + const key = current ? JSON.stringify(current) : null; + const stable = key !== null && key === last.key; + last.box = current; + last.key = key; return stable; }) .toBe(true); + if (!last.box) throw new Error("a settled element has a box"); + return last.box; } async function expectAssigned( From ce09360241c5f87d014100ff6b9bb613d2ea9c7e Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:55:35 +0000 Subject: [PATCH 128/160] fix(server): agents archived while not loaded get the archive time as their last update (#9926) * fix(server): move updatedAt when archiving an agent that is only in storage Archiving a loaded agent sets its updatedAt to the archive time (markRecordArchived). Archiving an agent that is only in storage, which is also how a parent's archive reaches its children, kept the old updatedAt. Lists sorted by updated_at, such as History, then left a just-archived agent where its last turn put it, sometimes days back, and clients paging such a list by time never reached it. archiveSnapshotUnlocked now records the archive time as updatedAt too. Co-authored-by: RoundRedDot * fix(server): keep updatedAt from moving back when an archive is restored Archiving a stored-only agent now sets updatedAt to the archive time. When the archive time is earlier than the record's updatedAt, as when a failed send or resume puts an agent's original archive back after unarchiving it, updatedAt stays where it is. Clients drop agent updates that are older than the one they hold, so moving it back left them showing the agent active. Co-authored-by: luke Co-Authored-By: Claude Opus 5.5 * fix(server): keep updatedAt from moving back when a loaded agent's archive is restored The rule that archiving never moves updatedAt backwards now lives in buildArchivedAgentRecord, which both archive paths use. A failed send that resumed the agent before a later loading step failed puts its original archive back through the loaded path, which had the same backwards move. The workspace archive stamp test now uses stamps taken after the agents' activity, as real archive stamps are. Co-authored-by: luke Co-Authored-By: Claude Opus 5.5 * refactor(server): require the archive time when building an archived agent buildArchivedAgentRecord no longer accepts an archive that leaves updatedAt unset, the gap #9920 came through, and its tests now assert the rule: a later archive time moves updatedAt, an earlier one keeps it. Co-authored-by: luke Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: luke Co-authored-by: RoundRedDot Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/agent-archive.test.ts | 36 +++--- .../server/src/server/agent/agent-archive.ts | 19 ++- .../src/server/agent/agent-manager.test.ts | 116 +++++++++++++++++- .../server/src/server/agent/agent-manager.ts | 8 +- 4 files changed, 153 insertions(+), 26 deletions(-) diff --git a/packages/server/src/server/agent/agent-archive.test.ts b/packages/server/src/server/agent/agent-archive.test.ts index c4dd34b7e2..21be7eef5f 100644 --- a/packages/server/src/server/agent/agent-archive.test.ts +++ b/packages/server/src/server/agent/agent-archive.test.ts @@ -14,18 +14,19 @@ const BASE_RECORD: StoredAgentRecord = { config: null, }; +const ARCHIVE = { + archivedAt: "2025-01-03T00:00:00.000Z", + updatedAt: "2025-01-03T00:00:00.000Z", +}; + test("archives a stored agent without changing terminal statuses", () => { const statuses: Array = ["idle", "error", "closed"]; for (const status of statuses) { - const archived = buildArchivedAgentRecord( - { ...BASE_RECORD, lastStatus: status }, - { archivedAt: "2025-01-03T00:00:00.000Z" }, - ); + const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE); expect(archived.lastStatus).toBe(status); expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z"); - expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt); } }); @@ -33,10 +34,7 @@ test("archives busy stored agents as idle", () => { const statuses: Array = ["initializing", "running"]; for (const status of statuses) { - const archived = buildArchivedAgentRecord( - { ...BASE_RECORD, lastStatus: status }, - { archivedAt: "2025-01-03T00:00:00.000Z" }, - ); + const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE); expect(archived.lastStatus).toBe("idle"); } @@ -50,7 +48,7 @@ test("clears persisted attention when archiving", () => { attentionReason: "finished", attentionTimestamp: "2025-01-02T12:00:00.000Z", }, - { archivedAt: "2025-01-03T00:00:00.000Z" }, + ARCHIVE, ); expect(archived).toMatchObject({ @@ -60,11 +58,19 @@ test("clears persisted attention when archiving", () => { }); }); -test("can stamp updatedAt to the archive timestamp", () => { - const archived = buildArchivedAgentRecord(BASE_RECORD, { - archivedAt: "2025-01-03T00:00:00.000Z", - updatedAt: "2025-01-03T00:00:00.000Z", - }); +test("moves updatedAt to the archive time", () => { + const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE); expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z"); }); + +test("keeps a later updatedAt when the archive time is earlier", () => { + // Putting an original archive back after a failed unarchive must not move updatedAt backwards. + const archived = buildArchivedAgentRecord( + { ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" }, + ARCHIVE, + ); + + expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z"); + expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z"); +}); diff --git a/packages/server/src/server/agent/agent-archive.ts b/packages/server/src/server/agent/agent-archive.ts index 7e35d98f89..a66b82c620 100644 --- a/packages/server/src/server/agent/agent-archive.ts +++ b/packages/server/src/server/agent/agent-archive.ts @@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js"; export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string }; interface BuildArchivedAgentRecordOptions { - archivedAt?: string; - updatedAt?: string; + archivedAt: string; + /** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */ + updatedAt: string; } export function buildArchivedAgentRecord( record: StoredAgentRecord, - options?: BuildArchivedAgentRecordOptions, + options: BuildArchivedAgentRecordOptions, ): ArchivedStoredAgentRecord { - const archivedAt = options?.archivedAt ?? new Date().toISOString(); return { ...record, - archivedAt, - updatedAt: options?.updatedAt ?? record.updatedAt, + archivedAt: options.archivedAt, + updatedAt: latestTimestamp(record.updatedAt, options.updatedAt), lastStatus: normalizeArchivedStatus(record.lastStatus), requiresAttention: false, attentionReason: null, @@ -23,6 +23,13 @@ export function buildArchivedAgentRecord( }; } +// Archiving is the agent's latest change. An earlier archive time (an original archive put back +// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is +// older than the one they hold. +function latestTimestamp(current: string, archiveTime: string): string { + return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current; +} + function normalizeArchivedStatus( status: StoredAgentRecord["lastStatus"], ): StoredAgentRecord["lastStatus"] { diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 352391108f..5274953e0d 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -6494,6 +6494,114 @@ test("archiveSnapshot dispatches archived state for stored-only agents", async ( expect(last.lifecycle).toBe("closed"); }); +test("archiveSnapshot moves a stored-only agent's updatedAt to its archive time, as a live archive does", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-updated-at-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + + const created = await manager.createAgent( + { provider: "codex", cwd: workdir, title: "Stored archive updatedAt" }, + undefined, + { workspaceId: undefined }, + ); + await manager.closeAgent(created.id); + const before = await storage.get(created.id); + expect(before?.updatedAt).toEqual(expect.any(String)); + + // Later than anything the agent did: lists sorted by updated_at put it first, as they do + // for an agent archived while loaded. + const archivedAt = new Date(Date.parse(before!.updatedAt) + 60_000).toISOString(); + const archived = await manager.archiveSnapshot(created.id, archivedAt); + + expect(archived.updatedAt).toBe(archivedAt); + expect((await storage.get(created.id))?.updatedAt).toBe(archivedAt); +}); + +test("archiveSnapshot restoring an earlier archive time keeps updatedAt at the unarchive", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + + const created = await manager.createAgent( + { provider: "codex", cwd: workdir, title: "Restore archive updatedAt" }, + undefined, + { workspaceId: undefined }, + ); + await manager.closeAgent(created.id); + const originalArchivedAt = (await manager.archiveSnapshot(created.id, new Date().toISOString())) + .archivedAt!; + await new Promise((resolve) => setTimeout(resolve, 5)); + await manager.unarchiveSnapshot(created.id); + const unarchivedAt = (await storage.get(created.id))!.updatedAt; + + const events: ManagedAgent[] = []; + manager.subscribe( + (event) => { + if (event.type === "agent_state" && event.agent.id === created.id) { + events.push(event.agent); + } + }, + { agentId: created.id, replayState: false }, + ); + + // A send that could not load the agent puts its original archive back. + await manager.archiveSnapshot(created.id, originalArchivedAt); + + // Clients keep the newer of two updates, so an older updatedAt would leave them showing it active. + const stored = await storage.get(created.id); + expect(stored?.archivedAt).toBe(originalArchivedAt); + expect(stored?.updatedAt).toBe(unarchivedAt); + expect(events.at(-1)?.updatedAt.toISOString()).toBe(unarchivedAt); +}); + +test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps updatedAt at the unarchive", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-loaded-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ + clients: { codex: new TestAgentClient() }, + registry: storage, + logger, + }); + + const created = await manager.createAgent( + { provider: "codex", cwd: workdir, title: "Restore loaded archive updatedAt" }, + undefined, + { workspaceId: undefined }, + ); + const { archivedAt: originalArchivedAt } = await manager.archiveAgent(created.id); + await new Promise((resolve) => setTimeout(resolve, 5)); + await manager.unarchiveSnapshot(created.id); + const unarchivedAt = Date.parse((await storage.get(created.id))!.updatedAt); + // The send resumed the agent before a later loading step failed, so it is still loaded. + await ensureAgentLoaded(created.id, { agentManager: manager, agentStorage: storage, logger }); + expect(manager.getAgent(created.id)).not.toBeNull(); + + const events: ManagedAgent[] = []; + manager.subscribe( + (event) => { + if (event.type === "agent_state" && event.agent.id === created.id) { + events.push(event.agent); + } + }, + { agentId: created.id, replayState: false }, + ); + + await manager.archiveSnapshot(created.id, originalArchivedAt); + + const stored = await storage.get(created.id); + expect(stored?.archivedAt).toBe(originalArchivedAt); + expect(Date.parse(stored!.updatedAt)).toBeGreaterThanOrEqual(unarchivedAt); + expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt); +}); + test("markAgentUnread restores error attention on a read errored agent", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-")); const storage = new AgentStorage(join(workdir, "agents"), logger); @@ -14606,14 +14714,16 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad labels: { [PARENT_AGENT_ID_LABEL]: parent.id }, workspaceId: undefined, }); - const stamp = "2026-11-09T00:00:00.000Z"; + // Archive stamps are taken when the archive happens, so they follow the agents' activity. + const stamp = new Date(Date.now() + 60_000).toISOString(); + const laterStamp = new Date(Date.now() + 120_000).toISOString(); await manager.archiveAgent(parent.id, stamp); expect((await storage.get(parent.id))?.archivedAt).toBe(stamp); expect((await storage.get(child.id))?.archivedAt).toBe(stamp); await ensureAgentLoaded(parent.id, { agentManager: manager, agentStorage: storage, logger }); - await manager.archiveAgent(parent.id, "2026-11-09T01:00:00.000Z"); + await manager.archiveAgent(parent.id, laterStamp); expect((await storage.get(parent.id))?.archivedAt).toBe(stamp); - expect((await storage.get(parent.id))?.updatedAt).toBe("2026-11-09T01:00:00.000Z"); + expect((await storage.get(parent.id))?.updatedAt).toBe(laterStamp); } finally { await storage.flush(); rmSync(workdir, { recursive: true, force: true }); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index ece45289e2..323c830483 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -2350,7 +2350,7 @@ export class AgentManager { private async persistArchivedRecord( record: StoredAgentRecord, - options: { archivedAt: string; updatedAt?: string }, + options: { archivedAt: string; updatedAt: string }, ): Promise { const archivedRecord = buildArchivedAgentRecord(record, options); await this.requireRegistry().upsert(archivedRecord); @@ -2870,7 +2870,11 @@ export class AgentManager { throw new Error(`Agent not found: ${agentId}`); } - const nextRecord = await this.persistArchivedRecord(record, { archivedAt }); + // Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent. + const nextRecord = await this.persistArchivedRecord(record, { + archivedAt, + updatedAt: archivedAt, + }); await this.syncNativeArchiveState(record.provider, record.persistence, "archive"); From e5352c9890aab867bdf30e268939511e178debbf Mon Sep 17 00:00:00 2001 From: Michael Thomas Date: Mon, 16 Nov 2026 22:48:34 -0500 Subject: [PATCH 129/160] fix: size controls by the primary pointer, not any touch screen (#9909) * feat(desktop): size controls by the primary pointer, not any touch screen The desktop app gave touch-sized controls to every machine with a touch screen, including Windows laptops driven by a trackpad. In Electron, ask whether a mouse-like primary pointer drives the UI instead: Chromium reports a fine primary pointer for those laptops and a coarse one for a tablet with no mouse or trackpad attached. Browsers and native keep the touch-screen check, so an iPad keeps touch sizes with a trackpad attached. Swipe gestures still follow the touch-screen capability. Refs #9892 * feat(app): size controls by the primary pointer on every platform Replace the Electron-only check with one rule everywhere: touch-sized when touch is the primary input, `(pointer: coarse)`, rather than when a touch screen exists at all. WebKit keeps touch primary on an iPad with a trackpad attached, so iPad Safari stays touch-sized; Chromium reports a fine primary pointer for a touch-screen laptop driven by its trackpad, in the browser and the desktop app. Native is always touch-sized. `hasTouchScreen()` and its `maxTouchPoints` fallback had no other caller and are removed. Swipe gestures still follow the touch-screen capability. Refs #9892 * test(app): exercise pointer sizing through the media source * test(app): cover touch laptops with a primary pointer --------- Co-authored-by: Mohamed Boudra --- docs/design.md | 2 +- .../e2e/browser/sidebar-touch-laptop.spec.ts | 36 +++++++++++++++++++ .../helpers/sidebar-footer-overflow.ts | 21 ++++++----- .../components/ui/control-geometry.test.ts | 21 ++++++----- .../app/src/components/ui/control-sizing.ts | 28 ++++++++------- .../src/hooks/pointer-capabilities.test.ts | 32 ++++++++++++++++- .../app/src/hooks/pointer-capabilities.ts | 18 ++++++---- 7 files changed, 120 insertions(+), 38 deletions(-) create mode 100644 packages/app/e2e/browser/sidebar-touch-laptop.spec.ts diff --git a/docs/design.md b/docs/design.md index e4acbe8af2..810b10c582 100644 --- a/docs/design.md +++ b/docs/design.md @@ -76,7 +76,7 @@ Dense toolbar rows, such as the composer's, are the exception to the 44pt contro In the composer, the first glyph's ink starts on the text column's edge, and the trailing control is always a disc, so the row does not shift as it changes between voice mode, send and stop. The disc nests into the corner, as far from the right edge as from the bottom, and touch-sized the composer's corner radius is concentric with it (`packages/app/src/composer/input/toolbar-rails.ts`). Touch-sized the disc keeps a 6pt clearance from its neighbour, because it is always painted and a pressed neighbour would merge with it. The attach button sits 2pt closer to the picker than its highlight would put it: the plus is all thin arms, so the full gap reads wide. That offset is set by eye. -One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or the device has a touch screen. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The touch-screen fact is read once at startup (`hasTouchScreen` in `hooks/use-fine-pointer.ts`), so attaching a mouse or keyboard to a tablet never shrinks its controls. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size. +One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size. Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use. diff --git a/packages/app/e2e/browser/sidebar-touch-laptop.spec.ts b/packages/app/e2e/browser/sidebar-touch-laptop.spec.ts new file mode 100644 index 0000000000..24fcd4c744 --- /dev/null +++ b/packages/app/e2e/browser/sidebar-touch-laptop.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { + expectFooterActionsInline, + seedDockedSidebarWidth, +} from "../support/helpers/sidebar-footer-overflow"; + +// Chromium's pointer bitmasks expose both inputs while the mouse is primary. +test.use({ + viewport: { width: 1280, height: 800 }, + launchOptions: { + args: [ + "--blink-settings=primaryPointerType=4,availablePointerTypes=6,primaryHoverType=2,availableHoverTypes=3", + ], + }, +}); + +test("a touchscreen laptop keeps sidebar actions visible with a fine primary pointer", async ({ + page, +}) => { + await seedDockedSidebarWidth(page, 200); + await gotoAppShell(page); + expect( + await page.evaluate(() => ({ + finePrimary: matchMedia("(pointer: fine)").matches, + touchScreen: matchMedia("(any-pointer: coarse)").matches, + })), + ).toEqual({ finePrimary: true, touchScreen: true }); + await expectFooterActionsInline(page, [ + "sidebar-add-project", + "sidebar-usage-icon", + "sidebar-hosts-trigger", + "sidebar-help", + "sidebar-settings", + ]); +}); diff --git a/packages/app/e2e/support/helpers/sidebar-footer-overflow.ts b/packages/app/e2e/support/helpers/sidebar-footer-overflow.ts index 85983578df..fb934722fc 100644 --- a/packages/app/e2e/support/helpers/sidebar-footer-overflow.ts +++ b/packages/app/e2e/support/helpers/sidebar-footer-overflow.ts @@ -60,14 +60,8 @@ export function footerOverflowMenu(page: Page): Locator { return page.getByTestId("sidebar-footer-overflow-menu"); } -/** - * The icon line shows exactly `testIDs`, in order, each `controlSize` square and wholly inside the - * line's box, so no button is cut off by the sidebar's edge. - */ -export async function expectFooterLine( - page: Page, - input: { testIDs: string[]; controlSize: number }, -): Promise { +/** The icon line shows exactly `testIDs`, in order. */ +export async function expectFooterActionsInline(page: Page, testIDs: string[]): Promise { const line = footerLine(page); await expect(line).toHaveCount(1); await expect @@ -76,7 +70,16 @@ export async function expectFooterLine( .locator(FOOTER_LINE_TEST_IDS.map((testID) => `[data-testid="${testID}"]`).join(",")) .evaluateAll((elements) => elements.map((element) => element.getAttribute("data-testid"))), ) - .toEqual(input.testIDs); + .toEqual(testIDs); +} + +/** The actions are square and fit inside the line. */ +export async function expectFooterLine( + page: Page, + input: { testIDs: string[]; controlSize: number }, +): Promise { + await expectFooterActionsInline(page, input.testIDs); + const line = footerLine(page); const { row, buttons } = await line.evaluate((element, testIDs) => { const rect = (node: Element) => { const { x, width, height } = node.getBoundingClientRect(); diff --git a/packages/app/src/components/ui/control-geometry.test.ts b/packages/app/src/components/ui/control-geometry.test.ts index 58086cf212..ad439d19c8 100644 --- a/packages/app/src/components/ui/control-geometry.test.ts +++ b/packages/app/src/components/ui/control-geometry.test.ts @@ -68,24 +68,27 @@ const theme = { } as unknown as Theme; describe("control sizing gate", () => { - it("is touch-sized in the compact layout or on a touch screen, and pointer-sized otherwise", () => { - expect(resolveControlSizing({ compactLayout: true, touchScreen: true })).toBe("touch"); - expect(resolveControlSizing({ compactLayout: true, touchScreen: false })).toBe("touch"); - expect(resolveControlSizing({ compactLayout: false, touchScreen: true })).toBe("touch"); - expect(resolveControlSizing({ compactLayout: false, touchScreen: false })).toBe("pointer"); + it("is touch-sized in the compact layout or where touch is the primary input, and pointer-sized otherwise", () => { + expect(resolveControlSizing({ compactLayout: true, touchPrimaryPointer: true })).toBe("touch"); + expect(resolveControlSizing({ compactLayout: true, touchPrimaryPointer: false })).toBe("touch"); + expect(resolveControlSizing({ compactLayout: false, touchPrimaryPointer: true })).toBe("touch"); + expect(resolveControlSizing({ compactLayout: false, touchPrimaryPointer: false })).toBe( + "pointer", + ); }); - it("gives a touch screen its touch sizes at every width", () => { + it("gives a touch primary pointer its touch sizes at every width", () => { const sizes = { touch: 44, pointer: 32 }; // An iPad: touch-sized in the docked desktop layout too. expect(bySizing(sizes, true)).toEqual({ xs: 44, md: 44 }); - // A mouse-driven window: touch-sized only once it narrows into the compact layout. + // A mouse- or trackpad-driven window, touch screen or not: touch-sized only once it narrows + // into the compact layout. expect(bySizing(sizes, false)).toEqual({ xs: 44, md: 32 }); }); - it("keeps a device without a touch screen on pointer sizes from md up", () => { - // The unit runtime has no touch screen, which is the desktop that must not change. + it("keeps a device without a touch primary pointer on pointer sizes from md up", () => { + // The unit runtime has no touch primary pointer, which is the desktop that must not change. expect(controlSizingForLayout(false)).toBe("pointer"); expect(controlSizingForLayout(true)).toBe("touch"); expect(CONTROL_HEIGHTS.md).toEqual({ xs: 44, md: 32 }); diff --git a/packages/app/src/components/ui/control-sizing.ts b/packages/app/src/components/ui/control-sizing.ts index 6dc371af76..ffe8629899 100644 --- a/packages/app/src/components/ui/control-sizing.ts +++ b/packages/app/src/components/ui/control-sizing.ts @@ -1,4 +1,4 @@ -import { hasTouchScreen } from "@/hooks/pointer-capabilities"; +import { hasTouchPrimaryPointer } from "@/hooks/pointer-capabilities"; // The sizing gate, apart from the control sizes so that low-level modules such as // `constants/layout` can size by it without loading the theme. Import it through @@ -14,28 +14,32 @@ export type ControlSizing = "touch" | "pointer"; export interface ControlSizingFacts { /** The layout is below the `md` breakpoint. */ compactLayout: boolean; - /** The device has a touch screen; see `hasTouchScreen`. */ - touchScreen: boolean; + /** Touch is the device's primary input; see `hasTouchPrimaryPointer`. */ + touchPrimaryPointer: boolean; } /** - * The one sizing gate: touch-sized in the compact layout or on any device with a touch screen, - * pointer-sized otherwise. A touch screen keeps touch sizing when a mouse or keyboard is attached. + * The one sizing gate: touch-sized in the compact layout or where touch is the primary input, + * pointer-sized otherwise. An iPad keeps touch sizing with a trackpad attached; a laptop with a + * touch screen that its trackpad drives is pointer-sized. */ export function resolveControlSizing({ compactLayout, - touchScreen, + touchPrimaryPointer, }: ControlSizingFacts): ControlSizing { - if (compactLayout || touchScreen) return "touch"; + if (compactLayout || touchPrimaryPointer) return "touch"; return "pointer"; } // Read once, so attaching a mouse or keyboard later never flips the sizing. -const DEVICE_HAS_TOUCH_SCREEN = hasTouchScreen(); +const DEVICE_HAS_TOUCH_PRIMARY_POINTER = hasTouchPrimaryPointer(); /** The sizing on this device for a layout, for code that sizes outside a stylesheet. */ export function controlSizingForLayout(compactLayout: boolean): ControlSizing { - return resolveControlSizing({ compactLayout, touchScreen: DEVICE_HAS_TOUCH_SCREEN }); + return resolveControlSizing({ + compactLayout, + touchPrimaryPointer: DEVICE_HAS_TOUCH_PRIMARY_POINTER, + }); } /** A Unistyles breakpoint value: one number in the compact layout, another from `md` up. */ @@ -51,11 +55,11 @@ export type SizingValue = Record; */ export function bySizing( sizes: SizingValue, - touchScreen: boolean = DEVICE_HAS_TOUCH_SCREEN, + touchPrimaryPointer: boolean = DEVICE_HAS_TOUCH_PRIMARY_POINTER, ): LayoutValue { return { - xs: sizes[resolveControlSizing({ compactLayout: true, touchScreen })], - md: sizes[resolveControlSizing({ compactLayout: false, touchScreen })], + xs: sizes[resolveControlSizing({ compactLayout: true, touchPrimaryPointer })], + md: sizes[resolveControlSizing({ compactLayout: false, touchPrimaryPointer })], }; } diff --git a/packages/app/src/hooks/pointer-capabilities.test.ts b/packages/app/src/hooks/pointer-capabilities.test.ts index 167db7c553..412eff7924 100644 --- a/packages/app/src/hooks/pointer-capabilities.test.ts +++ b/packages/app/src/hooks/pointer-capabilities.test.ts @@ -23,10 +23,18 @@ class FakeMediaQueryList { } } -function createFakeDisplay(initial: { finePointer: boolean; touchScreen: boolean }) { +function createFakeDisplay(initial: { + finePointer: boolean; + touchScreen: boolean; + touchPrimaryPointer?: boolean; +}) { const queries = { finePointer: new FakeMediaQueryList("(hover: hover) and (pointer: fine)", initial.finePointer), touchScreen: new FakeMediaQueryList("(any-pointer: coarse)", initial.touchScreen), + touchPrimaryPointer: new FakeMediaQueryList( + "(pointer: coarse)", + initial.touchPrimaryPointer ?? false, + ), }; const matchMedia = (query: string) => { const match = Object.values(queries).find((list) => list.media === query); @@ -75,3 +83,25 @@ describe("pointer capabilities", () => { }); }); }); + +describe("hasTouchPrimaryPointer", () => { + it("is false on a touch-screen laptop driven by its trackpad", () => { + const display = createFakeDisplay({ finePointer: true, touchScreen: true }); + expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe( + false, + ); + }); + + it("is true when the primary pointer is coarse", () => { + const display = createFakeDisplay({ + finePointer: false, + touchScreen: true, + touchPrimaryPointer: true, + }); + expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe(true); + }); + + it("is false without media queries", () => { + expect(createPointerCapabilitiesSource(null).hasTouchPrimaryPointer()).toBe(false); + }); +}); diff --git a/packages/app/src/hooks/pointer-capabilities.ts b/packages/app/src/hooks/pointer-capabilities.ts index 360ff88c24..bc6d802ac0 100644 --- a/packages/app/src/hooks/pointer-capabilities.ts +++ b/packages/app/src/hooks/pointer-capabilities.ts @@ -8,6 +8,7 @@ import { isWeb } from "@/constants/platform"; // (detachable keyboards, tablet mode, devtools touch emulation). const FINE_POINTER_QUERY = "(hover: hover) and (pointer: fine)"; const TOUCH_SCREEN_QUERY = "(any-pointer: coarse)"; +const TOUCH_PRIMARY_POINTER_QUERY = "(pointer: coarse)"; export interface PointerCapabilities { /** A mouse-like pointer drives the UI. */ @@ -21,6 +22,7 @@ type MatchMedia = (query: string) => MediaQueryList; export interface PointerCapabilitiesSource { getSnapshot: () => PointerCapabilities; subscribe: (onChange: () => void) => () => void; + hasTouchPrimaryPointer: () => boolean; } export function createPointerCapabilitiesSource( @@ -28,9 +30,11 @@ export function createPointerCapabilitiesSource( ): PointerCapabilitiesSource { const finePointerQuery = matchMedia?.(FINE_POINTER_QUERY) ?? null; const touchScreenQuery = matchMedia?.(TOUCH_SCREEN_QUERY) ?? null; + const touchPrimaryPointerQuery = matchMedia?.(TOUCH_PRIMARY_POINTER_QUERY) ?? null; let snapshot: PointerCapabilities = { finePointer: false, touchScreen: false }; return { + hasTouchPrimaryPointer: () => touchPrimaryPointerQuery?.matches ?? false, getSnapshot() { const finePointer = finePointerQuery?.matches ?? false; const touchScreen = touchScreenQuery?.matches ?? false; @@ -61,6 +65,7 @@ const NATIVE_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: false, t const nativeSource: PointerCapabilitiesSource = { getSnapshot: () => NATIVE_POINTER_CAPABILITIES, subscribe: () => () => {}, + hasTouchPrimaryPointer: () => true, }; const source = isWeb ? createPointerCapabilitiesSource(browserMatchMedia()) : nativeSource; @@ -79,10 +84,11 @@ export function hasFinePointer(): boolean { return source.getSnapshot().finePointer; } -/** Touch sizing remains enabled on hybrid browsers that report touch points. */ -export function hasTouchScreen(): boolean { - return ( - source.getSnapshot().touchScreen || - (isWeb && typeof window !== "undefined" && window.navigator.maxTouchPoints > 0) - ); +/** + * True when touch is the primary input, read at call time. iPadOS keeps touch primary with a + * trackpad attached; a laptop with a touch screen that its trackpad drives reports a fine primary + * pointer. + */ +export function hasTouchPrimaryPointer(): boolean { + return source.hasTouchPrimaryPointer(); } From 3eedffc4ac73d8a85621f8a5c27b22a640a54cbe Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 17 Nov 2026 10:53:08 +0700 Subject: [PATCH 130/160] fix(claude): keep the user's ask rules and hooks in Bypass (#9927) In Bypass, Claude agents again show a permission card for asks from the user's permissions.ask rules (including managed policy), PreToolUse hooks that return ask, compound and piped commands that hit an ask rule, permissions.blockReadsOutsideWorkingDirectories, an organization's ask limit, and sandbox overrides. Claude's own checks are still approved without a card. Upgrades @anthropic-ai/claude-agent-sdk to 0.3.326, which passes the ask's source to canUseTool. Closes #9916 --- package-lock.json | 74 +++++++++---------- packages/server/package.json | 2 +- .../claude/agent.auto-plan-approval.test.ts | 66 +++++++++++++++-- .../server/agent/providers/claude/agent.ts | 7 +- .../agent/providers/claude/bypass-approval.ts | 43 +++++++++++ 5 files changed, 142 insertions(+), 50 deletions(-) create mode 100644 packages/server/src/server/agent/providers/claude/bypass-approval.ts diff --git a/package-lock.json b/package-lock.json index 4dbb6d3eb4..52bce5f983 100644 --- a/package-lock.json +++ b/package-lock.json @@ -130,22 +130,22 @@ } }, "node_modules/@anthropic-ai/claude-agent-sdk": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.246.tgz", - "integrity": "sha512-FtR0HoHHNqeqJWjZN8qLUAzZVFUI9ztXYNPPwv98Ecmv9qq2QTauI8IzkY26CC0mleWAqb9RQEW2C0OtiUliug==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.326.tgz", + "integrity": "sha512-BUTSky/4YWfL/MxC+4kV0NDbJFjbJPoQMFEk/s9G6hV9LUfYPMbsWz94bFQ7ZIo2ubj2xwJ2c2NVxkNlQhVw+Q==", "license": "SEE LICENSE IN README.md", "engines": { - "node": ">=18.0.0" + "node": ">=18.14.0" }, "optionalDependencies": { - "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.246", - "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.246", - "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.246", - "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.246", - "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.246", - "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.246", - "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.246", - "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.246" + "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.326", + "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.326", + "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.326", + "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.326", + "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.326", + "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.326", + "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.326", + "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.326" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", @@ -154,9 +154,9 @@ } }, "node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.246.tgz", - "integrity": "sha512-pYDv2RT+UVOvEapMEWKf7Gm5a87Si1Zf+XR23IMGYbG5mESatNJ8Gz2PmkrwfTezZknb0ljWZe8zgcTFITM3dA==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.326.tgz", + "integrity": "sha512-D3ZbowCMdKNet0YPZlsJxdJUW1t1Q8KLy1BwNd+5eilf18TlCRtWZlm8DrewFLmu/gxBK7gcsq6uysrIVbPyQg==", "cpu": [ "arm64" ], @@ -167,9 +167,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.246.tgz", - "integrity": "sha512-yl+gMMFUQ8++SBaxUe2JxBqU0LOJO4HZTsWWTOrH5kRlTRhdQDF/lESsoNXCHgfF/+77YNKgef0h+rl/D12Jfg==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.326.tgz", + "integrity": "sha512-m8K3Im2S8STdAVBrriuDZyJcnjsu/Vc3476wIOqTAefnCCdtdZ4AHcOcWxt+4KIHE5Vx1qT2qacTRrQBaVVweA==", "cpu": [ "x64" ], @@ -180,9 +180,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.246.tgz", - "integrity": "sha512-t7AEewD7bcjZYMmrfFLjsUSxPo4z+5J5O5cC9V2zOvAhNkefdMeGWI2/1cdqZxuaOiFVt46byjlZuiNNunF+bQ==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.326.tgz", + "integrity": "sha512-nYVN8jCcH490DCXIvby7rllzQFxLzKeKClfo2u/yv7mx3ipZQv344caULL/amwZ8w8GUzYyZ8hnS6pI9goSq+A==", "cpu": [ "arm64" ], @@ -193,9 +193,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.246.tgz", - "integrity": "sha512-AeiDXveuA9dVRDouSRiQzL40P3dOuJPfZOlwwsFNbVUN0D+06WtwgmeWYnyRG4dxsM67Pf4lYcRZ0x9pfEZUwQ==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.326.tgz", + "integrity": "sha512-baSsuP2/wuWujRpHjKT4WkJB5lhttqKq9jcTfY2KRtQpylbk8E5PWcct/pmwJfNCKIUoE8CD+JpmoWzsdd5Ajw==", "cpu": [ "arm64" ], @@ -206,9 +206,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.246.tgz", - "integrity": "sha512-BIbBlJ6x7Cys6UFvahUfce26H+U+Q4tLWjKRD39AaV7JvRav8/vfdFytzWq6E+h9hT1OOWYuPYx2gMn5vDhZhQ==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.326.tgz", + "integrity": "sha512-WMhDY07gk2O0E8FXTbrVYmPjSLFaYPDCPwsNueVxm6vZ7ek+lPaKuOMAxTb1K07TzSmTOexoWeX2Y9VrbVDMpw==", "cpu": [ "x64" ], @@ -219,9 +219,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.246.tgz", - "integrity": "sha512-+3PrWX3qXgakO3tZImr7keKFry5XIkbHBEaUxgi3/RtPmxGwS+JdVAr0xxzOoC2F6Y66Kn0lUnztRnZHORBc+Q==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.326.tgz", + "integrity": "sha512-kK9VO3uFqNd4wgeU0Cefluam5AdPu6mvF1nn6aboGy8TA5NoxlWTmA4/AwMhK39zK1S9Q2OjeX0JtAahYlIchw==", "cpu": [ "x64" ], @@ -232,9 +232,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.246.tgz", - "integrity": "sha512-JV8b28OJ8d+EMVEVIWlN3aEkT8uSehO3ZN/PJzXFG7Jgn56oVYUew4aY9vK4jao/4E4mdfzvs358w4HcTBUzVw==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.326.tgz", + "integrity": "sha512-S+Ai+HhGRVFfTDmYWRfTrdWF3b4KMsfLSThZCqRJ0WCOKOXrRShMKV1hqqHBljx/wkMDPCpY0V/9S/e6w57eGQ==", "cpu": [ "arm64" ], @@ -245,9 +245,9 @@ ] }, "node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": { - "version": "0.3.246", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.246.tgz", - "integrity": "sha512-omI65bYGynLpE1Ybijk56K1wBnt0H6WujNwlg1LzIdeHrYmpUxoqncK92xKH5kb9XWUz3byHqArbv7wsT+M/2A==", + "version": "0.3.326", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.326.tgz", + "integrity": "sha512-Yn1gZXYFuHmjHz7SpHx4TqDcRDsC8TfwWcntJdYjFzMWm+caPAp6QRqr/aTvirjqVA1D+D8Rd29xhuytpE3xTQ==", "cpu": [ "x64" ], @@ -40521,7 +40521,7 @@ "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", - "@anthropic-ai/claude-agent-sdk": "0.3.246", + "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", "@getpaseo/client": "0.16.0", "@getpaseo/highlight": "0.16.0", diff --git a/packages/server/package.json b/packages/server/package.json index 58adbd86fa..486208f8f2 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -107,7 +107,7 @@ }, "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", - "@anthropic-ai/claude-agent-sdk": "0.3.246", + "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", "@getpaseo/client": "0.16.0", "@getpaseo/highlight": "0.16.0", diff --git a/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts b/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts index 23b1e79058..7f37a50e1f 100644 --- a/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.auto-plan-approval.test.ts @@ -91,7 +91,7 @@ test.each([ } }); -test("bypass allows execution without publishing permission events and follows live mode changes", async () => { +async function createBypassSession() { let requestPermission: CanUseTool | undefined; const query = Object.assign((async function* () {})(), { async setPermissionMode(_mode: PermissionMode) {}, @@ -112,17 +112,25 @@ test("bypass allows execution without publishing permission events and follows l }); const events: AgentStreamEvent[] = []; session.subscribe((event) => events.push(event)); + await session.setMode("bypassPermissions"); + if (!requestPermission) throw new Error("SDK permission callback was not installed"); + return { session, events, requestPermission }; +} + +test("bypass approves Claude's own checks without publishing permission events and follows live mode changes", async () => { + const { session, events, requestPermission } = await createBypassSession(); try { - await session.setMode("bypassPermissions"); - if (!requestPermission) throw new Error("SDK permission callback was not installed"); const controller = new AbortController(); - const input = { command: "echo hello" }; - const result = requestPermission("Bash", input, { + const input = { command: "rm -rf build" }; + // Claude Code sends these fields, but this SDK version does not declare them on CanUseTool. + const ownCheck = { signal: controller.signal, toolUseID: "execution", - decisionReason: "Explicit ask rule", - }); - // Abort also settles the pre-fix callback, so this repro never hangs. + decisionReason: "Dangerous rm command", + decisionReasonType: "safetyCheck", + }; + const result = requestPermission("Bash", input, ownCheck); + // Abort also settles a prompting callback, so this test never hangs. controller.abort(); await expect(result).resolves.toMatchObject({ behavior: "allow", updatedInput: input }); expect(events.filter((event) => event.type.startsWith("permission_"))).toEqual([]); @@ -135,6 +143,7 @@ test("bypass allows execution without publishing permission events and follows l ] as const) { await session.setMode(mode); const resolution = requestPermission(tool, toolInput, { + ...ownCheck, signal: new AbortController().signal, toolUseID: tool, }); @@ -149,3 +158,44 @@ test("bypass allows execution without publishing permission events and follows l await session.close(); } }); + +test.each([ + ["an ask rule", { decisionReasonType: "rule" }], + ["a hook", { decisionReasonType: "hook", decisionReason: "Confirm before posting" }], + [ + "an ask rule on Claude's own check", + { + decisionReasonType: "safetyCheck", + matchedAskRule: { source: "policySettings", toolName: "Bash", ruleContent: "rm *" }, + }, + ], + [ + "a tool the user answers on the card", + { decisionReasonType: "other", requiresUserInteraction: true }, + ], + ["a compound command with an ask rule in one part", { decisionReasonType: "subcommandResults" }], + [ + "a read the user blocked outside the working directories", + { decisionReasonType: "safetyCheck", decisionReasonCode: "outside_reads_blocked" }, + ], + [ + "an organization's ask limit", + { decisionReasonType: "workingDir", decisionReasonCode: "org_ask_ceiling" }, + ], + ["a sandbox override the user's read block raised", { decisionReasonType: "sandboxOverride" }], + ["a Claude Code that does not say why it asks", {}], +])("bypass still asks the user about %s", async (_source, why) => { + const { session, events, requestPermission } = await createBypassSession(); + try { + const ask = { signal: new AbortController().signal, toolUseID: "execution", ...why }; + const resolution = requestPermission("Bash", { command: "gh pr comment 1" }, ask); + const requestEvent = events.at(-1); + expect(requestEvent?.type).toBe("permission_requested"); + if (requestEvent?.type !== "permission_requested") + throw new Error("Missing permission request"); + await session.respondToPermission(requestEvent.request.id, { behavior: "deny" }); + await expect(resolution).resolves.toMatchObject({ behavior: "deny" }); + } finally { + await session.close(); + } +}); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 5c829801d5..7bd696e7aa 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -11,6 +11,7 @@ import path from "node:path"; import { LRUCache } from "lru-cache"; import stripAnsi from "strip-ansi"; import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.js"; +import { bypassApprovesAsk } from "./bypass-approval.js"; import { type AgentDefinition, type CanUseTool, @@ -5319,10 +5320,8 @@ class ClaudeAgentSession implements AgentSession { input, options, ): Promise => { - // Decide before publishing anything: bypassed tools never enter the permission UI. - // Claude also routes questions and plan review through this callback. - const needsUserAnswer = toolName === "AskUserQuestion" || toolName === "ExitPlanMode"; - if (this.currentMode === "bypassPermissions" && !needsUserAnswer) { + // Decide before publishing anything: bypassed asks never enter the permission UI. + if (this.currentMode === "bypassPermissions" && bypassApprovesAsk(toolName, options)) { return { behavior: "allow", updatedInput: input, toolUseID: options.toolUseID }; } diff --git a/packages/server/src/server/agent/providers/claude/bypass-approval.ts b/packages/server/src/server/agent/providers/claude/bypass-approval.ts new file mode 100644 index 0000000000..cd871439ea --- /dev/null +++ b/packages/server/src/server/agent/providers/claude/bypass-approval.ts @@ -0,0 +1,43 @@ +import type { CanUseTool } from "@anthropic-ai/claude-agent-sdk"; + +type PermissionOptions = Parameters[2]; + +// In bypassPermissions, Claude Code still forwards an ask when the user configured one +// (a permissions.ask rule, including managed policy, or a PreToolUse hook), when the tool +// needs an answer, or when one of its own checks fires. Bypass approves only Claude's own +// checks. A missing or unknown reason type stays with the user. +// `subcommandResults` is left out: a compound or piped command uses it as a container, +// including when a user's ask rule matched one of its parts. `sandboxOverride` is left +// out: in Bypass, Claude Code forwards it only when the user's read block or hook raised it. +const CLAUDE_OWN_CHECK_TYPES: ReadonlySet = new Set([ + "safetyCheck", + "workingDir", + "mode", + "classifier", + "asyncAgent", +]); + +// Settings the user or organization chose, which Claude Code reports under its own types: +// permissions.blockReadsOutsideWorkingDirectories, and an organization's ask limit. +const CONFIGURED_ASK_CODES: ReadonlySet = new Set([ + "outside_reads_blocked", + "org_ask_ceiling", +]); + +const QUESTION_TOOLS: ReadonlySet = new Set(["AskUserQuestion", "ExitPlanMode"]); + +export function bypassApprovesAsk(toolName: string, options: PermissionOptions): boolean { + if (QUESTION_TOOLS.has(toolName) || options.matchedAskRule) { + return false; + } + // The SDK forwards these from Claude Code without declaring them on CanUseTool. + if ("requiresUserInteraction" in options && options.requiresUserInteraction === true) { + return false; + } + const reasonCode = "decisionReasonCode" in options ? options.decisionReasonCode : undefined; + if (typeof reasonCode === "string" && CONFIGURED_ASK_CODES.has(reasonCode)) { + return false; + } + const reasonType = "decisionReasonType" in options ? options.decisionReasonType : undefined; + return typeof reasonType === "string" && CLAUDE_OWN_CHECK_TYPES.has(reasonType); +} From 0bac18f3593297c7ccbf24d8a831c7b8b557f27c Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:02:57 +0000 Subject: [PATCH 131/160] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index 68dd307a19..bfdaef93ac 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-alhf4ULeJ7n8sfgnxsX8Ugw40GB7jz0u9R/3/MOveIw= +sha256-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk= From eabbd3d97c2d6a9a24d72de0bf08db1c7398a8a5 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:11:25 +0000 Subject: [PATCH 132/160] Show a Codex message canceled before it starts as canceled, not as a startup error (#9931) * fix(server): treat canceled Codex starts as interruptions * fix(server): report a replaced pending start as undelivered to its sender waitForAgentRunStart followed the agent rather than the sender's run, so a send canceled by a replacement before reaching Codex resolved once the replacement started. Keep the sender's own pending run and reject when it is cleared before its turn starts. The canceled-start tests drain streamAgent, because a fresh Codex agent has no session handle before its first turn (#8393). Co-Authored-By: Claude Opus 5.5 * fix(server): keep a sender's start wait across a stale-session retry Co-Authored-By: Claude Opus 5.5 * test(server): expect the start options passed to a foreground run Session create and scheduled prompts now pass the sender's start options, so the two call-argument assertions include them. Co-authored-by: 3ae3ae <3ae3ae@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * fix(server): keep a Codex message canceled before it starts in history A Stop or replacing send during Codex preparation settled the run as canceled without recording the sender's prompt, so the message vanished from history after a reload and on other clients. Record it as a rejected attempt, as the start-failure branch already does, so it stays in history without being delivered. Co-authored-by: 3ae3ae <3ae3ae@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * fix(server): return each send's start from dispatch A send waited for its turn by looking up the agent's pending run when the wait began. When a provider plugin's session was stale, the first start failed and its run was cleared before the sender started waiting, so the send rejected with "has no pending run" while the retry answered it. startAgentRun now returns the start of the prompt it dispatched. Every run created for that prompt, including the stale-session retry, is bound to it, so the send resolves when its own turn starts and rejects when its own run ends unstarted. This replaces the retry hand-off between runs in the agent manager. Co-authored-by: 3ae3ae <3ae3ae@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: 3ae3ae Co-authored-by: Bae Seongmin <83870598+3ae3ae@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: bot Co-authored-by: paseo-bot[bot] Co-authored-by: 3ae3ae <3ae3ae@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- .../src/server/agent/agent-manager.test.ts | 472 +++++++++++++++++- .../server/src/server/agent/agent-manager.ts | 71 ++- .../src/server/agent/agent-prompt.test.ts | 17 +- .../server/src/server/agent/agent-prompt.ts | 95 +++- .../src/server/agent/agent-run-state.ts | 58 ++- .../src/server/agent/agent-sdk-types.ts | 8 + .../server/agent/create-agent/create.test.ts | 10 +- .../src/server/agent/mcp-server.test.ts | 12 +- .../providers/codex-app-server-agent.test.ts | 2 +- .../agent/providers/codex-app-server-agent.ts | 3 +- .../server/agent/providers/provider-runner.ts | 4 + .../src/server/agent/tools/paseo-tools.ts | 15 +- .../src/server/schedule/service.test.ts | 2 + packages/server/src/server/session.ts | 1 + .../src/server/test-utils/agent-messages.ts | 6 +- .../server/src/server/websocket-server.ts | 8 +- 16 files changed, 718 insertions(+), 66 deletions(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 5274953e0d..037f958785 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -20,6 +20,10 @@ import { type ManagedAgent, } from "./agent-manager.js"; import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js"; +import { AgentTurnStartCanceledError } from "./agent-sdk-types.js"; +import { ForegroundPromptStart } from "./agent-run-state.js"; +import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js"; +import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js"; @@ -1210,7 +1214,7 @@ test("starts its own turn when the previous turn fails to start under a steer se ); startHeld.resolve(); - await expect(second).resolves.toEqual({ disposition: "turn_started" }); + await expect(second).resolves.toMatchObject({ disposition: "turn_started" }); await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"])); expect(session.interruptCount).toBe(0); } finally { @@ -9749,6 +9753,464 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist ); }); +test("canceling a pending Codex start settles as canceled without accepting its prompt", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-cold-cancel-")); + const threadLoaded = deferred<{ data: string[] }>(); + const appServer = createFakeCodexAppServer({ "thread/loaded/list": () => threadLoaded.promise }); + class ColdStartClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new CodexAppServerAgentSession(config, null, logger, async () => appServer.child); + } + } + const manager = new AgentManager({ + clients: { codex: new ColdStartClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + }); + const events: AgentStreamEvent[] = []; + manager.subscribe((event) => { + if (event.type === "agent_stream") events.push(event.event); + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + // Drain the stream: a fresh Codex agent has no session handle for runAgent before its first turn. + const senderStart = new ForegroundPromptStart(agent.id); + const firstRun = drainAsyncGenerator( + manager.streamAgent( + agent.id, + "Canceled prompt", + { clientMessageId: "canceled-prompt" }, + senderStart, + ), + ); + void firstRun.catch(() => undefined); + await appServer.waitForRequest("thread/loaded/list"); + const senderRejection = expect(senderStart.started).rejects.toThrow( + "its prompt was not delivered", + ); + const cancel = manager.cancelAgentRun(agent.id); + await new Promise((resolve) => setTimeout(resolve, 0)); + threadLoaded.resolve({ data: ["thread-1"] }); + await expect(cancel).resolves.toEqual({ status: "settled" }); + await expect(firstRun).resolves.toBeUndefined(); + await senderRejection; + expect(manager.getAgent(agent.id)).toMatchObject({ lifecycle: "idle", lastError: undefined }); + expect(manager.hasInFlightRun(agent.id)).toBe(false); + expect(events.map((event) => event.type)).toEqual(["timeline", "turn_canceled"]); + // The canceled attempt stays in history like a rejected one, without being delivered. + expect(manager.getTimeline(agent.id)).toEqual([ + { + type: "user_message", + text: "Canceled prompt", + clientMessageId: "canceled-prompt", + messageId: "canceled-prompt", + }, + ]); + expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false); + + const nextRun = manager.runAgent(agent.id, "Next prompt", { clientMessageId: "next-prompt" }); + await appServer.waitForRequest("turn/start"); + appServer.startsTurn({ threadId: "thread-1", turnId: "next-turn" }); + appServer.completeTurn(); + await expect(nextRun).resolves.toMatchObject({ canceled: false }); + appServer.assertNoErrors(); + } finally { + threadLoaded.resolve({ data: ["thread-1"] }); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("stopping a Codex replacement of a stalled start clears replacement activity", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replacement-cancel-")); + const firstLoaded = deferred<{ data: string[] }>(); + const firstInterruptRequested = deferred(); + const replacementLoaded = deferred<{ data: string[] }>(); + const replacementEntered = deferred(); + let loadCount = 0; + const appServer = createFakeCodexAppServer({ + "thread/loaded/list": () => { + loadCount += 1; + if (loadCount === 1) return firstLoaded.promise; + replacementEntered.resolve(); + return replacementLoaded.promise; + }, + }); + class ColdStartSession extends CodexAppServerAgentSession { + override async interrupt(): Promise { + const interruption = super.interrupt(); + firstInterruptRequested.resolve(); + await interruption; + } + } + class ColdStartClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new ColdStartSession(config, null, logger, async () => appServer.child); + } + } + const manager = new AgentManager({ + clients: { codex: new ColdStartClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + rescueTimeouts: { interruptSessionMs: 10 }, + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const firstRun = drainAsyncGenerator(manager.streamAgent(agent.id, "Original prompt")); + await appServer.waitForRequest("thread/loaded/list"); + const replacement = manager.replaceAgentRun(agent.id, "Replacement prompt"); + await firstInterruptRequested.promise; + firstLoaded.resolve({ data: ["thread-1"] }); + const replacementStream = await replacement; + await expect(firstRun).resolves.toBeUndefined(); + expect(manager.getAgent(agent.id)?.lifecycle).toBe("running"); + const replacementEvent = replacementStream.next(); + await replacementEntered.promise; + const cancel = manager.cancelAgentRun(agent.id); + await new Promise((resolve) => setTimeout(resolve, 0)); + replacementLoaded.resolve({ data: ["thread-1"] }); + await expect(cancel).resolves.toEqual({ status: "settled" }); + await expect(replacementEvent).resolves.toMatchObject({ + value: { type: "turn_canceled" }, + }); + await expect(replacementStream.next()).resolves.toMatchObject({ done: true }); + expect(manager.hasInFlightRun(agent.id)).toBe(false); + expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle"); + expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false); + appServer.assertNoErrors(); + } finally { + firstLoaded.resolve({ data: ["thread-1"] }); + replacementLoaded.resolve({ data: ["thread-1"] }); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a stalled Codex start canceled by its replacement rejects its sender's start wait", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replaced-start-wait-")); + const firstLoaded = deferred<{ data: string[] }>(); + const firstInterruptRequested = deferred(); + let loadCount = 0; + const appServer = createFakeCodexAppServer({ + "thread/loaded/list": () => { + loadCount += 1; + return loadCount === 1 ? firstLoaded.promise : { data: ["thread-1"] }; + }, + }); + class ColdStartSession extends CodexAppServerAgentSession { + override async interrupt(): Promise { + const interruption = super.interrupt(); + firstInterruptRequested.resolve(); + await interruption; + } + } + class ColdStartClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new ColdStartSession(config, null, logger, async () => appServer.child); + } + } + const manager = new AgentManager({ + clients: { codex: new ColdStartClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + rescueTimeouts: { interruptSessionMs: 10 }, + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const firstStart = new ForegroundPromptStart(agent.id); + const secondStart = new ForegroundPromptStart(agent.id); + const firstRun = drainAsyncGenerator( + manager.streamAgent(agent.id, "First prompt", undefined, firstStart), + ); + await appServer.waitForRequest("thread/loaded/list"); + const firstWait = firstStart.started; + const replacement = manager.replaceAgentRun(agent.id, "Second prompt", undefined, secondStart); + await firstInterruptRequested.promise; + firstLoaded.resolve({ data: ["thread-1"] }); + const replacementStream = await replacement; + await expect(firstRun).resolves.toBeUndefined(); + + const secondWait = secondStart.started; + const replacementDrained = drainAsyncGenerator(replacementStream); + await appServer.waitForRequest("turn/start"); + appServer.startsTurn({ threadId: "thread-1", turnId: "second-turn" }); + await expect(secondWait).resolves.toBeUndefined(); + await expect(firstWait).rejects.toThrow("its prompt was not delivered"); + appServer.completeTurn(); + await replacementDrained; + expect(appServer.requests().filter((request) => request.method === "turn/start")).toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ + input: [expect.objectContaining({ text: "Second prompt" })], + }), + }), + ]); + appServer.assertNoErrors(); + } finally { + firstLoaded.resolve({ data: ["thread-1"] }); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a sender's start wait follows its prompt across a stale-session retry", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-wait-")); + const releaseStart = deferred(); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw new StaleProviderSessionError("stale-bridge"); + } + } + class StaleStartClient extends ResumeTrackingTestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + } + const client = new StaleStartClient(); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + const startedTurns: AgentStreamEvent[] = []; + manager.subscribe((event) => { + if (event.type === "agent_stream" && event.event.type === "turn_started") { + startedTurns.push(event.event); + } + }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderWait = dispatchStarted( + await startAgentRun(manager, agent.id, "Retry this prompt", logger, { + runOptions: { clientMessageId: "stale-start-wait" }, + }), + ); + releaseStart.resolve(); + await client.waitForRetryStart(); + await manager.waitForAgentEvent(agent.id); + expect(client.resumeOverrides).toHaveLength(1); + expect(startedTurns).toHaveLength(1); + expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([ + expect.objectContaining({ text: "Retry this prompt", clientMessageId: "stale-start-wait" }), + ]); + await expect(senderWait).resolves.toBeUndefined(); + } finally { + releaseStart.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a sender's start wait follows its prompt when the session is stale before the wait begins", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-immediate-stale-start-")); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + throw new StaleProviderSessionError("stale-bridge"); + } + } + class StaleStartClient extends ResumeTrackingTestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + } + const client = new StaleStartClient(); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const dispatch = await startAgentRun(manager, agent.id, "Retry this prompt", logger, { + runOptions: { clientMessageId: "immediate-stale-start" }, + }); + // The stale start has failed and been cleared before the sender begins waiting. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(manager.hasInFlightRun(agent.id)).toBe(false); + await expect(dispatchStarted(dispatch)).resolves.toBeUndefined(); + await client.waitForRetryStart(); + expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([ + expect.objectContaining({ + text: "Retry this prompt", + clientMessageId: "immediate-stale-start", + }), + ]); + } finally { + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test.each(["reload", "retry", "stale retry"])( + "a sender's start wait rejects when its stale-session %s fails", + async (failure) => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-failure-")); + const releaseStart = deferred(); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw new StaleProviderSessionError("stale-bridge"); + } + } + class FailedRetrySession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + if (failure === "stale retry") throw new StaleProviderSessionError("retry-bridge"); + throw new Error("retry failed"); + } + } + class FailedRetryClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + override async resumeSession(): Promise { + if (failure === "reload") throw new Error("reload failed"); + return new FailedRetrySession({ provider: "codex", cwd: workdir }); + } + } + const manager = new AgentManager({ clients: { codex: new FailedRetryClient() }, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderWait = dispatchStarted( + await startAgentRun(manager, agent.id, "Retry this prompt", logger), + ); + const rejection = expect(senderWait).rejects.toThrow( + failure === "retry" ? "retry failed" : "is stale after its plugin reloaded", + ); + releaseStart.resolve(); + await rejection; + } finally { + releaseStart.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } + }, +); + +test("a sender's start wait rejects when Stop cancels its pending stale-session retry", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-retry-stop-")); + const releaseStart = deferred(); + const retryEntered = deferred(); + const retryCanceled = deferred(); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw new StaleProviderSessionError("stale-bridge"); + } + } + class CanceledRetrySession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + retryEntered.resolve(); + await retryCanceled.promise; + throw new AgentTurnStartCanceledError(); + } + override async interrupt(): Promise { + retryCanceled.resolve(); + } + } + class RetryClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + override async resumeSession(): Promise { + return new CanceledRetrySession({ provider: "codex", cwd: workdir }); + } + } + const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderWait = dispatchStarted( + await startAgentRun(manager, agent.id, "Retry this prompt", logger), + ); + const rejection = expect(senderWait).rejects.toThrow("its prompt was not delivered"); + releaseStart.resolve(); + await retryEntered.promise; + await expect(manager.cancelAgentRun(agent.id)).resolves.toEqual({ status: "settled" }); + await rejection; + expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle"); + expect(manager.getTimeline(agent.id)).toEqual([]); + } finally { + releaseStart.resolve(); + retryCanceled.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + +test("a sender's start wait never adopts an unlinked run after a stale start", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-unlinked-start-")); + const releaseStart = deferred(); + const staleError = new StaleProviderSessionError("stale-bridge"); + class StaleStartSession extends TestAgentSession { + override async startTurn(): Promise<{ turnId: string }> { + await releaseStart.promise; + throw staleError; + } + } + class RetryClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new StaleStartSession(config); + } + } + const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger }); + try { + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const senderStart = new ForegroundPromptStart(agent.id); + const firstRun = drainAsyncGenerator( + manager.streamAgent(agent.id, "First prompt", undefined, senderStart), + ); + const firstFailure = expect(firstRun).rejects.toBe(staleError); + const rejection = expect(senderStart.started).rejects.toThrow(staleError.message); + releaseStart.resolve(); + await firstFailure; + try { + await manager.reloadAgentSession(agent.id); + const otherStart = new ForegroundPromptStart(agent.id); + const otherRun = drainAsyncGenerator( + manager.streamAgent(agent.id, "Another sender", undefined, otherStart), + ); + await expect(otherStart.started).resolves.toBeUndefined(); + await otherRun; + } finally { + senderStart.end(); + } + await rejection; + expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual( + [], + ); + } finally { + releaseStart.resolve(); + manager.prepareForShutdown(); + await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id))); + await manager.flushForShutdown(); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("acknowledged cancellation settles a pending run before it has a turn id", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-cancel-pending-start-")); const startEntered = deferred(); @@ -15071,3 +15533,11 @@ test("plugin instructions are recomputed for each launch without changing saved expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon"); expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved"); }); + +function dispatchStarted(dispatch: Awaited>): Promise { + if (dispatch.disposition !== "turn_started") { + throw new Error(`Expected a started turn, got ${dispatch.disposition}`); + } + void dispatch.started.catch(() => undefined); + return dispatch.started; +} diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 323c830483..ef3ec8126d 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -29,6 +29,7 @@ import { z } from "zod"; import type { TerminalManager } from "../../terminal/terminal-manager.js"; import { + AgentTurnStartCanceledError, getAgentStreamEventTurnId, type AgentCapabilityFlags, type AgentClient, @@ -92,6 +93,7 @@ import { import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { AgentRunState, + type ForegroundPromptStart, type ForegroundTurnWaiter, type PendingForegroundRun, } from "./agent-run-state.js"; @@ -3143,7 +3145,7 @@ export class AgentManager { pendingRun: PendingForegroundRun; prompt: AgentPromptInput; options?: AgentRunOptions; - }): Promise { + }): Promise { const { agent, agentId, pendingRun, prompt, options } = params; try { const result = await agent.session.startTurn(prompt, options); @@ -3152,11 +3154,32 @@ export class AgentManager { } return result.turnId; } catch (error) { + if (error instanceof AgentTurnStartCanceledError) { + if (!pendingRun.settled) { + if (options?.clientMessageId) { + this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", { + messageId: options.clientMessageId, + }); + } + await this.handleStreamEvent(agent, { + type: "turn_canceled", + provider: agent.provider, + reason: "interrupted", + }); + this.finalizeForegroundTurn(agent); + this.runs.settleForegroundRun(agentId, pendingRun.token); + } + return null; + } if (pendingRun.settled) { throw error; } if (isStaleProviderSessionError(error)) { - this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message }); + this.runs.settleForegroundStart(pendingRun, { + status: "failed", + error: error.message, + stale: true, + }); agent.pendingReplacement = false; if (!agent.activeForegroundTurnId) agent.lifecycle = "idle"; this.runs.settleForegroundRun(agentId, pendingRun.token); @@ -3212,15 +3235,17 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): AsyncGenerator { await this.ensureInteractiveSession(agentId); - yield* this.streamAgent(agentId, prompt, options); + yield* this.streamAgent(agentId, prompt, options, promptStart); } private async *streamAfterRuntimeCollection( agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): AsyncGenerator { await this.waitForAgentClose(agentId); await ensureAgentLoaded(agentId, { @@ -3228,19 +3253,20 @@ export class AgentManager { agentStorage: this.requireRegistry(), logger: this.logger, }); - yield* this.streamAgent(agentId, prompt, options); + yield* this.streamAgent(agentId, prompt, options, promptStart); } streamAgent( agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): AsyncGenerator { if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry)) - return this.streamAfterRuntimeCollection(agentId, prompt, options); + return this.streamAfterRuntimeCollection(agentId, prompt, options, promptStart); const existingAgent = this.requireSessionAgent(agentId); if (this.historySessions.has(existingAgent.session)) - return this.streamAfterHistoryLoad(agentId, prompt, options); + return this.streamAfterHistoryLoad(agentId, prompt, options, promptStart); this.logger.trace( { agentId, @@ -3275,9 +3301,10 @@ export class AgentManager { agent.lastError = undefined; const pendingRun = this.runs.createPendingRun(agentId); + promptStart?.bind(pendingRun); const streamForwarder = async function* streamForwarder(this: AgentManager) { - let turnId: string; + let turnId: string | null; let turnStream: ReturnType | null = null; turnId = await this.startPendingForegroundTurn({ agent, @@ -3286,6 +3313,15 @@ export class AgentManager { prompt, options, }); + if (turnId === null) { + const canceledEvent: AgentStreamEvent = { + type: "turn_canceled", + provider: agent.provider, + reason: "interrupted", + }; + yield canceledEvent; + return; + } if (isReplacement) { agent.pendingReplacement = false; @@ -3440,9 +3476,10 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): Promise> { this.requireSessionAgent(agentId); - return this.replaceRunInForegroundLane(agentId, prompt, options); + return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart); } async steerAgentRun( @@ -3483,6 +3520,7 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options?: AgentSteerOptions, + promptStart?: ForegroundPromptStart, ): Promise { // A turn that is still starting has no id to steer yet. Replacing it would drop its // prompt, so wait until it is accepted (or fails) and steer the turn it became. @@ -3530,6 +3568,7 @@ export class AgentManager { expectedTurnId, prompt, stripSteerOptions(options), + promptStart, ), }; } @@ -3595,9 +3634,10 @@ export class AgentManager { expectedTurnId: string, prompt: AgentPromptInput, options?: AgentRunOptions, + promptStart?: ForegroundPromptStart, ): Promise> { this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId); - return this.replaceRunInForegroundLane(agent.id, prompt, options, (live) => + return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) => this.assertSteerAdmissionOwnsTurn(live, expectedTurnId), ); } @@ -3610,12 +3650,13 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options: AgentRunOptions | undefined, + promptStart?: ForegroundPromptStart, assertAdmission?: (agent: ActiveManagedAgent) => void, ): Promise> { // Replacements queue in arrival order; each one holds the foreground lane only while // it cancels and reserves, so Stop is never stuck behind a replacement that is waiting. return this.runQueuedMutation(this.replacementMutationTails, agentId, () => - this.replaceRunWhenAdmitted(agentId, prompt, options, assertAdmission), + this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission), ); } @@ -3623,6 +3664,7 @@ export class AgentManager { agentId: string, prompt: AgentPromptInput, options: AgentRunOptions | undefined, + promptStart?: ForegroundPromptStart, assertAdmission?: (agent: ActiveManagedAgent) => void, ): Promise> { let stalledStart: PendingForegroundRun | null = null; @@ -3641,7 +3683,7 @@ export class AgentManager { if (!this.hasInFlightRun(agent.id)) { return { status: "reserved" as const, - iterator: this.streamAgent(agent.id, prompt, options), + iterator: this.streamAgent(agent.id, prompt, options, promptStart), }; } agent.pendingReplacement = true; @@ -3655,7 +3697,7 @@ export class AgentManager { } return { status: "reserved" as const, - iterator: this.streamAgent(agent.id, prompt, options), + iterator: this.streamAgent(agent.id, prompt, options, promptStart), }; } catch (error) { agent.pendingReplacement = false; @@ -3846,7 +3888,10 @@ export class AgentManager { } async cancelAgentRun(agentId: string): Promise { - return this.runForegroundMutation(agentId, () => this.cancelAgentRunNow(agentId)); + return this.runForegroundMutation(agentId, () => { + this.requireSessionAgent(agentId).pendingReplacement = false; + return this.cancelAgentRunNow(agentId); + }); } private async cancelAgentRunNow(agentId: string): Promise { diff --git a/packages/server/src/server/agent/agent-prompt.test.ts b/packages/server/src/server/agent/agent-prompt.test.ts index 2c150bd2e1..6a169c6df4 100644 --- a/packages/server/src/server/agent/agent-prompt.test.ts +++ b/packages/server/src/server/agent/agent-prompt.test.ts @@ -15,6 +15,7 @@ import { join } from "node:path"; import { createTestLogger } from "../../test-utils/test-logger.js"; import { AgentManager } from "./agent-manager.js"; import { waitForAgentRunStartWithTimeout } from "./agent-prompt.js"; +import { ForegroundPromptStart } from "./agent-run-state.js"; import type { AgentClient, AgentRunResult, @@ -161,7 +162,7 @@ class SlowStartAgentClient implements AgentClient { async function createRunStartScenario(startDelayMs: number | null): Promise<{ agentManager: AgentManager; agentId: string; - startRun: () => Promise; + startRun: () => Promise<{ started: Promise }>; cleanup: () => Promise; }> { const workdir = mkdtempSync(join(tmpdir(), "agent-run-start-budget-")); @@ -178,14 +179,16 @@ async function createRunStartScenario(startDelayMs: number | null): Promise<{ return { agentManager, agentId: snapshot.id, - // streamAgent registers the pending run synchronously, so the wait always observes it. + // Returns the sender's start, bound to the run streamAgent registers. startRun: async () => { - const run = agentManager.streamAgent(snapshot.id, "start the run"); + const start = new ForegroundPromptStart(snapshot.id); + const run = agentManager.streamAgent(snapshot.id, "start the run", undefined, start); drained = (async () => { for await (const _event of run) { // Drain whatever the turn produces. } })().catch(() => undefined); + return { started: start.started }; }, cleanup: async () => { // Release any turn still held open, then close. The drain is deliberately not @@ -207,8 +210,8 @@ test("waiting for a run start outlasts the slowest provider startup budget", asy vi.useFakeTimers(); try { - await scenario.startRun(); - const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId); + const { started } = await scenario.startRun(); + const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started); let settled = false; const markSettled = () => { settled = true; @@ -233,8 +236,8 @@ test("waiting for a run start still gives up at the run start budget", async () vi.useFakeTimers(); try { - await scenario.startRun(); - const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId); + const { started } = await scenario.startRun(); + const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started); const rejection = expect(wait).rejects.toThrow( "codex run did not start within 60 seconds (phase: run start)", ); diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index f23a549491..4cccd28be2 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -3,6 +3,7 @@ import type { Logger } from "pino"; import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js"; import type { AgentManager, ManagedAgent } from "./agent-manager.js"; +import { ForegroundPromptStart } from "./agent-run-state.js"; import type { AgentStorage } from "./agent-storage.js"; import { ensureAgentLoaded } from "./agent-loading.js"; import { isStaleProviderSessionError } from "./stale-provider-session-error.js"; @@ -38,11 +39,17 @@ export interface StartAgentRunOptions { export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started"; +/** A dispatched prompt. A started turn carries its sender's start outcome. */ +export type PromptDispatchResult = + | { disposition: "turn_started"; started: Promise } + | { disposition: Exclude }; + async function steerOrReplaceActiveRun( agentManager: AgentRunController, agentId: string, prompt: AgentPromptInput, options: StartAgentRunOptions | undefined, + promptStart: ForegroundPromptStart, ): Promise< | { disposition: "steered" } | { @@ -57,7 +64,12 @@ async function steerOrReplaceActiveRun( const steerOptions = options.clearPendingPermissions ? { ...options.runOptions, clearPendingPermissions: true } : options.runOptions; - const result = await agentManager.steerOrReplaceActiveTurn(agentId, prompt, steerOptions); + const result = await agentManager.steerOrReplaceActiveTurn( + agentId, + prompt, + steerOptions, + promptStart, + ); if (result.status === "steered") { return { disposition: "steered" }; } @@ -72,14 +84,15 @@ async function startOrReplaceRun( agentId: string, prompt: AgentPromptInput, options: StartAgentRunOptions | undefined, + promptStart: ForegroundPromptStart, ): Promise<{ iterator: AsyncGenerator; replaced: boolean; }> { const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId)); const iterator = replaced - ? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions) - : agentManager.streamAgent(agentId, prompt, options?.runOptions); + ? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart) + : agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart); return { iterator, replaced }; } @@ -97,7 +110,7 @@ export async function startAgentRun( prompt: AgentPromptInput, logger: Logger, options?: StartAgentRunOptions, -): Promise<{ disposition: PromptDispatchDisposition }> { +): Promise { const snapshot = agentManager.getAgent(agentId); logger.trace( { @@ -118,16 +131,25 @@ export async function startAgentRun( options?.onDispatch?.("out_of_band"); return { disposition: "out_of_band" }; } + const promptStart = new ForegroundPromptStart(agentId); try { - await agentManager.reloadStalePluginSession(agentId); - return await startAgentRunInner(agentManager, agentId, prompt, logger, options); + try { + await agentManager.reloadStalePluginSession(agentId); + return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart); + } catch (error) { + if (!isStaleProviderSessionError(error)) throw error; + logger.info( + { agentId, err: error }, + "Provider session went stale; reopening from persistence", + ); + // The live session belongs to a retired plugin runtime. Reload swaps in a + // fresh session on the current runtime while preserving history and labels. + await agentManager.reloadAgentSession(agentId); + return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart); + } } catch (error) { - if (!isStaleProviderSessionError(error)) throw error; - logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence"); - // The live session belongs to a retired plugin runtime. Reload swaps in a - // fresh session on the current runtime while preserving history and labels. - await agentManager.reloadAgentSession(agentId); - return await startAgentRunInner(agentManager, agentId, prompt, logger, options); + promptStart.end(); + throw error; } } @@ -136,12 +158,13 @@ async function startAgentRunInner( agentId: string, prompt: AgentPromptInput, logger: Logger, - options?: StartAgentRunOptions, -): Promise<{ disposition: PromptDispatchDisposition }> { + options: StartAgentRunOptions | undefined, + promptStart: ForegroundPromptStart, +): Promise { const snapshot = agentManager.getAgent(agentId); const steered = options?.idleOnly ? null - : await steerOrReplaceActiveRun(agentManager, agentId, prompt, options); + : await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart); if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) { throw new AgentTurnBusyError(`Agent ${agentId} is running`); } @@ -151,7 +174,7 @@ async function startAgentRunInner( } const { iterator, replaced } = steered ? { iterator: steered.iterator, replaced: true } - : await startOrReplaceRun(agentManager, agentId, prompt, options); + : await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart); logger.trace( { agentId, @@ -173,7 +196,7 @@ async function startAgentRunInner( "Provider session went stale; reopening from persistence", ); await agentManager.reloadAgentSession(agentId); - const retry = await startOrReplaceRun(agentManager, agentId, prompt, options); + const retry = await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart); await drainAgentRunIterator(retry.iterator); } logger.trace( @@ -195,9 +218,11 @@ async function startAgentRunInner( "agent.session.iterator.error", ); logger.error({ err: error, agentId }, "Agent stream failed"); + } finally { + promptStart.end(); } })(); - return { disposition: "turn_started" }; + return { disposition: "turn_started", started: promptStart.started }; } /** @@ -270,8 +295,9 @@ export interface StartCreatedAgentInitialPromptParams { const AGENT_RUN_START_TIMEOUT_MS = 60_000; export async function waitForAgentRunStartWithTimeout( - agentManager: AgentManager, + agentManager: Pick, agentId: string, + started: Promise, signal?: AbortSignal, ): Promise { const provider = agentManager.getAgent(agentId)?.provider ?? "provider"; @@ -286,15 +312,28 @@ export async function waitForAgentRunStartWithTimeout( AGENT_RUN_START_TIMEOUT_MS, ); + const abortSignal = signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal; + let onAbort: (() => void) | null = null; + const aborted = new Promise((_, reject) => { + onAbort = () => reject(createStartAbortError(abortSignal.reason)); + if (abortSignal.aborted) onAbort(); + else abortSignal.addEventListener("abort", onAbort, { once: true }); + }); try { - await agentManager.waitForAgentRunStart(agentId, { - signal: signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal, - }); + await Promise.race([started, aborted]); } finally { clearTimeout(startTimeout); + if (onAbort) abortSignal.removeEventListener("abort", onAbort); } } +function createStartAbortError(reason: unknown): Error { + let message = "wait_for_agent_start aborted"; + if (typeof reason === "string") message = reason; + else if (reason instanceof Error) message = reason.message; + return Object.assign(new Error(message), { name: "AbortError" }); +} + async function resolvePromptSource( source: AgentPromptSource | undefined, manager: Pick, @@ -320,7 +359,7 @@ async function resolvePromptSource( */ export async function sendPromptToAgent( params: SendPromptToAgentParams, -): Promise<{ disposition: PromptDispatchDisposition }> { +): Promise { const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage); const delivery = prepareAgentMessage(params.prompt, source, params.messageId); return sendPreparedPromptToAgent({ @@ -335,14 +374,14 @@ export async function sendPromptToAgent( /** Dispatch daemon-prepared context without reclassifying it as human input. */ export async function sendPreparedPromptToAgent( params: Omit, -): Promise<{ disposition: PromptDispatchDisposition }> { +): Promise { const unarchive = params.unarchive ?? true; const record = await params.agentStorage.get(params.agentId); let archivedAtToRestore: string | null = null; if (record?.archivedAt) { if (!unarchive) { - return { disposition: "turn_started" }; + return { disposition: "turn_started", started: Promise.resolve() }; } if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) { archivedAtToRestore = record.archivedAt; @@ -408,7 +447,11 @@ export async function startCreatedAgentInitialPrompt( ); if (dispatchResult.disposition === "turn_started") { - await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId); + await waitForAgentRunStartWithTimeout( + params.agentManager, + params.agentId, + dispatchResult.started, + ); } const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null; diff --git a/packages/server/src/server/agent/agent-run-state.ts b/packages/server/src/server/agent/agent-run-state.ts index 0ea85f6d81..3408fac978 100644 --- a/packages/server/src/server/agent/agent-run-state.ts +++ b/packages/server/src/server/agent/agent-run-state.ts @@ -13,7 +13,7 @@ export interface ForegroundTurnWaiter { type ForegroundRunStart = | { status: "pending" } | { status: "started"; turnId: string } - | { status: "failed"; error: string }; + | { status: "failed"; error: string; stale?: true }; export interface PendingForegroundRun { token: string; @@ -343,3 +343,59 @@ function settleTrackedRun(run: TrackedAgentRun): void { run.settled = true; run.resolveSettled(); } + +/** + * Follows one sender's prompt to the foreground run that starts it. Each run created for the + * prompt, including a stale-session retry, is bound here, so `started` settles for this + * sender's prompt and never for another run the agent tracks. + */ +export class ForegroundPromptStart { + readonly started: Promise; + private resolveStarted!: () => void; + private rejectStarted!: (error: Error) => void; + private run: PendingForegroundRun | null = null; + private done = false; + + constructor(private readonly agentId: string) { + this.started = new Promise((resolve, reject) => { + this.resolveStarted = resolve; + this.rejectStarted = reject; + }); + // Steered and fire-and-forget dispatches never wait on the start. + this.started.catch(() => undefined); + } + + /** A run was created for this prompt. */ + bind(run: PendingForegroundRun): void { + this.run = run; + void Promise.race([run.turnStartedPromise, run.settledPromise]).then(() => + this.settle(run, { ended: false }), + ); + } + + /** The prompt's dispatch is over; no further run will be created for it. */ + end(): void { + this.settle(this.run, { ended: true }); + } + + private settle(run: PendingForegroundRun | null, { ended }: { ended: boolean }): void { + if (this.done || run !== this.run) return; + if (run?.start.status === "started") { + this.done = true; + this.resolveStarted(); + return; + } + // A stale-session failure is retried with a new run; wait for it unless dispatch ended. + if (run?.start.status === "failed" && run.start.stale && !ended) return; + this.done = true; + this.rejectStarted(new Error(this.describeUnstarted(run))); + } + + private describeUnstarted(run: PendingForegroundRun | null): string { + if (run?.start.status === "failed") return run.start.error; + if (run?.settled) { + return `Agent ${this.agentId} run was canceled before its turn started; its prompt was not delivered`; + } + return `Agent ${this.agentId} run finished before starting`; + } +} diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 1f081885ce..ad7f97b834 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -528,6 +528,14 @@ export type AgentPermissionResponse = interrupt?: boolean; }; +/** A requested turn was canceled before the provider accepted it. */ +export class AgentTurnStartCanceledError extends Error { + constructor() { + super("Turn was canceled before starting"); + this.name = "AgentTurnStartCanceledError"; + } +} + export interface AgentRunResult { sessionId: string; finalText: string; diff --git a/packages/server/src/server/agent/create-agent/create.test.ts b/packages/server/src/server/agent/create-agent/create.test.ts index 4943628b17..b27b3c7c8a 100644 --- a/packages/server/src/server/agent/create-agent/create.test.ts +++ b/packages/server/src/server/agent/create-agent/create.test.ts @@ -10,6 +10,7 @@ import { AgentManager } from "../agent-manager.js"; import { AgentStorage } from "../agent-storage.js"; import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js"; import { createAgentCommand } from "./create.js"; +import { ForegroundPromptStart } from "../agent-run-state.js"; import type { ManagedAgent } from "../agent-manager.js"; const logger = createTestLogger(); @@ -89,9 +90,12 @@ test("session create forwards clientMessageId to the initial prompt run options" firstAgentContext: { attachments: [] }, }); - expect(streamAgent).toHaveBeenCalledWith("agent-1", "hello from create", { - clientMessageId: "msg-create-1", - }); + expect(streamAgent).toHaveBeenCalledWith( + "agent-1", + "hello from create", + { clientMessageId: "msg-create-1" }, + expect.any(ForegroundPromptStart), + ); }); test("session create validates the requested mode against the provider's modes", async () => { diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 679f4d04db..ad663bac0e 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -1,3 +1,4 @@ +import { AgentRunState, ForegroundPromptStart } from "./agent-run-state.js"; import { createFinishSubscriptions, createFinishObservation, @@ -279,8 +280,15 @@ function buildAgentManagerSpies() { steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }), tryRunOutOfBand: vi.fn().mockReturnValue(false), subscribe: vi.fn().mockReturnValue(() => {}), - streamAgent: vi.fn(() => (async function* noop() {})()), - waitForAgentRunStart: vi.fn().mockResolvedValue(undefined), + streamAgent: vi.fn( + (agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => { + const runs = new AgentRunState(); + const run = runs.createPendingRun(agentId); + runs.settleForegroundStart(run, { status: "started", turnId: `${agentId}-turn` }); + start?.bind(run); + return (async function* noop() {})(); + }, + ), respondToPermission: vi.fn(), cancelAgentRun: vi.fn(), getPendingPermissions: vi.fn(), diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 36985c4af3..d1c1a5055e 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -5428,7 +5428,7 @@ describe("Codex app-server provider", () => { threadStart.resolve({ thread: { id: "thread-1" } }); await expect(interruptPromise).resolves.toBeUndefined(); - await expect(resultPromise).rejects.toThrow("interrupted before reaching Codex"); + await expect(resultPromise).resolves.toMatchObject({ canceled: true, timeline: [] }); expect(appServer.requests()).not.toContainEqual( expect.objectContaining({ method: "turn/start" }), ); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 0e0be1042c..caae0c2261 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -3,6 +3,7 @@ import { applyProviderOptionsPatch } from "../option-controls.js"; import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js"; import { CodexBackgroundInventory } from "./codex/background-inventory.js"; import { + AgentTurnStartCanceledError, getAgentStreamEventTurnId, type AgentPermissionAction, type AgentCapabilityFlags, @@ -4696,7 +4697,7 @@ export class CodexAppServerAgentSession implements AgentSession { // outlives it into the new turn. await this.waitForInterruptedTurnCleanup(); if (pendingStart.cancelRequested) { - throw new Error("Codex turn start was interrupted before reaching Codex"); + throw new AgentTurnStartCanceledError(); } await this.client.request("turn/start", turnStart.params, TURN_START_TIMEOUT_MS); return { turnId }; diff --git a/packages/server/src/server/agent/providers/provider-runner.ts b/packages/server/src/server/agent/providers/provider-runner.ts index 94ec047706..4fa8d1c851 100644 --- a/packages/server/src/server/agent/providers/provider-runner.ts +++ b/packages/server/src/server/agent/providers/provider-runner.ts @@ -1,4 +1,5 @@ import { + AgentTurnStartCanceledError, getAgentStreamEventTurnId, type AgentPromptInput, type AgentRunOptions, @@ -90,6 +91,9 @@ export async function runProviderTurn({ processEvent(event); } await completion; + } catch (error) { + if (!(error instanceof AgentTurnStartCanceledError)) throw error; + return { sessionId: await getSessionId(), finalText: "", timeline: [], canceled: true }; } finally { unsubscribe(); } diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 1f22079bfa..c830717236 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -2051,7 +2051,7 @@ function createToolCatalog( }; } - const { disposition } = await sendPromptToAgent({ + const dispatch = await sendPromptToAgent({ agentManager, agentStorage, agentId, @@ -2070,11 +2070,14 @@ function createToolCatalog( }); // Return once the provider has accepted the turn, so the status reports it running. - if (disposition === "turn_started") { - await waitForAgentRunStartWithTimeout(agentManager, agentId).catch((error) => { - rejectNotification(); - throw error; - }); + const { disposition } = dispatch; + if (dispatch.disposition === "turn_started") { + await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch( + (error) => { + rejectNotification(); + throw error; + }, + ); } const currentSnapshot = agentManager.getAgent(agentId); diff --git a/packages/server/src/server/schedule/service.test.ts b/packages/server/src/server/schedule/service.test.ts index 26c4d0a62c..a2415ffe50 100644 --- a/packages/server/src/server/schedule/service.test.ts +++ b/packages/server/src/server/schedule/service.test.ts @@ -38,6 +38,7 @@ import { type ScheduleServiceOptions, } from "./service.js"; import { ScheduleStore } from "./store.js"; +import { ForegroundPromptStart } from "../agent/agent-run-state.js"; import type { ScheduleExecutionResult, StoredSchedule } from "@getpaseo/protocol/schedule/types"; interface ScheduleServiceInternals { @@ -754,6 +755,7 @@ describe("ScheduleService", () => { agent.id, expect.stringContaining(`Schedule fired (id=${schedule.id}, run=`), undefined, + expect.any(ForegroundPromptStart), ]); }); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index fcdbbae1ed..6b2b9f0f34 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -8993,6 +8993,7 @@ export class Session { await waitForAgentRunStartWithTimeout( this.agentManager, agentId, + result.started, this.delivery.requestSignal, ); } diff --git a/packages/server/src/server/test-utils/agent-messages.ts b/packages/server/src/server/test-utils/agent-messages.ts index ce188fbfd8..55cc698aab 100644 --- a/packages/server/src/server/test-utils/agent-messages.ts +++ b/packages/server/src/server/test-utils/agent-messages.ts @@ -50,7 +50,11 @@ export function createTestAgentMessages(params: { runOptions: { clientMessageId: request.messageIds[0] }, }); if (result.disposition === "turn_started") - await waitForAgentRunStartWithTimeout(params.agentManager, request.recipientId); + await waitForAgentRunStartWithTimeout( + params.agentManager, + request.recipientId, + result.started, + ); return result.disposition; }, onError: (error, request) => diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 793b8041e4..588624a9b5 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -745,7 +745,7 @@ export class VoiceAssistantWebSocketServer { { replayState: false }, ), dispatch: async (batch) => { - const { disposition } = await sendPreparedPromptToAgent({ + const dispatch = await sendPreparedPromptToAgent({ agentManager, agentStorage, agentId: batch.recipientId, @@ -758,9 +758,9 @@ export class VoiceAssistantWebSocketServer { runOptions: { clientMessageId: batch.messageIds[0] }, logger: this.logger, }); - if (disposition === "turn_started") - await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId); - return disposition; + if (dispatch.disposition === "turn_started") + await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId, dispatch.started); + return dispatch.disposition; }, onError: (err, batch) => this.logger.error( From 349a2e43eaf11259741c3d3d791a81d492201e91 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:41:21 +0000 Subject: [PATCH 133/160] Keep the phone model-label sweep from reading the browser's clipped label (#9934) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(app): wait for the model control to re-measure in the label sweep The phone label sweep read the folded model control twice, 100ms apart, after each resize. A resize reflows the page at once and the browser clips the model label with its own ellipsis until the control's layout event arrives. On a slow runner both reads landed in that window, so the sweep recorded a truncated label beside the thinking label and stopped. A settled read now also requires the model label to fit its box, and gives up after 10s with the last state. Co-Authored-By: Claude Opus 5.5 * test(app): settle the label sweep on the label its box fits The previous commit rejected one in-between state: the browser clipping the model label beside the thinking label. A slow runner can also leave the label truncated to "Ten second…" after the thinking label is gone, because the label's box widens at once but its text waits for the next layout event. A settled read now requires the shown label to match the box: the full text when the invisible full-text sizer fits, otherwise a truncation that fits. That covers both states, so the clipped-label special case goes. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../helpers/composer-control-density.ts | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/app/e2e/support/helpers/composer-control-density.ts b/packages/app/e2e/support/helpers/composer-control-density.ts index 089b112b74..e41add56c3 100644 --- a/packages/app/e2e/support/helpers/composer-control-density.ts +++ b/packages/app/e2e/support/helpers/composer-control-density.ts @@ -170,6 +170,11 @@ export interface ModelTriggerLabelState { modelShown: boolean; modelText: string; modelTruncated: boolean; + /** + * The model label shows what its box fits right now: the full text when it fits, otherwise a + * truncation that fits. False while the control has yet to catch up with a reflow. + */ + modelFitsBox: boolean; } declare global { @@ -194,12 +199,18 @@ function readModelTriggerLabelStateInPage(): ModelTriggerLabelState { }; const modelShown = model !== undefined && shown(model); const modelText = model?.textContent ?? ""; + const overflows = (node: Element) => node.scrollWidth > node.clientWidth; + const modelOverflows = model !== undefined && overflows(model); + // The label's box is sized by an invisible copy of the full text, its first child, so the box + // follows a reflow at once while the shown text waits for the control's next layout event. + const fullTextSizer = model?.parentElement?.parentElement?.firstElementChild; + const fullTextFits = fullTextSizer ? !overflows(fullTextSizer) : true; return { modelShown, modelText, thinkingShown: modelShown && thinking !== undefined, - modelTruncated: - model !== undefined && (modelText.endsWith("…") || model.scrollWidth > model.clientWidth), + modelTruncated: modelText.endsWith("…") || modelOverflows, + modelFitsBox: !modelOverflows && modelText.endsWith("…") !== fullTextFits, }; } @@ -217,13 +228,26 @@ export async function recordModelTriggerFramesFromLoad(page: Page): Promise { + const deadline = Date.now() + 10_000; let previous = await page.evaluate(readModelTriggerLabelStateInPage); for (;;) { await page.waitForTimeout(100); const next = await page.evaluate(readModelTriggerLabelStateInPage); - if (JSON.stringify(next) === JSON.stringify(previous)) return next; + const agrees = JSON.stringify(next) === JSON.stringify(previous); + if (agrees && next.modelFitsBox) return next; + if (Date.now() > deadline) { + throw new Error( + `the model control never settled on a label that fits its box: ${JSON.stringify(next)}`, + ); + } previous = next; } } From 689e3412b472ba6f17ed926e693d39441b8d82dd Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 17 Nov 2026 13:43:31 +0700 Subject: [PATCH 134/160] chore(release): reconcile main with 0.16.1 (#9945) Brings in the shipped 0.16.1 CHANGELOG.md and CHANGELOG.zh-CN.md entries exactly as tagged, the 0.16.1 version in every package.json and package-lock.json, and the F-Droid changelog files for version codes 160011-160014. --- CHANGELOG.md | 15 +++++ CHANGELOG.zh-CN.md | 15 +++++ .../android/en-US/changelogs/160011.txt | 6 ++ .../android/en-US/changelogs/160012.txt | 6 ++ .../android/en-US/changelogs/160013.txt | 6 ++ .../android/en-US/changelogs/160014.txt | 6 ++ package-lock.json | 56 +++++++++---------- package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 8 +-- packages/client/package.json | 6 +- packages/desktop/package.json | 2 +- packages/expo-two-way-audio/package.json | 2 +- packages/highlight/package.json | 2 +- packages/plugin/package.json | 10 ++-- packages/protocol/package.json | 2 +- packages/relay/package.json | 2 +- packages/server/package.json | 12 ++-- packages/website/package.json | 2 +- plugins/package.json | 2 +- 20 files changed, 109 insertions(+), 55 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/160011.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/160012.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/160013.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/160014.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 92cf6a76c8..96bb9aeee0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 0.16.1 - 2026-11-17 + +### Fixed + +- Fixed Claude Bypass approving actions without a permission card when a `permissions.ask` rule or a hook that returns `ask` required one ([#9927](https://github.com/getpaseo/paseo/pull/9927)) +- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input ([#9909](https://github.com/getpaseo/paseo/pull/9909) by [@michaelhthomas](https://github.com/michaelhthomas)) +- Fixed Claude sessions failing until `/login` when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token ([#9855](https://github.com/getpaseo/paseo/pull/9855) by [@daysun-k](https://github.com/daysun-k)) +- Fixed Add host text fields on web drawing without a box, which left the host password field invisible ([#9865](https://github.com/getpaseo/paseo/pull/9865) by [@angusb93](https://github.com/angusb93)) +- Fixed an OpenCode question that could not be answered or dismissed after a new message steered the turn ([#9891](https://github.com/getpaseo/paseo/pull/9891)) +- Fixed Pi and OMP model names that contain `/` being cut to the text after the last slash ([#9823](https://github.com/getpaseo/paseo/pull/9823), [#9836](https://github.com/getpaseo/paseo/pull/9836) by [@rms523](https://github.com/rms523)) +- Fixed Changes leaving out an edit when the file was saved with the same size in the same second it was staged ([#9854](https://github.com/getpaseo/paseo/pull/9854)) +- Fixed an error toast that never closed when marking a chat as read failed ([#9837](https://github.com/getpaseo/paseo/pull/9837)) +- Fixed wait results and finish notifications after a daemon restart joining an agent's self-started reply to the reply before it ([#9846](https://github.com/getpaseo/paseo/pull/9846)) +- Fixed Codex chats staying loaded in the daemon until restart when a client opened them only to read their history ([#9859](https://github.com/getpaseo/paseo/pull/9859) by [@Spshulem](https://github.com/Spshulem)) + ## 0.16.0 - 2026-11-16 - **Background tasks:** See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635) by [@fxlelouarn](https://github.com/fxlelouarn)) diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 21b99a1345..62dc8df5f8 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,5 +1,20 @@ # Changelog +## 0.16.1 - 2026-11-17 + +### 修复 + +- 修复 `permissions.ask` 规则或返回 `ask` 的钩子要求确认时,Claude Bypass 不显示权限卡片就批准操作的问题 ([#9927](https://github.com/getpaseo/paseo/pull/9927)) +- 修复触屏笔记本以触控板或鼠标为主要输入时,控件仍使用触控尺寸的问题 ([#9909](https://github.com/getpaseo/paseo/pull/9909),贡献者:[@michaelhthomas](https://github.com/michaelhthomas)) +- 修复 Claude Code 正在续期已过期的访问令牌时,Paseo 刷新 Claude 模型列表导致 Claude 会话在执行 `/login` 前一直失败的问题 ([#9855](https://github.com/getpaseo/paseo/pull/9855),贡献者:[@daysun-k](https://github.com/daysun-k)) +- 修复 Web 端“添加主机”的文本字段没有输入框,导致主机密码字段不可见的问题 ([#9865](https://github.com/getpaseo/paseo/pull/9865),贡献者:[@angusb93](https://github.com/angusb93)) +- 修复新消息引导当前回合后,OpenCode 提问既无法回答也无法关闭的问题 ([#9891](https://github.com/getpaseo/paseo/pull/9891)) +- 修复名称包含 `/` 的 Pi 和 OMP 模型被截成最后一个斜杠之后文本的问题 ([#9823](https://github.com/getpaseo/paseo/pull/9823), [#9836](https://github.com/getpaseo/paseo/pull/9836),贡献者:[@rms523](https://github.com/rms523)) +- 修复文件暂存后在同一秒内以相同大小保存时,“更改”遗漏该修改的问题 ([#9854](https://github.com/getpaseo/paseo/pull/9854)) +- 修复将对话标记为已读失败后,错误提示一直不关闭的问题 ([#9837](https://github.com/getpaseo/paseo/pull/9837)) +- 修复 daemon 重启后,等待结果和完成通知把 Agent 自行开始的回复与上一条回复拼接在一起的问题 ([#9846](https://github.com/getpaseo/paseo/pull/9846)) +- 修复客户端仅为读取历史而打开的 Codex 对话一直加载在 daemon 中直到重启的问题 ([#9859](https://github.com/getpaseo/paseo/pull/9859),贡献者:[@Spshulem](https://github.com/Spshulem)) + ## 0.16.0 - 2026-11-16 - **后台任务**:在 Composer 上方查看并停止 Claude Code、Codex 和 OpenCode v2 的后台任务。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635),贡献者:[@fxlelouarn](https://github.com/fxlelouarn)) diff --git a/fastlane/metadata/android/en-US/changelogs/160011.txt b/fastlane/metadata/android/en-US/changelogs/160011.txt new file mode 100644 index 0000000000..bb019577f4 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160011.txt @@ -0,0 +1,6 @@ +Fixed +- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one +- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input +- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/160012.txt b/fastlane/metadata/android/en-US/changelogs/160012.txt new file mode 100644 index 0000000000..bb019577f4 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160012.txt @@ -0,0 +1,6 @@ +Fixed +- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one +- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input +- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/160013.txt b/fastlane/metadata/android/en-US/changelogs/160013.txt new file mode 100644 index 0000000000..bb019577f4 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160013.txt @@ -0,0 +1,6 @@ +Fixed +- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one +- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input +- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token + +Full notes: https://paseo.sh/changelog diff --git a/fastlane/metadata/android/en-US/changelogs/160014.txt b/fastlane/metadata/android/en-US/changelogs/160014.txt new file mode 100644 index 0000000000..bb019577f4 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/160014.txt @@ -0,0 +1,6 @@ +Fixed +- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one +- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input +- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token + +Full notes: https://paseo.sh/changelog diff --git a/package-lock.json b/package-lock.json index 52bce5f983..c09530e917 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "paseo", - "version": "0.16.0", + "version": "0.16.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "paseo", - "version": "0.16.0", + "version": "0.16.1", "hasInstallScript": true, "license": "Apache-2.0", "workspaces": [ @@ -37468,7 +37468,7 @@ }, "packages/app": { "name": "@getpaseo/app", - "version": "0.16.0", + "version": "0.16.1", "dependencies": { "@codemirror/commands": "6.10.4", "@codemirror/language": "6.12.4", @@ -39637,13 +39637,13 @@ }, "packages/cli": { "name": "@getpaseo/cli", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0", - "@getpaseo/protocol": "0.16.0", - "@getpaseo/server": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/server": "0.16.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", @@ -39890,11 +39890,11 @@ }, "packages/client": { "name": "@getpaseo/client", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { - "@getpaseo/protocol": "0.16.0", - "@getpaseo/relay": "0.16.0", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/relay": "0.16.1", "ws": "^8.20.0", "zod": "^4.4.3" }, @@ -39906,7 +39906,7 @@ }, "packages/desktop": { "name": "@getpaseo/desktop", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "@getpaseo/cli": "*", @@ -40149,7 +40149,7 @@ }, "packages/expo-two-way-audio": { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0", + "version": "0.16.1", "license": "MIT", "devDependencies": { "@types/jest": "^29.5.14", @@ -40195,7 +40195,7 @@ }, "packages/highlight": { "name": "@getpaseo/highlight", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "@codemirror/language": "6.12.4", @@ -40225,7 +40225,7 @@ }, "packages/plugin": { "name": "@getpaseo/plugin", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^1.4.0", @@ -40233,8 +40233,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0", - "@getpaseo/protocol": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -40244,8 +40244,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0", - "@getpaseo/protocol": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" @@ -40267,7 +40267,7 @@ }, "packages/protocol": { "name": "@getpaseo/protocol", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "semver": "^7.8.5", @@ -40295,7 +40295,7 @@ }, "packages/relay": { "name": "@getpaseo/relay", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "@noble/ciphers": "^2.4.0", @@ -40517,17 +40517,17 @@ }, "packages/server": { "name": "@getpaseo/server", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0", - "@getpaseo/highlight": "0.16.0", - "@getpaseo/plugin": "0.16.0", - "@getpaseo/protocol": "0.16.0", - "@getpaseo/relay": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/highlight": "0.16.1", + "@getpaseo/plugin": "0.16.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/relay": "0.16.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", @@ -41474,7 +41474,7 @@ }, "packages/website": { "name": "@getpaseo/website", - "version": "0.16.0", + "version": "0.16.1", "dependencies": { "@cloudflare/vite-plugin": "^1.29.1", "@cloudflare/workers-types": "^4.20260317.1", @@ -43084,7 +43084,7 @@ }, "plugins": { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0", + "version": "0.16.1", "dependencies": { "@getpaseo/plugin": "*", "zod": "^4.4.3" diff --git a/package.json b/package.json index 1f75dabfe3..bac85284a3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paseo", - "version": "0.16.0", + "version": "0.16.1", "private": true, "description": "Paseo: voice-controlled development environment for local AI coding agents", "keywords": [ diff --git a/packages/app/package.json b/packages/app/package.json index 7b41060dda..6335a2673b 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/app", - "version": "0.16.0", + "version": "0.16.1", "private": true, "main": "index.ts", "scripts": { diff --git a/packages/cli/package.json b/packages/cli/package.json index b930245d22..06853cc2b3 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/cli", - "version": "0.16.0", + "version": "0.16.1", "description": "Paseo CLI - control your AI coding agents from the command line", "license": "Apache-2.0", "bin": { @@ -29,9 +29,9 @@ }, "dependencies": { "@clack/prompts": "^1.0.0", - "@getpaseo/client": "0.16.0", - "@getpaseo/protocol": "0.16.0", - "@getpaseo/server": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/server": "0.16.1", "chalk": "^5.3.0", "commander": "^12.0.0", "mime-types": "^2.1.35", diff --git a/packages/client/package.json b/packages/client/package.json index 79dbeba87f..9c418743e4 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/client", - "version": "0.16.0", + "version": "0.16.1", "description": "Paseo client SDK package", "license": "Apache-2.0", "files": [ @@ -49,8 +49,8 @@ "measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts" }, "dependencies": { - "@getpaseo/protocol": "0.16.0", - "@getpaseo/relay": "0.16.0", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/relay": "0.16.1", "ws": "^8.20.0", "zod": "^4.4.3" }, diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 13c5853a08..307c216a59 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/desktop", - "version": "0.16.0", + "version": "0.16.1", "private": true, "description": "Paseo desktop app (Electron wrapper)", "homepage": "https://paseo.sh", diff --git a/packages/expo-two-way-audio/package.json b/packages/expo-two-way-audio/package.json index 48768d5ba9..eb2f399a5b 100644 --- a/packages/expo-two-way-audio/package.json +++ b/packages/expo-two-way-audio/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/expo-two-way-audio", - "version": "0.16.0", + "version": "0.16.1", "description": "Native module for two way audio streaming", "keywords": [ "ExpoTwoWayAudio", diff --git a/packages/highlight/package.json b/packages/highlight/package.json index 9b86990ee6..6af3ddff26 100644 --- a/packages/highlight/package.json +++ b/packages/highlight/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/highlight", - "version": "0.16.0", + "version": "0.16.1", "license": "Apache-2.0", "files": [ "dist", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 89754fa032..7ff628dc38 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/plugin", - "version": "0.16.0", + "version": "0.16.1", "description": "Paseo plugin SDK package", "license": "Apache-2.0", "files": [ @@ -78,8 +78,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@getpaseo/client": "0.16.0", - "@getpaseo/protocol": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", "@types/node": "^20.9.0", "@types/react": "~19.2.0", "react": "19.2.3", @@ -89,8 +89,8 @@ "zod": "^4.4.3" }, "peerDependencies": { - "@getpaseo/client": "0.16.0", - "@getpaseo/protocol": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/protocol": "0.16.1", "react": ">=19.1.0 <20", "react-native": ">=0.81.5", "zod": "^4.4.3" diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 7b2ac77239..8f196a4743 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/protocol", - "version": "0.16.0", + "version": "0.16.1", "description": "Paseo shared protocol schemas and wire types", "license": "Apache-2.0", "files": [ diff --git a/packages/relay/package.json b/packages/relay/package.json index 34876b8756..df8c1de7df 100644 --- a/packages/relay/package.json +++ b/packages/relay/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/relay", - "version": "0.16.0", + "version": "0.16.1", "description": "Paseo relay for bridging daemon and client connections", "license": "Apache-2.0", "files": [ diff --git a/packages/server/package.json b/packages/server/package.json index 486208f8f2..f732124051 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/server", - "version": "0.16.0", + "version": "0.16.1", "description": "Paseo backend server", "license": "Apache-2.0", "files": [ @@ -109,11 +109,11 @@ "@agentclientprotocol/sdk": "^0.17.1", "@anthropic-ai/claude-agent-sdk": "0.3.326", "@anthropic-ai/sdk": "^0.104.2", - "@getpaseo/client": "0.16.0", - "@getpaseo/highlight": "0.16.0", - "@getpaseo/plugin": "0.16.0", - "@getpaseo/protocol": "0.16.0", - "@getpaseo/relay": "0.16.0", + "@getpaseo/client": "0.16.1", + "@getpaseo/highlight": "0.16.1", + "@getpaseo/plugin": "0.16.1", + "@getpaseo/protocol": "0.16.1", + "@getpaseo/relay": "0.16.1", "@isaacs/ttlcache": "^2.1.4", "@modelcontextprotocol/sdk": "1.29.0", "@opencode-ai/sdk": "1.14.46", diff --git a/packages/website/package.json b/packages/website/package.json index 7bdeba45b9..0e5a5f5003 100644 --- a/packages/website/package.json +++ b/packages/website/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/website", - "version": "0.16.0", + "version": "0.16.1", "private": true, "type": "module", "scripts": { diff --git a/plugins/package.json b/plugins/package.json index 158d533844..c0e59d6a6e 100644 --- a/plugins/package.json +++ b/plugins/package.json @@ -1,6 +1,6 @@ { "name": "@getpaseo/builtin-plugins", - "version": "0.16.0", + "version": "0.16.1", "private": true, "type": "module", "scripts": { From c71d41f687cd56a8709d90ab4c23873e44ab7407 Mon Sep 17 00:00:00 2001 From: "paseo-ai[bot]" <266920839+paseo-ai[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:51:06 +0000 Subject: [PATCH 135/160] fix: update lockfile signatures and Nix hash [skip ci] --- nix/npm-deps.hash | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/npm-deps.hash b/nix/npm-deps.hash index bfdaef93ac..37e312c5d4 100644 --- a/nix/npm-deps.hash +++ b/nix/npm-deps.hash @@ -1 +1 @@ -sha256-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk= +sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng= From 02124454bc6baf94f1730c986dfc36a031489069 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:04:50 +0000 Subject: [PATCH 136/160] Keep failed downloads inside the app on web and desktop (#9937) On web and desktop, Download over a direct connection now fetches the file and saves it from a blob instead of navigating the window to the host URL. A rejected or unreachable download shows an error in the download toast and the app stays on the workspace. The daemon's HTTP CORS check uses the same origin rule as the WebSocket upgrade. Closes #9895 Co-authored-by: panta82 <4291324+panta82@users.noreply.github.com> --- .../file-explorer-context-actions.spec.ts | 49 +++++++++++-- packages/app/src/i18n/resources/ar.ts | 1 + packages/app/src/i18n/resources/en.ts | 1 + packages/app/src/i18n/resources/es.ts | 1 + packages/app/src/i18n/resources/fr.ts | 1 + packages/app/src/i18n/resources/ja.ts | 1 + packages/app/src/i18n/resources/ko.ts | 1 + packages/app/src/i18n/resources/pt-BR.ts | 1 + packages/app/src/i18n/resources/ru.ts | 1 + packages/app/src/i18n/resources/zh-CN.ts | 1 + .../app/src/stores/download-store.test.ts | 53 ++++++++++++++ packages/app/src/stores/download-store.ts | 73 ++++++++++--------- packages/server/src/server/bootstrap.ts | 4 +- .../daemon-e2e/file-download.e2e.test.ts | 25 ++++++- .../server/src/server/websocket-server.ts | 20 ++++- 15 files changed, 188 insertions(+), 45 deletions(-) diff --git a/packages/app/e2e/browser/file-explorer-context-actions.spec.ts b/packages/app/e2e/browser/file-explorer-context-actions.spec.ts index 333ee31759..5c79fcf7ad 100644 --- a/packages/app/e2e/browser/file-explorer-context-actions.spec.ts +++ b/packages/app/e2e/browser/file-explorer-context-actions.spec.ts @@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as await gotoWorkspace(page, workspace.workspaceId); await openFileExplorer(page); + const daemonRequest = page.waitForRequest("**/api/files/download?*"); const downloaded = await downloadFileFromExplorer(page, fileName); - const url = new URL(downloaded.url()); - expect(url.protocol).toBe("http:"); - expect(url.port).toBe(getE2EDaemonPort()); - expect(url.pathname).toBe("/api/files/download"); - expect(url.searchParams.get("token")).toBeTruthy(); + const requestUrl = new URL((await daemonRequest).url()); + expect(requestUrl.port).toBe(getE2EDaemonPort()); + expect(requestUrl.searchParams.get("token")).toBeTruthy(); + expect(new URL(downloaded.url()).protocol).toBe("blob:"); expect(downloaded.suggestedFilename()).toBe(fileName); const savedFile = testInfo.outputPath(fileName); await downloaded.saveAs(savedFile); @@ -479,6 +479,45 @@ test("downloads a file over direct TCP with its original filename and bytes", as expect(await readFile(savedFile)).toEqual(source); }); +test("keeps the app open and shows the error when the host rejects a download", async ({ + page, +}, testInfo) => { + const fileName = "removed-during-download.bin"; + const filePath = path.join(workspace.workspaceDirectory, fileName); + const source = Buffer.from([0, 1, 2, 255]); + await writeFile(filePath, source); + await gotoWorkspace(page, workspace.workspaceId); + await openFileExplorer(page); + const workspaceUrl = page.url(); + + // The file disappears after the token is issued, so the real daemon answers 404. + await page.route( + "**/api/files/download?*", + async (route) => { + await rm(filePath); + await route.continue(); + }, + { times: 1 }, + ); + await page + .getByTestId("file-explorer-tree-scroll") + .getByText(fileName, { exact: true }) + .click({ button: "right" }); + await page.getByRole("menuitem", { name: "Download", exact: true }).click(); + + await expect( + page.getByText("Failed to download file (HTTP 404).", { exact: true }), + ).toBeVisible(); + expect(page.url()).toBe(workspaceUrl); + + await writeFile(filePath, source); + const downloaded = await downloadFileFromExplorer(page, fileName); + const savedFile = testInfo.outputPath(fileName); + await downloaded.saveAs(savedFile); + expect(await readFile(savedFile)).toEqual(source); + expect(page.url()).toBe(workspaceUrl); +}); + test("downloads an unsupported binary from its preview with original filename and bytes", async ({ page, }, testInfo) => { diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 51250d04b1..e79e901253 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2017,6 +2017,7 @@ export const ar: TranslationResources = { hostUnavailable: "مضيف التنزيل غير متاح.", cancelled: "تم إلغاء التنزيل.", failed: "فشل تنزيل الملف.", + httpFailed: "فشل تنزيل الملف (HTTP {{status}}).", shareFile: "مشاركة الملف", shareFileNamed: "مشاركة{{fileName}}", }, diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index f7452c2fc3..a59de6a6a1 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2045,6 +2045,7 @@ export const en = { hostUnavailable: "Download host is unavailable.", cancelled: "Download was cancelled.", failed: "Failed to download file.", + httpFailed: "Failed to download file (HTTP {{status}}).", shareFile: "Share file", shareFileNamed: "Share {{fileName}}", }, diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 6f3c051837..e8a942c775 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2066,6 +2066,7 @@ export const es: TranslationResources = { hostUnavailable: "El host de descarga no está disponible.", cancelled: "La descarga fue cancelada.", failed: "No se pudo descargar el archivo.", + httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).", shareFile: "compartir archivo", shareFileNamed: "Compartir{{fileName}}", }, diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 022bc3dd4c..8f7eba11ac 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2065,6 +2065,7 @@ export const fr: TranslationResources = { hostUnavailable: "L’hôte de téléchargement est indisponible.", cancelled: "Téléchargement annulé.", failed: "Impossible de télécharger le fichier.", + httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).", shareFile: "Partager le fichier", shareFileNamed: "Partager {{fileName}}", }, diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 75f2d55795..5cd17d7300 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2038,6 +2038,7 @@ export const ja: TranslationResources = { hostUnavailable: "ダウンロードホストが利用できません。", cancelled: "ダウンロードがキャンセルされました。", failed: "ファイルのダウンロードに失敗しました。", + httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).", shareFile: "ファイルを共有", shareFileNamed: "{{fileName}}を共有", }, diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index d4ec87ad8e..29fe850ac1 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2028,6 +2028,7 @@ export const ko: TranslationResources = { hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.", cancelled: "다운로드가 취소되었습니다.", failed: "파일을 다운로드하지 못했습니다.", + httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).", shareFile: "파일 공유", shareFileNamed: "{{fileName}} 공유", }, diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 54516fc2de..405de1fe44 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2051,6 +2051,7 @@ export const ptBR: TranslationResources = { hostUnavailable: "Host de download indisponível.", cancelled: "Download cancelado.", failed: "Falha ao baixar arquivo.", + httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).", shareFile: "Compartilhar arquivo", shareFileNamed: "Compartilhar {{fileName}}", }, diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 9ee2f1746c..bfe65aa2b6 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2051,6 +2051,7 @@ export const ru: TranslationResources = { hostUnavailable: "Хост загрузки недоступен.", cancelled: "Загрузка отменена.", failed: "Не удалось загрузить файл.", + httpFailed: "Не удалось загрузить файл (HTTP {{status}}).", shareFile: "Поделиться файлом", shareFileNamed: "Поделиться {{fileName}}", }, diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index e2b6762830..c2d2500240 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1994,6 +1994,7 @@ export const zhCN: TranslationResources = { hostUnavailable: "下载 Host 不可用。", cancelled: "下载已取消。", failed: "下载文件失败。", + httpFailed: "下载文件失败 (HTTP {{status}}).", shareFile: "共享文件", shareFileNamed: "共享 {{fileName}}", }, diff --git a/packages/app/src/stores/download-store.test.ts b/packages/app/src/stores/download-store.test.ts index d3657b4c34..4d176f6505 100644 --- a/packages/app/src/stores/download-store.test.ts +++ b/packages/app/src/stores/download-store.test.ts @@ -90,6 +90,7 @@ interface StartInput { token?: ReturnType; reader?: ReturnType; saver?: ReturnType; + fetchFile?: typeof fetch; } async function startDownload(input: StartInput): Promise { @@ -108,6 +109,7 @@ async function startDownload(input: StartInput): Promise { requestFileDownloadToken: token.request, readFile: reader.read, saveFile: saver.save, + fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)), }); const { activeDownloadId, downloads } = useDownloadStore.getState(); return activeDownloadId ? downloads.get(activeDownloadId) : undefined; @@ -203,6 +205,57 @@ describe("download store transport selection", () => { expect(saver.savedFiles).toEqual([]); }); + it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => { + const requests: Array = []; + const download = await startDownload({ + profile: profileWith([localTcpConnection]), + activeConnectionId: localTcpConnection.id, + fetchFile: async (_url, init) => { + requests.push(init); + return new Response("

401 Authorization Required

", { + status: 401, + headers: { "WWW-Authenticate": 'Basic realm="Paseo"' }, + }); + }, + }); + + expect(download).toMatchObject({ + status: "error", + message: i18n.t("downloads.httpFailed", { status: 401 }), + }); + expect(requests).toEqual([{ credentials: "include", redirect: "error" }]); + }); + + it("fails with a readable message when the download request cannot reach the host", async () => { + const download = await startDownload({ + profile: profileWith([localTcpConnection]), + activeConnectionId: localTcpConnection.id, + fetchFile: async () => { + throw new TypeError("Failed to fetch"); + }, + }); + + expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") }); + }); + + it("fails with a readable message when the connection drops while the file is downloading", async () => { + const saver = createFileSaver(); + const download = await startDownload({ + profile: profileWith([localTcpConnection]), + activeConnectionId: localTcpConnection.id, + fetchFile: async () => + new Response( + new ReadableStream({ + start: (controller) => controller.error(new TypeError("network error")), + }), + ), + saver, + }); + + expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") }); + expect(saver.savedFiles).toEqual([]); + }); + it("fails the download and saves nothing when the session read fails", async () => { const reader = createFileReader(async () => { throw new Error("Connection lost"); diff --git a/packages/app/src/stores/download-store.ts b/packages/app/src/stores/download-store.ts index 790fbd7dee..ae7ac647b4 100644 --- a/packages/app/src/stores/download-store.ts +++ b/packages/app/src/stores/download-store.ts @@ -4,7 +4,6 @@ import * as LegacyFileSystem from "expo-file-system/legacy"; import * as Sharing from "expo-sharing"; import type { HostProfile } from "@/types/host-connection"; import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints"; -import { openExternalUrl } from "@/utils/open-external-url"; import { isWeb } from "@/constants/platform"; import { i18n } from "@/i18n/i18next"; @@ -59,6 +58,7 @@ interface DownloadState { /** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */ readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>; saveFile?: typeof saveDownloadedBytes; + fetchFile?: typeof fetch; }) => Promise; updateProgress: (id: string, progress: DownloadProgress) => void; @@ -86,6 +86,7 @@ export const useDownloadStore = create()((set, get) => ({ requestFileDownloadToken, readFile, saveFile = saveDownloadedBytes, + fetchFile = fetch, }) => { const id = generateDownloadId(); const download: Download = { @@ -144,14 +145,11 @@ export const useDownloadStore = create()((set, get) => ({ throw new Error(i18n.t("downloads.hostUnavailable")); } - const downloadUrl = buildDownloadUrl( - downloadTarget.baseUrl, - tokenResponse.token, - isWeb ? downloadTarget.authCredentials : null, - ); + const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token); if (isWeb) { - triggerBrowserDownload(downloadUrl, resolvedFileName); + const file = await fetchDownload(fetchFile, downloadUrl); + saveBrowserFile(file, resolvedFileName); get().completeDownload(id); return; } @@ -198,11 +196,6 @@ export const useDownloadStore = create()((set, get) => ({ await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName); } catch (error) { const message = error instanceof Error ? error.message : i18n.t("downloads.failed"); - if (isWeb) { - console.warn("[DownloadStore] Download failed:", message); - get().failDownload(id, message); - return; - } get().failDownload(id, message); } }, @@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map): string | nu interface DownloadTarget { baseUrl: string | null; authHeader: string | null; - authCredentials: { username: string; password: string } | null; } /** @@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget( buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }), ); } catch { - return { baseUrl: null, authHeader: null, authCredentials: null }; + return { baseUrl: null, authHeader: null }; } if (parsed.protocol === "ws:") { @@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget( ? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}` : null; - return { baseUrl, authHeader, authCredentials }; + return { baseUrl, authHeader }; } -function buildDownloadUrl( - baseUrl: string, - token: string, - authCredentials: { username: string; password: string } | null, -): string { +function buildDownloadUrl(baseUrl: string, token: string): string { const url = new URL("/api/files/download", baseUrl); url.searchParams.set("token", token); - if (authCredentials) { - url.username = authCredentials.username; - url.password = authCredentials.password; - } return url.toString(); } +/** + * Fetches the file instead of navigating to it. The app runs on another origin than the host + * (paseo://app on desktop), so a link to the download URL navigates the whole window, and any + * response that is not the file (a proxy's 401 page, a 404) replaces the app. + */ +async function fetchDownload(fetchFile: typeof fetch, url: string): Promise { + let response: Response; + try { + // Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the + // host lets the download through. Refuse redirects: a proxy that redirects to a login page + // would otherwise be saved as the file. + response = await fetchFile(url, { credentials: "include", redirect: "error" }); + } catch { + throw new Error(i18n.t("downloads.failed")); + } + if (!response.ok) { + throw new Error(i18n.t("downloads.httpFailed", { status: response.status })); + } + try { + // The body streams after the headers, so the connection can still drop here. + return await response.blob(); + } catch { + throw new Error(i18n.t("downloads.failed")); + } +} + /** * Saves bytes read over the session. Web and Electron hand them to the browser's download * manager and return `null`; native writes the file and returns its URI for the share sheet. @@ -361,12 +371,7 @@ async function saveDownloadedBytes({ if (isWeb) { const buffer = new ArrayBuffer(bytes.byteLength); new Uint8Array(buffer).set(bytes); - const url = URL.createObjectURL( - new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), - ); - triggerBrowserDownload(url, fileName); - // The browser may still be reading the blob while its save prompt is open. - setTimeout(() => URL.revokeObjectURL(url), 60_000); + saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName); return null; } // Resolve and write in one tick so two downloads of the same name cannot pick the same path. @@ -390,14 +395,12 @@ async function shareSavedFile( } } -function triggerBrowserDownload(url: string, fileName: string) { +function saveBrowserFile(file: Blob, fileName: string) { if (typeof document === "undefined") { - if (typeof window !== "undefined") { - void openExternalUrl(url); - } return; } + const url = URL.createObjectURL(file); const link = document.createElement("a"); link.href = url; link.download = fileName; @@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, fileName: string) { document.body.appendChild(link); link.click(); link.remove(); + // The browser may still be reading the blob while its save prompt is open. + setTimeout(() => URL.revokeObjectURL(url), 60_000); } function resolveDownloadTargetFile(fileName: string): FSFile { diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index df4dd21c10..a1ee215515 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: { ); } -import { VoiceAssistantWebSocketServer } from "./websocket-server.js"; +import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js"; import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js"; import { createWorkspaceLabelService } from "./workspace-labels/index.js"; import { createGitHubService } from "../services/github-service.js"; @@ -813,7 +813,7 @@ export async function createPaseoDaemon( app.use((req, res, next) => { const origin = req.headers.origin; - if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) { + if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) { res.setHeader("Access-Control-Allow-Origin", origin); res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); diff --git a/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts b/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts index 54ec1964c1..0a0da6f0e9 100644 --- a/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/file-download.e2e.test.ts @@ -9,7 +9,7 @@ import { symlinkSync, } from "fs"; import { once } from "node:events"; -import { get } from "node:http"; +import { get, type IncomingMessage } from "node:http"; import { tmpdir } from "os"; import path from "path"; import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js"; @@ -69,6 +69,29 @@ describe("daemon E2E", () => { }, 60000); describe("file download tokens", () => { + test("lets a page on a loopback alias of the request's host and port fetch a download", async () => { + const cwd = tmpCwd(); + writeFileSync(path.join(cwd, "download.bin"), "download bytes"); + try { + // The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at + // http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket + // accepts this origin, so the download must as well. + const token = await ctx.client.requestDownloadToken(cwd, "download.bin"); + const request = get({ + host: "127.0.0.1", + port: ctx.daemon.port, + path: `/api/files/download?token=${token.token}`, + headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" }, + }); + const [response] = (await once(request, "response")) as [IncomingMessage]; + response.resume(); + expect(response.statusCode).toBe(200); + expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080"); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + }); + test.skipIf(process.platform !== "linux")( "releases file descriptors after repeated HTTP download cancellations", async () => { diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 588624a9b5..2e6e299837 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -998,9 +998,7 @@ export class VoiceAssistantWebSocketServer { callback(false, 403, "Host not allowed"); return; } - const sameOrigin = isWebSocketSameOrigin(origin, requestHost); - - if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) { + if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) { callback(true); } else { this.incrementRuntimeCounter("originRejected"); @@ -3267,6 +3265,22 @@ function isLoopbackAlias(hostname: string): boolean { return /^127(?:\.\d{1,3}){3}$/.test(normalized); } +/** + * Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket + * upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch. + */ +export function isDaemonOriginAllowed( + origin: string, + requestHost: string | null, + allowedOrigins: Set, +): boolean { + return ( + allowedOrigins.has("*") || + allowedOrigins.has(origin) || + isWebSocketSameOrigin(origin, requestHost) + ); +} + export function isWebSocketSameOrigin( origin: string | undefined, requestHost: string | null, From 94f2df6263525a0bca56deb3250f341d92f52899 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:00:55 +0000 Subject: [PATCH 137/160] Keep the Import Session list in place when Load more fetches the next page (#9974) Tapping Load more emptied the list until the larger page arrived: the sheet showed "Loading sessions...", unmounted the virtualized list, and brought it back scrolled to the top. The sessions queries set keepPreviousData, but useQueries gives a changed key a new observer with no previous data, so the placeholder was always empty. The placeholder is now the cached page that Load more grew from, for the same scope, search, and provider. The compact import-session journey flaked on this in CI: its scroll helper resolved a row, the list was replaced before the helper ran, and the walk up from the detached row found no scroller. The helper now scrolls the list itself, and the journey checks that Load more keeps the reader down the list. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../app/e2e/support/helpers/import-session.ts | 30 ++++++++------- .../import-session-sheet-view-model.ts | 5 +++ .../components/import-session-sheet.test.tsx | 38 +++++++++++++++++++ .../src/components/import-session-sheet.tsx | 23 ++++++++--- 4 files changed, 78 insertions(+), 18 deletions(-) diff --git a/packages/app/e2e/support/helpers/import-session.ts b/packages/app/e2e/support/helpers/import-session.ts index 9caabc5edd..757ab9e4ff 100644 --- a/packages/app/e2e/support/helpers/import-session.ts +++ b/packages/app/e2e/support/helpers/import-session.ts @@ -97,18 +97,15 @@ export class ImportSessionFlow { await target.scrollIntoViewIfNeeded(); await expect(target).toBeInViewport(); } + /** + * Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way + * in: the list unmounts rows as it scrolls, and a detached row has no scroller above it. + */ private async scrollList(forward: boolean) { - await this.page - .locator('[data-testid^="import-session-session-"]') - .first() - .evaluate((row, advance) => { - let element = row.parentElement; - while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY)) - element = element.parentElement; - if (!element) throw new Error("Import list has no scroll owner"); - element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0; - element.dispatchEvent(new Event("scroll")); - }, forward); + await this.page.getByTestId("import-session-list").evaluate((list, advance) => { + list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0; + list.dispatchEvent(new Event("scroll")); + }, forward); } async search(query: string) { await this.page.getByTestId("import-session-search").fill(query); @@ -120,11 +117,18 @@ export class ImportSessionFlow { await this.page.getByTestId("import-session-search").fill(""); await expect(this.page.getByTestId("import-session-load-more")).toBeVisible(); } + /** Load more keeps the reader down the list instead of sending them back to the top. */ async loadMore() { - await this.page.getByTestId("import-session-load-more").click(); + const loadMore = this.page.getByTestId("import-session-load-more"); + const topRow = this.page.getByTestId((await this.rowIds())[0]!); + await expect(topRow).toBeInViewport(); + await loadMore.click(); + // The next page is the last and short, so the button leaves once it lands. + await expect(loadMore).toHaveCount(0); + await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0); + await expect(topRow).not.toBeInViewport(); await this.revealSession("fixture-root-20"); await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport(); - await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0); } async retryProvider(provider: string, label: string) { await this.expectProviderError(label); diff --git a/packages/app/src/components/import-session-sheet-view-model.ts b/packages/app/src/components/import-session-sheet-view-model.ts index d9f31944c1..188442a449 100644 --- a/packages/app/src/components/import-session-sheet-view-model.ts +++ b/packages/app/src/components/import-session-sheet-view-model.ts @@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number { return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit; } +/** The page Load more grew this limit from, or null for the first page. */ +export function previousPageLimit(limit: number): number | null { + return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null; +} + export function requiresImportSessionsHostUpgrade(input: { supportsSnapshot: boolean; workspaceId?: string | null; diff --git a/packages/app/src/components/import-session-sheet.test.tsx b/packages/app/src/components/import-session-sheet.test.tsx index 167de2a0ed..0024ba7f20 100644 --- a/packages/app/src/components/import-session-sheet.test.tsx +++ b/packages/app/src/components/import-session-sheet.test.tsx @@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => { }); }); + it("keeps the loaded list in place while Load more fetches the next page", async () => { + let releaseNextPage: () => void = () => undefined; + const nextPage = new Promise((resolve) => { + releaseNextPage = resolve; + }); + const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => { + if (options?.limit !== 15) await nextPage; + return { + requestId: "recent-provider-sessions", + entries: createPageOfEntries(options?.limit === 15 ? 15 : 20), + }; + }); + + renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), { + cwd: null, + snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] }, + }); + + fireEvent.click(await screen.findByTestId("import-session-load-more")); + // The list the user scrolled to Load more is the one they keep: replacing it would drop + // them back at the top, behind a loading state, until the larger page lands. + const list = screen.getByTestId("import-session-list"); + await waitFor(() => { + expect(fetchRecentProviderSessions).toHaveBeenCalledWith({ + providers: ["claude"], + limit: 45, + }); + }); + expect(screen.getByTestId("import-session-list")).toBe(list); + expect(screen.queryByText("Loading sessions...")).toBeNull(); + + releaseNextPage(); + await waitFor(() => { + expect(screen.queryByTestId("import-session-load-more")).toBeNull(); + }); + expect(screen.getByTestId("import-session-list")).toBe(list); + }); + it("stops the refresh spinner and retries only the failed provider", async () => { const fetchRecentProviderSessions = vi.fn( async (options: { providers?: string[] } | undefined) => { diff --git a/packages/app/src/components/import-session-sheet.tsx b/packages/app/src/components/import-session-sheet.tsx index f97ae79cc6..5432b445b4 100644 --- a/packages/app/src/components/import-session-sheet.tsx +++ b/packages/app/src/components/import-session-sheet.tsx @@ -1,6 +1,6 @@ import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Pressable, type PressableStateCallbackType, Text, View } from "react-native"; -import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query"; import { useTranslation } from "react-i18next"; import type { DaemonClient, @@ -40,6 +40,7 @@ import { resolveDirectoryLabel, nextPageLimit, PER_PROVIDER_LIMIT, + previousPageLimit, type ProviderErrorRow, resolveImportTarget, resolveProvidersToFetch, @@ -100,11 +101,12 @@ interface SessionsQueryConfig { // Query's default retry would keep the header spinner turning and pile up // in-flight daemon requests behind a dead provider (#2512). retry: false; - placeholderData: typeof keepPreviousData; + placeholderData: () => RecentSessionsResponse | undefined; queryFn: () => Promise; } function buildSessionsQueriesConfig(args: { + queryClient: QueryClient; providersToFetch: AgentProvider[] | null; visible: boolean; client: RecentProviderSessionsClient | null; @@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: { limit: number; hostDisconnectedMessage?: string; }): SessionsQueryConfig[] { - const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args; + const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args; + const { hostDisconnectedMessage } = args; if (providersToFetch === null) return []; const enabled = visible && Boolean(client); + const previousLimit = previousPageLimit(limit); return providersToFetch.map((provider) => ({ queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }), enabled, retry: false as const, - placeholderData: keepPreviousData, + // While Load more fetches the next page, keep showing the page it grew from. React Query's + // keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which + // has no previous data, so the rows would vanish and the list would remount at the top. + placeholderData: () => + previousLimit === null + ? undefined + : queryClient.getQueryData( + buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }), + ), queryFn: async () => { if (!client) { throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected")); @@ -522,6 +534,7 @@ export function ImportSessionSheet({ const queriesConfig = useMemo( () => buildSessionsQueriesConfig({ + queryClient, providersToFetch, visible, client, @@ -530,7 +543,7 @@ export function ImportSessionSheet({ limit: pageLimit, hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"), }), - [providersToFetch, visible, client, scopeCwd, query, pageLimit, t], + [queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t], ); const queries = useQueries({ queries: queriesConfig }); From 7f0fe57c4804ad87098f0bb9e6eb9e6db173c29e Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:08:26 +0000 Subject: [PATCH 138/160] Settle a stuck agent run after a repeated cancel (#9774) A force-cancel finalizes turn X in the daemon while the provider keeps running it, so the next run can be bound to the same X. handleStreamEvent dropped every terminal for a finalized turn id, including the synthetic turn_canceled that cancelAgentRunNow dispatches for the tracked run and the provider's own terminal. The run never settled, cancelAgentRunNow waited on it forever, and every later cancel, reload and send queued behind it until the daemon restarted. A terminal for the tracked run's own turn id is no longer dropped. Fixes #6355 Supersedes #8405 Co-authored-by: Dominic Anaeto --- .../src/server/agent/agent-manager.test.ts | 95 +++++++++++++++++++ .../server/src/server/agent/agent-manager.ts | 3 +- 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 037f958785..5e4c104995 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -3473,6 +3473,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti } }); +test.each([ + { binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" }, + { binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" }, +] as const)( + "cancelAgentRun settles a $binding run bound to an already finalized turn", + async ({ binding, agentId }) => { + const fixture = await createControlledInterruptFixture({ + name: `interrupt-finalized-${binding}`, + agentId, + turnId: "finalized-turn", + interrupt: async () => {}, + }); + + try { + await fixture.startForegroundRun(); + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "settled", + }); + + if (binding === "foreground") { + await fixture.startForegroundRun(); + } else { + const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running"); + fixture.session.pushEvent({ + type: "turn_started", + provider: "codex", + turnId: "finalized-turn", + }); + await running; + } + + const cancellation = await Promise.race([ + fixture.manager.cancelAgentRun(fixture.agentId), + new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)), + ]); + expect(cancellation).toEqual({ status: "settled" }); + expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({ + lifecycle: "idle", + activeForegroundTurnId: null, + }); + + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "not_running", + }); + await fixture.startForegroundRun(); + expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({ + lifecycle: "running", + activeForegroundTurnId: "finalized-turn", + }); + } finally { + await fixture.cleanup(); + } + }, + 10_000, +); + +test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => { + const fixture = await createControlledInterruptFixture({ + name: "interrupt-finalized-provider-terminal", + agentId: "00000000-0000-4000-8000-000000000309", + turnId: "finalized-provider-terminal-turn", + interrupt: async () => {}, + }); + + try { + await fixture.startForegroundRun(); + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "settled", + }); + + await fixture.startForegroundRun(); + const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle"); + fixture.session.pushEvent({ + type: "turn_completed", + provider: "codex", + turnId: "finalized-provider-terminal-turn", + }); + const settlement = await Promise.race([ + idle.then(() => "idle" as const), + new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)), + ]); + + expect(settlement).toBe("idle"); + expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({ + lifecycle: "idle", + activeForegroundTurnId: null, + }); + await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({ + status: "not_running", + }); + } finally { + await fixture.cleanup(); + } +}, 10_000); + test("listProviderAvailability uses registered client keys, including custom providers", async () => { const customClient: AgentClient = { provider: "zai", diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index ef3ec8126d..009710664f 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -5132,7 +5132,8 @@ export class AgentManager { if ( eventTurnId && isTurnTerminalEvent(event) && - this.runs.hasFinalizedTurn(agent, eventTurnId) + this.runs.hasFinalizedTurn(agent, eventTurnId) && + this.runs.getTurnId(agent.id) !== eventTurnId ) { return false; } From 2c2385f362a24a35652ea883b2fb947169176492 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:51:43 +0000 Subject: [PATCH 139/160] Create the workspace in the caller's directory when --path is relative (#10010) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Create the workspace in the caller's directory when --path is relative `paseo workspace create --path .` adopted the daemon's working directory instead of the directory the command ran in. The CLI sent the relative path unchanged, and the daemon resolved it against its own cwd. The CLI now resolves a relative --path against the caller's directory before it sends the request, as it already does when --path is omitted. Absolute POSIX and Windows paths pass through unchanged so a remote daemon on another operating system still gets the path as written. Co-Authored-By: Claude Opus 5.5 * Leave a home-relative --path for the daemon to expand Resolving every non-absolute --path against the caller's directory turned `--path=~/repo` (and a quoted "~/repo") into `/~/repo`. Before this change the daemon expanded the leading ~ itself. `~` and `~/…` now pass through unchanged again. Co-Authored-By: Claude Opus 5.5 * Send a relative --path to an explicit daemon endpoint as written The CLI already resolves caller paths only for a local daemon and sends them unchanged to an explicit --host endpoint (resolveRepositoryDirectory, project create). workspace create, and paseo run, which builds its workspace source through it, now follow the same rule instead of turning a relative path into a path on the caller's machine for a remote daemon. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../cli/src/commands/workspace/create.test.ts | 44 +++++++++++++++++++ packages/cli/src/commands/workspace/create.ts | 22 +++++++++- 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands/workspace/create.test.ts b/packages/cli/src/commands/workspace/create.test.ts index 62bfcdc6f1..a0c03b5e0d 100644 --- a/packages/cli/src/commands/workspace/create.test.ts +++ b/packages/cli/src/commands/workspace/create.test.ts @@ -1,3 +1,4 @@ +import path from "node:path"; import { describe, expect, it } from "vitest"; import { buildWorkspaceSource } from "./create.js"; @@ -8,6 +9,49 @@ describe("workspace create source", () => { ).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" }); }); + it("resolves a relative path against the directory the command runs in", () => { + const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" }; + expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({ + kind: "directory", + path: process.cwd(), + }); + expect( + buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }), + ).toEqual({ + kind: "worktree", + cwd: path.resolve(process.cwd(), "../sibling"), + action: "branch-off", + }); + }); + + it("sends a relative path to an explicit daemon endpoint as written", () => { + const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" }; + expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({ + kind: "directory", + path: "repo", + }); + }); + + it("passes an absolute path from another operating system through unchanged", () => { + expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({ + kind: "directory", + path: "C:\\repos\\project", + }); + }); + + it("leaves a home-relative path for the daemon to expand", () => { + const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" }; + expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({ + kind: "directory", + path: "~/repo", + }); + expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({ + kind: "worktree", + cwd: "~", + action: "branch-off", + }); + }); + it("keeps branch names separate from managed worktree slugs", () => { expect( buildWorkspaceSource({ diff --git a/packages/cli/src/commands/workspace/create.ts b/packages/cli/src/commands/workspace/create.ts index 04d9e10ef0..63417587cb 100644 --- a/packages/cli/src/commands/workspace/create.ts +++ b/packages/cli/src/commands/workspace/create.ts @@ -1,6 +1,10 @@ +import { isAbsolute as isPosixAbsolute } from "node:path/posix"; +import { isAbsolute as isWindowsAbsolute } from "node:path/win32"; +import { resolve } from "node:path"; import type { Command } from "commander"; import { connectToDaemon, getDaemonHost } from "../../utils/client.js"; import { resolveCallerAgentId } from "../../utils/caller-agent.js"; +import type { DaemonTarget } from "../../utils/daemon-target.js"; import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js"; import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js"; @@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str } } +// A relative --path names a directory relative to where the command runs, so +// it is made absolute here for a local daemon, which would otherwise resolve +// it against its own working directory. For an explicit endpoint the path is +// sent as written, the same rule as resolveRepositoryDirectory. An absolute +// path can target a daemon on a different operating system, and the daemon +// expands a leading ~ to its own home directory. +function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string { + const isHomeRelative = input === "~" || input.startsWith("~/"); + if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input; + return daemonTarget.kind === "instance" ? resolve(input) : input; +} + export function buildWorkspaceSource(options: WorkspaceCreateOptions) { + const callerPath = + options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget); if (options.isolation === "local") { - return buildLocalWorkspaceSource(options, options.path ?? process.cwd()); + return buildLocalWorkspaceSource(options, callerPath ?? process.cwd()); } if (options.isolation === "worktree") { - const sourcePath = options.path ?? (options.project ? undefined : process.cwd()); + const sourcePath = callerPath ?? (options.project ? undefined : process.cwd()); return buildWorktreeWorkspaceSource(options, sourcePath); } throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`); From 95f2c7d16aa6499012f5f07bc28780e04fbc176f Mon Sep 17 00:00:00 2001 From: Gilad Rubin Date: Tue, 17 Nov 2026 18:57:22 +0200 Subject: [PATCH 140/160] Keep a Claude agent's process and background work when its effort level changes (#10008) Changing the thinking level of a running Claude agent marked its query for a restart. The next turn, mode change or model change then retired the Claude process, which ended every background shell, workflow and subagent it ran with "connection lost". A move between two effort levels now goes to the running query through applyFlagSettings({ effortLevel }), as Fast mode already does, and marks no restart. Switching thinking off, to ultracode or back to the default still restarts, because those change how the query is launched. If the running process does not take the change, the old restart path runs, so the change is never lost. Row: app-built-from-one-set Paseo: c6210e21-fc13-4dfa-adfc-43a050c7d75a Co-authored-by: gilad-rubin <6134299+gilad-rubin@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../claude/agent.live-settings.test.ts | 5 +- .../claude/agent.runtime-exit.test.ts | 79 +++++++++++++++++++ .../server/agent/providers/claude/agent.ts | 26 +++++- 3 files changed, 107 insertions(+), 3 deletions(-) diff --git a/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts b/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts index cb272ebecb..5f90adba8b 100644 --- a/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.live-settings.test.ts @@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)( try { await session.startTurn("Run the foreground command"); await running.promise; - expect(await session.setThinkingOption?.("medium")).toMatchObject({ + // Ultracode is launched with the query, so the change waits for a restart. + expect(await session.setThinkingOption?.("ultracode")).toMatchObject({ message: "Thinking level applies next turn", }); if (control === "mode") await session.setMode("acceptEdits"); @@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)( await session.startTurn("Run another command with the new thinking level"); queries[1].work.resolve(); expect(await terminal.promise).toBe("turn_completed"); - expect(efforts).toEqual(["low", "medium"]); + expect(efforts).toEqual(["low", "xhigh"]); } finally { await session.close(); } diff --git a/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts b/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts index d70d068717..b700ff81ac 100644 --- a/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.runtime-exit.test.ts @@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que close: vi.fn(() => undefined), setPermissionMode: vi.fn(async () => undefined), setModel: vi.fn(async () => undefined), + applyFlagSettings: vi.fn(async () => undefined), supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]), supportedCommands: vi.fn(async () => []), rewindFiles: vi.fn(async () => ({ canRewind: true })), @@ -382,6 +383,84 @@ describe("Claude runtime exit", () => { } }); + test("keeps the process and its background work when the effort level changes", async () => { + let capturedOptions: Options | undefined; + const child = createChildProcessStub(); + const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, { + tail: new Promise(() => undefined), + onReturn: () => child.emit("exit", 0, null), + }); + const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => { + capturedOptions = options; + return query; + }); + vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + thinkingOptionId: "low", + }); + + try { + await session.run("start a background shell"); + capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS); + const events: AgentStreamEvent[] = []; + session.subscribe((event) => events.push(event)); + + await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined(); + // A pending restart would be carried out here. + await session.listCommands(); + + expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" }); + expect(queryFactory).toHaveBeenCalledTimes(1); + expect(query.return).not.toHaveBeenCalled(); + expect(child.killSignals).toEqual([]); + expect(events).not.toContainEqual( + expect.objectContaining({ type: "background_work", provider: "claude", items: null }), + ); + } finally { + await session.close(); + } + }); + + test("restarts with the new effort level when the running process does not take it", async () => { + const efforts: Options["effort"][] = []; + const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => { + efforts.push(options.effort); + const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, { + tail: new Promise(() => undefined), + }); + vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported")); + return query; + }); + vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub()); + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ + provider: "claude", + cwd: process.cwd(), + thinkingOptionId: "low", + }); + + try { + await session.run("start a background shell"); + await session.setThinkingOption?.("high"); + await session.listCommands(); + + expect(efforts).toEqual(["low", "high"]); + } finally { + await session.close(); + } + }); + test("ignores background work a retired query reports after its restart", async () => { let capturedOptions: Options | undefined; let deliverLateEvent: ((event: unknown) => void) | undefined; diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 7bd696e7aa..1087e6dfe2 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -2859,6 +2859,7 @@ class ClaudeAgentSession implements AgentSession { ? thinkingOptionId : null; + const previousThinkingOptionId = this.config.thinkingOptionId; if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") { this.config.thinkingOptionId = undefined; } else if (isClaudeThinkingOption(normalizedThinkingOptionId)) { @@ -2867,12 +2868,35 @@ class ClaudeAgentSession implements AgentSession { } else { throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`); } - this.queryRestartNeeded = true; + if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) { + this.queryRestartNeeded = true; + } if (this.activeForegroundTurnId || this.autonomousTurn) { return THINKING_APPLIES_NEXT_TURN_NOTICE; } } + // A move between two effort levels changes only the effort, which a running Claude process + // takes through flag settings, so the process and its background work stay. Switching thinking + // off, to ultracode or back to the default changes how the query is launched, so it still + // restarts the query. The recorded option feeds every later launch either way. + private async applyEffortToRunningQuery( + previousThinkingOptionId: string | undefined, + ): Promise { + const effort = this.config.thinkingOptionId; + if (!this.query || this.queryRestartNeeded) return false; + if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) { + return false; + } + try { + await this.query.applyFlagSettings({ effortLevel: effort }); + return true; + } catch (error) { + this.logger.warn({ err: error, effort }, "Claude did not take a live effort change"); + return false; + } + } + async applyOptions(options: ProviderOptions): Promise { // Every option but Fast is read when the query is built, and replacing a started query would // end its background work, so once it exists only Fast can change. From c8e3d67e29ab39300f325b3a230790a716729658 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:01:24 +0000 Subject: [PATCH 141/160] Wait for each plugin content subscription id before checking its release (#10012) The plugin-buttons journey reads the details' event subscription id to check that closing, crashing and disabling the content releases it. The id arrives with the daemon's subscription response, after the details render. The first open already waited for it; the reopens read it as soon as the cached summary showed, so the id could still be empty and the release poll then waited for an id that never exists. Every read now waits for a non-empty id. Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../app/e2e/support/helpers/plugin-buttons.ts | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/app/e2e/support/helpers/plugin-buttons.ts b/packages/app/e2e/support/helpers/plugin-buttons.ts index b28050fd00..dae18fd1d4 100644 --- a/packages/app/e2e/support/helpers/plugin-buttons.ts +++ b/packages/app/e2e/support/helpers/plugin-buttons.ts @@ -198,6 +198,14 @@ async function expectDetails(page: Page) { await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport(); } +// The details render before the daemon answers their event subscription, and reopened +// details show the cached summary at once, so wait for the subscription id to arrive. +async function readContentObservation(page: Page): Promise { + const observation = page.getByLabel("Content observation", { exact: true }); + await expect(observation).not.toHaveText(""); + return (await observation.textContent())!; +} + function workspaceMenuRow(page: Page, title: string): Locator { return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true }); } @@ -354,14 +362,12 @@ export async function withButtonShowcase( test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => { await press(page, "Header status"); await expectDetails(page); - const observation = page.getByLabel("Content observation", { exact: true }); - await expect(observation).not.toHaveText(""); - const first = (await observation.textContent())!; + const first = await readContentObservation(page); await press(page, "Close deployment details"); await expect.poll(() => released.has(first)).toBe(true); await press(page, "Composer status"); await expectDetails(page); - const second = (await observation.textContent())!; + const second = await readContentObservation(page); expect(second).not.toBe(first); await workspace.client.renameProject(workspace.projectId, "Observer control"); await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible(); @@ -373,7 +379,7 @@ export async function withButtonShowcase( await page.keyboard.press("Escape"); await press(page, "Header status"); await expectDetails(page); - const recovered = (await observation.textContent())!; + const recovered = await readContentObservation(page); expect([first, second]).not.toContain(recovered); await showcase.setTitle("Healthy app after button failure"); await expect(page.getByTestId("workspace-header-title")).toHaveText( @@ -687,9 +693,7 @@ export async function withButtonShowcase( page, page.getByRole("button", { name: "Close deployment details", exact: true }), ); - const observation = page.getByLabel("Content observation", { exact: true }); - await expect(observation).not.toHaveText(""); - const owner = (await observation.textContent())!; + const owner = await readContentObservation(page); await showcase.disable(); await expect.poll(() => released.has(owner)).toBe(true); await expect( From 576d0320c88ff9f031d2e06d3bcf61257150e713 Mon Sep 17 00:00:00 2001 From: JIHUN LEE <255830512+easyhunjune@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:08:05 +0900 Subject: [PATCH 142/160] Keep Android text at the window's density on Samsung DeX (#9995) React Native 0.86 converts between px and dp with the density of the phone's built-in display, while Fabric lays out at the window's density. In a DeX window (240 dpi on a 360 dpi phone) every text box came out at two thirds of the height its text needed, so the text was clipped. Backport the rule from react/react-native#59087: right after React Native reads the display (when it creates the root view and on each configuration change), restore the window's density and keep only the display's size. Remove once the app runs React Native 0.89 or later with useWindowDensityForDisplayMetricsAndroid on. Co-authored-by: Claude Opus 5.5 --- docs/android.md | 8 ++ packages/app/app.config.js | 2 + .../modules/paseo-display-metrics/.gitignore | 2 + .../android/build.gradle | 23 +++++ .../displaymetrics/PaseoDisplayMetricsTest.kt | 86 +++++++++++++++++++ .../displaymetrics/PaseoDisplayMetrics.kt | 43 ++++++++++ .../paseo-display-metrics/app.plugin.js | 35 ++++++++ .../paseo-display-metrics/app.plugin.test.ts | 29 +++++++ .../expo-module.config.json | 6 ++ .../paseo-display-metrics/package.json | 5 ++ 10 files changed, 239 insertions(+) create mode 100644 packages/app/modules/paseo-display-metrics/.gitignore create mode 100644 packages/app/modules/paseo-display-metrics/android/build.gradle create mode 100644 packages/app/modules/paseo-display-metrics/android/src/androidTest/java/sh/paseo/displaymetrics/PaseoDisplayMetricsTest.kt create mode 100644 packages/app/modules/paseo-display-metrics/android/src/main/java/sh/paseo/displaymetrics/PaseoDisplayMetrics.kt create mode 100644 packages/app/modules/paseo-display-metrics/app.plugin.js create mode 100644 packages/app/modules/paseo-display-metrics/app.plugin.test.ts create mode 100644 packages/app/modules/paseo-display-metrics/expo-module.config.json create mode 100644 packages/app/modules/paseo-display-metrics/package.json diff --git a/docs/android.md b/docs/android.md index 229c2bf02d..f4fcfa27c0 100644 --- a/docs/android.md +++ b/docs/android.md @@ -121,6 +121,14 @@ from `packages/app/android`: These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing. +Run the display density regression tests the same way: + +```bash +./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false +``` + +These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX. + ### Diagnostic logs without ADB In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all diff --git a/packages/app/app.config.js b/packages/app/app.config.js index fecdcce31a..713f34371c 100644 --- a/packages/app/app.config.js +++ b/packages/app/app.config.js @@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable"); const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking"); const withPasteInput = require("./plugins/with-paste-input"); const withAndroidScroll = require("./modules/paseo-scroll/app.plugin"); +const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin"); const { getNativeReleaseVersion } = require("./native-release-version"); const appVariant = process.env.APP_VARIANT ?? "production"; const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1"; @@ -146,6 +147,7 @@ export default { "expo-router", withPasteInput, withAndroidScroll, + withAndroidDisplayMetrics, [withAndroidAsyncStorageSize, 64], ...buildProfile.cameraPlugins, withAndroidOptionalCamera, diff --git a/packages/app/modules/paseo-display-metrics/.gitignore b/packages/app/modules/paseo-display-metrics/.gitignore new file mode 100644 index 0000000000..d80969eb27 --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/.gitignore @@ -0,0 +1,2 @@ +/android/.cxx/ +/android/build/ diff --git a/packages/app/modules/paseo-display-metrics/android/build.gradle b/packages/app/modules/paseo-display-metrics/android/build.gradle new file mode 100644 index 0000000000..af750ac388 --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/android/build.gradle @@ -0,0 +1,23 @@ +apply plugin: 'com.android.library' + +group = 'sh.paseo.displaymetrics' +version = '0.1.0' + +def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle") +apply from: expoModulesCorePlugin +applyKotlinExpoModulesCorePlugin() +useCoreDependencies() +useDefaultAndroidSdkVersions() + +android { + namespace "sh.paseo.displaymetrics" + defaultConfig { + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } +} + +dependencies { + implementation "com.facebook.react:react-android" + androidTestImplementation 'androidx.test:runner:1.6.2' + androidTestImplementation 'androidx.test.ext:junit:1.2.1' +} diff --git a/packages/app/modules/paseo-display-metrics/android/src/androidTest/java/sh/paseo/displaymetrics/PaseoDisplayMetricsTest.kt b/packages/app/modules/paseo-display-metrics/android/src/androidTest/java/sh/paseo/displaymetrics/PaseoDisplayMetricsTest.kt new file mode 100644 index 0000000000..8c40b80f24 --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/android/src/androidTest/java/sh/paseo/displaymetrics/PaseoDisplayMetricsTest.kt @@ -0,0 +1,86 @@ +package sh.paseo.displaymetrics + +import android.util.DisplayMetrics +import android.util.TypedValue +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.facebook.react.uimanager.PixelUtil +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class PaseoDisplayMetricsTest { + private lateinit var display: DisplayMetrics + + @Before + fun readDisplayLikeReactNative() { + DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext) + display = DisplayMetricsHolder.getScreenDisplayMetrics() + } + + @After + fun forgetDisplay() { + DisplayMetricsHolder.setScreenDisplayMetrics(null) + } + + @Test + fun reservesRoomForTextAtTheWindowDensity() { + // A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native + // reads the font scale from the window but the density from the phone's display. + val window = windowAt(display.densityDpi * 2 / 3) + DisplayMetricsHolder.setScreenDisplayMetrics( + DisplayMetrics().apply { + setTo(display) + scaledDensity = window.scaledDensity + }, + ) + assertTrue(reservedTextPx(window) < drawnTextPx()) + + PaseoDisplayMetrics.syncWithWindow(window) + + assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f) + assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f) + val synced = DisplayMetricsHolder.getScreenDisplayMetrics() + assertEquals(window.densityDpi, synced.densityDpi) + assertEquals(display.widthPixels, synced.widthPixels) + assertEquals(display.heightPixels, synced.heightPixels) + } + + @Test + fun leavesTheBuiltInDisplayAlone() { + PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi)) + + assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics()) + } + + @Test + fun waitsForReactNativeToReadTheDisplay() { + DisplayMetricsHolder.setScreenDisplayMetrics(null) + + PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2)) + + assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() } + } + + private fun windowAt(densityDpi: Int): DisplayMetrics = + DisplayMetrics().apply { + setTo(display) + this.densityDpi = densityDpi + density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT + scaledDensity = density * display.scaledDensity / display.density + } + + /** A 16sp font as React Native draws it, in pixels. */ + private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f) + + /** The box React Native lays out for that font, once the window renders it in pixels. */ + private fun reservedTextPx(window: DisplayMetrics): Float = + PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density +} diff --git a/packages/app/modules/paseo-display-metrics/android/src/main/java/sh/paseo/displaymetrics/PaseoDisplayMetrics.kt b/packages/app/modules/paseo-display-metrics/android/src/main/java/sh/paseo/displaymetrics/PaseoDisplayMetrics.kt new file mode 100644 index 0000000000..4192ebb464 --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/android/src/main/java/sh/paseo/displaymetrics/PaseoDisplayMetrics.kt @@ -0,0 +1,43 @@ +package sh.paseo.displaymetrics + +import android.app.Activity +import android.util.DisplayMetrics +import com.facebook.react.uimanager.DisplayMetricsHolder + +/** + * React Native 0.86 converts between px and dp, and so sizes text, with the density of the + * device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`. + * Fabric lays out at the window's density. On a display with another density, such as a Samsung + * DeX monitor, text boxes come out too small and clip their text. + * + * Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the + * window's density and take only the size from the display. Remove once the app runs React Native + * 0.89 or later with that flag on. + */ +object PaseoDisplayMetrics { + /** Call right after React Native reads the display, which it does again on each configuration change. */ + @JvmStatic + fun syncWithWindow(activity: Activity) { + syncWithWindow(activity.resources.displayMetrics) + } + + @JvmStatic + fun syncWithWindow(window: DisplayMetrics) { + val screen = + try { + DisplayMetricsHolder.getScreenDisplayMetrics() + } catch (_: IllegalStateException) { + // React Native hasn't read the display yet, so there is nothing to correct. + return + } + if (screen.densityDpi == window.densityDpi) return + + DisplayMetricsHolder.setScreenDisplayMetrics( + DisplayMetrics().apply { + setTo(screen) + density = window.density + densityDpi = window.densityDpi + }, + ) + } +} diff --git a/packages/app/modules/paseo-display-metrics/app.plugin.js b/packages/app/modules/paseo-display-metrics/app.plugin.js new file mode 100644 index 0000000000..9b5787c60f --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/app.plugin.js @@ -0,0 +1,35 @@ +const { withMainActivity } = require("expo/config-plugins"); + +const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {"; +const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)"; +// React Native re-reads the built-in display's density when it creates the root view and on every +// configuration change, so the window's density has to be restored right after each `super` call. +const OVERRIDES = ` + override fun onContentChanged() { + super.onContentChanged() + ${SYNC} + } + + override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { + super.onConfigurationChanged(newConfig) + ${SYNC} + } +`; + +function configureDisplayMetricsActivity(contents) { + if (contents.includes(SYNC)) return contents; + if ( + !contents.includes(ACTIVITY_CLASS) || + /override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents) + ) { + throw new Error("Could not keep React Native text at the window's density in MainActivity"); + } + return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`); +} + +module.exports = (config) => + withMainActivity(config, (mod) => { + mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents); + return mod; + }); +module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity; diff --git a/packages/app/modules/paseo-display-metrics/app.plugin.test.ts b/packages/app/modules/paseo-display-metrics/app.plugin.test.ts new file mode 100644 index 0000000000..331d2231c8 --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/app.plugin.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; + +const { configureDisplayMetricsActivity } = require("./app.plugin"); + +const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)"; + +describe("Android display metrics", () => { + it("restores the window's density after React Native reads the display", () => { + const source = "class MainActivity : ReactActivity() {\n}"; + const result = configureDisplayMetricsActivity(source); + expect(result).toContain(`super.onContentChanged()\n ${SYNC}`); + expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`); + expect(configureDisplayMetricsActivity(result)).toBe(result); + }); + + it("fails prebuild when the template no longer has a place for the overrides", () => { + expect(() => configureDisplayMetricsActivity("changed template")).toThrow( + "Could not keep React Native text at the window's density", + ); + }); + + it("fails prebuild rather than replace another plugin's configuration handler", () => { + const source = + "class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}"; + expect(() => configureDisplayMetricsActivity(source)).toThrow( + "Could not keep React Native text at the window's density", + ); + }); +}); diff --git a/packages/app/modules/paseo-display-metrics/expo-module.config.json b/packages/app/modules/paseo-display-metrics/expo-module.config.json new file mode 100644 index 0000000000..c66785f09a --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/expo-module.config.json @@ -0,0 +1,6 @@ +{ + "platforms": ["android"], + "android": { + "modules": [] + } +} diff --git a/packages/app/modules/paseo-display-metrics/package.json b/packages/app/modules/paseo-display-metrics/package.json new file mode 100644 index 0000000000..3b231d62a1 --- /dev/null +++ b/packages/app/modules/paseo-display-metrics/package.json @@ -0,0 +1,5 @@ +{ + "name": "paseo-display-metrics", + "version": "0.1.0", + "private": true +} From a1088a787d05a9e0fc944fdbeae0770f0941b507 Mon Sep 17 00:00:00 2001 From: Orcun Simsek Date: Wed, 18 Nov 2026 01:54:59 +0300 Subject: [PATCH 143/160] Report background work from get_agent_status and list_agents (#10022) The MCP agent tools serialized live agents without the background work summary that the WebSocket snapshot carries, so a parent agent saw an idle worker with a running background shell as plain idle. Both tools now add the same summary the session adds, omitted when the agent has none. Co-authored-by: Orcun Simsek <1612171+ortschun@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/server/agent/mcp-server.test.ts | 31 +++++++++++++++++++ .../src/server/agent/tools/paseo-tools.ts | 18 ++++++----- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index ad663bac0e..1979192ba9 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -266,6 +266,7 @@ function buildAgentManagerSpies() { archiveAgent: vi.fn().mockResolvedValue({ archivedAt: new Date().toISOString() }), notifyAgentState: vi.fn(), getAgent: vi.fn(), + getAgentBackgroundWorkSummary: vi.fn().mockReturnValue(undefined), listAgents: vi.fn().mockReturnValue([]), getTimeline: vi.fn().mockReturnValue([]), resumeAgentFromPersistence: vi.fn(), @@ -6196,6 +6197,36 @@ describe("agent snapshot MCP serialization", () => { expect(structured.agents[0]).not.toHaveProperty("pendingPermissions"); }); + it("reports an idle agent's background work from get_agent_status and list_agents", async () => { + const { agentManager, agentStorage, spies } = createTestDeps(); + const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD }); + spies.agentManager.getAgent.mockReturnValue(agent); + spies.agentManager.listAgents.mockReturnValue([agent]); + spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 }); + + const server = await createAgentMcpServer({ + agentManager, + agentStorage, + providerSnapshotManager: createOpenCodeManager().manager, + logger, + }); + const status = await registeredTool(server, "get_agent_status").handler({ + agentId: "agent-with-shell", + }); + const list = await registeredTool(server, "list_agents").handler({}); + + expect(status.structuredContent).toEqual({ + status: "idle", + snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }), + }); + expect(list.structuredContent).toEqual({ + agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })], + }); + expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith( + "agent-with-shell", + ); + }); + it("returns archived agent snapshots from storage for get_agent_status", async () => { const { agentManager, agentStorage, spies } = createTestDeps(); const record = createStoredRecord({ diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index c830717236..9fbb4c057b 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -15,7 +15,7 @@ import { ensureValidJson } from "../../json-utils.js"; import type { Logger } from "pino"; import type { AgentMode, AgentProvider, AgentSessionConfig } from "../agent-sdk-types.js"; -import type { AgentManager } from "../agent-manager.js"; +import type { AgentManager, ManagedAgent } from "../agent-manager.js"; import { ActiveTurnBehaviorSchema, AgentProfileSchema } from "@getpaseo/protocol/messages"; import type { DaemonConfigStore } from "../../daemon-config-store.js"; import { featuresFromControls } from "@getpaseo/protocol/option-controls"; @@ -2099,6 +2099,13 @@ function createToolCatalog( }, ); + // Match the WebSocket snapshot: idle agents can still own background work. + async function projectLiveAgent(agent: ManagedAgent) { + const snapshot = await serializeSnapshotWithMetadata(agentStorage, agent, childLogger); + const backgroundWork = agentManager.getAgentBackgroundWorkSummary(agent.id); + return backgroundWork ? { ...snapshot, backgroundWork } : snapshot; + } + registerTool( "get_agent_status", { @@ -2116,11 +2123,7 @@ function createToolCatalog( async ({ agentId }) => { const snapshot = agentManager.getAgent(agentId); if (snapshot) { - const structuredSnapshot = await serializeSnapshotWithMetadata( - agentStorage, - snapshot, - childLogger, - ); + const structuredSnapshot = await projectLiveAgent(snapshot); return { content: [], structuredContent: ensureValidJson({ @@ -2188,8 +2191,7 @@ function createToolCatalog( manager: agentManager, storage: agentStorage, workspaces: options.workspaceRegistry, - projectLive: (snapshot) => - serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger), + projectLive: projectLiveAgent, projectStored: (record) => buildStoredAgentPayload( record, From 1821ac3f9325674897dcebd5172665c8f1489bb8 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:06:23 +0000 Subject: [PATCH 144/160] Let a steered message wait out a Claude compaction instead of cancelling it (#10028) * Let a steer wait out a Claude compaction instead of cancelling it While Claude compacted, the Claude session answered every steer with "unavailable". The agent manager reads that as "replace the turn", so it interrupted the turn and Claude Code printed "Compaction canceled.". Claude Code already holds a `next`-priority message until compaction finishes, so the session now accepts the steer during compaction. Co-authored-by: NightMachinery <36224762+NightMachinery@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * Steer only while the compaction is still running in the real Claude test Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: NightMachinery <36224762+NightMachinery@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../agent/providers/claude/agent.test.ts | 54 ++++++++ .../server/agent/providers/claude/agent.ts | 5 +- ...e-steer-during-compaction.real.e2e.test.ts | 122 ++++++++++++++++++ 3 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts diff --git a/packages/server/src/server/agent/providers/claude/agent.test.ts b/packages/server/src/server/agent/providers/claude/agent.test.ts index ff76e5186d..fbb7907b2a 100644 --- a/packages/server/src/server/agent/providers/claude/agent.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.test.ts @@ -1544,6 +1544,60 @@ describe("ClaudeAgentSession features", () => { } }); + test("accepts a steer while Claude compacts, so the compaction is not interrupted", async () => { + const { queryFactory, push } = createStreamingQueryMock(); + const client = new ClaudeAgentClient({ + logger, + queryFactory, + resolveBinary: async () => "/test/claude/bin", + }); + const session = await client.createSession({ provider: "claude", cwd: process.cwd() }); + const events: AgentStreamEvent[] = []; + const unsubscribe = session.subscribe((event) => events.push(event)); + try { + const { turnId } = await session.startTurn("/compact"); + const input = queryFactory.mock.calls[0]?.[0].prompt as AsyncIterable; + const iterator = input[Symbol.asyncIterator](); + await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } }); + await vi.waitFor(() => + expect(events).toContainEqual( + expect.objectContaining({ + type: "timeline", + item: expect.objectContaining({ type: "user_message" }), + }), + ), + ); + push({ + type: "system", + subtype: "status", + status: "compacting", + session_id: "session-1", + } as unknown as SDKMessage); + await vi.waitFor(() => + expect(events).toContainEqual( + expect.objectContaining({ + type: "timeline", + item: { type: "compaction", status: "loading" }, + }), + ), + ); + + const admission = await session.steerActiveTurn?.("message during compaction", { + expectedTurnId: turnId, + }); + + // Claude Code holds a `next` message until the compaction finishes. Refusing it makes the + // manager replace the turn, and the interrupt cancels the compaction. + expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) }); + await expect(iterator.next()).resolves.toMatchObject({ + value: { type: "user", priority: "next" }, + }); + } finally { + unsubscribe(); + await session.close(); + } + }); + test("a human steer supersedes blocking permissions until Claude reads it", async () => { const { queryFactory } = createQueryMock(); const client = new ClaudeAgentClient({ diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index 1087e6dfe2..ba559dedf7 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -2637,7 +2637,10 @@ class ClaudeAgentSession implements AgentSession { return { status: "unavailable" }; } const activeTurnId = this.activeForegroundTurnId ?? this.autonomousTurn?.id; - if (this.compacting || activeTurnId !== options.expectedTurnId) { + // A compacting turn still takes a steer: Claude Code holds a `next` message until the + // compaction finishes. Refusing it makes the manager replace the turn, and that interrupt + // cancels the compaction. + if (activeTurnId !== options.expectedTurnId) { return { status: "unavailable" }; } diff --git a/packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts b/packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts new file mode 100644 index 0000000000..85fc3547bf --- /dev/null +++ b/packages/server/src/server/daemon-e2e/claude-steer-during-compaction.real.e2e.test.ts @@ -0,0 +1,122 @@ +import { beforeAll, beforeEach, describe, expect, test } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import pino from "pino"; + +import { ClaudeAgentClient } from "../agent/providers/claude/agent.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { canRunRealProvider, getRealProviderConfig } from "./real-provider-test-config.js"; + +function tmpCwd(): string { + return mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-compaction-")); +} + +type TimelineItem = Awaited< + ReturnType +>["entries"][number]["item"]; + +// The steer must land while the compaction is still running, or it takes the idle path. +function isCompacting(items: TimelineItem[]): boolean { + const statuses = new Set( + items.flatMap((item) => (item.type === "compaction" ? [item.status] : [])), + ); + return statuses.has("loading") && !statuses.has("completed"); +} + +function hasAssistantText(items: TimelineItem[], text: string): boolean { + return items.some((item) => item.type === "assistant_message" && item.text.includes(text)); +} + +async function timelineItems(client: DaemonClient, agentId: string): Promise { + const timeline = await client.fetchAgentTimeline(agentId, { + direction: "tail", + limit: 200, + }); + return timeline.entries.map((entry) => entry.item); +} + +async function waitForTimeline( + client: DaemonClient, + agentId: string, + check: (items: TimelineItem[]) => boolean, + timeoutMs: number, + label: string, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const items = await timelineItems(client, agentId); + if (check(items)) return items; + if (Date.now() > deadline) { + throw new Error(`Timed out: ${label}: ${JSON.stringify(items.slice(-6)).slice(0, 2000)}`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +describe("daemon E2E (real claude) - steer during compaction", () => { + let canRun = false; + + beforeAll(async () => { + canRun = await canRunRealProvider("claude"); + }); + + beforeEach((context) => { + if (!canRun) context.skip(); + }); + + test("a steered message waits for a running /compact instead of cancelling it", async () => { + const logger = pino({ level: "silent" }); + const cwd = tmpCwd(); + const daemon = await createTestPaseoDaemon({ + agentClients: { claude: new ClaudeAgentClient({ logger }) }, + logger, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + }); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const agent = await client.createAgent({ + cwd, + title: "claude-steer-during-compaction", + ...getRealProviderConfig("claude"), + }); + await client.sendAgentMessage( + agent.id, + `Remember this list for later and reply exactly: NOTED. ${Array.from( + { length: 400 }, + (_, index) => `item-${index}`, + ).join(" ")}`, + ); + const firstFinish = await client.waitForFinish(agent.id, 120_000); + expect(firstFinish.status, firstFinish.error).toBe("idle"); + + await client.sendAgentMessage(agent.id, "/compact"); + await waitForTimeline(client, agent.id, isCompacting, 60_000, "Claude reports compacting"); + + await client.sendAgentMessage(agent.id, "Reply exactly: AFTER_COMPACT", { + activeTurnBehavior: "steer", + }); + await waitForTimeline( + client, + agent.id, + (items) => hasAssistantText(items, "AFTER_COMPACT"), + 180_000, + "Claude answers the steered message", + ); + await client.waitForFinish(agent.id, 120_000); + const finalItems = await timelineItems(client, agent.id); + expect( + finalItems.filter((item) => item.type === "compaction").map((item) => item.status), + ).toContain("completed"); + expect(hasAssistantText(finalItems, "Compaction canceled")).toBe(false); + } finally { + await client.close().catch(() => undefined); + await daemon.close().catch(() => undefined); + rmSync(cwd, { recursive: true, force: true }); + } + }, 420_000); +}); From b24eab785bee2df459a4f65ddb2165534ff5c054 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:04:06 +0000 Subject: [PATCH 145/160] Reload the desktop window when its renderer exits (#10035) * Reload the desktop window when its renderer exits When the renderer process of the main window exits without a clean shutdown (killed by an out-of-memory killer, crashed, or out of memory), Electron keeps the window frame but shows nothing until the user presses Ctrl+R. The main process had no handler for render-process-gone, so it neither recovered nor logged the exit. The window now reloads itself and logs the exit reason to main.log. If the renderer exits three times within a minute, it stops reloading and logs that, so a page that crashes on load does not restart in a loop. Fixes #9999 Co-Authored-By: Claude Opus 5.5 * Leave a renderer exit before the first page commits to Chromium Before the window's first navigation commits, Chromium finishes it in a new renderer by itself. Reloading at that point aborted the initial loadURL with ERR_ABORTED, which fails desktop startup. Skip the reload while the window has no committed URL. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/desktop/e2e/window-startup.e2e.mjs | 36 +++++++- packages/desktop/src/main.ts | 2 + .../src/window/renderer-recovery.test.ts | 86 +++++++++++++++++++ .../desktop/src/window/renderer-recovery.ts | 56 ++++++++++++ 4 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 packages/desktop/src/window/renderer-recovery.test.ts create mode 100644 packages/desktop/src/window/renderer-recovery.ts diff --git a/packages/desktop/e2e/window-startup.e2e.mjs b/packages/desktop/e2e/window-startup.e2e.mjs index e6654c09c2..974cc0f30c 100644 --- a/packages/desktop/e2e/window-startup.e2e.mjs +++ b/packages/desktop/e2e/window-startup.e2e.mjs @@ -5,18 +5,25 @@ import { fileURLToPath } from "node:url"; import { _electron as electron, expect } from "playwright/test"; const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-")); -const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url)); +const showWhenReadyPath = fileURLToPath( + new URL("../dist/window/show-when-ready.js", import.meta.url), +); +const rendererRecoveryPath = fileURLToPath( + new URL("../dist/window/renderer-recovery.js", import.meta.url), +); -async function launchWindowWithoutHiddenFrames() { +async function launchDesktopWindow() { const main = path.join(root, "main.cjs"); await writeFile( main, `const { app, BrowserWindow } = require("electron"); - const { showWindowWhenReady } = require(${JSON.stringify(modulePath)}); + const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)}); + const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)}); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(async () => { const win = global.mainWindow = new BrowserWindow({ show: false, paintWhenInitiallyHidden: false }); showWindowWhenReady(win, { showOnLoad: true }); + reloadWhenRendererExits(win); await win.loadURL("data:text/html,

Desktop ready

"); global.visibleAfterLoad = win.isVisible(); });`, @@ -37,11 +44,32 @@ async function expectLoadedDesktopIsShown(desktop) { await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); } +function rendererPid(desktop) { + return desktop.evaluate(() => global.mainWindow.webContents.getOSProcessId()); +} + +async function expectDesktopReloadsAfterRendererIsTerminated(desktop) { + const terminated = await rendererPid(desktop); + process.kill(terminated, "SIGTERM"); + await expect.poll(() => rendererPid(desktop), { timeout: 15_000 }).not.toBe(terminated); + await expect + .poll( + () => + desktop.evaluate(() => + global.mainWindow.webContents.executeJavaScript("document.body.textContent"), + ), + { timeout: 15_000 }, + ) + .toBe("Desktop ready"); +} + let desktop; try { - desktop = await launchWindowWithoutHiddenFrames(); + desktop = await launchDesktopWindow(); await expectLoadedDesktopIsShown(desktop); console.log("Loaded desktop is visible without hidden compositor frames"); + await expectDesktopReloadsAfterRendererIsTerminated(desktop); + console.log("Desktop reloads its window after the renderer is terminated"); } finally { await desktop?.close(); await rm(root, { recursive: true, force: true }); diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts index 072f96a26d..196f9a47f4 100644 --- a/packages/desktop/src/main.ts +++ b/packages/desktop/src/main.ts @@ -46,6 +46,7 @@ import { buildStandardContextMenuItems, } from "./window/window-manager.js"; import { setupDarwinCompositorWatchdog } from "./window/compositor-watchdog/index.js"; +import { reloadWhenRendererExits } from "./window/renderer-recovery.js"; import { showWindowWhenReady } from "./window/show-when-ready.js"; import { resolveDesktopWindowChromeMode, windowChromeModeArgument } from "./window/chrome.js"; import { registerDialogHandlers } from "./features/dialogs.js"; @@ -734,6 +735,7 @@ async function createWindow( } setupDarwinCompositorWatchdog(mainWindow); + reloadWhenRendererExits(mainWindow); setupWindowResizeEvents(mainWindow); if (windowStateStore) { setupWindowStatePersistence(mainWindow, windowStateStore); diff --git a/packages/desktop/src/window/renderer-recovery.test.ts b/packages/desktop/src/window/renderer-recovery.test.ts new file mode 100644 index 0000000000..2d1ba58e4c --- /dev/null +++ b/packages/desktop/src/window/renderer-recovery.test.ts @@ -0,0 +1,86 @@ +import { EventEmitter } from "node:events"; +import { describe, expect, it } from "vitest"; +import { reloadWhenRendererExits } from "./renderer-recovery.js"; + +class Contents extends EventEmitter { + reloads = 0; + url = "paseo://app/"; + getURL() { + return this.url; + } + reload() { + this.reloads += 1; + } + exit(reason: string) { + this.emit("render-process-gone", {}, { reason, exitCode: reason === "clean-exit" ? 0 : 15 }); + } +} + +class Window { + webContents = new Contents(); + destroyed = false; + isDestroyed() { + return this.destroyed; + } +} + +function recoverableWindow() { + const win = new Window(); + let time = 0; + reloadWhenRendererExits(win, { now: () => time }); + return { + win, + advance(ms: number) { + time += ms; + }, + }; +} + +describe("reloadWhenRendererExits", () => { + it("reloads the window when its renderer is killed", () => { + const { win } = recoverableWindow(); + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(1); + }); + + it("reloads after a renderer crash or out-of-memory exit", () => { + const { win, advance } = recoverableWindow(); + win.webContents.exit("crashed"); + advance(120_000); + win.webContents.exit("oom"); + expect(win.webContents.reloads).toBe(2); + }); + + it("leaves a renderer that exited cleanly alone", () => { + const { win } = recoverableWindow(); + win.webContents.exit("clean-exit"); + expect(win.webContents.reloads).toBe(0); + }); + + it("leaves a renderer that exits before the first page commits to Chromium", () => { + const { win } = recoverableWindow(); + win.webContents.url = ""; + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(0); + }); + + it("leaves a closed window closed", () => { + const { win } = recoverableWindow(); + win.destroyed = true; + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(0); + }); + + it("stops reloading a renderer that keeps exiting, and recovers again later", () => { + const { win, advance } = recoverableWindow(); + for (let exit = 0; exit < 5; exit += 1) { + win.webContents.exit("crashed"); + advance(1_000); + } + expect(win.webContents.reloads).toBe(3); + + advance(60_000); + win.webContents.exit("killed"); + expect(win.webContents.reloads).toBe(4); + }); +}); diff --git a/packages/desktop/src/window/renderer-recovery.ts b/packages/desktop/src/window/renderer-recovery.ts new file mode 100644 index 0000000000..4c4befe3ea --- /dev/null +++ b/packages/desktop/src/window/renderer-recovery.ts @@ -0,0 +1,56 @@ +import log from "electron-log/main"; + +// A window whose renderer exits keeps its frame but shows nothing until it is +// reloaded. Reload it, but stop when the renderer keeps exiting so a page that +// crashes on load does not restart in a loop. +const MAX_RELOADS_PER_WINDOW = 3; +const RELOAD_WINDOW_MS = 60_000; + +interface RendererExit { + reason: string; + exitCode: number; +} + +interface RecoverableWindow { + isDestroyed(): boolean; + webContents: { + on( + event: "render-process-gone", + listener: (event: unknown, details: RendererExit) => void, + ): unknown; + getURL(): string; + reload(): void; + }; +} + +export function reloadWhenRendererExits( + win: RecoverableWindow, + options: { now?: () => number } = {}, +): void { + const now = options.now ?? Date.now; + let reloadTimes: number[] = []; + + win.webContents.on("render-process-gone", (_event, details) => { + if (details.reason === "clean-exit" || win.isDestroyed()) return; + // Before the first page commits, Chromium finishes the navigation in a new + // renderer by itself. Reloading then would abort the window's initial load. + if (win.webContents.getURL() === "") return; + + const time = now(); + reloadTimes = reloadTimes.filter((reloadTime) => time - reloadTime < RELOAD_WINDOW_MS); + if (reloadTimes.length >= MAX_RELOADS_PER_WINDOW) { + log.error( + `[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` + + `not reloading after ${reloadTimes.length} reloads in the last minute`, + ); + return; + } + + reloadTimes.push(time); + log.warn( + `[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` + + `reloading the window (reload ${reloadTimes.length} in the last minute)`, + ); + win.webContents.reload(); + }); +} From 59d6018dacc1a0d0737f9227d85c9e6b28f0cc8b Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 10:10:45 +0700 Subject: [PATCH 146/160] Preserve commits when archiving workspaces (#10009) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(workspaces): preserve commits when archiving worktrees A removed worktree can be the only reference to its HEAD. Keep that commit before deletion and record the checkout so detached workspaces restore at the same commit. Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> * fix(workspaces): restore saved checkouts through one git path Keep existing archive and deletion behavior when Git cannot read a worktree HEAD, and record every readable checkout for a common restore path. * fix(workspaces): preserve git HEAD identity through restore Record Git’s full HEAD ref or commit so restore can pass branch and detached checkouts to Git without guessing from a short name. * fix(workspaces): scope saved HEAD to each archive An archive with no readable checkout must not retain the HEAD saved by an earlier archive. * test(workspaces): verify detached checkout after restore Update the browser journey for detached restore and allow the daemon restart test enough time on Windows runners. --------- Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> --- .../app/e2e/browser/worktree-restore.spec.ts | 17 +- packages/app/src/i18n/resources/ar.ts | 3 +- packages/app/src/i18n/resources/en.ts | 3 +- packages/app/src/i18n/resources/es.ts | 3 +- packages/app/src/i18n/resources/fr.ts | 3 +- packages/app/src/i18n/resources/ja.ts | 3 +- packages/app/src/i18n/resources/ko.ts | 3 +- packages/app/src/i18n/resources/pt-BR.ts | 3 +- packages/app/src/i18n/resources/ru.ts | 2 +- packages/app/src/i18n/resources/zh-CN.ts | 3 +- .../hub/execution-session.websocket.test.ts | 2 +- .../resolve-worktree-creation-intent.ts | 2 +- .../workspace-recovery-service.test.ts | 184 +++++++++++++++++- .../workspace-recovery-service.ts | 43 +++- .../src/server/workspace-archive-service.ts | 11 +- .../server/workspace-archive-undo.e2e.test.ts | 34 ++++ .../server/src/server/workspace-registry.ts | 3 + .../server/src/utils/worktree.posix.test.ts | 26 +++ packages/server/src/utils/worktree.test.ts | 24 +++ packages/server/src/utils/worktree.ts | 75 ++++++- 20 files changed, 396 insertions(+), 51 deletions(-) diff --git a/packages/app/e2e/browser/worktree-restore.spec.ts b/packages/app/e2e/browser/worktree-restore.spec.ts index 5849415984..069a9725e6 100644 --- a/packages/app/e2e/browser/worktree-restore.spec.ts +++ b/packages/app/e2e/browser/worktree-restore.spec.ts @@ -361,6 +361,10 @@ test.describe("Worktree restore", () => { cwd: backingWorktree.workspaceDirectory, stdio: "pipe", }); + const originalHead = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: backingWorktree.workspaceDirectory, + encoding: "utf8", + }).trim(); const created = await worktreeClient.createWorkspace({ source: { kind: "directory", path: backingWorktree.workspaceDirectory }, title: "Sample workspace", @@ -389,10 +393,7 @@ test.describe("Worktree restore", () => { await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click(); await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible(); await expect( - page.getByText( - "Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.", - { exact: true }, - ), + page.getByText("Restore Sample workspace to return to its agents.", { exact: true }), ).toBeVisible(); await captureBranchlessRestoreStep(page, "01-restore-workspace.png"); @@ -409,17 +410,13 @@ test.describe("Worktree restore", () => { cwd: backingWorktree.workspaceDirectory, encoding: "utf8", }).trim(); - const defaultHead = execFileSync("git", ["rev-parse", "main"], { - cwd: tempRepo.path, - encoding: "utf8", - }).trim(); - expect(restoredHead).toBe(defaultHead); + expect(restoredHead).toBe(originalHead); expect( execFileSync("git", ["branch", "--show-current"], { cwd: backingWorktree.workspaceDirectory, encoding: "utf8", }).trim(), - ).toMatch(/^restored\//); + ).toBe(""); }); test("restore failure stays visible and permits a successful retry", async ({ page }) => { diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index e79e901253..593d50d922 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -484,8 +484,7 @@ export const ar: TranslationResources = { archivedTitle: "مساحة العمل مؤرشفة", restoreDescription: "استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.", - restoreWithoutBranchDescription: - "استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.", + restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.", unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.", restoreAction: "استعادة", unarchiveAction: "إلغاء الأرشفة", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index a59de6a6a1..02e875a75f 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -483,8 +483,7 @@ export const en = { archivedTitle: "Workspace archived", restoreDescription: "Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.", - restoreWithoutBranchDescription: - "Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.", + restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.", unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.", restoreAction: "Restore", unarchiveAction: "Unarchive", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index e8a942c775..fa510cc8eb 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -489,8 +489,7 @@ export const es: TranslationResources = { archivedTitle: "Espacio de trabajo archivado", restoreDescription: "Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.", - restoreWithoutBranchDescription: - "Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.", + restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.", unarchiveDescription: "{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.", restoreAction: "Restaurar", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 8f7eba11ac..18536c5e96 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -489,8 +489,7 @@ export const fr: TranslationResources = { archivedTitle: "Espace de travail archivé", restoreDescription: "Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.", - restoreWithoutBranchDescription: - "Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.", + restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.", unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.", restoreAction: "Restaurer", unarchiveAction: "Désarchiver", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 5cd17d7300..6d177c808f 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -489,8 +489,7 @@ export const ja: TranslationResources = { archivedTitle: "ワークスペースはアーカイブ済みです", restoreDescription: "{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。", - restoreWithoutBranchDescription: - "{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。", + restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。", unarchiveDescription: "{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。", restoreAction: "復元", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 29fe850ac1..6a629c3fa4 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -485,8 +485,7 @@ export const ko: TranslationResources = { archivedTitle: "워크스페이스가 보관되었습니다", restoreDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.", - restoreWithoutBranchDescription: - "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.", + restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.", unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.", restoreAction: "복원", unarchiveAction: "보관 취소", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 405de1fe44..23ec297c45 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -488,8 +488,7 @@ export const ptBR: TranslationResources = { archivedTitle: "Workspace arquivado", restoreDescription: "Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.", - restoreWithoutBranchDescription: - "Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.", + restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.", unarchiveDescription: "{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.", restoreAction: "Restaurar", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index bfe65aa2b6..729c04d88e 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -489,7 +489,7 @@ export const ru: TranslationResources = { restoreDescription: "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.", restoreWithoutBranchDescription: - "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.", + "Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.", unarchiveDescription: "Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.", restoreAction: "Восстановить", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index c2d2500240..b47edf1e6c 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -484,8 +484,7 @@ export const zhCN: TranslationResources = { archivedTitle: "Workspace 已归档", restoreDescription: "恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。", - restoreWithoutBranchDescription: - "恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。", + restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。", unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。", restoreAction: "恢复", unarchiveAction: "取消归档", diff --git a/packages/server/src/server/hub/execution-session.websocket.test.ts b/packages/server/src/server/hub/execution-session.websocket.test.ts index 7cc2db0480..f9f9227f40 100644 --- a/packages/server/src/server/hub/execution-session.websocket.test.ts +++ b/packages/server/src/server/hub/execution-session.websocket.test.ts @@ -554,7 +554,7 @@ test("Hub resolves persisted execution ownership after daemon restart", async () expect(workspaceId).toEqual(expect.any(String)); expect(await hub.archivedWorkspaceAt(workspaceId!)).toEqual(expect.any(String)); expect(await hub.worktreeState(worktreeCwd)).toEqual({ exists: false, listed: false }); -}, 20_000); +}, 60_000); test("Hub treats missing and foreign executions as already controlled without exposing ownership", async () => { const hub = await launchRelationship(); diff --git a/packages/server/src/server/resolve-worktree-creation-intent.ts b/packages/server/src/server/resolve-worktree-creation-intent.ts index 5eddc0ef7b..34d587da03 100644 --- a/packages/server/src/server/resolve-worktree-creation-intent.ts +++ b/packages/server/src/server/resolve-worktree-creation-intent.ts @@ -3,7 +3,7 @@ import type { WorktreeSource } from "../utils/worktree.js"; export type WorktreeCreationIntent = Exclude< WorktreeSource, - { kind: "restore" | "restore-from-base" } + { kind: "restore" | "restore-from-base" | "restore-commit" } >; export interface ResolveWorktreeCreationIntentInput { diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts index 5526166d05..16a59dcd62 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.test.ts @@ -335,11 +335,15 @@ async function createBaseRecoveryFixture(baseBranch: string | null) { await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null })); }, }); - async function archiveAndRemove() { - await archivePersistedWorkspaceRecord({ - workspaceId: workspace.workspaceId, - workspaceRegistry: registry, - }); + async function archiveAndRemove(legacy = false) { + if (legacy) { + await registry.archive(workspace.workspaceId, new Date().toISOString()); + } else { + await archivePersistedWorkspaceRecord({ + workspaceId: workspace.workspaceId, + workspaceRegistry: registry, + }); + } await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome }); expect(existsSync(workspace.cwd)).toBe(false); } @@ -357,6 +361,134 @@ test("preserves ordinary checkout behavior when no separate base was recorded", ).toMatchObject({ currentBranch: "feature", baseRef: "feature" }); }); +test("records the full HEAD ref of an archived checkout", async () => { + const fixture = await createBaseRecoveryFixture(null); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: "refs/heads/feature", + }); +}); + +test("archives a workspace whose worktree Git administration is missing", async () => { + const fixture = await createBaseRecoveryFixture(null); + const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + rmSync(gitDir, { recursive: true, force: true }); + await archivePersistedWorkspaceRecord({ + workspaceId: fixture.workspace.workspaceId, + workspaceRegistry: fixture.registry, + }); + expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeTruthy(); +}); + +test("restores a branch that shares its name with a tag", async () => { + const fixture = await createBaseRecoveryFixture("main"); + execFileSync("git", ["tag", "feature"], { cwd: fixture.repoDir }); + await fixture.archiveAndRemove(); + expect((await fixture.registry.get(fixture.workspace.workspaceId))?.head).toBe( + "refs/heads/feature", + ); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature"); +}); + +test("restores detached HEAD even when the stored branch is stale", async () => { + const fixture = await createBaseRecoveryFixture("main"); + execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: commit, + }); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: null, + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("HEAD"); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); +}); + +test.each(["manual", "reconciliation"] as const)( + "a later %s archive without a readable HEAD restores the latest recorded branch", + async (route) => { + const fixture = await createBaseRecoveryFixture("main"); + await fixture.archiveAndRemove(); + await fixture.service.restore(fixture.workspace.workspaceId); + execFileSync("git", ["switch", "-c", "feature-b"], { cwd: fixture.workspace.cwd }); + writeFileSync(join(fixture.workspace.cwd, "newer.txt"), "newer\n"); + execFileSync("git", ["add", "newer.txt"], { cwd: fixture.workspace.cwd }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "newer"], { + cwd: fixture.workspace.cwd, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + // Placement reconciliation records the branch observed while the workspace is active. + await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({ + ...workspace, + branch: "feature-b", + })); + execFileSync("git", ["worktree", "remove", "--force", fixture.workspace.cwd], { + cwd: fixture.repoDir, + }); + if (route === "manual") { + await archivePersistedWorkspaceRecord({ + workspaceId: fixture.workspace.workspaceId, + workspaceRegistry: fixture.registry, + }); + } else { + await fixture.registry.archive(fixture.workspace.workspaceId, new Date().toISOString()); + } + + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature-b", + head: undefined, + }); + expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature-b", + }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect( + execFileSync("git", ["symbolic-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("refs/heads/feature-b"); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); + }, +); + test("restores a branchless workspace from its recorded base so work can continue", async () => { const fixture = await createBaseRecoveryFixture("refs/heads/release"); execFileSync("git", ["switch", "-c", "release"], { cwd: fixture.repoDir, stdio: "pipe" }); @@ -368,7 +500,7 @@ test("restores a branchless workspace from its recorded base so work can continu ...workspace, branch: null, })); - await fixture.archiveAndRemove(); + await fixture.archiveAndRemove(true); await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({ kind: "recoverable", @@ -402,7 +534,7 @@ test("restores a branchless workspace from the repository default when its base ...workspace, branch: null, })); - await fixture.archiveAndRemove(); + await fixture.archiveAndRemove(true); await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({ workspaceId: fixture.workspace.workspaceId, @@ -418,6 +550,44 @@ test("restores a branchless workspace from the repository default when its base ); }); +test("restores the archived detached checkout at its recorded commit", async () => { + const fixture = await createBaseRecoveryFixture("refs/heads/main"); + execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd }); + writeFileSync(join(fixture.workspace.cwd, "detached.txt"), "detached\n"); + execFileSync("git", ["add", "detached.txt"], { cwd: fixture.workspace.cwd }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], { + cwd: fixture.workspace.cwd, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(); + await fixture.archiveAndRemove(); + expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({ + branch: "feature", + head: commit, + }); + execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir }); + execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir }); + await fixture.service.restore(fixture.workspace.workspaceId); + expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({ + baseRefName: "main", + baseRef: "refs/heads/main", + }); + expect( + execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe(commit); + expect( + execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd: fixture.workspace.cwd, + encoding: "utf8", + }).trim(), + ).toBe("HEAD"); +}); + test("restores the branch HEAD with a base name when the exact base is missing", async () => { const fixture = await createBaseRecoveryFixture("refs/remotes/upstream/main"); const headBeforeArchive = execFileSync("git", ["rev-parse", "HEAD"], { diff --git a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts index a683a07744..38c95cb421 100644 --- a/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts +++ b/packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts @@ -151,13 +151,27 @@ export function createWorkspaceRecoveryService(deps: { workspace: PersistedWorkspaceRecord, sourceRepoRoot: string, ): Promise { - const source: WorktreeSource = workspace.branch - ? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch } - : { - kind: "restore-from-base", - branchName: `restored/${randomUUID().slice(0, 8)}`, - baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), - }; + let source: WorktreeSource; + const checkout = parseWorkspaceHead(workspace); + if (checkout.kind === "branch") { + source = { + kind: "restore", + branchName: checkout.branch, + baseRef: workspace.baseBranch, + }; + } else if (checkout.kind === "commit") { + source = { + kind: "restore-commit", + commit: checkout.commit, + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } else { + source = { + kind: "restore-from-base", + branchName: `restored/${randomUUID().slice(0, 8)}`, + baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch), + }; + } try { await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 }); @@ -251,16 +265,29 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null return defaultBranch; } +function parseWorkspaceHead( + workspace: PersistedWorkspaceRecord, +): { kind: "branch"; branch: string } | { kind: "commit"; commit: string } | { kind: "missing" } { + if (workspace.head) { + const prefix = "refs/heads/"; + return workspace.head.startsWith(prefix) + ? { kind: "branch", branch: workspace.head.slice(prefix.length) } + : { kind: "commit", commit: workspace.head }; + } + return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" }; +} + function createRecoveryPlan( input: | { action: "unarchive"; workspace: PersistedWorkspaceRecord } | { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string }, ): RecoveryPlan { + const checkout = parseWorkspaceHead(input.workspace); const state = { kind: "recoverable" as const, workspaceId: input.workspace.workspaceId, workspaceName: resolveWorkspaceDisplayName(input.workspace), - branch: input.workspace.branch, + branch: checkout.kind === "branch" ? checkout.branch : null, }; if (input.action === "restore") { return { diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index 7a71b4682b..5f6fb473e7 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -8,6 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js"; import type { ForgeService } from "../services/forge-service.js"; import { deletePaseoWorktree, + readWorktreeHeadReference, isPaseoOwnedWorktreeCwd, runWorktreeTeardownCommands, WorktreeTeardownError, @@ -707,7 +708,15 @@ export async function archivePersistedWorkspaceRecord(input: { } const archivedAt = input.archivedAt ?? new Date().toISOString(); - await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context); + let head: string | null = null; + if (existingWorkspace.kind === "worktree") { + const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd; + head = await readWorktreeHeadReference(cwd); + } + await input.workspaceRegistry.archive(input.workspaceId, archivedAt, { + ...input.context, + ...(head ? { head } : {}), + }); return existingWorkspace; } diff --git a/packages/server/src/server/workspace-archive-undo.e2e.test.ts b/packages/server/src/server/workspace-archive-undo.e2e.test.ts index a509cb2b6a..f68dbc5dd1 100644 --- a/packages/server/src/server/workspace-archive-undo.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-undo.e2e.test.ts @@ -151,6 +151,40 @@ test.skipIf(process.platform === "win32")( 60000, ); +test.skipIf(process.platform === "win32").each([ + ["branch", "restore"], + ["branch", "undo"], + ["detached", "restore"], + ["detached", "undo"], +] as const)( + "%s checkout survives archive and %s", + async (checkout, action) => { + const repo = createRepoWithGatedTeardown(); + repo.releaseTeardown(); + const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent( + repo.repoDir, + `keep-${checkout}-${action}`, + ); + if (checkout === "detached") git(directory, ["switch", "--detach"]); + writeFileSync(path.join(directory, "change.txt"), `${checkout}\n`); + git(directory, ["add", "change.txt"]); + git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "workspace commit"]); + const readHead = (args: string[]) => + execFileSync("git", args, { cwd: directory, encoding: "utf8" }).trim(); + const commit = readHead(["rev-parse", "HEAD"]); + const branch = readHead(["rev-parse", "--abbrev-ref", "HEAD"]); + expect((await ctx.client.archiveWorkspace(workspaceId)).error).toBeNull(); + expect(existsSync(directory)).toBe(false); + git(repo.repoDir, ["reflog", "expire", "--expire=now", "--all"]); + git(repo.repoDir, ["gc", "--prune=now"]); + if (action === "undo") await ctx.client.undoWorkspaceArchive(workspaceId); + else await ctx.client.restoreWorkspace(workspaceId); + expect(readHead(["rev-parse", "HEAD"])).toBe(commit); + expect(readHead(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(branch); + }, + 60000, +); + test.skipIf(process.platform === "win32")( "archive, undo, archive leaves the workspace archived", async () => { diff --git a/packages/server/src/server/workspace-registry.ts b/packages/server/src/server/workspace-registry.ts index fd376cc14c..04265da0c2 100644 --- a/packages/server/src/server/workspace-registry.ts +++ b/packages/server/src/server/workspace-registry.ts @@ -72,6 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({ .nullable() .optional() .transform((value) => value ?? null), + head: z.string().optional(), // Exact checkout/worktree root backing cwd. This differs from cwd when the // selected project is a subdirectory inside a repository. Persist it so // archive and recovery do not need the directory to still exist in order to @@ -126,6 +127,7 @@ export interface WorkspaceMutationContext { export interface WorkspaceArchiveContext { autoArchivedChangeRequestUrl?: string; + head?: string; } export interface ProjectMutation { @@ -586,6 +588,7 @@ export class FileBackedWorkspaceRegistry ...existing, updatedAt: archivedAt, archivedAt, + head: context?.head, ...(context?.autoArchivedChangeRequestUrl ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl } : {}), diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 35d59cce3f..5ee2ec5b1a 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -1406,6 +1406,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { rmSync(tempDir, { recursive: true, force: true }); }); + it("keeps an otherwise unreachable detached commit after deleting the worktree", async () => { + const result = await createWorktreePrimitive({ + cwd: repoDir, + worktreeSlug: "keep-commit", + source: { kind: "branch-off", baseBranch: "main", branchName: "feature/keep-commit" }, + paseoHome, + }); + execFileSync("git", ["checkout", "--detach"], { cwd: result.worktreePath }); + writeFileSync(join(result.worktreePath, "file.txt"), "detached change\n"); + execFileSync("git", ["add", "file.txt"], { cwd: result.worktreePath }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], { + cwd: result.worktreePath, + }); + const commit = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: result.worktreePath, + encoding: "utf8", + }).trim(); + + await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome }); + execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: repoDir }); + execFileSync("git", ["gc", "--prune=now"], { cwd: repoDir }); + expect( + execFileSync("git", ["cat-file", "-t", commit], { cwd: repoDir, encoding: "utf8" }).trim(), + ).toBe("commit"); + }); + it("places, owns, lists, and deletes a worktree outside the legacy root", async () => { // Sibling layout: /wt- diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index f549b461f8..39f2af09c0 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -3,6 +3,7 @@ import { createWorktree as createWorktreePrimitive, deriveWorktreeProjectHash, deletePaseoWorktree, + readWorktreeHead, isPaseoOwnedWorktreeCwd, mapWorkspaceCwdToWorktree, runWorktreeTeardownCommands, @@ -302,6 +303,29 @@ describe("paseo worktree manager", () => { expect(existsSync(created.worktreePath)).toBe(false); }); + it("does not read a parent repository's HEAD when the worktree has no .git", async () => { + const directory = join(repoDir, "missing-worktree"); + mkdirSync(directory); + await expect(readWorktreeHead(directory)).resolves.toBeNull(); + }); + + it("keeps a worktree when writing its retention ref fails", async () => { + const created = await createLegacyWorktreeForTest({ + branchName: "ref-write-failure", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "ref-write-failure", + paseoHome, + }); + mkdirSync(join(repoDir, ".git", "refs", "paseo"), { recursive: true }); + writeFileSync(join(repoDir, ".git", "refs", "paseo", "kept-commits"), "blocked\n"); + + await expect( + deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }), + ).rejects.toThrow(); + expect(existsSync(created.worktreePath)).toBe(true); + }); + it("deletes a worktree when Git reports its source through native and long path spellings", async () => { const created = await createLegacyWorktreeForTest({ branchName: "identity-delete", diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 2fc8bc05db..92e70c9e87 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -188,6 +188,7 @@ export type WorktreeSource = | { kind: "branch-off"; baseBranch: string; branchName: string } | { kind: "checkout-branch"; branchName: string } | { kind: "restore"; branchName: string; baseRef: string | null } + | { kind: "restore-commit"; commit: string; baseRef: string } | { kind: "restore-from-base"; baseRef: string; branchName: string } | { kind: "checkout-change-request"; @@ -1153,6 +1154,32 @@ async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): P } } +export async function readWorktreeHead(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) return null; + try { + const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], { + cwd: worktreePath, + }); + return stdout.trim(); + } catch { + return null; + } +} + +export async function readWorktreeHeadReference(worktreePath: string): Promise { + if (!(await pathExists(join(worktreePath, ".git")))) return null; + try { + const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], { + cwd: worktreePath, + acceptExitCodes: [0, 1], + }); + if (result.exitCode === 0) return result.stdout.trim(); + return readWorktreeHead(worktreePath); + } catch { + return null; + } +} + export async function deletePaseoWorktree({ cwd, worktreePath, @@ -1208,6 +1235,12 @@ export async function deletePaseoWorktree({ teardownCwd, }); } + const commit = await readWorktreeHead(resolvedWorktree); + if (commit) { + await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], { + cwd: resolvedWorktree, + }); + } } if (cwd) { @@ -1361,14 +1394,22 @@ export async function resolveDefaultWorktreePath( /** * Create a git worktree with proper naming conventions */ -export const createWorktree = async ({ +export function createWorktree( + options: CreateWorktreeOptions & { source: Exclude }, +): Promise; +export function createWorktree( + options: CreateWorktreeOptions, +): Promise & { branchName: string | null }>; +export async function createWorktree({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, -}: CreateWorktreeOptions): Promise => { +}: CreateWorktreeOptions): Promise< + Omit & { branchName: string | null } +> { const branchesBefore = source.kind === "checkout-branch" || source.kind === "checkout-change-request" || @@ -1394,14 +1435,14 @@ export const createWorktree = async ({ }); worktreePath = await normalizePathForOwnership(worktreePath); - if (sourcePlan.pushRemote) { + if (sourcePlan.pushRemote && sourcePlan.branchName) { await configureWorktreePushRemote({ cwd, branchName: sourcePlan.branchName, remote: sourcePlan.pushRemote, }); } - if (sourcePlan.trackingRemote) { + if (sourcePlan.trackingRemote && sourcePlan.branchName) { await configureWorktreeTrackingRemote({ cwd, branchName: sourcePlan.branchName, @@ -1434,7 +1475,7 @@ export const createWorktree = async ({ } throw error; } -}; +} interface ResolveWorktreeSourcePlanOptions { cwd: string; @@ -1443,7 +1484,7 @@ interface ResolveWorktreeSourcePlanOptions { } interface WorktreeSourcePlan { - branchName: string; + branchName: string | null; // Display name and exact ref are two different facts. The name cannot round-trip to a // commit — "main" resolves local-first even when the worktree was cut from a fork's // upstream — so comparisons and actions read the ref and the UI reads the name. @@ -1492,6 +1533,26 @@ async function resolveRestoredWorktreeSourcePlan( }; } +async function resolveRestoredCommitSourcePlan( + cwd: string, + source: Extract, +): Promise { + let exactBase: string | undefined; + if (isQualifiedRef(source.baseRef)) { + try { + exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef); + } catch { + // Restore the saved commit even when its comparison ref no longer exists. + } + } + return { + branchName: null, + metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef), + ...(exactBase ? { metadataBaseRef: exactBase } : {}), + addArguments: ["--detach", source.commit], + }; +} + async function resolveRestoredWorktreeFromBasePlan( cwd: string, source: Extract, @@ -1544,6 +1605,8 @@ async function resolveWorktreeSourcePlan({ return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug); case "restore": return resolveRestoredWorktreeSourcePlan(cwd, source); + case "restore-commit": + return resolveRestoredCommitSourcePlan(cwd, source); case "restore-from-base": return resolveRestoredWorktreeFromBasePlan(cwd, source); case "checkout-branch": { From e44edf5b3553371bfd571a5b63d7ad1171b353e7 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:16:36 +0000 Subject: [PATCH 147/160] Keep the sidebar's projects when the app renders while restoring hosts (#10042) * fix(app): publish restored hosts together with their directory sync A component that rendered while the host registry restored the project icon cache saw the host but found no directory sync for it, so its directory demand was dropped and the sidebar stayed on No projects yet for the session. Hosts are now published in the same step that creates their runtimes. Fixes #9996 Co-Authored-By: Claude Opus 5.5 * refactor(app): publish restored hosts through setHostsAndSync Every host-list change now goes through the one method that assigns the hosts, creates their runtimes, and notifies listeners in a single step. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/app/src/runtime/host-runtime.test.ts | 49 ++++++++++++++++++- packages/app/src/runtime/host-runtime.ts | 4 +- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/packages/app/src/runtime/host-runtime.test.ts b/packages/app/src/runtime/host-runtime.test.ts index fa4520e62e..69210defb6 100644 --- a/packages/app/src/runtime/host-runtime.test.ts +++ b/packages/app/src/runtime/host-runtime.test.ts @@ -2739,6 +2739,52 @@ describe("HostRuntimeStore", () => { session.clearSession(host.serverId); }); + it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => { + const host = makeHost({ + connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }], + }); + const fakeClient = new FakeDaemonClient(); + fakeClient.setConnectionState({ status: "connected" }); + const store = new HostRuntimeStore({ + storage: createMemoryHostRuntimeStorage({ + [REGISTRY_KEY]: JSON.stringify([host]), + "@paseo:e2e": "1", + }), + deps: { + createClient: () => fakeClient as unknown as DaemonClient, + connectToDaemon: async ({ host: hostProfile }) => ({ + client: fakeClient as unknown as DaemonClient, + serverId: hostProfile.serverId, + hostname: hostProfile.label ?? null, + }), + getClientId: async () => "cid_test_runtime", + }, + }); + + // A component renders on every tick while the registry loads, and acquires directory + // demand for each host it reads, as the sidebar does on its first render. + const registry = { loading: true }; + const boot = store.boot().finally(() => { + registry.loading = false; + }); + let releaseDemand: (() => void) | null = null; + while (registry.loading && !releaseDemand) { + if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) { + releaseDemand = store.acquireDirectoryDemand(host.serverId); + } + await Promise.resolve(); + } + await boot; + expect(releaseDemand).not.toBeNull(); + + await waitForHostOnline(store, host.serverId); + await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1)); + + releaseDemand?.(); + store.syncHosts([]); + useSessionStore.getState().clearSession(host.serverId); + }); + it("keeps readable hosts when the registry holds entries this build can't read", async () => { const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries)); @@ -2863,7 +2909,8 @@ describe("HostRuntimeStore", () => { await registryLoaded; expect(store.isHostRegistryLoaded()).toBe(true); - expect(hostListNotifications).toBe(2); + // Publishing the restored hosts, the registry turning ready, and the registry loading. + expect(hostListNotifications).toBe(3); } finally { if (previousOverride === undefined) { delete process.env.EXPO_PUBLIC_LOCAL_DAEMON; diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index f883c19b65..4cdee90385 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -1816,11 +1816,9 @@ export class HostRuntimeStore { shouldPersistHosts = true; } } - this.hosts = profiles; - this.replicaCache.setHosts(profiles.map((profile) => profile.serverId)); projectIconCache.setHosts(profiles.map((profile) => profile.serverId)); await projectIconCache.restore(); - this.syncHosts(profiles); + this.setHostsAndSync(profiles); for (const profile of profiles) { void this.directorySyncByServer .get(profile.serverId) From a5edd91f916b77991469c7816a503004a84c6969 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:26:42 +0000 Subject: [PATCH 148/160] Delete a stopped terminal worker's copy on Windows (#10039) * fix(terminal): delete a stopped worker's copy on Windows Windows keeps a just-exited worker's files open for a moment, so the single rm in pruneTerminalWorkerRuntimes failed and left the copy until the next daemon start. Retry the delete for up to 5.5s. Co-Authored-By: Claude Opus 5.5 * fix(terminal): bound the Windows retry of a worker copy delete rm's maxRetries repeats at every directory level, so a file that stays locked deep in node-pty would hold daemon start and stop far past the intended window. Retry one rm per attempt for up to 3s instead. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../src/terminal/terminal-worker-runtime.ts | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/server/src/terminal/terminal-worker-runtime.ts b/packages/server/src/terminal/terminal-worker-runtime.ts index 7ee0696478..1f24e73b0d 100644 --- a/packages/server/src/terminal/terminal-worker-runtime.ts +++ b/packages/server/src/terminal/terminal-worker-runtime.ts @@ -13,6 +13,7 @@ import { import { createRequire } from "node:module"; import { access, readdir, rm } from "node:fs/promises"; import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import { ensurePrivateDirectory } from "../server/private-files.js"; import { listTerminalWorkerRecords, terminalWorkerDirectory } from "./terminal-worker-record.js"; @@ -193,6 +194,28 @@ export function prepareTerminalWorkerRuntime(input: { return entry; } +// Windows keeps a just-exited worker's files open for a moment, so a delete that fails with one +// of these codes is retried for a short window. Each attempt is a single rm: rm's own maxRetries +// repeats at every directory level, so a file that stays locked deep in node-pty would hold +// daemon start and stop far past any window. +const TRANSIENT_REMOVE_ERRORS = new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]); +const TRANSIENT_REMOVE_WINDOW_MS = 3_000; +const TRANSIENT_REMOVE_PAUSE_MS = 100; + +async function removeCopy(directory: string): Promise { + const deadline = Date.now() + TRANSIENT_REMOVE_WINDOW_MS; + for (;;) { + try { + await rm(directory, { recursive: true, force: true }); + return; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!code || !TRANSIENT_REMOVE_ERRORS.has(code) || Date.now() >= deadline) throw error; + await delay(TRANSIENT_REMOVE_PAUSE_MS); + } + } +} + export interface PruneTerminalWorkerRuntimesResult { removed: string[]; /** Copies that could not be deleted (a worker that just exited can still hold files on Windows). */ @@ -236,7 +259,7 @@ export async function pruneTerminalWorkerRuntimes( ) continue; try { - await rm(directory, { recursive: true, force: true }); + await removeCopy(directory); result.removed.push(directory); } catch (error) { result.failed.push({ From 63a33ac3fd3e30c16ae7013c104f0ff4d1179616 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:01:21 +0000 Subject: [PATCH 149/160] Let plugin screens use the plugin state hooks (#10049) * Let plugin screens use the plugin state hooks A plugin screen opened from the Command Center or the sidebar showed "Plugin failed: Plugin state hooks must run inside a plugin host" as soon as it called useWorkspaces, useAgents or another state hook. Every plugin host paired the installation provider with its own state provider, and the screen host and the plugin settings host did not. The installation provider now supplies the state source for the installation's host, so every surface rendered under it can read state, and the hosts no longer wrap a second provider of their own. Co-Authored-By: Claude Opus 5.5 * Keep a sidebar view's cross-host state in its hooks A sidebar view renders once across every connected host and builds an unscoped state source for that. After the installation provider took over the state source, the environment provider dropped the view's own source, so its hooks read state scoped to one host. The installation provider now takes the surface's source when one is passed and falls back to the installation's host. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../e2e/browser/plugin-sidebar-items.spec.ts | 10 ++++ .../support/helpers/plugin-sidebar-items.ts | 12 ++++ packages/app/src/file-panels/plugin-host.tsx | 11 +--- .../plugins/installation-provider.test.tsx | 56 ++++++++++++++++++- .../app/src/plugins/installation-provider.tsx | 19 ++++++- packages/app/src/plugins/popover.tsx | 5 +- packages/app/src/plugins/timeline/view.tsx | 7 +-- .../src/plugins/workspace-panels/panel.tsx | 7 +-- 8 files changed, 98 insertions(+), 29 deletions(-) diff --git a/packages/app/e2e/browser/plugin-sidebar-items.spec.ts b/packages/app/e2e/browser/plugin-sidebar-items.spec.ts index 3acf19a860..e9858c1ab4 100644 --- a/packages/app/e2e/browser/plugin-sidebar-items.spec.ts +++ b/packages/app/e2e/browser/plugin-sidebar-items.spec.ts @@ -362,6 +362,16 @@ test.describe("Plugin sidebar items", () => { }); }); + test("a plugin screen reads workspaces through the state hooks", async ({ page }) => { + await page.setViewportSize(WIDE); + await gotoWorkspace(page, workspaceId); + await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 }); + await runCommand(page, "Open plugin workspaces"); + await expect(screenTitle(page)).toHaveText("Workspaces"); + await expect(page.getByText(`Workspace ${workspaceId}`, { exact: true })).toBeVisible(); + await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0); + }); + test("a header row's shortcut hint presses the row", async ({ page }) => { await page.setViewportSize(WIDE); await gotoWorkspace(page, workspaceId); diff --git a/packages/app/e2e/support/helpers/plugin-sidebar-items.ts b/packages/app/e2e/support/helpers/plugin-sidebar-items.ts index 0722bd8317..cdc6de753f 100644 --- a/packages/app/e2e/support/helpers/plugin-sidebar-items.ts +++ b/packages/app/e2e/support/helpers/plugin-sidebar-items.ts @@ -15,8 +15,18 @@ export const COMPACT = { width: 390, height: 844 }; /** A plugin written against the current API: a screen, header and footer items, a command. */ const SHOWCASE_SOURCE = `import React from "react"; import { Pressable, Text, View } from "react-native"; +import { useWorkspaces } from "@getpaseo/plugin/client"; import { SidebarRow } from "@getpaseo/plugin/client/ui"; +function WorkspacesScreen({ theme }) { + const workspaces = useWorkspaces(); + return ( + + {workspaces.map((ref) => {"Workspace " + ref.id})} + + ); +} + function DeploysScreen({ theme }) { return Deploys screen body; } @@ -63,11 +73,13 @@ function Broken() { export default function contribute(client) { client.addScreen({ id: "deploys", title: "Deploys", Component: DeploysScreen }); + client.addScreen({ id: "workspaces", title: "Workspaces", Component: WorkspacesScreen }); client.addSidebarHeaderItem({ id: "deploys", title: "Deploys", Component: DeploysItem }); client.addSidebarHeaderItem({ id: "broken", title: "Broken header", Component: Broken }); client.addSidebarFooterItem({ id: "sync", title: "Sync", Component: SyncItem }); client.addSidebarFooterItem({ id: "broken", title: "Broken footer", Component: Broken }); client.addCommandCenterItem({ id: "open-deploys", title: "Open deploys", icon: "Rocket", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "deploys" }) }); + client.addCommandCenterItem({ id: "open-workspaces", title: "Open plugin workspaces", icon: "List", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "workspaces" }) }); return () => {}; } `; diff --git a/packages/app/src/file-panels/plugin-host.tsx b/packages/app/src/file-panels/plugin-host.tsx index 4cc96cdc3d..d62a17cade 100644 --- a/packages/app/src/file-panels/plugin-host.tsx +++ b/packages/app/src/file-panels/plugin-host.tsx @@ -1,7 +1,4 @@ -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import type { PluginFilePanelProps } from "@getpaseo/plugin/client"; -import { useMemo } from "react"; -import { createPluginClientStateSource } from "@/plugins/client-state/source"; import { PluginInstallationProvider } from "@/plugins/installation-provider"; import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary"; import type { PluginFilePanel } from "./panels"; @@ -11,17 +8,11 @@ export function PluginFilePanelHost({ ...props }: PluginFilePanelProps & { panel: PluginFilePanel }) { const { plugin, contribution } = panel; - const stateSource = useMemo( - () => createPluginClientStateSource(plugin.serverId), - [plugin.serverId], - ); const Component = contribution.Component; return ( - - - + ); diff --git a/packages/app/src/plugins/installation-provider.test.tsx b/packages/app/src/plugins/installation-provider.test.tsx index 9248221704..0428e3bb2f 100644 --- a/packages/app/src/plugins/installation-provider.test.tsx +++ b/packages/app/src/plugins/installation-provider.test.tsx @@ -1,5 +1,5 @@ import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host"; -import { usePaseo, useRpc } from "@getpaseo/plugin/client"; +import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client"; import { defineRpc } from "@getpaseo/plugin"; import { createPaseoApi, type PaseoApi } from "@getpaseo/client"; import { DaemonClient } from "@getpaseo/client/internal/daemon-client"; @@ -8,7 +8,11 @@ import React from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { expect, it } from "vitest"; import { z } from "zod"; +import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin"; +import type { PluginClientStateSource } from "@getpaseo/plugin/client/host"; +import type { ToastApi } from "@/components/toast-host"; import { PluginInstallationProvider } from "./installation-provider"; +import { PluginEnvironmentProvider } from "./popover"; import type { InstalledPlugin } from "./types"; const status = defineRpc({ @@ -89,3 +93,53 @@ it("gives every surface the installation's client and RPCs on its first frame", plugin.lifetime.abort(); await plugin.paseo.dispose(); }); + +it("lets every surface read state through the plugin state hooks", async () => { + const plugin = installation([]); + function Surface() { + return {useWorkspaces().length} workspaces; + } + + const markup = renderToStaticMarkup( + + + , + ); + + expect(markup).toBe("0 workspaces"); + plugin.lifetime.abort(); + await plugin.paseo.dispose(); +}); + +function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) { + return { installation: plugin, state, toast: {} as ToastApi }; +} + +it("lets a surface read the state source its host passes", async () => { + const plugin = installation([]); + // A sidebar view spans every connected host, so its source is not the installation's host. + const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot; + const state: PluginClientStateSource = { + subscribe: () => () => undefined, + getWorkspace: () => workspace, + getAgent: () => null, + getProject: () => null, + getTerminal: () => null, + getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }), + }; + function Surface() { + return {useWorkspace("ws-on-another-host")?.id}; + } + + const environment = pluginEnvironment(plugin, state); + + const markup = renderToStaticMarkup( + + + , + ); + + expect(markup).toBe("ws-on-another-host"); + plugin.lifetime.abort(); + await plugin.paseo.dispose(); +}); diff --git a/packages/app/src/plugins/installation-provider.tsx b/packages/app/src/plugins/installation-provider.tsx index 19fb3bc8ab..d5faf75b8b 100644 --- a/packages/app/src/plugins/installation-provider.tsx +++ b/packages/app/src/plugins/installation-provider.tsx @@ -2,29 +2,42 @@ import { getPluginClientApi } from "./client-state/api"; import { QueryClientProvider } from "@tanstack/react-query"; import { PaseoApiProvider, + PluginClientStateProvider, PluginComposersProvider, PluginRpcProvider, PluginTranslationProvider, + type PluginClientStateSource, } from "@getpaseo/plugin/client/host"; -import React, { type ReactNode } from "react"; +import React, { useMemo, type ReactNode } from "react"; +import { createPluginClientStateSource } from "./client-state/source"; import { pluginComposersSource } from "./composer-items/source"; import type { InstalledPlugin } from "./types"; -/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */ +/** + * Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs, + * and the state the plugin state hooks read. That state is scoped to the installation's host + * unless the surface passes its own, as a sidebar view does to span every connected host. + */ export function PluginInstallationProvider({ plugin, + state: surfaceState, children, }: { plugin: InstalledPlugin; + state?: PluginClientStateSource; children: ReactNode; }) { + const state = useMemo( + () => surfaceState ?? createPluginClientStateSource(plugin.serverId), + [plugin.serverId, surfaceState], + ); return ( - {children} + {children} diff --git a/packages/app/src/plugins/popover.tsx b/packages/app/src/plugins/popover.tsx index f9680ebb29..d56b69f0d5 100644 --- a/packages/app/src/plugins/popover.tsx +++ b/packages/app/src/plugins/popover.tsx @@ -1,4 +1,3 @@ -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import type { ReactNode } from "react"; import { View } from "react-native"; import { StyleSheet } from "react-native-unistyles"; @@ -30,8 +29,8 @@ export function PluginEnvironmentProvider({ }: PluginEnvironmentProviderProps) { return ( - - {children} + + {children} ); diff --git a/packages/app/src/plugins/timeline/view.tsx b/packages/app/src/plugins/timeline/view.tsx index 90f6e0e1a2..8a3d522a2b 100644 --- a/packages/app/src/plugins/timeline/view.tsx +++ b/packages/app/src/plugins/timeline/view.tsx @@ -1,4 +1,3 @@ -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import type { PluginTimelineItemProps } from "@getpaseo/plugin/client"; import type { PluginTheme } from "@getpaseo/plugin"; import React, { type ComponentType, useMemo } from "react"; @@ -8,7 +7,6 @@ import { useIsCompactFormFactor } from "@/constants/layout"; import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime"; import type { Theme } from "@/styles/theme"; import type { PluginTimelineStreamItem } from "@/types/stream"; -import { createPluginClientStateSource } from "../client-state/source"; import { useInstalledPlugin } from "../registry"; import { PluginInstallationProvider } from "../installation-provider"; import { SurfaceErrorBoundary } from "../surface-error-boundary"; @@ -59,7 +57,6 @@ function PluginTimelineItemBody({ const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId; const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]); const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]); - const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]); if (!plugin || !renderer || !parsed || !client) { return ; @@ -82,9 +79,7 @@ function PluginTimelineItemBody({ return ( - - - + ); diff --git a/packages/app/src/plugins/workspace-panels/panel.tsx b/packages/app/src/plugins/workspace-panels/panel.tsx index 096400fb66..1500f1cdf1 100644 --- a/packages/app/src/plugins/workspace-panels/panel.tsx +++ b/packages/app/src/plugins/workspace-panels/panel.tsx @@ -5,7 +5,6 @@ import type { PluginTab, } from "@getpaseo/plugin/client"; import type { PluginTheme } from "@getpaseo/plugin"; -import { PluginClientStateProvider } from "@getpaseo/plugin/client/host"; import { CircleAlert } from "lucide-react-native"; import { useMemo, useState } from "react"; import { Text, View } from "react-native"; @@ -20,7 +19,6 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks"; import type { Theme } from "@/styles/theme"; import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity"; import { usePluginHostNavigation } from "../host-navigation"; -import { createPluginClientStateSource } from "../client-state/source"; import { toPluginTheme } from "../theme"; import { pluginIconComponent } from "../icons"; import { useInstalledPlugin } from "../registry"; @@ -67,7 +65,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) { const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId; const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]); const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]); - const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]); const navigation = usePluginHostNavigation(serverId); if (!plugin || !contribution || !workspaceExists) { @@ -123,9 +120,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) { Surface={Surface} key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`} > - - {panel} - + {panel} ); } From 91e72937739f3a1d3faeb358593efdbf171c8923 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 11:08:44 +0700 Subject: [PATCH 150/160] Hide historical PR badges on the default branch (#10053) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hide closed and merged requests on the origin repository’s default branch. Keep branch-based status matching for feature workspaces. Closes #9908. --- docs/forge-providers.md | 6 +- .../src/server/workspace-git-service.ts | 25 ++- packages/server/src/services/forge-service.ts | 37 ++-- .../server/src/services/gitea-service.test.ts | 27 +++ packages/server/src/services/gitea-service.ts | 51 +++--- .../src/services/github-service.test.ts | 108 ++++++++++-- .../server/src/services/github-service.ts | 166 +++++++++++------- .../src/services/gitlab-service.test.ts | 20 +++ .../server/src/services/gitlab-service.ts | 34 ++-- .../server/src/utils/checkout-git.test.ts | 24 ++- packages/server/src/utils/checkout-git.ts | 30 ++-- 11 files changed, 379 insertions(+), 149 deletions(-) diff --git a/docs/forge-providers.md b/docs/forge-providers.md index 62c91611f8..f66800a671 100644 --- a/docs/forge-providers.md +++ b/docs/forge-providers.md @@ -99,8 +99,10 @@ Register the adapter in `defaultForgeRegistry` with: Current change-request lookup matches the branch and repository for both open and terminal requests. Prefer an open request, then a terminal request at the local -HEAD, then the most recently updated terminal request. A reused branch can show -its previous request until a new one opens. Auto-archive separately requires an +HEAD, then the most recently updated terminal request. When the forge identifies +the checkout's branch as the origin repository's default branch, only open +requests are eligible. A reused feature branch can show its previous request +until a new one opens. Auto-archive separately requires an observed open-to-merged transition and a fresh exact match between checkout HEAD and the PR head, along with the existing workspace safety checks. diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index 93b5982b36..cdafbdd507 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -604,6 +604,7 @@ interface WorkspaceGitAuxiliaryReadCacheEntry { interface WorkspaceForgePrStatusPollTarget { headRef: string; + currentBranch?: string; headSha?: string; headRepositoryOwner?: string; } @@ -3150,11 +3151,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { if (resolution.service.retainCurrentPullRequestStatusPoll) { target.forgePrStatusPollSubscription = resolution.service.retainCurrentPullRequestStatusPoll({ cwd: target.cwd, - headRef: pollTarget.headRef, - ...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}), - ...(pollTarget.headRepositoryOwner - ? { headRepositoryOwner: pollTarget.headRepositoryOwner } - : {}), + ...pollTarget, onStatus: (status) => { if (!this.isActiveObservedWorkspaceTarget(target)) { return; @@ -3226,11 +3223,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { try { const status = await service.getCurrentPullRequestStatus({ cwd: target.cwd, - headRef: pollTarget.headRef, - ...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}), - ...(pollTarget.headRepositoryOwner - ? { headRepositoryOwner: pollTarget.headRepositoryOwner } - : {}), + ...pollTarget, reason: "self-heal-forge-pr-status", }); if (!closed && this.isActiveObservedWorkspaceTarget(target)) { @@ -3285,13 +3278,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { target.latestFacts?.isGit && target.latestFacts.currentBranch === git.currentBranch ? target.latestFacts.pullRequestLookupTarget : null; - if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) { - return lookupTarget; - } if (lookupTarget) { - return lookupTarget; + return git.currentBranch === lookupTarget.headRef + ? lookupTarget + : { ...lookupTarget, currentBranch: git.currentBranch }; + } + if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) { + return null; } - return { headRef: git.currentBranch }; } @@ -4424,6 +4418,7 @@ function buildWorkspaceForgePrStatusPollKey({ forge, remoteUrl, target.headRef, + target.currentBranch ?? null, target.headSha ?? null, target.headRepositoryOwner ?? null, ]); diff --git a/packages/server/src/services/forge-service.ts b/packages/server/src/services/forge-service.ts index fbf7f6522d..264ed7acd6 100644 --- a/packages/server/src/services/forge-service.ts +++ b/packages/server/src/services/forge-service.ts @@ -436,6 +436,22 @@ export interface CreatePullRequestOptions { body?: string; } +export interface CurrentPullRequestLookup { + cwd: string; + headRef: string; + headSha?: string; + headRepositoryOwner?: string; + /** Local branch name when it differs from the PR source ref. */ + currentBranch?: string; +} + +export function isOnDefaultBranch( + lookup: Pick, + defaultBranch: string | null | undefined, +): boolean { + return (lookup.currentBranch ?? lookup.headRef) === defaultBranch; +} + export interface ForgeService { listPullRequests(options: ListPullRequestsOptions): Promise; listIssues(options: ListIssuesOptions): Promise; @@ -475,12 +491,7 @@ export interface ForgeService { */ getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise; getCurrentPullRequestStatus( - options: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - } & ForgeReadOptions, + options: CurrentPullRequestLookup & ForgeReadOptions, ): Promise; getPullRequestTimeline(options: GetPullRequestTimelineOptions): Promise; getCheckDetails(options: GetCheckDetailsOptions): Promise; @@ -516,14 +527,12 @@ export interface ForgeService { * cannot change the outcome and is pure overhead. */ authProbeCanThrow?: boolean; - retainCurrentPullRequestStatusPoll?(options: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - onStatus?: (status: CurrentPullRequestStatus | null) => void; - onError?: (error: unknown) => void; - }): { unsubscribe: () => void }; + retainCurrentPullRequestStatusPoll?( + options: CurrentPullRequestLookup & { + onStatus?: (status: CurrentPullRequestStatus | null) => void; + onError?: (error: unknown) => void; + }, + ): { unsubscribe: () => void }; invalidate(options: { cwd: string }): void; dispose?(): void; } diff --git a/packages/server/src/services/gitea-service.test.ts b/packages/server/src/services/gitea-service.test.ts index 174e870839..b4aca78bd4 100644 --- a/packages/server/src/services/gitea-service.test.ts +++ b/packages/server/src/services/gitea-service.test.ts @@ -2036,6 +2036,33 @@ describe("createGiteaService", () => { ]); }); + it("hides a historical PR on the repository's default branch", async () => { + const historical = currentPullRequestApi({ + number: 8, + state: "closed", + headRef: "trunk", + headSha: "8888888888888888888888888888888888888888", + }); + const { service } = makeService((args) => { + if (args[0] === "pr" && args[1] === "list") return ok("[]"); + if (args[0] === "api" && args[1].includes("/pulls?state=all")) { + return ok(JSON.stringify([historical])); + } + if (args[0] === "api" && args[1] === "repos/example-user/sample-repo") { + return ok( + JSON.stringify({ + full_name: "example-user/sample-repo", + default_branch: "trunk", + }), + ); + } + throw new Error(`unexpected call: ${args.join(" ")}`); + }); + await expect( + service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }), + ).resolves.toBeNull(); + }); + it("falls back to the recent all-state PR window for a recently closed current branch PR", async () => { const headSha = "8888888888888888888888888888888888888888"; const closedPr = currentPullRequestApi({ diff --git a/packages/server/src/services/gitea-service.ts b/packages/server/src/services/gitea-service.ts index f1148c655e..f974d05693 100644 --- a/packages/server/src/services/gitea-service.ts +++ b/packages/server/src/services/gitea-service.ts @@ -26,11 +26,13 @@ import { compareTimelineItems, createUnavailableSearchResult, normalizeForgeSearchKinds, + isOnDefaultBranch, parseOptionalTime, } from "./forge-service.js"; import type { CheckDetails, CreatePullRequestOptions, + CurrentPullRequestLookup, CurrentPullRequestStatus, DisablePullRequestAutoMergeOptions, EnablePullRequestAutoMergeOptions, @@ -251,6 +253,7 @@ const GiteaPullRequestApiSchema = z const GiteaRepositoryApiSchema = z .object({ full_name: z.string(), + default_branch: z.string().nullish(), parent: z.object({ full_name: z.string().optional() }).nullable().optional(), }) .passthrough(); @@ -1585,11 +1588,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For return { items, truncated: true }; } - async function loadCurrentPullRequestStatus(input: { - cwd: string; - headRef: string; - headSha?: string; - }): Promise { + async function loadCurrentPullRequestStatus( + input: CurrentPullRequestLookup, + ): Promise { const match = await findCurrentPullRequestForHeadRef(input); if (!match) { return null; @@ -1613,11 +1614,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For return identity ? { owner: identity.owner, name: identity.name } : null; } - async function findCurrentPullRequestForHeadRef(input: { - cwd: string; - headRef: string; - headSha?: string; - }): Promise { + function readRepository(cwd: string, repoPath: string) { + return runJson(["api", repoPath], { cwd }, GiteaRepositoryApiSchema); + } + + function repositoryApiPath(repo: { owner: string; name: string } | null): string { + return repo + ? `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}` + : "repos/{owner}/{repo}"; + } + + async function findCurrentPullRequestForHeadRef( + input: CurrentPullRequestLookup, + ): Promise { const repoIdentity = await resolveCurrentRepoIdentity(input.cwd); const expectedHeadOwner = repoIdentity?.owner ?? null; const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner); @@ -1628,9 +1637,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For // tea discovers repository context from any configured git remote, while // the default remote resolver reads origin only. Preserve that broader // discovery for repositories whose primary remote has another name. - const repoPath = repoIdentity - ? `repos/${encodeURIComponent(repoIdentity.owner)}/${encodeURIComponent(repoIdentity.name)}` - : "repos/{owner}/{repo}"; + const repoPath = repositoryApiPath(repoIdentity); const recentItems = await runJsonArray( [ "api", @@ -1666,6 +1673,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For ) ?? candidates[0] ?? null; + if (match && mapGiteaState(match.state) !== "open") { + const repository = await readRepository(input.cwd, repoPath).catch(() => null); + if (isOnDefaultBranch(input, repository?.default_branch)) { + return null; + } + } return match ? currentPullRequestApiToListItem(match) : null; } @@ -2020,20 +2033,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For if (!repo) { return null; } - const repository = await runJson( - ["api", `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`], - { cwd: input.cwd }, - GiteaRepositoryApiSchema, - ); + const repository = await readRepository(input.cwd, repositoryApiPath(repo)); return repository.parent?.full_name ?? null; }, getCurrentPullRequestStatus(input): Promise { - return loadCurrentPullRequestStatus({ - cwd: input.cwd, - headRef: input.headRef, - headSha: input.headSha, - }); + return loadCurrentPullRequestStatus(input); }, async getPullRequest(input: GetPullRequestOptions): Promise { diff --git a/packages/server/src/services/github-service.test.ts b/packages/server/src/services/github-service.test.ts index 02aa8d4993..910a40c3b9 100644 --- a/packages/server/src/services/github-service.test.ts +++ b/packages/server/src/services/github-service.test.ts @@ -552,7 +552,7 @@ describe("ForgeService", () => { "view", "fork-owner/repo", "--json", - "owner,name,parent", + "owner,name,parent,defaultBranchRef", ]); }); @@ -862,7 +862,7 @@ describe("ForgeService", () => { expect(runner.calls).toHaveLength(2); expect(runner.calls[0]).toEqual({ cwd: "/repo", - args: ["repo", "view", "--json", "owner,name,parent"], + args: ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], }); expect(runner.calls[1]?.cwd).toBe("/repo"); expect(runner.calls[1]?.args.slice(0, 3)).toEqual(["api", "graphql", "-f"]); @@ -1111,6 +1111,56 @@ describe("ForgeService", () => { expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1); }); + it.each([ + { currentBranch: undefined, state: "MERGED", expected: null, calls: 1 }, + { currentBranch: undefined, state: "OPEN", expected: "open", calls: 2 }, + { currentBranch: "fork/trunk", state: "MERGED", expected: "merged", calls: 2 }, + ])( + "polls a $state PR with source trunk from checkout $currentBranch", + async ({ currentBranch, state, expected, calls }) => { + const runner = createScriptedRunner([ + batchPollStatusJson({ + t0: batchPollRepositoryJson( + [ + batchPollPrNodeJson({ + headRefName: "trunk", + state, + ...(state === "OPEN" ? { mergedAt: null } : {}), + }), + ], + { + defaultBranchRef: { name: "trunk" }, + }, + ), + }), + batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }), + ]); + const service = createGitHubService({ + runner: runner.runner, + resolveGhPath: async () => "/usr/bin/gh", + resolveRepoHost: async () => null, + resolveRepoSlug: async () => "acme/widgets", + now: () => 0, + }); + const statuses: Array = []; + try { + service.retainCurrentPullRequestStatusPoll?.({ + cwd: "/repo", + headRef: "trunk", + currentBranch, + onStatus: (status) => statuses.push(status), + }); + await vi.advanceTimersByTimeAsync(0); + await flushMicrotasks(); + + expect(statuses.map((status) => status?.state ?? null)).toEqual([expected]); + expect(runner.calls).toHaveLength(calls); + } finally { + service.dispose?.(); + } + }, + ); + it("batches PR status polls across workspaces into one GraphQL request", async () => { let now = 0; const runner = createScriptedRunner([ @@ -1490,13 +1540,19 @@ describe("ForgeService", () => { batchPollStatusJson({ t0: batchPollRepositoryJson([], { isFork: true, parent }), }), - batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }), + batchPollStatusJson({ + t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }), + origin0: { defaultBranchRef: { name: "main" } }, + }), batchPollStatusJson({ t0: batchPollChecksAliasJson([ { __typename: "StatusContext", context: "ci", state: "SUCCESS" }, ]), }), - batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }), + batchPollStatusJson({ + t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }), + origin0: { defaultBranchRef: { name: "main" } }, + }), ]); const service = createGitHubService({ ttlMs: 0, @@ -1524,6 +1580,9 @@ describe("ForgeService", () => { expect(runner.calls[1]?.args[3]).toContain( 't0: repository(owner: "upstream", name: "widgets")', ); + expect(runner.calls[1]?.args[3]).toContain( + 'origin0: repository(owner: "forkowner", name: "widgets")', + ); expect(statuses).toEqual([ expect.objectContaining({ number: 42, repoOwner: "upstream", checksStatus: "success" }), ]); @@ -3278,6 +3337,30 @@ describe("ForgeService", () => { }); }); + it.each([ + ["main", "CLOSED"], + ["master", "MERGED"], + ])("hides a %s PR on the default branch in a direct read (state %s)", async (headRef, state) => { + const historical = currentPullRequestJson({ + headRefName: headRef, + headRepositoryOwner: { login: "acme" }, + state, + }); + const runner = createScriptedRunner([ + historical, + JSON.stringify({ owner: { login: "acme" }, defaultBranchRef: { name: headRef } }), + JSON.stringify([JSON.parse(historical)]), + ]); + const service = createGitHubService({ + runner: runner.runner, + resolveGhPath: async () => "/usr/bin/gh", + }); + + await expect( + service.getCurrentPullRequestStatus({ cwd: "/repo", headRef }), + ).resolves.toBeNull(); + }); + it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => { const headSha = "2222222222222222222222222222222222222222"; const runner = createRunner([ @@ -3605,7 +3688,7 @@ describe("ForgeService", () => { }); expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([ ["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS], - ["repo", "view", "--json", "owner,name,parent"], + ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], ["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`], ["pr", "view", "41", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS], ["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS], @@ -3837,7 +3920,7 @@ describe("ForgeService", () => { }); expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([ ["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS], - ["repo", "view", "--json", "owner,name,parent"], + ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], ["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`], ["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS], [ @@ -3902,7 +3985,7 @@ describe("ForgeService", () => { ).resolves.toBeNull(); expect(calls.map((call) => call.args)).toEqual([ ["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS], - ["repo", "view", "--json", "owner,name,parent"], + ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"], [ "pr", "list", @@ -4750,7 +4833,12 @@ describe("ForgeService", () => { }), ).resolves.toEqual({ url: "https://github.com/acme/repo/pull/7", number: 7 }); - expect(runner.calls[0]?.args).toEqual(["repo", "view", "--json", "owner,name,parent"]); + expect(runner.calls[0]?.args).toEqual([ + "repo", + "view", + "--json", + "owner,name,parent,defaultBranchRef", + ]); expect(runner.calls[1]?.args).toEqual([ "api", "-X", @@ -4824,7 +4912,7 @@ describe("ForgeService", () => { expect(readFakeGitHubCliLog(fixture.logPath)).toEqual( expect.arrayContaining([ "auth status --hostname github.acme.internal|", - "repo view --json owner,name,parent|github.acme.internal", + "repo view --json owner,name,parent,defaultBranchRef|github.acme.internal", "api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal", ]), ); @@ -4869,7 +4957,7 @@ describe("ForgeService", () => { ).toHaveLength(2); expect(log).toEqual( expect.arrayContaining([ - "repo view --json owner,name,parent|github.acme.internal", + "repo view --json owner,name,parent,defaultBranchRef|github.acme.internal", "api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal", ]), ); diff --git a/packages/server/src/services/github-service.ts b/packages/server/src/services/github-service.ts index 189d53de5b..cdb701ffb3 100644 --- a/packages/server/src/services/github-service.ts +++ b/packages/server/src/services/github-service.ts @@ -27,6 +27,7 @@ import { computeChecksStatus, compareTimelineItems, createUnavailableSearchResult, + isOnDefaultBranch, normalizeForgeSearchKinds, parseOptionalTime, } from "./forge-service.js"; @@ -34,6 +35,7 @@ import type { CheckAnnotation, CheckDetails, CheckFailedJob, + CurrentPullRequestLookup, CurrentPullRequestStatus, DisablePullRequestAutoMergeOptions, EnablePullRequestAutoMergeOptions, @@ -446,7 +448,11 @@ const PullRequestTimelineGraphqlSchema = z.object({ .optional(), }); -const GitHubRepoViewSchema = z.object({ +const GitHubDefaultBranchSchema = z.object({ + defaultBranchRef: z.object({ name: z.string() }).nullish(), +}); + +const GitHubRepoViewSchema = GitHubDefaultBranchSchema.extend({ owner: z .object({ login: z.string().optional(), @@ -657,7 +663,7 @@ const BatchPollPrNodeSchema = z.object({ isInMergeQueue: z.boolean().optional().catch(false), }); -const BatchPollRepositorySchema = z.object({ +const BatchPollRepositorySchema = GitHubDefaultBranchSchema.extend({ owner: z.object({ login: z.string().optional() }).nullable().optional().catch(null), isFork: z.boolean().optional().catch(false), parent: z @@ -779,9 +785,7 @@ function graphqlString(value: string): string { return JSON.stringify(value); } -function buildBatchPullRequestStatusQuery( - entries: Array<{ owner: string; name: string; headRef: string }>, -): string { +function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): string { const aliases = entries.map( (entry, index) => ` ${batchAlias(index)}: repository(owner: ${graphqlString( entry.owner, @@ -789,6 +793,9 @@ function buildBatchPullRequestStatusQuery( owner { login } + defaultBranchRef { + name + } isFork parent { owner { @@ -802,7 +809,7 @@ function buildBatchPullRequestStatusQuery( rebaseMergeAllowed viewerDefaultMergeMethod pullRequests(headRefName: ${graphqlString( - entry.headRef, + entry.target.headRef, )}, first: ${BATCH_PR_CANDIDATE_LIMIT}, orderBy: {field: CREATED_AT, direction: DESC}) { nodes { ...PaseoPollPullRequest @@ -810,13 +817,26 @@ function buildBatchPullRequestStatusQuery( } }`, ); + const originAliases = entries.flatMap((entry, index) => + entry.owner === entry.originOwner && entry.name === entry.originName + ? [] + : [ + ` origin${index}: repository(owner: ${graphqlString( + entry.originOwner, + )}, name: ${graphqlString(entry.originName)}) { + defaultBranchRef { + name + } + }`, + ], + ); return `query PaseoBatchPullRequestStatus { rateLimit { limit remaining resetAt } -${aliases.join("\n")} +${[...aliases, ...originAliases].join("\n")} }\n${BATCH_PR_STATUS_FRAGMENT}`; } @@ -1076,11 +1096,7 @@ interface InFlightCacheEntry { force: boolean; } -interface GitHubPollTarget { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; +interface GitHubPollTarget extends CurrentPullRequestLookup { retainCount: number; /** Absolute due time on the shared poll grid; null while a poll is in flight. */ nextDueAt: number | null; @@ -1364,12 +1380,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G }); } - function getPollTargetKey(target: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - }): string { + function getPollTargetKey(target: CurrentPullRequestLookup): string { return buildCacheKey({ cwd: target.cwd, method: "getCurrentPullRequestStatus", @@ -1377,18 +1388,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: target.headRef, headSha: target.headSha, headRepositoryOwner: target.headRepositoryOwner, + currentBranch: target.currentBranch, }, }); } - function updatePollTargetAfterSuccess(update: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - status: CurrentPullRequestStatus | null; - notify: boolean; - }): void { + function updatePollTargetAfterSuccess( + update: CurrentPullRequestLookup & { + status: CurrentPullRequestStatus | null; + notify: boolean; + }, + ): void { const target = pollTargets.get(getPollTargetKey(update)); if (!target) { return; @@ -1638,13 +1648,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G if (!firstEntry) { return; } - const query = buildBatchPullRequestStatusQuery( - addressedEntries.map((entry) => ({ - owner: entry.owner, - name: entry.name, - headRef: entry.target.headRef, - })), - ); + const query = buildBatchPullRequestStatusQuery(addressedEntries); const args = ["api", "graphql", "-f", `query=${query}`]; const response = await loadGitHubPollBatchResponse({ entries: addressedEntries, @@ -1760,6 +1764,18 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G } continue; } + if ( + isTerminalOnDefaultBranch(entry, node, repository.data, input.aliases[`origin${index}`]) + ) { + finalizeBatchPollTarget({ + entry, + node: null, + repository: repository.data, + rollup: null, + startedAt: input.startedAt, + }); + continue; + } const frozenKey = node.state !== "OPEN" && node.headRefOid.length > 0 ? `${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}` @@ -1786,6 +1802,22 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G return distribution; } + function isTerminalOnDefaultBranch( + entry: GitHubBatchPollEntry, + node: BatchPollPrNode, + repository: BatchPollRepository, + originAlias: unknown, + ): boolean { + if (node.state === "OPEN") { + return false; + } + const origin = + entry.owner === entry.originOwner && entry.name === entry.originName + ? repository + : GitHubDefaultBranchSchema.safeParse(originAlias).data; + return isOnDefaultBranch(entry.target, origin?.defaultBranchRef?.name); + } + function addressGitHubBatchEntry(entry: GitHubBatchPollEntry): GitHubBatchPollEntry { const redirect = pollRepositoryRedirects.get(batchRepositoryRedirectKey(entry)); return redirect @@ -1963,25 +1995,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G ); status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null; } - const cacheKey = buildCacheKey({ - cwd: entry.target.cwd, - method: "getCurrentPullRequestStatus", - args: { - headRef: entry.target.headRef, - headSha: entry.target.headSha, - headRepositoryOwner: entry.target.headRepositoryOwner, - }, - }); + const cacheKey = getPollTargetKey(entry.target); // A direct or forced read can finish between this batch becoming due and // its checks query returning. Its cache write is newer than this cycle, so // converge on it instead of overwriting fresher data with the batch's. const existing = cache.get(cacheKey); if (existing && existing.expiresAt - ttlMs > input.startedAt) { updatePollTargetAfterSuccess({ - cwd: entry.target.cwd, - headRef: entry.target.headRef, - headSha: entry.target.headSha, - headRepositoryOwner: entry.target.headRepositoryOwner, + ...entry.target, status: existing.value as CurrentPullRequestStatus | null, notify: true, }); @@ -1991,10 +2012,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G // between polls reuse the batch result instead of spawning gh again. cache.set(cacheKey, { value: status, cwd: entry.target.cwd, expiresAt: deps.now() + ttlMs }); updatePollTargetAfterSuccess({ - cwd: entry.target.cwd, - headRef: entry.target.headRef, - headSha: entry.target.headSha, - headRepositoryOwner: entry.target.headRepositoryOwner, + ...entry.target, status, notify: true, }); @@ -2007,6 +2025,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: target.headRef, headSha: target.headSha, headRepositoryOwner: target.headRepositoryOwner, + currentBranch: target.currentBranch, reason: "self-heal-github", }); } catch (error) { @@ -2173,14 +2192,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, }, readOptions: input, load: async () => { - const status = await resolveCurrentPullRequestView({ + const status = await loadCurrentPullRequestView({ cwd: input.cwd, headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, + resolveOriginRepo: () => resolveRepoSlugCached(input.cwd), run, }); return addCurrentPullRequestGithubFacts({ cwd: input.cwd, status, run }); @@ -2191,6 +2213,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, status, notify: input.reason === "self-heal-github", }); @@ -2603,6 +2626,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G headRef: input.headRef, headSha: input.headSha, headRepositoryOwner: input.headRepositoryOwner, + currentBranch: input.currentBranch, retainCount: 0, nextDueAt: null, pollCycleStartedAt: null, @@ -2984,13 +3008,35 @@ function isGitHubRateLimitError(error: unknown): boolean { ); } -async function resolveCurrentPullRequestView(options: { - cwd: string; - headRef: string; - headSha?: string; - headRepositoryOwner?: string; - run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; -}): Promise { +async function loadCurrentPullRequestView( + options: CurrentPullRequestLookup & { + resolveOriginRepo(): Promise; + run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; + }, +): Promise { + let repoRead: ReturnType | undefined; + const readRepo = () => (repoRead ??= getGitHubRepoView(options)); + const status = await resolveCurrentPullRequestView({ ...options, readRepo }); + if (!status || status.state === "open") { + return status; + } + + const originRepo = await options.resolveOriginRepo(); + const repo = await repoRead; + const repoName = repo?.owner?.login && repo.name ? `${repo.owner.login}/${repo.name}` : null; + const origin = + originRepo && originRepo.toLowerCase() !== repoName?.toLowerCase() + ? await getGitHubRepoView({ ...options, repo: originRepo }) + : await readRepo(); + return isOnDefaultBranch(options, origin?.defaultBranchRef?.name) ? null : status; +} + +async function resolveCurrentPullRequestView( + options: CurrentPullRequestLookup & { + readRepo(): Promise | null>; + run: (args: string[], options: GitHubCommandRunnerOptions) => Promise; + }, +): Promise { const viewCandidate = await tryCurrentPullRequestView(options); const viewMatch = viewCandidate ? pickPullRequestCandidate({ @@ -3007,7 +3053,7 @@ async function resolveCurrentPullRequestView(options: { let headRepositoryOwner = options.headRepositoryOwner; if (!headRepositoryOwner) { - const repo = await getGitHubRepoView(options); + const repo = await options.readRepo(); const forkOwner = repo?.owner?.login; const parentOwner = repo?.parent?.owner?.login; const parentName = repo?.parent?.name; @@ -3282,7 +3328,7 @@ async function readGitHubRepoView( "view", ...(options.repo ? [options.repo] : []), "--json", - "owner,name,parent", + "owner,name,parent,defaultBranchRef", ]; const stdout = await options.run(args, { cwd: options.cwd, diff --git a/packages/server/src/services/gitlab-service.test.ts b/packages/server/src/services/gitlab-service.test.ts index 2e6df284c9..cb2034a2c9 100644 --- a/packages/server/src/services/gitlab-service.test.ts +++ b/packages/server/src/services/gitlab-service.test.ts @@ -389,6 +389,26 @@ describe("createGitLabService", () => { expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]); }); + it("hides a historical MR on the project's default branch", async () => { + const historical = { ...OPEN_MR, state: "merged", source_branch: "trunk" }; + const { service } = makeService((args) => { + if (args[1] === "list") return ok(JSON.stringify([historical])); + if (args[1] === "view") return ok(JSON.stringify(historical)); + if (args[0] === "api" && args[1] === "projects/example-group%2Fexample-project") { + return ok( + JSON.stringify({ + path_with_namespace: "example-group/example-project", + default_branch: "trunk", + }), + ); + } + return ok("{}"); + }); + await expect( + service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }), + ).resolves.toBeNull(); + }); + it("keeps a merged MR when its remote head advances beyond the checkout", async () => { const stale = { ...OPEN_MR, diff --git a/packages/server/src/services/gitlab-service.ts b/packages/server/src/services/gitlab-service.ts index 3e0111a439..25737e321e 100644 --- a/packages/server/src/services/gitlab-service.ts +++ b/packages/server/src/services/gitlab-service.ts @@ -16,6 +16,7 @@ import { compareTimelineItems, createUnavailableSearchResult, normalizeForgeSearchKinds, + isOnDefaultBranch, parseOptionalTime, } from "./forge-service.js"; import type { @@ -252,6 +253,7 @@ const GitLabApprovalsSchema = z const GitLabProjectSchema = z .object({ path_with_namespace: z.string(), + default_branch: z.string().nullish(), forked_from_project: z .object({ path_with_namespace: z.string().optional() }) .nullable() @@ -1142,6 +1144,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F return issues.map(toIssueSummary); } + async function readOriginProject(cwd: string) { + const remoteUrl = await resolveRemoteUrl(cwd); + const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null; + if (!projectPath) { + return null; + } + return runJson( + ["api", `projects/${encodeURIComponent(projectPath)}`], + { cwd: cwd }, + GitLabProjectSchema, + ); + } + return { async isAuthenticated(input: { cwd: string } & ForgeReadOptions): Promise { const glabPath = await resolveGlab(); @@ -1162,17 +1177,8 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F }, async getReferenceRepository(input): Promise { - const remoteUrl = await resolveRemoteUrl(input.cwd); - const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null; - if (!projectPath) { - return null; - } - const project = await runJson( - ["api", `projects/${encodeURIComponent(projectPath)}`], - { cwd: input.cwd }, - GitLabProjectSchema, - ); - return project.forked_from_project?.path_with_namespace ?? null; + const project = await readOriginProject(input.cwd); + return project?.forked_from_project?.path_with_namespace ?? null; }, async getCurrentPullRequestStatus(input): Promise { @@ -1181,6 +1187,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F if (!mr) { return null; } + if (mapMergeRequestState(mr.state) !== "open") { + const project = await readOriginProject(input.cwd).catch(() => null); + if (isOnDefaultBranch(input, project?.default_branch)) { + return null; + } + } const [approvals, pipelineChecks] = await Promise.all([ fetchApprovals(input.cwd, mr), fetchPipelineChecks(input.cwd, mr), diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index 13944108e2..ef240fa63c 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -178,6 +178,7 @@ function createPullRequestStatus(overrides?: Partial) interface RequestedPullRequestTarget { headRef: string; + currentBranch?: string; headSha?: string; headRepositoryOwner?: string; } @@ -194,6 +195,7 @@ function createGitHubServiceRecordingPullRequestTargets( github.getCurrentPullRequestStatus = async (request) => { options.requestedTargets.push({ headRef: request.headRef, + ...(request.currentBranch ? { currentBranch: request.currentBranch } : {}), ...(request.headSha ? { headSha: request.headSha } : {}), ...(request.headRepositoryOwner ? { headRepositoryOwner: request.headRepositoryOwner } : {}), }); @@ -3460,7 +3462,7 @@ const x = 1; { paseoHome }, ); - expect(requestedTargets).toEqual([factsTarget]); + expect(requestedTargets).toEqual([{ ...factsTarget, currentBranch: "tender-parrot" }]); }); it("uses the tracked fork branch for PR worktree status lookup", async () => { @@ -3490,7 +3492,11 @@ const x = 1; const status = await getPullRequestStatus(repoDir, github); expect(requestedTargets).toEqual([ - expect.objectContaining({ headRef: "main", headRepositoryOwner: "chethanuk" }), + expect.objectContaining({ + headRef: "main", + currentBranch: "chethanuk/main", + headRepositoryOwner: "chethanuk", + }), ]); expect(status.status?.number).toBe(345); expect(status.status?.headRefName).toBe("main"); @@ -3521,6 +3527,20 @@ const x = 1; expect(status.status?.state).toBe("closed"); }); + it("looks up PR status again when switching branches at the same commit", async () => { + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); + const requestedTargets: RequestedPullRequestTarget[] = []; + const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets }); + + const feature = await getPullRequestStatus(repoDir, forge); + execFileSync("git", ["checkout", "main"], { cwd: repoDir }); + const main = await getPullRequestStatus(repoDir, forge); + + expect(feature.status?.headRefName).toBe("feature"); + expect(main.status?.headRefName).toBe("main"); + expect(requestedTargets.map(({ headRef }) => headRef)).toEqual(["feature", "main"]); + }); + it("caches PR status results for duplicate lookups", async () => { execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], { diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index c817ed5e9b..f465edadb4 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -153,8 +153,12 @@ function createShortstatCache(ttlMs: number) { }); } -function getPullRequestStatusCacheKey(cwd: string, headSha: string | null): string { - return `${resolve(cwd)}\u0000${headSha ?? ""}`; +function getPullRequestStatusCacheKey( + cwd: string, + currentBranch: string | null, + headSha: string | null, +): string { + return `${resolve(cwd)}\u0000${currentBranch ?? ""}\u0000${headSha ?? ""}`; } function rememberPullRequestStatus(cacheKey: string, status: PullRequestStatusResult): void { @@ -4437,8 +4441,11 @@ export async function getPullRequestStatus( options?: CheckoutReadCacheOptions, context?: CheckoutContext, ): Promise { - const headSha = await getCurrentHeadSha(cwd, context); - const cacheKey = getPullRequestStatusCacheKey(cwd, headSha); + const [headSha, head] = await Promise.all([ + getCurrentHeadSha(cwd, context), + context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context), + ]); + const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha); if (!options?.force) { const cached = pullRequestStatusCache.get(cacheKey); if (cached) { @@ -4451,7 +4458,7 @@ export async function getPullRequestStatus( } } - const lookup = getPullRequestStatusUncached(cwd, forgeService, options, context, headSha) + const lookup = getPullRequestStatusUncached(cwd, forgeService, head, options, context, headSha) .then((status) => { pullRequestStatusCache.set(cacheKey, status); rememberPullRequestStatus(cacheKey, status); @@ -4477,6 +4484,7 @@ export async function getPullRequestStatus( async function getPullRequestStatusUncached( cwd: string, forgeService: ForgeService, + head: string | null, options?: CheckoutReadCacheOptions, context?: CheckoutContext, headSha?: string | null, @@ -4486,18 +4494,16 @@ async function getPullRequestStatusUncached( if (!context?.facts?.isGit) { await requireGitRepo(cwd, context); } - const head = context?.facts?.isGit - ? context.facts.currentBranch - : await getCurrentBranch(cwd, context); if (!head) { return buildPullRequestStatusResult(null, "no_remote"); } try { const resolvedLookupTarget = await resolvePullRequestStatusLookupTarget(cwd, head, context); - const lookupTarget = - headSha && !resolvedLookupTarget.headSha - ? { ...resolvedLookupTarget, headSha } - : resolvedLookupTarget; + const lookupTarget = { + ...resolvedLookupTarget, + ...(headSha && !resolvedLookupTarget.headSha ? { headSha } : {}), + ...(head !== resolvedLookupTarget.headRef ? { currentBranch: head } : {}), + }; let status: CurrentPullRequestStatus | null; if (options?.force) { const reason = options.reason; From a75c2b46353f3be3074f048b8bec8b0ba297af10 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:55:46 +0000 Subject: [PATCH 151/160] Keep background workspaces out of the dock badge and favicon (#9983) * Keep background workspaces out of the dock badge and favicon A workspace created with `--background` is hidden from the sidebar, but an agent finishing in it still counted toward the macOS dock badge and turned the web favicon to attention, pointing at something the user cannot see. The dock badge now skips background workspaces, and the favicon skips agents whose workspace is background, the same way both already skipped background agents. The favicon selector also rescans when the workspace map changes, so an agent synced before its workspace is dropped once the workspace arrives. Closes #9975 * Count background workspaces in the badge while Show background is on The sidebar shows background workspaces when Show background is on, so the dock badge and favicon now count them in that case too. They follow the same setting the sidebar reads. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/app/src/hooks/use-favicon-status.ts | 13 +++- .../app/src/utils/desktop-badge-state.test.ts | 12 ++++ packages/app/src/utils/desktop-badge-state.ts | 22 +++++-- packages/app/src/utils/favicon-status.test.ts | 61 ++++++++++++++++++- packages/app/src/utils/favicon-status.ts | 28 +++++++-- .../app/src/utils/memoize-on-session-maps.ts | 8 +-- 6 files changed, 124 insertions(+), 20 deletions(-) diff --git a/packages/app/src/hooks/use-favicon-status.ts b/packages/app/src/hooks/use-favicon-status.ts index 4686b10ff8..f6e8ac6693 100644 --- a/packages/app/src/hooks/use-favicon-status.ts +++ b/packages/app/src/hooks/use-favicon-status.ts @@ -6,6 +6,7 @@ import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state"; import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status"; import { isNative } from "@/constants/platform"; import { useSessionStore } from "@/stores/session-store"; +import { useSidebarViewStore } from "@/stores/sidebar-view-store"; import { useHosts } from "@/runtime/host-runtime"; type ColorScheme = "dark" | "light"; @@ -85,8 +86,16 @@ export function useFaviconStatus() { // The favicon reads the whole fleet, so it has to keep every host's directory loading even // though it no longer subscribes to the agent maps. useAllDirectoryDemand({ serverIds, enabled: !isNative }); - const selectFaviconStatus = useMemo(createFaviconStatusSelector, []); - const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []); + // Background workspaces count exactly when the sidebar shows them. + const showBackground = useSidebarViewStore((state) => state.showBackground); + const selectFaviconStatus = useMemo( + () => createFaviconStatusSelector({ showBackground }), + [showBackground], + ); + const selectMacDockBadgeCount = useMemo( + () => createMacDockBadgeCountSelector({ showBackground }), + [showBackground], + ); const status = useSessionStore(selectFaviconStatus); const dockBadgeCount = useSessionStore(selectMacDockBadgeCount); const [colorScheme, setColorScheme] = useState(getSystemColorScheme); diff --git a/packages/app/src/utils/desktop-badge-state.test.ts b/packages/app/src/utils/desktop-badge-state.test.ts index 69c747bcfe..c02a667249 100644 --- a/packages/app/src/utils/desktop-badge-state.test.ts +++ b/packages/app/src/utils/desktop-badge-state.test.ts @@ -73,6 +73,18 @@ describe("desktop-badge-state", () => { expect(selectMacDockBadgeCount(state)).toBe(3); }); + it("leaves out background workspaces, which the sidebar hides", () => { + const hidden = { ...workspace("a", "attention"), background: true }; + expect(selectMacDockBadgeCount(stateWith(hidden))).toBeUndefined(); + expect(selectMacDockBadgeCount(stateWith(hidden, workspace("b", "failed")))).toBe(1); + }); + + it("counts background workspaces while Show background puts them in the sidebar", () => { + const hidden = { ...workspace("a", "attention"), background: true }; + expect(selectMacDockBadgeCount(stateWith(hidden), { showBackground: true })).toBe(1); + expect(createMacDockBadgeCountSelector({ showBackground: true })(stateWith(hidden))).toBe(1); + }); + it("recounts only when a workspace map is replaced", () => { const select = createMacDockBadgeCountSelector(); const state = stateWith(workspace("a", "attention")); diff --git a/packages/app/src/utils/desktop-badge-state.ts b/packages/app/src/utils/desktop-badge-state.ts index 94cf025b50..1888cb9534 100644 --- a/packages/app/src/utils/desktop-badge-state.ts +++ b/packages/app/src/utils/desktop-badge-state.ts @@ -19,11 +19,21 @@ export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspa * The macOS dock badge only needs a count, so count here instead of materialising every * workspace status and comparing the whole list on every store write. */ -export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined { +export interface DockBadgeOptions { + /** Count background workspaces too, as the sidebar shows them while Show background is on. */ + showBackground?: boolean; +} + +export function selectMacDockBadgeCount( + state: WorkspaceStatusSource, + options: DockBadgeOptions = {}, +): number | undefined { let actionableCount = 0; for (const session of Object.values(state.sessions)) { if (!session) continue; for (const workspace of session.workspaces.values()) { + // A hidden background workspace would leave the badge pointing at nothing in the sidebar. + if (workspace.background && !options.showBackground) continue; if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1; } } @@ -31,11 +41,11 @@ export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | } /** A session-store selector for the dock badge count that recounts only when a workspace map changes. */ -export function createMacDockBadgeCountSelector(): ( - state: WorkspaceStatusSource, -) => number | undefined { +export function createMacDockBadgeCountSelector( + options: DockBadgeOptions = {}, +): (state: WorkspaceStatusSource) => number | undefined { return memoizeOnSessionMaps( - (session) => session.workspaces, - selectMacDockBadgeCount, + (session) => [session.workspaces], + (state) => selectMacDockBadgeCount(state, options), ); } diff --git a/packages/app/src/utils/favicon-status.test.ts b/packages/app/src/utils/favicon-status.test.ts index 6bb6a71d8e..a2e26e2ac1 100644 --- a/packages/app/src/utils/favicon-status.test.ts +++ b/packages/app/src/utils/favicon-status.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { Agent } from "@/stores/session-store"; +import type { Agent, WorkspaceDescriptor } from "@/stores/session-store"; import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status"; function agent(input: Partial & { id: string }): Agent { @@ -14,7 +14,21 @@ function agent(input: Partial & { id: string }): Agent { } function stateWith(...agents: Agent[]) { - return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } }; + return stateWithWorkspaces([], ...agents); +} + +function stateWithWorkspaces( + workspaces: Array>, + ...agents: Agent[] +) { + return { + sessions: { + srv: { + agents: new Map(agents.map((entry) => [entry.id, entry])), + workspaces: new Map(workspaces.map((entry) => [entry.id, entry])), + }, + }, + }; } describe("deriveFaviconStatus", () => { @@ -50,6 +64,37 @@ describe("deriveFaviconStatus", () => { ), ).toBe("none"); }); + + it("ignores agents in background workspaces, which the sidebar hides", () => { + const hidden = { id: "ws-hidden", background: true }; + expect( + deriveFaviconStatus( + stateWithWorkspaces( + [hidden], + agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }), + agent({ id: "b", workspaceId: "ws-hidden", status: "running" }), + ), + ), + ).toBe("none"); + expect( + deriveFaviconStatus( + stateWithWorkspaces( + [hidden, { id: "ws-shown", background: false }], + agent({ id: "a", workspaceId: "ws-hidden", status: "running" }), + agent({ id: "b", workspaceId: "ws-shown", requiresAttention: true }), + ), + ), + ).toBe("attention"); + }); + + it("counts agents in background workspaces while Show background puts them in the sidebar", () => { + const state = stateWithWorkspaces( + [{ id: "ws-hidden", background: true }], + agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }), + ); + expect(deriveFaviconStatus(state, { showBackground: true })).toBe("attention"); + expect(createFaviconStatusSelector({ showBackground: true })(state)).toBe("attention"); + }); }); describe("createFaviconStatusSelector", () => { @@ -63,6 +108,18 @@ describe("createFaviconStatusSelector", () => { expect(select({ sessions: { ...state.sessions } })).toBe("running"); }); + it("rescans when a workspace map is replaced", () => { + const select = createFaviconStatusSelector(); + const state = stateWithWorkspaces( + [], + agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }), + ); + expect(select(state)).toBe("attention"); + // The agent synced before its workspace; only the workspace map changes. + const workspaces = new Map([["ws-hidden", { id: "ws-hidden", background: true }]]); + expect(select({ sessions: { srv: { ...state.sessions.srv, workspaces } } })).toBe("none"); + }); + it("rescans when an agent map is replaced", () => { const select = createFaviconStatusSelector(); expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running"); diff --git a/packages/app/src/utils/favicon-status.ts b/packages/app/src/utils/favicon-status.ts index 62d1630ab7..cea80b7f83 100644 --- a/packages/app/src/utils/favicon-status.ts +++ b/packages/app/src/utils/favicon-status.ts @@ -1,10 +1,11 @@ -import type { Agent } from "@/stores/session-store"; +import type { Agent, WorkspaceDescriptor } from "@/stores/session-store"; import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; export type FaviconStatus = "none" | "running" | "attention"; interface FaviconAgentSession { agents: ReadonlyMap; + workspaces: ReadonlyMap>; } interface FaviconAgentSource { @@ -16,13 +17,22 @@ interface FaviconAgentSource { * three states here instead of building the aggregated agent list: the list allocates a * projection per agent, deep-compares it and sorts every agent on the host on each update. */ -export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus { +export interface FaviconStatusOptions { + /** Count agents in background workspaces too, as the sidebar shows them while Show background is on. */ + showBackground?: boolean; +} + +export function deriveFaviconStatus( + state: FaviconAgentSource, + options: FaviconStatusOptions = {}, +): FaviconStatus { let hasAttention = false; let hasNeedsInput = false; for (const session of Object.values(state.sessions)) { if (!session) continue; for (const agent of session.agents.values()) { if (agent.background || agent.archivedAt) continue; + if (!options.showBackground && isInBackgroundWorkspace(agent, session)) continue; if (agent.status === "running") return "running"; if (agent.requiresAttention) hasAttention = true; if (agent.pendingPermissions.length > 0) hasNeedsInput = true; @@ -31,10 +41,16 @@ export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus { return hasAttention || hasNeedsInput ? "attention" : "none"; } -/** A session-store selector for the favicon status that rescans only when an agent map changes. */ -export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus { +function isInBackgroundWorkspace(agent: Agent, session: FaviconAgentSession): boolean { + return agent.workspaceId ? session.workspaces.get(agent.workspaceId)?.background === true : false; +} + +/** A session-store selector for the favicon status that rescans only when an agent or workspace map changes. */ +export function createFaviconStatusSelector( + options: FaviconStatusOptions = {}, +): (state: FaviconAgentSource) => FaviconStatus { return memoizeOnSessionMaps( - (session) => session.agents, - deriveFaviconStatus, + (session) => [session.agents, session.workspaces], + (state) => deriveFaviconStatus(state, options), ); } diff --git a/packages/app/src/utils/memoize-on-session-maps.ts b/packages/app/src/utils/memoize-on-session-maps.ts index ed621ee1c4..5daeb58674 100644 --- a/packages/app/src/utils/memoize-on-session-maps.ts +++ b/packages/app/src/utils/memoize-on-session-maps.ts @@ -4,18 +4,18 @@ interface SessionsSource { /** * Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has - * changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost + * changed. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost * a reference check per host instead of a walk over every entry. */ export function memoizeOnSessionMaps, TResult>( - pickMap: (session: TSession) => unknown, + pickMaps: (session: TSession) => readonly unknown[], derive: (state: TState) => TResult, ): (state: TState) => TResult { let previousMaps: unknown[] | null = null; let previousResult: TResult; return (state) => { - const maps = Object.values(state.sessions).map((session) => - session ? pickMap(session) : undefined, + const maps = Object.values(state.sessions).flatMap((session) => + session ? pickMaps(session) : [undefined], ); if ( previousMaps && From f510b3edb7acc76e5d0be41fab43971f1ff1a261 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 12:05:21 +0700 Subject: [PATCH 152/160] Tell plugin agents to develop in a directory plugin, never a Git or npm installation (#10061) * Tell plugin agents to develop in a directory plugin, never a Git or npm installation paseo plugin update replaces a Git or npm installation and remove deletes it, so edits and commits made in Paseo's managed copy are lost. The paseo-plugin skill now says to clone the source outside the daemon home and install that directory, and to move any work out of a managed copy before update or remove. Refs #7904 * Rewrite the plugin development guidance as plain steps * Keep settings, runtime ID, and build output when moving a plugin to a local folder --- skills/paseo-plugin/SKILL.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/skills/paseo-plugin/SKILL.md b/skills/paseo-plugin/SKILL.md index 53a301eeb6..85030768d9 100644 --- a/skills/paseo-plugin/SKILL.md +++ b/skills/paseo-plugin/SKILL.md @@ -52,6 +52,36 @@ Pick the contribution that matches the request. Each row names the registration, | Inject launch-only MCP servers and save Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | | Attach a tool to selected agents | [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | +## Develop plugins in a local folder + +Develop a plugin in a local folder that you own, the same way you develop an npm package. Install +that folder by path. Paseo runs the plugin from that folder, `paseo plugin reload ` loads your +edits, and `paseo plugin update` does not change it. + +Do not edit, build, or commit inside the installation of a Git or npm plugin. That folder is +Paseo's managed storage in the `plugins/` directory of the daemon home. `paseo plugin update` +replaces it, and `paseo plugin remove` deletes it. Both commands discard every edit and commit in +that folder. + +Before you edit an installed plugin, run `paseo plugin ls ` and read the SOURCE column. A +`git:` source, an `npm:` source, or a registry source such as `/owner/slug` is a +managed installation. Its DIRECTORY column shows the managed folder. + +To develop a plugin that is installed from Git or npm: + +1. Clone the source repository of the plugin into a folder outside the daemon home. For an npm + plugin, find the repository in its `package.json`. +2. If SOURCE ends with `:`, use that subfolder of the clone as the plugin folder. +3. If the managed folder holds edits or commits, move them into the plugin folder. +4. In the plugin folder, install the dependencies and run the `build` commands from + `paseo-plugin.json`. Paseo runs `build` only for managed installations. +5. Ask the user before you remove the managed installation. `paseo plugin remove ` also + deletes the saved settings of the plugin. +6. Run `paseo plugin remove `. +7. Run `paseo plugin install /absolute/path/to/plugin-folder --id ` to keep the runtime ID. +8. Edit the plugin folder, and run `paseo plugin reload ` after each change. If a change needs + a `build` command, run that command before `reload`. + ## Create the project Use an absolute path on the daemon machine. `init` writes files but does not install packages. From 871c714b46208d3fa815cbe412a28a921b4af977 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:26:35 +0700 Subject: [PATCH 153/160] Create worktrees in large repos without scanning every ignored file (#10020) List ignored directories as single entries and only search inside them when a .worktreeinclude pattern matches the directory or names a path inside it. A bare .env no longer selects node_modules/pkg/.env. Verified with real Git and isolated daemon workspace creation on Linux. With 300,000 ignored files, Git trace2 recorded over 6,000 directory visits before the fix and fewer than five after. The workspace copied the root .env. The lifecycle test also verified rollback when copying fails. Closes #10004 Co-authored-by: mgranderath <22001111+mgranderath@users.noreply.github.com> --- plugins/worktree-include/server/copy.test.ts | 291 ++++++++++++++++++ plugins/worktree-include/server/copy.ts | 178 ++++++++++- public-docs/worktrees/worktreeinclude.md | 2 + .../worktrees/worktreeinclude.zh-CN.md | 2 + 4 files changed, 457 insertions(+), 16 deletions(-) create mode 100644 plugins/worktree-include/server/copy.test.ts diff --git a/plugins/worktree-include/server/copy.test.ts b/plugins/worktree-include/server/copy.test.ts new file mode 100644 index 0000000000..30ada0c06d --- /dev/null +++ b/plugins/worktree-include/server/copy.test.ts @@ -0,0 +1,291 @@ +import { execFileSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { copyWorktreeIncludes } from "./copy.js"; + +let root: string; +let source: string; +let worktree: string; + +async function writeSource(files: Record): Promise { + for (const [file, contents] of Object.entries(files)) { + await mkdir(dirname(join(source, file)), { recursive: true }); + await writeFile(join(source, file), contents); + } +} + +// Total directories Git visits while listing files, read from its trace2 events. +async function directoriesVisited(run: () => Promise): Promise { + const trace = join(root, "trace.json"); + process.env.GIT_TRACE2_EVENT = trace; + try { + await run(); + } finally { + delete process.env.GIT_TRACE2_EVENT; + } + return (await readFile(trace, "utf8")) + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as { event: string; key?: string; value?: string }) + .filter((event) => event.event === "data" && event.key === "directories-visited") + .reduce((total, event) => total + Number(event.value), 0); +} + +async function copied(): Promise { + const result = await copyWorktreeIncludes(worktree, source); + if (result.kind !== "copied") throw new Error(`expected a copy, got ${result.kind}`); + return [...result.copied].sort(); +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "worktree-include-")); + source = join(root, "source"); + worktree = join(root, "worktree"); + await mkdir(source); + await mkdir(worktree); + execFileSync("git", ["init", "-q", source]); +}); + +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +describe("copyWorktreeIncludes", () => { + it("does not search inside an ignored directory that no pattern names", async () => { + await writeSource({ + ".gitignore": "node_modules/\n.env\n", + ".worktreeinclude": ".env\n", + ".env": "SECRET=root", + "apps/web/.env": "SECRET=web", + "node_modules/pkg/.env": "SECRET=package", + }); + + expect(await copied()).toEqual([".env", "apps/web/.env"]); + expect(existsSync(join(worktree, "node_modules"))).toBe(false); + }); + + it("searches inside ignored directories for a pattern that starts with **/", async () => { + await writeSource({ + ".gitignore": "node_modules/\n.env\n", + ".worktreeinclude": "**/.env\n", + ".env": "SECRET=root", + "node_modules/pkg/.env": "SECRET=package", + }); + + expect(await copied()).toEqual([".env", "node_modules/pkg/.env"]); + }); + + it("copies a file in an untracked directory once when a **/ pattern also searches it", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": "**/.env\nnew-package/.env\n", + "new-package/.env": "SECRET=new", + }); + + const result = await copyWorktreeIncludes(worktree, source); + expect(result).toEqual({ + kind: "copied", + copied: ["new-package/.env"], + skipped: [], + }); + }); + + it("copies a path a pattern names inside an ignored directory", async () => { + await writeSource({ + ".gitignore": "node_modules/\n", + ".worktreeinclude": "node_modules/pkg/.env\n", + "node_modules/pkg/.env": "SECRET=package", + "node_modules/other/.env": "SECRET=other", + }); + + expect(await copied()).toEqual(["node_modules/pkg/.env"]); + }); + + it("copies an ignored directory that a pattern names", async () => { + await writeSource({ + ".gitignore": ".secrets/\nbuild/\n", + ".worktreeinclude": ".secrets/\n", + ".secrets/a.key": "a", + ".secrets/nested/b.key": "b", + "build/out.js": "built", + }); + + expect(await copied()).toEqual([".secrets/a.key", ".secrets/nested/b.key"]); + }); + + it("searches inside an ignored directory for a path a pattern names", async () => { + await writeSource({ + ".gitignore": "config/\n", + ".worktreeinclude": "config/*.local.json\n!config/production.local.json\n", + "config/dev.local.json": "dev", + "config/production.local.json": "production", + "config/defaults.json": "defaults", + }); + + expect(await copied()).toEqual(["config/dev.local.json"]); + expect(await readFile(join(worktree, "config/dev.local.json"), "utf8")).toBe("dev"); + }); + + it("copies ignored files inside an untracked directory", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": ".env\n", + "new-package/.env": "SECRET=new", + }); + + expect(await copied()).toEqual(["new-package/.env"]); + }); + + it("copies nothing that is tracked or not ignored", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": ".env\nnotes.txt\n", + "notes.txt": "not ignored", + }); + + expect(await copied()).toEqual([]); + }); + + it("searches only the path a glob-free pattern names directly inside an ignored directory", async () => { + const packages: Record = {}; + for (let i = 0; i < 20; i++) packages[`node_modules/pkg${i}/lib/index.js`] = "code"; + await writeSource({ + ".gitignore": "node_modules/\n", + ".worktreeinclude": "node_modules/.cache\n", + "node_modules/.cache/state.json": "cache", + ...packages, + }); + + let result: Awaited> | undefined; + const visited = await directoriesVisited(async () => { + result = await copyWorktreeIncludes(worktree, source); + }); + + expect(result).toEqual({ + kind: "copied", + copied: ["node_modules/.cache/state.json"], + skipped: [], + }); + expect(visited).toBeLessThan(10); + }); + + it.skipIf(process.platform === "win32")( + "copies includes when an ignored file is named like a Git pathspec", + async () => { + await writeSource({ + ".gitignore": "*.log\n.env\n", + ".worktreeinclude": ".env\n", + ".env": "SECRET=root", + ":(oops.log": "log", + ":!c.log": "log", + }); + + expect(await copied()).toEqual([".env"]); + }, + ); + + it("ignores exclude patterns from the user's git template", async () => { + const template = join(root, "template"); + await mkdir(join(template, "info"), { recursive: true }); + await writeFile(join(template, "info", "exclude"), "*.log\n"); + await writeSource({ + ".gitignore": "*.log\n.env\n", + ".worktreeinclude": ".env\n", + ".env": "SECRET=root", + "debug.log": "log", + }); + + process.env.GIT_TEMPLATE_DIR = template; + try { + expect(await copied()).toEqual([".env"]); + } finally { + delete process.env.GIT_TEMPLATE_DIR; + } + }); + + it("does not search an ignored directory deeper than a pattern without ** can reach", async () => { + const packages: Record = {}; + for (let i = 0; i < 20; i++) packages[`apps/web/node_modules/pkg${i}/lib/index.js`] = "code"; + await writeSource({ + ".gitignore": "node_modules/\n.env\n", + ".worktreeinclude": "apps/*/.env\n", + "apps/web/.env": "SECRET=web", + ...packages, + }); + + let result: Awaited> | undefined; + const visited = await directoriesVisited(async () => { + result = await copyWorktreeIncludes(worktree, source); + }); + + expect(result).toEqual({ kind: "copied", copied: ["apps/web/.env"], skipped: [] }); + expect(visited).toBeLessThan(10); + }); + + it("reads the first pattern after a UTF-8 byte order mark", async () => { + await writeSource({ + ".gitignore": "node_modules/\n", + ".worktreeinclude": "\uFEFFnode_modules/.cache/\n", + "node_modules/.cache/state.json": "cache", + }); + + expect(await copied()).toEqual(["node_modules/.cache/state.json"]); + }); + + it("matches patterns case-insensitively when the source repo ignores case", async () => { + execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]); + await writeSource({ + ".gitignore": ".env\nconfig/\n", + ".worktreeinclude": ".ENV\nCONFIG/a.json\n", + ".env": "SECRET=root", + "config/a.json": "a", + }); + + expect(await copied()).toEqual([".env", "config/a.json"]); + }); + + it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => { + execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]); + await writeSource({ + ".gitignore": "Config/\nÉTÉ/\n", + ".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n", + "Config/a.json": "a", + "ÉTÉ/sub/.env": "SECRET=summer", + }); + + expect(await copied()).toEqual(["Config/a.json", "ÉTÉ/sub/.env"]); + }); + + // Each searched folder is one argument to Git. Windows caps a command line at 32,767 + // characters and Linux at 2 MB, so each platform gets enough folders to exceed its own + // limit, with names short enough for Windows paths. + it("searches more ignored folders than fit on one command line", async () => { + const folders = process.platform === "win32" ? 300 : 15_000; + const name = (i: number) => `${"x".repeat(150)}${i}`; + await writeSource({ + ".gitignore": "x*/\n.env\n", + ".worktreeinclude": "**/.env\n", + [`${name(folders - 1)}/.env`]: "SECRET=last", + }); + for (let i = 0; i < folders - 1; i++) await mkdir(join(source, name(i))); + await Promise.all( + Array.from({ length: folders - 1 }, (_, i) => writeFile(join(source, name(i), "a"), "")), + ); + + expect(await copied()).toEqual([`${name(folders - 1)}/.env`]); + }, 60_000); + + it("copies ignored files inside an untracked directory a pattern names", async () => { + await writeSource({ + ".gitignore": ".env\n", + ".worktreeinclude": "newdir/\n", + "newdir/.env": "SECRET=new", + "newdir/notes.txt": "untracked", + }); + + expect(await copied()).toEqual(["newdir/.env"]); + }); +}); diff --git a/plugins/worktree-include/server/copy.ts b/plugins/worktree-include/server/copy.ts index 73a3ba63f3..1b8cab3cbd 100644 --- a/plugins/worktree-include/server/copy.ts +++ b/plugins/worktree-include/server/copy.ts @@ -2,7 +2,8 @@ // Copyright (c) 2026 Carlos Precioso. import { execFile } from "node:child_process"; import { constants, existsSync } from "node:fs"; -import { copyFile, mkdir } from "node:fs/promises"; +import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; @@ -22,37 +23,33 @@ async function git(cwd: string, args: string[], input?: string): Promise return stdout; } -async function gitAllowExit1(cwd: string, args: string[], input: string): Promise { +// `git check-ignore --stdin` reads each path as a pathspec, so a name such as `:(x` +// would be parsed as pathspec magic. A `./` prefix keeps every path literal. +async function checkIgnore(cwd: string, args: string[], paths: string[]): Promise { + const input = paths.map((path) => `./${path}\0`).join(""); + let output: string; try { - return await git(cwd, args, input); + output = await git(cwd, [...args, "check-ignore", "--stdin", "-z"], input); } catch (error) { // `git check-ignore` exits 1 when nothing matched. - if ((error as { code?: number }).code === 1) return ""; + if ((error as { code?: number }).code === 1) return []; throw error; } + return splitNul(output).map((path) => path.replace(/^\.\//, "")); } const splitNul = (s: string) => s.split("\0").filter(Boolean); +const isDirectory = (entry: string) => entry.endsWith("/"); // Copy files that match .worktreeinclude (gitignore syntax) // AND are gitignored, so tracked files are never touched. export async function copyWorktreeIncludes(worktree: string, source: string): Promise { if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" }; - const matches = splitNul( - await git(source, [ - "ls-files", - "--others", - "--ignored", - `--exclude-from=${INCLUDE_FILE}`, - "-z", - ]), - ); + const matches = await findIncludedFiles(source); if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] }; - const ignored = splitNul( - await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"), - ); + const ignored = await checkIgnore(source, [], matches); const copied: string[] = []; const skipped: string[] = []; @@ -69,3 +66,152 @@ export async function copyWorktreeIncludes(worktree: string, source: string): Pr } return { kind: "copied", copied, skipped }; } + +// Git lists a directory it ignores as a whole, such as node_modules/, as one entry. +// Only directories that a pattern matches or names a path inside are searched, and +// only as deep as the pattern names, so creating a worktree does not walk every file +// in large ignored trees. +async function findIncludedFiles(source: string): Promise { + const ignored = splitNul( + await git(source, [ + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--directory", + "-z", + ]), + ); + if (ignored.length === 0) return []; + + const ignoreCase = await sourceIgnoresCase(source); + const patterns = parsePatterns(await readFile(join(source, INCLUDE_FILE), "utf8")); + const matched = new Set(await matchIncludePatterns(source, ignored, ignoreCase)); + const files = ignored.filter((entry) => !isDirectory(entry) && matched.has(entry)); + const searched = new Set(); + // Git also lists an untracked folder that holds ignored entries, which are listed on + // their own, so only folders Git ignores as a whole are searched. + const directories = await checkIgnore(source, [], ignored.filter(isDirectory)); + for (const directory of directories) { + if (matched.has(directory)) { + searched.add(directory); + continue; + } + for (const pattern of patterns) { + const inside = searchedPathInside(pattern, directory, ignoreCase); + if (inside !== null) searched.add(inside); + } + } + if (searched.size === 0) return files; + + const pathspecs = [...searched].map( + (path) => `:(${ignoreCase ? "literal,icase" : "literal"})${path}`, + ); + const inside: string[] = []; + for (const batch of commandLineBatches(pathspecs)) { + const listed = await git(source, [ + "ls-files", + "--others", + "--ignored", + `--exclude-from=${INCLUDE_FILE}`, + "-z", + "--", + ...batch, + ]); + inside.push(...splitNul(listed)); + } + return [...new Set([...files, ...inside])]; +} + +// Windows caps a command line at 32,767 characters, so a pattern such as `**/.env` in a +// repo with many ignored folders searches them over several Git calls. +const COMMAND_LINE_BATCH_CHARS = 16_000; + +function commandLineBatches(args: string[]): string[][] { + const batches: string[][] = []; + let batch: string[] = []; + let length = 0; + for (const arg of args) { + if (batch.length > 0 && length + arg.length + 1 > COMMAND_LINE_BATCH_CHARS) { + batches.push(batch); + batch = []; + length = 0; + } + batch.push(arg); + length += arg.length + 1; + } + if (batch.length > 0) batches.push(batch); + return batches; +} + +// Match entries against .worktreeinclude alone, in a scratch repository where no other +// ignore rules apply. Directory entries keep their trailing slash, so directory +// patterns match them without anything on disk. +async function matchIncludePatterns( + source: string, + entries: string[], + ignoreCase: boolean, +): Promise { + const scratch = await mkdtemp(join(tmpdir(), "paseo-worktree-include-")); + try { + // An empty template keeps the user's template `info/exclude` out of the matching. + await git(scratch, ["init", "-q", "--template="]); + return await checkIgnore( + scratch, + [ + "-c", + `core.excludesFile=${join(source, INCLUDE_FILE)}`, + "-c", + `core.ignoreCase=${ignoreCase}`, + ], + entries, + ); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +} + +// The scratch repository would otherwise take core.ignoreCase from the temp folder. +async function sourceIgnoresCase(source: string): Promise { + try { + return (await git(source, ["config", "--type=bool", "core.ignoreCase"])).trim() === "true"; + } catch { + // `git config` exits 1 when the key is unset. + return false; + } +} + +function parsePatterns(contents: string): string[] { + // Git skips a leading UTF-8 byte order mark in exclude files. + return contents + .replace(/^\uFEFF/, "") + .split(/\r?\n/) + .map((line) => line.trimEnd()) + .filter((line) => line !== "" && !line.startsWith("#") && !line.startsWith("!")); +} + +// A pattern with a slash before its end is anchored to the checkout root, so it can +// name a path inside `directory` when its literal start and the directory overlap. +// Without `**`, a pattern matches paths of exactly its own depth, so a directory that +// deep or deeper can hold no match below it. Returns the narrowest path to search: the +// whole path when the pattern has no glob, else the folder before its first glob, or +// `directory` itself when the path ends above it. +function searchedPathInside( + pattern: string, + rawDirectory: string, + ignoreCase: boolean, +): string | null { + // Git folds only ASCII letters when it ignores case. + const fold = (text: string) => + ignoreCase ? text.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()) : text; + const path = fold(pattern.replace(/^\//, "")); + const directory = fold(rawDirectory); + const depth = (text: string) => text.replace(/\/$/, "").split("/").length; + if (depth(path) < 2) return null; + if (!path.includes("**") && depth(directory) >= depth(path)) return null; + const globAt = path.search(/[*?[\\]/); + const literal = globAt === -1 ? path : path.slice(0, globAt); + if (!literal.startsWith(directory) && !directory.startsWith(literal)) return null; + const searched = globAt === -1 ? literal : literal.slice(0, literal.lastIndexOf("/") + 1); + return searched.length > directory.length ? searched : directory; +} diff --git a/public-docs/worktrees/worktreeinclude.md b/public-docs/worktrees/worktreeinclude.md index 50c5f0370a..21ba7afc2f 100644 --- a/public-docs/worktrees/worktreeinclude.md +++ b/public-docs/worktrees/worktreeinclude.md @@ -36,6 +36,8 @@ config/*.local.json A pattern only selects files that Git already ignores. Adding a path here does not ignore it, so also configure `.gitignore` when needed. Tracked files and untracked files that Git does not ignore are excluded. +Paseo does not search inside a directory that Git ignores as a whole, such as `node_modules/`, unless a pattern names that directory or a path inside it. A bare name like `.env` matches `.env` and `apps/web/.env`, but not `node_modules/pkg/.env`. To copy from inside an ignored directory, name it in the pattern, as in `node_modules/pkg/.env` or `.secrets/`. A pattern with a glob in its first directory name, such as `**/.env` or `*/.env`, searches every ignored directory, including `node_modules/`, so name the directory instead when it is large. + ## When files are copied The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run. diff --git a/public-docs/worktrees/worktreeinclude.zh-CN.md b/public-docs/worktrees/worktreeinclude.zh-CN.md index e80e386a01..f391865999 100644 --- a/public-docs/worktrees/worktreeinclude.zh-CN.md +++ b/public-docs/worktrees/worktreeinclude.zh-CN.md @@ -36,6 +36,8 @@ config/*.local.json 模式只会选择 Git 已忽略的文件。在此添加路径不会使 Git 忽略该文件,需要时还应配置 `.gitignore`。已跟踪的文件和未被 Git 忽略的未跟踪文件都不会被复制。 +对于被 Git 整体忽略的目录(例如 `node_modules/`),除非某个模式指明了该目录或其中的路径,否则 Paseo 不会在其中查找。像 `.env` 这样的纯文件名会匹配 `.env` 和 `apps/web/.env`,但不会匹配 `node_modules/pkg/.env`。要从被忽略的目录中复制文件,请在模式中写出该目录,例如 `node_modules/pkg/.env` 或 `.secrets/`。第一级目录名中带有通配符的模式(例如 `**/.env` 或 `*/.env`)会在所有被忽略的目录中查找,包括 `node_modules/`,因此目录较大时请直接写出目录。 + ## 文件复制时机 {#when-files-are-copied} 内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。 From 3815e72359be181c37d1866a251831132825e22d Mon Sep 17 00:00:00 2001 From: Monarch Maisuriya Date: Wed, 18 Nov 2026 11:17:31 +0530 Subject: [PATCH 154/160] fix(desktop): refuse browser screenshots with no painted pixels (#9807) Viewport and full-page browser screenshots wait for a frame with non-transparent pixels. When the page does not paint within the existing capture budget, the tool returns screenshot_no_frame. Fixes #9810. Co-authored-by: monarchmaisuriya Co-authored-by: Claude Opus 5.5 --- docs/browser-capture-harness.md | 5 +- .../features/browser-automation/ipc.test.ts | 24 +++++++ .../src/features/browser-automation/ipc.ts | 8 ++- .../browser-automation/service.test.ts | 67 +++++++++++++++++++ .../features/browser-automation/service.ts | 26 ++++++- 5 files changed, 126 insertions(+), 4 deletions(-) diff --git a/docs/browser-capture-harness.md b/docs/browser-capture-harness.md index f760fafa67..0458356b2d 100644 --- a/docs/browser-capture-harness.md +++ b/docs/browser-capture-harness.md @@ -117,7 +117,10 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov Screenshot capture temporarily enables frame production inside the shared serialized queue, restores the previous throttling policy on success or failure, and retains a 5-second capture budget. The browser tool takes one viewport frame through Electron's frame subscription and releases the -subscription on completion or cancellation. A resized resident guest can produce fresh pixels +subscription on completion or cancellation. Guest pages have a transparent base background, so a page +that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where +every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame` +when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout metrics and screenshot clip. diff --git a/packages/desktop/src/features/browser-automation/ipc.test.ts b/packages/desktop/src/features/browser-automation/ipc.test.ts index 427e86e1b1..2ea5f599c7 100644 --- a/packages/desktop/src/features/browser-automation/ipc.test.ts +++ b/packages/desktop/src/features/browser-automation/ipc.test.ts @@ -4,6 +4,8 @@ import { adaptWebContents, HostSnapshotEngineRegistry } from "./ipc.js"; import type { IsolatedKeyboardInputEvent } from "./trusted-input.js"; class FakeImage implements TabImage { + public constructor(private readonly alpha = 255) {} + public toPNG(): Uint8Array { return new Uint8Array([137, 80, 78, 71]); } @@ -11,6 +13,10 @@ class FakeImage implements TabImage { public getSize(): { width: number; height: number } { return { width: 640, height: 480 }; } + + public toBitmap(): Uint8Array { + return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]); + } } class FakeDebugger { @@ -268,6 +274,24 @@ describe("browser automation IPC adapter", () => { expect(contents.endedFrameSubscriptions).toBe(1); }); + test("skips frames with no painted pixels and captures the first painted frame", async () => { + const contents = new FakeWebContents(2004); + const tab = adaptWebContents(contents); + const controller = new AbortController(); + const capture = tab.captureFrame(controller.signal); + const unpainted = new FakeImage(0); + const painted = new FakeImage(255); + + contents.frameListener?.(unpainted); + expect(contents.frameListener).not.toBeNull(); + contents.frameListener?.(painted); + + expect(await capture).toBe(painted); + expect(contents.frameListener).toBeNull(); + controller.abort(); + expect(contents.endedFrameSubscriptions).toBe(1); + }); + test("cancels a pending frame subscription when the capture budget expires", async () => { const contents = new FakeWebContents(2001); const tab = adaptWebContents(contents); diff --git a/packages/desktop/src/features/browser-automation/ipc.ts b/packages/desktop/src/features/browser-automation/ipc.ts index 18e5b84544..5932ccd0b1 100644 --- a/packages/desktop/src/features/browser-automation/ipc.ts +++ b/packages/desktop/src/features/browser-automation/ipc.ts @@ -1,4 +1,4 @@ -import { ipcMain } from "electron"; +import { ipcMain, nativeImage } from "electron"; import { BrowserAutomationExecuteRequestSchema } from "@getpaseo/protocol/browser-automation/rpc-schemas"; import type { BrowserAutomationConsoleLogEntry, @@ -15,7 +15,7 @@ import { promptShimInstallScript, promptShimRestoreScript, } from "./dialog-handling.js"; -import { BrowserTabClosedError, executeAutomationCommand } from "./service.js"; +import { BrowserTabClosedError, executeAutomationCommand, hasPaintedPixels } from "./service.js"; import { BrowserSnapshotEngine } from "./snapshot-engine.js"; import { listRegisteredPaseoBrowserIds, @@ -133,6 +133,7 @@ export function adaptWebContents(contents: BrowserAutomationWebContents): TabCon goForward: () => contents.goForward(), reload: () => contents.reload(), captureFrame: (signal) => captureViewportFrame(contents, signal), + decodePng: (png) => nativeImage.createFromBuffer(Buffer.from(png)), invalidate: () => contents.invalidate(), withFrameProduction: async (capture) => { const previous = contents.getBackgroundThrottling(); @@ -182,6 +183,9 @@ function captureViewportFrame( // A resized resident guest can paint while capturePage's surface-copy // request remains pending. Subscribe to its rendered frames instead. contents.beginFrameSubscription(false, (image) => { + // Keep the subscription open until the page has painted; the capture + // budget turns a page that never paints into screenshot_no_frame. + if (!hasPaintedPixels(image)) return; stop(); resolve(image); }); diff --git a/packages/desktop/src/features/browser-automation/service.test.ts b/packages/desktop/src/features/browser-automation/service.test.ts index d793e138b7..5f892bbe59 100644 --- a/packages/desktop/src/features/browser-automation/service.test.ts +++ b/packages/desktop/src/features/browser-automation/service.test.ts @@ -22,6 +22,7 @@ class FakeImage implements TabImage { public constructor( private readonly bytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3]), private readonly size = { width: 640, height: 480 }, + private readonly alpha = 255, ) {} public toPNG(): Uint8Array { @@ -31,8 +32,14 @@ class FakeImage implements TabImage { public getSize(): { width: number; height: number } { return this.size; } + + public toBitmap(): Uint8Array { + return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]); + } } +const UNPAINTED_FULL_PAGE_PNG = "unpaintedPng"; + class FakeTab implements TabContents { public withFrameProduction(capture: () => Promise): Promise { return capture(); @@ -77,6 +84,7 @@ class FakeTab implements TabContents { public fullPageScreenshotThrows = false; public fullPageScreenshotErrorMessage = "UnknownVizError"; public fullPageCaptureFailuresBeforeSuccess = 0; + public fullPageUnpaintedCapturesBeforePainted = 0; public layoutMetrics = { cssLayoutViewport: { clientWidth: 390, clientHeight: 844 }, cssContentSize: { width: 390, height: 1200 }, @@ -191,6 +199,11 @@ class FakeTab implements TabContents { this.actions.push("invalidate"); } + public decodePng(png: Uint8Array): TabImage { + const unpainted = Buffer.from(png).equals(Buffer.from(UNPAINTED_FULL_PAGE_PNG, "base64")); + return new FakeImage(png, { width: 390, height: 1200 }, unpainted ? 0 : 255); + } + public getConsoleMessages(): BrowserAutomationConsoleLogEntry[] { return this.consoleMessages; } @@ -218,6 +231,10 @@ class FakeTab implements TabContents { if (this.fullPageScreenshotThrows) { throw new Error(this.fullPageScreenshotErrorMessage); } + if (this.fullPageUnpaintedCapturesBeforePainted > 0) { + this.fullPageUnpaintedCapturesBeforePainted -= 1; + return { data: UNPAINTED_FULL_PAGE_PNG }; + } return { data: this.fullPageScreenshotData }; } if (command === "Runtime.evaluate") { @@ -2035,6 +2052,56 @@ describe("executeAutomationCommand", () => { } }); + test("screenshot with fullPage waits for a CDP image with painted pixels", async () => { + vi.useFakeTimers(); + try { + const browser = new BrowserAutomationHarness(); + browser.tab.fullPageUnpaintedCapturesBeforePainted = 1; + + const resultPromise = browser.execute({ + command: "screenshot", + args: { browserId: BROWSER_A, fullPage: true }, + }); + await vi.advanceTimersByTimeAsync(200); + + await expect(resultPromise).resolves.toMatchObject({ + ok: true, + result: { command: "screenshot", dataBase64: "fullPagePng" }, + }); + expect( + browser.tab.debugCommands.filter((entry) => entry.command === "Page.captureScreenshot"), + ).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + + test("screenshot with fullPage returns no-frame when the page never paints", async () => { + vi.useFakeTimers(); + try { + const browser = new BrowserAutomationHarness(); + browser.tab.fullPageUnpaintedCapturesBeforePainted = Number.POSITIVE_INFINITY; + + const resultPromise = browser.execute({ + command: "screenshot", + args: { browserId: BROWSER_A, fullPage: true }, + }); + await vi.advanceTimersByTimeAsync(5_000); + + await expect(resultPromise).resolves.toEqual({ + requestId: "req-screenshot", + ok: false, + error: { + code: "screenshot_no_frame", + message: "The tab has not painted yet. Retry the screenshot.", + retryable: true, + }, + }); + } finally { + vi.useRealTimers(); + } + }); + test("screenshot with fullPage surfaces ordinary CDP capture errors", async () => { const browser = new BrowserAutomationHarness(); browser.tab.fullPageScreenshotThrows = true; diff --git a/packages/desktop/src/features/browser-automation/service.ts b/packages/desktop/src/features/browser-automation/service.ts index 34a01ed074..5f038dd453 100644 --- a/packages/desktop/src/features/browser-automation/service.ts +++ b/packages/desktop/src/features/browser-automation/service.ts @@ -36,6 +36,7 @@ export interface TabContents { goForward(): void; reload(): void; captureFrame(signal: AbortSignal): Promise; + decodePng(png: Uint8Array): TabImage; invalidate(): void; withFrameProduction(capture: () => Promise): Promise; sendInputEvent(event: IsolatedKeyboardInputEvent): void; @@ -52,6 +53,22 @@ export interface TabContents { export interface TabImage { toPNG(): Uint8Array; getSize(): { width: number; height: number }; + // Raw 32-bit pixels. Alpha is the fourth byte of each pixel in BGRA and RGBA order alike. + toBitmap(): Uint8Array; +} + +// Electron guest pages have a transparent base background, so a page that has +// painted nothing yet (for example a dev server hiding body until its JS boots) +// yields a frame where every pixel is transparent. That frame is not a +// screenshot of the page. +export function hasPaintedPixels(image: TabImage): boolean { + const bitmap = image.toBitmap(); + for (let alpha = 3; alpha < bitmap.length; alpha += 4) { + if (bitmap[alpha] !== 0) { + return true; + } + } + return false; } export interface BrowserRegistry { @@ -1348,11 +1365,18 @@ async function executeFullPageScreenshot( const metrics = await getCdpLayoutMetrics(target.contents); width = metrics.contentWidth; height = metrics.contentHeight; - return (await sendDebugCommand("Page.captureScreenshot", { + const result = (await sendDebugCommand("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, clip: { x: 0, y: 0, width, height, scale: 1 }, })) as CdpCaptureScreenshotResult; + if ( + result.data && + !hasPaintedPixels(target.contents.decodePng(Buffer.from(result.data, "base64"))) + ) { + throw new Error("Page.captureScreenshot returned no painted frame"); + } + return result; }); } catch (error) { if (isScreenshotNoFrameError(error)) { From f81bc2b5a38e13d0db5b78f3b5b3e14608788260 Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:59:03 +0700 Subject: [PATCH 155/160] Keep the prompt and whole reply when an empty chat reconnects mid-reply (#9723) Recover missing timeline rows when a chat was empty before disconnect and live reply rows arrive before history catch-up. Keep the replica cache at schema version 1. Closes #9650. Supersedes #9626. Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> --- docs/timeline-sync.md | 14 +- .../browser/agent-message-submission.spec.ts | 10 + .../e2e/browser/agent-timeline-resume.spec.ts | 29 ++ .../e2e/support/helpers/timeline-resume.ts | 98 ++++++ packages/app/src/timeline/replica.test.ts | 315 ++++++++++++++++++ .../timeline/session-stream-reducers.test.ts | 32 +- .../src/timeline/session-stream-reducers.ts | 21 +- .../app/src/timeline/timeline-sync-plan.ts | 15 + .../src/timeline/viewed-timeline-sync.test.ts | 93 +++++- .../app/src/timeline/viewed-timeline-sync.ts | 15 +- 10 files changed, 621 insertions(+), 21 deletions(-) diff --git a/docs/timeline-sync.md b/docs/timeline-sync.md index 33a89123da..b0643b72e5 100644 --- a/docs/timeline-sync.md +++ b/docs/timeline-sync.md @@ -49,9 +49,17 @@ Large unbounded timeline responses can exceed relay frame limits, so catch-up us Page limits are projected-item targets. A tool call lifecycle is one projected item even if it spans many source sequence numbers, and assistant/reasoning chunks are merged before counting. The response carries `seqStart`, `seqEnd`, `sourceSeqRanges`, and `collapsed` so clients can advance sequence cursors without rendering delta rows. -When live delivery detects a sequence gap, the app fetches `direction: "after"`. If the daemon -responds with `hasNewer: true`, the app immediately fetches the next page from `endCursor`. Gap -recovery is complete only when `hasNewer: false`. +When live delivery detects a sequence gap, the app fetches `direction: "after"` its end cursor. If +the daemon responds with `hasNewer: true`, the app immediately fetches the next page from +`endCursor`. Gap recovery is complete only when `hasNewer: false`. + +A chat that was empty when it last caught up has no end cursor to compare a live row against. Such a +row starts coverage only if it is the epoch's first row, seq 1. A later row means the chat missed the +rows before it, such as a prompt sent while the app was offline, so the app drops it and recovers +after seq 0. Coverage started at that later row would make the resume page look already applied, and +the chat and its replica cache would keep only the end of the reply. A recovery that waits behind a +running catch-up starts after whatever that catch-up applied, because the app applies a forward page +row by row and an older cursor repeats rows. Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog. diff --git a/packages/app/e2e/browser/agent-message-submission.spec.ts b/packages/app/e2e/browser/agent-message-submission.spec.ts index 24f26f1c44..20c8722793 100644 --- a/packages/app/e2e/browser/agent-message-submission.spec.ts +++ b/packages/app/e2e/browser/agent-message-submission.spec.ts @@ -527,7 +527,17 @@ async function expectHiddenStreamingSubmissionOrderAfterWorkspaceEviction( expect(gate.getClientRequestCount("agent.timeline.set_subscription.request")).toBe( subscriptionRequests, ); + const requestsBeforeRelease = rememberTimelineRequestCounts(gate, target.agentId); gate.releaseHeldAgentStreamEvent("turn_started"); + // The chat never saw the hidden prompt's live row, so the reply's first row is a gap. + // The chat recovers the missing rows once, while its workspace is still evicted. + await expect + .poll(() => gate.getTimelineRequestCount("after", target.agentId)) + .toBe(requestsBeforeRelease.after + 1); + await gate.waitForServerMessage( + "fetch_agent_timeline_response", + gate.getClientRequestCount("fetch_agent_timeline_request"), + ); const requestsBeforeReturn = rememberTimelineRequestCounts(gate, target.agentId); await waitForWorkspaceInSidebar(page, { serverId: getServerId(), diff --git a/packages/app/e2e/browser/agent-timeline-resume.spec.ts b/packages/app/e2e/browser/agent-timeline-resume.spec.ts index c3054b2ebc..065534ad47 100644 --- a/packages/app/e2e/browser/agent-timeline-resume.spec.ts +++ b/packages/app/e2e/browser/agent-timeline-resume.spec.ts @@ -14,6 +14,8 @@ import { answerFreshnessCheck, commitTimelineTurnsWhileDisconnected, disconnectViewedTimeline, + expectEmptyChatSynced, + expectPromptAndWholeReply, expectResumeAnsweredWithoutFetch, expectResumeOverflowFallsBackToOneTail, hideTabAndReturn, @@ -22,7 +24,11 @@ import { restoreUnchangedViewedTimeline, restoreViewedTimelineHoldingCatchUp, restoreViewedTimelineWithHeldResponse, + restoreViewedTimelineWithLiveRowsFirst, reopenWithFreshnessCheckUnanswered, + seedStreamingReplyAgent, + sendPromptWhileDisconnected, + stopStreamingReply, waitForResumeAnswer, reopenAppWatchingForUpdatingToast, watchForUpdatingToast, @@ -147,4 +153,27 @@ test.describe("Agent timeline resume", () => { await agent.cleanup(); } }); + + test("an empty chat that reconnects mid-reply keeps the prompt and the whole reply", async ({ + page, + }) => { + test.setTimeout(120_000); + const gate = await installDaemonWebSocketGate(page); + const agent = await seedStreamingReplyAgent(); + try { + await openAgentTimeline(page, agent); + await expectEmptyChatSynced(page, gate); + await disconnectViewedTimeline(page, gate); + await sendPromptWhileDisconnected(agent); + await restoreViewedTimelineWithLiveRowsFirst(gate); + const reply = await stopStreamingReply(agent); + await expectPromptAndWholeReply(page, agent, reply); + + await page.reload(); + await expectPromptAndWholeReply(page, agent, reply); + } finally { + gate.restore(); + await agent.cleanup(); + } + }); }); diff --git a/packages/app/e2e/support/helpers/timeline-resume.ts b/packages/app/e2e/support/helpers/timeline-resume.ts index 028ab90f03..7477290440 100644 --- a/packages/app/e2e/support/helpers/timeline-resume.ts +++ b/packages/app/e2e/support/helpers/timeline-resume.ts @@ -1,5 +1,6 @@ import { expect, type Page } from "@playwright/test"; import type { installDaemonWebSocketGate } from "./daemon-websocket-gate"; +import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent"; import { readReplicaCache } from "./replica-cache-storage"; import type { LongTimelineAgent } from "./timeline-pagination"; import { @@ -241,3 +242,100 @@ export async function restoreUnchangedViewedTimeline( gate.restore(); await expectReconnectingToastGone(page); } + +export interface StreamingReplyAgent extends MockAgentWorkspace { + prompt: string; +} + +/** + * A mock agent with no history whose reply streams one word every 100 ms. At 2,000 words the + * reply outlasts the test's timeout, so it is still streaming however long the app takes to + * reconnect. The test ends the turn with {@link stopStreamingReply}. + */ +export async function seedStreamingReplyAgent(): Promise { + const reply = Array.from({ length: 2_000 }, (_unused, index) => `word${index}`).join(" "); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "reply-reconnect-", + title: "Reply through reconnect", + featureValues: { + mockStreamingAssistantResponse: reply, + mockStreamingAssistantIntervalMs: 100, + }, + }); + return { + ...agent, + prompt: "stream through a reconnect", + cleanup: async () => { + await agent.client.cancelAgent(agent.agentId).catch(() => undefined); + await agent.cleanup(); + }, + }; +} + +interface TimelineReader { + fetchAgentTimeline( + agentId: string, + request: { direction: "tail"; limit: number }, + ): Promise<{ entries: Array<{ item: { type: string; text?: string } }> }>; +} + +async function readDaemonReply(agent: StreamingReplyAgent): Promise { + const timeline = await (agent.client as unknown as TimelineReader).fetchAgentTimeline( + agent.agentId, + { direction: "tail", limit: 0 }, + ); + return timeline.entries + .map(({ item }) => (item.type === "assistant_message" ? (item.text ?? "") : "")) + .join(""); +} + +/** Waits for the empty chat's first catch-up, so the chat is synced with no range. */ +export async function expectEmptyChatSynced(page: Page, gate: DaemonWebSocketGate): Promise { + await gate.waitForServerMessage(TIMELINE_RESPONSE); + await expect(page.getByTestId("agent-chat-scroll").filter({ visible: true })).toHaveCount(1, { + timeout: 30_000, + }); +} + +/** Another client sends the prompt, and the reply starts, while the chat is away. */ +export async function sendPromptWhileDisconnected(agent: StreamingReplyAgent): Promise { + await agent.client.sendAgentMessage(agent.agentId, agent.prompt); + await expect.poll(() => readDaemonReply(agent), { timeout: 30_000 }).toContain("word10"); +} + +/** Reconnects with live reply chunks reaching the chat before the catch-up page that holds them. */ +export async function restoreViewedTimelineWithLiveRowsFirst( + gate: DaemonWebSocketGate, +): Promise { + gate.holdNextClientRequest(TIMELINE_REQUEST); + const chunksBeforeReconnect = gate.getAgentStreamItemCount("assistant_message"); + gate.restore(); + await gate.waitForHeldClientRequest(); + await gate.waitForAgentStreamItem("assistant_message", chunksBeforeReconnect + 5); + gate.releaseHeldClientRequest(); +} + +/** Stops the turn and returns the reply as the daemon recorded it. */ +export async function stopStreamingReply(agent: StreamingReplyAgent): Promise { + await agent.client.cancelAgent(agent.agentId); + await agent.client.waitForFinish(agent.agentId, 30_000); + const reply = (await readDaemonReply(agent)).trim(); + expect(reply).toMatch(/^word0 word1 word2 .* word10 /); + return reply; +} + +export async function expectPromptAndWholeReply( + page: Page, + agent: StreamingReplyAgent, + reply: string, +): Promise { + const chat = page.getByTestId("agent-chat-scroll").filter({ visible: true }).first(); + await expect(chat.getByText(agent.prompt, { exact: true })).toBeVisible({ timeout: 30_000 }); + await expect + .poll( + async () => + (await chat.getByTestId("assistant-message").allInnerTexts()).map((text) => text.trim()), + { timeout: 30_000 }, + ) + .toEqual([reply]); +} diff --git a/packages/app/src/timeline/replica.test.ts b/packages/app/src/timeline/replica.test.ts index 13046701ee..2254aacf5d 100644 --- a/packages/app/src/timeline/replica.test.ts +++ b/packages/app/src/timeline/replica.test.ts @@ -6,6 +6,7 @@ import { type SqliteValue, } from "@/runtime/replica-cache/row-store-sqlite"; import { afterEach, describe, expect, it } from "vitest"; +import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages"; import type { CachedTimeline } from "@/runtime/replica-cache"; import { @@ -17,6 +18,8 @@ import { } from "@/stores/session-store"; import { useCreateFlowStore, type PendingCreateAttempt } from "@/stores/create-flow-store"; import type { StreamItem } from "@/types/stream"; +import type { AgentStreamReducerEvent } from "./session-stream-reducers"; +import type { ProjectedTimelineForwardFetchPlan } from "./timeline-sync-plan"; import { reduceTurnLiveness, type TurnLivenessTransition } from "./turn-liveness"; import { createTimelineReplica, @@ -1379,6 +1382,318 @@ describe("create handoff lifetime", () => { }); }); +describe("a chat that was empty when it went offline", () => { + const EPOCH = "epoch-1"; + const PROMPT = "stream through a reconnect"; + const THOUGHT = "Thinking before the reply."; + const TURN_ID = "turn-1"; + const TIMESTAMP = "2026-10-31T10:00:00.000Z"; + + /** The daemon's timeline: one row per flushed chunk, read back as projected pages. */ + class DaemonTimeline { + private readonly rows: Array<{ seq: number; item: AgentTimelineItem }> = []; + + record(timelineItem: AgentTimelineItem): AgentStreamReducerEvent { + const seq = this.rows.length + 1; + this.rows.push({ seq, item: timelineItem }); + return { + event: { type: "timeline", provider: "mock", turnId: TURN_ID, item: timelineItem }, + seq, + epoch: EPOCH, + timestamp: new Date(TIMESTAMP), + }; + } + + page(request: ProjectedTimelineForwardFetchPlan): TimelineResponsePayload { + const maxSeq = this.rows.at(-1)?.seq ?? 0; + const after = request.direction === "after" ? request.cursor.seq : 0; + const entries = this.projected().filter((entry) => entry.seqEnd > after); + const first = entries[0]; + const startSeq = request.direction === "after" ? after + 1 : first?.seqStart; + return { + requestId: `${request.direction}-${after}`, + agentId: AGENT_ID, + agent: null, + direction: request.direction, + projection: "projected", + reset: false, + epoch: EPOCH, + window: { minSeq: this.rows[0]?.seq ?? 0, maxSeq, nextSeq: maxSeq + 1 }, + startCursor: first && startSeq !== undefined ? { epoch: EPOCH, seq: startSeq } : null, + endCursor: first ? { epoch: EPOCH, seq: maxSeq } : null, + entries, + error: null, + hasNewer: false, + hasOlder: after > 0, + staleCursor: false, + gap: false, + }; + } + + /** Contiguous reply and thought chunks read back as one row, like the daemon's projection. */ + private projected(): TimelineResponsePayload["entries"] { + const entries: TimelineResponsePayload["entries"] = []; + for (const { seq, item: row } of this.rows) { + const previous = entries.at(-1); + const continues = + previous !== undefined && + ((row.type === "assistant_message" && + previous.item.type === "assistant_message" && + previous.item.messageId === row.messageId) || + (row.type === "reasoning" && previous.item.type === "reasoning")); + if ( + continues && + (previous.item.type === "assistant_message" || previous.item.type === "reasoning") && + (row.type === "assistant_message" || row.type === "reasoning") + ) { + previous.item = { ...previous.item, text: `${previous.item.text}${row.text}` }; + previous.seqEnd = seq; + previous.sourceSeqRanges = [{ startSeq: previous.seqStart, endSeq: seq }]; + previous.collapsed = [ + row.type === "assistant_message" ? "assistant_merge" : "reasoning_merge", + ]; + continue; + } + entries.push({ + provider: "mock", + item: row, + timestamp: TIMESTAMP, + seqStart: seq, + seqEnd: seq, + sourceSeqRanges: [{ startSeq: seq, endSeq: seq }], + collapsed: [], + turnId: TURN_ID, + }); + } + return entries; + } + } + + interface PendingFetch { + request: ProjectedTimelineForwardFetchPlan; + /** Delivers a page the way the host runtime does: queued live chunks first, then the page. */ + deliver(page: TimelineResponsePayload): void; + } + + function openChat(storage: TimelineReplicaStorage) { + const fetches: PendingFetch[] = []; + const errors: unknown[] = []; + const fetch = (request: ProjectedTimelineForwardFetchPlan) => + new Promise<{ hasNewer: boolean; endCursor: { epoch: string; seq: number } | null }>( + (resolve) => { + fetches.push({ + request, + deliver: (page) => { + owner.flushStreamAgent(AGENT_ID); + owner.applyTimelineResponse(page); + resolve({ hasNewer: page.hasNewer, endCursor: page.endCursor }); + }, + }); + }, + ); + const replica = createTimelineReplica({ + serverId: SERVER_ID, + storage, + prepareAgent: async () => undefined, + }); + const owner = createViewedTimelineOwner({ + serverId: SERVER_ID, + replica, + replaceDemandedAgentIds: () => undefined, + drainQueuedAgentMessage: () => undefined, + applyTurnLiveness: () => undefined, + ports: { + canCheckFreshness: () => true, + observe: () => ({ ready: Promise.resolve(), release: async () => undefined }), + readCursor: (agentId) => { + const timeline = selectAgentTimelineState( + useSessionStore.getState().sessions[SERVER_ID], + agentId, + ); + return timeline.status === "synced" && timeline.range + ? { epoch: timeline.range.epoch, endSeq: timeline.range.endSeq } + : undefined; + }, + fetchPage: (_agentId, request) => fetch(request), + fetchLatestTail: () => + fetch({ direction: "tail", limit: 40, projection: "projected", wholeTurns: true }), + reportError: (error) => errors.push(error), + }, + }); + owner.setConnected(true); + owner.replaceVisibleAgentIds("test", [AGENT_ID]); + return { + owner, + async nextFetch(): Promise { + await expect.poll(() => fetches.length).toBeGreaterThan(0); + return fetches.shift()!; + }, + live(event: AgentStreamReducerEvent): void { + owner.applyStreamEvent(AGENT_ID, event); + owner.flushStreamAgent(AGENT_ID); + }, + /** Answers every catch-up the chat still asks for until it reports itself current. */ + async settle(daemon: DaemonTimeline): Promise { + for (let turn = 0; turn < 20; turn += 1) { + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(errors).toEqual([]); + const next = fetches.shift(); + if (next) next.deliver(daemon.page(next.request)); + else if (owner.getAgentTimelineStatus(AGENT_ID) === "ready") return; + } + throw new Error("The chat never caught up"); + }, + }; + } + + function rows(): Array<{ kind: StreamItem["kind"]; text: string }> { + const session = useSessionStore.getState().sessions[SERVER_ID]; + return [ + ...(session?.agentStreamTail.get(AGENT_ID) ?? []), + ...(session?.agentStreamHead.get(AGENT_ID) ?? []), + ].map((entry) => ({ + kind: entry.kind, + text: "text" in entry && typeof entry.text === "string" ? entry.text : "", + })); + } + + const reply = (words: number) => + Array.from({ length: words }, (_unused, index) => `word${index}`).join(" "); + const chunk = (index: number) => `${index === 0 ? "" : " "}word${index}`; + const replyChunk = (index: number): AgentTimelineItem => ({ + type: "assistant_message", + text: chunk(index), + messageId: "reply-1", + }); + + /** + * Opens the chat while its timeline is empty, then drops the connection while the prompt, + * an optional thought and the first three reply chunks are recorded. + */ + async function goOfflineWhileTheReplyStarts(input: { + reasoning: boolean; + storage: TimelineReplicaStorage; + }) { + useSessionStore.getState().initializeSession(SERVER_ID, null); + const daemon = new DaemonTimeline(); + const chat = openChat(input.storage); + const opened = await chat.nextFetch(); + opened.deliver(daemon.page(opened.request)); + expect( + selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID), + ).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" }); + + chat.owner.setConnected(false); + daemon.record({ type: "user_message", text: PROMPT, messageId: "prompt-1" }); + if (input.reasoning) daemon.record({ type: "reasoning", text: THOUGHT }); + for (const index of [0, 1, 2]) daemon.record(replyChunk(index)); + chat.owner.setConnected(true); + const catchUp = await chat.nextFetch(); + return { daemon, chat, catchUp }; + } + + function expectedRows(reasoning: boolean, words: number) { + return [ + { kind: "user_message", text: PROMPT }, + ...(reasoning ? [{ kind: "thought", text: THOUGHT }] : []), + { kind: "assistant_message", text: reply(words) }, + ]; + } + + /** A saved range that starts after the prompt claims history the chat never received. */ + function expectCoverageFromTheFirstRow(commits: CachedTimeline[]): void { + expect(commits.map((commit) => commit.range?.startSeq ?? 1)).toEqual(commits.map(() => 1)); + } + + it.each([true, false])( + "keeps the prompt and the whole reply when live chunks arrive before a page that holds them (reasoning=%s)", + async (reasoning) => { + const commits: CachedTimeline[] = []; + const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({ + reasoning, + storage: { + readTimeline: async () => undefined, + commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline), + }, + }); + try { + chat.live(daemon.record(replyChunk(3))); + chat.live(daemon.record(replyChunk(4))); + catchUp.deliver(daemon.page(catchUp.request)); + chat.live(daemon.record(replyChunk(5))); + await chat.settle(daemon); + + expect(rows()).toEqual(expectedRows(reasoning, 6)); + expectCoverageFromTheFirstRow(commits); + } finally { + chat.owner.dispose(); + } + + // The saved chat paints the same rows after a reload. + const saved = commits.at(-1); + useSessionStore.getState().clearSession(SERVER_ID); + useSessionStore.getState().initializeSession(SERVER_ID, null); + const reopened = createOwner({ + readTimeline: async () => saved, + commitTimeline: () => undefined, + }); + try { + reopened.replaceVisibleAgentIds("test", [AGENT_ID]); + await expect.poll(rows).toEqual(expectedRows(reasoning, 6)); + } finally { + reopened.dispose(); + } + }, + ); + + it("keeps the prompt when the page already holds a chunk the chat has not seen live", async () => { + const commits: CachedTimeline[] = []; + const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({ + reasoning: true, + storage: { + readTimeline: async () => undefined, + commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline), + }, + }); + try { + chat.live(daemon.record(replyChunk(3))); + const notYetLive = daemon.record(replyChunk(4)); + catchUp.deliver(daemon.page(catchUp.request)); + chat.live(notYetLive); + chat.live(daemon.record(replyChunk(5))); + await chat.settle(daemon); + + expect(rows()).toEqual(expectedRows(true, 6)); + expectCoverageFromTheFirstRow(commits); + } finally { + chat.owner.dispose(); + } + }); + + it("finishes the reply when its last chunks arrive while an older page is in flight", async () => { + const commits: CachedTimeline[] = []; + const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({ + reasoning: true, + storage: { + readTimeline: async () => undefined, + commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline), + }, + }); + try { + const olderPage = daemon.page(catchUp.request); + chat.live(daemon.record(replyChunk(3))); + chat.live(daemon.record(replyChunk(4))); + catchUp.deliver(olderPage); + await chat.settle(daemon); + + expect(rows()).toEqual(expectedRows(true, 5)); + expectCoverageFromTheFirstRow(commits); + } finally { + chat.owner.dispose(); + } + }); +}); + function createSqliteCache() { const database = new DatabaseSync(":memory:"); let beforeRead = async () => {}; diff --git a/packages/app/src/timeline/session-stream-reducers.test.ts b/packages/app/src/timeline/session-stream-reducers.test.ts index 0e401ad7a0..45b4e293dd 100644 --- a/packages/app/src/timeline/session-stream-reducers.test.ts +++ b/packages/app/src/timeline/session-stream-reducers.test.ts @@ -53,6 +53,7 @@ it.each([false, true])( (hasAuthoritativeBaseline) => { let head: StreamItem[] = []; let tail: StreamItem[] = []; + let cursor: TimelineCursor | undefined; for (const [index, turnId] of ["turn-1", "turn-2"].entries()) { const result = processAgentStreamEvent({ event: { @@ -65,12 +66,13 @@ it.each([false, true])( epoch: "epoch-1", currentTail: tail, currentHead: head, - currentCursor: undefined, + currentCursor: cursor, timestamp: new Date(1000), hasAuthoritativeBaseline, }); head = result.head; tail = result.tail; + cursor = result.cursor ?? cursor; } expect([...tail, ...head]).toMatchObject([ { kind: "thought", text: "turn-1", turnId: "turn-1" }, @@ -2848,7 +2850,7 @@ describe("processTimelineResponse", () => { ], currentTail: [], currentHead: [], - currentCursor: undefined, + currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 }, }); expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([ "First paragraph.\n\nSecond paragraph.", @@ -3677,6 +3679,7 @@ describe("processAgentStreamEvent", () => { event: makeAssistantTimelineEvent("[System Error] failed"), epoch: "timeline-1", seq: 42, + currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 }, }); expect(result.head).toEqual([ @@ -3897,6 +3900,24 @@ describe("processAgentStreamEvent", () => { }); }); + it("catches up from the first row when a chat that was empty receives a later row", () => { + const result = processAgentStreamEvent({ + ...baseStreamInput, + event: makeTimelineEvent("word3"), + seq: 6, + epoch: "epoch-1", + currentCursor: undefined, + }); + + expect(result).toMatchObject({ + head: [], + changedHead: false, + cursor: null, + cursorChanged: false, + sideEffects: [{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 0 } }], + }); + }); + it("renders a live row over painted items without creating an authoritative cursor", () => { const result = processAgentStreamEvent({ ...baseStreamInput, @@ -4087,7 +4108,7 @@ describe("processAgentStreamEvents", () => { ], currentTail: [], currentHead: [], - currentCursor: undefined, + currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 }, }); expect(result.changedTail).toBe(false); @@ -4261,6 +4282,7 @@ describe("processAgentStreamEvents", () => { currentTail: [], currentHead: [], currentCursor: undefined, + hasAuthoritativeBaseline: false, timestamp: new Date("2026-05-02T10:00:00.186Z"), }); @@ -4462,7 +4484,7 @@ describe("createAgentStreamReducerQueue", () => { const scheduler = createManualScheduler(); let currentTail: StreamItem[] = []; let currentHead: StreamItem[] = []; - let currentCursor: TimelineCursor | undefined; + let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 }; const queue = createAgentStreamReducerQueue({ getSnapshot: () => ({ @@ -4505,7 +4527,7 @@ describe("createAgentStreamReducerQueue", () => { expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]); expect(currentCursor).toEqual({ epoch: "epoch-1", - startSeq: 2, + startSeq: 1, endSeq: 4, }); }); diff --git a/packages/app/src/timeline/session-stream-reducers.ts b/packages/app/src/timeline/session-stream-reducers.ts index a46ec8188f..1eec63ed9a 100644 --- a/packages/app/src/timeline/session-stream-reducers.ts +++ b/packages/app/src/timeline/session-stream-reducers.ts @@ -289,7 +289,10 @@ function classifySessionTimelineSeq({ seq: number; }): SessionTimelineSeqDecision { if (!cursor) { - return "init"; + // A synced chat without coverage was empty when it last caught up. Only an epoch's + // first row can start coverage; a later row means rows before it were missed, for + // example while offline, and a cursor started there would hide them from catch-up. + return seq === 1 ? "init" : "gap"; } if (cursor.epoch !== epoch) { return "drop_epoch"; @@ -1543,14 +1546,14 @@ function processTimelineSequencingGate(input: { return { ...base, shouldApplyStreamEvent: false, - sideEffects: currentCursor - ? [ - { - type: "catch_up", - cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }, - }, - ] - : [], + sideEffects: [ + { + type: "catch_up", + cursor: currentCursor + ? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } + : { epoch, endSeq: 0 }, + }, + ], }; } if (decision === "drop_epoch" && seq === 1) { diff --git a/packages/app/src/timeline/timeline-sync-plan.ts b/packages/app/src/timeline/timeline-sync-plan.ts index b66de16941..8aa2dc5a35 100644 --- a/packages/app/src/timeline/timeline-sync-plan.ts +++ b/packages/app/src/timeline/timeline-sync-plan.ts @@ -64,6 +64,21 @@ export function planTimelineResumeFetch( : planTimelineTailFetch(); } +/** + * A catch-up that waited behind another starts after the rows applied meanwhile. A forward + * page is applied row by row, so asking again for rows the chat already holds repeats them. + */ +export function planTimelineCatchUpPastApplied( + request: ProjectedTimelineForwardFetchPlan, + applied: { epoch: string; endSeq: number } | undefined, +): ProjectedTimelineForwardFetchPlan { + if (request.direction !== "after" || !applied) return request; + if (applied.epoch !== request.cursor.epoch || applied.endSeq <= request.cursor.seq) { + return request; + } + return planTimelineCatchUpAfter({ epoch: applied.epoch, seq: applied.endSeq }); +} + export function planTimelineOlderFetch(cursor: TimelineSyncCursor) { return { direction: "before", diff --git a/packages/app/src/timeline/viewed-timeline-sync.test.ts b/packages/app/src/timeline/viewed-timeline-sync.test.ts index d61581cc73..6550350829 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.test.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.test.ts @@ -441,6 +441,96 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); }); +test("a gap parked behind a running tail resumes after the rows that tail applied", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + const tail = await world.nextFetch("agent-a"); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 }); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 7 }); + tail.respond({ hasNewer: false, seq: 7 }); + + const recovery = await world.nextFetch("agent-a"); + expect(recovery.request).toEqual({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 7 }, + limit: 40, + projection: "projected", + wholeTurns: true, + }); + recovery.respond({ hasNewer: false, seq: 7 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + +test("a chat without coverage that recovers a gap loads the latest tail when history overflows a page", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + const tail = await world.nextFetch("agent-a"); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 }); + tail.respond({ hasNewer: false, seq: 0 }); + + const recovery = await world.nextFetch("agent-a"); + expect(recovery.request).toEqual({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 0 }, + limit: 40, + projection: "projected", + wholeTurns: true, + }); + recovery.respond({ hasNewer: true, seq: 40 }); + + const fallback = await world.nextFetch("agent-a"); + expect(fallback.request).toEqual({ + direction: "tail", + limit: 40, + projection: "projected", + wholeTurns: true, + }); + fallback.respond({ hasNewer: false, seq: 90 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + +test("a recovery's follow-up page starts after rows another fetch applied meanwhile", async () => { + const world = new TimelineWorld(); + world.sync.setConnected(true); + world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); + (await world.nextMembership()).succeed(); + (await world.nextFetch("agent-a")).respond({ hasNewer: false, seq: 0 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 }); + const firstPage = await world.nextFetch("agent-a"); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 40 }); + firstPage.respond({ hasNewer: true, seq: 40 }); + const latestTail = await world.nextFetch("agent-a"); + expect(latestTail.request.direction).toBe("tail"); + + world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 40 }); + const recovery = await world.nextFetch("agent-a"); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 300 }); + latestTail.respond({ hasNewer: false, seq: 300 }); + recovery.respond({ hasNewer: true, seq: 80 }); + + const followUp = await world.nextFetch("agent-a"); + expect(followUp.request).toEqual({ + direction: "after", + cursor: { epoch: "epoch-agent-a", seq: 300 }, + limit: 40, + projection: "projected", + wholeTurns: true, + }); + followUp.respond({ hasNewer: false, seq: 300 }); + await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); + world.sync.dispose(); +}); + test("reports a chat current only once its parked follow-up page completes", async () => { const world = new TimelineWorld(); world.sync.setConnected(true); @@ -885,7 +975,8 @@ test("gap recovery supersedes completed catch-up and pages through the current t const membership = await world.nextMembership(); membership.succeed(); const initial = await world.nextFetch("agent-a"); - initial.respond({ hasNewer: false }); + world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 }); + initial.respond({ hasNewer: false, seq: 10 }); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 }); diff --git a/packages/app/src/timeline/viewed-timeline-sync.ts b/packages/app/src/timeline/viewed-timeline-sync.ts index d46b67005d..b6423de9c3 100644 --- a/packages/app/src/timeline/viewed-timeline-sync.ts +++ b/packages/app/src/timeline/viewed-timeline-sync.ts @@ -1,5 +1,6 @@ import { planTimelineCatchUpAfter, + planTimelineCatchUpPastApplied, planTimelineResumeFetch, type ProjectedTimelineForwardFetchPlan, } from "./timeline-sync-plan"; @@ -741,7 +742,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed await fetchUntilCurrent( agentId, generation, - planTimelineCatchUpAfter(page.endCursor), + planTimelineCatchUpPastApplied( + planTimelineCatchUpAfter(page.endCursor), + ports.readCursor(agentId), + ), false, ); return; @@ -819,7 +823,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed ensureCacheLoaded(agentId); return; } - const nextRequest = request ?? planTimelineResumeFetch(ports.readCursor(agentId)); + const applied = ports.readCursor(agentId); + const nextRequest = request + ? planTimelineCatchUpPastApplied(request, applied) + : planTimelineResumeFetch(applied); const current = catchUps.get(agentId); const decision = decideCatchUp({ current, request: nextRequest, supersede }); if (decision === "keep-and-park") { @@ -833,11 +840,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed catchUpGenerations.set(agentId, generation); catchUps.set(agentId, { generation, status: "running", request: nextRequest }); pendingCatchUps.delete(agentId); + // A gap recovery pages forward to keep the coverage it extends. Without coverage there is + // nothing to keep, so an overflowing page falls back to the latest tail, as a resume does. void fetchUntilCurrent( agentId, generation, nextRequest, - request === undefined && nextRequest.direction === "after", + nextRequest.direction === "after" && (request === undefined || applied === undefined), ); }; From 4f2fbe18afaa25d6afcf7ca89fc5455250fddde9 Mon Sep 17 00:00:00 2001 From: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:10:41 +0000 Subject: [PATCH 156/160] fix(archive): bound worktree teardown and stream its output (#9852) Give worktree teardown commands a shared one-minute deadline. Projects can override it with `worktree.teardownTimeoutMs` in `paseo.json`. Drain output so successful teardowns can exceed the old 1 MiB buffer. Bound the output retained for diagnostics. At the deadline, try to terminate the command, close its output streams, and keep the worktree on disk. An exit status of zero in response to the stop signal still counts as a timeout. Closes #9857. Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com> --- packages/protocol/src/paseo-config-schema.ts | 14 ++ ...orkspace-archive-record-scoped.e2e.test.ts | 175 ++++++++++++++---- .../server/workspace-archive-undo.e2e.test.ts | 59 +++++- .../src/utils/paseo-config-file.test.ts | 29 +++ .../utils/worktree-shell-selection.test.ts | 32 +--- packages/server/src/utils/worktree.test.ts | 24 +++ packages/server/src/utils/worktree.ts | 55 ++++-- public-docs/worktrees/index.md | 13 ++ public-docs/worktrees/index.zh-CN.md | 13 ++ 9 files changed, 343 insertions(+), 71 deletions(-) diff --git a/packages/protocol/src/paseo-config-schema.ts b/packages/protocol/src/paseo-config-schema.ts index 31935bd796..541f876229 100644 --- a/packages/protocol/src/paseo-config-schema.ts +++ b/packages/protocol/src/paseo-config-schema.ts @@ -47,6 +47,9 @@ export const PaseoWorktreeConfigRawSchema = z .object({ setup: PaseoLifecycleCommandRawSchema.optional(), teardown: PaseoLifecycleCommandRawSchema.optional(), + // Checked by WorktreeConfigSchema, where an invalid value falls back to the default, so it + // never stops paseo.json from being edited or sent to the app. + teardownTimeoutMs: z.unknown().optional(), terminals: z.unknown().optional(), servicePorts: PaseoServicePortAllocationSchema.optional(), }) @@ -79,9 +82,20 @@ export const PaseoConfigRawSchema = z }) .passthrough(); +// Node timers can't wait longer than this; a longer delay fires at once. +const MAX_TIMER_DELAY_MS = 2_147_483_647; + export const WorktreeConfigSchema = PaseoWorktreeConfigRawSchema.extend({ setup: z.unknown().optional().transform(normalizeLifecycleCommands), teardown: z.unknown().optional().transform(normalizeLifecycleCommands), + // Its own catch, so an invalid limit doesn't drop the commands with the rest of the worktree. + teardownTimeoutMs: z + .number() + .int() + .positive() + .max(MAX_TIMER_DELAY_MS) + .optional() + .catch(undefined), }) .passthrough() .catch({ setup: [], teardown: [] }); diff --git a/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts b/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts index d10a098d79..bd243ced8e 100644 --- a/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-record-scoped.e2e.test.ts @@ -1,5 +1,13 @@ -import { execFile, execFileSync, spawn } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { execFile, execFileSync } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -569,7 +577,130 @@ test.skipIf(process.platform === "win32")( 60000, ); +async function createWorktreeWithTeardown( + slug: string, + worktreeConfig: { teardown: string; teardownTimeoutMs?: number }, +): Promise<{ workspaceId: string; worktreePath: string }> { + const repoDir = createGitRepo(); + writeFileSync(path.join(repoDir, "paseo.json"), JSON.stringify({ worktree: worktreeConfig })); + execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" }); + execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add teardown"], { + cwd: repoDir, + stdio: "pipe", + }); + const result = await ctx.client.createWorkspace({ + source: { kind: "worktree", cwd: repoDir, worktreeSlug: slug, baseBranch: "main" }, + }); + const workspace = result.workspace; + if (!workspace?.workspaceDirectory) { + throw new Error(result.error ?? "Failed to create worktree workspace"); + } + return { workspaceId: workspace.id, worktreePath: workspace.workspaceDirectory }; +} + +function isProcessRunning(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + test.skipIf(process.platform === "win32")( + "a paseo.json teardown that never exits is stopped and the archive answers", + async () => { + const pidFile = path.join(makeTempDir("hanging-teardown-"), "sleep.pid"); + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("hanging-teardown", { + teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`, + teardownTimeoutMs: 2000, + }); + + try { + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true }); + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + await expect.poll(() => isProcessRunning(sleepPid), { timeout: 5000 }).toBe(false); + } finally { + if (existsSync(pidFile)) { + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL"); + } + } + }, + 30000, +); + +test.skipIf(process.platform === "win32")( + "a paseo.json teardown that prints more than 1 MiB still removes the worktree", + async () => { + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("chatty-teardown", { + teardown: `node -e "process.stdout.write('x'.repeat(2 * 1024 * 1024))"`, + }); + + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: false }); + }, + 60000, +); + +test.skipIf(process.platform === "win32")( + "a teardown that handles SIGTERM and exits zero still leaves the worktree", + async () => { + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-trap", { + teardown: `trap 'exit 0' TERM; sleep 5 & wait`, + teardownTimeoutMs: 2000, + }); + + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true }); + }, + 15000, +); + +test.skipIf(process.platform === "win32")( + "the archive answers when an exited teardown shell's child holds its output open", + async () => { + const pidFile = path.join(makeTempDir("teardown-open-output-"), "sleep.pid"); + const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-open-output", { + teardown: `sleep 12 & echo $! > ${JSON.stringify(pidFile)}`, + teardownTimeoutMs: 2000, + }); + + try { + const archive = await ctx.client.archiveWorkspace(workspaceId); + + expect({ + error: archive.error, + workspaceActive: (await activeWorkspaceIds()).has(workspaceId), + worktreeOnDisk: existsSync(worktreePath), + }).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true }); + } finally { + if (existsSync(pidFile)) { + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL"); + } + } + }, + 10000, +); + +test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( "repeating archive removes a residual worktree for an already-archived workspace", async () => { const repoDir = createGitRepo(); @@ -586,42 +717,24 @@ test.skipIf(process.platform === "win32")( throw new Error(result.error ?? "Failed to create worktree workspace"); } - const writerStartedPath = path.join(repoDir, "writer-started"); - const stopWriterPath = path.join(repoDir, "stop-writer"); - const target = path.join( - workspace.workspaceDirectory, - "node_modules/react-native-svg/lib/typescript", - ); - const writer = spawn( - process.execPath, - [ - "-e", - `const fs=require('fs'),path=require('path');const target=${JSON.stringify(target)};const started=${JSON.stringify(writerStartedPath)};const stop=${JSON.stringify(stopWriterPath)};fs.writeFileSync(started,'started');while(!fs.existsSync(stop)){try{fs.mkdirSync(target,{recursive:true});fs.writeFileSync(path.join(target,'active'),String(Date.now()))}catch{}}`, - ], - { stdio: "ignore" }, - ); - const writerExit = new Promise((resolve) => writer.once("exit", () => resolve())); - + const directory = workspace.workspaceDirectory; + const originalMode = statSync(directory).mode & 0o777; + // Deny removal of entries such as .git until the second archive request. + chmodSync(directory, originalMode & ~0o222); try { - await expect.poll(() => existsSync(writerStartedPath), { timeout: 10000 }).toBe(true); - const firstArchive = await ctx.client.archiveWorkspace(workspace.id); expect(firstArchive.error).toBeNull(); expect((await activeWorkspaceIds()).has(workspace.id)).toBe(false); - expect(existsSync(workspace.workspaceDirectory)).toBe(true); - - writeFileSync(stopWriterPath, "stop\n"); - await writerExit; - - const retry = await ctx.client.archiveWorkspace(workspace.id); - - expect(retry.error).toBeNull(); - expect(existsSync(workspace.workspaceDirectory)).toBe(false); + expect(existsSync(directory)).toBe(true); } finally { - writeFileSync(stopWriterPath, "stop\n"); - await writerExit; + if (existsSync(directory)) chmodSync(directory, originalMode); } + + const retry = await ctx.client.archiveWorkspace(workspace.id); + + expect(retry.error).toBeNull(); + expect(existsSync(directory)).toBe(false); }, 60000, ); diff --git a/packages/server/src/server/workspace-archive-undo.e2e.test.ts b/packages/server/src/server/workspace-archive-undo.e2e.test.ts index f68dbc5dd1..1d65afc307 100644 --- a/packages/server/src/server/workspace-archive-undo.e2e.test.ts +++ b/packages/server/src/server/workspace-archive-undo.e2e.test.ts @@ -1,6 +1,14 @@ import { DaemonClient } from "./test-utils/daemon-client.js"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync, writeFileSync, renameSync, mkdirSync } from "node:fs"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + renameSync, + mkdirSync, +} from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, expect, test } from "vitest"; @@ -125,6 +133,55 @@ test.skipIf(process.platform === "win32")( 60000, ); +test.skipIf(process.platform === "win32")( + "an undo during a teardown that never exits returns once the deadline stops it", + async () => { + const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-hang-")); + tempRoots.push(tempRoot); + const repoDir = path.join(tempRoot, "repo"); + const pidFile = path.join(tempRoot, "sleep.pid"); + execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" }); + git(repoDir, ["config", "user.email", "test@getpaseo.local"]); + git(repoDir, ["config", "user.name", "Paseo Test"]); + writeFileSync( + path.join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`, + teardownTimeoutMs: 2000, + }, + }), + ); + git(repoDir, ["add", "paseo.json"]); + git(repoDir, ["-c", "commit.gpgsign=false", "commit", "-m", "hanging teardown"]); + const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent( + repoDir, + "undo-during-hanging-teardown", + ); + try { + const archive = ctx.client.archiveWorkspace(workspaceId); + await expect.poll(() => existsSync(pidFile), { timeout: 15000 }).toBe(true); + await Promise.all([archive, ctx.client.undoWorkspaceArchive(workspaceId)]); + + expect({ + workspaceActive: await isWorkspaceActive(workspaceId), + directoryExists: existsSync(directory), + agentArchived: await isAgentArchived(agentId), + }).toEqual({ workspaceActive: true, directoryExists: true, agentArchived: false }); + } finally { + if (existsSync(pidFile)) { + const sleepPid = Number(readFileSync(pidFile, "utf8").trim()); + try { + process.kill(sleepPid, "SIGKILL"); + } catch { + // Already stopped by the teardown deadline. + } + } + } + }, + 30000, +); + test.skipIf(process.platform === "win32")( "an undo after the archive finished recreates the worktree and its agents", async () => { diff --git a/packages/server/src/utils/paseo-config-file.test.ts b/packages/server/src/utils/paseo-config-file.test.ts index 6a7e43c757..ff77f44bce 100644 --- a/packages/server/src/utils/paseo-config-file.test.ts +++ b/packages/server/src/utils/paseo-config-file.test.ts @@ -14,6 +14,7 @@ import { PaseoConfigRawSchema, getWorktreeSetupCommands, getWorktreeTeardownCommands, + getWorktreeTeardownTimeoutMs, } from "./worktree.js"; import { readPaseoConfigForEdit, @@ -295,6 +296,34 @@ describe("paseo config file substrate", () => { expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean", "npm run reset"]); }); + it("reads the teardown time limit and defaults to one minute", async () => { + expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000); + + for (const teardownTimeoutMs of [1, 300_000, 2_147_483_647]) { + writeFileSync( + join(tempDir, "paseo.json"), + JSON.stringify({ worktree: { teardownTimeoutMs } }), + ); + expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(teardownTimeoutMs); + } + }); + + it.each([0, -1000, 1500.5, 2_147_483_648, "90000", null, true, { ms: 90_000 }])( + "falls back to the default teardown time limit for %j and keeps the commands", + async (teardownTimeoutMs) => { + const config = { worktree: { teardown: "npm run clean", teardownTimeoutMs } }; + writeFileSync(join(tempDir, "paseo.json"), JSON.stringify(config)); + + expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000); + expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean"]); + expect(await readPaseoConfigForEdit(tempDir)).toEqual({ + ok: true, + config, + revision: await statPaseoConfigPath(tempDir), + }); + }, + ); + it("writes pretty JSON with a trailing newline when revision matches", async () => { writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "old" } })); const expectedRevision = await statPaseoConfigPath(tempDir); diff --git a/packages/server/src/utils/worktree-shell-selection.test.ts b/packages/server/src/utils/worktree-shell-selection.test.ts index a17d6cd498..62f34174e4 100644 --- a/packages/server/src/utils/worktree-shell-selection.test.ts +++ b/packages/server/src/utils/worktree-shell-selection.test.ts @@ -5,17 +5,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const execFileMock = vi.hoisted(() => vi.fn()); const spawnProcessMock = vi.hoisted(() => vi.fn()); -vi.mock("child_process", async () => { - const actual = await vi.importActual("child_process"); - return { - ...actual, - execFile: execFileMock, - }; -}); - vi.mock("./spawn.js", async () => { const actual = await vi.importActual("./spawn.js"); return { @@ -42,19 +33,7 @@ describe("worktree shell selection", () => { const originalPlatform = process.platform; beforeEach(() => { - execFileMock.mockReset(); spawnProcessMock.mockReset(); - execFileMock.mockImplementation( - ( - _file: string, - _args: string[], - _options: unknown, - callback?: (error: Error | null, stdout: string, stderr: string) => void, - ) => { - callback?.(null, "", ""); - return {}; - }, - ); spawnProcessMock.mockImplementation(createSpawnChildStub); }); @@ -94,8 +73,8 @@ describe("worktree shell selection", () => { branchName: "main", }); - expect(execFileMock).toHaveBeenCalledTimes(1); - expect(execFileMock).toHaveBeenCalledWith( + expect(spawnProcessMock).toHaveBeenCalledTimes(1); + expect(spawnProcessMock).toHaveBeenCalledWith( "powershell", [ "-NoProfile", @@ -105,11 +84,10 @@ describe("worktree shell selection", () => { "-Command", "Write-Output 'teardown'", ], - expect.objectContaining({ cwd: worktreePath }), - expect.any(Function), + expect.objectContaining({ cwd: worktreePath, shell: false }), ); - const execOptions = execFileMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv }; - expect(execOptions.env?.BASH_ENV).toBeUndefined(); + const spawnOptions = spawnProcessMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv }; + expect(spawnOptions.env?.BASH_ENV).toBeUndefined(); } finally { if (originalBashEnv === undefined) { delete process.env.BASH_ENV; diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index 39f2af09c0..4f0a1d5ef3 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -190,6 +190,30 @@ describe("paseo worktree manager", () => { }); }); + it("retains bounded diagnostic text per teardown output stream", async () => { + const limit = 1024 * 1024; + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + teardown: `node -e "process.stdout.write('x'.repeat(${2 * limit})); process.stderr.write('y'.repeat(${2 * limit}))"`, + }, + }), + ); + + const [result] = await runWorktreeTeardownCommands({ + worktreePath: repoDir, + repoRootPath: repoDir, + branchName: "main", + }); + + expect({ + exitCode: result.exitCode, + stdoutLength: result.stdout.length, + stderrLength: result.stderr.length, + }).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit }); + }); + it("rejects paths that are not under the paseo worktrees root", async () => { const outsidePath = join(tempDir, "outside-paseo-home"); mkdirSync(outsidePath, { recursive: true }); diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 92e70c9e87..98c48e460c 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -146,6 +146,13 @@ export class WorktreeSetupError extends Error { export type WorktreeTeardownCommandResult = WorktreeSetupCommandResult; +// paseo.json can change this with worktree.teardownTimeoutMs. Archive waits for teardown before it +// answers, and the app stops waiting for an archive answer after 60 seconds +// (DEFAULT_SESSION_RPC_TIMEOUT_MS in the client). A teardown that runs to this limit, or to a longer +// one, answers after the app has reported the archive as failed. +const DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS = 60_000; +const MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM = 1024 * 1024; + export class WorktreeTeardownError extends Error { readonly results: WorktreeTeardownCommandResult[]; @@ -281,6 +288,13 @@ export async function getWorktreeTeardownCommands(repoRoot: string): Promise { + return ( + (await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardownTimeoutMs ?? + DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS + ); +} + export async function getWorktreeTerminalSpecs( repoRoot: string, ): Promise { @@ -449,12 +463,14 @@ async function execSetupCommandStreamed(options: { index: number; total: number; signal?: AbortSignal; + maxOutputCharsPerStream?: number; onEvent?: (event: WorktreeSetupCommandProgressEvent) => void; }): Promise { return new Promise((resolvePromise) => { const startedAt = Date.now(); - const stdoutChunks: string[] = []; - const stderrChunks: string[] = []; + const outputChunks: Record<"stdout" | "stderr", string[]> = { stdout: [], stderr: [] }; + const outputLimit = options.maxOutputCharsPerStream ?? Infinity; + const remainingOutputChars = { stdout: outputLimit, stderr: outputLimit }; let settled = false; let termination: Promise | null = null; @@ -463,10 +479,10 @@ async function execSetupCommandStreamed(options: { if (!text) { return; } - if (stream === "stdout") { - stdoutChunks.push(text); - } else { - stderrChunks.push(text); + const retainedText = text.slice(0, remainingOutputChars[stream]); + if (retainedText) { + outputChunks[stream].push(retainedText); + remainingOutputChars[stream] -= retainedText.length; } options.onEvent?.({ type: "output", @@ -485,12 +501,17 @@ async function execSetupCommandStreamed(options: { } settled = true; options.signal?.removeEventListener("abort", abort); - await termination; + if (termination) { + await termination; + // A descendant can keep these pipes open after the shell exits. + child.stdout?.destroy(); + child.stderr?.destroy(); + } const result: WorktreeSetupCommandResult = { command: options.command, cwd: options.cwd, - stdout: stdoutChunks.join(""), - stderr: stderrChunks.join(""), + stdout: outputChunks.stdout.join(""), + stderr: outputChunks.stderr.join(""), exitCode, durationMs: Date.now() - startedAt, }; @@ -529,6 +550,7 @@ async function execSetupCommandStreamed(options: { gracefulTimeoutMs: 1000, forceTimeoutMs: 1000, }); + void finish(null); }; if (options.signal?.aborted) { abort(); @@ -768,17 +790,26 @@ export async function runWorktreeTeardownCommands(options: { }), ); + // One deadline covers every command. Reaching it counts as failure and keeps the worktree. + const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd); + const deadline = AbortSignal.timeout(timeoutMs); const results: WorktreeTeardownCommandResult[] = []; - for (const cmd of teardownCommands) { - const result = await execSetupCommand(cmd, { + for (const [index, cmd] of teardownCommands.entries()) { + const result = await execSetupCommandStreamed({ + command: cmd, cwd: teardownCwd, env: teardownEnv, + index: index + 1, + total: teardownCommands.length, + signal: deadline, + maxOutputCharsPerStream: MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM, }); results.push(result); if (result.exitCode !== 0) { + const reason = deadline.aborted ? `Timed out after ${timeoutMs / 1000}s` : result.stderr; throw new WorktreeTeardownError( - `Worktree teardown command failed: ${cmd}\n${result.stderr}`.trim(), + `Worktree teardown command failed: ${cmd}\n${reason}`.trim(), results, ); } diff --git a/public-docs/worktrees/index.md b/public-docs/worktrees/index.md index faabb2d81f..55eb4de01b 100644 --- a/public-docs/worktrees/index.md +++ b/public-docs/worktrees/index.md @@ -122,6 +122,19 @@ Both fields accept a multiline shell script or an array of commands; commands ru Commands run with the worktree as `cwd`. Use `$PASEO_SOURCE_CHECKOUT_PATH` to reach files in the original checkout (untracked config, local caches, etc). +Teardown commands share a one minute limit. Set `teardownTimeoutMs` to change it, in milliseconds: + +```json +{ + "worktree": { + "teardown": "docker compose down", + "teardownTimeoutMs": 300000 + } +} +``` + +At the limit, Paseo tries to stop the command and its child processes and stops waiting for output. If teardown fails or reaches the limit, the workspace still archives and the worktree stays on disk. `teardownTimeoutMs` accepts whole numbers from 1 to 2147483647. Other values use the default. + ## Scripts and services `scripts` are named commands you can run inside a worktree on demand. Mark one as a _service_ and Paseo supervises it as a long-running process, assigns it a port, and routes HTTP traffic to it through the daemon's reverse proxy. diff --git a/public-docs/worktrees/index.zh-CN.md b/public-docs/worktrees/index.zh-CN.md index cce65fc090..59f4342627 100644 --- a/public-docs/worktrees/index.zh-CN.md +++ b/public-docs/worktrees/index.zh-CN.md @@ -120,6 +120,19 @@ paseo workspace create \ 命令以 worktree 作为 `cwd` 运行。使用 `$PASEO_SOURCE_CHECKOUT_PATH` 访问原始检出中的文件(未跟踪的配置、本地缓存等)。 +teardown 的所有命令共用一分钟的时限。用 `teardownTimeoutMs` 修改它,单位为毫秒: + +```json +{ + "worktree": { + "teardown": "docker compose down", + "teardownTimeoutMs": 300000 + } +} +``` + +达到时限后,Paseo 会尝试停止命令及其子进程,并停止等待输出。如果 teardown 失败或达到时限,工作区仍会归档,worktree 会保留在磁盘上。`teardownTimeoutMs` 接受 1 到 2147483647 之间的整数。其他值使用默认时限。 + ## 脚本与服务 {#scripts-and-services} `scripts` 是可以在 worktree 中按需运行的具名命令。把其中一个标记为 _service_,Paseo 就会把它作为长时间运行的进程进行监管,为它分配端口,并通过 daemon 的反向代理把 HTTP 流量路由给它。 From f1f2509c12f6dcf327d92a39f55364785d6d4caa Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 15:52:41 +0700 Subject: [PATCH 157/160] Keep Android composer taps working after zooming a chat image (#10057) * fix(android): keep composer taps working after pinching an image React Native counted two touches at the start of a pinch but received a native takeover cancellation for just one. Typing could then claim the responder and consume the first toolbar tap. Cancel the active contacts when the gesture handler takes over. * docs(android): describe the chat image fixture for the pinch regression --- docs/mobile-testing.md | 15 ++++ .../lightbox-pinch.android.ad | 15 ++++ .../react-native-gesture-handler+2.32.0.patch | 80 ++++++++++++++++++- 3 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad diff --git a/docs/mobile-testing.md b/docs/mobile-testing.md index 3dbea66676..c61c56ab52 100644 --- a/docs/mobile-testing.md +++ b/docs/mobile-testing.md @@ -49,6 +49,21 @@ restarting the process. It writes snapshots and native failure state under production package. This needs a native rebuild when the Unistyles patch changes; a Metro reload cannot update it. +To check the first Android composer tap after pinch-to-zoom, install the rebuilt +APK and connect it to a chat whose latest assistant message contains a visible +Markdown image. For example, put `picture.png` in the agent workspace and have +the assistant reply with `![Test image](picture.png)`. Set `CHAT_URL` to the +chat's Paseo deep link and run from the repository root: + +```bash +agent-device test packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad \ + --platform android --serial emulator-5554 -e APP_ID=sh.paseo -e "CHAT_URL=$CHAT_URL" +``` + +Use `APP_ID=sh.paseo.debug` for a development build. If the image has different +alt text, pass it with `-e IMAGE_LABEL="..."`. The test pinches the image, closes +it, types in the composer, and checks that a single Attach tap opens Upload file. + For Android keyboard continuity, run the current checkout in the app, open an idle terminal with an empty prompt, hide its keyboard, and run: diff --git a/packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad b/packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad new file mode 100644 index 0000000000..d56b70ea32 --- /dev/null +++ b/packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad @@ -0,0 +1,15 @@ +# CHAT_URL opens a connected chat containing a visible Markdown image with alt text IMAGE_LABEL. +context platform=android timeout=120000 retries=0 +env APP_ID=sh.paseo.debug +env IMAGE_LABEL="Test image" + +open "${APP_ID}" "${CHAT_URL}" +wait "label=\"${IMAGE_LABEL}\"" 30000 +press "label=\"${IMAGE_LABEL}\"" +wait "label=\"Close image\"" 5000 +gesture pinch 1.7 +press "label=\"Close image\"" +press "editable=true" +type "pinch regression" +press "role=\"button\" label=\"Add attachment\"" +wait "label=\"Upload file\"" 3000 diff --git a/patches/react-native-gesture-handler+2.32.0.patch b/patches/react-native-gesture-handler+2.32.0.patch index b6e3a810f1..1a8e6ae60f 100644 --- a/patches/react-native-gesture-handler+2.32.0.patch +++ b/patches/react-native-gesture-handler+2.32.0.patch @@ -152,18 +152,92 @@ index 8d78aea..b84d19e 100644 viewGroup: ViewGroup, coords: FloatArray, diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt -index 629c155..dc0790d 100644 +index 629c155..2efd508 100644 --- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt +++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt -@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: +@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: private val jsGestureHandler: GestureHandler? val rootView: ViewGroup private var shouldIntercept = false + private var wasIntercepting = false private var passingTouch = false ++ private var lastTouch: MotionEvent? = null init { -@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + UiThreadUtil.assertOnUiThread() +@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + } + + fun tearDown() { ++ clearLastTouch() + Log.i( + ReactConstants.TAG, + "[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView", +@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + + override fun onCancel() { + shouldIntercept = true +- val time = SystemClock.uptimeMillis() +- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply { +- action = MotionEvent.ACTION_CANCEL +- } + if (rootView is RootView) { +- rootView.onChildStartedNativeGesture(rootView, event) ++ val cancel = createReactCancelEvent() ++ try { ++ rootView.onChildStartedNativeGesture(rootView, cancel) ++ } finally { ++ cancel.recycle() ++ clearLastTouch() ++ } + } +- event.recycle() + } + } + ++ private fun clearLastTouch() { ++ lastTouch?.recycle() ++ lastTouch = null ++ } ++ ++ private fun createReactCancelEvent(): MotionEvent { ++ val now = SystemClock.uptimeMillis() ++ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) ++ // The enclosing React root already dispatched this event before it reached the ++ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS. ++ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1 ++ val count = touch.pointerCount - if (lifted >= 0) 1 else 0 ++ val properties = Array(count) { MotionEvent.PointerProperties() } ++ val coords = Array(count) { MotionEvent.PointerCoords() } ++ var index = 0 ++ for (pointer in 0 until touch.pointerCount) { ++ if (pointer == lifted) continue ++ touch.getPointerProperties(pointer, properties[index]) ++ touch.getPointerCoords(pointer, coords[index]) ++ index++ ++ } ++ return MotionEvent.obtain( ++ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords, ++ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision, ++ touch.deviceId, touch.edgeFlags, touch.source, touch.flags, ++ ) ++ } ++ + fun requestDisallowInterceptTouchEvent() { + // If this method gets called it means that some native view is attempting to grab lock for + // touch event delivery. In that case we cancel all gesture recognizers +@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: + // We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell + // if `requestDisallow` has been called as a result of a normal gesture handling process or + // as a result of one of the gesture handlers activating ++ // Keep the stream for recognizers that activate between events (e.g. long press). ++ // Once native handling begins, React no longer receives the remaining touches. ++ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) { ++ clearLastTouch() ++ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) { ++ lastTouch = MotionEvent.obtainNoHistory(event) ++ } ++ } passingTouch = true orchestrator!!.onTouchEvent(event) passingTouch = false From 017f0d8b0d47ee3f38efff7f14dc416333f301b7 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 16:01:26 +0700 Subject: [PATCH 158/160] feat(cli): include labels and workspace IDs in agent listings (#10076) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Let scripts group a worker’s agents by label and workspace from a single listing. --- packages/cli/src/commands/agent/ls.test.ts | 16 +++++++++++++++- packages/cli/src/commands/agent/ls.ts | 4 ++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/agent/ls.test.ts b/packages/cli/src/commands/agent/ls.test.ts index 82d6c09a61..f2a09d2902 100644 --- a/packages/cli/src/commands/agent/ls.test.ts +++ b/packages/cli/src/commands/agent/ls.test.ts @@ -15,7 +15,8 @@ function createPagingClient() { cwd: "/tmp/project", createdAt: `2026-10-0${n}T00:00:00.000Z`, updatedAt: `2026-10-0${n}T00:00:00.000Z`, - labels: {}, + labels: n === 3 ? { bot: "worker", issue: "42" } : {}, + workspaceId: n === 3 ? "workspace-3" : undefined, model: null, lastUserMessageAt: null, currentModeId: null, @@ -124,6 +125,19 @@ describe("buildAgentLsFetchOptions", () => { }); describe("runLsCommand", () => { + it("includes labels and workspace IDs in JSON listings", async () => { + const result = await listAgents({ daemonTarget, global: true }, async () => + createPagingClient(), + ); + const rows = JSON.parse(render(result, { format: "json" })); + + expect(rows).toMatchObject([ + { name: "agent 3", labels: { bot: "worker", issue: "42" }, workspaceId: "workspace-3" }, + { name: "agent 2", labels: {}, workspaceId: null }, + { name: "agent 1", labels: {}, workspaceId: null }, + ]); + }); + it("lists agents on every page, including one updated during the listing", async () => { const result = await listAgents({ daemonTarget, all: true, global: true }, async () => createPagingClient(), diff --git a/packages/cli/src/commands/agent/ls.ts b/packages/cli/src/commands/agent/ls.ts index d60ad0ce97..2e6bf68330 100644 --- a/packages/cli/src/commands/agent/ls.ts +++ b/packages/cli/src/commands/agent/ls.ts @@ -36,6 +36,8 @@ export interface AgentListItem { cwd: string; created: string; background: boolean; + labels: Record; + workspaceId: string | null; } /** Helper to get relative time string */ @@ -112,6 +114,8 @@ function toListItem(agent: AgentSnapshotPayload): AgentListItem { cwd: shortenPath(agent.cwd), created: relativeTime(agent.createdAt), background: agent.background === true, + labels: agent.labels, + workspaceId: agent.workspaceId ?? null, }; } From 59ca1f5f77b905fe642e7c5ae03ca47ddeb43189 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 16:05:12 +0700 Subject: [PATCH 159/160] Replace Desktop's own daemon on update after Desktop relaunches (#10067) An in-app update and the startup version check again use the desktopManaged flag in paseo.pid, while Manage built-in daemon is on. A daemon that an earlier Desktop session launched is now replaced on update. A daemon that the user started through the CLI is still never stopped automatically. Closes #6385. --- docs/architecture.md | 2 +- packages/desktop/bin/paseo.cmd | 3 - packages/desktop/e2e/daemon-lifecycle.e2e.mjs | 63 ++++++++++++++----- packages/desktop/src/daemon/daemon-manager.ts | 27 ++++++-- 4 files changed, 71 insertions(+), 24 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index de6c619ae3..f74d6456c9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -506,5 +506,5 @@ Agent and terminal environments are unchanged. System proxy settings and SOCKS-o ## Deployment models 1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767` -2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only a matching `{pid, startedAt}` from a spawn in the current Desktop session authorizes automatic stop or binary replacement. Preexisting instances, including legacy `desktopManaged` records, are attach-only. Keep-running survivors attach in the next session. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform. +2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only Desktop's own launch writes `desktopManaged: true` to `paseo.pid`. The CLI launch path removes the flag. While Desktop manages the built-in daemon, an app update or a version mismatch replaces any `desktopManaged` daemon, including one that an earlier Desktop session left running. Bundled CLIs before v0.9.0 exported the flag, so a daemon that one of them started also carries it and is replaced. Quit, Settings, and host removal stop only a daemon that the current session launched, matched by `{pid, startedAt}`. A daemon that the user started through the CLI is attach-only. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform. 3. **Remote + relay**: Daemon behind firewall, relay bridges with E2E encryption diff --git a/packages/desktop/bin/paseo.cmd b/packages/desktop/bin/paseo.cmd index 1e767523bb..2dac445381 100644 --- a/packages/desktop/bin/paseo.cmd +++ b/packages/desktop/bin/paseo.cmd @@ -11,9 +11,6 @@ if not exist "%APP_EXECUTABLE%" ( set "ELECTRON_RUN_AS_NODE=1" set "PASEO_NODE_ENV=production" -rem PASEO_DESKTOP_MANAGED marks daemons started through this bundled CLI as -rem desktop-managed, so the desktop app restarts them when it upgrades. -set "PASEO_DESKTOP_MANAGED=1" set "PASEO_CLI=%~f0" "%APP_EXECUTABLE%" --disable-warning=DEP0040 "%RESOURCES_DIR%\app.asar.unpacked\dist\daemon\node-entrypoint-runner.js" node-script "%RESOURCES_DIR%\app.asar\node_modules\@getpaseo\cli\dist\index.js" %* exit /b %errorlevel% diff --git a/packages/desktop/e2e/daemon-lifecycle.e2e.mjs b/packages/desktop/e2e/daemon-lifecycle.e2e.mjs index 870e0f7db5..f0cbb74553 100644 --- a/packages/desktop/e2e/daemon-lifecycle.e2e.mjs +++ b/packages/desktop/e2e/daemon-lifecycle.e2e.mjs @@ -41,16 +41,24 @@ savePersistedConfig(home, { }, }); const main = path.join(root, "main.cjs"); +const updatedMain = path.join(root, "updated-main.cjs"); const managerPath = path.join(repo, "packages/desktop/dist/daemon/daemon-manager.js"); +const desktopMain = (setup) => + `const { app } = require("electron"); ${setup} app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`; +await writeFile(main, desktopMain("")); +// An unpackaged Desktop reads its version from packages/desktop/package.json. This entry +// reports a newer version, standing in for the Desktop an update installs. await writeFile( - main, - `const { app } = require("electron"); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`, + updatedMain, + desktopMain( + `const fs = require("node:fs"); const path = require("node:path"); const readFileSync = fs.readFileSync; fs.readFileSync = (file, ...rest) => typeof file === "string" && path.relative(${JSON.stringify(path.join(repo, "packages/desktop"))}, file) === "package.json" ? JSON.stringify({ version: "999.0.0" }) : readFileSync(file, ...rest);`, + ), ); let desktop; let captured; -async function openDesktop() { +async function openDesktop(entry = main) { desktop = await electron.launch({ - args: ["--no-sandbox", "--ozone-platform=headless", main], + args: ["--no-sandbox", "--ozone-platform=headless", entry], env: { ...env, PASEO_LISTEN: "127.0.0.1:1", @@ -78,27 +86,31 @@ async function command(name, args) { ); } try { - // Simulate a legacy independent launch that carries the old Desktop flag. + // A daemon the user started through the CLI, which Desktop must never stop on its own. + // Older bundled CLIs exported PASEO_DESKTOP_MANAGED, and the CLI launch must not record it. const launch = await startDaemonInstance({ home, command: process.execPath, args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")], - env, + env: { ...env, PASEO_DESKTOP_MANAGED: "1" }, mode: "deployment", - desktopManaged: true, timeoutMs: 30_000, }); captured = launch.instance; await openDesktop(); const attached = await command("start_desktop_daemon"); assert.equal(attached.pid, captured.pid); - assert.equal(attached.desktopManaged, true); + assert.equal(attached.desktopManaged, false); assert.equal(attached.ownedByDesktop, false); for (const reason of ["quit", "settings", "app_update", "host_remove", "version_mismatch"]) { const status = await command("stop_desktop_daemon", { reason }); assert.equal(status.pid, captured.pid, `${reason} stopped an attached daemon`); process.kill(captured.pid, 0); } + await closeDesktop(); + await openDesktop(updatedMain); + const afterUpdate = await command("start_desktop_daemon"); + assert.equal(afterUpdate.pid, captured.pid, "a newer Desktop replaced a daemon the user started"); const restarted = await command("restart_desktop_daemon"); assert.equal(restarted.pid, captured.pid); await assert.rejects( @@ -134,18 +146,37 @@ try { desktop = null; process.kill(captured.pid, 0); await openDesktop(); - assert.equal((await command("start_desktop_daemon")).ownedByDesktop, false); - await command("stop_desktop_daemon", { reason: "quit" }); + // The next session attaches to the daemon Desktop launched before it quit. + const survivor = await command("start_desktop_daemon"); + assert.equal(survivor.pid, captured.pid); + assert.equal(survivor.desktopManaged, true); + assert.equal(survivor.ownedByDesktop, false); + for (const reason of ["quit", "settings", "host_remove"]) { + await command("stop_desktop_daemon", { reason }); + process.kill(captured.pid, 0); + } + // With management off, Desktop leaves the daemon running through an update. + await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: false } }); + await command("stop_desktop_daemon", { reason: "app_update" }); process.kill(captured.pid, 0); - await command("stop_desktop_daemon", { - reason: "manual_ipc", - pid: captured.pid, - startedAt: captured.startedAt, - }); + await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: true } }); + // Installing an update stops it, so the updated Desktop starts its own daemon. + const beforeInstall = await command("stop_desktop_daemon", { reason: "app_update" }); + assert.equal(beforeInstall.status, "stopped", "app_update left Desktop's daemon running"); captured = null; const next = await command("start_desktop_daemon"); captured = await readDaemonInstance(home); assert.equal(next.ownedByDesktop, true); + await closeDesktop(); + process.kill(captured.pid, 0); + // A newer Desktop replaces the daemon an older Desktop launched and kept running. + const outdated = captured; + await openDesktop(updatedMain); + const replaced = await command("start_desktop_daemon"); + captured = await readDaemonInstance(home); + assert.notEqual(replaced.pid, outdated.pid, "a newer Desktop kept the outdated daemon"); + assert.equal(replaced.ownedByDesktop, true); + assert.throws(() => process.kill(outdated.pid, 0), "the outdated daemon is still running"); await command("stop_desktop_daemon", { reason: "quit" }); assert.equal(await readDaemonInstance(home), null); captured = null; @@ -195,7 +226,7 @@ try { ); } console.log( - "PASS: attached legacy daemon survives automatic actions; explicit captured stop, owned launch, managed settings, worker restart, and next-session attachment.", + "PASS: a user-started daemon survives automatic actions and updates; explicit captured stop, owned launch, managed settings, worker restart, next-session attachment, and update replacement of an earlier session's daemon.", ); } finally { await closeDesktop(); diff --git a/packages/desktop/src/daemon/daemon-manager.ts b/packages/desktop/src/daemon/daemon-manager.ts index 98d5287932..44076bbc4b 100644 --- a/packages/desktop/src/daemon/daemon-manager.ts +++ b/packages/desktop/src/daemon/daemon-manager.ts @@ -269,7 +269,7 @@ function normalizeVersion(version: string | null): string | null { } function shouldRestartForVersion(current: DesktopDaemonStatus): boolean { - if (!current.ownedByDesktop) return false; + if (!current.desktopManaged) return false; const appVersion = normalizeVersion(resolveDesktopAppVersion()); const daemonVersion = normalizeVersion(current.version); return Boolean(appVersion && daemonVersion && appVersion !== daemonVersion); @@ -336,12 +336,13 @@ export async function stopDesktopDaemon( ): Promise { const home = getPaseoHome(); const instance = await readDaemonInstance(home); - const owned = Boolean( + const launchedThisSession = Boolean( instance && ownedLaunch && ownedLaunch.home === home && isSameDaemonInstance(instance, ownedLaunch.instance), ); + const owned = launchedThisSession || (await replacesDesktopDaemon(reason, instance)); const explicit = reason === "manual_ipc" && confirmedInstance && @@ -361,10 +362,28 @@ export async function stopDesktopDaemon( keepTerminals, }); await stopCapturedDaemon({ home, instance, reason, keepTerminals }); - if (owned) ownedLaunch = null; + if (launchedThisSession) ownedLaunch = null; return resolveDesktopDaemonStatus(); } +/** An app update or a version mismatch replaces the daemon with the one this Desktop bundles. */ +function isReplacement(reason: DesktopDaemonStopReason): boolean { + return reason === "app_update" || reason === "version_mismatch"; +} + +/** + * While Desktop manages the built-in daemon, a replacement applies to every daemon Desktop + * launched, which `paseo.pid` records as `desktopManaged`. That includes one an earlier Desktop + * session left running. Other automatic stops apply only to a daemon this session launched. + */ +async function replacesDesktopDaemon( + reason: DesktopDaemonStopReason, + instance: DaemonInstance | null, +): Promise { + if (!isReplacement(reason) || instance?.desktopManaged !== true) return false; + return (await getDesktopSettingsStore().get()).daemon.manageBuiltInDaemon; +} + export interface StopCapturedDaemonInput { home: string; instance: DaemonInstance; @@ -428,7 +447,7 @@ export function keepsTerminalsOnStop( platform: NodeJS.Platform, ): boolean { if (platform === "win32") return false; - return reason === "app_update" || reason === "version_mismatch"; + return isReplacement(reason); } async function restartDaemon(): Promise { From 62fc15d77a2cd994d066ee35ca1e3c0ce57f6a56 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 18 Nov 2026 17:10:21 +0700 Subject: [PATCH 160/160] feat(agents): show and stop heartbeats alongside background tasks (#10097) --- .../app/e2e/browser/turn-collapse.spec.ts | 15 +- packages/app/src/background-work/index.tsx | 4 +- packages/app/src/i18n/resources/ar.ts | 1 + packages/app/src/i18n/resources/en.ts | 1 + packages/app/src/i18n/resources/es.ts | 1 + packages/app/src/i18n/resources/fr.ts | 1 + packages/app/src/i18n/resources/ja.ts | 1 + packages/app/src/i18n/resources/ko.ts | 1 + packages/app/src/i18n/resources/pt-BR.ts | 1 + packages/app/src/i18n/resources/ru.ts | 1 + packages/app/src/i18n/resources/zh-CN.ts | 1 + .../src/server/agent/agent-manager.test.ts | 109 ++++++ .../server/src/server/agent/agent-manager.ts | 55 ++- .../src/server/agent/agent-projections.ts | 9 + .../src/server/agent/background-work/index.ts | 122 +++++-- .../src/server/agent/mcp-server.test.ts | 69 ++-- .../src/server/agent/tools/paseo-tools.ts | 24 +- .../server/src/server/authorization/index.ts | 2 +- .../src/server/schedule/service.test.ts | 166 +++++++++- .../server/src/server/schedule/service.ts | 82 ++++- packages/server/src/server/schedule/store.ts | 58 +++- packages/server/src/server/session.test.ts | 313 ++++++++++++++++-- packages/server/src/server/session.ts | 86 +++-- .../agent-updates/agent-updates-service.ts | 30 +- 24 files changed, 985 insertions(+), 168 deletions(-) diff --git a/packages/app/e2e/browser/turn-collapse.spec.ts b/packages/app/e2e/browser/turn-collapse.spec.ts index 1ae180fb8e..bdc0132274 100644 --- a/packages/app/e2e/browser/turn-collapse.spec.ts +++ b/packages/app/e2e/browser/turn-collapse.spec.ts @@ -705,7 +705,7 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous }); const schedules = agent.client as unknown as Pick< DaemonClient, - "scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" + "scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" | "scheduleList" >; let scheduleId: string | undefined; try { @@ -743,7 +743,18 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous await expect(summaries).toHaveCount(2); await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0); await expect(page.getByRole("button", { name: /^Worked for/ })).toHaveCount(2); - await page.screenshot({ path: "/tmp/heartbeat-turn-footer.png" }); + const tasks = page.getByRole("button", { name: "1 background task", exact: true }); + await expect(page.getByTestId("workspace-status-indicator-running").first()).toBeVisible(); + await expect(page.getByRole("button", { name: "Stop agent", exact: true })).toHaveCount(0); + await tasks.click(); + const panel = page.getByTestId("background-work-panel"); + await expect(panel).toContainText("Heartbeat"); + await panel.getByRole("button", { name: "Stop Check the completed work" }).click(); + await expect(tasks).toHaveCount(0); + await expect(page.getByTestId("workspace-status-indicator-running")).toHaveCount(0); + const remaining = await schedules.scheduleList(); + expect(remaining.error).toBeNull(); + expect(remaining.schedules.map((schedule) => schedule.id)).not.toContain(scheduleId); } finally { if (scheduleId) await schedules.scheduleDelete({ id: scheduleId }); await agent.cleanup(); diff --git a/packages/app/src/background-work/index.tsx b/packages/app/src/background-work/index.tsx index 34dfbb83ff..bafa953fa6 100644 --- a/packages/app/src/background-work/index.tsx +++ b/packages/app/src/background-work/index.tsx @@ -10,8 +10,8 @@ import { createHostBackgroundWorkModel } from "./host"; import { backgroundWorkText } from "./presentation"; export { createHostBackgroundWorkModel } from "./host"; -function kindKey(kind: string): "shell" | "monitor" | "other" { - if (kind === "shell" || kind === "monitor") return kind; +function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" { + if (kind === "shell" || kind === "monitor" || kind === "heartbeat") return kind; return "other"; } diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 593d50d922..4dc4784e07 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -394,6 +394,7 @@ export const ar: TranslationResources = { otherPlaceholder: "آخر...", }, backgroundWork: { + heartbeat: "نبضة دورية", pillOne: "مهمة واحدة في الخلفية", pillMany: "{{count}} مهمة في الخلفية", notRunning: "لم يعد قيد التشغيل", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 02e875a75f..87241cad0a 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -393,6 +393,7 @@ export const en = { otherPlaceholder: "Other...", }, backgroundWork: { + heartbeat: "Heartbeat", pillOne: "1 background task", pillMany: "{{count}} background tasks", notRunning: "No longer running", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index fa510cc8eb..5768982f14 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -399,6 +399,7 @@ export const es: TranslationResources = { otherPlaceholder: "Otro...", }, backgroundWork: { + heartbeat: "Latido", pillOne: "1 tarea en segundo plano", pillMany: "{{count}} tareas en segundo plano", notRunning: "Ya no está en ejecución", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 18536c5e96..cb64c3652f 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -399,6 +399,7 @@ export const fr: TranslationResources = { otherPlaceholder: "Autre…", }, backgroundWork: { + heartbeat: "Battement périodique", pillOne: "1 tâche en arrière-plan", pillMany: "{{count}} tâches en arrière-plan", notRunning: "N’est plus en cours", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 6d177c808f..689a676deb 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -399,6 +399,7 @@ export const ja: TranslationResources = { otherPlaceholder: "その他...", }, backgroundWork: { + heartbeat: "ハートビート", pillOne: "バックグラウンドタスク1件", pillMany: "バックグラウンドタスク{{count}}件", notRunning: "実行は終了しました", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 6a629c3fa4..aaea487a26 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -395,6 +395,7 @@ export const ko: TranslationResources = { otherPlaceholder: "기타...", }, backgroundWork: { + heartbeat: "하트비트", pillOne: "백그라운드 작업 1개", pillMany: "백그라운드 작업 {{count}}개", notRunning: "더 이상 실행 중이 아님", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 23ec297c45..0f64a803fb 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -398,6 +398,7 @@ export const ptBR: TranslationResources = { otherPlaceholder: "Outro...", }, backgroundWork: { + heartbeat: "Batimento", pillOne: "1 tarefa em segundo plano", pillMany: "{{count}} tarefas em segundo plano", notRunning: "Não está mais em execução", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 729c04d88e..d59121a130 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -398,6 +398,7 @@ export const ru: TranslationResources = { otherPlaceholder: "Другой ответ...", }, backgroundWork: { + heartbeat: "Периодический сигнал", pillOne: "1 фоновая задача", pillMany: "Фоновые задачи: {{count}}", notRunning: "Больше не выполняется", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index b47edf1e6c..8b863abcd8 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -394,6 +394,7 @@ export const zhCN: TranslationResources = { otherPlaceholder: "其他...", }, backgroundWork: { + heartbeat: "心跳", pillOne: "1 个后台任务", pillMany: "{{count}} 个后台任务", notRunning: "已不再运行", diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 5e4c104995..3a91addcdb 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -15223,6 +15223,115 @@ test("stops only a currently owned public background item with its current token await manager.closeAgent(agent.id); }); +test("lists and stops heartbeat background work across provider session closure", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-background-heartbeat-")); + const stopped: string[] = []; + let activeSession: TestAgentSession | undefined; + class StoppableSession extends TestAgentSession { + async stopBackgroundWork(id: string) { + stopped.push(id); + } + } + class BackgroundWorkClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + activeSession = new StoppableSession(config); + return activeSession; + } + } + const manager = new AgentManager({ + clients: { codex: new BackgroundWorkClient() }, + registry: new AgentStorage(join(workdir, "agents"), logger), + logger, + }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const events: AgentManagerEvent[] = []; + manager.subscribe((event) => events.push(event), { agentId: agent.id, replayState: false }); + const heartbeat = { + agentId: agent.id, + scheduleId: "schedule-1", + name: "Check build", + createdAt: "2026-10-06T10:00:00.000Z", + stop: async () => { + stopped.push("schedule-1"); + manager.removeHeartbeatBackgroundWork(agent.id, "schedule-1"); + }, + }; + try { + manager.setHeartbeatBackgroundWork(heartbeat); + const [item] = manager.listAgentBackgroundWork(agent.id); + expect(item).toMatchObject({ + kind: "heartbeat", + description: "Check build", + startedAt: heartbeat.createdAt, + canStop: true, + stopToken: expect.any(String), + }); + manager.setHeartbeatBackgroundWork({ ...heartbeat, name: "Check CI" }); + const renamed = { ...item, description: "Check CI" }; + + activeSession?.pushEvent({ + type: "background_work", + provider: "codex", + items: [{ id: item.id, kind: "shell", description: null, canStop: true }], + }); + await vi.waitFor(() => + expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 2 }), + ); + const providerItem = manager + .listAgentBackgroundWork(agent.id) + .find((row) => row.kind === "shell")!; + expect(providerItem.id).not.toBe(item.id); + expect(events).toContainEqual({ + type: "background_work", + agentId: agent.id, + items: expect.arrayContaining([providerItem, renamed]), + }); + await manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: providerItem.id, + stopToken: providerItem.stopToken!, + }); + expect(stopped).toEqual([item.id]); + + const eventsBeforeClose = events.length; + await manager.closeAgent(agent.id); + expect(manager.getAgent(agent.id)).toBeNull(); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([renamed]); + expect(manager.getAgentBackgroundWorkSummary(agent.id)).toEqual({ count: 1 }); + expect(events.slice(eventsBeforeClose)).toContainEqual({ + type: "background_work", + agentId: agent.id, + items: [renamed], + }); + + const stop = { agentId: agent.id, itemId: item.id, stopToken: item.stopToken! }; + await expect(manager.stopAgentBackgroundWork(stop)).rejects.toThrow(); + await expect( + manager.stopAgentBackgroundWork({ + ...stop, + stopToken: providerItem.stopToken!, + canManageAutomation: true, + }), + ).rejects.toThrow(); + expect(stopped).toEqual([item.id]); + await manager.stopAgentBackgroundWork({ ...stop, canManageAutomation: true }); + expect(stopped).toEqual([item.id, "schedule-1"]); + expect(manager.getAgentBackgroundWorkSummary(agent.id)).toBeUndefined(); + expect(events.at(-1)).toEqual({ type: "background_work", agentId: agent.id, items: [] }); + + manager.setHeartbeatBackgroundWork(heartbeat); + await expect( + manager.stopAgentBackgroundWork({ ...stop, canManageAutomation: true }), + ).rejects.toThrow(); + expect(manager.listAgentBackgroundWork(agent.id)[0].stopToken).not.toBe(item.stopToken); + } finally { + if (manager.getAgent(agent.id)) await manager.closeAgent(agent.id); + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("turns keep distinct identities across an idle runtime collection and resume", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-turn-identity-")); const storage = new AgentStorage(join(workdir, "agents"), logger); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 009710664f..bf610674c4 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -113,7 +113,12 @@ import { type ProviderSubagentDescriptor, type ProviderSubagentStoreEvent, } from "./provider-subagents/store.js"; -import { AgentBackgroundWorkStore, type AgentBackgroundWorkItem } from "./background-work/index.js"; +import { + AgentBackgroundWorkStore, + isHeartbeatBackgroundWorkItem, + type AgentBackgroundWorkItem, + type HeartbeatBackgroundWorkInput, +} from "./background-work/index.js"; import { withTimeout } from "../../utils/promise-timeout.js"; import { buildSessionConfig, extractAttention } from "../persistence-hooks.js"; @@ -191,6 +196,7 @@ interface StopAgentBackgroundWorkOptions { agentId: string; itemId: string; stopToken: string; + canManageAutomation?: boolean; } async function resolveResumePurpose( @@ -1430,37 +1436,56 @@ export class AgentManager { } listAgentBackgroundWork(agentId: string): AgentBackgroundWorkItem[] { - this.requirePublicAgent(agentId); + const agent = this.agents.get(agentId); + if (agent?.internal || (!agent && !this.backgroundWork.summary(agentId))) { + throw new Error(`Unknown agent '${agentId}'`); + } return this.backgroundWork.list(agentId); } + setHeartbeatBackgroundWork(input: HeartbeatBackgroundWorkInput): void { + this.publishBackgroundWork(input.agentId, this.backgroundWork.setHeartbeat(input)); + } + + removeHeartbeatBackgroundWork(agentId: string, scheduleId: string): void { + this.publishBackgroundWork(agentId, this.backgroundWork.removeHeartbeat(agentId, scheduleId)); + } + async stopAgentBackgroundWork({ agentId, itemId, stopToken, + canManageAutomation, }: StopAgentBackgroundWorkOptions): Promise { + if (isHeartbeatBackgroundWorkItem({ id: itemId })) { + if (this.agents.get(agentId)?.internal) throw new Error(`Unknown agent '${agentId}'`); + if (!canManageAutomation) + throw new Error("Managing automation is required to stop a heartbeat"); + await this.backgroundWork.stopHeartbeat(agentId, itemId, stopToken); + return; + } this.requirePublicAgent(agentId); // Inventory events share the session queue; drain events already received before // authorizing the token, including a reconnect's ownership revocation. await this.sessionEventTails.get(agentId)?.catch(() => undefined); - const agent = this.requirePublicAgent(agentId); - if (!agent.session || !agent.session.stopBackgroundWork) - throw new Error("Background work cannot be stopped"); - const item = this.backgroundWork.list(agentId).find((entry) => entry.id === itemId); - if (!item?.canStop || item.stopToken !== stopToken) - throw new Error("Background work is no longer available to stop"); - await agent.session.stopBackgroundWork(itemId); + const { session } = this.requirePublicAgent(agentId); + if (!session?.stopBackgroundWork) throw new Error("Background work cannot be stopped"); + const providerItemId = this.backgroundWork.authorizeProviderStop(agentId, itemId, stopToken); + await session.stopBackgroundWork(providerItemId); } getAgentBackgroundWorkSummary(agentId: string): { count: number } | undefined { return this.backgroundWork.summary(agentId); } - private clearBackgroundWork(agentId: string): void { - const items = this.backgroundWork.clear(agentId); + private publishBackgroundWork(agentId: string, items: AgentBackgroundWorkItem[] | null): void { if (items) this.dispatch({ type: "background_work", agentId, items }); } + private clearProviderBackgroundWork(agentId: string): void { + this.publishBackgroundWork(agentId, this.backgroundWork.clear(agentId)); + } + listProviderSubagentActivity(): ProviderSubagentDescriptor[] { const publicParentIds = new Set( Array.from(this.agents.values()) @@ -1922,7 +1947,7 @@ export class AgentManager { await this.closeReloadedSession(existing.session, agentId); await this.drainSessionEvents(agentId); this.cancelRunningProviderSubagents(agentId); - this.clearBackgroundWork(agentId); + this.clearProviderBackgroundWork(agentId); closedExisting = this.prepareAgentForClosure(existing, "agent reloaded"); await this.persistSnapshot(closedExisting); this.assertAcceptingAgentRegistrations(); @@ -2178,7 +2203,7 @@ export class AgentManager { await this.drainSessionEvents(agentId); this.cancelRunningProviderSubagents(agentId); // close() drops the session's subscribers before the provider could report an empty list. - this.clearBackgroundWork(agentId); + this.clearProviderBackgroundWork(agentId); const closedAgent = this.prepareAgentForClosure(agent, "agent closed"); let persistError: unknown; @@ -4674,7 +4699,7 @@ export class AgentManager { for (const event of this.providerSubagents.deleteParent(agentId)) { this.dispatch({ type: "provider_subagent", event }); } - this.clearBackgroundWork(agentId); + this.clearProviderBackgroundWork(agentId); } private emitClosedAgent(agent: ManagedAgentClosed, options?: { persist?: boolean }): void { @@ -4789,7 +4814,7 @@ export class AgentManager { event.items === null ? this.backgroundWork.clear(agent.id) : this.backgroundWork.apply(agent.id, event.items); - if (items) this.dispatch({ type: "background_work", agentId: agent.id, items }); + this.publishBackgroundWork(agent.id, items); return; } const turnId = getAgentStreamEventTurnId(event); diff --git a/packages/server/src/server/agent/agent-projections.ts b/packages/server/src/server/agent/agent-projections.ts index 60d7f3ba4e..3a3af01166 100644 --- a/packages/server/src/server/agent/agent-projections.ts +++ b/packages/server/src/server/agent/agent-projections.ts @@ -260,10 +260,18 @@ function buildStoredOptionControls( }; } +function visibleStoredBackgroundWork( + record: StoredAgentRecord, + summary: AgentSnapshotPayload["backgroundWork"], +): AgentSnapshotPayload["backgroundWork"] { + return record.internal || record.archivedAt ? undefined : summary; +} + export function buildStoredAgentPayload( record: StoredAgentRecord, validProviders: Iterable, effectiveOptionsFor: EffectiveOptionsResolver, + backgroundWork?: AgentSnapshotPayload["backgroundWork"], ): AgentSnapshotPayload { const defaultCapabilities = { supportsStreaming: false, @@ -304,6 +312,7 @@ export function buildStoredAgentPayload( updatedAt: updatedAt.toISOString(), lastUserMessageAt: lastUserMessageAt ? lastUserMessageAt.toISOString() : null, status: record.lastStatus, + backgroundWork: visibleStoredBackgroundWork(record, backgroundWork), capabilities: defaultCapabilities, currentModeId: record.lastModeId ?? null, availableModes: [], diff --git a/packages/server/src/server/agent/background-work/index.ts b/packages/server/src/server/agent/background-work/index.ts index 3290f13503..90df243bb2 100644 --- a/packages/server/src/server/agent/background-work/index.ts +++ b/packages/server/src/server/agent/background-work/index.ts @@ -14,55 +14,137 @@ export interface AgentBackgroundWorkItem extends AgentBackgroundWorkInput { stopToken?: string; } +export interface HeartbeatBackgroundWorkInput { + agentId: string; + scheduleId: string; + name: string | null; + createdAt: string; + stop: () => Promise; +} + +interface HeartbeatBackgroundWork { + item: AgentBackgroundWorkItem; + stop: HeartbeatBackgroundWorkInput["stop"]; +} + +const HEARTBEAT_ID_PREFIX = "heartbeat:"; +const PROVIDER_ID_ESCAPE = "provider:"; + +export function isHeartbeatBackgroundWorkItem(item: { id: string }): boolean { + return item.id.startsWith(HEARTBEAT_ID_PREFIX); +} + +function encodeProviderItemId(id: string): string { + // Preserve existing wire IDs outside the reserved namespaces. + return id.startsWith(HEARTBEAT_ID_PREFIX) || id.startsWith(PROVIDER_ID_ESCAPE) + ? PROVIDER_ID_ESCAPE + id + : id; +} + /** - * Live background work per agent. Providers report the whole list on every change, so `apply` - * replaces it. `startedAt` is stamped the first time an id is seen and kept while it stays listed. - * Nothing is persisted; providers determine when their live inventory is no longer available. + * Live inventory per agent. Providers replace their entire contribution with `apply`. + * The scheduler publishes heartbeats individually and retains ownership across provider closure. */ export class AgentBackgroundWorkStore { - private readonly items = new Map(); + private readonly providerItems = new Map(); + private readonly heartbeats = new Map>(); apply( agentId: string, inputs: readonly AgentBackgroundWorkInput[], timestamp: string = new Date().toISOString(), ): AgentBackgroundWorkItem[] | null { - const known = this.items.has(agentId); - const previous = this.items.get(agentId) ?? []; - const previousById = new Map(previous.map((item) => [item.id, item])); + const previous = this.providerItems.get(agentId); + const previousById = new Map(previous?.map((item) => [item.id, item])); const seen = new Set(); const next: AgentBackgroundWorkItem[] = []; for (const input of inputs) { - if (seen.has(input.id)) continue; - seen.add(input.id); + const id = encodeProviderItemId(input.id); + if (seen.has(id)) continue; + seen.add(id); next.push({ - id: input.id, + id, kind: input.kind, description: input.description, ...(input.command ? { command: input.command } : {}), ...(input.canStop - ? { canStop: true, stopToken: previousById.get(input.id)?.stopToken ?? randomUUID() } + ? { canStop: true, stopToken: previousById.get(id)?.stopToken ?? randomUUID() } : {}), - startedAt: previousById.get(input.id)?.startedAt ?? timestamp, + startedAt: previousById.get(id)?.startedAt ?? timestamp, }); } - if (known && sameItems(previous, next)) return null; - this.items.set(agentId, next); - return [...next]; + if (previous && sameItems(previous, next)) return null; + this.providerItems.set(agentId, next); + return this.list(agentId); + } + + setHeartbeat({ + agentId, + scheduleId, + name, + createdAt, + stop, + }: HeartbeatBackgroundWorkInput): AgentBackgroundWorkItem[] | null { + const id = HEARTBEAT_ID_PREFIX + scheduleId; + const heartbeats = this.heartbeats.get(agentId) ?? new Map(); + const previous = heartbeats.get(id)?.item; + const item: AgentBackgroundWorkItem = { + id, + kind: "heartbeat", + description: name, + startedAt: createdAt, + canStop: true, + stopToken: previous?.stopToken ?? randomUUID(), + }; + heartbeats.set(id, { item, stop }); + this.heartbeats.set(agentId, heartbeats); + return previous?.description === name && previous.startedAt === createdAt + ? null + : this.list(agentId); + } + + removeHeartbeat(agentId: string, scheduleId: string): AgentBackgroundWorkItem[] | null { + const heartbeats = this.heartbeats.get(agentId); + if (!heartbeats?.delete(HEARTBEAT_ID_PREFIX + scheduleId)) return null; + if (heartbeats.size === 0) this.heartbeats.delete(agentId); + return this.list(agentId); + } + + async stopHeartbeat(agentId: string, itemId: string, stopToken: string): Promise { + const heartbeat = this.heartbeats.get(agentId)?.get(itemId); + if (!heartbeat || heartbeat.item.stopToken !== stopToken) { + throw new Error("Background work is no longer available to stop"); + } + await heartbeat.stop(); + } + + authorizeProviderStop(agentId: string, itemId: string, stopToken: string): string { + const item = this.providerItems.get(agentId)?.find(({ id }) => id === itemId); + if (!item?.canStop || item.stopToken !== stopToken) { + throw new Error("Background work is no longer available to stop"); + } + return itemId.startsWith(PROVIDER_ID_ESCAPE) ? itemId.slice(PROVIDER_ID_ESCAPE.length) : itemId; } list(agentId: string): AgentBackgroundWorkItem[] { - return [...(this.items.get(agentId) ?? [])]; + const items = [...(this.providerItems.get(agentId) ?? [])]; + for (const { item } of this.heartbeats.get(agentId)?.values() ?? []) { + items.push(item); + } + return items; } summary(agentId: string): { count: number } | undefined { - const items = this.items.get(agentId); - return items ? { count: items.length } : undefined; + const items = this.providerItems.get(agentId); + const heartbeats = this.heartbeats.get(agentId); + return items || heartbeats + ? { count: (items?.length ?? 0) + (heartbeats?.size ?? 0) } + : undefined; } clear(agentId: string): AgentBackgroundWorkItem[] | null { - if (!this.items.delete(agentId)) return null; - return []; + if (!this.providerItems.delete(agentId)) return null; + return this.list(agentId); } } diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 1979192ba9..071084b1fa 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -6197,35 +6197,50 @@ describe("agent snapshot MCP serialization", () => { expect(structured.agents[0]).not.toHaveProperty("pendingPermissions"); }); - it("reports an idle agent's background work from get_agent_status and list_agents", async () => { - const { agentManager, agentStorage, spies } = createTestDeps(); - const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD }); - spies.agentManager.getAgent.mockReturnValue(agent); - spies.agentManager.listAgents.mockReturnValue([agent]); - spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 }); + it.each(["loaded", "stored"])( + "reports background work for a %s agent from get_agent_status and list_agents", + async (source) => { + const { agentManager, agentStorage, spies } = createTestDeps(); + const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD }); + if (source === "stored") { + const record = createStoredRecord({ + id: agent.id, + cwd: agent.cwd, + archivedAt: null, + lastStatus: "idle", + updatedAt: new Date().toISOString(), + }); + spies.agentStorage.get.mockResolvedValue(record); + spies.agentStorage.listActive.mockResolvedValue([record]); + } else { + spies.agentManager.getAgent.mockReturnValue(agent); + spies.agentManager.listAgents.mockReturnValue([agent]); + } + spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 }); - const server = await createAgentMcpServer({ - agentManager, - agentStorage, - providerSnapshotManager: createOpenCodeManager().manager, - logger, - }); - const status = await registeredTool(server, "get_agent_status").handler({ - agentId: "agent-with-shell", - }); - const list = await registeredTool(server, "list_agents").handler({}); + const server = await createAgentMcpServer({ + agentManager, + agentStorage, + providerSnapshotManager: createClaudeOnlyManager(), + logger, + }); + const status = await registeredTool(server, "get_agent_status").handler({ + agentId: "agent-with-shell", + }); + const list = await registeredTool(server, "list_agents").handler({}); - expect(status.structuredContent).toEqual({ - status: "idle", - snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }), - }); - expect(list.structuredContent).toEqual({ - agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })], - }); - expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith( - "agent-with-shell", - ); - }); + expect(status.structuredContent).toEqual({ + status: "idle", + snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }), + }); + expect(list.structuredContent).toEqual({ + agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })], + }); + expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith( + "agent-with-shell", + ); + }, + ); it("returns archived agent snapshots from storage for get_agent_status", async () => { const { agentManager, agentStorage, spies } = createTestDeps(); diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 9fbb4c057b..1123e59ced 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -33,7 +33,7 @@ import { toAgentPayload, } from "../agent-projections.js"; import { summarizeAgentActivity } from "../activity-curator.js"; -import type { AgentStorage } from "../agent-storage.js"; +import type { AgentStorage, StoredAgentRecord } from "../agent-storage.js"; import { AgentNotFoundError, ensureAgentLoaded } from "../agent-loading.js"; import { isStoredAgentProviderAvailable } from "../../persistence-hooks.js"; import { @@ -2106,6 +2106,15 @@ function createToolCatalog( return backgroundWork ? { ...snapshot, backgroundWork } : snapshot; } + function projectStoredAgent(record: StoredAgentRecord) { + return buildStoredAgentPayload( + record, + new Set(providerSnapshotManager.listRegisteredProviderIds()), + (provider, own) => agentManager.effectiveOptionsFor(provider, own), + agentManager.getAgentBackgroundWorkSummary(record.id), + ); + } + registerTool( "get_agent_status", { @@ -2138,11 +2147,7 @@ function createToolCatalog( throw new PaseoToolInputError(`Agent ${agentId} not found`); } - const structuredSnapshot = buildStoredAgentPayload( - record, - new Set(providerSnapshotManager.listRegisteredProviderIds()), - (provider, own) => agentManager.effectiveOptionsFor(provider, own), - ); + const structuredSnapshot = projectStoredAgent(record); return { content: [], structuredContent: ensureValidJson({ @@ -2192,12 +2197,7 @@ function createToolCatalog( storage: agentStorage, workspaces: options.workspaceRegistry, projectLive: projectLiveAgent, - projectStored: (record) => - buildStoredAgentPayload( - record, - new Set(providerSnapshotManager.listRegisteredProviderIds()), - (provider, own) => agentManager.effectiveOptionsFor(provider, own), - ), + projectStored: projectStoredAgent, isProviderVisible: () => true, isStoredProviderAvailable: (record) => isStoredAgentProviderAvailable( diff --git a/packages/server/src/server/authorization/index.ts b/packages/server/src/server/authorization/index.ts index e79f5d28e7..dec5bca819 100644 --- a/packages/server/src/server/authorization/index.ts +++ b/packages/server/src/server/authorization/index.ts @@ -29,7 +29,7 @@ export class SessionAuthorization { this.permissions = new Set(permissions); } - allowsInbound(message: SessionInboundMessage): boolean { + allowsInbound(message: Pick): boolean { return this.allows(requiredPermissionForInbound(message.type)); } diff --git a/packages/server/src/server/schedule/service.test.ts b/packages/server/src/server/schedule/service.test.ts index a2415ffe50..9c17720833 100644 --- a/packages/server/src/server/schedule/service.test.ts +++ b/packages/server/src/server/schedule/service.test.ts @@ -649,6 +649,157 @@ describe("ScheduleService", () => { expect(resumed.nextRunAt).toBe("2026-01-01T00:04:00.000Z"); }); + test("shows an active heartbeat and stops it through agent background work", async () => { + const logger = createTestLogger(); + const manager = new AgentManager({ + logger, + clients: createTestAgentClients(), + registry: agentStorage, + }); + const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, { + workspaceId: undefined, + }); + const service = createScheduleService({ + paseoHome: tempDir, + logger, + agentManager: manager, + agentStorage, + providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, + now: () => now, + }); + const input = { + prompt: "Private heartbeat instruction", + cadence: { type: "every", everyMs: 60_000 }, + target: { type: "agent", agentId: agent.id }, + } as const; + const created = await service.create(input); + + const items = manager.listAgentBackgroundWork(agent.id); + expect(items).toEqual([ + expect.objectContaining({ + kind: "heartbeat", + description: null, + canStop: true, + startedAt: created.createdAt, + }), + ]); + expect(JSON.stringify(items)).not.toContain(created.prompt); + await service.update({ id: created.id, name: "Status check" }); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([ + expect.objectContaining({ description: "Status check", startedAt: created.createdAt }), + ]); + const replacement = await service.createOrReplace({ ...input, name: "Status check" }); + expect(replacement.id).toBe(created.id); + expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(1); + await service.pause(created.id); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + await service.resume(created.id); + const [firstResume] = manager.listAgentBackgroundWork(agent.id); + const pausing = service.pause(created.id); + const resuming = service.resume(created.id); + const staleStop = expect( + manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: firstResume.id, + stopToken: firstResume.stopToken!, + canManageAutomation: true, + }), + ).rejects.toThrow("Background work is no longer available to stop"); + await Promise.all([pausing, resuming, staleStop]); + const [resumed] = manager.listAgentBackgroundWork(agent.id); + await manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: resumed.id, + stopToken: resumed.stopToken!, + canManageAutomation: true, + }); + await expect(service.inspect(created.id)).rejects.toThrow(`Schedule not found: ${created.id}`); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + + const deleted = await service.createOrReplace({ ...input, name: "Another check" }); + expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(1); + await service.delete(deleted.id); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + }); + + test("removes heartbeats when they expire or finish their last run", async () => { + const logger = createTestLogger(); + const manager = new AgentManager({ logger, clients: createTestAgentClients() }); + const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, { + workspaceId: undefined, + }); + const service = createScheduleService({ + paseoHome: tempDir, + logger, + agentManager: manager, + agentStorage, + providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, + now: () => now, + runner: async () => ({ agentId: agent.id, output: "done" }), + }); + const input = { + prompt: "Check", + cadence: { type: "every", everyMs: 60_000 }, + target: { type: "agent", agentId: agent.id }, + } as const; + const expiring = await service.create({ + ...input, + expiresAt: "2026-01-01T00:00:30.000Z", + runOnCreate: false, + }); + const finite = await service.create({ ...input, maxRuns: 1 }); + expect(manager.listAgentBackgroundWork(agent.id)).toHaveLength(2); + + now = new Date("2026-01-01T00:00:30.000Z"); + await service.tick(); + + expect(await service.inspect(expiring.id)).toMatchObject({ status: "completed", runs: [] }); + expect(await service.inspect(finite.id)).toMatchObject({ + status: "completed", + runs: [{ status: "succeeded" }], + }); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + }); + + test("lets an already launched heartbeat turn finish after Stop deletes its schedule", async () => { + const logger = createTestLogger(); + const manager = new AgentManager({ logger, clients: createTestAgentClients() }); + const agent = await manager.createAgent({ provider: "claude", cwd: tempDir }, undefined, { + workspaceId: undefined, + }); + const runner = new OverlappingTickRunner(); + const service = createScheduleService({ + paseoHome: tempDir, + logger, + agentManager: manager, + agentStorage, + providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, + now: () => now, + runner: (schedule) => runner.run(schedule), + }); + const created = await service.create({ + prompt: "block the first tick", + cadence: { type: "every", everyMs: 60_000 }, + target: { type: "agent", agentId: agent.id }, + }); + const tick = service.tick(); + await runner.firstRunStarted; + try { + const [item] = manager.listAgentBackgroundWork(agent.id); + await manager.stopAgentBackgroundWork({ + agentId: agent.id, + itemId: item.id, + stopToken: item.stopToken!, + canManageAutomation: true, + }); + } finally { + runner.unblockFirstRun(); + await tick; + } + await expect(service.inspect(created.id)).rejects.toThrow(`Schedule not found: ${created.id}`); + expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]); + }); + test("completes schedules when max runs is reached", async () => { const service = createScheduleService({ paseoHome: tempDir, @@ -3093,12 +3244,19 @@ describe("ScheduleService", () => { target: { type: "agent", agentId: liveAgentId }, }); await service1.pause(pausedLive.id); + const expired = await service1.create({ + prompt: "Expired check", + cadence: { type: "every", everyMs: 60_000 }, + expiresAt: "2026-01-01T00:01:00.000Z", + target: { type: "agent", agentId: liveAgentId }, + }); now = new Date("2026-01-01T00:10:00.000Z"); + const replacementManager = new AgentManager({ logger: createTestLogger() }); const service2 = createScheduleService({ paseoHome: tempDir, logger: createTestLogger(), - agentManager: new AgentManager({ logger: createTestLogger() }), + agentManager: replacementManager, agentStorage, providerSnapshotManager: NO_UNATTENDED_SCHEDULE_POLICY, now: () => now, @@ -3112,6 +3270,12 @@ describe("ScheduleService", () => { expect((await service2.inspect(archived.id)).status).toBe("completed"); expect((await service2.inspect(live.id)).status).toBe("active"); expect((await service2.inspect(newAgent.id)).status).toBe("active"); + expect((await service2.inspect(expired.id)).status).toBe("completed"); + expect(replacementManager.getAgentBackgroundWorkSummary(missingAgentId)).toBeUndefined(); + expect(replacementManager.getAgentBackgroundWorkSummary(archivedAgentId)).toBeUndefined(); + expect(replacementManager.listAgentBackgroundWork(liveAgentId)).toEqual([ + expect.objectContaining({ id: `heartbeat:${live.id}`, startedAt: live.createdAt }), + ]); // Paused schedules are swept too when their agent is gone, but survive when it lives. expect((await service2.inspect(pausedMissing.id)).status).toBe("completed"); expect((await service2.inspect(pausedLive.id)).status).toBe("paused"); diff --git a/packages/server/src/server/schedule/service.ts b/packages/server/src/server/schedule/service.ts index 6e6ad6e7c2..8434d80ef7 100644 --- a/packages/server/src/server/schedule/service.ts +++ b/packages/server/src/server/schedule/service.ts @@ -243,6 +243,8 @@ type ScheduleAgentManager = Pick< | "runAgent" | "waitForAgentEvent" | "waitForAgentClose" + | "setHeartbeatBackgroundWork" + | "removeHeartbeatBackgroundWork" >; interface ScheduleWorkspaceCreateInput { @@ -286,12 +288,18 @@ export class ScheduleService { runId: string, ) => Promise; private readonly runningScheduleIds = new Set(); + private readonly heartbeatStops = new Map Promise>(); + private recovering = false; private tickTimer: ReturnType | null = null; constructor(options: ScheduleServiceOptions) { this.logger = options.logger.child({ module: "schedule-service" }); - this.store = new ScheduleStore(join(options.paseoHome, "schedules"), this.logger); this.agentManager = options.agentManager; + this.store = new ScheduleStore( + join(options.paseoHome, "schedules"), + this.logger, + (schedule, change) => this.syncHeartbeat(schedule, change), + ); this.agentStorage = options.agentStorage; this.createAgent = options.createAgent; this.createDirectoryWorkspace = options.createDirectoryWorkspace; @@ -302,11 +310,19 @@ export class ScheduleService { } async start(): Promise { - await this.recoverInterruptedRuns(); - await this.sweepOrphanedSchedules(); if (this.tickTimer) { return; } + this.recovering = true; + try { + await this.recoverInterruptedRuns(); + await this.sweepOrphanedSchedules(); + } finally { + this.recovering = false; + } + for (const schedule of await this.store.list()) { + this.syncHeartbeat(schedule, "write"); + } const timer = setInterval(() => { void this.tick().catch((error) => { this.logger.error({ err: error }, "Failed to process schedule tick"); @@ -505,6 +521,46 @@ export class ScheduleService { await this.store.delete(id); } + private syncHeartbeat(schedule: StoredSchedule, change: "write" | "delete"): void { + if (schedule.target.type !== "agent") { + return; + } + const { agentId } = schedule.target; + const { id, name, createdAt } = schedule; + if (change === "delete" || schedule.status !== "active") { + this.heartbeatStops.delete(id); + this.agentManager.removeHeartbeatBackgroundWork(agentId, id); + return; + } + if (this.recovering) { + return; + } + let stop = this.heartbeatStops.get(id); + if (!stop) { + const stopHeartbeat = () => + this.store.delete(id, (current) => { + // A queued Stop can reach the store after a pause and resume replaced its row. + if ( + current?.status !== "active" || + current.target.type !== "agent" || + current.target.agentId !== agentId || + this.heartbeatStops.get(id) !== stopHeartbeat + ) { + throw new ScheduleStateConflictError("Background work is no longer available to stop"); + } + }); + this.heartbeatStops.set(id, stopHeartbeat); + stop = stopHeartbeat; + } + this.agentManager.setHeartbeatBackgroundWork({ + agentId, + scheduleId: id, + name, + createdAt, + stop, + }); + } + async completeForAgent(agentId: string): Promise { const now = this.now(); const schedules = await this.store.list(); @@ -590,7 +646,7 @@ export class ScheduleService { } private async completeScheduleIfDue(scheduleId: string, now: Date): Promise { - const updated = await this.store.update(scheduleId, (schedule) => { + await this.store.update(scheduleId, (schedule) => { if ( schedule.status !== "active" || !schedule.nextRunAt || @@ -600,7 +656,6 @@ export class ScheduleService { } return completeSchedule(schedule, now); }); - requireSchedule(updated, scheduleId); } private async recoverInterruptedRuns(): Promise { @@ -646,12 +701,16 @@ export class ScheduleService { error: "Daemon restarted before the scheduled run completed", }; updated = { ...updated, runs }; - if (shouldCompleteSchedule(updated, now)) { - updated = completeSchedule(updated, now); - } dirty = true; } + if ( + (updated.status === "active" || runningIndex !== -1) && + shouldCompleteSchedule(updated, now) + ) { + return completeSchedule(updated, now); + } + if ( updated.status === "active" && updated.nextRunAt && @@ -778,7 +837,7 @@ export class ScheduleService { now: Date, ): Promise<{ schedule: StoredSchedule; runId: string } | null> { let claimed: { schedule: StoredSchedule; runId: string } | null = null; - const updatedSchedule = await this.store.update(scheduleId, (schedule) => { + await this.store.update(scheduleId, (schedule) => { if ( schedule.status !== "active" || !schedule.nextRunAt || @@ -821,7 +880,6 @@ export class ScheduleService { claimed = { schedule: updated, runId }; return updated; }); - requireSchedule(updatedSchedule, scheduleId); return claimed; } @@ -847,7 +905,8 @@ export class ScheduleService { targetGone: boolean; manual: boolean; }): Promise { - const updatedSchedule = await this.store.update(params.scheduleId, (schedule) => { + // A Stop can delete the schedule while its already launched turn is still running. + await this.store.update(params.scheduleId, (schedule) => { const now = this.now(); const completedRuns = schedule.runs.map((run) => run.id === params.runId @@ -900,7 +959,6 @@ export class ScheduleService { return updated; }); - requireSchedule(updatedSchedule, params.scheduleId); } private async recordRunWorkspace(params: { diff --git a/packages/server/src/server/schedule/store.ts b/packages/server/src/server/schedule/store.ts index 6feee5bc85..964adfeb93 100644 --- a/packages/server/src/server/schedule/store.ts +++ b/packages/server/src/server/schedule/store.ts @@ -100,6 +100,17 @@ function parseStoredSchedule( return StoredScheduleSchema.safeParse(json); } +async function readScheduleFile(filePath: string): Promise { + try { + return await readFile(filePath, "utf-8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; + } +} + export class ScheduleStore { private readonly scheduleMutations = new Map>(); private readonly identityMutations = new Map>(); @@ -108,6 +119,7 @@ export class ScheduleStore { constructor( private readonly dir: string, private readonly logger: Logger, + private readonly onChange?: (schedule: StoredSchedule, change: "write" | "delete") => void, ) {} private filePath(id: string): string { @@ -128,12 +140,17 @@ export class ScheduleStore { .filter((entry) => entry.isFile() && entry.name.endsWith(".json")) .map(async (entry) => { const filePath = join(this.dir, entry.name); - return { filePath, parsed: parseStoredSchedule(await readFile(filePath, "utf-8")) }; + const content = await readScheduleFile(filePath); + return content === null ? null : { filePath, parsed: parseStoredSchedule(content) }; }), ); const schedules: StoredSchedule[] = []; const invalidFiles = new Set(); - for (const { filePath, parsed } of files) { + for (const file of files) { + if (!file) { + continue; + } + const { filePath, parsed } = file; if (parsed.success) { schedules.push(parsed.data); continue; @@ -149,21 +166,16 @@ export class ScheduleStore { async get(id: string): Promise { await this.ensureDir(); - try { - const content = await readFile(this.filePath(id), "utf-8"); - return StoredScheduleSchema.parse(JSON.parse(content)); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return null; - } - throw error; - } + const content = await readScheduleFile(this.filePath(id)); + return content === null ? null : StoredScheduleSchema.parse(JSON.parse(content)); } async create(schedule: Omit): Promise { const created = StoredScheduleSchema.parse({ ...schedule, id: generateScheduleId() }); - await this.write(created); - return created; + return this.serializeScheduleMutation(created.id, async () => { + await this.write(created); + return created; + }); } async update(id: string, updater: ScheduleUpdater): Promise { @@ -204,8 +216,10 @@ export class ScheduleStore { if (!matchesNameAndTarget(created, name, target)) { throw new Error("Created schedule does not match requested identity"); } - await this.write(created); - return created; + return this.serializeScheduleMutation(created.id, async () => { + await this.write(created); + return created; + }); } const updated = await this.updateMatchedSchedule(existing.id, name, target, options.update); @@ -219,12 +233,22 @@ export class ScheduleStore { private async write(schedule: StoredSchedule): Promise { await this.ensureDir(); await writeJsonFileAtomic(this.filePath(schedule.id), schedule); + this.onChange?.(schedule, "write"); } - async delete(id: string): Promise { + async delete( + id: string, + assertDeletable?: (schedule: StoredSchedule | null) => void, + ): Promise { await this.serializeScheduleMutation(id, async () => { - await this.ensureDir(); + const content = await readScheduleFile(this.filePath(id)); + const parsed = content === null ? null : parseStoredSchedule(content); + const schedule = parsed?.success ? parsed.data : null; + assertDeletable?.(schedule); await rm(this.filePath(id), { force: true }); + if (schedule) { + this.onChange?.(schedule, "delete"); + } }); } diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index 83ed767460..adafdc7eb4 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -48,7 +48,10 @@ import type { StoredAgentRecord } from "./agent/agent-storage.js"; import type { AgentManagerEvent } from "./agent/agent-manager.js"; import type { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js"; import { WorkspaceLabelError, type WorkspaceLabelService } from "./workspace-labels/index.js"; -import { createPersistedProjectRecord } from "./workspace-registry.js"; +import { + createPersistedProjectRecord, + createPersistedWorkspaceRecord, +} from "./workspace-registry.js"; import { deriveProjectKey } from "./project-key.js"; import type { SessionOptions } from "./session.js"; import type { SessionInboundMessage, SessionOutboundMessage } from "./messages.js"; @@ -6142,6 +6145,7 @@ test("answers an agent background work list request", async () => { const messages: SessionOutboundMessage[] = []; const session = createSessionForTest({ messages, + permissions: ["workspace.read", "workspace.write"], agentManager: { waitForAgentClose: vi.fn().mockResolvedValue(undefined), getAgent: vi.fn(() => ({ id: "agent-a" })), @@ -6151,6 +6155,8 @@ test("answers an agent background work list request", async () => { id: "bash-1", kind: "shell", description: "sleep 20", + canStop: true, + stopToken: "provider-token", startedAt: "2026-10-06T10:00:00.000Z", }, ]), @@ -6173,6 +6179,8 @@ test("answers an agent background work list request", async () => { id: "bash-1", kind: "shell", description: "sleep 20", + canStop: true, + stopToken: "provider-token", startedAt: "2026-10-06T10:00:00.000Z", }, ], @@ -6181,6 +6189,228 @@ test("answers an agent background work list request", async () => { }); }); +const heartbeatBackgroundWork = { + id: "heartbeat:heartbeat-a", + kind: "heartbeat", + description: "Check progress", + startedAt: "2026-10-06T10:00:00.000Z", + canStop: true, + stopToken: "heartbeat-token", +}; + +test.each([ + { permissions: ["workspace.read"], canStop: false }, + { permissions: ["workspace.read", "automation.manage"], canStop: false }, + { permissions: ["workspace.read", "workspace.write"], canStop: false }, + { permissions: ["workspace.read", "hub.execute", "automation.manage"], canStop: true }, +] satisfies Array<{ permissions: DaemonPermission[]; canStop: boolean }>)( + "filters dormant heartbeat controls for $permissions on list and update", + async ({ permissions, canStop }) => { + const messages: SessionOutboundMessage[] = []; + let listener: ((event: AgentManagerEvent) => void) | undefined; + const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }); + const session = createSessionForTest({ + messages, + permissions, + agentManager: { + getAgent: () => undefined, + getAgentBackgroundWorkSummary: () => ({ count: 1 }), + listAgentBackgroundWork: () => [heartbeatBackgroundWork], + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, + }, + agentStorage: { get: async () => record }, + }); + await session.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "subscribe-heartbeat", + events: ["agent.background_work.update"], + }); + await session.handleMessage({ + type: "agent.background_work.list.request", + requestId: "list-heartbeat", + agentId: record.id, + }); + if (!listener) throw new Error("Agent event listener was not installed"); + listener({ + type: "background_work", + agentId: record.id, + items: [heartbeatBackgroundWork], + }); + + const { canStop: _canStop, stopToken: _token, ...readOnly } = heartbeatBackgroundWork; + const items = [canStop ? heartbeatBackgroundWork : readOnly]; + expect(findByType(messages, "agent.background_work.list.response")?.payload).toEqual({ + requestId: "list-heartbeat", + agentId: record.id, + items, + error: null, + }); + await expect + .poll(() => findByType(messages, "agent.background_work.update")?.payload) + .toEqual({ agentId: record.id, items }); + + await session.cleanup(); + }, +); + +test("publishes the current dormant inventory when an older update waits on storage", async () => { + const messages: SessionOutboundMessage[] = []; + const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }); + const pendingRecord = deferred(); + let firstRead = true; + let listener: ((event: AgentManagerEvent) => void) | undefined; + let items = [heartbeatBackgroundWork]; + const session = createSessionForTest({ + messages, + agentManager: { + getAgent: () => null, + getAgentBackgroundWorkSummary: () => (items.length ? { count: items.length } : undefined), + listAgentBackgroundWork: () => items, + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, + }, + agentStorage: { + get: async () => { + if (!firstRead) return record; + firstRead = false; + return pendingRecord.promise; + }, + }, + }); + await session.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "subscribe-delayed-inventory", + events: ["agent.background_work.update"], + }); + + if (!listener) throw new Error("Agent event listener was not installed"); + listener({ type: "background_work", agentId: record.id, items }); + items = []; + listener({ type: "background_work", agentId: record.id, items }); + await expect + .poll(() => findByType(messages, "agent.background_work.update")?.payload.items) + .toEqual([]); + + pendingRecord.resolve(record); + await new Promise((resolve) => setImmediate(resolve)); + const updates = messages.filter((message) => message.type === "agent.background_work.update"); + expect(updates.every((message) => message.payload.items.length === 0)).toBe(true); + await session.cleanup(); +}); + +test("passes the automation grant to the dormant background work stop operation", async () => { + const messages: SessionOutboundMessage[] = []; + const stops: Parameters[0][] = []; + const record = createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }); + const session = createSessionForTest({ + messages, + permissions: ["workspace.read", "automation.manage"], + agentManager: { + getAgent: () => undefined, + stopAgentBackgroundWork: async ( + request: Parameters[0], + ) => { + stops.push(request); + }, + }, + agentStorage: { get: async () => record }, + }); + const request = { + type: "agent.background_work.stop.request", + requestId: "stop-heartbeat", + agentId: record.id, + itemId: heartbeatBackgroundWork.id, + stopToken: heartbeatBackgroundWork.stopToken, + } as const; + await session.handleMessage({ ...request, requestId: "stop-heartbeat-read-only" }); + expect(findByType(messages, "rpc_error")?.payload.code).toBe("access_denied"); + session.setPermissions(["workspace.read", "workspace.write"]); + await session.handleMessage(request); + session.setPermissions(["workspace.read", "workspace.write", "automation.manage"]); + await session.handleMessage({ ...request, requestId: "stop-heartbeat-owner" }); + + const { agentId, itemId, stopToken } = request; + expect(stops).toEqual([ + { agentId, itemId, stopToken, canManageAutomation: false }, + { agentId, itemId, stopToken, canManageAutomation: true }, + ]); + expect(findByType(messages, "agent.background_work.stop.response")?.payload.error).toBeNull(); + await session.cleanup(); +}); + +test("projects dormant heartbeat counts in directory snapshots and live updates", async () => { + const messages: SessionOutboundMessage[] = []; + let listener: ((event: AgentManagerEvent) => void) | undefined; + let count = 1; + const record = createStoredAgentRecord({ + id: "agent-a", + workspaceId: "workspace-a", + cwd: "/tmp/repo", + }); + const workspace = createPersistedWorkspaceRecord({ + workspaceId: "workspace-a", + projectId: "project-a", + cwd: record.cwd, + kind: "directory", + displayName: "Workspace", + createdAt: record.createdAt, + updatedAt: record.updatedAt, + }); + const project = createPersistedProjectRecord({ + projectId: workspace.projectId, + rootPath: workspace.cwd, + kind: "non_git", + displayName: "Project", + createdAt: record.createdAt, + updatedAt: record.updatedAt, + }); + const providers = createProviderSnapshotManagerStub(); + providers.listRegisteredProviderIds.mockReturnValue([record.provider]); + const session = createSessionForTest({ + messages, + providerSnapshotManager: providers.manager, + permissions: ["workspace.read"], + agentManager: { + getAgent: () => undefined, + getAgentBackgroundWorkSummary: () => (count ? { count } : undefined), + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, + }, + agentStorage: { get: async () => record, listAll: async () => [record] }, + workspaceRegistry: { get: vi.fn(async () => workspace) }, + projectRegistry: { get: async () => project }, + }); + + await session.handleMessage({ + type: "fetch_agents_request", + requestId: "list-heartbeat-agents", + subscribe: { subscriptionId: "heartbeat-agents" }, + }); + expect(findByType(messages, "fetch_agents_response")?.payload.entries).toMatchObject([ + { agent: { id: record.id, backgroundWork: { count: 1 } } }, + ]); + + if (!listener) throw new Error("Agent event listener was not installed"); + count = 0; + listener({ type: "background_work", agentId: record.id, items: [] }); + await expect + .poll(() => findByType(messages, "agent_update")?.payload) + .toMatchObject({ + kind: "upsert", + agent: { id: record.id }, + }); + const update = findByType(messages, "agent_update")?.payload; + expect(update?.kind === "upsert" && update.agent.backgroundWork).toBeUndefined(); + await session.cleanup(); +}); + test("reports an unavailable inventory for a stored agent without loading it", async () => { const messages: SessionOutboundMessage[] = []; const resumeAgentFromPersistence = vi.fn(); @@ -6244,8 +6474,9 @@ test.each([ record: createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo", internal: true }), error: "Unknown agent 'agent-a'", }, -])("rejects a background work list request for $name that is not loaded", async (scenario) => { +])("rejects background work control and updates for $name that is not loaded", async (scenario) => { const messages: SessionOutboundMessage[] = []; + let listener: ((event: AgentManagerEvent) => void) | undefined; const session = createSessionForTest({ messages, agentManager: { @@ -6254,20 +6485,45 @@ test.each([ getRegisteredProviderIds: vi.fn(() => ["codex"]), resumeAgentFromPersistence: vi.fn(), createAgent: vi.fn(), + subscribe: (callback: (event: AgentManagerEvent) => void) => { + listener = callback; + return () => {}; + }, }, agentStorage: { get: vi.fn().mockResolvedValue(scenario.record) }, }); + await session.handleMessage({ + type: "session.events.set_subscription.request", + requestId: "subscribe-background-work", + events: ["agent.background_work.update"], + }); await session.handleMessage({ type: "agent.background_work.list.request", agentId: "agent-a", requestId: "list-rejected", }); + await session.handleMessage({ + type: "agent.background_work.stop.request", + requestId: "stop-rejected", + agentId: "agent-a", + itemId: heartbeatBackgroundWork.id, + stopToken: heartbeatBackgroundWork.stopToken, + }); + if (!listener) throw new Error("Agent event listener was not installed"); + listener({ type: "background_work", agentId: "agent-a", items: [heartbeatBackgroundWork] }); + await new Promise((resolve) => setImmediate(resolve)); + expect(messages).toContainEqual({ type: "agent.background_work.list.response", payload: { requestId: "list-rejected", agentId: "agent-a", items: [], error: scenario.error }, }); + expect(findByType(messages, "agent.background_work.stop.response")?.payload.error).toBe( + scenario.error, + ); + expect(findByType(messages, "agent.background_work.update")).toBeUndefined(); + await session.cleanup(); }); test("never pushes background work to an old app", async () => { @@ -6284,6 +6540,7 @@ test("never pushes background work to an old app", async () => { return () => {}; }), }, + agentStorage: { get: async () => createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }) }, }); // provider_subagents makes subagent updates flow to this legacy socket, so the // manager listener is installed for it. @@ -6300,6 +6557,7 @@ test("never pushes background work to an old app", async () => { ], }); + await new Promise((resolve) => setImmediate(resolve)); const pushed = [...messages, ...targetedMessages.map((entry) => entry.message)]; expect(pushed.some((message) => message.type === "agent.background_work.update")).toBe(false); }); @@ -6307,19 +6565,6 @@ test("never pushes background work to an old app", async () => { test("pushes background work only to clients that subscribed to it", async () => { const messages: SessionOutboundMessage[] = []; const agentEventListeners: Array<(event: AgentManagerEvent) => void> = []; - const session = createSessionForTest({ - messages, - agentManager: { - getAgent: vi.fn(() => undefined), - subscribe: vi.fn((listener: (event: AgentManagerEvent) => void) => { - agentEventListeners.push(listener); - return () => {}; - }), - }, - }); - const forward = (event: AgentManagerEvent) => { - for (const listener of agentEventListeners) listener(event); - }; const event: AgentManagerEvent = { type: "background_work", agentId: "agent-a", @@ -6327,6 +6572,22 @@ test("pushes background work only to clients that subscribed to it", async () => { id: "bash-1", kind: "shell", description: null, startedAt: "2026-10-06T10:00:00.000Z" }, ], }; + const session = createSessionForTest({ + messages, + agentManager: { + getAgent: vi.fn(() => undefined), + getAgentBackgroundWorkSummary: () => ({ count: event.items.length }), + listAgentBackgroundWork: () => event.items, + subscribe: vi.fn((listener: (event: AgentManagerEvent) => void) => { + agentEventListeners.push(listener); + return () => {}; + }), + }, + agentStorage: { get: async () => createStoredAgentRecord({ id: "agent-a", cwd: "/tmp/repo" }) }, + }); + const forward = () => { + for (const listener of agentEventListeners) listener(event); + }; // Subscribe to an unrelated event so the manager listener is installed, then prove // a client that did not ask for background work never receives it. @@ -6336,7 +6597,8 @@ test("pushes background work only to clients that subscribed to it", async () => events: ["agent.provider_subagents.update"], }); if (agentEventListeners.length === 0) throw new Error("Agent event listener was not installed"); - forward(event); + forward(); + await new Promise((resolve) => setImmediate(resolve)); expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false); await session.handleMessage({ @@ -6346,14 +6608,16 @@ test("pushes background work only to clients that subscribed to it", async () => }); messages.length = 0; - forward(event); + forward(); - expect(messages).toContainEqual( - expect.objectContaining({ - type: "agent.background_work.update", - payload: expect.objectContaining({ agentId: "agent-a", items: event.items }), - }), - ); + await expect + .poll(() => messages) + .toContainEqual( + expect.objectContaining({ + type: "agent.background_work.update", + payload: expect.objectContaining({ agentId: "agent-a", items: event.items }), + }), + ); }); test("does not publish internal agents' background work to subscribed clients", async () => { @@ -6363,7 +6627,7 @@ test("does not publish internal agents' background work to subscribed clients", messages, agentManager: { getAgent: () => ({ id: "internal-agent", internal: true }) as never, - subscribe: (callback) => { + subscribe: (callback: (event: AgentManagerEvent) => void) => { listener = callback; return () => {}; }, @@ -6383,5 +6647,6 @@ test("does not publish internal agents' background work to subscribed clients", { id: "work", kind: "shell", description: "private", startedAt: "2026-10-06T10:00:00.000Z" }, ], }); + await new Promise((resolve) => setImmediate(resolve)); expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false); }); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 6b2b9f0f34..2bdad76ba3 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -23,7 +23,10 @@ import { isAbsolute } from "node:path"; import { CreationService, type CreatedAgent } from "./creation/index.js"; import type { CreationSnapshot, AgentCreateRequest } from "@getpaseo/protocol/messages"; import type { MessageReceipts } from "./message-receipts/index.js"; -import type { AgentBackgroundWorkItem } from "./agent/background-work/index.js"; +import { + isHeartbeatBackgroundWorkItem, + type AgentBackgroundWorkItem, +} from "./agent/background-work/index.js"; import equal from "fast-deep-equal"; import { WorkspaceSetupObservation } from "./workspace-setup-observation.js"; import { SessionDelivery, type OwnedSubscription } from "./session/owned-subscriptions/index.js"; @@ -2180,7 +2183,12 @@ export class Session { } if (event.type === "background_work") { - this.forwardBackgroundWork(event); + void this.forwardBackgroundWork(event.agentId).catch((error) => + this.sessionLogger.error( + { err: error, agentId: event.agentId }, + "Failed to emit background work update", + ), + ); return; } @@ -2263,16 +2271,34 @@ export class Session { this.forwardProviderSubagentUpdate(event); } - private forwardBackgroundWork( - event: Extract, - ): void { - const agent = this.agentManager.getAgent(event.agentId); - if (agent?.internal) return; + private async forwardBackgroundWork(agentId: string): Promise { + const target = await this.resolveBackgroundWorkAgent(agentId); + if ("error" in target) return; + const { agent, record } = target; + // The inventory may have changed while resolving a dormant agent. + const items = this.agentManager.getAgentBackgroundWorkSummary(agentId) + ? this.agentManager.listAgentBackgroundWork(agentId) + : []; this.emit({ type: "agent.background_work.update", - payload: { agentId: event.agentId, items: event.items }, + payload: { agentId, items: this.projectBackgroundWorkItems(items) }, + }); + if (agent) await this.agentUpdates.forwardLiveAgent(agent); + else if (record) await this.agentUpdates.forwardStoredAgent(record); + } + + private projectBackgroundWorkItems(items: AgentBackgroundWorkItem[]): AgentBackgroundWorkItem[] { + if ( + this.authorization.allowsPermission("automation.manage") && + this.authorization.allowsInbound({ type: "agent.background_work.stop.request" }) + ) { + return items; + } + return items.map((item) => { + if (!isHeartbeatBackgroundWorkItem(item)) return item; + const { canStop: _canStop, stopToken: _stopToken, ...visible } = item; + return visible; }); - if (agent) void this.agentUpdates.forwardLiveAgent(agent); } private emitProviderSubagentWorkspaceUpdate(event: ProviderSubagentManagerEvent): void { @@ -2307,10 +2333,12 @@ export class Session { } private async enrichAgentPayload(payload: AgentSnapshotPayload): Promise { - payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id); const storedRecord = await this.agentStorage.get(payload.id); payload.title = storedRecord?.title ?? null; payload.archivedAt = storedRecord?.archivedAt ?? null; + if (!payload.internal && !storedRecord?.internal && !payload.archivedAt) { + payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id); + } return payload; } @@ -2322,8 +2350,11 @@ export class Session { record: StoredAgentRecord, registeredProviderIds = new Set(this.providerSnapshotManager.listRegisteredProviderIds()), ): AgentSnapshotPayload { - return buildStoredAgentPayload(record, registeredProviderIds, (provider, own) => - this.agentManager.effectiveOptionsFor(provider, own), + return buildStoredAgentPayload( + record, + registeredProviderIds, + (provider, own) => this.agentManager.effectiveOptionsFor(provider, own), + this.agentManager.getAgentBackgroundWorkSummary(record.id), ); } @@ -8685,10 +8716,13 @@ export class Session { ): Promise { let error: string | null = null; try { + const target = await this.resolveBackgroundWorkAgent(msg.agentId); + if ("error" in target) throw new Error(target.error); await this.agentManager.stopAgentBackgroundWork({ agentId: msg.agentId, itemId: msg.itemId, stopToken: msg.stopToken, + canManageAutomation: this.authorization.allowsPermission("automation.manage"), }); } catch (cause) { error = cause instanceof Error ? cause.message : String(cause); @@ -8730,23 +8764,27 @@ export class Session { } } - // Background work lives only in memory, so an agent that is not loaded has none. - // Answering from storage keeps a read from resuming a dormant agent. private async readAgentBackgroundWork(agentId: string): Promise { - if (this.agentManager.getAgent(agentId)) { - if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) { - throw new Error("Background work inventory is unavailable"); - } - return this.agentManager.listAgentBackgroundWork(agentId); + const target = await this.resolveBackgroundWorkAgent(agentId); + if ("error" in target) throw new Error(target.error); + if (!this.agentManager.getAgentBackgroundWorkSummary(agentId)) { + throw new Error("Background work inventory is unavailable"); } + return this.projectBackgroundWorkItems(this.agentManager.listAgentBackgroundWork(agentId)); + } + + private async resolveBackgroundWorkAgent( + agentId: string, + ): Promise<{ agent: ManagedAgent | null; record: StoredAgentRecord | null } | { error: string }> { const record = await this.agentStorage.get(agentId); - if (!record || record.internal) { - throw new Error(`Unknown agent '${agentId}'`); + const agent = this.agentManager.getAgent(agentId); + if ((!agent && !record) || agent?.internal || record?.internal) { + return { error: `Unknown agent '${agentId}'` }; } - if (record.archivedAt) { - throw new Error(`Agent is archived: ${agentId}`); + if (record?.archivedAt) { + return { error: `Agent is archived: ${agentId}` }; } - throw new Error("Background work inventory is unavailable"); + return { agent, record }; } private async handleProviderSubagentTimelineRequest( diff --git a/packages/server/src/server/session/agent-updates/agent-updates-service.ts b/packages/server/src/server/session/agent-updates/agent-updates-service.ts index 789dcbe5c3..08cfb03582 100644 --- a/packages/server/src/server/session/agent-updates/agent-updates-service.ts +++ b/packages/server/src/server/session/agent-updates/agent-updates-service.ts @@ -44,6 +44,7 @@ export interface AgentUpdatesService { hasSubscription(): boolean; includesLiveAgent(agent: ManagedAgent, subscriptionIds?: ReadonlySet): Promise; forwardLiveAgent(agent: ManagedAgent): Promise; + forwardStoredAgent(record: StoredAgentRecord): Promise; emitStoredRecord(record: StoredAgentRecord): Promise; removeAgent(agentId: string): Promise; dispose(): void; @@ -302,10 +303,13 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU return payload; } - async function emitLiveAgentUpdate(payload: AgentSnapshotPayload): Promise { + async function emitAgentUpdate( + workspaceId: string | undefined, + projectPayload?: () => AgentSnapshotPayload | Promise, + ): Promise { try { - if (hasSubscription()) await publishPayload(await deps.enrichAgentPayload(payload)); - if (payload.workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(payload.workspaceId); + if (projectPayload && hasSubscription()) await publishPayload(await projectPayload()); + if (workspaceId) await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId); } catch (error) { deps.logger.error({ err: error }, "Failed to emit agent update"); } @@ -330,17 +334,20 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU if (!hasSubscription()) { const workspaceId = agent.workspaceId; return workspaceId - ? enqueueAgentUpdate(agent.id, async () => { - try { - await deps.emitWorkspaceUpdateForWorkspaceId(workspaceId); - } catch (error) { - deps.logger.error({ err: error }, "Failed to emit workspace update"); - } - }) + ? enqueueAgentUpdate(agent.id, () => emitAgentUpdate(workspaceId)) : Promise.resolve(); } const payload = toAgentPayload(agent); - return enqueueAgentUpdate(payload.id, () => emitLiveAgentUpdate(payload)); + return enqueueAgentUpdate(payload.id, () => + emitAgentUpdate(payload.workspaceId, () => deps.enrichAgentPayload(payload)), + ); + } + + function forwardStoredAgent(record: StoredAgentRecord): Promise { + if (!hasSubscription() && !record.workspaceId) return Promise.resolve(); + return enqueueAgentUpdate(record.id, () => + emitAgentUpdate(record.workspaceId, () => deps.buildStoredAgentPayload(record)), + ); } function removeAgent(agentId: string): Promise { @@ -362,6 +369,7 @@ export function createAgentUpdatesService(deps: AgentUpdatesServiceDeps): AgentU hasSubscription, includesLiveAgent, forwardLiveAgent, + forwardStoredAgent, emitStoredRecord, removeAgent, dispose,