mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-19 06:45:15 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c479d7b3d | ||
|
|
808766ed7f | ||
|
|
9faa3034f1 | ||
|
|
157abbbbda | ||
|
|
2c22e64644 | ||
|
|
b09b17e6ee | ||
|
|
f5d27b7901 | ||
|
|
4e78d15bdc | ||
|
|
2327701497 | ||
|
|
a6da22f86a | ||
|
|
a8456ee63f | ||
|
|
cf91362af4 | ||
|
|
4663f3e40f | ||
|
|
51baa2beb8 | ||
|
|
31b6c2ebd3 | ||
|
|
3da26f32ab | ||
|
|
bcf52f93b1 | ||
|
|
d8c98400fb | ||
|
|
77392d3c1b | ||
|
|
8edccf0503 | ||
|
|
ac633eb096 | ||
|
|
25ff8adf06 | ||
|
|
09a15abb06 | ||
|
|
81fb9c03f6 | ||
|
|
0e67045c4b | ||
|
|
50b2c7f9d9 | ||
|
|
f346e72691 | ||
|
|
a030e905e8 | ||
|
|
2a10550a02 | ||
|
|
32bdb9e7af | ||
|
|
a3c41ecc1d |
+22
-1
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath))
|
||||
- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery))
|
||||
- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto))
|
||||
- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82))
|
||||
- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid))
|
||||
- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem))
|
||||
- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun))
|
||||
- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### Fixed
|
||||
@@ -23,6 +44,7 @@
|
||||
- **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))
|
||||
- **fx provider:** Run [fx](https://paseo.sh/docs/supported-providers/fx), the coding agent from Vercel Labs, in Paseo. Add it from the provider catalog in Settings → Hosts → Providers. ([#9160](https://github.com/getpaseo/paseo/pull/9160))
|
||||
- **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))
|
||||
@@ -36,7 +58,6 @@
|
||||
- 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 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))
|
||||
|
||||
+22
-1
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复启用“折叠轮次”时,Claude 回复后续后台任务通知导致上一条已完成的回复被折叠的问题 ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- 修复归档工作区时丢失分离 HEAD 的 worktree 提交的问题 ([#10009](https://github.com/getpaseo/paseo/pull/10009),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复 Desktop 更新后,由上一次 Desktop 会话启动的旧版 daemon 仍在运行的问题 ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- 修复更改执行权限后 daemon 与 Hub 断开连接的问题 ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- 修复一条已保存的主机记录无法读取时,其他主机也消失的问题 ([#9847](https://github.com/getpaseo/paseo/pull/9847),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复创建 worktree 时,扫描 `.worktreeinclude` 未指定的大型忽略目录导致超时的问题 ([#10020](https://github.com/getpaseo/paseo/pull/10020),贡献者:[@mgranderath](https://github.com/mgranderath))
|
||||
- 修复发送引导消息时取消 Claude 正在进行的上下文压缩的问题 ([#10028](https://github.com/getpaseo/paseo/pull/10028),贡献者:[@NightMachinery](https://github.com/NightMachinery))
|
||||
- 修复 Provider 重用已取消的轮次 ID 时,再次停止导致 Agent 卡住的问题 ([#9774](https://github.com/getpaseo/paseo/pull/9774),贡献者:[@DAnaeto](https://github.com/DAnaeto))
|
||||
- 修复 Desktop 渲染进程意外退出后窗口一直空白的问题 ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- 修复 Web 和 Desktop 上文件下载失败时,错误页面占据应用窗口的问题 ([#9937](https://github.com/getpaseo/paseo/pull/9937),贡献者:[@panta82](https://github.com/panta82))
|
||||
- 修复在“导入会话”中选择“加载更多”时丢失滚动位置的问题 ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- 修复主目录所在的文件系统拒绝 Unix 套接字时无法打开终端的问题,例如 AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214),贡献者:[@bendavid](https://github.com/bendavid))
|
||||
- 修复 Git 监视器设置超时后反复扫描大型仓库的问题 ([#9828](https://github.com/getpaseo/paseo/pull/9828),贡献者:[@Spshulem](https://github.com/Spshulem))
|
||||
- 修复 `paseo workspace create --path .` 使用本地 daemon 的目录而非命令所在目录的问题 ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- 修复针对空闲 Agent 查询 MCP 状态或列表时漏报后台任务的问题 ([#10022](https://github.com/getpaseo/paseo/pull/10022),贡献者:[@ortschun](https://github.com/ortschun))
|
||||
- 修复 OMP 更改思考级别后,选择器仍显示旧级别的问题 ([#9841](https://github.com/getpaseo/paseo/pull/9841),贡献者:[@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### 修复
|
||||
@@ -23,6 +44,7 @@
|
||||
- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏,展示已连接主机上的工作区和 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))
|
||||
- **fx Provider**:在 Paseo 中运行 Vercel Labs 的编程 Agent [fx](https://paseo.sh/zh-CN/docs/supported-providers/fx)。在“设置 → Hosts → 提供方”的 Provider 目录中添加。 ([#9160](https://github.com/getpaseo/paseo/pull/9160))
|
||||
- **返回应用时更少提示**:返回没有变化的聊天时,不再闪现“正在更新消息”。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))
|
||||
@@ -36,7 +58,6 @@
|
||||
- 为 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 列表中 ([#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))
|
||||
|
||||
@@ -91,8 +91,12 @@ You need at least one agent CLI installed and configured with your credentials:
|
||||
- [GitHub Copilot](https://github.com/features/copilot/cli/)
|
||||
- [OpenCode](https://github.com/anomalyco/opencode)
|
||||
- [Pi](https://pi.dev)
|
||||
- [Antigravity](https://paseo.sh/docs/supported-providers#antigravity)
|
||||
- [Muse Code](https://paseo.sh/docs/muse-code)
|
||||
- [Antigravity](https://paseo.sh/docs/supported-providers/antigravity)
|
||||
- [Muse Code](https://paseo.sh/docs/supported-providers/muse-code)
|
||||
- [fx](https://paseo.sh/docs/supported-providers/fx)
|
||||
- [Hoplite](https://paseo.sh/docs/supported-providers/hoplite)
|
||||
|
||||
Paseo also runs Cursor, Gemini CLI, and many other agents. See [Supported providers](https://paseo.sh/docs/supported-providers) for the full list and setup steps.
|
||||
|
||||
### Desktop app (recommended)
|
||||
|
||||
|
||||
@@ -163,8 +163,16 @@ override a scroll away because they can arrive after the action that requested t
|
||||
|
||||
### Draw distance
|
||||
|
||||
`drawDistance` is 2000 px on each side of the viewport. A fling over rows that were never measured
|
||||
blanks the viewport until LegendList renders and measures them. Twelve flings over a chat with a
|
||||
The native timeline starts with one window-height of draw distance, up to 2000 px. This keeps
|
||||
nearby rows ready for a fling during placement. Once the chat is placed, history is visible, and
|
||||
the sidebar has settled, the timeline schedules expansion to 2000 px through two frame callbacks.
|
||||
The callbacks leave time for the reveal to paint. Verify the actual reveal on the device.
|
||||
A drag cancels a pending expansion and uses the existing buffer as the window moves. Expansion
|
||||
resumes when the gesture settles, including momentum. In an Android emulator capture, expanding
|
||||
the full buffer during the first fling changed the measured content height and returned the chat
|
||||
to the end mid-fling.
|
||||
A fling over rows that were never measured blanks the viewport
|
||||
until LegendList renders and measures them. Twelve flings over a chat with a
|
||||
15,000 px turn expanded, Android emulator, dev build:
|
||||
|
||||
| List | Blank viewport | Janky frames | p50 / p90 / p99 |
|
||||
@@ -179,9 +187,8 @@ With every turn collapsed, flinging from a cold open into history did not blank
|
||||
|
||||
### LegendList patch
|
||||
|
||||
`patches/@legendapp+list+3.7.1.patch` carries twelve changes for the timeline. Its header lists
|
||||
them by purpose, and
|
||||
[legend-list #593](https://github.com/LegendApp/legend-list/issues/593) reports each upstream.
|
||||
`patches/@legendapp+list+3.7.1.patch` lists its changes by purpose.
|
||||
[legend-list #593](https://github.com/LegendApp/legend-list/issues/593) reports the first twelve.
|
||||
Drop a hunk when the installed LegendList ships its fix.
|
||||
|
||||
### Scroll view corrections
|
||||
|
||||
@@ -24,7 +24,7 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. The patch also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. The package patch is tracked by [upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997); remove the patch when the pinned release includes it.
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The patch also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. The package patch is tracked by [upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997); remove the patch when the pinned release includes it.
|
||||
|
||||
The package patch also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
|
||||
|
||||
+1
-1
@@ -129,7 +129,7 @@ availability and a diagnostic after the daemon resolves the executable. Configur
|
||||
environment, or enablement overrides under `agents.providers.muse`. Omit `extends` to keep
|
||||
the bundled integration; an entry with `extends` shadows it with a custom provider. See
|
||||
[provider contributions](#contribute-a-provider) for the contract and
|
||||
[Muse Code](../public-docs/muse-code.md) for setup, per-agent options, and version limitations.
|
||||
[Muse Code](../public-docs/supported-providers/muse-code.md) for setup, per-agent options, and version limitations.
|
||||
|
||||
## Install from a registry
|
||||
|
||||
|
||||
+4
-4
@@ -19,8 +19,8 @@ provider icon map. You do not need a core manifest entry or provider factory.
|
||||
|
||||
| Provider | Transport | Setup and limitations |
|
||||
| ----------- | ------------------------------------------ | ---------------------------------------------------------------- |
|
||||
| Antigravity | Installed `agy` CLI | [Antigravity](../public-docs/supported-providers.md#antigravity) |
|
||||
| Muse Code | MSP over one `muse serve` host per session | [Muse Code](../public-docs/muse-code.md) |
|
||||
| Antigravity | Installed `agy` CLI | [Antigravity](../public-docs/supported-providers/antigravity.md) |
|
||||
| Muse Code | MSP over one `muse serve` host per session | [Muse Code](../public-docs/supported-providers/muse-code.md) |
|
||||
|
||||
## Provider-native session options
|
||||
|
||||
@@ -50,8 +50,8 @@ or without a control.
|
||||
reject. A key the running session cannot apply (one the provider reads only when it opens) is
|
||||
rejected too, so a stored option always describes what runs. Claude reads most options when it
|
||||
starts its query, and replacing a started query would end its background work, so after the
|
||||
first prompt only Fast can change. Codex fixes its approval policy and sandbox when the thread
|
||||
starts, so it applies only `service_tier` and `plan_mode` live. A session with no
|
||||
first prompt only Fast and Ultracode can change. Codex fixes its approval policy and sandbox
|
||||
when the thread starts, so it applies only `service_tier` and `plan_mode` live. A session with no
|
||||
`applyOptions` rejects every patch; the daemon enforces this. The provider returns the options
|
||||
it ended up with when they differ from the request. The daemon stores the patch and that
|
||||
result in one step after the call resolves. Throwing rejects the whole patch and none of it is
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng=
|
||||
sha256-yLTaVMgu3tc/dgngJ7RP0htJcWE0ZtQ4mouypevyv0s=
|
||||
|
||||
Generated
+28
-28
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37468,7 +37468,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39637,13 +39637,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.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.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39906,7 +39906,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.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.1",
|
||||
"version": "0.16.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40195,7 +40195,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40225,7 +40225,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.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.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.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.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.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.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40295,7 +40295,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40517,17 +40517,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.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.1",
|
||||
"version": "0.16.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.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -2,9 +2,11 @@ import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
blurComposerInput,
|
||||
cancelAgent,
|
||||
fillComposerDraft,
|
||||
expectComposerDraft,
|
||||
expectComposerNotFocused,
|
||||
expectComposerVisible,
|
||||
submitMessage,
|
||||
} from "../support/helpers/composer";
|
||||
@@ -71,6 +73,7 @@ test.describe("Agent message rewind", () => {
|
||||
minDistanceFromBottom: 300,
|
||||
});
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
@@ -84,6 +87,7 @@ test.describe("Agent message rewind", () => {
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
|
||||
@@ -72,14 +72,12 @@ const ASSISTANT_MARKDOWN = [
|
||||
"| Current \\| active | ~~obsolete~~ | ready |",
|
||||
].join("\n");
|
||||
|
||||
const EXPECTED_WHOLE_SELECTION_MARKDOWN = ASSISTANT_MARKDOWN.replace(
|
||||
// text/plain carries the selection as displayed, so an inline code span the renderer
|
||||
// linked copies without its destination.
|
||||
const EXPECTED_WHOLE_SELECTION_TEXT = ASSISTANT_MARKDOWN.replace(
|
||||
"www.example.com stays",
|
||||
"[www.example.com](http://www.example.com) stays",
|
||||
)
|
||||
.replace(
|
||||
"`https://example.com/generated` stays",
|
||||
"[`https://example.com/generated`](https://example.com/generated) stays",
|
||||
)
|
||||
.replace(`${CROSS_STRUCTURE_MARKDOWN}\n\n`, "")
|
||||
.replace(
|
||||
"<https://autolink.example.com>",
|
||||
@@ -422,7 +420,7 @@ test("copying an assistant selection preserves Markdown structure and links", as
|
||||
await copySelection(page);
|
||||
|
||||
const clipboard = await readRichClipboard(page);
|
||||
expect(clipboard.plainText).toBe(EXPECTED_WHOLE_SELECTION_MARKDOWN);
|
||||
expect(clipboard.plainText).toBe(EXPECTED_WHOLE_SELECTION_TEXT);
|
||||
expect(clipboard.html).not.toContain("<ul>");
|
||||
expect(clipboard.html).not.toContain("<li>");
|
||||
expect(clipboard.html).toContain("<div>- ");
|
||||
@@ -688,6 +686,77 @@ test("copying an assistant selection preserves Markdown structure and links", as
|
||||
}
|
||||
});
|
||||
|
||||
test("pasting an assistant selection preserves literal underscores and authored links", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "assistant-selection-paste-",
|
||||
title: "Assistant selection paste",
|
||||
initialPrompt: "Render the paste fixture.",
|
||||
featureValues: {
|
||||
mockAssistantResponse:
|
||||
"Keep \\_literal\\_ and `https://example.com/generated` beside [the docs](https://example.com/docs).",
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await allowRichClipboard(context);
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await openAgentRoute(page, agent);
|
||||
|
||||
const message = assistantMessageBlocks(page);
|
||||
await expect(message.locator('a[href="https://example.com/generated"]')).toHaveText(
|
||||
"https://example.com/generated",
|
||||
);
|
||||
await selectAssistantTextRange(page, "Keep _literal_", "the docs.");
|
||||
await copySelection(page);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const fields = document.createElement("div");
|
||||
fields.style.cssText =
|
||||
"position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
|
||||
const plainText = document.createElement("textarea");
|
||||
plainText.setAttribute("aria-label", "Plain text paste");
|
||||
const richText = document.createElement("div");
|
||||
richText.contentEditable = "true";
|
||||
richText.setAttribute("role", "textbox");
|
||||
richText.setAttribute("aria-label", "Rich text paste");
|
||||
fields.append(plainText, richText);
|
||||
document.body.append(fields);
|
||||
});
|
||||
|
||||
const plainText = page.getByRole("textbox", { name: "Plain text paste" });
|
||||
await plainText.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
await expect(plainText).toHaveValue(
|
||||
"Keep _literal_ and `https://example.com/generated` beside [the docs](https://example.com/docs).",
|
||||
);
|
||||
|
||||
const richText = page.getByRole("textbox", { name: "Rich text paste" });
|
||||
await richText.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
await expect(richText).toHaveText(
|
||||
"Keep _literal_ and https://example.com/generated beside the docs.",
|
||||
);
|
||||
await expect(richText.locator("code")).toHaveText("https://example.com/generated");
|
||||
await expect(richText.getByRole("link")).toHaveCount(2);
|
||||
await expect(
|
||||
richText.getByRole("link", { name: "https://example.com/generated" }),
|
||||
).toHaveAttribute("href", "https://example.com/generated");
|
||||
await expect(richText.getByRole("link", { name: "the docs" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com/docs",
|
||||
);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
|
||||
context,
|
||||
page,
|
||||
|
||||
@@ -26,7 +26,7 @@ test.use({
|
||||
},
|
||||
});
|
||||
|
||||
// Rendered light-theme colors: palette yellow 400 for Fast and Ultrafast, muted foreground for Normal.
|
||||
// The Speed icon highlights any explicit tier other than Normal.
|
||||
const ACTIVE_SPEED_COLOR = "rgb(251, 191, 36)";
|
||||
const NORMAL_SPEED_COLOR = "rgb(113, 113, 122)";
|
||||
|
||||
@@ -63,7 +63,7 @@ async function expectSpeedIconColor(page: Page, color: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function expectSpeedChoices(page: Page, choices: string[]): Promise<void> {
|
||||
for (const choice of ["Normal", "Fast", "Ultrafast"]) {
|
||||
for (const choice of ["Normal", "Flex", "Fast", "Ultrafast"]) {
|
||||
const option = page.getByText(choice, { exact: true }).last();
|
||||
if (choices.includes(choice)) {
|
||||
await expect(option).toBeVisible();
|
||||
@@ -115,21 +115,24 @@ for (const viewport of [
|
||||
await expectSpeedIconColor(page, ACTIVE_SPEED_COLOR);
|
||||
await page.screenshot({ path: testInfo.outputPath(`${viewport.name}-fast-selected.png`) });
|
||||
await openSpeedSelector(page);
|
||||
await expectSpeedChoices(page, ["Normal", "Fast", "Ultrafast"]);
|
||||
await expectSpeedChoices(page, ["Normal", "Flex", "Fast", "Ultrafast"]);
|
||||
await page.screenshot({ path: testInfo.outputPath(`${viewport.name}-speed-options.png`) });
|
||||
await selectSpeed(page, "Ultrafast");
|
||||
await expectSpeedIconColor(page, ACTIVE_SPEED_COLOR);
|
||||
await openSpeedSelector(page);
|
||||
await expectSpeedChoices(page, ["Normal", "Fast", "Ultrafast"]);
|
||||
await expectSpeedChoices(page, ["Normal", "Flex", "Fast", "Ultrafast"]);
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath(`${viewport.name}-ultrafast-selected.png`),
|
||||
});
|
||||
await selectSpeed(page, "Flex");
|
||||
await expectSpeedIconColor(page, ACTIVE_SPEED_COLOR);
|
||||
await openSpeedSelector(page);
|
||||
await selectSpeed(page, "Normal");
|
||||
await expectSpeedIconColor(page, NORMAL_SPEED_COLOR);
|
||||
if (viewport.name === "desktop") {
|
||||
await switchAgentModel(agent.id, "gpt-6-sol");
|
||||
await openSpeedSelector(page);
|
||||
await expectSpeedChoices(page, ["Normal", "Fast"]);
|
||||
await expectSpeedChoices(page, ["Normal", "Flex", "Fast"]);
|
||||
await page.screenshot({ path: testInfo.outputPath("desktop-fast-only.png") });
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import type { FormPreferences } from "@/create-agent-preferences/preferences";
|
||||
import { closeCommandCenter, openCommandCenter } from "../support/helpers/command-center";
|
||||
import {
|
||||
closeCommandCenter,
|
||||
openCommandCenter,
|
||||
openCommandCenterWithShortcut,
|
||||
} from "../support/helpers/command-center";
|
||||
import {
|
||||
enterComposerFullscreen,
|
||||
exitComposerFullscreen,
|
||||
expectComposerVisible,
|
||||
fillComposerDraft,
|
||||
resizeComposerViewport,
|
||||
} from "../support/helpers/composer";
|
||||
import {
|
||||
applyCommandCenterAgentControls,
|
||||
chooseCommandCenterAgentControl,
|
||||
@@ -14,8 +25,18 @@ import {
|
||||
} from "../support/helpers/command-center-agent-controls";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import {
|
||||
assertNewWorkspaceSidebarAndHeader,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
openGlobalNewWorkspaceComposer,
|
||||
selectNewWorkspaceProject,
|
||||
selectWorkspaceIsolation,
|
||||
submitNewWorkspacePrompt,
|
||||
} from "../support/helpers/new-workspace";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { closeMobileAgentSidebar, openMobileAgentSidebar } from "../support/helpers/sidebar";
|
||||
import { buildSchedulesRoute } from "@/utils/host-routes";
|
||||
|
||||
const CREATE_AGENT_PREFERENCES_KEY = "@paseo:create-agent-preferences";
|
||||
@@ -30,7 +51,7 @@ async function seedMockDraftPreferences(page: import("@playwright/test").Page):
|
||||
providerPreferences: {
|
||||
mock: {
|
||||
model: "five-minute-stream",
|
||||
mode: "load-test",
|
||||
mode: "approval-test",
|
||||
},
|
||||
},
|
||||
} satisfies FormPreferences),
|
||||
@@ -221,6 +242,94 @@ test.describe("Command Center agent controls", () => {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("applies New workspace model and mode choices before the first message", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "command-center-new-workspace-controls-" });
|
||||
await seedMockDraftPreferences(page);
|
||||
const client = await connectNewWorkspaceDaemonClient();
|
||||
|
||||
try {
|
||||
const backgroundAgent = await workspace.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title: "Background agent",
|
||||
model: "five-minute-stream",
|
||||
modeId: "approval-test",
|
||||
});
|
||||
await openAgentRoute(page, {
|
||||
workspaceId: workspace.workspaceId,
|
||||
agentId: backgroundAgent.id,
|
||||
});
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
await selectNewWorkspaceProject(page, workspace);
|
||||
await selectWorkspaceIsolation(page, "local");
|
||||
|
||||
await applyCommandCenterAgentControls(page, DRAFT_AGENT_CONTROL_CHOICES);
|
||||
await closeCommandCenter(page);
|
||||
await submitNewWorkspacePrompt(page, "Create with Command Center choices");
|
||||
const created = await assertNewWorkspaceSidebarAndHeader(page, {
|
||||
serverId: getServerId(),
|
||||
client,
|
||||
previousWorkspaceId: workspace.workspaceId,
|
||||
projectDisplayName: workspace.projectDisplayName,
|
||||
});
|
||||
|
||||
await expectWorkspaceAgentConfiguration(
|
||||
{ client: workspace.client, workspaceId: created.workspaceId },
|
||||
{ provider: "mock", model: "ten-second-stream", modeId: "load-test" },
|
||||
);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: backgroundAgent.id,
|
||||
provider: "mock",
|
||||
model: "five-minute-stream",
|
||||
modeId: "approval-test",
|
||||
});
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps draft settings searchable from the compact sidebar and fullscreen editor", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "command-center-fullscreen-draft-" });
|
||||
await seedMockDraftPreferences(page);
|
||||
|
||||
try {
|
||||
await openDraftComposer(page, workspace.workspaceId);
|
||||
await resizeComposerViewport(page, "portrait");
|
||||
await applyCompactComposerSettings(page);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("applies compact sidebar and fullscreen settings to the running agent", async ({ page }) => {
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "command-center-fullscreen-agent-",
|
||||
title: "Compact Command Center settings",
|
||||
model: "five-minute-stream",
|
||||
modeId: "approval-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await resizeComposerViewport(page, "portrait");
|
||||
await openAgentRoute(page, workspace);
|
||||
await applyCompactComposerSettings(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const DRAFT_AGENT_CONTROL_CHOICES = [
|
||||
@@ -233,3 +342,22 @@ async function openDraftComposer(page: import("@playwright/test").Page, workspac
|
||||
await clickNewChat(page);
|
||||
await waitForDraftComposer(page);
|
||||
}
|
||||
|
||||
async function applyCompactComposerSettings(page: import("@playwright/test").Page): Promise<void> {
|
||||
const [model, mode] = DRAFT_AGENT_CONTROL_CHOICES;
|
||||
await expectComposerVisible(page);
|
||||
await openMobileAgentSidebar(page);
|
||||
await openCommandCenter(page);
|
||||
await chooseCommandCenterAgentControl({ page, ...mode });
|
||||
await closeMobileAgentSidebar(page);
|
||||
|
||||
await fillComposerDraft(page, "First line\nSecond line\nThird line");
|
||||
await enterComposerFullscreen(page);
|
||||
await openCommandCenterWithShortcut(page);
|
||||
await chooseCommandCenterAgentControl({ page, ...model });
|
||||
await exitComposerFullscreen(page);
|
||||
|
||||
await openCommandCenterWithShortcut(page);
|
||||
await expectCommandCenterAgentControlSelected({ page, ...model });
|
||||
await expectCommandCenterAgentControlSelected({ page, ...mode });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { openWorkspaceWithAgents } from "../support/helpers/archive-tab";
|
||||
import {
|
||||
composerLocator,
|
||||
@@ -311,3 +311,86 @@ test.describe("Composer trailing disc on a new chat", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const SHORTCUT_MOD = process.platform === "darwin" ? "Meta" : "Control";
|
||||
|
||||
async function toggleModelPickerFromComposer(page: Page) {
|
||||
await composerLocator(page).focus();
|
||||
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
|
||||
}
|
||||
|
||||
async function expectModelPickerClosesFromSearch(page: Page) {
|
||||
const search = page.getByPlaceholder(/Search (all )?models/);
|
||||
await expect(search).toBeVisible();
|
||||
await search.focus();
|
||||
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
|
||||
await expect(search).toBeHidden();
|
||||
}
|
||||
|
||||
async function cycleComposerEffort(page: Page) {
|
||||
await composerLocator(page).focus();
|
||||
await page.keyboard.press(`${SHORTCUT_MOD}+Shift+Slash`);
|
||||
}
|
||||
|
||||
function modelControl(page: Page) {
|
||||
return page.getByRole("button", { name: "Select model (Ten second stream)", exact: true });
|
||||
}
|
||||
|
||||
function thinkingControl(page: Page, effort: string) {
|
||||
return page.getByRole("button", { name: `Select thinking option (${effort})`, exact: true });
|
||||
}
|
||||
|
||||
async function expectShortcutHint(
|
||||
page: Page,
|
||||
control: ReturnType<typeof modelControl>,
|
||||
label: string,
|
||||
) {
|
||||
await control.hover();
|
||||
const tooltip = page.getByRole("tooltip").filter({ hasText: label });
|
||||
await expect(tooltip).toContainText("/");
|
||||
}
|
||||
|
||||
test.describe("Composer model and effort shortcuts", () => {
|
||||
test("opens and closes the model picker and wraps effort in toolbar order", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-shortcuts-",
|
||||
title: "Composer shortcuts",
|
||||
model: "ten-second-stream",
|
||||
thinkingOptionId: "high",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await expect(thinkingControl(page, "High")).toBeVisible();
|
||||
|
||||
await test.step("Show both shortcuts in the toolbar tooltips", async () => {
|
||||
await expectShortcutHint(page, modelControl(page), "Change model");
|
||||
await expectShortcutHint(page, thinkingControl(page, "High"), "Thinking mode");
|
||||
});
|
||||
|
||||
await test.step("Toggle the picker with its search field focused", async () => {
|
||||
await toggleModelPickerFromComposer(page);
|
||||
await expectModelPickerClosesFromSearch(page);
|
||||
});
|
||||
|
||||
await test.step("Wrap from High to Low and advance to Medium", async () => {
|
||||
await cycleComposerEffort(page);
|
||||
await expect(thinkingControl(page, "Low")).toBeVisible();
|
||||
await cycleComposerEffort(page);
|
||||
await expect(thinkingControl(page, "Medium")).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("Toggle the folded picker and cycle effort in a compact window", async () => {
|
||||
await page.setViewportSize({ width: 480, height: 844 });
|
||||
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
|
||||
await expect(effortLabel).toHaveText("Medium");
|
||||
await toggleModelPickerFromComposer(page);
|
||||
await expectModelPickerClosesFromSearch(page);
|
||||
await cycleComposerEffort(page);
|
||||
await expect(effortLabel).toHaveText("High");
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -513,3 +513,37 @@ test("compact file sheets cover Explorer and return to its retained file list",
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function toggleCommentInMainEditor(page: Parameters<typeof ensureExplorerSidebar>[0]) {
|
||||
const editor = page.getByLabel("Source editor for comment.cs").getByRole("textbox");
|
||||
await expect(editor).toBeVisible();
|
||||
await editor.press(process.platform === "darwin" ? "Meta+Slash" : "Control+Slash");
|
||||
await expect(editor).toHaveText("// public class Example {}");
|
||||
}
|
||||
|
||||
test("keeps the comment shortcut in the editor beside an Explorer agent", async ({ page }) => {
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "explorer-comment-shortcut-",
|
||||
title: "Chat beside the editor",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
try {
|
||||
await writeFile(`${workspace.cwd}/comment.cs`, "public class Example {}");
|
||||
await openAgentRoute(page, workspace);
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Select model (Ten second stream)" }),
|
||||
).toBeVisible();
|
||||
await ensureExplorerSidebar(page);
|
||||
await dragTabIntoExplorer(page, `agent_${workspace.agentId}`);
|
||||
await expect(
|
||||
explorerSidebar(page).getByRole("button", { name: "Select model (Ten second stream)" }),
|
||||
).toBeVisible();
|
||||
await openFilesPanel(page);
|
||||
await openFileFromExplorer(page, "comment.cs");
|
||||
await explorerSidebar(page).getByTestId(`workspace-tab-agent_${workspace.agentId}`).click();
|
||||
await toggleCommentInMainEditor(page);
|
||||
await expect(page.getByPlaceholder(/Search (all )?models/)).toBeHidden();
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -16,6 +16,13 @@ import {
|
||||
expectComposerFullscreenControls,
|
||||
} from "../support/helpers/composer";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import {
|
||||
seedTerminalProfiles,
|
||||
selectLaunchOption,
|
||||
terminalPromptInput,
|
||||
} from "../support/helpers/new-workspace-launch";
|
||||
|
||||
test.use({ channel: "chromium", launchOptions: { args: ["--use-fake-device-for-media-stream"] } });
|
||||
|
||||
type WebSocketMessage = string | Buffer;
|
||||
|
||||
@@ -254,3 +261,82 @@ test("dictation shortcut leaves retained fullscreen and exposes recording contro
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function controlMicrophonePermission(page: Page) {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const { targetInfo } = await cdp.send("Target.getTargetInfo");
|
||||
const origin = new URL(page.url()).origin;
|
||||
return async (setting: "denied" | "granted") => {
|
||||
await cdp.send("Browser.setPermission", {
|
||||
permission: { name: "microphone" },
|
||||
setting,
|
||||
origin,
|
||||
browserContextId: targetInfo.browserContextId,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function startDictationByMic(page: Page) {
|
||||
return page.getByRole("button", { name: "Start dictation", exact: true }).click();
|
||||
}
|
||||
|
||||
function expectDictationPermissionError(page: Page) {
|
||||
return expect(page.getByTestId("message-input-root").getByRole("alert")).toHaveText(
|
||||
"Allow microphone access and try again.",
|
||||
);
|
||||
}
|
||||
|
||||
test("keeps the draft and retries from the mic after access is restored", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "dictation-permission-",
|
||||
title: "Dictation permission",
|
||||
});
|
||||
const draft = "Keep my draft";
|
||||
await installDictationFailureHarness(page);
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await fillComposerDraft(page, draft);
|
||||
|
||||
const setMicrophonePermission = await controlMicrophonePermission(page);
|
||||
await setMicrophonePermission("denied");
|
||||
await startDictationByMic(page);
|
||||
await expectDictationPermissionError(page);
|
||||
await expect(composerLocator(page)).toHaveValue(draft);
|
||||
|
||||
await setMicrophonePermission("granted");
|
||||
await startDictationByMic(page);
|
||||
await expect(page.getByRole("button", { name: "Cancel dictation", exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Allow microphone access and try again.")).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Cancel dictation", exact: true }).click();
|
||||
await expect(composerLocator(page)).toHaveValue(draft);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("shows dictation failure when the terminal prompt starts it by shortcut", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "terminal-dictation-permission-" });
|
||||
const profile = {
|
||||
id: "echo-prompt",
|
||||
name: "Echo prompt",
|
||||
command: "echo",
|
||||
args: ["{{{prompt}}}"],
|
||||
};
|
||||
const profiles = await seedTerminalProfiles([profile]);
|
||||
await installDictationFailureHarness(page);
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openNewWorkspaceComposer(page, workspace);
|
||||
await selectLaunchOption(page, profile.id);
|
||||
|
||||
const setMicrophonePermission = await controlMicrophonePermission(page);
|
||||
await setMicrophonePermission("denied");
|
||||
await terminalPromptInput(page).press("Control+d");
|
||||
await expectDictationPermissionError(page);
|
||||
} finally {
|
||||
await profiles.restore();
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,16 +1,29 @@
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import {
|
||||
closeCommandCenter,
|
||||
openCommandCenter,
|
||||
selectCommandCenterTab,
|
||||
} from "../support/helpers/command-center";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import {
|
||||
attachComposerTestImage,
|
||||
composerLocator,
|
||||
expectComposerDraft,
|
||||
expectComposerFocused,
|
||||
expectComposerNotFocused,
|
||||
expectComposerVisible,
|
||||
fillComposerDraft,
|
||||
submitMessage,
|
||||
submitMessageWithButton,
|
||||
} from "../support/helpers/composer";
|
||||
import { readReplicaCache, writeReplicaCache } from "../support/helpers/replica-cache-storage";
|
||||
import {
|
||||
disconnectViewedTimeline,
|
||||
releaseHeldCatchUp,
|
||||
restoreViewedTimelineHoldingCatchUp,
|
||||
} from "../support/helpers/timeline-resume";
|
||||
|
||||
// UI plumbing contract against the dev mock provider. Real-provider behavior is tested in `daemon-e2e/*-rewind.real.e2e.test.ts`.
|
||||
|
||||
@@ -33,6 +46,17 @@ async function selectRewindOption(page: Page, name: string): Promise<void> {
|
||||
await option.click();
|
||||
}
|
||||
|
||||
async function searchRewindActions(page: Page): Promise<Locator> {
|
||||
const palette = await openCommandCenter(page);
|
||||
await selectCommandCenterTab(palette, "Actions");
|
||||
await palette.getByRole("textbox").fill("rewind last turn");
|
||||
return palette;
|
||||
}
|
||||
|
||||
function rewindAction(palette: Locator, name: string): Locator {
|
||||
return palette.getByRole("button", { name: `${name} This action cannot be undone`, exact: true });
|
||||
}
|
||||
|
||||
async function rewriteCachedMessageAsLegacyRow(
|
||||
page: Page,
|
||||
input: { prompt: string; agentId: string; workspaceId: string },
|
||||
@@ -199,10 +223,6 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageCount(page, 2);
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
});
|
||||
await userMessage(page, firstPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").first().click();
|
||||
const rewindSheet = page.getByTestId("rewind-menu-content");
|
||||
@@ -217,6 +237,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
await submitMessage(page, replacementPrompt);
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
@@ -232,17 +253,7 @@ test.describe("Rewind sheet", () => {
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
@@ -253,12 +264,109 @@ test.describe("Rewind sheet", () => {
|
||||
await selectRewindOption(page, "Rewind conversation and files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("rewinds the latest turn from the Command Center", async ({ page }) => {
|
||||
const firstPrompt = "Keep this earlier turn.";
|
||||
const latestPrompt = "Edit this latest turn.";
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "rewind-command-center-e2e-",
|
||||
title: "Command Center rewind",
|
||||
initialPrompt: firstPrompt,
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
await submitMessage(page, latestPrompt);
|
||||
await expectUserMessageVisible(page, latestPrompt);
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
|
||||
const palette = await searchRewindActions(page);
|
||||
await expect(rewindAction(palette, "Rewind files")).toBeVisible();
|
||||
await expect(rewindAction(palette, "Rewind conversation and files")).toBeVisible();
|
||||
await rewindAction(palette, "Rewind conversation").click();
|
||||
|
||||
await expectUserMessageVisible(page, firstPrompt);
|
||||
await expect(userMessage(page, latestPrompt)).toHaveCount(0);
|
||||
await expectComposerDraft(page, latestPrompt);
|
||||
await expectComposerFocused(page);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("waits for the latest prompt before offering Command Center rewind after reconnect", async ({
|
||||
page,
|
||||
}) => {
|
||||
const cachedPrompt = "Keep the prompt that was visible before reconnect.";
|
||||
const latestPrompt = "Rewind the prompt sent while the app was disconnected.";
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "rewind-reconnect-e2e-",
|
||||
title: "Rewind after reconnect",
|
||||
initialPrompt: cachedPrompt,
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectUserMessageVisible(page, cachedPrompt);
|
||||
const initialPalette = await searchRewindActions(page);
|
||||
await expect(rewindAction(initialPalette, "Rewind conversation")).toBeVisible();
|
||||
await closeCommandCenter(page);
|
||||
|
||||
await disconnectViewedTimeline(page, gate);
|
||||
await session.client.sendAgentMessage(session.agentId, latestPrompt);
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
await restoreViewedTimelineHoldingCatchUp(page, gate);
|
||||
|
||||
const palette = await searchRewindActions(page);
|
||||
await expect(palette.getByText("No matches", { exact: true })).toBeVisible();
|
||||
await releaseHeldCatchUp(page, gate);
|
||||
await rewindAction(palette, "Rewind conversation").click();
|
||||
|
||||
await expectUserMessageVisible(page, cachedPrompt);
|
||||
await expectComposerDraft(page, latestPrompt);
|
||||
} finally {
|
||||
gate.restore();
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("hides rewind when the latest prompt only contains an attachment", async ({ page }) => {
|
||||
const session = await seedMockAgentWorkspace({
|
||||
repoPrefix: "rewind-image-only-e2e-",
|
||||
title: "Rewind image-only prompt",
|
||||
initialPrompt: "Earlier text prompt.",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
const palette = await searchRewindActions(page);
|
||||
await expect(rewindAction(palette, "Rewind conversation")).toBeVisible();
|
||||
await closeCommandCenter(page);
|
||||
|
||||
await attachComposerTestImage(page);
|
||||
await submitMessageWithButton(page, "");
|
||||
const imagePrompt = page.getByTestId("user-message").filter({
|
||||
has: page.getByRole("button", { name: "Open image attachment" }),
|
||||
});
|
||||
await expect(imagePrompt).toHaveAttribute("aria-busy", "false");
|
||||
await session.client.waitForFinish(session.agentId);
|
||||
|
||||
const reopened = await searchRewindActions(page);
|
||||
await expect(reopened.getByText("No matches", { exact: true })).toBeVisible();
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("surfaces rewind failures without crashing the page", async ({ page }) => {
|
||||
const firstPrompt = "emit 1 coalesced agent stream updates for failed rewind turn.";
|
||||
const rewindError = "No file checkpoint found for message rewind-failure-e2e.";
|
||||
@@ -277,6 +385,10 @@ test.describe("Rewind sheet", () => {
|
||||
|
||||
await expectUserMessageVisible(page, firstPrompt);
|
||||
|
||||
const palette = await searchRewindActions(page);
|
||||
await rewindAction(palette, "Rewind conversation").click();
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(rewindError);
|
||||
|
||||
await userMessage(page, firstPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").first().click();
|
||||
const rewindSheet = page.getByTestId("rewind-menu-content");
|
||||
|
||||
@@ -23,6 +23,8 @@ import {
|
||||
outlastUndoWindow,
|
||||
pressArchiveShortcut,
|
||||
pressUndoShortcut,
|
||||
readSidebarListLayout,
|
||||
recordLastRowBottomPerFrame,
|
||||
resizeSidebarToMinimum,
|
||||
rowArchiveButton,
|
||||
rowKebab,
|
||||
@@ -121,7 +123,7 @@ 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 ({
|
||||
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.clock.install({ time: Date.now() });
|
||||
@@ -136,18 +138,35 @@ test.describe("Workspace archive undo", () => {
|
||||
const worktree = await seedWorktree(page, "archive-toast-long-list");
|
||||
|
||||
const resting = await scrollSidebarListToEnd(page);
|
||||
expect(resting.listBottom - resting.rowBottoms.at(-1)!).toBeLessThan(resting.rowHeight);
|
||||
const restingEndGap = resting.listBottom - resting.rowBottoms.at(-1)!;
|
||||
expect(restingEndGap).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);
|
||||
// The list keeps its usual end gap, measured from the toast's top instead of its own bottom.
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const layout = await scrollSidebarListToEnd(page);
|
||||
return Math.round(toastBox.y - layout.rowBottoms.at(-1)!);
|
||||
})
|
||||
.toBe(Math.round(restingEndGap));
|
||||
|
||||
const frames = recordLastRowBottomPerFrame(page, 40);
|
||||
await outlastUndoWindow(page);
|
||||
const bottoms = await frames;
|
||||
await expect(archivedToast(page)).toHaveCount(0);
|
||||
expect(await scrollSidebarListToEnd(page)).toEqual(withToast);
|
||||
|
||||
// Without scrolling again, the list ends just below its last row once more.
|
||||
const settled = await readSidebarListLayout(page);
|
||||
expect(settled.listBottom - settled.rowBottoms.at(-1)!).toBeCloseTo(restingEndGap, 0);
|
||||
// The rows travel down by the toast's height over several frames, never in one jump.
|
||||
const travel = bottoms.at(-1)! - bottoms[0]!;
|
||||
expect(travel).toBeGreaterThan(toastBox.height);
|
||||
const steps = bottoms.slice(1).map((bottom, index) => bottom - bottoms[index]!);
|
||||
expect(Math.min(...steps)).toBeGreaterThanOrEqual(0);
|
||||
expect(Math.max(...steps)).toBeLessThan(travel / 2);
|
||||
} finally {
|
||||
for (const projectId of fillerProjectIds) {
|
||||
await client.removeProject(projectId).catch(() => undefined);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { gotoAppShell } from "../support/helpers/app";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import { openWorkspaceSidebarKebab } from "../support/helpers/sidebar";
|
||||
import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
|
||||
|
||||
interface SessionEnvelope {
|
||||
@@ -114,11 +115,7 @@ async function expectAssigned(
|
||||
}
|
||||
|
||||
async function openWorkspaceLabels(page: import("@playwright/test").Page, workspaceId: string) {
|
||||
const serverId = getServerId();
|
||||
const row = page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`).first();
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await row.hover();
|
||||
await page.getByTestId(`sidebar-workspace-kebab-${serverId}:${workspaceId}`).first().click();
|
||||
const serverId = await openWorkspaceSidebarKebab(page, workspaceId);
|
||||
await page.getByTestId(`sidebar-workspace-menu-labels-${serverId}:${workspaceId}`).click();
|
||||
await expect(page.getByTestId("workspace-label-picker-create")).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ function send(message) {
|
||||
function respond(method, params) {
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
return {};
|
||||
return { userAgent: "codex/0.159.0" };
|
||||
case "model/list":
|
||||
return { data: models };
|
||||
case "config/read":
|
||||
|
||||
@@ -56,11 +56,20 @@ function inFlightTurn(page: Page) {
|
||||
return page.getByTestId("turn-working-indicator");
|
||||
}
|
||||
|
||||
/**
|
||||
* Presses a fork trigger until its menu shows.
|
||||
*
|
||||
* The in-flight turn's trigger sits below text that is still streaming in. While the chat is
|
||||
* shorter than the viewport, each new line moves the trigger down. A line that arrives between
|
||||
* the press and the release moves the trigger away from the pointer, so the press opens nothing,
|
||||
* and the next press lands on the trigger where it is now.
|
||||
*/
|
||||
async function openForkMenu(page: Page, trigger: ReturnType<Page["getByRole"]>): Promise<void> {
|
||||
await trigger.click();
|
||||
await expect(page.getByRole("menuitem", { name: "Fork in a new tab" })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
const forkInNewTab = page.getByRole("menuitem", { name: "Fork in a new tab" });
|
||||
await expect(async () => {
|
||||
await trigger.click({ timeout: 5_000 });
|
||||
await expect(forkInNewTab).toBeVisible({ timeout: 5_000 });
|
||||
}).toPass({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function openMostRecentAssistantForkMenu(page: Page): Promise<void> {
|
||||
|
||||
@@ -23,6 +23,11 @@ export async function openCommandCenter(page: Page): Promise<Locator> {
|
||||
return panel;
|
||||
}
|
||||
|
||||
export async function openCommandCenterWithShortcut(page: Page): Promise<void> {
|
||||
await page.keyboard.press("ControlOrMeta+k");
|
||||
await expect(page.getByTestId("command-center-panel")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function closeCommandCenter(page: Page): Promise<void> {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByTestId("command-center-panel")).not.toBeVisible();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { expect, type Page } from "../fixtures";
|
||||
import { getServerId } from "./server-id";
|
||||
import { expectAppRoute } from "./route-assertions";
|
||||
import { escapeRegex } from "./regex";
|
||||
|
||||
/**
|
||||
* Settings → Host → Plugins: the Installed and Browse tabs, the page menu, the install sheet and a
|
||||
@@ -28,8 +29,17 @@ function pluginSwitch(page: Page, name: string, action: "Disable" | "Enable") {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A toast that times out stays in the page while it fades, so the next toast can share the screen
|
||||
* with it, even when both have the same text. The pattern matches case, so "Installed x" does not
|
||||
* match "Uninstalled x".
|
||||
*/
|
||||
export async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toContainText(message);
|
||||
const toast = page
|
||||
.getByTestId("app-toast-message")
|
||||
.filter({ hasText: new RegExp(escapeRegex(message)) })
|
||||
.first();
|
||||
await expect(toast).toBeVisible();
|
||||
}
|
||||
|
||||
// Tabs and search
|
||||
|
||||
@@ -190,14 +190,25 @@ export async function selectWorkspaceInSidebar(page: Page, workspaceId: string):
|
||||
await row.click();
|
||||
}
|
||||
|
||||
async function openWorkspaceSidebarKebab(page: Page, workspaceId: string) {
|
||||
/**
|
||||
* Opens a workspace row's kebab menu the way a pointer does: enter the row, then press the kebab
|
||||
* it reveals.
|
||||
*
|
||||
* The kebab only mounts while the row holds hover, and hover only arrives on pointerenter. A row
|
||||
* that re-renders or shifts under a parked pointer drops that hover with no new pointerenter to
|
||||
* restore it, so each attempt leaves the row and enters it again instead of waiting on a kebab
|
||||
* that a still pointer cannot bring back.
|
||||
*/
|
||||
export async function openWorkspaceSidebarKebab(page: Page, workspaceId: string) {
|
||||
const serverId = getServerId();
|
||||
const row = page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await row.hover();
|
||||
|
||||
const kebab = page.getByTestId(`sidebar-workspace-kebab-${serverId}:${workspaceId}`);
|
||||
await expect(kebab).toBeVisible({ timeout: 10_000 });
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(async () => {
|
||||
await page.mouse.move(0, 0);
|
||||
await row.hover();
|
||||
await expect(kebab).toBeVisible({ timeout: 2_000 });
|
||||
}).toPass({ timeout: 15_000 });
|
||||
await kebab.click();
|
||||
|
||||
return serverId;
|
||||
|
||||
@@ -175,13 +175,19 @@ export interface SidebarListLayout {
|
||||
rowHeight: number;
|
||||
}
|
||||
|
||||
const SIDEBAR_LIST = "sidebar-project-workspace-list-scroll";
|
||||
|
||||
/** Scrolls the sidebar's workspace list to its end and reads where its rows sit. */
|
||||
export async function scrollSidebarListToEnd(page: Page): Promise<SidebarListLayout> {
|
||||
const list = page.getByTestId("sidebar-project-workspace-list-scroll");
|
||||
await list.evaluate((element) => {
|
||||
await page.getByTestId(SIDEBAR_LIST).evaluate((element) => {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
});
|
||||
return list.evaluate((element) => {
|
||||
return readSidebarListLayout(page);
|
||||
}
|
||||
|
||||
/** Reads where the sidebar list's rows sit, without scrolling it. */
|
||||
export async function readSidebarListLayout(page: Page): Promise<SidebarListLayout> {
|
||||
return page.getByTestId(SIDEBAR_LIST).evaluate((element) => {
|
||||
const visible = element.getBoundingClientRect();
|
||||
const rows = Array.from(
|
||||
element.querySelectorAll<HTMLElement>(
|
||||
@@ -197,3 +203,26 @@ export async function scrollSidebarListToEnd(page: Page): Promise<SidebarListLay
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recording the bottom edge of the sidebar list's last row once per painted frame.
|
||||
* Resolves with one value per frame after `frameCount` frames.
|
||||
*/
|
||||
export function recordLastRowBottomPerFrame(page: Page, frameCount: number): Promise<number[]> {
|
||||
return page.getByTestId(SIDEBAR_LIST).evaluate(
|
||||
(element, count) =>
|
||||
new Promise<number[]>((resolve) => {
|
||||
const bottoms: number[] = [];
|
||||
const sample = () => {
|
||||
const rows = element.querySelectorAll<HTMLElement>(
|
||||
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
|
||||
);
|
||||
bottoms.push(Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)));
|
||||
if (bottoms.length >= count) resolve(bottoms);
|
||||
else requestAnimationFrame(sample);
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
}),
|
||||
frameCount,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.pressfeedback'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useExpoPublishing()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.pressfeedback"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package sh.paseo.pressfeedback
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import expo.modules.kotlin.types.ColorCompat
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class PaseoPressFeedbackModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView::class) {
|
||||
Prop("tint") { view: PaseoPressFeedbackView, color: Color -> view.paint.color = ColorCompat.toArgb(color) }
|
||||
Prop("radius") { view: PaseoPressFeedbackView, radius: Double -> view.radius = radius.toFloat() * view.resources.displayMetrics.density }
|
||||
Prop("resetKey") { view: PaseoPressFeedbackView, key: String -> view.reset(key) }
|
||||
AsyncFunction("acknowledge") { view: PaseoPressFeedbackView -> view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PaseoPressFeedbackView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
var radius = 0f
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
init { setWillNotDraw(false); importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
|
||||
fun acknowledge() { acknowledged = true; invalidate() }
|
||||
fun reset(key: String) {
|
||||
if (key != resetKey) { resetKey = key; acknowledged = false; invalidate() }
|
||||
}
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
if (acknowledged) canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, paint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"platforms": ["android", "ios"],
|
||||
"android": { "modules": ["sh.paseo.pressfeedback.PaseoPressFeedbackModule"] },
|
||||
"ios": { "modules": ["PaseoPressFeedbackModule"] }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { useWorkspaceRowPress } from "./src/ui";
|
||||
@@ -0,0 +1,22 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'PaseoPressFeedback'
|
||||
s.version = '0.1.0'
|
||||
s.summary = 'Native accepted press feedback for Paseo'
|
||||
s.description = 'Paints accepted press feedback independently of React commits'
|
||||
s.license = 'Apache-2.0'
|
||||
s.author = 'Paseo'
|
||||
s.homepage = 'https://paseo.sh'
|
||||
s.platforms = { :ios => '15.1' }
|
||||
s.swift_version = '5.4'
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
'SWIFT_COMPILATION_MODE' => 'wholemodule'
|
||||
}
|
||||
|
||||
s.source_files = "**/*.{h,m,swift}"
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public class PaseoPressFeedbackModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView.self) {
|
||||
Prop("tint") { (view: PaseoPressFeedbackView, color: UIColor) in view.tint = color }
|
||||
Prop("radius") { (view: PaseoPressFeedbackView, radius: Double) in view.radius = radius }
|
||||
Prop("resetKey") { (view: PaseoPressFeedbackView, key: String) in view.reset(key) }
|
||||
AsyncFunction("acknowledge") { (view: PaseoPressFeedbackView) in view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class PaseoPressFeedbackView: ExpoView {
|
||||
var tint = UIColor.clear
|
||||
var radius: Double = 0
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
isOpaque = false
|
||||
isUserInteractionEnabled = false
|
||||
}
|
||||
func acknowledge() { acknowledged = true; setNeedsDisplay() }
|
||||
func reset(_ key: String) {
|
||||
if key != resetKey { resetKey = key; acknowledged = false; setNeedsDisplay() }
|
||||
}
|
||||
override func draw(_ rect: CGRect) {
|
||||
if acknowledged { tint.setFill(); UIBezierPath(roundedRect: bounds, cornerRadius: radius).fill() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "paseo-press-feedback",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { acceptWorkspaceRowPress, type WorkspaceRowPress } from "./accept";
|
||||
|
||||
function rowPress(overrides: Partial<WorkspaceRowPress> = {}) {
|
||||
const visible: string[] = [];
|
||||
const press: WorkspaceRowPress = {
|
||||
cancelled: false,
|
||||
native: true,
|
||||
selected: false,
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
acknowledge: () => visible.push("row"),
|
||||
navigate: () => visible.push("workspace"),
|
||||
...overrides,
|
||||
};
|
||||
return { press, visible };
|
||||
}
|
||||
|
||||
it("acknowledges an accepted row before navigation starts", () => {
|
||||
const { press, visible } = rowPress();
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
|
||||
it("does not acknowledge or navigate after scrolling or a long press claims the touch", () => {
|
||||
const { press, visible } = rowPress({ cancelled: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts only the first row while its selection closes the sidebar", () => {
|
||||
const { press, visible } = rowPress();
|
||||
press.navigate = () => {
|
||||
press.target = "agent";
|
||||
visible.push("workspace B");
|
||||
};
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual(["row", "workspace B"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "open phone or tablet overlay",
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "closing overlay", sidebar: "overlay", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "explorer covering an overlay",
|
||||
sidebar: "overlay",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{ name: "docked sidebar", sidebar: "dock", target: "agent", native: true, accepted: true },
|
||||
{
|
||||
name: "docked sidebar beside explorer",
|
||||
sidebar: "dock",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "hidden sidebar", sidebar: "hidden", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "suspended open overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{
|
||||
name: "suspended closed overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{
|
||||
name: "web sidebar independent of native panel target",
|
||||
sidebar: "overlay",
|
||||
target: "agent",
|
||||
native: false,
|
||||
accepted: true,
|
||||
},
|
||||
] as const)("uses the panel state for $name", ({ accepted, name: _, ...state }) => {
|
||||
const { press, visible } = rowPress(state);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(accepted);
|
||||
expect(visible).toEqual(accepted ? ["row", "workspace"] : []);
|
||||
});
|
||||
|
||||
it("does not leave an acknowledgement over an already selected docked row", () => {
|
||||
const { press, visible } = rowPress({ selected: true, sidebar: "dock", target: "agent" });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["workspace"]);
|
||||
});
|
||||
|
||||
it("still acknowledges a selected overlay row before the sidebar leaves", () => {
|
||||
const { press, visible } = rowPress({ selected: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { LeftSidebarPresentation, MobilePanelView } from "@/stores/panel-store";
|
||||
|
||||
export interface WorkspaceRowPress {
|
||||
cancelled: boolean;
|
||||
native: boolean;
|
||||
selected: boolean;
|
||||
sidebar: LeftSidebarPresentation;
|
||||
target: MobilePanelView;
|
||||
acknowledge(): void;
|
||||
navigate(): void;
|
||||
}
|
||||
|
||||
export function acceptWorkspaceRowPress(press: WorkspaceRowPress): boolean {
|
||||
if (press.cancelled) return false;
|
||||
if (press.native && press.sidebar !== "dock" && press.target !== "agent-list") return false;
|
||||
// A selected docked row neither changes selection nor leaves the screen to clear the fill.
|
||||
if (!press.selected || press.sidebar !== "dock") press.acknowledge();
|
||||
press.navigate();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { requireNativeView } from "expo";
|
||||
import { type Ref } from "react";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { View, StyleSheet, type ViewProps } from "react-native";
|
||||
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
interface FeedbackProps extends ViewProps {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
resetKey: string;
|
||||
tint?: string;
|
||||
radius?: number;
|
||||
}
|
||||
const NativeFeedback = withUnistyles(requireNativeView<FeedbackProps>("PaseoPressFeedback"));
|
||||
const mapTheme = (theme: import("@/styles/theme").Theme) => ({
|
||||
tint: theme.colors.interactionHighlight,
|
||||
radius: theme.borderRadius.lg,
|
||||
});
|
||||
export function RowFeedback({
|
||||
ref,
|
||||
selected,
|
||||
}: {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const revision = usePanelStore((state) => state.mobilePanel.revision);
|
||||
// Selection takes over the fill; a new panel transition clears it before reopening.
|
||||
const resetKey = `${selected}:${revision}`;
|
||||
return (
|
||||
<View pointerEvents="none" style={styles.overlay}>
|
||||
<NativeFeedback
|
||||
ref={ref}
|
||||
resetKey={resetKey}
|
||||
pointerEvents="none"
|
||||
style={styles.fill}
|
||||
uniProps={mapTheme}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 },
|
||||
fill: { flex: 1 },
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Ref } from "react";
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useCallback, useRef, type RefObject } from "react";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { acceptWorkspaceRowPress } from "../accept";
|
||||
import { RowFeedback, type RowFeedbackHandle } from "./feedback";
|
||||
|
||||
export function useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
}: {
|
||||
didLongPressRef?: RefObject<boolean>;
|
||||
onPress(): void;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const feedback = useRef<RowFeedbackHandle>(null);
|
||||
const handlePress = useCallback(() => {
|
||||
const cancelled = didLongPressRef?.current ?? false;
|
||||
if (didLongPressRef) didLongPressRef.current = false;
|
||||
const panel = usePanelStore.getState();
|
||||
acceptWorkspaceRowPress({
|
||||
cancelled,
|
||||
native: isNative,
|
||||
selected,
|
||||
sidebar: panel.layout.leftSidebar,
|
||||
target: panel.mobilePanel.target,
|
||||
// Paint on the native UI thread before navigation occupies JS; never wait for paint.
|
||||
acknowledge: () => {
|
||||
void feedback.current?.acknowledge();
|
||||
},
|
||||
navigate: onPress,
|
||||
});
|
||||
}, [didLongPressRef, onPress, selected]);
|
||||
return {
|
||||
onPress: handlePress,
|
||||
feedback: <RowFeedback ref={feedback} selected={selected} />,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -30,6 +30,25 @@ function answer(
|
||||
}
|
||||
|
||||
describe("draft options model", () => {
|
||||
it("retains an Ultracode option only after the current host advertises it", () => {
|
||||
const model = openDraftOptions({ provider: "claude" });
|
||||
const legacy = { provider: "claude", cwd: "/repo", thinkingOptionId: "ultracode" };
|
||||
model.applyResolved(answer("claude", "old-host", {}, []));
|
||||
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
|
||||
expect(draftControlsRequest(model.getState(), legacy)).toEqual(legacy);
|
||||
|
||||
model.applyResolved(
|
||||
answer("claude", "new-host", { ultracode: true }, [
|
||||
{ type: "toggle", key: "ultracode", label: "Ultracode" },
|
||||
]),
|
||||
);
|
||||
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
|
||||
expect(model.retainResolvedOption("ultracode", "new-host")).toEqual({ ultracode: true });
|
||||
expect(
|
||||
draftControlsRequest(model.getState(), { ...legacy, thinkingOptionId: "high" }),
|
||||
).toMatchObject({ thinkingOptionId: "high", providerOptions: { ultracode: true } });
|
||||
});
|
||||
|
||||
it("draws a legacy Fast profile as the Fast tier the daemon resolved", () => {
|
||||
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "fast" } });
|
||||
model.applyResolved(answer("codex", "k1", { service_tier: "priority" }));
|
||||
|
||||
@@ -47,6 +47,7 @@ export interface DraftOptionsModel {
|
||||
applyProfile: (profile: { provider: string; options: ProviderOptions }) => void;
|
||||
setRemembered: (remembered: ProviderOptions) => void;
|
||||
setOption: (key: string, value: unknown) => void;
|
||||
retainResolvedOption: (key: string, requestKey: string) => ProviderOptions | undefined;
|
||||
applyResolved: (resolved: ResolvedDraftOptions) => void;
|
||||
}
|
||||
|
||||
@@ -112,6 +113,17 @@ export function openDraftOptions(input: {
|
||||
: { ...current, edits: { ...current.edits, [key]: value } },
|
||||
);
|
||||
},
|
||||
retainResolvedOption: (key, requestKey) => {
|
||||
const resolved = state.resolved;
|
||||
if (resolved?.requestKey !== requestKey || key in state.edits) return undefined;
|
||||
const value = resolved.options[key];
|
||||
if (value === undefined || !resolved.controls.some((control) => control.key === key)) {
|
||||
return undefined;
|
||||
}
|
||||
const patch = { [key]: value };
|
||||
publish((current) => ({ ...current, edits: { ...current.edits, ...patch } }));
|
||||
return patch;
|
||||
},
|
||||
applyResolved: (resolved) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { createInitialDrawDistanceExpansion } from "./initial-draw-distance";
|
||||
|
||||
function mountInitialBuffer() {
|
||||
let nextId = 0;
|
||||
const pending = new Map<number, () => void>();
|
||||
const expansions: string[] = [];
|
||||
const buffer = createInitialDrawDistanceExpansion(
|
||||
{
|
||||
requestFrame(callback) {
|
||||
const id = ++nextId;
|
||||
pending.set(id, callback);
|
||||
return id;
|
||||
},
|
||||
cancelFrame(id) {
|
||||
pending.delete(id);
|
||||
},
|
||||
},
|
||||
() => expansions.push("full draw distance"),
|
||||
);
|
||||
function advanceFrame() {
|
||||
const callbacks = [...pending.values()];
|
||||
pending.clear();
|
||||
for (const callback of callbacks) callback();
|
||||
}
|
||||
return { buffer, expansions, advanceFrame };
|
||||
}
|
||||
|
||||
it("requests the full draw distance after two frame callbacks once the reveal is eligible", () => {
|
||||
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
|
||||
buffer.schedule();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual([]);
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual(["full draw distance"]);
|
||||
});
|
||||
|
||||
it.each([0, 1])(
|
||||
"leaves initial draw distance in place during a gesture after %i frames",
|
||||
(elapsed) => {
|
||||
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
|
||||
buffer.schedule();
|
||||
if (elapsed === 1) advanceFrame();
|
||||
|
||||
buffer.pauseForScroll();
|
||||
advanceFrame();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual([]);
|
||||
|
||||
buffer.resumeAfterScroll();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual([]);
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual(["full draw distance"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("cancels a covered reveal and schedules again when it is eligible", () => {
|
||||
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
|
||||
const cancel = buffer.schedule();
|
||||
advanceFrame();
|
||||
cancel();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual([]);
|
||||
|
||||
buffer.schedule();
|
||||
advanceFrame();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual(["full draw distance"]);
|
||||
});
|
||||
|
||||
it("keeps a covered list at its initial draw distance when a gesture ends", () => {
|
||||
const { buffer, expansions, advanceFrame } = mountInitialBuffer();
|
||||
buffer.pauseForScroll();
|
||||
const cover = buffer.schedule();
|
||||
advanceFrame();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual([]);
|
||||
|
||||
cover();
|
||||
buffer.resumeAfterScroll();
|
||||
advanceFrame();
|
||||
advanceFrame();
|
||||
expect(expansions).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
interface InitialDrawDistanceFrames {
|
||||
requestFrame(callback: () => void): number;
|
||||
cancelFrame(id: number): void;
|
||||
}
|
||||
|
||||
export function createInitialDrawDistanceExpansion(
|
||||
frames: InitialDrawDistanceFrames,
|
||||
expand: () => void,
|
||||
) {
|
||||
let frame: number | null = null;
|
||||
let eligible = false;
|
||||
let scrolling = false;
|
||||
let expanded = false;
|
||||
|
||||
function cancel() {
|
||||
if (frame === null) return;
|
||||
frames.cancelFrame(frame);
|
||||
frame = null;
|
||||
}
|
||||
|
||||
function scheduleIfIdle() {
|
||||
if (!eligible || scrolling || expanded || frame !== null) return;
|
||||
frame = frames.requestFrame(() => {
|
||||
frame = frames.requestFrame(() => {
|
||||
frame = null;
|
||||
expanded = true;
|
||||
expand();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
schedule() {
|
||||
eligible = true;
|
||||
scheduleIfIdle();
|
||||
return () => {
|
||||
eligible = false;
|
||||
cancel();
|
||||
};
|
||||
},
|
||||
pauseForScroll() {
|
||||
scrolling = true;
|
||||
cancel();
|
||||
},
|
||||
resumeAfterScroll() {
|
||||
scrolling = false;
|
||||
scheduleIfIdle();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -40,6 +40,7 @@ function wait(ms: number): Promise<void> {
|
||||
}
|
||||
|
||||
const LIST_STYLE = { flex: 1 };
|
||||
const ESTIMATED_LIST_SIZE = { width: 300, height: VIEWPORT_HEIGHT };
|
||||
const rowStyles = new Map<number, { height: number }>();
|
||||
|
||||
function rowStyle(height: number) {
|
||||
@@ -89,6 +90,10 @@ function keyExtractor(item: Row) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function estimateRowSize(item: Row) {
|
||||
return item.height;
|
||||
}
|
||||
|
||||
function mountList(heldRowId: string) {
|
||||
const listRef = React.createRef<LegendListRef>();
|
||||
const maintainVisibleContentPosition = holdOnly(heldRowId);
|
||||
@@ -264,3 +269,49 @@ it("keeps measured row sizes while the list is not laid out", async () => {
|
||||
|
||||
expect(rows.map((row) => list.rowSize(row.id))).toEqual([40, 40, 40]);
|
||||
});
|
||||
|
||||
it("expands the draw distance of a placed end-anchored list without moving its bottom row", async () => {
|
||||
const rows: Row[] = Array.from({ length: 99 }, (_, index) => ({
|
||||
id: `row-${index}`,
|
||||
height: index % 2 === 0 ? 20 : 60,
|
||||
}));
|
||||
const lastRow = { id: "last-row", height: 180 };
|
||||
rows.push(lastRow);
|
||||
const listRef = React.createRef<LegendListRef>();
|
||||
|
||||
function render(drawDistance: number) {
|
||||
act(() => {
|
||||
root.render(
|
||||
<LegendList
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
renderItem={renderRow}
|
||||
keyExtractor={keyExtractor}
|
||||
estimatedListSize={ESTIMATED_LIST_SIZE}
|
||||
recycleItems={false}
|
||||
getEstimatedItemSize={estimateRowSize}
|
||||
drawDistance={drawDistance}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
style={LIST_STYLE}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
render(50);
|
||||
await wait(300);
|
||||
const initial = listRef.current?.getState();
|
||||
const lastRowTop = initial?.positionByKey(lastRow.id);
|
||||
expect(initial?.sizes.get(lastRow.id)).toBe(lastRow.height);
|
||||
expect(initial?.sizes.size).toBeLessThan(8);
|
||||
expect(initial?.scroll).toBe(Number(lastRowTop) + lastRow.height - VIEWPORT_HEIGHT);
|
||||
|
||||
render(1000);
|
||||
await wait(150);
|
||||
|
||||
const expanded = listRef.current?.getState();
|
||||
expect(expanded?.sizes.size).toBeGreaterThan(20);
|
||||
expect(expanded?.scroll).toBe(initial?.scroll);
|
||||
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
Dimensions,
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
type NativeScrollEvent,
|
||||
@@ -31,6 +32,7 @@ import { useTranslation } from "react-i18next";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useIsMobilePanelActive } from "@/mobile-panels/provider";
|
||||
import { shouldAnimateNativeScrollToBottom } from "./native-scroll-animation";
|
||||
import { useRevisedHistoryRows } from "./history-row-revision";
|
||||
import { useBottomAnchorController } from "./bottom-anchor-controller";
|
||||
@@ -43,6 +45,7 @@ import {
|
||||
} from "./native-disclosure-hold";
|
||||
import { EndPinnedScrollView } from "./native-end-pin";
|
||||
import { createNewRowEstimates } from "./new-row-estimates";
|
||||
import { createInitialDrawDistanceExpansion } from "./initial-draw-distance";
|
||||
import type {
|
||||
DisclosureTriggerEdge,
|
||||
StreamRenderInput,
|
||||
@@ -132,6 +135,14 @@ function keyExtractor(item: { id: string }): string {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function InitialDrawDistanceExpansion({ schedule }: { schedule: () => () => void }) {
|
||||
const isSidebarActive = useIsMobilePanelActive("agent-list");
|
||||
useLayoutEffect(() => {
|
||||
if (!isSidebarActive) return schedule();
|
||||
}, [schedule, isSidebarActive]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrategy }) {
|
||||
const {
|
||||
agentId,
|
||||
@@ -157,6 +168,16 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
strategy,
|
||||
} = props;
|
||||
const isActive = useRetainedPanelActive();
|
||||
// Keep a screenful in reserve for a fling that starts before the full buffer mounts.
|
||||
const [drawDistance, setDrawDistance] = useState(() =>
|
||||
Math.min(Dimensions.get("window").height, NATIVE_STREAM_DRAW_DISTANCE),
|
||||
);
|
||||
const [drawDistanceExpansion] = useState(() =>
|
||||
createInitialDrawDistanceExpansion(
|
||||
{ requestFrame: requestAnimationFrame, cancelFrame: cancelAnimationFrame },
|
||||
() => setDrawDistance(NATIVE_STREAM_DRAW_DISTANCE),
|
||||
),
|
||||
);
|
||||
const { t } = useTranslation();
|
||||
const { renderHistoryMountedRow, renderLiveHeadRow, renderLiveAuxiliary } = renderers;
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
@@ -569,6 +590,9 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
cancelDisclosureHold();
|
||||
bottomAnchorController.beginUserScroll();
|
||||
historyStartPagination.rearm();
|
||||
// The reserve follows the gesture. Expanding the buffer here shifted the measured
|
||||
// content and returned the viewport to the end during an Android fling.
|
||||
drawDistanceExpansion.pauseForScroll();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -591,6 +615,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
bottomAnchorController.endUserScroll({
|
||||
isAtEnd: isReleasedAtEndRef.current || isAtEnd(),
|
||||
});
|
||||
drawDistanceExpansion.resumeAfterScroll();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -610,6 +635,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
bottomAnchorController.endUserScroll({
|
||||
isAtEnd: isReleasedAtEndRef.current || isScrollEventAtEnd(event),
|
||||
});
|
||||
drawDistanceExpansion.resumeAfterScroll();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -732,6 +758,11 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
);
|
||||
}, [historyStartPaginationState, hasOlderHistory, retryHistoryStart, t]);
|
||||
|
||||
const canExpandDrawDistance =
|
||||
drawDistance < NATIVE_STREAM_DRAW_DISTANCE &&
|
||||
isActive &&
|
||||
isListPlaced &&
|
||||
historyStartPaginationState.visible;
|
||||
return (
|
||||
<View style={viewportStyle}>
|
||||
<LegendList<StreamItem>
|
||||
@@ -764,11 +795,14 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
recycleItems={false}
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
drawDistance={NATIVE_STREAM_DRAW_DISTANCE}
|
||||
drawDistance={drawDistance}
|
||||
getEstimatedItemSize={getEstimatedItemSize}
|
||||
scrollEnabled={scrollEnabled}
|
||||
showsVerticalScrollIndicator
|
||||
/>
|
||||
{canExpandDrawDistance ? (
|
||||
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
|
||||
) : null}
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<View pointerEvents="none" testID="agent-initial-fill" style={initialFillStyle}>
|
||||
<ThemedLoadingSpinner size="large" uniProps={foregroundMutedColorMapping} />
|
||||
|
||||
@@ -851,6 +851,94 @@ it("copies a selection inside semantic inline code without Markdown escaping", (
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps intraword underscores in prose unescaped", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML = "<p>Set max_retries and snake_case before the call.</p>";
|
||||
const paragraph = fixtureElement(message, "p");
|
||||
expect(createAssistantSelectionClipboardContent(selectNodeContents(paragraph))?.plainText).toBe(
|
||||
"Set max_retries and snake_case before the call.",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies literal paired underscores raw in text/plain and escaped in text/html", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML = "<p>literal _word_ stays literal</p>";
|
||||
const paragraph = fixtureElement(message, "p");
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(paragraph));
|
||||
expect(content?.plainText).toBe("literal _word_ stays literal");
|
||||
expect(content?.html).toContain("literal _word_ stays literal");
|
||||
});
|
||||
|
||||
it("copies a path the renderer recognized as text, and an authored link as a link", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
'<p>See <a href="src/index.ts" data-paseo-markdown-recognized-link="true">src/index.ts</a> and <a href="https://example.test/doc">the doc</a>.</p>';
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe("See src/index.ts and [the doc](https://example.test/doc).");
|
||||
expect(content?.html).not.toContain('href="src/index.ts"');
|
||||
});
|
||||
|
||||
it("copies a recognized inline-code path without its link", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
'<p>Edited <a href="src/app.tsx" data-paseo-markdown-recognized-link="true"><code>src/app.tsx</code></a> today.</p>';
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe("Edited `src/app.tsx` today.");
|
||||
expect(content?.html).not.toContain('href="src/app.tsx"');
|
||||
});
|
||||
|
||||
it("copies a recognized web link as its text in text/plain and as a link in text/html", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
'<p>Fixed in <a href="https://github.com/o/r/issues/12" data-paseo-markdown-recognized-link="true">#12</a> today.</p>';
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe("Fixed in #12 today.");
|
||||
expect(content?.html).toContain('<a href="https://github.com/o/r/issues/12">#12</a>');
|
||||
});
|
||||
|
||||
it("copies a recognized Windows drive path as text in both clipboard flavors", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
'<p>Open <a href="C:%5Crepo%5Csrc%5Cx.ts" data-paseo-markdown-recognized-link="true">C:\\repo\\src\\x.ts</a> now.</p>';
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe("Open C:\\repo\\src\\x.ts now.");
|
||||
expect(content?.html).not.toContain("<a ");
|
||||
});
|
||||
|
||||
it("keeps literal angle brackets around a URL in text/html", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML = "<p>Open <http://localhost:3000> before the call.</p>";
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe("Open <http://localhost:3000> before the call.");
|
||||
expect(content?.html).toContain("<p>Open <http://localhost:3000> before the call.</p>");
|
||||
});
|
||||
|
||||
it("keeps a heading marker split across inline elements literal in text/html", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML = "<p>Use <strong>C#</strong> for the service layer.</p>";
|
||||
const paragraph = fixtureElement(message, "p");
|
||||
const range = document.createRange();
|
||||
range.setStart(textNode(fixtureElement(message, "strong")), 1);
|
||||
range.setEnd(paragraph.lastChild!, paragraph.lastChild!.textContent!.length);
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
const content = createAssistantSelectionClipboardContent(selection);
|
||||
expect(content?.plainText).toBe("# for the service layer.");
|
||||
expect(content?.html).toContain("<p># for the service layer.</p>");
|
||||
});
|
||||
|
||||
it("keeps table cell pipes escaped in text/plain table syntax and literal in text/html", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
"<table><thead><tr><th>Header | label</th></tr></thead><tbody><tr><td>Value | detail</td></tr></tbody></table>";
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toContain("Header \\| label");
|
||||
expect(content?.plainText).toContain("Value \\| detail");
|
||||
expect(content?.html).toContain("<th>Header | label</th>");
|
||||
expect(content?.html).toContain("<td>Value | detail</td>");
|
||||
});
|
||||
|
||||
it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
const message = mountFixture();
|
||||
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
|
||||
|
||||
@@ -2,7 +2,7 @@ import TurndownService from "turndown";
|
||||
import { gfm } from "turndown-plugin-gfm";
|
||||
import {
|
||||
createCodeClipboardContent,
|
||||
createMarkdownClipboardContent,
|
||||
createSelectionClipboardContent,
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
MARKDOWN_COPY_LIST_START_ATTRIBUTE,
|
||||
MARKDOWN_COPY_SRC_ATTRIBUTE,
|
||||
MARKDOWN_COPY_TAG_ATTRIBUTE,
|
||||
MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE,
|
||||
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
|
||||
TRAILING_CODE_LINE_BREAKS,
|
||||
} from "./markup";
|
||||
@@ -56,40 +57,68 @@ function copySemanticAttributes(original: Element, copy: Element): void {
|
||||
}
|
||||
}
|
||||
|
||||
const turndown = new TurndownService({
|
||||
bulletListMarker: "-",
|
||||
codeBlockStyle: "fenced",
|
||||
emDelimiter: "_",
|
||||
strongDelimiter: "**",
|
||||
});
|
||||
turndown.use(gfm);
|
||||
turndown.addRule("escapedGfmTableCell", {
|
||||
filter: ["th", "td"],
|
||||
replacement: (content, node) => {
|
||||
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
|
||||
const prefix = index === 0 ? "| " : " ";
|
||||
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
});
|
||||
turndown.addRule("compactListItem", {
|
||||
filter: "li",
|
||||
replacement: (content, node, options) => {
|
||||
const item = content
|
||||
.replace(/^\n+/, "")
|
||||
.replace(/\n+$/, "\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`;
|
||||
}
|
||||
return `${node.getAttribute("value")}. ${item}\n`;
|
||||
},
|
||||
});
|
||||
function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
const turndown = new TurndownService({
|
||||
bulletListMarker: "-",
|
||||
codeBlockStyle: "fenced",
|
||||
emDelimiter: "_",
|
||||
strongDelimiter: "**",
|
||||
});
|
||||
turndown.use(gfm);
|
||||
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
|
||||
turndown.addRule("escapedGfmTableCell", {
|
||||
filter: ["th", "td"],
|
||||
replacement: (content, node) => {
|
||||
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
|
||||
const prefix = index === 0 ? "| " : " ";
|
||||
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
|
||||
},
|
||||
});
|
||||
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
|
||||
// link when it points to a web page, such as a forge reference.
|
||||
turndown.addRule("recognizedLink", {
|
||||
filter: (node) =>
|
||||
node.nodeName === "A" &&
|
||||
node.hasAttribute(MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE) &&
|
||||
(flavor === "plain" || !isWebUrl(node.getAttribute("href") ?? "")),
|
||||
replacement: (content) => content,
|
||||
});
|
||||
if (flavor === "markdown") {
|
||||
// Turndown leaves `<` unescaped, so displayed text such as `<http://localhost>`
|
||||
// would render back into text/html as an autolink.
|
||||
const escapeMarkdown = turndown.escape.bind(turndown);
|
||||
turndown.escape = (text) => escapeMarkdown(text).replace(/</g, "\\<");
|
||||
} else {
|
||||
turndown.escape = (text) => text;
|
||||
}
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
});
|
||||
turndown.addRule("compactListItem", {
|
||||
filter: "li",
|
||||
replacement: (content, node, options) => {
|
||||
const item = content
|
||||
.replace(/^\n+/, "")
|
||||
.replace(/\n+$/, "\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`;
|
||||
}
|
||||
return `${node.getAttribute("value")}. ${item}\n`;
|
||||
},
|
||||
});
|
||||
return turndown;
|
||||
}
|
||||
|
||||
function isWebUrl(href: string): boolean {
|
||||
return /^https?:\/\//i.test(href);
|
||||
}
|
||||
|
||||
const markdownTurndown = createTurndown("markdown");
|
||||
const plainTurndown = createTurndown("plain");
|
||||
|
||||
export function createAssistantSelectionClipboardContent(
|
||||
selection: Selection | null,
|
||||
@@ -117,11 +146,15 @@ export function createAssistantSelectionClipboardContent(
|
||||
}
|
||||
restoreMarkdownElements(container);
|
||||
|
||||
const markdown = turndown.turndown(container.innerHTML).trim();
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
const content = createMarkdownClipboardContent(markdown);
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
@@ -651,13 +684,15 @@ function restoreMarkdownElements(container: HTMLElement): void {
|
||||
for (const element of presentational.toReversed()) {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
// Turndown escapes line-start Markdown per text node, so text split by an unwrapped
|
||||
// element, such as `#` and ` for`, has to be one node to keep `# for` literal.
|
||||
container.normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Each item carries its number before Turndown re-parses the HTML. Until then every
|
||||
* child of the list is one item, including a partly selected item demoted to a `p`.
|
||||
* The parser splits a `p` that holds a code block into several siblings, so counting
|
||||
* siblings afterwards numbers the next item too high.
|
||||
* Assign item numbers before passing the DOM to Turndown. A partly selected item
|
||||
* still takes its original list position when copied as a paragraph, so the following
|
||||
* items keep their numbers.
|
||||
*/
|
||||
function numberOrderedListItems(list: Element, start: number): void {
|
||||
Array.from(list.children).forEach((child, index) => {
|
||||
|
||||
@@ -2,6 +2,8 @@ export const MARKDOWN_COPY_TAG_ATTRIBUTE = "data-paseo-markdown-tag";
|
||||
export const MARKDOWN_COPY_IGNORE_ATTRIBUTE = "data-paseo-markdown-ignore";
|
||||
export const MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE = "data-paseo-markdown-list-marker";
|
||||
export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
|
||||
/** A link Paseo recognized in the reply text, as opposed to one the Markdown wrote. */
|
||||
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
|
||||
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
|
||||
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
|
||||
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
|
||||
|
||||
@@ -3,7 +3,6 @@ export interface AudioEngineCallbacks {
|
||||
onVolumeLevel(level: number): void;
|
||||
onInterruption?(): void;
|
||||
onCaptureAvailabilityChange?(available: boolean): void;
|
||||
onError?(error: Error): void;
|
||||
}
|
||||
|
||||
export interface AudioPlaybackSource {
|
||||
@@ -31,3 +30,21 @@ export interface AudioEngineOptions {
|
||||
traceLabel?: string;
|
||||
captureMode?: "conversation" | "dictation";
|
||||
}
|
||||
|
||||
export type AudioCaptureStartFailure =
|
||||
| "permissionDenied"
|
||||
| "insecureContext"
|
||||
| "unsupported"
|
||||
| "noMicrophone"
|
||||
| "startFailed";
|
||||
|
||||
export class AudioCaptureStartError extends Error {
|
||||
constructor(
|
||||
readonly reason: AudioCaptureStartFailure,
|
||||
message: string,
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(message, options);
|
||||
this.name = "AudioCaptureStartError";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,239 +1,60 @@
|
||||
import type {
|
||||
AudioEngine,
|
||||
AudioEngineCallbacks,
|
||||
AudioEngineOptions,
|
||||
AudioPlaybackSource,
|
||||
} from "./audio-engine-types";
|
||||
import type { AudioEngine, AudioEngineCallbacks, AudioEngineOptions } from "./audio-engine-types";
|
||||
|
||||
import { createAudioPlayer, setAudioModeAsync } from "expo-audio";
|
||||
import { File, Paths } from "expo-file-system";
|
||||
import { createPlaybackQueue } from "./playback";
|
||||
import { playFile } from "./file-playback";
|
||||
import { playPcm16 } from "./pcm";
|
||||
import { createNativeAudioEngine, type NativeAudioEngineDeps } from "./native-audio-engine";
|
||||
|
||||
// AVPlayer needs a file extension to recognize local encoded audio on iOS.
|
||||
const FILE_EXTENSIONS: Record<string, string> = {
|
||||
"audio/wav": "wav",
|
||||
"audio/x-wav": "wav",
|
||||
"audio/wave": "wav",
|
||||
"audio/mpeg": "mp3",
|
||||
"audio/mp3": "mp3",
|
||||
"audio/mp4": "m4a",
|
||||
"audio/aac": "aac",
|
||||
"audio/ogg": "ogg",
|
||||
"audio/flac": "flac",
|
||||
};
|
||||
|
||||
let nextFileId = 0;
|
||||
|
||||
async function playEncodedAudio(
|
||||
bytes: Uint8Array,
|
||||
mimeType: string,
|
||||
signal: AbortSignal,
|
||||
context: { isCaptureActive(): boolean },
|
||||
): Promise<number> {
|
||||
// Capture owns its audio session while active. File playback alone must not
|
||||
// initialize the microphone or the native two-way engine.
|
||||
if (!context.isCaptureActive()) {
|
||||
await setAudioModeAsync({
|
||||
playsInSilentMode: true,
|
||||
allowsRecording: false,
|
||||
interruptionMode: "duckOthers",
|
||||
interruptionModeAndroid: "duckOthers",
|
||||
});
|
||||
}
|
||||
if (signal.aborted) throw new Error("Playback stopped");
|
||||
const extension = FILE_EXTENSIONS[mimeType.split(";")[0].trim()] ?? "audio";
|
||||
const file = new File(Paths.cache, `paseo-audio-${Date.now()}-${nextFileId++}.${extension}`);
|
||||
try {
|
||||
file.write(bytes);
|
||||
const player = createAudioPlayer(file.uri, {
|
||||
updateInterval: 100,
|
||||
keepAudioSessionActive: context.isCaptureActive(),
|
||||
});
|
||||
return await playFile(player, signal);
|
||||
} finally {
|
||||
if (file.exists) file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
export function createAudioEngine(
|
||||
callbacks: AudioEngineCallbacks,
|
||||
options?: AudioEngineOptions,
|
||||
): AudioEngine {
|
||||
const native = require("@getpaseo/expo-two-way-audio");
|
||||
|
||||
const refs: {
|
||||
initialized: boolean;
|
||||
captureActive: boolean;
|
||||
muted: boolean;
|
||||
destroyed: boolean;
|
||||
} = {
|
||||
initialized: false,
|
||||
captureActive: false,
|
||||
muted: false,
|
||||
destroyed: false,
|
||||
};
|
||||
|
||||
const microphoneSubscription = native.addExpoTwoWayAudioEventListener(
|
||||
"onMicrophoneData",
|
||||
(event: { data: Uint8Array }) => {
|
||||
if (!refs.captureActive || refs.muted) {
|
||||
return;
|
||||
}
|
||||
const pcm = event.data;
|
||||
callbacks.onCaptureData(pcm);
|
||||
},
|
||||
);
|
||||
const volumeSubscription = native.addExpoTwoWayAudioEventListener(
|
||||
"onInputVolumeLevelData",
|
||||
(event: { data: number }) => {
|
||||
if (!refs.captureActive) {
|
||||
return;
|
||||
}
|
||||
const level = refs.muted ? 0 : event.data;
|
||||
callbacks.onVolumeLevel(level);
|
||||
},
|
||||
);
|
||||
const interruptionSubscription = native.addExpoTwoWayAudioEventListener(
|
||||
"onAudioInterruption",
|
||||
(event: { data: string }) => {
|
||||
if (event.data === "capture_paused" || event.data === "capture_resumed") {
|
||||
if (refs.captureActive) {
|
||||
callbacks.onCaptureAvailabilityChange?.(event.data === "capture_resumed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.data !== "blocked") {
|
||||
return;
|
||||
}
|
||||
const wasCaptureActive = refs.captureActive;
|
||||
refs.captureActive = false;
|
||||
refs.muted = false;
|
||||
callbacks.onVolumeLevel(0);
|
||||
if (wasCaptureActive) {
|
||||
callbacks.onInterruption?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
async function ensureInitialized(): Promise<void> {
|
||||
if (refs.initialized) {
|
||||
return;
|
||||
}
|
||||
const success = await native.initialize();
|
||||
if (!success) {
|
||||
throw new Error("expo-two-way-audio: native initialize() returned false");
|
||||
}
|
||||
refs.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the OS audio session as soon as we are neither capturing nor playing.
|
||||
* Holding it keeps the user's background music paused — on iOS the non-mixing
|
||||
* `.playAndRecord` category survives backgrounding and is re-asserted on every
|
||||
* foreground, so an unreleased session means their music never comes back.
|
||||
*/
|
||||
function releaseSessionIfIdle(): void {
|
||||
if (!refs.initialized || refs.destroyed) {
|
||||
return;
|
||||
}
|
||||
if (refs.captureActive || playback.isPlaying()) {
|
||||
return;
|
||||
}
|
||||
// The wrapper no-ops on binaries whose native module predates this function.
|
||||
native.releaseAudioSession();
|
||||
}
|
||||
|
||||
async function ensureMicrophonePermission(): Promise<void> {
|
||||
let permission = await native.getMicrophonePermissionsAsync().catch(() => null);
|
||||
if (!permission?.granted) {
|
||||
permission = await native.requestMicrophonePermissionsAsync().catch(() => null);
|
||||
}
|
||||
if (!permission?.granted) {
|
||||
throw new Error(
|
||||
"Microphone permission is required to capture audio. Please enable microphone access in system settings.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let nextFileId = 0;
|
||||
async function playAudio(audio: AudioPlaybackSource, signal: AbortSignal): Promise<number> {
|
||||
const bytes = new Uint8Array(await audio.arrayBuffer());
|
||||
if (signal.aborted) throw new Error("Playback stopped");
|
||||
if (audio.type.startsWith("audio/pcm")) {
|
||||
await ensureInitialized();
|
||||
return playPcm16(bytes, audio.type, signal, native);
|
||||
}
|
||||
// Capture owns its audio session while active. File playback alone must not
|
||||
// initialize the microphone or the native two-way engine.
|
||||
if (!refs.captureActive) {
|
||||
await setAudioModeAsync({
|
||||
playsInSilentMode: true,
|
||||
allowsRecording: false,
|
||||
interruptionMode: "duckOthers",
|
||||
interruptionModeAndroid: "duckOthers",
|
||||
});
|
||||
}
|
||||
if (signal.aborted) throw new Error("Playback stopped");
|
||||
// AVPlayer needs a file extension to recognize local encoded audio on iOS.
|
||||
const extension =
|
||||
{
|
||||
"audio/wav": "wav",
|
||||
"audio/x-wav": "wav",
|
||||
"audio/wave": "wav",
|
||||
"audio/mpeg": "mp3",
|
||||
"audio/mp3": "mp3",
|
||||
"audio/mp4": "m4a",
|
||||
"audio/aac": "aac",
|
||||
"audio/ogg": "ogg",
|
||||
"audio/flac": "flac",
|
||||
}[audio.type.split(";")[0].trim()] ?? "audio";
|
||||
const file = new File(Paths.cache, `paseo-audio-${Date.now()}-${nextFileId++}.${extension}`);
|
||||
try {
|
||||
file.write(bytes);
|
||||
const player = createAudioPlayer(file.uri, {
|
||||
updateInterval: 100,
|
||||
keepAudioSessionActive: refs.captureActive,
|
||||
});
|
||||
return await playFile(player, signal);
|
||||
} finally {
|
||||
if (file.exists) file.delete();
|
||||
}
|
||||
}
|
||||
const playback = createPlaybackQueue(playAudio, releaseSessionIfIdle);
|
||||
|
||||
return {
|
||||
async initialize() {
|
||||
await ensureInitialized();
|
||||
},
|
||||
|
||||
async destroy() {
|
||||
if (refs.destroyed) {
|
||||
return;
|
||||
}
|
||||
refs.destroyed = true;
|
||||
playback.destroy();
|
||||
if (refs.captureActive) {
|
||||
native.toggleRecording(false);
|
||||
refs.captureActive = false;
|
||||
}
|
||||
refs.muted = false;
|
||||
callbacks.onVolumeLevel(0);
|
||||
if (refs.initialized) {
|
||||
native.tearDown();
|
||||
refs.initialized = false;
|
||||
}
|
||||
microphoneSubscription.remove();
|
||||
volumeSubscription.remove();
|
||||
interruptionSubscription.remove();
|
||||
},
|
||||
|
||||
async startCapture() {
|
||||
if (refs.captureActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureMicrophonePermission();
|
||||
await ensureInitialized();
|
||||
const isRecording =
|
||||
options?.captureMode === "dictation"
|
||||
? native.startDictation()
|
||||
: native.toggleRecording(true);
|
||||
if (!isRecording) {
|
||||
throw new Error(
|
||||
"Microphone capture could not start because Android audio focus is unavailable.",
|
||||
);
|
||||
}
|
||||
refs.captureActive = true;
|
||||
} catch (error) {
|
||||
const wrapped = error instanceof Error ? error : new Error(String(error));
|
||||
callbacks.onError?.(wrapped);
|
||||
throw wrapped;
|
||||
}
|
||||
},
|
||||
|
||||
async stopCapture() {
|
||||
if (refs.captureActive) {
|
||||
native.toggleRecording(false);
|
||||
}
|
||||
refs.captureActive = false;
|
||||
refs.muted = false;
|
||||
callbacks.onVolumeLevel(0);
|
||||
callbacks.onCaptureAvailabilityChange?.(true);
|
||||
releaseSessionIfIdle();
|
||||
},
|
||||
|
||||
toggleMute() {
|
||||
refs.muted = !refs.muted;
|
||||
if (refs.muted) {
|
||||
callbacks.onVolumeLevel(0);
|
||||
}
|
||||
return refs.muted;
|
||||
},
|
||||
|
||||
isMuted() {
|
||||
return refs.muted;
|
||||
},
|
||||
|
||||
play: playback.play,
|
||||
stop: playback.stop,
|
||||
clearQueue: playback.clearQueue,
|
||||
isPlaying: playback.isPlaying,
|
||||
};
|
||||
const native: NativeAudioEngineDeps["native"] = require("@getpaseo/expo-two-way-audio");
|
||||
return createNativeAudioEngine({ native, playEncodedAudio }, callbacks, options);
|
||||
}
|
||||
|
||||
@@ -292,9 +292,7 @@ export function createAudioEngine(
|
||||
refs.gain = gain;
|
||||
} catch (error) {
|
||||
await stopCapture();
|
||||
const wrapped = error instanceof Error ? error : new Error(String(error));
|
||||
callbacks.onError?.(wrapped);
|
||||
throw wrapped;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export { createAudioEngine } from "./audio-engine";
|
||||
export type { AudioEngine, AudioEngineCallbacks, AudioPlaybackSource } from "./audio-engine-types";
|
||||
export { createPlayAudio } from "./play-audio";
|
||||
export { AudioCaptureStartError, type AudioCaptureStartFailure } from "./audio-engine-types";
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { expect, test } from "vitest";
|
||||
import type { AudioEngineCallbacks } from "./audio-engine-types";
|
||||
import { createNativeAudioEngine, type NativeAudioEngineDeps } from "./native-audio-engine";
|
||||
|
||||
// In-memory stand-in for `@getpaseo/expo-two-way-audio`, matching its iOS and Android modules:
|
||||
// one native engine per app, `initialize()` reuses it, `tearDown()` frees it, and
|
||||
// `toggleRecording(true)` / `startDictation()` return false while no engine exists.
|
||||
// Session handling follows iOS: recording activates the OS audio session, stopping does not
|
||||
// deactivate it, and `releaseAudioSession()` deactivates it only while nothing is recording.
|
||||
function fakeTwoWayAudio({
|
||||
captureAvailable = true,
|
||||
permissionRequestError,
|
||||
}: { captureAvailable?: boolean; permissionRequestError?: Error } = {}) {
|
||||
let engine: { recording: boolean; sessionActive: boolean } | null = null;
|
||||
const calls = { initialize: 0, tearDown: 0 };
|
||||
const native: NativeAudioEngineDeps["native"] = {
|
||||
async initialize() {
|
||||
calls.initialize += 1;
|
||||
engine ??= { recording: false, sessionActive: false };
|
||||
return true;
|
||||
},
|
||||
tearDown() {
|
||||
calls.tearDown += 1;
|
||||
engine = null;
|
||||
},
|
||||
toggleRecording(value: boolean) {
|
||||
if (!engine) return false;
|
||||
engine.recording = value;
|
||||
if (value) engine.sessionActive = true;
|
||||
return value;
|
||||
},
|
||||
startDictation() {
|
||||
if (!engine || !captureAvailable) return false;
|
||||
engine.recording = true;
|
||||
engine.sessionActive = true;
|
||||
return true;
|
||||
},
|
||||
releaseAudioSession() {
|
||||
if (engine && !engine.recording) engine.sessionActive = false;
|
||||
},
|
||||
playPCMData() {},
|
||||
resumePlayback() {},
|
||||
stopPlayback() {},
|
||||
async getMicrophonePermissionsAsync() {
|
||||
return { granted: !permissionRequestError };
|
||||
},
|
||||
async requestMicrophonePermissionsAsync() {
|
||||
if (permissionRequestError) throw permissionRequestError;
|
||||
return { granted: true };
|
||||
},
|
||||
addExpoTwoWayAudioEventListener() {
|
||||
return { remove() {} };
|
||||
},
|
||||
};
|
||||
return {
|
||||
native,
|
||||
calls,
|
||||
hasEngine: () => engine !== null,
|
||||
sessionActive: () => engine?.sessionActive ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
const recordingCallbacks: AudioEngineCallbacks = {
|
||||
onCaptureData() {},
|
||||
onVolumeLevel() {},
|
||||
};
|
||||
|
||||
function deps(native: NativeAudioEngineDeps["native"]): NativeAudioEngineDeps {
|
||||
return {
|
||||
native,
|
||||
playEncodedAudio: async () => 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Issue #4147: on iPhone, voice mode failed with "Android audio focus is unavailable"
|
||||
// after the dictation engine was destroyed.
|
||||
test("voice capture starts after the dictation engine is destroyed", async () => {
|
||||
const fake = fakeTwoWayAudio();
|
||||
const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks);
|
||||
await voiceEngine.initialize();
|
||||
|
||||
const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
await dictationEngine.startCapture();
|
||||
await dictationEngine.stopCapture();
|
||||
await dictationEngine.destroy();
|
||||
|
||||
await expect(voiceEngine.startCapture()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test("destroying dictation while voice is capturing keeps the native engine", async () => {
|
||||
const fake = fakeTwoWayAudio();
|
||||
const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks);
|
||||
await voiceEngine.startCapture();
|
||||
|
||||
const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
await dictationEngine.initialize();
|
||||
await dictationEngine.destroy();
|
||||
|
||||
expect(fake.hasEngine()).toBe(true);
|
||||
expect(fake.calls.tearDown).toBe(0);
|
||||
});
|
||||
|
||||
// Review on #9051: with voice holding the engine, destroying an active dictation engine must
|
||||
// still hand back the idle OS audio session so background music resumes (#2866).
|
||||
test("destroying active dictation releases the idle audio session while voice keeps the engine", async () => {
|
||||
const fake = fakeTwoWayAudio();
|
||||
const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks);
|
||||
await voiceEngine.initialize();
|
||||
|
||||
const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
await dictationEngine.startCapture();
|
||||
await dictationEngine.destroy();
|
||||
|
||||
expect(fake.hasEngine()).toBe(true);
|
||||
expect(fake.sessionActive()).toBe(false);
|
||||
});
|
||||
|
||||
test("destroying dictation does not release the session while voice is recording", async () => {
|
||||
const fake = fakeTwoWayAudio();
|
||||
const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks);
|
||||
await voiceEngine.startCapture();
|
||||
|
||||
const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
await dictationEngine.initialize();
|
||||
await dictationEngine.destroy();
|
||||
|
||||
expect(fake.sessionActive()).toBe(true);
|
||||
});
|
||||
|
||||
test("destroying the last engine tears the native engine down", async () => {
|
||||
const fake = fakeTwoWayAudio();
|
||||
const voiceEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks);
|
||||
const dictationEngine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
await voiceEngine.initialize();
|
||||
await dictationEngine.initialize();
|
||||
|
||||
await dictationEngine.destroy();
|
||||
await voiceEngine.destroy();
|
||||
|
||||
expect(fake.calls.tearDown).toBe(1);
|
||||
expect(fake.hasEngine()).toBe(false);
|
||||
});
|
||||
|
||||
test("an engine destroyed while initializing does not keep the native engine", async () => {
|
||||
const fake = fakeTwoWayAudio();
|
||||
const engine = createNativeAudioEngine(deps(fake.native), recordingCallbacks);
|
||||
|
||||
const initializing = expect(engine.initialize()).rejects.toThrow("Audio engine destroyed");
|
||||
await engine.destroy();
|
||||
await initializing;
|
||||
|
||||
expect(fake.hasEngine()).toBe(false);
|
||||
});
|
||||
|
||||
test("a failed native recording start rejects with a platform-neutral error", async () => {
|
||||
const fake = fakeTwoWayAudio({ captureAvailable: false });
|
||||
const engine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
|
||||
await expect(engine.startCapture()).rejects.toThrow(/^Microphone capture could not start\.$/);
|
||||
await engine.destroy();
|
||||
});
|
||||
|
||||
test("a failed native permission request retains the permission reason and original error", async () => {
|
||||
const permissionRequestError = new Error("The current activity is not available.");
|
||||
const fake = fakeTwoWayAudio({ permissionRequestError });
|
||||
const engine = createNativeAudioEngine(deps(fake.native), recordingCallbacks, {
|
||||
captureMode: "dictation",
|
||||
});
|
||||
|
||||
await expect(engine.startCapture()).rejects.toMatchObject({
|
||||
reason: "permissionDenied",
|
||||
cause: permissionRequestError,
|
||||
});
|
||||
expect(fake.hasEngine()).toBe(false);
|
||||
await engine.destroy();
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import type {
|
||||
AudioEngine,
|
||||
AudioEngineCallbacks,
|
||||
AudioEngineOptions,
|
||||
AudioPlaybackSource,
|
||||
} from "./audio-engine-types";
|
||||
|
||||
import { AudioCaptureStartError } from "./audio-engine-types";
|
||||
import { createNativeEngineLease, type NativeEngineLease } from "./native-engine-lease";
|
||||
import { createPlaybackQueue } from "./playback";
|
||||
import { playPcm16 } from "./pcm";
|
||||
|
||||
interface NativeSubscription {
|
||||
remove(): void;
|
||||
}
|
||||
|
||||
interface MicrophonePermission {
|
||||
granted: boolean;
|
||||
}
|
||||
|
||||
/** The surface of `@getpaseo/expo-two-way-audio` the engine drives. */
|
||||
export interface TwoWayAudioModule {
|
||||
initialize(): Promise<boolean>;
|
||||
tearDown(): void;
|
||||
toggleRecording(value: boolean): boolean;
|
||||
startDictation(): boolean;
|
||||
releaseAudioSession(): void;
|
||||
playPCMData(data: Uint8Array): void;
|
||||
getMicrophonePermissionsAsync(): Promise<MicrophonePermission>;
|
||||
requestMicrophonePermissionsAsync(): Promise<MicrophonePermission>;
|
||||
addExpoTwoWayAudioEventListener(
|
||||
event: "onMicrophoneData",
|
||||
listener: (event: { data: Uint8Array }) => void,
|
||||
): NativeSubscription;
|
||||
addExpoTwoWayAudioEventListener(
|
||||
event: "onInputVolumeLevelData",
|
||||
listener: (event: { data: number }) => void,
|
||||
): NativeSubscription;
|
||||
addExpoTwoWayAudioEventListener(
|
||||
event: "onAudioInterruption",
|
||||
listener: (event: { data: string }) => void,
|
||||
): NativeSubscription;
|
||||
}
|
||||
|
||||
export interface NativeAudioEngineDeps {
|
||||
native: TwoWayAudioModule & Parameters<typeof playPcm16>[3];
|
||||
/** Plays encoded audio (wav, mp3, ...) through the platform player. */
|
||||
playEncodedAudio(
|
||||
bytes: Uint8Array,
|
||||
mimeType: string,
|
||||
signal: AbortSignal,
|
||||
context: { isCaptureActive(): boolean },
|
||||
): Promise<number>;
|
||||
}
|
||||
|
||||
// Voice mode and dictation each create an engine, but the native module holds a single engine
|
||||
// per app. Every JS engine on the same module shares one lease, so one engine's teardown
|
||||
// cannot free the native engine another still uses (#4147).
|
||||
const leases = new WeakMap<TwoWayAudioModule, NativeEngineLease>();
|
||||
|
||||
function leaseFor(native: TwoWayAudioModule): NativeEngineLease {
|
||||
let lease = leases.get(native);
|
||||
if (!lease) {
|
||||
lease = createNativeEngineLease(native);
|
||||
leases.set(native, lease);
|
||||
}
|
||||
return lease;
|
||||
}
|
||||
|
||||
export function createNativeAudioEngine(
|
||||
deps: NativeAudioEngineDeps,
|
||||
callbacks: AudioEngineCallbacks,
|
||||
options?: AudioEngineOptions,
|
||||
): AudioEngine {
|
||||
const { native } = deps;
|
||||
const lease = leaseFor(native);
|
||||
|
||||
const refs: {
|
||||
initialized: boolean;
|
||||
captureActive: boolean;
|
||||
muted: boolean;
|
||||
destroyed: boolean;
|
||||
} = {
|
||||
initialized: false,
|
||||
captureActive: false,
|
||||
muted: false,
|
||||
destroyed: false,
|
||||
};
|
||||
|
||||
const microphoneSubscription = native.addExpoTwoWayAudioEventListener(
|
||||
"onMicrophoneData",
|
||||
(event: { data: Uint8Array }) => {
|
||||
if (!refs.captureActive || refs.muted) {
|
||||
return;
|
||||
}
|
||||
const pcm = event.data;
|
||||
callbacks.onCaptureData(pcm);
|
||||
},
|
||||
);
|
||||
const volumeSubscription = native.addExpoTwoWayAudioEventListener(
|
||||
"onInputVolumeLevelData",
|
||||
(event: { data: number }) => {
|
||||
if (!refs.captureActive) {
|
||||
return;
|
||||
}
|
||||
const level = refs.muted ? 0 : event.data;
|
||||
callbacks.onVolumeLevel(level);
|
||||
},
|
||||
);
|
||||
const interruptionSubscription = native.addExpoTwoWayAudioEventListener(
|
||||
"onAudioInterruption",
|
||||
(event: { data: string }) => {
|
||||
if (event.data === "capture_paused" || event.data === "capture_resumed") {
|
||||
if (refs.captureActive) {
|
||||
callbacks.onCaptureAvailabilityChange?.(event.data === "capture_resumed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.data !== "blocked") {
|
||||
return;
|
||||
}
|
||||
const wasCaptureActive = refs.captureActive;
|
||||
refs.captureActive = false;
|
||||
refs.muted = false;
|
||||
callbacks.onVolumeLevel(0);
|
||||
if (wasCaptureActive) {
|
||||
callbacks.onInterruption?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let initializing: Promise<void> | null = null;
|
||||
async function ensureInitialized(): Promise<void> {
|
||||
if (refs.destroyed) {
|
||||
throw new Error("Audio engine destroyed");
|
||||
}
|
||||
if (refs.initialized) {
|
||||
return;
|
||||
}
|
||||
initializing ??= (async () => {
|
||||
try {
|
||||
await lease.acquire();
|
||||
if (refs.destroyed) {
|
||||
releaseNativeEngine();
|
||||
throw new Error("Audio engine destroyed");
|
||||
}
|
||||
refs.initialized = true;
|
||||
} finally {
|
||||
initializing = null;
|
||||
}
|
||||
})();
|
||||
await initializing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the OS audio session as soon as we are neither capturing nor playing.
|
||||
* Holding it keeps the user's background music paused — on iOS the non-mixing
|
||||
* `.playAndRecord` category survives backgrounding and is re-asserted on every
|
||||
* foreground, so an unreleased session means their music never comes back.
|
||||
*/
|
||||
function releaseSessionIfIdle(): void {
|
||||
if (!refs.initialized || refs.destroyed) {
|
||||
return;
|
||||
}
|
||||
if (refs.captureActive || playback.isPlaying()) {
|
||||
return;
|
||||
}
|
||||
// The wrapper no-ops on binaries whose native module predates this function.
|
||||
native.releaseAudioSession();
|
||||
}
|
||||
|
||||
async function ensureMicrophonePermission(): Promise<void> {
|
||||
const permission = await native.getMicrophonePermissionsAsync().catch(() => null);
|
||||
if (permission?.granted) return;
|
||||
|
||||
let cause: unknown;
|
||||
try {
|
||||
if ((await native.requestMicrophonePermissionsAsync()).granted) return;
|
||||
} catch (error) {
|
||||
cause = error;
|
||||
}
|
||||
throw new AudioCaptureStartError(
|
||||
"permissionDenied",
|
||||
"Allow microphone access in system settings and try again.",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
|
||||
function releaseNativeEngine(): void {
|
||||
try {
|
||||
// Native keeps the session active while any wrapper is capturing or playing.
|
||||
native.releaseAudioSession();
|
||||
} finally {
|
||||
lease.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function playAudio(audio: AudioPlaybackSource, signal: AbortSignal): Promise<number> {
|
||||
const bytes = new Uint8Array(await audio.arrayBuffer());
|
||||
if (signal.aborted) throw new Error("Playback stopped");
|
||||
if (audio.type.startsWith("audio/pcm")) {
|
||||
await ensureInitialized();
|
||||
if (signal.aborted) throw new Error("Playback stopped");
|
||||
return playPcm16(bytes, audio.type, signal, native);
|
||||
}
|
||||
return deps.playEncodedAudio(bytes, audio.type, signal, {
|
||||
isCaptureActive: () => refs.captureActive,
|
||||
});
|
||||
}
|
||||
const playback = createPlaybackQueue(playAudio, releaseSessionIfIdle);
|
||||
|
||||
return {
|
||||
async initialize() {
|
||||
await ensureInitialized();
|
||||
},
|
||||
|
||||
async destroy() {
|
||||
if (refs.destroyed) {
|
||||
return;
|
||||
}
|
||||
refs.destroyed = true;
|
||||
try {
|
||||
playback.destroy();
|
||||
if (refs.captureActive) {
|
||||
refs.captureActive = false;
|
||||
native.toggleRecording(false);
|
||||
}
|
||||
refs.muted = false;
|
||||
callbacks.onVolumeLevel(0);
|
||||
} finally {
|
||||
microphoneSubscription.remove();
|
||||
volumeSubscription.remove();
|
||||
interruptionSubscription.remove();
|
||||
if (refs.initialized) {
|
||||
refs.initialized = false;
|
||||
releaseNativeEngine();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async startCapture() {
|
||||
if (refs.captureActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
await ensureMicrophonePermission();
|
||||
await ensureInitialized();
|
||||
if (refs.destroyed) {
|
||||
throw new Error("Audio engine destroyed");
|
||||
}
|
||||
if (refs.captureActive) {
|
||||
return;
|
||||
}
|
||||
const isRecording =
|
||||
options?.captureMode === "dictation"
|
||||
? native.startDictation()
|
||||
: native.toggleRecording(true);
|
||||
if (!isRecording) {
|
||||
throw new Error("Microphone capture could not start.");
|
||||
}
|
||||
refs.captureActive = true;
|
||||
},
|
||||
|
||||
async stopCapture() {
|
||||
if (refs.captureActive) {
|
||||
native.toggleRecording(false);
|
||||
}
|
||||
refs.captureActive = false;
|
||||
refs.muted = false;
|
||||
callbacks.onVolumeLevel(0);
|
||||
callbacks.onCaptureAvailabilityChange?.(true);
|
||||
releaseSessionIfIdle();
|
||||
},
|
||||
|
||||
toggleMute() {
|
||||
refs.muted = !refs.muted;
|
||||
if (refs.muted) {
|
||||
callbacks.onVolumeLevel(0);
|
||||
}
|
||||
return refs.muted;
|
||||
},
|
||||
|
||||
isMuted() {
|
||||
return refs.muted;
|
||||
},
|
||||
|
||||
play: playback.play,
|
||||
stop: playback.stop,
|
||||
clearQueue: playback.clearQueue,
|
||||
isPlaying: playback.isPlaying,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { createNativeEngineLease, type NativeAudioEngineLifecycle } from "./native-engine-lease";
|
||||
|
||||
// Mirrors the iOS and Android modules: one engine per app, `initialize()` reuses it,
|
||||
// `tearDown()` frees it, and `toggleRecording(true)` returns false once it is gone.
|
||||
function fakeNativeModule(options: { initializeResult?: boolean } = {}) {
|
||||
let engine: object | null = null;
|
||||
const calls = { initialize: 0, tearDown: 0 };
|
||||
let finishInitialize: (() => void) | null = null;
|
||||
let deferInitialize = false;
|
||||
const native: NativeAudioEngineLifecycle & {
|
||||
toggleRecording(value: boolean): boolean;
|
||||
} = {
|
||||
initialize() {
|
||||
calls.initialize += 1;
|
||||
const complete = () => {
|
||||
if (options.initializeResult === false) {
|
||||
return false;
|
||||
}
|
||||
engine ??= {};
|
||||
return true;
|
||||
};
|
||||
if (!deferInitialize) {
|
||||
return Promise.resolve(complete());
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
finishInitialize = () => resolve(complete());
|
||||
});
|
||||
},
|
||||
tearDown() {
|
||||
calls.tearDown += 1;
|
||||
engine = null;
|
||||
},
|
||||
toggleRecording(value: boolean) {
|
||||
return engine !== null && value;
|
||||
},
|
||||
};
|
||||
return {
|
||||
native,
|
||||
calls,
|
||||
deferNextInitialize() {
|
||||
deferInitialize = true;
|
||||
},
|
||||
finishInitialize() {
|
||||
finishInitialize?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("dictation releasing the engine keeps it for voice mode", async () => {
|
||||
const fake = fakeNativeModule();
|
||||
const lease = createNativeEngineLease(fake.native);
|
||||
|
||||
await lease.acquire(); // voice mode
|
||||
await lease.acquire(); // dictation
|
||||
lease.release(); // dictation unmounts
|
||||
|
||||
expect(fake.calls.tearDown).toBe(0);
|
||||
expect(fake.native.toggleRecording(true)).toBe(true);
|
||||
});
|
||||
|
||||
test("the last release tears the native engine down and the next acquire rebuilds it", async () => {
|
||||
const fake = fakeNativeModule();
|
||||
const lease = createNativeEngineLease(fake.native);
|
||||
|
||||
await lease.acquire();
|
||||
lease.release();
|
||||
expect(fake.calls.tearDown).toBe(1);
|
||||
expect(fake.native.toggleRecording(true)).toBe(false);
|
||||
|
||||
await lease.acquire();
|
||||
expect(fake.calls.initialize).toBe(2);
|
||||
expect(fake.native.toggleRecording(true)).toBe(true);
|
||||
});
|
||||
|
||||
test("concurrent acquires share one native initialize", async () => {
|
||||
const fake = fakeNativeModule();
|
||||
fake.deferNextInitialize();
|
||||
const lease = createNativeEngineLease(fake.native);
|
||||
|
||||
const first = lease.acquire();
|
||||
const second = lease.acquire();
|
||||
fake.finishInitialize();
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(fake.calls.initialize).toBe(1);
|
||||
lease.release();
|
||||
expect(fake.calls.tearDown).toBe(0);
|
||||
lease.release();
|
||||
expect(fake.calls.tearDown).toBe(1);
|
||||
});
|
||||
|
||||
test("a failed initialize is not counted as a holder and can be retried", async () => {
|
||||
const fake = fakeNativeModule({ initializeResult: false });
|
||||
const lease = createNativeEngineLease(fake.native);
|
||||
|
||||
await expect(lease.acquire()).rejects.toThrow("native initialize() returned false");
|
||||
lease.release();
|
||||
expect(fake.calls.tearDown).toBe(0);
|
||||
|
||||
await expect(lease.acquire()).rejects.toThrow();
|
||||
expect(fake.calls.initialize).toBe(2);
|
||||
});
|
||||
|
||||
test("a release with no holders is a no-op", async () => {
|
||||
const fake = fakeNativeModule();
|
||||
const lease = createNativeEngineLease(fake.native);
|
||||
|
||||
await lease.acquire();
|
||||
lease.release();
|
||||
lease.release();
|
||||
await lease.acquire();
|
||||
lease.release();
|
||||
|
||||
expect(fake.calls.tearDown).toBe(2);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* The part of `@getpaseo/expo-two-way-audio` that owns the native engine's lifetime.
|
||||
* Each platform keeps a single engine per app: `initialize()` reuses it, `tearDown()` frees it.
|
||||
*/
|
||||
export interface NativeAudioEngineLifecycle {
|
||||
initialize(): Promise<boolean>;
|
||||
tearDown(): void;
|
||||
}
|
||||
|
||||
export interface NativeEngineLease {
|
||||
/** Ensure the native engine exists and count the caller as a holder. */
|
||||
acquire(): Promise<void>;
|
||||
/** Drop one holder; the native engine is torn down when the last holder releases. */
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Voice mode and dictation each create their own JS audio engine, but both drive the one
|
||||
* native engine. Counting holders keeps one consumer's teardown from freeing the engine
|
||||
* the other still uses (issue #4147: voice mode on iOS could not start after dictation).
|
||||
*/
|
||||
export function createNativeEngineLease(native: NativeAudioEngineLifecycle): NativeEngineLease {
|
||||
let holders = 0;
|
||||
let ready: Promise<void> | null = null;
|
||||
|
||||
async function initialize(): Promise<void> {
|
||||
const success = await native.initialize();
|
||||
if (!success) {
|
||||
throw new Error("expo-two-way-audio: native initialize() returned false");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async acquire() {
|
||||
holders += 1;
|
||||
ready ??= initialize();
|
||||
try {
|
||||
await ready;
|
||||
} catch (error) {
|
||||
holders -= 1;
|
||||
ready = null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
release() {
|
||||
if (holders === 0) {
|
||||
return;
|
||||
}
|
||||
holders -= 1;
|
||||
if (holders === 0) {
|
||||
ready = null;
|
||||
native.tearDown();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
CalendarClock,
|
||||
CircleDashed,
|
||||
Copy,
|
||||
Folder,
|
||||
FolderPlus,
|
||||
History,
|
||||
@@ -17,6 +18,8 @@ import {
|
||||
} from "lucide-react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
|
||||
import { useOpenAddProject } from "@/hooks/use-open-add-project";
|
||||
import { useImportSession } from "@/hooks/use-import-session";
|
||||
@@ -27,6 +30,7 @@ import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
import { clearCommandCenterFocusRestoreElement } from "@/utils/command-center-focus-restore";
|
||||
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
||||
import {
|
||||
buildOpenProjectRoute,
|
||||
buildSchedulesRoute,
|
||||
@@ -35,6 +39,7 @@ import {
|
||||
} from "@/utils/host-routes";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import type { CommandCenterContribution, CommandCenterIconProps } from "./contributions";
|
||||
import { getCommandCenterIcon } from "./icon";
|
||||
import { useCommandCenterActions } from "./provider";
|
||||
import { buildGroupingContribution } from "./root-contributions";
|
||||
|
||||
@@ -63,6 +68,7 @@ const ThemedCircleDashed = withUnistyles(CircleDashed, (theme) => ({
|
||||
const ThemedPanelLeft = withUnistyles(PanelLeft, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const BrowserHostCopyIcon = getCommandCenterIcon(Copy);
|
||||
|
||||
function PlusIcon({ size }: CommandCenterIconProps) {
|
||||
return <ThemedPlus size={size} strokeWidth={2.4} />;
|
||||
@@ -111,6 +117,8 @@ function PanelLeftIcon({ size }: CommandCenterIconProps) {
|
||||
export function CommandCenterRootActions() {
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const browserHostLabel = getDesktopHost()?.browserHostLabel;
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
const shortcutsAvailable = useHardwareKeyboardPresent();
|
||||
const openAddProject = useOpenAddProject();
|
||||
@@ -296,6 +304,32 @@ export function CommandCenterRootActions() {
|
||||
},
|
||||
];
|
||||
|
||||
if (browserHostLabel) {
|
||||
availableActions.push({
|
||||
id: "copy-browser-host-name",
|
||||
group: "actions",
|
||||
groupRank: 0,
|
||||
rank: 9,
|
||||
keywords: ["browser", "host", "window", browserHostLabel],
|
||||
visibility: "query",
|
||||
run: async () => {
|
||||
try {
|
||||
await copyToClipboard(browserHostLabel);
|
||||
toast.copied();
|
||||
} catch {
|
||||
toast.error(t("common.errors.unableToCopy"));
|
||||
}
|
||||
},
|
||||
presentation: {
|
||||
kind: "action",
|
||||
title: t("shell.commandCenter.copyBrowserHostName"),
|
||||
subtitle: browserHostLabel,
|
||||
sectionTitle: t("shell.commandCenter.actions"),
|
||||
icon: BrowserHostCopyIcon,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (shortcutsAvailable) {
|
||||
availableActions.push({
|
||||
id: "keyboard-shortcuts",
|
||||
@@ -332,6 +366,7 @@ export function CommandCenterRootActions() {
|
||||
|
||||
return availableActions;
|
||||
}, [
|
||||
browserHostLabel,
|
||||
groupMode,
|
||||
homeRoute,
|
||||
keyboardActionDispatcher,
|
||||
@@ -346,6 +381,7 @@ export function CommandCenterRootActions() {
|
||||
shortcutPlatform,
|
||||
shortcutsAvailable,
|
||||
t,
|
||||
toast,
|
||||
toggleAgentList,
|
||||
]);
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
type ToolbarGlyph,
|
||||
} from "@/components/ui/control-geometry";
|
||||
|
||||
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
|
||||
|
||||
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
@@ -47,6 +49,7 @@ interface CombinedModelSelectorProps {
|
||||
hovered: boolean;
|
||||
pressed: boolean;
|
||||
}) => React.ReactNode;
|
||||
toggleAction?: KeyboardToggleAction;
|
||||
onOpen?: () => void;
|
||||
onClose?: () => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
@@ -82,6 +85,7 @@ export function CombinedModelSelector({
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
renderTrigger,
|
||||
toggleAction,
|
||||
onOpen,
|
||||
onClose,
|
||||
onRetryProvider,
|
||||
@@ -147,6 +151,14 @@ export function CombinedModelSelector({
|
||||
handleOpenChange(!isOpen);
|
||||
}, [handleOpenChange, isOpen]);
|
||||
|
||||
useKeyboardToggle({
|
||||
action: toggleAction,
|
||||
disabled,
|
||||
open: isOpen,
|
||||
searchFocused: browser.isSearchFocused,
|
||||
onToggle: handleTriggerPress,
|
||||
});
|
||||
|
||||
const triggerStyle = useCallback(
|
||||
({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
|
||||
if (triggerFill) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -215,6 +215,32 @@ describe("Mermaid sandbox runtime", () => {
|
||||
expect(widths).toEqual([240, 350, 900]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Agents often write a label that starts with a mention or holds an email address. Mermaid 11
|
||||
* read the text up to the "@" as an edge id, so these diagrams failed to parse.
|
||||
*/
|
||||
it.each([
|
||||
"flowchart LR\n F[@mention in any workspace] --> G[Look up token]",
|
||||
"flowchart LR\n A[ops@example.com] --> B",
|
||||
"flowchart LR\n A -->|@user approves| B",
|
||||
"graph TD\n A(@x) --> B{@x?}",
|
||||
])("renders a flowchart whose label contains an @: %s", async (source) => {
|
||||
const frame = await mountRuntime();
|
||||
|
||||
const result = await render(frame, { revision: 1, source });
|
||||
|
||||
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
|
||||
});
|
||||
|
||||
it("still renders a flowchart edge id", async () => {
|
||||
const frame = await mountRuntime();
|
||||
const source = "flowchart LR\n A[Start] e1@--> B[End]";
|
||||
|
||||
const result = await render(frame, { revision: 1, source });
|
||||
|
||||
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
|
||||
});
|
||||
|
||||
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")}`;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// @vitest-environment jsdom
|
||||
import type { ReactNode } from "react";
|
||||
import { cleanup, renderHook, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import type { AttachmentStore } from "@/attachments/types";
|
||||
import { useMarkdownSource, type MarkdownImageContext } from "./images";
|
||||
import { PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
|
||||
const memoryStore: AttachmentStore = {
|
||||
storageType: "web-indexeddb",
|
||||
async save(input) {
|
||||
return {
|
||||
id: input.id ?? "att_chart",
|
||||
mimeType: input.mimeType ?? "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
storageKey: input.id ?? "att_chart",
|
||||
fileName: input.fileName,
|
||||
createdAt: 1,
|
||||
};
|
||||
},
|
||||
async encodeBase64() {
|
||||
return "";
|
||||
},
|
||||
async resolvePreviewUrl() {
|
||||
return "blob:chart";
|
||||
},
|
||||
async releasePreviewUrl() {},
|
||||
async delete() {},
|
||||
async garbageCollect() {},
|
||||
};
|
||||
|
||||
function createHostFiles() {
|
||||
const reads: { cwd: string; path: string }[] = [];
|
||||
return {
|
||||
reads,
|
||||
async readFile(cwd: string, path: string): Promise<FileReadResult> {
|
||||
reads.push({ cwd, path });
|
||||
return {
|
||||
kind: "image",
|
||||
path,
|
||||
mime: "image/png",
|
||||
size: 4,
|
||||
modifiedAt: "2026-11-18T00:00:00.000Z",
|
||||
bytes: new Uint8Array([1, 2, 3, 4]),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
__setAttachmentStoreForTests(memoryStore);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
__setAttachmentStoreForTests(null);
|
||||
});
|
||||
|
||||
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
|
||||
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
|
||||
// retries have run out on a host that is slow to connect.
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
|
||||
wrapper,
|
||||
initialProps,
|
||||
});
|
||||
return { ...rendered, queryClient };
|
||||
}
|
||||
|
||||
it("waits for the host's client before reading a workspace image", async () => {
|
||||
const context = { serverId: "srv_test", workspaceRoot: "/repo" };
|
||||
const { result, rerender, queryClient } = renderMarkdownSource("", {
|
||||
...context,
|
||||
client: null,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe(
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
const files = createHostFiles();
|
||||
rerender({ ...context, client: files });
|
||||
|
||||
await waitFor(() => expect(result.current.imageSources).toEqual({ "blob:chart": "chart.png" }));
|
||||
expect(files.reads).toEqual([{ cwd: "/repo", path: "chart.png" }]);
|
||||
});
|
||||
|
||||
it("shows the alt text of a file image in Markdown that belongs to no host", async () => {
|
||||
const { result } = renderMarkdownSource("", {});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
|
||||
);
|
||||
});
|
||||
@@ -81,7 +81,10 @@ export function useMarkdownSource(
|
||||
const results = useFetchQueries(
|
||||
acquisitions.map((acquisition, index) => ({
|
||||
queryKey: ["markdownImage", acquisition?.key ?? sources[index]],
|
||||
enabled: acquisition !== null,
|
||||
// A host that hasn't connected yet has no client. Its images stay pending until it does: the
|
||||
// key doesn't change when the client arrives, so a read that already failed would not run
|
||||
// again. Markdown with no host has no client to wait for and falls back to its alt text.
|
||||
enabled: acquisition !== null && (context.client != null || !context.serverId),
|
||||
immutableWhen: () => true,
|
||||
dataShape: "value",
|
||||
gcTime: 0,
|
||||
|
||||
@@ -13,7 +13,7 @@ import { decodeMarkdownImage, getMarkdownImageStatus } from "./image-decoding";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { darkTheme, lightTheme } from "@/styles/theme";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import { isRecognizedLink, prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
|
||||
it("recognizes complete known commands in inline code", () => {
|
||||
@@ -38,6 +38,13 @@ it("resolves authored root-relative links only when the target is a known comman
|
||||
expect(matchCommandLink("https://example.com/code-review", "markdown", names)).toBeNull();
|
||||
});
|
||||
|
||||
it("treats only a parsed path or code span as a link the author did not write", () => {
|
||||
expect(isRecognizedLink({ sourceType: "text" })).toBe(true);
|
||||
expect(isRecognizedLink({ sourceType: "inline-code" })).toBe(true);
|
||||
expect(isRecognizedLink({ sourceType: "markdown" })).toBe(false);
|
||||
expect(isRecognizedLink({})).toBe(false);
|
||||
});
|
||||
|
||||
describe("shared Markdown source adaptation", () => {
|
||||
it("keeps paragraphs, fences and quotes together for the library", () => {
|
||||
const source = "First paragraph.\n\nSecond paragraph.\n\n```ts\nconst n = 1;\n```\n\n> Quote";
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { WEB_RENDERERS } from "./renderers.web";
|
||||
|
||||
const Link = WEB_RENDERERS.link;
|
||||
const LINK_TEXT = "src/index.ts";
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function anchorPropsFor(url: string) {
|
||||
return { href: url };
|
||||
}
|
||||
|
||||
function renderAnchor(link: { url: string; sourceType?: "markdown" | "text" | "inline-code" }) {
|
||||
if (!Link) {
|
||||
throw new Error("Expected a web link renderer");
|
||||
}
|
||||
const anchorProps = anchorPropsFor(link.url);
|
||||
const client = new QueryClient();
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<Link link={link} anchorProps={anchorProps}>
|
||||
{LINK_TEXT}
|
||||
</Link>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
const anchor = container.querySelector("a");
|
||||
if (!anchor) {
|
||||
throw new Error("Expected a rendered link");
|
||||
}
|
||||
return anchor;
|
||||
}
|
||||
|
||||
it("marks a link it recognized from a path for selection copy", () => {
|
||||
const anchor = renderAnchor({ url: LINK_TEXT, sourceType: "text" });
|
||||
expect(anchor.getAttribute("href")).toBe(LINK_TEXT);
|
||||
expect(anchor.getAttribute("data-paseo-markdown-recognized-link")).toBe("true");
|
||||
});
|
||||
|
||||
it("leaves an authored link wrapped", () => {
|
||||
const anchor = renderAnchor({ url: "https://example.test/doc", sourceType: "markdown" });
|
||||
expect(anchor.hasAttribute("data-paseo-markdown-recognized-link")).toBe(false);
|
||||
});
|
||||
@@ -7,12 +7,13 @@ import type {
|
||||
} from "react-native-enriched-markdown";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useFileLink } from "@/assistant-file-links";
|
||||
import { MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE } from "@/assistant-selection-copy/markup";
|
||||
import { useForgeShorthand } from "@/git/forge-shorthand";
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
||||
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { markdownLinkSource } from "./source";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
const codeStyle = (theme: Theme) => ({
|
||||
@@ -50,9 +51,18 @@ function WebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
}),
|
||||
[anchorProps.style, hovered],
|
||||
);
|
||||
// Selection copy pastes a link Paseo recognized as the text the reply showed.
|
||||
const recognized = isRecognizedLink(link);
|
||||
const copyAnchorProps = useMemo(
|
||||
() =>
|
||||
recognized
|
||||
? { ...anchorProps, [MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE]: "true" }
|
||||
: anchorProps,
|
||||
[anchorProps, recognized],
|
||||
);
|
||||
const anchor = (
|
||||
<a
|
||||
{...anchorProps}
|
||||
{...copyAnchorProps}
|
||||
href={forgeUrl ?? anchorProps.href}
|
||||
style={anchorStyle}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
|
||||
@@ -111,15 +111,25 @@ function collectInlineCodePaths(
|
||||
return paths;
|
||||
}
|
||||
|
||||
type LinkSourceType = "markdown" | "text" | "inline-code";
|
||||
|
||||
export function markdownLinkSource(
|
||||
url: string,
|
||||
sourceType?: "markdown" | "text" | "inline-code",
|
||||
sourceType?: LinkSourceType,
|
||||
): AssistantFileLinkSource {
|
||||
if (sourceType === "inline-code") return { href: url, text: url, sourceType };
|
||||
if (sourceType === "text") return { href: url, text: url, markup: "linkify" };
|
||||
return { href: url, text: url };
|
||||
}
|
||||
|
||||
/**
|
||||
* Link recognition classifies matches as `text` or `inline-code`. The renderer
|
||||
* classifies parser autolinks such as `www.example.com` as `markdown`.
|
||||
*/
|
||||
export function isRecognizedLink(link: { sourceType?: LinkSourceType }): boolean {
|
||||
return link.sourceType === "text" || link.sourceType === "inline-code";
|
||||
}
|
||||
|
||||
// Generated by scripts/generate-markdown-image-placeholder.mjs; reserves the image box.
|
||||
export const PENDING_MARKDOWN_IMAGE =
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAKACAYAAAAMzckjAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKBklEQVR42u3dXWscVRgH8ElFLK032tiCN1nSEiiowdKAn8DY2rR+AG965Qt4Y24Sm91kd5tN1ogQaGzzFfIl43Nki+s4u+m+ZWfC7weH0M6Z2QPn5s8zc87JMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgKvm/Px8YXd3d7Hdbi/Ns6UxxHAWzAgAwIxE4LrebDafxd/f9/b2TkvSujGep2lsZggAYIr29/c/iZDVKlHwy7dmryIIAEA2hcpfo9Folzj89YdAlUAAgEml174VCH//tBjrhhkDAMgmXvDxn2/+4t+von0dbXmOC0CW6/X6ehpL/9iiUtnNLAwBAMgmef27mK+ypfCXlac6uZ4fX6fTuWXmAADGD4C1fMCKCtzdsowvjaUgoNbMHADA+AFwuSBgLRsfAIAAmL/vRrSVVqu1mipy0a4JgAAAVzAAbm9v34nrP0a/17l7/oz25PT09H0BEADgigTAnZ2d+3H9eNg2LXHvb9E+FAABACoeAFPl76Lw13f/r9mUtmoRAAEA5hQAe69933nD5uj/UAAEAKhoAOwt+Pgr1+cwFoB8Hn9vx159j+Lvm9xzfhEAAQCqGwBXCvp80d8n/u957vofAiAAQEUDYCz+WC3oczv3nMe5I9tOBEAAgOpWAP93Wkh67fv2+tnZ2Xtp9W+uz74ACABQ3QB4Le3zl+uTvvl73qv8vSh4xvcCIABAhVcB1+v1jRFWAb+OZ3x60RnE0b6Lvj+kFhXFZ3Hu75IACABQkgCYTvgoeM07aAuYx4N+7+jo6GZc/3nI/T9tbm7eFAABAEpwEkg64SOubw6r/EUl79tswCbQW1tbH8XikPZFATL1SX0FQACAEpwFnMJd2uQ57fMX7SjaSVrwkb75G/baNwW6uP5yhI2kX/buEQABAOYcAEd2Qfh7Edd2BoXA2Gx6VQAEAKhQABwU/tLJIrGwZC37d5HJWv60kd7r4K4ACABQkQCYwl88rz3gW8G1fP+o9n1ZFAIFQACACgTAUcPfKCFQAAQAKFkAHDf8vWsIFAABAEoUAId98xftwQjjejAoBHY6nXtmDgCgBAFwWuGvPwSmqmHB874ycwAAcw6A0w5/b8Ur40f5Z8Yr4vtmDgBgjgFwVuHPSSAAACUMgJMu+BAAAQAqFABnHf4EQACAEgXAywh/AiAAQEkC4GWFPwEQAKAEAfAyw58ACAAw5wB42eFPAAQAmE3AquUDVrvdvluG8Ncb372CAFgzcwAA4wesxXzAqtfr62UIf73xfVNwFNwtMwcAML6FCFXdXIXtVQS79fSqNdpn0Q4LqnBv0ikdUS1cmkVLv52e32g0TnK/e5jGbNoAALKJqmxPC6p7pWwx1idmDABg8gB4PcJVswLhb+/4+PgDMwYAMKVvAaO1yhz+0hjNFADAFKXqWnx3txHf3XVLFPwO02tflT8AgNlaSCtt02KMg4ODWlrpGyFsZVYLPoYsBPnYgg8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOBK+hsMQ7RDjzvGwwAAAABJRU5ErkJggg==";
|
||||
|
||||
@@ -11,8 +11,12 @@ import {
|
||||
} from "@/components/attachment-pill";
|
||||
import { MarkdownRenderer } from "@/components/markdown/renderer";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { RewindMenu, type RewindMode } from "@/components/rewind/rewind-menu";
|
||||
import { useRewindAgentMutation } from "@/components/rewind/use-rewind-agent-mutation";
|
||||
import {
|
||||
isRewindableMessage,
|
||||
RewindMenu,
|
||||
useRewindAgentMutation,
|
||||
type RewindMode,
|
||||
} from "@/components/rewind";
|
||||
import { TaskListRow } from "@/components/task-list-row";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
@@ -530,7 +534,7 @@ export const UserMessage = memo(function UserMessage({
|
||||
<Text style={userMessageStylesheet.timestampText} testID="user-message-timestamp">
|
||||
{formattedTimestamp}
|
||||
</Text>
|
||||
{capabilities && messageId ? (
|
||||
{capabilities && isRewindableMessage(messageId, message) ? (
|
||||
<RewindMenu
|
||||
capabilities={capabilities}
|
||||
isPending={rewindMutation.isPending}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Undo2 } from "lucide-react-native";
|
||||
import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types";
|
||||
import type { CommandCenterContribution } from "@/command-center/contributions";
|
||||
import { getCommandCenterIcon } from "@/command-center/icon";
|
||||
import { useCommandCenterActions } from "@/command-center/provider";
|
||||
import { hasActiveMessageSubmission } from "@/composer/submission/model";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
|
||||
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
|
||||
export function RewindCommandCenterRegistration({
|
||||
serverId,
|
||||
agentId,
|
||||
capabilities,
|
||||
timelineSync,
|
||||
enabled,
|
||||
}: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
capabilities: AgentCapabilityFlags | null | undefined;
|
||||
timelineSync: AgentScreenReadySyncState | null;
|
||||
enabled: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const canSelectLatestMessage = enabled && timelineSync?.status === "idle";
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client);
|
||||
const message = useSessionStore((state) => {
|
||||
const session = state.sessions[serverId];
|
||||
if (
|
||||
!canSelectLatestMessage ||
|
||||
!session ||
|
||||
hasActiveMessageSubmission(session.messageSubmissions.get(agentId))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const timeline = selectAgentTimelineState(session, agentId);
|
||||
if (timeline.status !== "synced" || timeline.newer === "available") {
|
||||
return undefined;
|
||||
}
|
||||
return (
|
||||
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
|
||||
timeline.items.findLast((item) => item.kind === "user_message")
|
||||
);
|
||||
});
|
||||
const { rewindAgent, isPending } = useRewindAgentMutation({
|
||||
serverId,
|
||||
agentId,
|
||||
client,
|
||||
messageId: message?.messageId,
|
||||
});
|
||||
const items = useRewindMenuItems(capabilities);
|
||||
const actions = useMemo<CommandCenterContribution[]>(() => {
|
||||
if (!message || !isRewindableMessage(message.messageId, message.text)) return [];
|
||||
return items.map((item, rank) => ({
|
||||
id: `rewind:${item.mode}`,
|
||||
group: "rewind",
|
||||
groupRank: 1.5,
|
||||
rank,
|
||||
visibility: "query",
|
||||
keywords: ["rewind last turn", ...(item.mode === "files" ? [] : ["rewind chat"])],
|
||||
presentation: {
|
||||
kind: "action",
|
||||
title: item.label,
|
||||
subtitle: t("rewind.warning"),
|
||||
icon: getCommandCenterIcon(Undo2),
|
||||
},
|
||||
run: async () => {
|
||||
const dismiss = toast.show(`${item.label}…`, { durationMs: null });
|
||||
try {
|
||||
await rewindAgent({ mode: item.mode, rewoundText: message.text });
|
||||
} catch {
|
||||
// The mutation reports the failure through the app toast.
|
||||
} finally {
|
||||
dismiss();
|
||||
}
|
||||
},
|
||||
}));
|
||||
}, [items, message, rewindAgent, t, toast]);
|
||||
|
||||
useCommandCenterActions({
|
||||
sourceId: `rewind:${serverId}:${agentId}`,
|
||||
enabled: canSelectLatestMessage && Boolean(client) && !isPending,
|
||||
actions,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
@@ -8,7 +8,7 @@ interface RewindComposerRestoreContextValue {
|
||||
interface RewindComposerRestoreProviderProps {
|
||||
textSource: ComposerTextSource;
|
||||
setText: (text: string) => void;
|
||||
onRewindComplete: () => void;
|
||||
onRewindComplete: (restoredComposerText: boolean) => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
@@ -37,10 +37,11 @@ export function RewindComposerRestoreProvider({
|
||||
currentText: currentText,
|
||||
rewoundText,
|
||||
});
|
||||
if (nextText !== currentText) {
|
||||
const restoredComposerText = nextText !== currentText;
|
||||
if (restoredComposerText) {
|
||||
setText(nextText);
|
||||
}
|
||||
onRewindComplete();
|
||||
onRewindComplete(restoredComposerText);
|
||||
},
|
||||
[onRewindComplete, setText, textSource],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export { RewindCommandCenterRegistration } from "./command-center-registration";
|
||||
export { RewindComposerRestoreProvider } from "./composer-restore";
|
||||
export { RewindMenu } from "./rewind-menu";
|
||||
export { useRewindAgentMutation } from "./use-rewind-agent-mutation";
|
||||
export { isRewindableMessage, type RewindMode } from "./use-rewind-capabilities";
|
||||
@@ -11,11 +11,9 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { type RewindMode, useRewindCapabilities } from "./use-rewind-capabilities";
|
||||
import { type RewindMode, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
export type { RewindMode };
|
||||
|
||||
interface RewindMenuProps {
|
||||
capabilities: AgentCapabilityFlags;
|
||||
rewoundText: string;
|
||||
@@ -44,15 +42,7 @@ export const RewindMenu = memo(function RewindMenu({
|
||||
}: RewindMenuProps) {
|
||||
const { theme } = useUnistyles();
|
||||
const { t } = useTranslation();
|
||||
const rewindLabels = useMemo(
|
||||
() => ({
|
||||
conversation: t("rewind.actions.conversation"),
|
||||
files: t("rewind.actions.files"),
|
||||
both: t("rewind.actions.both"),
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const items = useRewindCapabilities(capabilities, rewindLabels);
|
||||
const items = useRewindMenuItems(capabilities);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [pendingMode, setPendingMode] = useState<RewindMode | null>(null);
|
||||
const isLocked = isPendingProp || pendingMode !== null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { RewindMode } from "./use-rewind-capabilities";
|
||||
@@ -29,7 +29,14 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
const toast = useToast();
|
||||
const { t } = useTranslation();
|
||||
const composerRestore = useRewindComposerRestore();
|
||||
const { isPending, mutateAsync } = useMutation({
|
||||
const queryClient = useQueryClient();
|
||||
const mutationKey = useMemo(
|
||||
() => ["agent-rewind", input.serverId, input.agentId],
|
||||
[input.serverId, input.agentId],
|
||||
);
|
||||
const isPending = useIsMutating({ mutationKey, exact: true }) > 0;
|
||||
const { mutateAsync } = useMutation({
|
||||
mutationKey,
|
||||
mutationFn: async ({ mode }: RewindAgentInput) => {
|
||||
if (!input.client || !input.agentId || !input.messageId) {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
@@ -61,12 +68,12 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
|
||||
const rewindAgent = useCallback(
|
||||
async (rewindInput: RewindAgentInput) => {
|
||||
if (isPending) {
|
||||
if (queryClient.isMutating({ mutationKey, exact: true }) > 0) {
|
||||
return;
|
||||
}
|
||||
await mutateAsync(rewindInput);
|
||||
},
|
||||
[isPending, mutateAsync],
|
||||
[mutateAsync, mutationKey, queryClient],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
export type RewindMode = "conversation" | "files" | "both";
|
||||
@@ -21,6 +22,10 @@ const DEFAULT_REWIND_MENU_LABELS: RewindMenuLabels = {
|
||||
both: "Rewind conversation and files",
|
||||
};
|
||||
|
||||
export function isRewindableMessage(messageId: string | undefined, text: string): boolean {
|
||||
return Boolean(messageId) && text.trim().length > 0;
|
||||
}
|
||||
|
||||
export function resolveRewindMenuItems(
|
||||
capabilities:
|
||||
| Pick<
|
||||
@@ -60,9 +65,17 @@ export function resolveRewindMenuItems(
|
||||
return items;
|
||||
}
|
||||
|
||||
export function useRewindCapabilities(
|
||||
export function useRewindMenuItems(
|
||||
capabilities: Parameters<typeof resolveRewindMenuItems>[0],
|
||||
labels?: Partial<RewindMenuLabels>,
|
||||
): RewindMenuItem[] {
|
||||
return useMemo(() => resolveRewindMenuItems(capabilities, labels), [capabilities, labels]);
|
||||
const { t } = useTranslation();
|
||||
return useMemo(
|
||||
() =>
|
||||
resolveRewindMenuItems(capabilities, {
|
||||
conversation: t("rewind.actions.conversation"),
|
||||
files: t("rewind.actions.files"),
|
||||
both: t("rewind.actions.both"),
|
||||
}),
|
||||
[capabilities, t],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useWorkspaceRowPress } from "../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import {
|
||||
@@ -86,6 +87,7 @@ import {
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { ProjectLeadingVisual } from "@/components/sidebar/project-leading-visual";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { SidebarToastClearance } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { getForgePresentation, normalizeForge } from "@/git/forge";
|
||||
import { hasVisibleOrderChanged, mergeWithRemainder } from "@/utils/sidebar-reorder";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
@@ -1090,13 +1092,11 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const handlePress = useCallback(() => {
|
||||
if (interaction.didLongPressRef.current) {
|
||||
interaction.didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [interaction.didLongPressRef, onPress]);
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
@@ -1191,6 +1191,7 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
/>
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
@@ -2551,6 +2552,7 @@ function ProjectModeList({
|
||||
: null}
|
||||
{sidebarFilterEmpty ? <SidebarFilterEmptyState /> : projectBody}
|
||||
{listFooterComponent}
|
||||
<SidebarToastClearance />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -2592,8 +2594,7 @@ 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,
|
||||
// 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.
|
||||
// Room for the sidebar toast comes from SidebarToastClearance at the end of the content.
|
||||
paddingBottom: theme.spacing[4],
|
||||
},
|
||||
projectListContainer: {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useWorkspaceRowPress } from "../../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
@@ -34,6 +35,7 @@ import {
|
||||
CircleX,
|
||||
} from "lucide-react-native";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { SidebarToastClearance } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { useSidebarWorkspaceRename } from "@/workspace-rename";
|
||||
import { useWorkspaceClipboardActions } from "@/hooks/use-workspace-clipboard-actions";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
@@ -270,6 +272,7 @@ export function SidebarStatusWorkspaceList({
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
/>
|
||||
)}
|
||||
<SidebarToastClearance />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -846,13 +849,11 @@ function StatusWorkspaceRowInnerContent({
|
||||
const startDragPress = dragInteraction?.handlePressIn;
|
||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||
const endDragPress = dragInteraction?.handlePressOut;
|
||||
const handlePress = useCallback(() => {
|
||||
if (didLongPressRef?.current) {
|
||||
didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [didLongPressRef, onPress]);
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
@@ -965,6 +966,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
/>
|
||||
) : null}
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
@@ -1089,8 +1091,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
// Keep status mode's Pinned/Workspaces boundary identical to project mode.
|
||||
paddingTop: 2,
|
||||
// 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.
|
||||
// Room for the sidebar toast comes from SidebarToastClearance at the end of the content.
|
||||
paddingBottom: theme.spacing[4],
|
||||
},
|
||||
pinnedSection: {
|
||||
|
||||
@@ -1,9 +1,31 @@
|
||||
import { useEffect, useMemo, useRef, type ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, {
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
|
||||
|
||||
interface SidebarToastCoverage {
|
||||
toastVisible: boolean;
|
||||
/** Distance from the region's bottom edge to the toast's top edge, as last laid out. */
|
||||
height: SharedValue<number>;
|
||||
}
|
||||
|
||||
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
|
||||
|
||||
/**
|
||||
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
|
||||
*
|
||||
@@ -15,6 +37,8 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
|
||||
const appToast = useToast();
|
||||
const { api: sidebarToast, toast, dismiss } = useToastHost();
|
||||
const activeRef = useRef(active);
|
||||
const coverageHeight = useSharedValue(0);
|
||||
const toastVisible = toast !== null;
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = active;
|
||||
@@ -35,14 +59,58 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
|
||||
};
|
||||
}, [appToast, sidebarToast]);
|
||||
|
||||
const coverage = useMemo<SidebarToastCoverage>(
|
||||
() => ({ toastVisible, height: coverageHeight }),
|
||||
[toastVisible, coverageHeight],
|
||||
);
|
||||
const handleCoverageChange = useCallback(
|
||||
(height: number) => {
|
||||
coverageHeight.value = height;
|
||||
},
|
||||
[coverageHeight],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.region}>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
<ToastViewport toast={toast} onDismiss={dismiss} placement="sidebar" />
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
|
||||
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
|
||||
* with the toast's fade, so a list scrolled to its end settles back with the toast instead of
|
||||
* jumping.
|
||||
*/
|
||||
export function SidebarToastClearance() {
|
||||
const coverage = useContext(SidebarToastCoverageContext);
|
||||
return coverage ? <AnimatedClearance coverage={coverage} /> : null;
|
||||
}
|
||||
|
||||
function AnimatedClearance({ coverage }: { coverage: SidebarToastCoverage }) {
|
||||
const { toastVisible, height } = coverage;
|
||||
const style = useAnimatedStyle(() => ({
|
||||
height: withTiming(toastVisible ? height.value : 0, { duration: TOAST_FADE_MS }),
|
||||
}));
|
||||
return (
|
||||
<Animated.View
|
||||
style={style}
|
||||
pointerEvents="none"
|
||||
testID="sidebar-toast-clearance"
|
||||
aria-hidden
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
region: {
|
||||
position: "relative",
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function mountToastHost(): ToastApi {
|
||||
let api: ToastApi | null = null;
|
||||
function Host() {
|
||||
const host = useToastHost();
|
||||
api = host.api;
|
||||
return <ToastViewport toast={host.toast} onDismiss={host.dismiss} placement="sidebar" />;
|
||||
}
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() =>
|
||||
root?.render(
|
||||
<SafeAreaProvider>
|
||||
<Host />
|
||||
</SafeAreaProvider>,
|
||||
),
|
||||
);
|
||||
if (!api) throw new Error("The toast host did not render");
|
||||
return api;
|
||||
}
|
||||
|
||||
function shownMessage(): string | null {
|
||||
return document.querySelector('[data-testid="app-toast-message"]')?.textContent ?? null;
|
||||
}
|
||||
|
||||
describe("ToastViewport", () => {
|
||||
it("keeps a new toast when the toast it replaced times out before the next render", () => {
|
||||
vi.useFakeTimers();
|
||||
const toast = mountToastHost();
|
||||
act(() => {
|
||||
toast.show("Installed review");
|
||||
});
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2199);
|
||||
});
|
||||
|
||||
// The new toast is in state, but React has not rendered it, so the old toast's timer is
|
||||
// still scheduled when it expires.
|
||||
act(() => {
|
||||
toast.show("Reloaded review");
|
||||
vi.advanceTimersByTime(1);
|
||||
});
|
||||
|
||||
expect(shownMessage()).toBe("Reloaded review");
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2199);
|
||||
});
|
||||
expect(shownMessage()).toBe("Reloaded review");
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,14 @@ import {
|
||||
} from "@/components/floating-header";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Platform, StyleSheet as NativeStyleSheet, Text, ToastAndroid, View } from "react-native";
|
||||
import {
|
||||
Platform,
|
||||
StyleSheet as NativeStyleSheet,
|
||||
Text,
|
||||
ToastAndroid,
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native";
|
||||
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
@@ -46,6 +53,12 @@ export interface ToastState {
|
||||
/** Dismisses the toast it was returned for; a no-op once another toast replaced it. */
|
||||
export type DismissToast = () => void;
|
||||
|
||||
/**
|
||||
* Dismisses the toast with this ID, and does nothing once another toast replaced it. Without an
|
||||
* ID, it dismisses whichever toast is shown.
|
||||
*/
|
||||
export type DismissToastById = (id?: number) => void;
|
||||
|
||||
export interface ToastApi {
|
||||
show: (content: ReactNode, options?: ToastShowOptions) => DismissToast;
|
||||
copied: (label?: string) => void;
|
||||
@@ -57,8 +70,11 @@ type ToastViewportPlacement = "app-shell" | "panel" | "sidebar";
|
||||
const DEFAULT_DURATION_MS = 2200;
|
||||
const noopDismiss: DismissToast = () => {};
|
||||
const TOAST_MAX_WIDTH = 480;
|
||||
const toastEntering = FadeIn.duration(140);
|
||||
const toastExiting = FadeOut.duration(140);
|
||||
/** How long a toast takes to fade in or out. */
|
||||
export const TOAST_FADE_MS = 140;
|
||||
const SIDEBAR_TOAST_INSET = SPACING[2];
|
||||
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
|
||||
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
|
||||
const ThemedCheckCircle = withUnistyles(CheckCircle2);
|
||||
const ThemedInfo = withUnistyles(Info);
|
||||
const ThemedWarning = withUnistyles(AlertTriangle);
|
||||
@@ -71,7 +87,7 @@ const errorIcon = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
export function useToastHost(): {
|
||||
api: ToastApi;
|
||||
toast: ToastState | null;
|
||||
dismiss: () => void;
|
||||
dismiss: DismissToastById;
|
||||
} {
|
||||
const { t } = useTranslation();
|
||||
const [toast, setToastState] = useState<ToastState | null>(null);
|
||||
@@ -86,6 +102,13 @@ export function useToastHost(): {
|
||||
previous?.onDismiss?.();
|
||||
}, []);
|
||||
|
||||
const dismiss = useCallback<DismissToastById>(
|
||||
(id) => {
|
||||
if (id === undefined || toastRef.current?.id === id) setToast(null);
|
||||
},
|
||||
[setToast],
|
||||
);
|
||||
|
||||
const show = useCallback(
|
||||
(content: ReactNode, options?: ToastShowOptions): DismissToast => {
|
||||
const nativeMessage = typeof content === "string" ? content.trim() : null;
|
||||
@@ -117,11 +140,9 @@ export function useToastHost(): {
|
||||
testID: options?.testID,
|
||||
onDismiss: options?.onDismiss,
|
||||
});
|
||||
return () => {
|
||||
if (toastRef.current?.id === id) setToast(null);
|
||||
};
|
||||
return () => dismiss(id);
|
||||
},
|
||||
[setToast],
|
||||
[dismiss, setToast],
|
||||
);
|
||||
|
||||
const api = useMemo<ToastApi>(
|
||||
@@ -137,10 +158,6 @@ export function useToastHost(): {
|
||||
[show, t],
|
||||
);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
setToast(null);
|
||||
}, [setToast]);
|
||||
|
||||
return { api, toast, dismiss };
|
||||
}
|
||||
|
||||
@@ -148,10 +165,14 @@ export function ToastViewport({
|
||||
toast,
|
||||
onDismiss,
|
||||
placement = "app-shell",
|
||||
onBottomCoverageChange,
|
||||
}: {
|
||||
toast: ToastState | null;
|
||||
onDismiss: () => void;
|
||||
/** Called with the ID of the toast that timed out. */
|
||||
onDismiss: (id: number) => void;
|
||||
placement?: ToastViewportPlacement;
|
||||
/** Sidebar placement: reports the distance from the region's bottom edge to the toast's top. */
|
||||
onBottomCoverageChange?: (coverage: number) => void;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
@@ -167,7 +188,7 @@ export function ToastViewport({
|
||||
}, []);
|
||||
|
||||
const scheduleDismiss = useCallback(
|
||||
(durationMs: number | null) => {
|
||||
(id: number, durationMs: number | null) => {
|
||||
clearTimer();
|
||||
if (durationMs === null) {
|
||||
remainingDurationRef.current = 0;
|
||||
@@ -177,8 +198,10 @@ export function ToastViewport({
|
||||
const nextDurationMs = Math.max(0, durationMs);
|
||||
remainingDurationRef.current = nextDurationMs;
|
||||
dismissDeadlineRef.current = Date.now() + nextDurationMs;
|
||||
// A replacing toast is in the host before this viewport renders it and reschedules, so the
|
||||
// timer names its own toast rather than dismissing whichever one is current.
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
onDismiss();
|
||||
onDismiss(id);
|
||||
}, nextDurationMs);
|
||||
},
|
||||
[onDismiss, clearTimer],
|
||||
@@ -196,16 +219,24 @@ export function ToastViewport({
|
||||
if (!toast || toast.durationMs === null) {
|
||||
return;
|
||||
}
|
||||
scheduleDismiss(remainingDurationRef.current || toast.durationMs);
|
||||
scheduleDismiss(toast.id, remainingDurationRef.current || toast.durationMs);
|
||||
}, [scheduleDismiss, toast]);
|
||||
|
||||
const toastId = toast?.id;
|
||||
const durationMs = toast?.durationMs ?? null;
|
||||
useEffect(() => {
|
||||
scheduleDismiss(durationMs);
|
||||
if (toastId === undefined) return;
|
||||
scheduleDismiss(toastId, durationMs);
|
||||
return clearTimer;
|
||||
}, [clearTimer, durationMs, scheduleDismiss, toastId]);
|
||||
|
||||
const handleSidebarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
|
||||
},
|
||||
[onBottomCoverageChange],
|
||||
);
|
||||
|
||||
const panelClearance = useFloatingHeaderOverlayClearance();
|
||||
const headerHeight = isMobile ? HEADER_INNER_HEIGHT_MOBILE : HEADER_INNER_HEIGHT;
|
||||
const headerTopPadding = isMobile ? HEADER_TOP_PADDING_MOBILE : 0;
|
||||
@@ -227,6 +258,7 @@ export function ToastViewport({
|
||||
}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
|
||||
>
|
||||
<View
|
||||
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
|
||||
@@ -307,9 +339,9 @@ const animatedStyles = NativeStyleSheet.create({
|
||||
},
|
||||
sidebarContainer: {
|
||||
position: "absolute",
|
||||
left: SPACING[2],
|
||||
right: SPACING[2],
|
||||
bottom: SPACING[2],
|
||||
left: SIDEBAR_TOAST_INSET,
|
||||
right: SIDEBAR_TOAST_INSET,
|
||||
bottom: SIDEBAR_TOAST_INSET,
|
||||
zIndex: OVERLAY_Z.toast,
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
@@ -21,7 +21,7 @@ import { highlightDiffLines } from "@/utils/diff-highlight";
|
||||
import { hasMeaningfulToolCallDetail } from "@/utils/tool-call-detail-state";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
|
||||
import { extensionFromPath, highlightToKeyedLines } from "@/utils/highlight-cache";
|
||||
import { highlightToKeyedLines } from "@/utils/highlight-cache";
|
||||
import { HighlightedLines } from "./highlighted-content";
|
||||
import { DiffViewer } from "./diff-viewer";
|
||||
import { getCodeInsets } from "./code-insets";
|
||||
@@ -226,7 +226,7 @@ function ScrollableTextSection({
|
||||
startLine,
|
||||
}: ScrollableContentProps) {
|
||||
const keyedLines = useMemo(
|
||||
() => (filePath ? highlightToKeyedLines(content, extensionFromPath(filePath)) : null),
|
||||
() => highlightToKeyedLines(content, filePath ?? null),
|
||||
[content, filePath],
|
||||
);
|
||||
const body = (
|
||||
|
||||
@@ -3,7 +3,15 @@ import { createRoot, type Root } from "react-dom/client";
|
||||
import { Text, View } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
import { MenuRoot, MenuSurface, MenuTrigger, type Size } from "./index";
|
||||
import {
|
||||
MenuItem,
|
||||
MenuRoot,
|
||||
MenuSubTrigger,
|
||||
MenuSurface,
|
||||
MenuTrigger,
|
||||
type MenuPageDefinition,
|
||||
type Size,
|
||||
} from "./index";
|
||||
|
||||
// App sources compile against the classic JSX runtime, which expects React on the global.
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
@@ -122,3 +130,65 @@ describe("anchored menu surface on web", () => {
|
||||
expect(panel.width).toBeGreaterThanOrEqual(body.width);
|
||||
});
|
||||
});
|
||||
|
||||
const SUB_PAGES: MenuPageDefinition[] = [
|
||||
{
|
||||
id: "show",
|
||||
title: "Show",
|
||||
content: (
|
||||
<MenuItem testID="show-option" closeOnSelect={false}>
|
||||
Archived
|
||||
</MenuItem>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
/** Past the grace a flyout is given after the pointer leaves, so a queued close has landed. */
|
||||
const HOVER_CLOSE_SETTLED_MS = 600;
|
||||
|
||||
/**
|
||||
* A tap as the browser reports it: the finger enters the row as it lands and leaves it as it
|
||||
* lifts, and only then does the click arrive.
|
||||
*/
|
||||
function tap(target: HTMLElement): void {
|
||||
const pointer = (type: string) =>
|
||||
target.dispatchEvent(
|
||||
new PointerEvent(type, { bubbles: true, pointerType: "touch", isPrimary: true }),
|
||||
);
|
||||
act(() => {
|
||||
pointer("pointerover");
|
||||
pointer("pointerdown");
|
||||
pointer("pointerup");
|
||||
pointer("pointerout");
|
||||
target.click();
|
||||
});
|
||||
}
|
||||
|
||||
describe("submenu flyout on a touch screen", () => {
|
||||
beforeEach(async () => {
|
||||
await page.viewport(1280, 900);
|
||||
});
|
||||
|
||||
it("stays open after a tap on its row, and after a tap inside it", async () => {
|
||||
mount(
|
||||
<MenuRoot>
|
||||
<MenuTrigger testID="pill" accessibilityLabel="Open menu">
|
||||
<Text>Open menu</Text>
|
||||
</MenuTrigger>
|
||||
<MenuSurface pages={SUB_PAGES} testID="panel">
|
||||
<MenuSubTrigger id="show" testID="show-row">
|
||||
Show
|
||||
</MenuSubTrigger>
|
||||
</MenuSurface>
|
||||
</MenuRoot>,
|
||||
);
|
||||
act(() => element("pill").click());
|
||||
|
||||
tap(element("show-row"));
|
||||
await wait(HOVER_CLOSE_SETTLED_MS);
|
||||
tap(element("show-option"));
|
||||
await wait(HOVER_CLOSE_SETTLED_MS);
|
||||
|
||||
expect(document.querySelector('[data-testid="show-option"]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
Platform,
|
||||
Pressable,
|
||||
View,
|
||||
type PointerEvent,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
@@ -217,8 +218,8 @@ export interface AnchoredSurfaceProps {
|
||||
* Hover tracking for the surface box, per docs/hover.md: plain View, pointer events, never
|
||||
* a Pressable. Web-only by nature, which is all a flyout needs.
|
||||
*/
|
||||
onPointerEnter?: () => void;
|
||||
onPointerLeave?: () => void;
|
||||
onPointerEnter?: (event: PointerEvent) => void;
|
||||
onPointerLeave?: (event: PointerEvent) => void;
|
||||
testID?: string;
|
||||
keyboardFocusScope?: KeyboardFocusScope;
|
||||
children: ReactElement;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { PointerEvent } from "react-native";
|
||||
|
||||
/**
|
||||
* Whether a pointer event came from something that can rest on a row without pressing it.
|
||||
*
|
||||
* A finger cannot, but the browser still reports one entering a row as the tap lands and leaving
|
||||
* as it lifts. Read as hover, that leave queues a close just as the tap's own press opens the
|
||||
* submenu, and the flyout vanishes a moment after it appears. A touch screen can have a mouse
|
||||
* attached too, so this has to be asked of each event, not of the device.
|
||||
*/
|
||||
export function isHoverPointer(event: PointerEvent): boolean {
|
||||
return event.nativeEvent.pointerType !== "touch";
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type PropsWithChildren,
|
||||
type ReactElement,
|
||||
} from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { Text, View, type PointerEvent } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { ChevronRight } from "lucide-react-native";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -14,6 +14,7 @@ import { useMenuContext, useMenuDepth } from "./menu-context";
|
||||
import { isSubPageOpen } from "./menu-navigation";
|
||||
import { useMenuSurface } from "./menu-surface";
|
||||
import { MenuItem } from "./menu-item";
|
||||
import { isHoverPointer } from "./menu-pointer";
|
||||
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight);
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
@@ -25,7 +26,8 @@ const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMute
|
||||
*
|
||||
* Hover lives on a plain `View` wrapping the item's `Pressable`, per docs/hover.md — a
|
||||
* `Pressable` tracking its own hover would fight the one inside it. Hover only fires on web,
|
||||
* which is exactly where flyouts exist; every other platform opens the page by pressing.
|
||||
* which is exactly where flyouts exist; every other platform opens the page by pressing. So does
|
||||
* a finger on the web, whose taps arrive as pointer events but are not hover.
|
||||
*/
|
||||
export function MenuSubTrigger({
|
||||
id,
|
||||
@@ -68,14 +70,22 @@ export function MenuSubTrigger({
|
||||
menu.openSub({ id, depth });
|
||||
}, [menu, id, depth]);
|
||||
|
||||
const handlePointerEnter = useCallback(() => {
|
||||
cancelHoverClose();
|
||||
hoverOpen({ id, depth });
|
||||
}, [cancelHoverClose, hoverOpen, id, depth]);
|
||||
const handlePointerEnter = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
if (!isHoverPointer(event)) return;
|
||||
cancelHoverClose();
|
||||
hoverOpen({ id, depth });
|
||||
},
|
||||
[cancelHoverClose, hoverOpen, id, depth],
|
||||
);
|
||||
|
||||
const handlePointerLeave = useCallback(() => {
|
||||
hoverClose(depth);
|
||||
}, [hoverClose, depth]);
|
||||
const handlePointerLeave = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
if (!isHoverPointer(event)) return;
|
||||
hoverClose(depth);
|
||||
},
|
||||
[hoverClose, depth],
|
||||
);
|
||||
|
||||
const trailing = useMemo(
|
||||
() => <MenuSubTrailing value={value} indicator={indicator} />,
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pressable, Text, View, useWindowDimensions } from "react-native";
|
||||
import { Pressable, Text, View, useWindowDimensions, type PointerEvent } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { BottomSheetScrollView } from "@gorhom/bottom-sheet";
|
||||
import { ChevronLeft } from "lucide-react-native";
|
||||
@@ -30,6 +30,7 @@ import { useMenuContext, MenuContextProvider } from "./menu-context";
|
||||
import { MenuPage } from "./menu-item";
|
||||
import { currentPageId, isSubPageOpen } from "./menu-navigation";
|
||||
import { AnchoredSurface, MenuOverlay } from "./menu-overlay";
|
||||
import { isHoverPointer } from "./menu-pointer";
|
||||
import { getMenuSheetBottomPadding } from "./menu-sheet-layout";
|
||||
import type { Alignment, Placement } from "../anchor";
|
||||
import type { KeyboardFocusScope } from "@/keyboard/actions";
|
||||
@@ -327,7 +328,19 @@ function MenuFlyout({
|
||||
const menu = useMenuContext("MenuFlyout");
|
||||
const { hoverClose, cancelHoverClose } = useMenuSurface("MenuFlyout");
|
||||
const handleClose = useCallback(() => menu.setOpen(false), [menu]);
|
||||
const handleHoverOut = useCallback(() => hoverClose(depth), [hoverClose, depth]);
|
||||
const handleHoverIn = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
if (isHoverPointer(event)) cancelHoverClose();
|
||||
},
|
||||
[cancelHoverClose],
|
||||
);
|
||||
// A tap inside the flyout ends with the finger leaving it, which is not the pointer walking off.
|
||||
const handleHoverOut = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
if (isHoverPointer(event)) hoverClose(depth);
|
||||
},
|
||||
[hoverClose, depth],
|
||||
);
|
||||
|
||||
if (!anchorRef) return null;
|
||||
|
||||
@@ -344,7 +357,7 @@ function MenuFlyout({
|
||||
maxHeight={maxHeight}
|
||||
scrollable={scrollable}
|
||||
backdrop={false}
|
||||
onPointerEnter={cancelHoverClose}
|
||||
onPointerEnter={handleHoverIn}
|
||||
onPointerLeave={handleHoverOut}
|
||||
testID={testID}
|
||||
>
|
||||
|
||||
@@ -82,10 +82,10 @@ describe("ComposerControls", () => {
|
||||
expect(trigger.textContent).not.toContain("Large");
|
||||
});
|
||||
|
||||
it("flips a toggle on press in the toolbar", () => {
|
||||
it("keeps the toolbar toggle name and flips it on press", () => {
|
||||
const onChange = vi.fn();
|
||||
renderControls([{ ...base, type: "toggle", value: true, onChange }]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Context" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Context$/ }));
|
||||
expect(onChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
@@ -94,6 +94,12 @@ describe("ComposerControls", () => {
|
||||
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("On");
|
||||
});
|
||||
|
||||
it("keeps the provider's tooltip for a toolbar toggle", () => {
|
||||
const tooltip = "Fast is enabled but does not apply to this model.";
|
||||
renderControls([{ ...base, type: "toggle", value: true, tooltip, onChange: () => undefined }]);
|
||||
expect(screen.getByRole("button", { name: tooltip })).toBeDefined();
|
||||
});
|
||||
|
||||
it("gives a sheet row's value the row's width, so a short value is not truncated", () => {
|
||||
const toast = createToast();
|
||||
render(
|
||||
@@ -157,6 +163,8 @@ describe("ComposerControls", () => {
|
||||
});
|
||||
|
||||
const FAST_ON = { fast_mode: true };
|
||||
const ULTRACODE_ON = { ultracode: true };
|
||||
const ignoreOption = () => undefined;
|
||||
|
||||
describe("provider option controls", () => {
|
||||
const fastMode: AgentOptionControl = {
|
||||
@@ -173,7 +181,11 @@ describe("provider option controls", () => {
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}) {
|
||||
const optionControls = React.useMemo(
|
||||
() => ({ controls: [fastMode], options, onSetOption }),
|
||||
() => ({
|
||||
controls: [fastMode, { key: "ultracode", label: "Ultracode", type: "toggle" as const }],
|
||||
options,
|
||||
onSetOption,
|
||||
}),
|
||||
[onSetOption, options],
|
||||
);
|
||||
const items = useAgentControlItems({
|
||||
@@ -197,4 +209,9 @@ describe("provider option controls", () => {
|
||||
fireEvent.click(screen.getByTestId("agent-feature-fast_mode"));
|
||||
expect(writes).toEqual([["fast_mode", false]]);
|
||||
});
|
||||
|
||||
it("announces the state of a provider toggle with no custom tooltip", () => {
|
||||
render(<OptionControls options={ULTRACODE_ON} onSetOption={ignoreOption} />);
|
||||
expect(screen.getByRole("button", { name: "Ultracode: On" })).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,6 +21,8 @@ import { ICON_SIZE } from "@/styles/theme";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { AgentControlTrigger } from "@/composer/agent-controls/control";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
|
||||
interface ComposerControlBase {
|
||||
@@ -28,7 +30,7 @@ interface ComposerControlBase {
|
||||
title: string;
|
||||
icon: AgentControlIcon;
|
||||
/** Tints the icon; muted when absent. */
|
||||
highlight?: "blue" | "green" | "yellow";
|
||||
highlight?: "blue" | "green" | "purple" | "yellow";
|
||||
/** Defaults to the title, or to "title: choice" on an icon-only select. */
|
||||
tooltip?: string;
|
||||
/** Defaults to the tooltip. */
|
||||
@@ -106,6 +108,7 @@ interface ComposerControlProps {
|
||||
disabled?: boolean;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
shortcutKeys?: ShortcutKey[][] | null;
|
||||
/** Runs after a toolbar toggle or action, so the composer can take focus back. */
|
||||
onActionComplete?: () => void;
|
||||
}
|
||||
@@ -217,6 +220,7 @@ export function ComposerControl({
|
||||
open,
|
||||
onOpenChange,
|
||||
onActionComplete,
|
||||
shortcutKeys,
|
||||
}: ComposerControlProps) {
|
||||
const { t } = useTranslation();
|
||||
const anchorRef = useRef<View>(null);
|
||||
@@ -279,7 +283,7 @@ export function ComposerControl({
|
||||
{trigger}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<Text style={styles.tooltipText}>{view.tooltip}</Text>
|
||||
<ControlTooltipHint label={view.tooltip} shortcutKeys={shortcutKeys} />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
@@ -349,6 +353,7 @@ interface ComposerControlsProps {
|
||||
items: readonly ComposerControlItem[];
|
||||
surface: ComposerControlSurface;
|
||||
disabled?: boolean;
|
||||
shortcutKeys?: ShortcutKey[][] | null;
|
||||
/** The id of the item whose list is open. */
|
||||
openId: string | null;
|
||||
onOpenIdChange: (id: string | null) => void;
|
||||
@@ -390,9 +395,30 @@ function ComposerControlSlot({
|
||||
return <ComposerControl item={item} open={open} onOpenChange={handleOpenChange} {...rest} />;
|
||||
}
|
||||
|
||||
export function ControlTooltipHint({
|
||||
label,
|
||||
shortcutKeys,
|
||||
}: {
|
||||
label: string;
|
||||
shortcutKeys?: ShortcutKey[][] | null;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.tooltipRow}>
|
||||
<Text style={styles.tooltipText}>{label}</Text>
|
||||
{shortcutKeys ? <Shortcut chord={shortcutKeys} /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
tooltipRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
fieldIcon: { color: theme.colors.foregroundMuted },
|
||||
blue: { color: theme.colors.palette.blue[400] },
|
||||
purple: { color: theme.colors.palette.purple[500] },
|
||||
green: { color: theme.colors.palette.green[400] },
|
||||
yellow: { color: theme.colors.palette.yellow[400] },
|
||||
tooltipText: {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from "react";
|
||||
import { useId, useMemo } from "react";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DensityIcon } from "@/components/ui/density-icon";
|
||||
@@ -19,6 +19,12 @@ import {
|
||||
import type { ComposerControlPresentation } from "@/composer/agent-controls/layout";
|
||||
import { getAgentControlHintKey, getFeatureHighlightColor } from "@/composer/agent-controls/utils";
|
||||
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useComposerInput } from "@/composer/session";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { resolveNextChoiceId } from "./mode";
|
||||
|
||||
const SEARCH_THRESHOLD = 6;
|
||||
|
||||
function getFeatureHighlight(
|
||||
@@ -33,6 +39,8 @@ function getFeatureHighlight(
|
||||
function toFeatureItem(
|
||||
control: AgentOptionControl,
|
||||
optionControls: ComposerOptionControls,
|
||||
surface: ComposerControlSurface,
|
||||
t: TFunction,
|
||||
): ComposerControlItem {
|
||||
const { options, onSetOption } = optionControls;
|
||||
const base = {
|
||||
@@ -43,11 +51,15 @@ function toFeatureItem(
|
||||
testID: `agent-feature-${control.key}`,
|
||||
};
|
||||
if (control.type === "toggle") {
|
||||
const enabled = readToggleOption(control, options);
|
||||
const stateLabel = enabled ? t("agentControls.features.on") : t("agentControls.features.off");
|
||||
return {
|
||||
...base,
|
||||
type: "toggle",
|
||||
tooltip: getControlTooltip(control),
|
||||
value: readToggleOption(control, options),
|
||||
tooltip:
|
||||
control.tooltip ??
|
||||
(surface === "toolbar" ? `${control.label}: ${stateLabel}` : control.label),
|
||||
value: enabled,
|
||||
onChange: (value) => onSetOption(control.key, value),
|
||||
};
|
||||
}
|
||||
@@ -71,6 +83,41 @@ interface ThinkingControl {
|
||||
displayLabel: string;
|
||||
}
|
||||
|
||||
export function useModelPickerShortcut(disabled: boolean) {
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const input = useComposerInput();
|
||||
const action =
|
||||
isActiveComposer && !disabled && input
|
||||
? {
|
||||
id: "message-input.model-toggle" as const,
|
||||
canOpen: input.isFocused,
|
||||
}
|
||||
: undefined;
|
||||
const keys = useShortcutKeys(action ? "toggle-model-picker" : null);
|
||||
return { action, keys };
|
||||
}
|
||||
|
||||
export function useEffortCycleShortcut(thinking: ThinkingControl | null, disabled: boolean) {
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const input = useComposerInput();
|
||||
const effortHandlerId = useId();
|
||||
const nextEffortId = resolveNextChoiceId(thinking?.options ?? [], thinking?.selectedId);
|
||||
const canCycleEffort = isActiveComposer && !disabled && nextEffortId !== null && input !== null;
|
||||
useKeyboardActionHandler({
|
||||
handlerId: effortHandlerId,
|
||||
actions: ["message-input.effort-cycle"],
|
||||
enabled: canCycleEffort,
|
||||
isActive: input?.isFocused,
|
||||
priority: 200,
|
||||
handle: () => {
|
||||
if (!thinking || nextEffortId === null) return false;
|
||||
thinking.onSelect(nextEffortId);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
return useShortcutKeys(canCycleEffort ? "cycle-effort" : null);
|
||||
}
|
||||
|
||||
/** The thinking select and the option controls, as the data `ComposerControl` draws. */
|
||||
export function useAgentControlItems({
|
||||
surface,
|
||||
@@ -92,9 +139,11 @@ export function useAgentControlItems({
|
||||
const features = useMemo(
|
||||
() =>
|
||||
optionControls
|
||||
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
|
||||
? optionControls.controls.map((control) =>
|
||||
toFeatureItem(control, optionControls, surface, t),
|
||||
)
|
||||
: [],
|
||||
[optionControls],
|
||||
[optionControls, surface, t],
|
||||
);
|
||||
return { thinking: thinkingItem, features };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useTranslation } from "react-i18next";
|
||||
import { router } from "expo-router";
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
Pressable,
|
||||
Keyboard,
|
||||
useWindowDimensions,
|
||||
@@ -62,6 +61,7 @@ import {
|
||||
useAgentControlCommandCenterActions,
|
||||
type AgentControlCommandCenterSource,
|
||||
} from "@/command-center/agent-control-registration";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import {
|
||||
composerToolbarGeometry,
|
||||
@@ -74,9 +74,14 @@ import { ComposerControlLayoutProvider } from "@/composer/agent-controls/layout-
|
||||
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
|
||||
import {
|
||||
ComposerControls,
|
||||
ControlTooltipHint,
|
||||
type ComposerControlItem,
|
||||
} from "@/composer/agent-controls/composer-control";
|
||||
import { useAgentControlItems } from "@/composer/agent-controls/control-items";
|
||||
import {
|
||||
useAgentControlItems,
|
||||
useEffortCycleShortcut,
|
||||
useModelPickerShortcut,
|
||||
} from "@/composer/agent-controls/control-items";
|
||||
import { CompactModelSheet } from "@/composer/agent-controls/model-sheet";
|
||||
import { useComposerSheetBridge } from "@/composer/agent-controls/sheet-bridge";
|
||||
import { draftComposerAgent } from "@/composer/draft/composer-agent";
|
||||
@@ -143,6 +148,7 @@ export interface DraftAgentControlsProps {
|
||||
onSelectMode: (modeId: string) => void;
|
||||
models: AgentModelDefinition[];
|
||||
selectedModel: string;
|
||||
effectiveModelId: string;
|
||||
onSelectModel: (modelId: string) => void;
|
||||
isModelLoading: boolean;
|
||||
modelSelectorProviders: ProviderSelectorProvider[];
|
||||
@@ -173,6 +179,7 @@ export interface DraftAgentControlsProps {
|
||||
}
|
||||
|
||||
interface AgentControlsProps {
|
||||
showToolbar: boolean;
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
onDropdownClose?: () => void;
|
||||
@@ -188,10 +195,10 @@ function AgentControlCommandCenterRegistration({
|
||||
enabled: boolean;
|
||||
controls: AgentControlCommandCenterSource;
|
||||
}) {
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const { isCommandCenterTarget } = useComposerKeyboardScope();
|
||||
useAgentControlCommandCenterActions({
|
||||
sourceId,
|
||||
enabled: enabled && isActiveComposer,
|
||||
enabled: enabled && isCommandCenterTarget,
|
||||
controls,
|
||||
});
|
||||
return null;
|
||||
@@ -583,6 +590,7 @@ function ControlledAgentControls({
|
||||
selectedThinkingOptionId,
|
||||
],
|
||||
);
|
||||
const effortKeys = useEffortCycleShortcut(thinking, disabled);
|
||||
const items = useAgentControlItems({
|
||||
surface: presentation.foldControls ? "sheet" : "toolbar",
|
||||
presentation,
|
||||
@@ -645,6 +653,7 @@ function ControlledAgentControls({
|
||||
provider={provider}
|
||||
selectedModelId={selectedModelId}
|
||||
thinkingItems={items.thinking}
|
||||
effortKeys={effortKeys}
|
||||
featureItems={items.features}
|
||||
onApplyAgentProfile={onApplyAgentProfile}
|
||||
onEditAgentProfiles={onEditAgentProfiles}
|
||||
@@ -677,6 +686,7 @@ function ControlledAgentControls({
|
||||
provider={provider}
|
||||
selectedModelId={selectedModelId}
|
||||
thinkingItems={items.thinking}
|
||||
effortKeys={effortKeys}
|
||||
featureItems={items.features}
|
||||
onApplyAgentProfile={onApplyAgentProfile}
|
||||
onEditAgentProfiles={onEditAgentProfiles}
|
||||
@@ -719,6 +729,7 @@ interface AgentControlsContentProps {
|
||||
provider: string;
|
||||
selectedModelId?: string;
|
||||
thinkingItems: ComposerControlItem[];
|
||||
effortKeys: ReturnType<typeof useShortcutKeys>;
|
||||
featureItems: ComposerControlItem[];
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
@@ -758,6 +769,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
provider,
|
||||
selectedModelId,
|
||||
thinkingItems,
|
||||
effortKeys,
|
||||
featureItems,
|
||||
onApplyAgentProfile,
|
||||
onEditAgentProfiles,
|
||||
@@ -785,6 +797,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
handleCloseSheet,
|
||||
modelSelectorServerId,
|
||||
} = props;
|
||||
const { action: toggleAction, keys: modelKeys } = useModelPickerShortcut(disabled);
|
||||
const modelToolbar = useMemo(
|
||||
() => ({ glyph: glyphs.label, showCaret: presentation.showCarets }),
|
||||
[glyphs, presentation.showCarets],
|
||||
@@ -813,6 +826,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
onEditProfile={onEditAgentProfile}
|
||||
isLoading={isModelLoading}
|
||||
disabled={disabled}
|
||||
toggleAction={toggleAction}
|
||||
onOpen={onModelSelectorOpen}
|
||||
onClose={onDropdownClose}
|
||||
onRetryProvider={onRetryModelProvider}
|
||||
@@ -825,13 +839,17 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
</View>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<Text style={styles.tooltipText}>{t(getAgentControlHintKey("model"))}</Text>
|
||||
<ControlTooltipHint
|
||||
label={t(getAgentControlHintKey("model"))}
|
||||
shortcutKeys={modelKeys}
|
||||
/>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
|
||||
<ComposerControls
|
||||
items={thinkingItems}
|
||||
shortcutKeys={effortKeys}
|
||||
surface="toolbar"
|
||||
disabled={disabled}
|
||||
openId={openSelector}
|
||||
@@ -902,6 +920,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
provider,
|
||||
selectedModelId,
|
||||
thinkingItems,
|
||||
effortKeys,
|
||||
featureItems,
|
||||
onApplyAgentProfile,
|
||||
onEditAgentProfiles,
|
||||
@@ -956,6 +975,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
selectedProvider={provider}
|
||||
selectedModel={selectedModelId ?? ""}
|
||||
thinkingLabel={displayThinking}
|
||||
effortKeys={effortKeys}
|
||||
onSelect={handleSheetModelSelect}
|
||||
profiles={agentProfiles}
|
||||
onApplyProfile={onApplyAgentProfile}
|
||||
@@ -992,6 +1012,7 @@ function useAgentOptionControls(
|
||||
}
|
||||
|
||||
export const AgentControls = memo(function AgentControls({
|
||||
showToolbar,
|
||||
agentId,
|
||||
serverId,
|
||||
onDropdownClose,
|
||||
@@ -1251,37 +1272,44 @@ export const AgentControls = memo(function AgentControls({
|
||||
return (
|
||||
<ComposerModelProvider value={composer}>
|
||||
{commandCenterRegistration}
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={agent.provider}
|
||||
modelSelectorProviders={agentModelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={modelSelection.activeModelId ?? undefined}
|
||||
onSelectModel={handleSelectModel}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
isRetryingModelProvider={snapshotIsRefreshing}
|
||||
onDropdownClose={onDropdownClose}
|
||||
disabled={!client}
|
||||
modeControl={modeControl}
|
||||
modelSelectorServerId={serverId}
|
||||
isCompactLayout={isCompactLayout}
|
||||
/>
|
||||
{showToolbar ? (
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={agent.provider}
|
||||
modelSelectorProviders={agentModelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={modelSelection.activeModelId ?? undefined}
|
||||
onSelectModel={handleSelectModel}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
isRetryingModelProvider={snapshotIsRefreshing}
|
||||
onDropdownClose={onDropdownClose}
|
||||
disabled={!client}
|
||||
modeControl={modeControl}
|
||||
modelSelectorServerId={serverId}
|
||||
isCompactLayout={isCompactLayout}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</ComposerModelProvider>
|
||||
);
|
||||
});
|
||||
|
||||
export function DraftAgentControls({
|
||||
showToolbar,
|
||||
draftId,
|
||||
serverId,
|
||||
providerDefinitions,
|
||||
selectedProvider,
|
||||
modeOptions,
|
||||
@@ -1289,6 +1317,7 @@ export function DraftAgentControls({
|
||||
onSelectMode,
|
||||
models,
|
||||
selectedModel,
|
||||
effectiveModelId,
|
||||
onSelectModel,
|
||||
isModelLoading: _isModelLoading,
|
||||
modelSelectorProviders,
|
||||
@@ -1311,13 +1340,12 @@ export function DraftAgentControls({
|
||||
context = "draft",
|
||||
metadata,
|
||||
onSetMetadata,
|
||||
}: DraftAgentControlsProps) {
|
||||
}: DraftAgentControlsProps & { draftId: string; serverId: string; showToolbar: boolean }) {
|
||||
const mappedThinkingOptions = useMemo<AgentControlOption[]>(() => {
|
||||
return toThinkingControlOptions(thinkingOptions);
|
||||
}, [thinkingOptions]);
|
||||
|
||||
const effectiveSelectedThinkingOption =
|
||||
selectedThinkingOptionId || mappedThinkingOptions[0]?.id || undefined;
|
||||
const effectiveSelectedThinkingOption = selectedThinkingOptionId || mappedThinkingOptions[0]?.id;
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(
|
||||
() =>
|
||||
@@ -1420,36 +1448,83 @@ export function DraftAgentControls({
|
||||
[composerAgent, composerInput],
|
||||
);
|
||||
|
||||
const commandCenterControls = useMemo<AgentControlCommandCenterSource>(
|
||||
() => ({
|
||||
serverId,
|
||||
ownerKey: draftId,
|
||||
provider: selectedProvider,
|
||||
providerDefinitions,
|
||||
models: {
|
||||
providers: modelSelectorProviders,
|
||||
selectedProvider,
|
||||
selectedModelId: effectiveModelId,
|
||||
select: (provider, modelId) => {
|
||||
onSelectProviderAndModel(provider, modelId);
|
||||
},
|
||||
},
|
||||
thinking: {
|
||||
options: thinkingOptions,
|
||||
selectedId: selectedThinkingOptionId,
|
||||
select: onSelectThinkingOption,
|
||||
},
|
||||
modes: toCommandCenterModes(modeControl),
|
||||
optionControls: optionControls ?? null,
|
||||
}),
|
||||
[
|
||||
serverId,
|
||||
draftId,
|
||||
selectedProvider,
|
||||
providerDefinitions,
|
||||
modelSelectorProviders,
|
||||
effectiveModelId,
|
||||
onSelectProviderAndModel,
|
||||
thinkingOptions,
|
||||
selectedThinkingOptionId,
|
||||
onSelectThinkingOption,
|
||||
modeControl,
|
||||
optionControls,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<ComposerAgentProvider value={composerAgent}>
|
||||
<ComposerModelProvider value={composerModel}>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={selectedProvider ?? ""}
|
||||
modelSelectorProviders={modelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={selectedModel}
|
||||
onSelectModel={onSelectModel}
|
||||
onSelectProviderAndModel={onSelectProviderAndModel}
|
||||
isModelLoading={isAllModelsLoading}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={mappedThinkingOptions.length > 0 ? mappedThinkingOptions : undefined}
|
||||
selectedThinkingOptionId={effectiveSelectedThinkingOption}
|
||||
onSelectThinkingOption={onSelectThinkingOption}
|
||||
optionControls={optionControls}
|
||||
onDropdownClose={onDropdownClose}
|
||||
onModelSelectorOpen={onModelSelectorOpen}
|
||||
onRetryModelProvider={onRetryModelProvider}
|
||||
isRetryingModelProvider={isRetryingModelProvider}
|
||||
disabled={disabled}
|
||||
modeControl={modeControl}
|
||||
modelSelectorServerId={modelSelectorServerId}
|
||||
isCompactLayout={isCompactLayout}
|
||||
<AgentControlCommandCenterRegistration
|
||||
sourceId={`draft:${serverId}:${draftId}`}
|
||||
enabled={!disabled}
|
||||
controls={commandCenterControls}
|
||||
/>
|
||||
{showToolbar ? (
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={selectedProvider ?? ""}
|
||||
modelSelectorProviders={modelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={selectedModel}
|
||||
onSelectModel={onSelectModel}
|
||||
onSelectProviderAndModel={onSelectProviderAndModel}
|
||||
isModelLoading={isAllModelsLoading}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={mappedThinkingOptions.length > 0 ? mappedThinkingOptions : undefined}
|
||||
selectedThinkingOptionId={effectiveSelectedThinkingOption}
|
||||
onSelectThinkingOption={onSelectThinkingOption}
|
||||
optionControls={optionControls}
|
||||
onDropdownClose={onDropdownClose}
|
||||
onModelSelectorOpen={onModelSelectorOpen}
|
||||
onRetryModelProvider={onRetryModelProvider}
|
||||
isRetryingModelProvider={isRetryingModelProvider}
|
||||
disabled={disabled}
|
||||
modeControl={modeControl}
|
||||
modelSelectorServerId={modelSelectorServerId}
|
||||
isCompactLayout={isCompactLayout}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</ComposerModelProvider>
|
||||
</ComposerAgentProvider>
|
||||
);
|
||||
@@ -1479,11 +1554,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: "transparent",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
tooltipText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: theme.fontSize.base * 1.4,
|
||||
},
|
||||
combinedSheetControls: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
|
||||
@@ -25,6 +25,7 @@ describe("resolveAgentControlsMode", () => {
|
||||
onSelectMode: () => undefined,
|
||||
models: [],
|
||||
selectedModel: "",
|
||||
effectiveModelId: "",
|
||||
onSelectModel: () => true,
|
||||
isModelLoading: false,
|
||||
modelSelectorProviders: [],
|
||||
|
||||
@@ -8,12 +8,18 @@ export function resolveNextAgentModeId({
|
||||
modeOptions: readonly AgentMode[];
|
||||
selectedMode: string | null | undefined;
|
||||
}): string | null {
|
||||
if (modeOptions.length < 2) return null;
|
||||
return resolveNextChoiceId(modeOptions, selectedMode);
|
||||
}
|
||||
|
||||
const selectedIndex = modeOptions.findIndex((mode) => mode.id === selectedMode);
|
||||
export function resolveNextChoiceId(
|
||||
options: readonly { id: string }[],
|
||||
selectedId: string | null | undefined,
|
||||
): string | null {
|
||||
if (options.length < 2) return null;
|
||||
|
||||
const selectedIndex = options.findIndex((option) => option.id === selectedId);
|
||||
const currentIndex = selectedIndex >= 0 ? selectedIndex : 0;
|
||||
const nextIndex = (currentIndex + 1) % modeOptions.length;
|
||||
return modeOptions[nextIndex]?.id ?? null;
|
||||
return options[(currentIndex + 1) % options.length].id;
|
||||
}
|
||||
|
||||
export function resolveAgentControlsMode(agentControls?: DraftAgentControlsProps) {
|
||||
|
||||
@@ -31,7 +31,12 @@ import {
|
||||
toolbarSlot,
|
||||
type ToolbarGlyphs,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { shortModelLabel } from "./utils";
|
||||
import { getAgentControlHintKey, shortModelLabel } from "./utils";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardToggle } from "@/hooks/use-keyboard-toggle";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { ControlTooltipHint } from "./composer-control";
|
||||
import { useModelPickerShortcut } from "./control-items";
|
||||
|
||||
const SNAP_POINTS = ["80%", "90%"];
|
||||
const MODEL_LIST_TOP_INSET = 4;
|
||||
@@ -45,6 +50,7 @@ interface CompactModelSheetProps {
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
thinkingLabel: string | null;
|
||||
effortKeys: ReturnType<typeof useShortcutKeys>;
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
isLoading: boolean;
|
||||
profiles?: AgentProfilePicker | null;
|
||||
@@ -133,6 +139,7 @@ export function CompactModelSheet({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
thinkingLabel,
|
||||
effortKeys,
|
||||
onSelect,
|
||||
isLoading,
|
||||
profiles = null,
|
||||
@@ -316,11 +323,13 @@ export function CompactModelSheet({
|
||||
glyphs={glyphs}
|
||||
iconOnly={!showLabels && hasSelectedProvider}
|
||||
isOpen={isOpen}
|
||||
searchFocused={rootBrowser.isSearchFocused || modelBrowser.isSearchFocused}
|
||||
disabled={disabled}
|
||||
onPress={toggle}
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
model: rootBrowser.selectedModelLabel,
|
||||
})}
|
||||
effortKeys={effortKeys}
|
||||
/>
|
||||
|
||||
<AdaptiveModalSheet
|
||||
@@ -409,17 +418,7 @@ export function CompactModelSheet({
|
||||
* The folded model control in the toolbar: the provider glyph, then the model and thinking
|
||||
* labels for as long as they fit.
|
||||
*/
|
||||
function ModelSheetTrigger({
|
||||
ModelIcon,
|
||||
modelLabel,
|
||||
thinkingLabel,
|
||||
glyphs,
|
||||
iconOnly,
|
||||
isOpen,
|
||||
disabled,
|
||||
onPress,
|
||||
accessibilityLabel,
|
||||
}: {
|
||||
interface ModelSheetTriggerProps {
|
||||
/** The selected provider's glyph, or null before a provider is selected. */
|
||||
ModelIcon: ReturnType<typeof useProviderIcon> | null;
|
||||
modelLabel: string;
|
||||
@@ -427,10 +426,36 @@ function ModelSheetTrigger({
|
||||
glyphs: ToolbarGlyphs;
|
||||
iconOnly: boolean;
|
||||
isOpen: boolean;
|
||||
searchFocused: boolean;
|
||||
disabled: boolean;
|
||||
onPress: () => void;
|
||||
accessibilityLabel: string;
|
||||
}) {
|
||||
effortKeys: ReturnType<typeof useShortcutKeys>;
|
||||
}
|
||||
|
||||
function ModelSheetTrigger({
|
||||
ModelIcon,
|
||||
modelLabel,
|
||||
thinkingLabel,
|
||||
glyphs,
|
||||
iconOnly,
|
||||
isOpen,
|
||||
searchFocused,
|
||||
disabled,
|
||||
onPress,
|
||||
accessibilityLabel,
|
||||
effortKeys,
|
||||
}: ModelSheetTriggerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { action: toggleAction, keys: modelKeys } = useModelPickerShortcut(disabled);
|
||||
useKeyboardToggle({
|
||||
action: toggleAction,
|
||||
disabled,
|
||||
open: isOpen,
|
||||
searchFocused,
|
||||
onToggle: onPress,
|
||||
});
|
||||
|
||||
const glyphRole = iconOnly ? "icon" : "label";
|
||||
const glyph = glyphs[glyphRole];
|
||||
const triggerLabels = useModelTriggerLabels({
|
||||
@@ -451,7 +476,7 @@ function ModelSheetTrigger({
|
||||
[disabled, iconOnly, isOpen],
|
||||
);
|
||||
|
||||
return (
|
||||
const trigger = (
|
||||
<View style={styles.triggerFrame} onLayout={triggerLabels.onFrameLayout}>
|
||||
<ComboboxTrigger
|
||||
collapsable={false}
|
||||
@@ -521,6 +546,23 @@ function ModelSheetTrigger({
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild triggerRefProp="ref">
|
||||
{trigger}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<ControlTooltipHint label={t(getAgentControlHintKey("model"))} shortcutKeys={modelKeys} />
|
||||
{effortKeys ? (
|
||||
<ControlTooltipHint
|
||||
label={t("settings.shortcuts.help.cycleEffort")}
|
||||
shortcutKeys={effortKeys}
|
||||
/>
|
||||
) : null}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
|
||||
@@ -20,6 +20,7 @@ describe("feature metadata helpers", () => {
|
||||
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
|
||||
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
|
||||
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
|
||||
expect(getFeatureHighlightColor("ultracode")).toBe("purple");
|
||||
expect(getFeatureHighlightColor("other")).toBe("default");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "@/agent-controls/policy";
|
||||
|
||||
export type ExplainedAgentControl = "mode" | "model" | "thinking";
|
||||
export type FeatureHighlightColor = "blue" | "default" | "green" | "yellow";
|
||||
export type FeatureHighlightColor = "blue" | "default" | "green" | "purple" | "yellow";
|
||||
export type AgentControlHintKey =
|
||||
| "agentControls.hints.thinking"
|
||||
| "agentControls.hints.model"
|
||||
@@ -48,6 +48,8 @@ export function getFeatureHighlightColor(featureId: string): FeatureHighlightCol
|
||||
return "yellow";
|
||||
case "auto_accept":
|
||||
return "green";
|
||||
case "ultracode":
|
||||
return "purple";
|
||||
case PLAN_MODE_FEATURE_ID:
|
||||
return "blue";
|
||||
default:
|
||||
|
||||
@@ -21,6 +21,7 @@ export function resolveDraftKey(input: {
|
||||
|
||||
export function buildDraftAgentControls(input: {
|
||||
formState: UseAgentFormStateResult;
|
||||
effectiveModelId: string;
|
||||
optionControls?: DraftAgentControlsProps["optionControls"];
|
||||
options: DraftAgentControlsProps["options"];
|
||||
onSetOption: DraftAgentControlsProps["onSetOption"];
|
||||
@@ -49,6 +50,7 @@ export function buildDraftAgentControls(input: {
|
||||
onSelectMode: formState.setModeFromUser,
|
||||
models: formState.availableModels,
|
||||
selectedModel: formState.selectedModel,
|
||||
effectiveModelId: input.effectiveModelId,
|
||||
onSelectModel: formState.setModelFromUser,
|
||||
isModelLoading: formState.isModelLoading,
|
||||
modelSelectorProviders: formState.modelSelectorProviders,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
resolveEffectiveComposerThinkingOptionId,
|
||||
type ProviderSelectionState,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
|
||||
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
|
||||
import { AfterPaintPublication } from "@/composer/after-paint-publication";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
@@ -293,6 +294,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
options: draftOptions,
|
||||
shownOptions: draftShownOptions,
|
||||
setOption: setDraftOption,
|
||||
retainLegacyUltracode,
|
||||
applyProfile: applyProfileOptions,
|
||||
} = useDraftProviderOptions({
|
||||
serverId: formState.selectedServerId,
|
||||
@@ -312,6 +314,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
},
|
||||
[applyProfileOptions, formState],
|
||||
);
|
||||
const setDraftThinking = useCallback(
|
||||
(thinkingOptionId: string) =>
|
||||
formState.setThinkingOptionFromUser(thinkingOptionId, retainLegacyUltracode()),
|
||||
[formState, retainLegacyUltracode],
|
||||
);
|
||||
|
||||
const commandDraft = useMemo(
|
||||
() =>
|
||||
@@ -330,8 +337,18 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
|
||||
const draftForm = {
|
||||
...formState,
|
||||
selectedThinkingOptionId:
|
||||
findThinkingOptionReplacement(
|
||||
formState.availableThinkingOptions,
|
||||
formState.selectedThinkingOptionId,
|
||||
) ?? formState.selectedThinkingOptionId,
|
||||
setThinkingOptionFromUser: setDraftThinking,
|
||||
};
|
||||
return {
|
||||
...draftForm,
|
||||
workingDir,
|
||||
effectiveModeId,
|
||||
effectiveModelId,
|
||||
@@ -339,7 +356,8 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
providerOptions: draftOptions,
|
||||
metadata,
|
||||
agentControls: buildDraftAgentControls({
|
||||
formState,
|
||||
formState: draftForm,
|
||||
effectiveModelId,
|
||||
optionControls: draftOptionControls,
|
||||
options: draftShownOptions,
|
||||
onSetOption: setDraftOption,
|
||||
@@ -360,6 +378,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
draftOptions,
|
||||
draftShownOptions,
|
||||
setDraftOption,
|
||||
setDraftThinking,
|
||||
applyDraftAgentProfile,
|
||||
formState,
|
||||
metadata,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user