mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 14:25:25 +00:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ee30f4164 | ||
|
|
ac54c07639 | ||
|
|
46bd5d8a3e | ||
|
|
9895e0c957 | ||
|
|
2e9921e0e0 | ||
|
|
b1a2a50d50 | ||
|
|
9493a4f436 | ||
|
|
a87bd7fc0c | ||
|
|
527be52f2b | ||
|
|
fa6c50063e | ||
|
|
d364dbecb5 | ||
|
|
8edd1f407d | ||
|
|
f284e9abe5 | ||
|
|
c5bfe79c33 | ||
|
|
8d66a7c52e | ||
|
|
7a5b8e68e3 | ||
|
|
d577594173 | ||
|
|
293fbf825d | ||
|
|
c09a3d81e7 | ||
|
|
8c91adeba8 | ||
|
|
0a8b7a6a1e | ||
|
|
18192dc48b | ||
|
|
162745d8e6 | ||
|
|
937a610006 | ||
|
|
2269c8a010 | ||
|
|
e0847ac82f | ||
|
|
9ba2950132 | ||
|
|
fbb7a2c094 | ||
|
|
4437186c49 | ||
|
|
4bba288c10 | ||
|
|
c48d1c1700 | ||
|
|
db3cfadc6c | ||
|
|
c54bc39e79 | ||
|
|
228e6f75ea |
+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,7 +44,6 @@
|
||||
- **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))
|
||||
@@ -37,6 +57,7 @@
|
||||
- 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,7 +44,6 @@
|
||||
- **插件侧边栏视图**:插件可以用自己的布局替换侧边栏,展示已连接主机上的工作区和 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))
|
||||
@@ -37,6 +57,7 @@
|
||||
- 为 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,12 +91,8 @@ 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/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.
|
||||
- [Antigravity](https://paseo.sh/docs/supported-providers#antigravity)
|
||||
- [Muse Code](https://paseo.sh/docs/muse-code)
|
||||
|
||||
### Desktop app (recommended)
|
||||
|
||||
|
||||
@@ -150,13 +150,12 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches.
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches.
|
||||
|
||||
The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt
|
||||
crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
|
||||
admission within their original timeout and cancellation scope, and return permission checkpoints
|
||||
while messages are waiting.
|
||||
admission within their original timeout and cancellation scope.
|
||||
|
||||
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
|
||||
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
|
||||
|
||||
@@ -121,14 +121,6 @@ from `packages/app/android`:
|
||||
|
||||
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
|
||||
|
||||
Run the display density regression tests the same way:
|
||||
|
||||
```bash
|
||||
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
|
||||
|
||||
### Diagnostic logs without ADB
|
||||
|
||||
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
|
||||
|
||||
@@ -117,10 +117,7 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov
|
||||
Screenshot capture temporarily enables frame production inside the shared serialized queue,
|
||||
restores the previous throttling policy on success or failure, and retains a 5-second capture budget.
|
||||
The browser tool takes one viewport frame through Electron's frame subscription and releases the
|
||||
subscription on completion or cancellation. Guest pages have a transparent base background, so a page
|
||||
that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where
|
||||
every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame`
|
||||
when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels
|
||||
subscription on completion or cancellation. A resized resident guest can produce fresh pixels
|
||||
while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or
|
||||
retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout
|
||||
metrics and screenshot clip.
|
||||
|
||||
@@ -99,10 +99,8 @@ Register the adapter in `defaultForgeRegistry` with:
|
||||
|
||||
Current change-request lookup matches the branch and repository for both open and
|
||||
terminal requests. Prefer an open request, then a terminal request at the local
|
||||
HEAD, then the most recently updated terminal request. When the forge identifies
|
||||
the checkout's branch as the origin repository's default branch, only open
|
||||
requests are eligible. A reused feature branch can show its previous request
|
||||
until a new one opens. Auto-archive separately requires an
|
||||
HEAD, then the most recently updated terminal request. A reused branch can show
|
||||
its previous request until a new one opens. Auto-archive separately requires an
|
||||
observed open-to-merged transition and a fresh exact match between checkout HEAD
|
||||
and the PR head, along with the existing workspace safety checks.
|
||||
|
||||
|
||||
@@ -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. 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -49,21 +49,6 @@ restarting the process. It writes snapshots and native failure state under
|
||||
production package. This needs a native rebuild when the Unistyles patch changes; a Metro
|
||||
reload cannot update it.
|
||||
|
||||
To check the first Android composer tap after pinch-to-zoom, install the rebuilt
|
||||
APK and connect it to a chat whose latest assistant message contains a visible
|
||||
Markdown image. For example, put `picture.png` in the agent workspace and have
|
||||
the assistant reply with ``. Set `CHAT_URL` to the
|
||||
chat's Paseo deep link and run from the repository root:
|
||||
|
||||
```bash
|
||||
agent-device test packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad \
|
||||
--platform android --serial emulator-5554 -e APP_ID=sh.paseo -e "CHAT_URL=$CHAT_URL"
|
||||
```
|
||||
|
||||
Use `APP_ID=sh.paseo.debug` for a development build. If the image has different
|
||||
alt text, pass it with `-e IMAGE_LABEL="..."`. The test pinches the image, closes
|
||||
it, types in the composer, and checks that a single Attach tap opens Upload file.
|
||||
|
||||
For Android keyboard continuity, run the current checkout in the app, open an idle terminal
|
||||
with an empty prompt, hide its keyboard, and run:
|
||||
|
||||
|
||||
+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/supported-providers/muse-code.md) for setup, per-agent options, and version limitations.
|
||||
[Muse Code](../public-docs/muse-code.md) for setup, per-agent options, and version limitations.
|
||||
|
||||
## Install from a registry
|
||||
|
||||
|
||||
+2
-2
@@ -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/antigravity.md) |
|
||||
| Muse Code | MSP over one `muse serve` host per session | [Muse Code](../public-docs/supported-providers/muse-code.md) |
|
||||
| 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) |
|
||||
|
||||
## Provider-native session options
|
||||
|
||||
|
||||
+3
-11
@@ -49,17 +49,9 @@ Large unbounded timeline responses can exceed relay frame limits, so catch-up us
|
||||
|
||||
Page limits are projected-item targets. A tool call lifecycle is one projected item even if it spans many source sequence numbers, and assistant/reasoning chunks are merged before counting. The response carries `seqStart`, `seqEnd`, `sourceSeqRanges`, and `collapsed` so clients can advance sequence cursors without rendering delta rows.
|
||||
|
||||
When live delivery detects a sequence gap, the app fetches `direction: "after"` its end cursor. If
|
||||
the daemon responds with `hasNewer: true`, the app immediately fetches the next page from
|
||||
`endCursor`. Gap recovery is complete only when `hasNewer: false`.
|
||||
|
||||
A chat that was empty when it last caught up has no end cursor to compare a live row against. Such a
|
||||
row starts coverage only if it is the epoch's first row, seq 1. A later row means the chat missed the
|
||||
rows before it, such as a prompt sent while the app was offline, so the app drops it and recovers
|
||||
after seq 0. Coverage started at that later row would make the resume page look already applied, and
|
||||
the chat and its replica cache would keep only the end of the reply. A recovery that waits behind a
|
||||
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
|
||||
row by row and an older cursor repeats rows.
|
||||
When live delivery detects a sequence gap, the app fetches `direction: "after"`. If the daemon
|
||||
responds with `hasNewer: true`, the app immediately fetches the next page from `endCursor`. Gap
|
||||
recovery is complete only when `hasNewer: false`.
|
||||
|
||||
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
|
||||
|
||||
|
||||
@@ -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-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk=
|
||||
|
||||
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": [
|
||||
|
||||
@@ -7,7 +7,6 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
|
||||
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
|
||||
const withPasteInput = require("./plugins/with-paste-input");
|
||||
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
|
||||
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
|
||||
const { getNativeReleaseVersion } = require("./native-release-version");
|
||||
const appVariant = process.env.APP_VARIANT ?? "production";
|
||||
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
|
||||
@@ -147,7 +146,6 @@ export default {
|
||||
"expo-router",
|
||||
withPasteInput,
|
||||
withAndroidScroll,
|
||||
withAndroidDisplayMetrics,
|
||||
[withAndroidAsyncStorageSize, 64],
|
||||
...buildProfile.cameraPlugins,
|
||||
withAndroidOptionalCamera,
|
||||
|
||||
@@ -527,17 +527,7 @@ async function expectHiddenStreamingSubmissionOrderAfterWorkspaceEviction(
|
||||
expect(gate.getClientRequestCount("agent.timeline.set_subscription.request")).toBe(
|
||||
subscriptionRequests,
|
||||
);
|
||||
const requestsBeforeRelease = rememberTimelineRequestCounts(gate, target.agentId);
|
||||
gate.releaseHeldAgentStreamEvent("turn_started");
|
||||
// The chat never saw the hidden prompt's live row, so the reply's first row is a gap.
|
||||
// The chat recovers the missing rows once, while its workspace is still evicted.
|
||||
await expect
|
||||
.poll(() => gate.getTimelineRequestCount("after", target.agentId))
|
||||
.toBe(requestsBeforeRelease.after + 1);
|
||||
await gate.waitForServerMessage(
|
||||
"fetch_agent_timeline_response",
|
||||
gate.getClientRequestCount("fetch_agent_timeline_request"),
|
||||
);
|
||||
const requestsBeforeReturn = rememberTimelineRequestCounts(gate, target.agentId);
|
||||
await waitForWorkspaceInSidebar(page, {
|
||||
serverId: getServerId(),
|
||||
|
||||
@@ -14,8 +14,6 @@ import {
|
||||
answerFreshnessCheck,
|
||||
commitTimelineTurnsWhileDisconnected,
|
||||
disconnectViewedTimeline,
|
||||
expectEmptyChatSynced,
|
||||
expectPromptAndWholeReply,
|
||||
expectResumeAnsweredWithoutFetch,
|
||||
expectResumeOverflowFallsBackToOneTail,
|
||||
hideTabAndReturn,
|
||||
@@ -24,11 +22,7 @@ import {
|
||||
restoreUnchangedViewedTimeline,
|
||||
restoreViewedTimelineHoldingCatchUp,
|
||||
restoreViewedTimelineWithHeldResponse,
|
||||
restoreViewedTimelineWithLiveRowsFirst,
|
||||
reopenWithFreshnessCheckUnanswered,
|
||||
seedStreamingReplyAgent,
|
||||
sendPromptWhileDisconnected,
|
||||
stopStreamingReply,
|
||||
waitForResumeAnswer,
|
||||
reopenAppWatchingForUpdatingToast,
|
||||
watchForUpdatingToast,
|
||||
@@ -153,27 +147,4 @@ test.describe("Agent timeline resume", () => {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("an empty chat that reconnects mid-reply keeps the prompt and the whole reply", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const agent = await seedStreamingReplyAgent();
|
||||
try {
|
||||
await openAgentTimeline(page, agent);
|
||||
await expectEmptyChatSynced(page, gate);
|
||||
await disconnectViewedTimeline(page, gate);
|
||||
await sendPromptWhileDisconnected(agent);
|
||||
await restoreViewedTimelineWithLiveRowsFirst(gate);
|
||||
const reply = await stopStreamingReply(agent);
|
||||
await expectPromptAndWholeReply(page, agent, reply);
|
||||
|
||||
await page.reload();
|
||||
await expectPromptAndWholeReply(page, agent, reply);
|
||||
} finally {
|
||||
gate.restore();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -72,12 +72,14 @@ const ASSISTANT_MARKDOWN = [
|
||||
"| Current \\| active | ~~obsolete~~ | ready |",
|
||||
].join("\n");
|
||||
|
||||
// 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(
|
||||
const EXPECTED_WHOLE_SELECTION_MARKDOWN = 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>",
|
||||
@@ -420,7 +422,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_TEXT);
|
||||
expect(clipboard.plainText).toBe(EXPECTED_WHOLE_SELECTION_MARKDOWN);
|
||||
expect(clipboard.html).not.toContain("<ul>");
|
||||
expect(clipboard.html).not.toContain("<li>");
|
||||
expect(clipboard.html).toContain("<div>- ");
|
||||
@@ -686,77 +688,6 @@ 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,
|
||||
|
||||
@@ -2,16 +2,10 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { expect, test as base, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
|
||||
async function openExample(page: Page, example: string) {
|
||||
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
|
||||
const title = page.getByText(`Modal example: ${example}`, { exact: true });
|
||||
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
|
||||
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
|
||||
// two equal reads during the hold would otherwise count as settled.
|
||||
await expect(title).toBeInViewport();
|
||||
await waitForSettledPosition(title);
|
||||
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function closeExample(page: Page) {
|
||||
|
||||
@@ -208,35 +208,6 @@ test.describe("Plugin sidebar items", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 480 });
|
||||
await gotoAppShell(page);
|
||||
await expect(botRow(page, "status")).toBeAttached();
|
||||
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
|
||||
await expect(workspace).toBeInViewport({ ratio: 1 });
|
||||
await expect(botRow(page, "status")).not.toBeInViewport();
|
||||
|
||||
await test.step("navigation stays within half the sidebar", async () => {
|
||||
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
|
||||
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
|
||||
});
|
||||
|
||||
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
|
||||
const before = await boxOf(workspace);
|
||||
await visibleTestId(page, "sidebar-global-new-workspace").hover();
|
||||
await page.mouse.wheel(0, 800);
|
||||
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
|
||||
await expect(workspace).toBeInViewport({ ratio: 1 });
|
||||
expect((await boxOf(workspace)).y).toBe(before.y);
|
||||
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
|
||||
await botRow(page, "status").click();
|
||||
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
|
||||
});
|
||||
});
|
||||
|
||||
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
@@ -362,16 +333,6 @@ test.describe("Plugin sidebar items", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a plugin screen reads workspaces through the state hooks", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
|
||||
await runCommand(page, "Open plugin workspaces");
|
||||
await expect(screenTitle(page)).toHaveText("Workspaces");
|
||||
await expect(page.getByText(`Workspace ${workspaceId}`, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -110,7 +110,6 @@ test.describe("Sidebar items in Appearance settings", () => {
|
||||
|
||||
await test.step("the sidebar starts in the default order", async () => {
|
||||
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
|
||||
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("the Sidebar section lists every item in the same order", async () => {
|
||||
@@ -196,9 +195,6 @@ test.describe("Sidebar items in Appearance settings", () => {
|
||||
await expectSidebarItemHidden(page, "history");
|
||||
await expectSidebarItemHidden(page, "search");
|
||||
await expectSidebarItemHidden(page, "schedules");
|
||||
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
|
||||
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
|
||||
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -705,7 +705,7 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous
|
||||
});
|
||||
const schedules = agent.client as unknown as Pick<
|
||||
DaemonClient,
|
||||
"scheduleCreate" | "scheduleRunOnce" | "scheduleDelete" | "scheduleList"
|
||||
"scheduleCreate" | "scheduleRunOnce" | "scheduleDelete"
|
||||
>;
|
||||
let scheduleId: string | undefined;
|
||||
try {
|
||||
@@ -743,18 +743,7 @@ test("a scheduled heartbeat opens a separate turn without reopening the previous
|
||||
await expect(summaries).toHaveCount(2);
|
||||
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
|
||||
await expect(page.getByRole("button", { name: /^Worked for/ })).toHaveCount(2);
|
||||
const tasks = page.getByRole("button", { name: "1 background task", exact: true });
|
||||
await expect(page.getByTestId("workspace-status-indicator-running").first()).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Stop agent", exact: true })).toHaveCount(0);
|
||||
await tasks.click();
|
||||
const panel = page.getByTestId("background-work-panel");
|
||||
await expect(panel).toContainText("Heartbeat");
|
||||
await panel.getByRole("button", { name: "Stop Check the completed work" }).click();
|
||||
await expect(tasks).toHaveCount(0);
|
||||
await expect(page.getByTestId("workspace-status-indicator-running")).toHaveCount(0);
|
||||
const remaining = await schedules.scheduleList();
|
||||
expect(remaining.error).toBeNull();
|
||||
expect(remaining.schedules.map((schedule) => schedule.id)).not.toContain(scheduleId);
|
||||
await page.screenshot({ path: "/tmp/heartbeat-turn-footer.png" });
|
||||
} finally {
|
||||
if (scheduleId) await schedules.scheduleDelete({ id: scheduleId });
|
||||
await agent.cleanup();
|
||||
|
||||
@@ -23,8 +23,6 @@ import {
|
||||
outlastUndoWindow,
|
||||
pressArchiveShortcut,
|
||||
pressUndoShortcut,
|
||||
readSidebarListLayout,
|
||||
recordLastRowBottomPerFrame,
|
||||
resizeSidebarToMinimum,
|
||||
rowArchiveButton,
|
||||
rowKebab,
|
||||
@@ -123,7 +121,7 @@ test.describe("Workspace archive undo", () => {
|
||||
expect(shortcutBox.x - (labelBox.x + labelBox.width)).toBeLessThanOrEqual(8.5);
|
||||
});
|
||||
|
||||
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
|
||||
test("a long list ends just below its last row, and the toast over it moves no row", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.clock.install({ time: Date.now() });
|
||||
@@ -138,35 +136,18 @@ test.describe("Workspace archive undo", () => {
|
||||
const worktree = await seedWorktree(page, "archive-toast-long-list");
|
||||
|
||||
const resting = await scrollSidebarListToEnd(page);
|
||||
const restingEndGap = resting.listBottom - resting.rowBottoms.at(-1)!;
|
||||
expect(restingEndGap).toBeLessThan(resting.rowHeight);
|
||||
expect(resting.listBottom - resting.rowBottoms.at(-1)!).toBeLessThan(resting.rowHeight);
|
||||
|
||||
await archiveFromRowButton(page, worktree.workspaceId);
|
||||
await page.mouse.move(0, 0);
|
||||
const withToast = await scrollSidebarListToEnd(page);
|
||||
const toastBox = await archivedToast(page).boundingBox();
|
||||
if (!toastBox) throw new Error("Toast is not laid out");
|
||||
// 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));
|
||||
expect(toastBox.y + toastBox.height).toBeLessThanOrEqual(withToast.listBottom);
|
||||
|
||||
const frames = recordLastRowBottomPerFrame(page, 40);
|
||||
await outlastUndoWindow(page);
|
||||
const bottoms = await frames;
|
||||
await expect(archivedToast(page)).toHaveCount(0);
|
||||
|
||||
// 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);
|
||||
expect(await scrollSidebarListToEnd(page)).toEqual(withToast);
|
||||
} finally {
|
||||
for (const projectId of fillerProjectIds) {
|
||||
await client.removeProject(projectId).catch(() => undefined);
|
||||
|
||||
@@ -3,7 +3,6 @@ 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 {
|
||||
@@ -74,36 +73,35 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
|
||||
return page.getByTestId(`workspace-label-picker-row-${name}`);
|
||||
}
|
||||
|
||||
async function box(locator: import("@playwright/test").Locator) {
|
||||
const measured = await locator.boundingBox();
|
||||
if (!measured) throw new Error("expected a visible element to measure");
|
||||
return measured;
|
||||
}
|
||||
|
||||
async function size(locator: import("@playwright/test").Locator) {
|
||||
const { width, height } = await settled(locator);
|
||||
await settled(locator);
|
||||
const { width, height } = await box(locator);
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until an element is on screen and stops moving, and returns where it settled.
|
||||
* Waits until an element stops moving.
|
||||
*
|
||||
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
|
||||
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
|
||||
* would take its two halves from two different frames. A row that has not been laid out yet has
|
||||
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
|
||||
* would take its two halves from two different frames.
|
||||
*/
|
||||
async function settled(locator: import("@playwright/test").Locator) {
|
||||
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
|
||||
box: null,
|
||||
key: null,
|
||||
};
|
||||
let previous = "";
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const current = await locator.boundingBox();
|
||||
const key = current ? JSON.stringify(current) : null;
|
||||
const stable = key !== null && key === last.key;
|
||||
last.box = current;
|
||||
last.key = key;
|
||||
const current = JSON.stringify(await box(locator));
|
||||
const stable = current === previous;
|
||||
previous = current;
|
||||
return stable;
|
||||
})
|
||||
.toBe(true);
|
||||
if (!last.box) throw new Error("a settled element has a box");
|
||||
return last.box;
|
||||
}
|
||||
|
||||
async function expectAssigned(
|
||||
@@ -115,7 +113,11 @@ async function expectAssigned(
|
||||
}
|
||||
|
||||
async function openWorkspaceLabels(page: import("@playwright/test").Page, workspaceId: string) {
|
||||
const serverId = await openWorkspaceSidebarKebab(page, workspaceId);
|
||||
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();
|
||||
await page.getByTestId(`sidebar-workspace-menu-labels-${serverId}:${workspaceId}`).click();
|
||||
await expect(page.getByTestId("workspace-label-picker-create")).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
# CHAT_URL opens a connected chat containing a visible Markdown image with alt text IMAGE_LABEL.
|
||||
context platform=android timeout=120000 retries=0
|
||||
env APP_ID=sh.paseo.debug
|
||||
env IMAGE_LABEL="Test image"
|
||||
|
||||
open "${APP_ID}" "${CHAT_URL}"
|
||||
wait "label=\"${IMAGE_LABEL}\"" 30000
|
||||
press "label=\"${IMAGE_LABEL}\""
|
||||
wait "label=\"Close image\"" 5000
|
||||
gesture pinch 1.7
|
||||
press "label=\"Close image\""
|
||||
press "editable=true"
|
||||
type "pinch regression"
|
||||
press "role=\"button\" label=\"Add attachment\""
|
||||
wait "label=\"Upload file\"" 3000
|
||||
@@ -170,11 +170,6 @@ export interface ModelTriggerLabelState {
|
||||
modelShown: boolean;
|
||||
modelText: string;
|
||||
modelTruncated: boolean;
|
||||
/**
|
||||
* The model label shows what its box fits right now: the full text when it fits, otherwise a
|
||||
* truncation that fits. False while the control has yet to catch up with a reflow.
|
||||
*/
|
||||
modelFitsBox: boolean;
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -199,18 +194,12 @@ function readModelTriggerLabelStateInPage(): ModelTriggerLabelState {
|
||||
};
|
||||
const modelShown = model !== undefined && shown(model);
|
||||
const modelText = model?.textContent ?? "";
|
||||
const overflows = (node: Element) => node.scrollWidth > node.clientWidth;
|
||||
const modelOverflows = model !== undefined && overflows(model);
|
||||
// The label's box is sized by an invisible copy of the full text, its first child, so the box
|
||||
// follows a reflow at once while the shown text waits for the control's next layout event.
|
||||
const fullTextSizer = model?.parentElement?.parentElement?.firstElementChild;
|
||||
const fullTextFits = fullTextSizer ? !overflows(fullTextSizer) : true;
|
||||
return {
|
||||
modelShown,
|
||||
modelText,
|
||||
thinkingShown: modelShown && thinking !== undefined,
|
||||
modelTruncated: modelText.endsWith("…") || modelOverflows,
|
||||
modelFitsBox: !modelOverflows && modelText.endsWith("…") !== fullTextFits,
|
||||
modelTruncated:
|
||||
model !== undefined && (modelText.endsWith("…") || model.scrollWidth > model.clientWidth),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -228,26 +217,13 @@ export async function recordModelTriggerFramesFromLoad(page: Page): Promise<void
|
||||
})()`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The model control's labels once it has caught up with its width: two reads 100ms apart agree
|
||||
* and the model label shows what its box fits. A resize reflows the page at once, but the control
|
||||
* chooses its labels again only when its layout events arrive, and on a slow runner that takes
|
||||
* longer than 100ms. Until then the label can be clipped by the browser beside the thinking
|
||||
* label, or truncated in a box that has since widened.
|
||||
*/
|
||||
/** The model control's labels once two reads 100ms apart agree. */
|
||||
export async function readSettledModelTriggerLabels(page: Page): Promise<ModelTriggerLabelState> {
|
||||
const deadline = Date.now() + 10_000;
|
||||
let previous = await page.evaluate(readModelTriggerLabelStateInPage);
|
||||
for (;;) {
|
||||
await page.waitForTimeout(100);
|
||||
const next = await page.evaluate(readModelTriggerLabelStateInPage);
|
||||
const agrees = JSON.stringify(next) === JSON.stringify(previous);
|
||||
if (agrees && next.modelFitsBox) return next;
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(
|
||||
`the model control never settled on a label that fits its box: ${JSON.stringify(next)}`,
|
||||
);
|
||||
}
|
||||
if (JSON.stringify(next) === JSON.stringify(previous)) return next;
|
||||
previous = next;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type ChildProcess,
|
||||
type SpawnOptions,
|
||||
} from "node:child_process";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -59,17 +59,7 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* it in between also accepts connections while the daemon exits with
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||
*/
|
||||
async function waitForServer(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
): Promise<void> {
|
||||
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
|
||||
@@ -80,13 +70,22 @@ async function waitForServer(
|
||||
);
|
||||
}
|
||||
try {
|
||||
const serverId = await readServerId(port, identity.paseoHome);
|
||||
if (serverId === identity.serverId) return;
|
||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const socket = net.connect(port, "127.0.0.1", () => {
|
||||
socket.end();
|
||||
resolve();
|
||||
});
|
||||
socket.setTimeout(1_000, () => {
|
||||
socket.destroy();
|
||||
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
|
||||
});
|
||||
socket.on("error", reject);
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
@@ -96,25 +95,6 @@ async function waitForServer(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
* writes into its home before listening, as the CLI does for local status.
|
||||
*/
|
||||
async function readServerId(port: number, paseoHome: string): Promise<string> {
|
||||
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
|
||||
(token) => token.trim(),
|
||||
() => null,
|
||||
);
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
|
||||
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
|
||||
const status = (await response.json()) as { serverId?: unknown };
|
||||
return String(status.serverId);
|
||||
}
|
||||
|
||||
function withMutableRelay(
|
||||
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
|
||||
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
|
||||
@@ -141,7 +121,7 @@ export async function startIsolatedHostDaemon(
|
||||
serverId: string,
|
||||
options: IsolatedHostDaemonOptions = {},
|
||||
): Promise<IsolatedHostDaemon> {
|
||||
let port = await getAvailableHostDaemonPort();
|
||||
const port = await getAvailableHostDaemonPort();
|
||||
|
||||
const metroPort = process.env.E2E_METRO_PORT;
|
||||
if (!metroPort) throw new Error("E2E_METRO_PORT is required to start an isolated host daemon");
|
||||
@@ -241,7 +221,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
await waitForServer(port, spawned);
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
@@ -251,25 +231,8 @@ export async function startIsolatedHostDaemon(
|
||||
}
|
||||
};
|
||||
|
||||
// The reserved port is released before the daemon binds it, so another
|
||||
// process can take it in between. Only the first start picks a new port:
|
||||
// restart() keeps the endpoint the app already knows.
|
||||
const startOnFreePort = async (): Promise<void> => {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
await spawnDaemon();
|
||||
return;
|
||||
} catch (error) {
|
||||
const lostPort = error instanceof Error && error.message.includes("EADDRINUSE");
|
||||
if (!lostPort || attempt === 3) throw error;
|
||||
await stopDaemon();
|
||||
port = await getAvailableHostDaemonPort();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await startOnFreePort();
|
||||
await spawnDaemon();
|
||||
} catch (error) {
|
||||
await stopDaemon();
|
||||
if (!options.preserveHome) {
|
||||
|
||||
@@ -198,14 +198,6 @@ async function expectDetails(page: Page) {
|
||||
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
|
||||
}
|
||||
|
||||
// The details render before the daemon answers their event subscription, and reopened
|
||||
// details show the cached summary at once, so wait for the subscription id to arrive.
|
||||
async function readContentObservation(page: Page): Promise<string> {
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
return (await observation.textContent())!;
|
||||
}
|
||||
|
||||
function workspaceMenuRow(page: Page, title: string): Locator {
|
||||
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
|
||||
}
|
||||
@@ -362,12 +354,14 @@ export async function withButtonShowcase(
|
||||
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const first = await readContentObservation(page);
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
const first = (await observation.textContent())!;
|
||||
await press(page, "Close deployment details");
|
||||
await expect.poll(() => released.has(first)).toBe(true);
|
||||
await press(page, "Composer status");
|
||||
await expectDetails(page);
|
||||
const second = await readContentObservation(page);
|
||||
const second = (await observation.textContent())!;
|
||||
expect(second).not.toBe(first);
|
||||
await workspace.client.renameProject(workspace.projectId, "Observer control");
|
||||
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
|
||||
@@ -379,7 +373,7 @@ export async function withButtonShowcase(
|
||||
await page.keyboard.press("Escape");
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const recovered = await readContentObservation(page);
|
||||
const recovered = (await observation.textContent())!;
|
||||
expect([first, second]).not.toContain(recovered);
|
||||
await showcase.setTitle("Healthy app after button failure");
|
||||
await expect(page.getByTestId("workspace-header-title")).toHaveText(
|
||||
@@ -693,7 +687,9 @@ export async function withButtonShowcase(
|
||||
page,
|
||||
page.getByRole("button", { name: "Close deployment details", exact: true }),
|
||||
);
|
||||
const owner = await readContentObservation(page);
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
const owner = (await observation.textContent())!;
|
||||
await showcase.disable();
|
||||
await expect.poll(() => released.has(owner)).toBe(true);
|
||||
await expect(
|
||||
|
||||
@@ -15,18 +15,8 @@ export const COMPACT = { width: 390, height: 844 };
|
||||
/** A plugin written against the current API: a screen, header and footer items, a command. */
|
||||
const SHOWCASE_SOURCE = `import React from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { useWorkspaces } from "@getpaseo/plugin/client";
|
||||
import { SidebarRow } from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function WorkspacesScreen({ theme }) {
|
||||
const workspaces = useWorkspaces();
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 24, gap: 8 }}>
|
||||
{workspaces.map((ref) => <Text key={ref.id} style={{ color: theme.colors.foreground }}>{"Workspace " + ref.id}</Text>)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DeploysScreen({ theme }) {
|
||||
return <View style={{ flex: 1, padding: 24 }}><Text style={{ color: theme.colors.foreground }}>Deploys screen body</Text></View>;
|
||||
}
|
||||
@@ -73,13 +63,11 @@ function Broken() {
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addScreen({ id: "deploys", title: "Deploys", Component: DeploysScreen });
|
||||
client.addScreen({ id: "workspaces", title: "Workspaces", Component: WorkspacesScreen });
|
||||
client.addSidebarHeaderItem({ id: "deploys", title: "Deploys", Component: DeploysItem });
|
||||
client.addSidebarHeaderItem({ id: "broken", title: "Broken header", Component: Broken });
|
||||
client.addSidebarFooterItem({ id: "sync", title: "Sync", Component: SyncItem });
|
||||
client.addSidebarFooterItem({ id: "broken", title: "Broken footer", Component: Broken });
|
||||
client.addCommandCenterItem({ id: "open-deploys", title: "Open deploys", icon: "Rocket", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "deploys" }) });
|
||||
client.addCommandCenterItem({ id: "open-workspaces", title: "Open plugin workspaces", icon: "List", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "workspaces" }) });
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -190,25 +190,14 @@ export async function selectWorkspaceInSidebar(page: Page, workspaceId: string):
|
||||
await row.click();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
async function openWorkspaceSidebarKebab(page: Page, workspaceId: string) {
|
||||
const serverId = getServerId();
|
||||
const row = page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`);
|
||||
const kebab = page.getByTestId(`sidebar-workspace-kebab-${serverId}:${workspaceId}`);
|
||||
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 row.hover();
|
||||
|
||||
const kebab = page.getByTestId(`sidebar-workspace-kebab-${serverId}:${workspaceId}`);
|
||||
await expect(kebab).toBeVisible({ timeout: 10_000 });
|
||||
await kebab.click();
|
||||
|
||||
return serverId;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import type { installDaemonWebSocketGate } from "./daemon-websocket-gate";
|
||||
import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
import { readReplicaCache } from "./replica-cache-storage";
|
||||
import type { LongTimelineAgent } from "./timeline-pagination";
|
||||
import {
|
||||
@@ -242,100 +241,3 @@ export async function restoreUnchangedViewedTimeline(
|
||||
gate.restore();
|
||||
await expectReconnectingToastGone(page);
|
||||
}
|
||||
|
||||
export interface StreamingReplyAgent extends MockAgentWorkspace {
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A mock agent with no history whose reply streams one word every 100 ms. At 2,000 words the
|
||||
* reply outlasts the test's timeout, so it is still streaming however long the app takes to
|
||||
* reconnect. The test ends the turn with {@link stopStreamingReply}.
|
||||
*/
|
||||
export async function seedStreamingReplyAgent(): Promise<StreamingReplyAgent> {
|
||||
const reply = Array.from({ length: 2_000 }, (_unused, index) => `word${index}`).join(" ");
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "reply-reconnect-",
|
||||
title: "Reply through reconnect",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse: reply,
|
||||
mockStreamingAssistantIntervalMs: 100,
|
||||
},
|
||||
});
|
||||
return {
|
||||
...agent,
|
||||
prompt: "stream through a reconnect",
|
||||
cleanup: async () => {
|
||||
await agent.client.cancelAgent(agent.agentId).catch(() => undefined);
|
||||
await agent.cleanup();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface TimelineReader {
|
||||
fetchAgentTimeline(
|
||||
agentId: string,
|
||||
request: { direction: "tail"; limit: number },
|
||||
): Promise<{ entries: Array<{ item: { type: string; text?: string } }> }>;
|
||||
}
|
||||
|
||||
async function readDaemonReply(agent: StreamingReplyAgent): Promise<string> {
|
||||
const timeline = await (agent.client as unknown as TimelineReader).fetchAgentTimeline(
|
||||
agent.agentId,
|
||||
{ direction: "tail", limit: 0 },
|
||||
);
|
||||
return timeline.entries
|
||||
.map(({ item }) => (item.type === "assistant_message" ? (item.text ?? "") : ""))
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Waits for the empty chat's first catch-up, so the chat is synced with no range. */
|
||||
export async function expectEmptyChatSynced(page: Page, gate: DaemonWebSocketGate): Promise<void> {
|
||||
await gate.waitForServerMessage(TIMELINE_RESPONSE);
|
||||
await expect(page.getByTestId("agent-chat-scroll").filter({ visible: true })).toHaveCount(1, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** Another client sends the prompt, and the reply starts, while the chat is away. */
|
||||
export async function sendPromptWhileDisconnected(agent: StreamingReplyAgent): Promise<void> {
|
||||
await agent.client.sendAgentMessage(agent.agentId, agent.prompt);
|
||||
await expect.poll(() => readDaemonReply(agent), { timeout: 30_000 }).toContain("word10");
|
||||
}
|
||||
|
||||
/** Reconnects with live reply chunks reaching the chat before the catch-up page that holds them. */
|
||||
export async function restoreViewedTimelineWithLiveRowsFirst(
|
||||
gate: DaemonWebSocketGate,
|
||||
): Promise<void> {
|
||||
gate.holdNextClientRequest(TIMELINE_REQUEST);
|
||||
const chunksBeforeReconnect = gate.getAgentStreamItemCount("assistant_message");
|
||||
gate.restore();
|
||||
await gate.waitForHeldClientRequest();
|
||||
await gate.waitForAgentStreamItem("assistant_message", chunksBeforeReconnect + 5);
|
||||
gate.releaseHeldClientRequest();
|
||||
}
|
||||
|
||||
/** Stops the turn and returns the reply as the daemon recorded it. */
|
||||
export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<string> {
|
||||
await agent.client.cancelAgent(agent.agentId);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const reply = (await readDaemonReply(agent)).trim();
|
||||
expect(reply).toMatch(/^word0 word1 word2 .* word10 /);
|
||||
return reply;
|
||||
}
|
||||
|
||||
export async function expectPromptAndWholeReply(
|
||||
page: Page,
|
||||
agent: StreamingReplyAgent,
|
||||
reply: string,
|
||||
): Promise<void> {
|
||||
const chat = page.getByTestId("agent-chat-scroll").filter({ visible: true }).first();
|
||||
await expect(chat.getByText(agent.prompt, { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await chat.getByTestId("assistant-message").allInnerTexts()).map((text) => text.trim()),
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toEqual([reply]);
|
||||
}
|
||||
|
||||
@@ -175,19 +175,13 @@ 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> {
|
||||
await page.getByTestId(SIDEBAR_LIST).evaluate((element) => {
|
||||
const list = page.getByTestId("sidebar-project-workspace-list-scroll");
|
||||
await list.evaluate((element) => {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
});
|
||||
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) => {
|
||||
return list.evaluate((element) => {
|
||||
const visible = element.getBoundingClientRect();
|
||||
const rows = Array.from(
|
||||
element.querySelectorAll<HTMLElement>(
|
||||
@@ -203,26 +197,3 @@ export async function readSidebarListLayout(page: Page): Promise<SidebarListLayo
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
/android/.cxx/
|
||||
/android/build/
|
||||
@@ -1,23 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.displaymetrics'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.displaymetrics"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "com.facebook.react:react-android"
|
||||
androidTestImplementation 'androidx.test:runner:1.6.2'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package sh.paseo.displaymetrics
|
||||
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.TypedValue
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.facebook.react.uimanager.PixelUtil
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PaseoDisplayMetricsTest {
|
||||
private lateinit var display: DisplayMetrics
|
||||
|
||||
@Before
|
||||
fun readDisplayLikeReactNative() {
|
||||
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
|
||||
display = DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
}
|
||||
|
||||
@After
|
||||
fun forgetDisplay() {
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reservesRoomForTextAtTheWindowDensity() {
|
||||
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
|
||||
// reads the font scale from the window but the density from the phone's display.
|
||||
val window = windowAt(display.densityDpi * 2 / 3)
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(
|
||||
DisplayMetrics().apply {
|
||||
setTo(display)
|
||||
scaledDensity = window.scaledDensity
|
||||
},
|
||||
)
|
||||
assertTrue(reservedTextPx(window) < drawnTextPx())
|
||||
|
||||
PaseoDisplayMetrics.syncWithWindow(window)
|
||||
|
||||
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
|
||||
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
|
||||
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
assertEquals(window.densityDpi, synced.densityDpi)
|
||||
assertEquals(display.widthPixels, synced.widthPixels)
|
||||
assertEquals(display.heightPixels, synced.heightPixels)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leavesTheBuiltInDisplayAlone() {
|
||||
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
|
||||
|
||||
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun waitsForReactNativeToReadTheDisplay() {
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(null)
|
||||
|
||||
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
|
||||
|
||||
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
|
||||
}
|
||||
|
||||
private fun windowAt(densityDpi: Int): DisplayMetrics =
|
||||
DisplayMetrics().apply {
|
||||
setTo(display)
|
||||
this.densityDpi = densityDpi
|
||||
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
|
||||
scaledDensity = density * display.scaledDensity / display.density
|
||||
}
|
||||
|
||||
/** A 16sp font as React Native draws it, in pixels. */
|
||||
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
|
||||
|
||||
/** The box React Native lays out for that font, once the window renders it in pixels. */
|
||||
private fun reservedTextPx(window: DisplayMetrics): Float =
|
||||
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package sh.paseo.displaymetrics
|
||||
|
||||
import android.app.Activity
|
||||
import android.util.DisplayMetrics
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
|
||||
/**
|
||||
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
|
||||
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
|
||||
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
|
||||
* DeX monitor, text boxes come out too small and clip their text.
|
||||
*
|
||||
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
|
||||
* window's density and take only the size from the display. Remove once the app runs React Native
|
||||
* 0.89 or later with that flag on.
|
||||
*/
|
||||
object PaseoDisplayMetrics {
|
||||
/** Call right after React Native reads the display, which it does again on each configuration change. */
|
||||
@JvmStatic
|
||||
fun syncWithWindow(activity: Activity) {
|
||||
syncWithWindow(activity.resources.displayMetrics)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun syncWithWindow(window: DisplayMetrics) {
|
||||
val screen =
|
||||
try {
|
||||
DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
} catch (_: IllegalStateException) {
|
||||
// React Native hasn't read the display yet, so there is nothing to correct.
|
||||
return
|
||||
}
|
||||
if (screen.densityDpi == window.densityDpi) return
|
||||
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(
|
||||
DisplayMetrics().apply {
|
||||
setTo(screen)
|
||||
density = window.density
|
||||
densityDpi = window.densityDpi
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
|
||||
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
|
||||
// React Native re-reads the built-in display's density when it creates the root view and on every
|
||||
// configuration change, so the window's density has to be restored right after each `super` call.
|
||||
const OVERRIDES = `
|
||||
override fun onContentChanged() {
|
||||
super.onContentChanged()
|
||||
${SYNC}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
${SYNC}
|
||||
}
|
||||
`;
|
||||
|
||||
function configureDisplayMetricsActivity(contents) {
|
||||
if (contents.includes(SYNC)) return contents;
|
||||
if (
|
||||
!contents.includes(ACTIVITY_CLASS) ||
|
||||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
|
||||
) {
|
||||
throw new Error("Could not keep React Native text at the window's density in MainActivity");
|
||||
}
|
||||
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
|
||||
}
|
||||
|
||||
module.exports = (config) =>
|
||||
withMainActivity(config, (mod) => {
|
||||
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
|
||||
return mod;
|
||||
});
|
||||
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
|
||||
@@ -1,29 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const { configureDisplayMetricsActivity } = require("./app.plugin");
|
||||
|
||||
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
|
||||
|
||||
describe("Android display metrics", () => {
|
||||
it("restores the window's density after React Native reads the display", () => {
|
||||
const source = "class MainActivity : ReactActivity() {\n}";
|
||||
const result = configureDisplayMetricsActivity(source);
|
||||
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
|
||||
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
|
||||
expect(configureDisplayMetricsActivity(result)).toBe(result);
|
||||
});
|
||||
|
||||
it("fails prebuild when the template no longer has a place for the overrides", () => {
|
||||
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
|
||||
"Could not keep React Native text at the window's density",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails prebuild rather than replace another plugin's configuration handler", () => {
|
||||
const source =
|
||||
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
|
||||
expect(() => configureDisplayMetricsActivity(source)).toThrow(
|
||||
"Could not keep React Native text at the window's density",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"platforms": ["android"],
|
||||
"android": {
|
||||
"modules": []
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "paseo-display-metrics",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -851,94 +851,6 @@ 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,
|
||||
createSelectionClipboardContent,
|
||||
createMarkdownClipboardContent,
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
@@ -15,7 +15,6 @@ 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";
|
||||
@@ -57,68 +56,40 @@ function copySemanticAttributes(original: Element, copy: Element): void {
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
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`;
|
||||
},
|
||||
});
|
||||
|
||||
export function createAssistantSelectionClipboardContent(
|
||||
selection: Selection | null,
|
||||
@@ -146,15 +117,11 @@ export function createAssistantSelectionClipboardContent(
|
||||
}
|
||||
restoreMarkdownElements(container);
|
||||
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
const markdown = turndown.turndown(container.innerHTML).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// 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);
|
||||
const content = createMarkdownClipboardContent(markdown);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
@@ -684,15 +651,13 @@ 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
function numberOrderedListItems(list: Element, start: number): void {
|
||||
Array.from(list.children).forEach((child, index) => {
|
||||
|
||||
@@ -2,8 +2,6 @@ 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";
|
||||
|
||||
@@ -10,8 +10,8 @@ import { createHostBackgroundWorkModel } from "./host";
|
||||
import { backgroundWorkText } from "./presentation";
|
||||
export { createHostBackgroundWorkModel } from "./host";
|
||||
|
||||
function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" {
|
||||
if (kind === "shell" || kind === "monitor" || kind === "heartbeat") return kind;
|
||||
function kindKey(kind: string): "shell" | "monitor" | "other" {
|
||||
if (kind === "shell" || kind === "monitor") return kind;
|
||||
return "other";
|
||||
}
|
||||
|
||||
|
||||
@@ -17,13 +17,6 @@ import { isNative } from "@/constants/platform";
|
||||
* On macOS, Electron handles edge resize natively.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marks a scroll viewport as window content: it and its descendants emit no window
|
||||
* regions, because Electron does not clip app-region rects to scroll viewports.
|
||||
* See the `[data-window-content]` rule in public/index.html.
|
||||
*/
|
||||
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
export const titlebarDragSurfaceStyle: React.CSSProperties = {
|
||||
cursor: "default",
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
|
||||
@@ -9,16 +9,7 @@ import {
|
||||
type LucideIcon,
|
||||
} from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
ScrollView,
|
||||
@@ -28,19 +19,12 @@ import {
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
Gesture,
|
||||
type GestureType,
|
||||
ScrollView as GHScrollView,
|
||||
} from "react-native-gesture-handler";
|
||||
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
|
||||
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
TitlebarDragRegion,
|
||||
WINDOW_CONTENT_DATASET,
|
||||
} from "@/components/desktop/titlebar-drag-region";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import {
|
||||
resolveDesktopSidebarInsetLeft,
|
||||
@@ -55,7 +39,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
||||
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
||||
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
||||
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
|
||||
@@ -638,7 +622,29 @@ function MobileSidebar({
|
||||
>
|
||||
<View style={styles.sidebarContent} pointerEvents="auto">
|
||||
<WindowChromeSafeArea placement="below" />
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
|
||||
{platformIsNative ? (
|
||||
<GHScrollView
|
||||
// Same contract as the workspace list: vertical drags scroll the nav
|
||||
// block, a clear horizontal intent still activates the close pan.
|
||||
simultaneousHandlers={closeGestureRef}
|
||||
style={styles.mobileNavScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{navRows}
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
style={styles.mobileNavScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{navRows}
|
||||
</ScrollView>
|
||||
)}
|
||||
<SidebarSeparator />
|
||||
|
||||
<SidebarViewSlot dismiss={handleWorkspacePress}>
|
||||
<SidebarToastRegion active={active}>
|
||||
@@ -683,47 +689,6 @@ function MobileSidebar({
|
||||
);
|
||||
}
|
||||
|
||||
interface SidebarNavScrollProps {
|
||||
closeGestureRef: RefObject<GestureType | undefined>;
|
||||
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
|
||||
windowContent?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
|
||||
// divider below it. The divider is a sibling because Unistyles does not patch the
|
||||
// gesture-handler ScrollView.
|
||||
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
|
||||
return (
|
||||
<>
|
||||
{platformIsNative ? (
|
||||
<GHScrollView
|
||||
// Same contract as the workspace list: vertical drags scroll the nav
|
||||
// block, a clear horizontal intent still activates the close pan.
|
||||
simultaneousHandlers={closeGestureRef}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{children}
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{children}
|
||||
</ScrollView>
|
||||
)}
|
||||
<SidebarSeparator testID="sidebar-nav-separator" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopSidebar({
|
||||
theme,
|
||||
workspaceGroups,
|
||||
@@ -844,14 +809,12 @@ function DesktopSidebar({
|
||||
],
|
||||
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
|
||||
);
|
||||
// Below the window controls' row, or in the top band's place, the first row starts flush.
|
||||
const inTopBand = useTopBand() !== null;
|
||||
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
|
||||
// row there. The strip above the scrolling rows is then its window drag surface.
|
||||
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
|
||||
// With every top item hidden the sidebar starts at the Workspaces section, as before the
|
||||
// nav scroller existed: no strip above it and no divider below it.
|
||||
const hasNavRows = useVisibleSidebarNavItems().length > 0;
|
||||
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
|
||||
const sidebarHeaderGroupStyle = useMemo(
|
||||
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
|
||||
[ownsTopLeft, inTopBand],
|
||||
);
|
||||
return (
|
||||
<MobilePanelOverlay
|
||||
panel="agent-list"
|
||||
@@ -862,7 +825,7 @@ function DesktopSidebar({
|
||||
<Animated.View style={desktopSidebarStyle}>
|
||||
<View style={desktopSidebarBorderStyle}>
|
||||
<View style={styles.sidebarDragArea}>
|
||||
{showsChromeRow ? (
|
||||
{ownsTopLeft || DEV_BUILD_LABEL ? (
|
||||
<View style={styles.desktopChromeRow}>
|
||||
<TitlebarDragRegion />
|
||||
{DEV_BUILD_LABEL ? (
|
||||
@@ -879,21 +842,11 @@ function DesktopSidebar({
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
{showsDragStrip ? (
|
||||
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
|
||||
<TitlebarDragRegion />
|
||||
</View>
|
||||
) : null}
|
||||
) : (
|
||||
<TitlebarDragRegion />
|
||||
)}
|
||||
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
|
||||
</View>
|
||||
{/* The drag overlay stays above this viewport: Electron does not clip
|
||||
app-region rects to scroll viewports, so a scrolled-out row would
|
||||
still claim its no-drag rect. */}
|
||||
{hasNavRows ? (
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
|
||||
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
|
||||
</SidebarNavScroll>
|
||||
) : null}
|
||||
|
||||
<SidebarViewSlot dismiss={closeSidebar}>
|
||||
<SidebarToastRegion active={active}>
|
||||
@@ -982,18 +935,19 @@ const staticStyles = RNStyleSheet.create({
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
|
||||
sidebarHeaderGroup: {
|
||||
paddingTop: theme.spacing[2],
|
||||
gap: 2,
|
||||
paddingBottom: theme.spacing[1.5],
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
desktopDragStrip: {
|
||||
position: "relative",
|
||||
height: theme.spacing[2],
|
||||
sidebarHeaderGroupFlush: {
|
||||
paddingTop: 0,
|
||||
},
|
||||
// The nav block caps at half the sidebar; a long item list scrolls inside the
|
||||
// cap instead of crowding the workspace list off a short screen.
|
||||
navScroll: {
|
||||
mobileNavScroll: {
|
||||
flexGrow: 0,
|
||||
flexShrink: 1,
|
||||
maxHeight: "50%",
|
||||
|
||||
@@ -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 { isRecognizedLink, prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import { prepareMarkdownSource, PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
|
||||
it("recognizes complete known commands in inline code", () => {
|
||||
@@ -38,13 +38,6 @@ 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";
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
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,13 +7,12 @@ 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 { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { markdownLinkSource } from "./source";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
const codeStyle = (theme: Theme) => ({
|
||||
@@ -51,18 +50,9 @@ 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
|
||||
{...copyAnchorProps}
|
||||
{...anchorProps}
|
||||
href={forgeUrl ?? anchorProps.href}
|
||||
style={anchorStyle}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
|
||||
@@ -111,25 +111,15 @@ function collectInlineCodePaths(
|
||||
return paths;
|
||||
}
|
||||
|
||||
type LinkSourceType = "markdown" | "text" | "inline-code";
|
||||
|
||||
export function markdownLinkSource(
|
||||
url: string,
|
||||
sourceType?: LinkSourceType,
|
||||
sourceType?: "markdown" | "text" | "inline-code",
|
||||
): 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==";
|
||||
|
||||
@@ -86,7 +86,6 @@ 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";
|
||||
@@ -2552,7 +2551,6 @@ function ProjectModeList({
|
||||
: null}
|
||||
{sidebarFilterEmpty ? <SidebarFilterEmptyState /> : projectBody}
|
||||
{listFooterComponent}
|
||||
<SidebarToastClearance />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -2594,7 +2592,8 @@ 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,
|
||||
// Room for the sidebar toast comes from SidebarToastClearance at the end of the content.
|
||||
// The sidebar toast floats over the list's end. Keep this padding the same whether or not
|
||||
// a toast shows: changing it moves the rows when the toast leaves.
|
||||
paddingBottom: theme.spacing[4],
|
||||
},
|
||||
projectListContainer: {
|
||||
|
||||
@@ -35,19 +35,14 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
|
||||
firstRowTrailing?: ReactNode;
|
||||
}
|
||||
|
||||
/** The top-level items the user keeps visible, in display order. */
|
||||
export function useVisibleSidebarNavItems() {
|
||||
const { items } = useSidebarNavItems("header");
|
||||
return useMemo(() => items.filter((item) => item.visible), [items]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level sidebar navigation, ordered and filtered by the user's
|
||||
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
|
||||
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
|
||||
*/
|
||||
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
|
||||
const visibleItems = useVisibleSidebarNavItems();
|
||||
const { items } = useSidebarNavItems("header");
|
||||
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
|
||||
const groupRef = useRef<View | null>(null);
|
||||
|
||||
if (visibleItems.length === 0 && !firstRowTrailing) return null;
|
||||
|
||||
@@ -34,7 +34,6 @@ 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";
|
||||
@@ -271,7 +270,6 @@ export function SidebarStatusWorkspaceList({
|
||||
onToggleWorkspacePin={onToggleWorkspacePin}
|
||||
/>
|
||||
)}
|
||||
<SidebarToastClearance />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1091,7 +1089,8 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
// Keep status mode's Pinned/Workspaces boundary identical to project mode.
|
||||
paddingTop: 2,
|
||||
// Room for the sidebar toast comes from SidebarToastClearance at the end of the content.
|
||||
// The sidebar toast floats over the list's end. Keep this padding the same whether or not
|
||||
// a toast shows: changing it moves the rows when the toast leaves.
|
||||
paddingBottom: theme.spacing[4],
|
||||
},
|
||||
pinnedSection: {
|
||||
|
||||
@@ -1,31 +1,9 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { 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 { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
import { 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.
|
||||
*
|
||||
@@ -37,8 +15,6 @@ 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;
|
||||
@@ -59,58 +35,14 @@ 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}>
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
<ToastViewport toast={toast} onDismiss={dismiss} placement="sidebar" />
|
||||
</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",
|
||||
|
||||
@@ -4,14 +4,7 @@ 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,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native";
|
||||
import { Platform, StyleSheet as NativeStyleSheet, Text, ToastAndroid, View } 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";
|
||||
@@ -64,11 +57,8 @@ type ToastViewportPlacement = "app-shell" | "panel" | "sidebar";
|
||||
const DEFAULT_DURATION_MS = 2200;
|
||||
const noopDismiss: DismissToast = () => {};
|
||||
const TOAST_MAX_WIDTH = 480;
|
||||
/** 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 toastEntering = FadeIn.duration(140);
|
||||
const toastExiting = FadeOut.duration(140);
|
||||
const ThemedCheckCircle = withUnistyles(CheckCircle2);
|
||||
const ThemedInfo = withUnistyles(Info);
|
||||
const ThemedWarning = withUnistyles(AlertTriangle);
|
||||
@@ -158,13 +148,10 @@ export function ToastViewport({
|
||||
toast,
|
||||
onDismiss,
|
||||
placement = "app-shell",
|
||||
onBottomCoverageChange,
|
||||
}: {
|
||||
toast: ToastState | null;
|
||||
onDismiss: () => 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();
|
||||
@@ -219,13 +206,6 @@ export function ToastViewport({
|
||||
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;
|
||||
@@ -247,7 +227,6 @@ export function ToastViewport({
|
||||
}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
|
||||
>
|
||||
<View
|
||||
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
|
||||
@@ -328,9 +307,9 @@ const animatedStyles = NativeStyleSheet.create({
|
||||
},
|
||||
sidebarContainer: {
|
||||
position: "absolute",
|
||||
left: SIDEBAR_TOAST_INSET,
|
||||
right: SIDEBAR_TOAST_INSET,
|
||||
bottom: SIDEBAR_TOAST_INSET,
|
||||
left: SPACING[2],
|
||||
right: SPACING[2],
|
||||
bottom: SPACING[2],
|
||||
zIndex: OVERLAY_Z.toast,
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { useMemo } from "react";
|
||||
import { createPluginClientStateSource } from "@/plugins/client-state/source";
|
||||
import { PluginInstallationProvider } from "@/plugins/installation-provider";
|
||||
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
|
||||
import type { PluginFilePanel } from "./panels";
|
||||
@@ -8,11 +11,17 @@ export function PluginFilePanelHost({
|
||||
...props
|
||||
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
|
||||
const { plugin, contribution } = panel;
|
||||
const stateSource = useMemo(
|
||||
() => createPluginClientStateSource(plugin.serverId),
|
||||
[plugin.serverId],
|
||||
);
|
||||
const Component = contribution.Component;
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Component {...props} />
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<Component {...props} />
|
||||
</PluginClientStateProvider>
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -6,7 +6,6 @@ import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state";
|
||||
import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
|
||||
type ColorScheme = "dark" | "light";
|
||||
@@ -86,16 +85,8 @@ export function useFaviconStatus() {
|
||||
// The favicon reads the whole fleet, so it has to keep every host's directory loading even
|
||||
// though it no longer subscribes to the agent maps.
|
||||
useAllDirectoryDemand({ serverIds, enabled: !isNative });
|
||||
// Background workspaces count exactly when the sidebar shows them.
|
||||
const showBackground = useSidebarViewStore((state) => state.showBackground);
|
||||
const selectFaviconStatus = useMemo(
|
||||
() => createFaviconStatusSelector({ showBackground }),
|
||||
[showBackground],
|
||||
);
|
||||
const selectMacDockBadgeCount = useMemo(
|
||||
() => createMacDockBadgeCountSelector({ showBackground }),
|
||||
[showBackground],
|
||||
);
|
||||
const selectFaviconStatus = useMemo(createFaviconStatusSelector, []);
|
||||
const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []);
|
||||
const status = useSessionStore(selectFaviconStatus);
|
||||
const dockBadgeCount = useSessionStore(selectMacDockBadgeCount);
|
||||
const [colorScheme, setColorScheme] = useState<ColorScheme>(getSystemColorScheme);
|
||||
|
||||
@@ -394,7 +394,6 @@ export const ar: TranslationResources = {
|
||||
otherPlaceholder: "آخر...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "نبضة دورية",
|
||||
pillOne: "مهمة واحدة في الخلفية",
|
||||
pillMany: "{{count}} مهمة في الخلفية",
|
||||
notRunning: "لم يعد قيد التشغيل",
|
||||
|
||||
@@ -393,7 +393,6 @@ export const en = {
|
||||
otherPlaceholder: "Other...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "Heartbeat",
|
||||
pillOne: "1 background task",
|
||||
pillMany: "{{count}} background tasks",
|
||||
notRunning: "No longer running",
|
||||
|
||||
@@ -399,7 +399,6 @@ export const es: TranslationResources = {
|
||||
otherPlaceholder: "Otro...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "Latido",
|
||||
pillOne: "1 tarea en segundo plano",
|
||||
pillMany: "{{count}} tareas en segundo plano",
|
||||
notRunning: "Ya no está en ejecución",
|
||||
|
||||
@@ -399,7 +399,6 @@ export const fr: TranslationResources = {
|
||||
otherPlaceholder: "Autre…",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "Battement périodique",
|
||||
pillOne: "1 tâche en arrière-plan",
|
||||
pillMany: "{{count}} tâches en arrière-plan",
|
||||
notRunning: "N’est plus en cours",
|
||||
|
||||
@@ -399,7 +399,6 @@ export const ja: TranslationResources = {
|
||||
otherPlaceholder: "その他...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "ハートビート",
|
||||
pillOne: "バックグラウンドタスク1件",
|
||||
pillMany: "バックグラウンドタスク{{count}}件",
|
||||
notRunning: "実行は終了しました",
|
||||
|
||||
@@ -395,7 +395,6 @@ export const ko: TranslationResources = {
|
||||
otherPlaceholder: "기타...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "하트비트",
|
||||
pillOne: "백그라운드 작업 1개",
|
||||
pillMany: "백그라운드 작업 {{count}}개",
|
||||
notRunning: "더 이상 실행 중이 아님",
|
||||
|
||||
@@ -398,7 +398,6 @@ export const ptBR: TranslationResources = {
|
||||
otherPlaceholder: "Outro...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "Batimento",
|
||||
pillOne: "1 tarefa em segundo plano",
|
||||
pillMany: "{{count}} tarefas em segundo plano",
|
||||
notRunning: "Não está mais em execução",
|
||||
|
||||
@@ -398,7 +398,6 @@ export const ru: TranslationResources = {
|
||||
otherPlaceholder: "Другой ответ...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "Периодический сигнал",
|
||||
pillOne: "1 фоновая задача",
|
||||
pillMany: "Фоновые задачи: {{count}}",
|
||||
notRunning: "Больше не выполняется",
|
||||
|
||||
@@ -394,7 +394,6 @@ export const zhCN: TranslationResources = {
|
||||
otherPlaceholder: "其他...",
|
||||
},
|
||||
backgroundWork: {
|
||||
heartbeat: "心跳",
|
||||
pillOne: "1 个后台任务",
|
||||
pillMany: "{{count}} 个后台任务",
|
||||
notRunning: "已不再运行",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
|
||||
import { usePaseo, useRpc } from "@getpaseo/plugin/client";
|
||||
import { defineRpc } from "@getpaseo/plugin";
|
||||
import { createPaseoApi, type PaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -8,11 +8,7 @@ import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin";
|
||||
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { PluginInstallationProvider } from "./installation-provider";
|
||||
import { PluginEnvironmentProvider } from "./popover";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
const status = defineRpc({
|
||||
@@ -93,53 +89,3 @@ it("gives every surface the installation's client and RPCs on its first frame",
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
it("lets every surface read state through the plugin state hooks", async () => {
|
||||
const plugin = installation([]);
|
||||
function Surface() {
|
||||
return <span>{useWorkspaces().length} workspaces</span>;
|
||||
}
|
||||
|
||||
const markup = renderToStaticMarkup(
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Surface />
|
||||
</PluginInstallationProvider>,
|
||||
);
|
||||
|
||||
expect(markup).toBe("<span>0 workspaces</span>");
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) {
|
||||
return { installation: plugin, state, toast: {} as ToastApi };
|
||||
}
|
||||
|
||||
it("lets a surface read the state source its host passes", async () => {
|
||||
const plugin = installation([]);
|
||||
// A sidebar view spans every connected host, so its source is not the installation's host.
|
||||
const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot;
|
||||
const state: PluginClientStateSource = {
|
||||
subscribe: () => () => undefined,
|
||||
getWorkspace: () => workspace,
|
||||
getAgent: () => null,
|
||||
getProject: () => null,
|
||||
getTerminal: () => null,
|
||||
getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }),
|
||||
};
|
||||
function Surface() {
|
||||
return <span>{useWorkspace("ws-on-another-host")?.id}</span>;
|
||||
}
|
||||
|
||||
const environment = pluginEnvironment(plugin, state);
|
||||
|
||||
const markup = renderToStaticMarkup(
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<Surface />
|
||||
</PluginEnvironmentProvider>,
|
||||
);
|
||||
|
||||
expect(markup).toBe("<span>ws-on-another-host</span>");
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
@@ -2,42 +2,29 @@ import { getPluginClientApi } from "./client-state/api";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
PaseoApiProvider,
|
||||
PluginClientStateProvider,
|
||||
PluginComposersProvider,
|
||||
PluginRpcProvider,
|
||||
PluginTranslationProvider,
|
||||
type PluginClientStateSource,
|
||||
} from "@getpaseo/plugin/client/host";
|
||||
import React, { useMemo, type ReactNode } from "react";
|
||||
import { createPluginClientStateSource } from "./client-state/source";
|
||||
import React, { type ReactNode } from "react";
|
||||
import { pluginComposersSource } from "./composer-items/source";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
/**
|
||||
* Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs,
|
||||
* and the state the plugin state hooks read. That state is scoped to the installation's host
|
||||
* unless the surface passes its own, as a sidebar view does to span every connected host.
|
||||
*/
|
||||
/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */
|
||||
export function PluginInstallationProvider({
|
||||
plugin,
|
||||
state: surfaceState,
|
||||
children,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
state?: PluginClientStateSource;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const state = useMemo(
|
||||
() => surfaceState ?? createPluginClientStateSource(plugin.serverId),
|
||||
[plugin.serverId, surfaceState],
|
||||
);
|
||||
return (
|
||||
<QueryClientProvider client={plugin.queryClient}>
|
||||
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
|
||||
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
|
||||
<PluginTranslationProvider runtime={plugin.i18n}>
|
||||
<PluginComposersProvider source={pluginComposersSource(plugin)}>
|
||||
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
|
||||
{children}
|
||||
</PluginComposersProvider>
|
||||
</PluginTranslationProvider>
|
||||
</PluginRpcProvider>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -29,8 +30,8 @@ export function PluginEnvironmentProvider({
|
||||
}: PluginEnvironmentProviderProps) {
|
||||
return (
|
||||
<ToastApiProvider api={environment.toast}>
|
||||
<PluginInstallationProvider plugin={environment.installation} state={environment.state}>
|
||||
{children}
|
||||
<PluginInstallationProvider plugin={environment.installation}>
|
||||
<PluginClientStateProvider source={environment.state}>{children}</PluginClientStateProvider>
|
||||
</PluginInstallationProvider>
|
||||
</ToastApiProvider>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import React, { type ComponentType, useMemo } from "react";
|
||||
@@ -7,6 +8,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { PluginTimelineStreamItem } from "@/types/stream";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
import { PluginInstallationProvider } from "../installation-provider";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
@@ -57,6 +59,7 @@ function PluginTimelineItemBody({
|
||||
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
|
||||
if (!plugin || !renderer || !parsed || !client) {
|
||||
return <TimelineItemUnavailable />;
|
||||
@@ -79,7 +82,9 @@ function PluginTimelineItemBody({
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} resetKey={item.data} Surface={Component}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Component {...props} />
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<Component {...props} />
|
||||
</PluginClientStateProvider>
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
PluginTab,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import { CircleAlert } from "lucide-react-native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -19,6 +20,7 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
|
||||
import { usePluginHostNavigation } from "../host-navigation";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { toPluginTheme } from "../theme";
|
||||
import { pluginIconComponent } from "../icons";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
@@ -65,6 +67,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
const navigation = usePluginHostNavigation(serverId);
|
||||
|
||||
if (!plugin || !contribution || !workspaceExists) {
|
||||
@@ -120,7 +123,9 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
Surface={Surface}
|
||||
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
|
||||
>
|
||||
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>{panel}</PluginClientStateProvider>
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2739,52 +2739,6 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => {
|
||||
const host = makeHost({
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
});
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.setConnectionState({ status: "connected" });
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: JSON.stringify([host]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: hostProfile }) => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: hostProfile.serverId,
|
||||
hostname: hostProfile.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
});
|
||||
|
||||
// A component renders on every tick while the registry loads, and acquires directory
|
||||
// demand for each host it reads, as the sidebar does on its first render.
|
||||
const registry = { loading: true };
|
||||
const boot = store.boot().finally(() => {
|
||||
registry.loading = false;
|
||||
});
|
||||
let releaseDemand: (() => void) | null = null;
|
||||
while (registry.loading && !releaseDemand) {
|
||||
if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) {
|
||||
releaseDemand = store.acquireDirectoryDemand(host.serverId);
|
||||
}
|
||||
await Promise.resolve();
|
||||
}
|
||||
await boot;
|
||||
expect(releaseDemand).not.toBeNull();
|
||||
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1));
|
||||
|
||||
releaseDemand?.();
|
||||
store.syncHosts([]);
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
@@ -2909,8 +2863,7 @@ describe("HostRuntimeStore", () => {
|
||||
await registryLoaded;
|
||||
|
||||
expect(store.isHostRegistryLoaded()).toBe(true);
|
||||
// Publishing the restored hosts, the registry turning ready, and the registry loading.
|
||||
expect(hostListNotifications).toBe(3);
|
||||
expect(hostListNotifications).toBe(2);
|
||||
} finally {
|
||||
if (previousOverride === undefined) {
|
||||
delete process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
|
||||
@@ -1816,9 +1816,11 @@ export class HostRuntimeStore {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
this.hosts = profiles;
|
||||
this.replicaCache.setHosts(profiles.map((profile) => profile.serverId));
|
||||
projectIconCache.setHosts(profiles.map((profile) => profile.serverId));
|
||||
await projectIconCache.restore();
|
||||
this.setHostsAndSync(profiles);
|
||||
this.syncHosts(profiles);
|
||||
for (const profile of profiles) {
|
||||
void this.directorySyncByServer
|
||||
.get(profile.serverId)
|
||||
|
||||
@@ -21,7 +21,8 @@ import {
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
|
||||
const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
export function OpenProjectScreen() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -106,79 +106,6 @@ describe("workspace-pane-state", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not locate a file by an id retained from a previous target", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "split-side-pane",
|
||||
paneId: "main",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"agent_agent-a",
|
||||
);
|
||||
});
|
||||
|
||||
it("matches a retained file instance when only the requested line range differs", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["retained-file", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
};
|
||||
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
|
||||
const tabs = [
|
||||
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = {
|
||||
kind: "file",
|
||||
path: "/repo/a.ts",
|
||||
lineStart: 12,
|
||||
lineEnd: 20,
|
||||
};
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "open-in-source",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"retained-file",
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers an exact file navigation target over another instance of the same resource", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["first", "second"],
|
||||
focusedTabId: "first",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
|
||||
];
|
||||
|
||||
expect(
|
||||
deriveWorkspacePaneState({
|
||||
pane,
|
||||
tabs,
|
||||
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
|
||||
}).activeTabId,
|
||||
).toBe("second");
|
||||
});
|
||||
|
||||
it("resolves side file opens to an existing file tab", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
normalizeWorkspaceTabTarget,
|
||||
workspaceTabTargetsEqual,
|
||||
} from "@/workspace-tabs/identity";
|
||||
import { findAdjacentPane } from "@/utils/split-navigation";
|
||||
import { panelResourceKey } from "@/panels/panel-manifest";
|
||||
|
||||
export interface WorkspaceDerivedTab {
|
||||
descriptor: WorkspaceTabDescriptor;
|
||||
@@ -121,10 +124,8 @@ function getActiveTabId(input: {
|
||||
}
|
||||
const matchingTab =
|
||||
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
|
||||
input.tabs.find(
|
||||
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
|
||||
);
|
||||
return matchingTab?.descriptor.tabId ?? null;
|
||||
null;
|
||||
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
|
||||
})();
|
||||
|
||||
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
|
||||
@@ -210,8 +211,10 @@ export function resolveSideFileOpenPlacement(input: {
|
||||
tabs: WorkspaceTab[];
|
||||
target: WorkspaceTabTarget;
|
||||
}): WorkspaceSideFileOpenPlacement {
|
||||
const targetKey = panelResourceKey(input.target);
|
||||
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
|
||||
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
|
||||
const existingTab = input.tabs.find(
|
||||
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
|
||||
);
|
||||
if (existingTab) {
|
||||
return { kind: "open-in-source" };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
|
||||
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
|
||||
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
@@ -137,8 +137,6 @@ interface OpenTabInLayoutInput {
|
||||
placement: WorkspaceTabPlacement;
|
||||
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
|
||||
explorerSidebarPaneId: string | null;
|
||||
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
|
||||
@@ -263,7 +261,6 @@ interface ReorderPaneTabsInLayoutInput {
|
||||
|
||||
export interface WorkspaceTabReconcileState {
|
||||
layout: WorkspaceLayout;
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
pinnedAgentIds?: ReadonlySet<string> | null;
|
||||
hiddenAgentIds?: ReadonlySet<string> | null;
|
||||
explorerSidebarPaneId: string | null;
|
||||
@@ -401,11 +398,15 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
|
||||
if (!Array.isArray(input)) {
|
||||
return [];
|
||||
}
|
||||
// Preserve colliding entries until the whole layout can assign each an identity.
|
||||
const next: WorkspaceTab[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const value of input) {
|
||||
const tab = normalizeWorkspaceTab(value);
|
||||
if (tab) next.push(tab);
|
||||
if (!tab || seen.has(tab.tabId)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(tab.tabId);
|
||||
next.push(tab);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1021,65 +1022,13 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
|
||||
};
|
||||
}
|
||||
|
||||
function repairDuplicateTabIds(root: SplitNodeInternal): {
|
||||
root: SplitNodeInternal;
|
||||
ambiguousIds: ReadonlySet<string>;
|
||||
} {
|
||||
const keepers = new Map<string, WorkspaceTab>();
|
||||
const ambiguousIds = new Set<string>();
|
||||
for (const tab of collectAllTabs(root)) {
|
||||
const keeper = keepers.get(tab.tabId);
|
||||
if (!keeper) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
continue;
|
||||
}
|
||||
ambiguousIds.add(tab.tabId);
|
||||
if (
|
||||
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
|
||||
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
|
||||
) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
}
|
||||
}
|
||||
if (ambiguousIds.size === 0) return { root, ambiguousIds };
|
||||
|
||||
// Reserve every original id before assigning replacements, including hidden panes.
|
||||
const occupiedIds = new Set(keepers.keys());
|
||||
function repair(node: SplitNodeInternal): SplitNodeInternal {
|
||||
if (node.kind === "group") {
|
||||
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
|
||||
}
|
||||
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
|
||||
const focusedTab =
|
||||
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
|
||||
let focusedTabId = node.pane.focusedTabId;
|
||||
const tabs = node.pane.tabs.map((tab) => {
|
||||
if (keepers.get(tab.tabId) === tab) return tab;
|
||||
const tabId = allocateWorkspaceTabId(
|
||||
buildDeterministicWorkspaceTabId(tab.target),
|
||||
occupiedIds,
|
||||
);
|
||||
occupiedIds.add(tabId);
|
||||
if (tab === focusedTab) focusedTabId = tabId;
|
||||
return { ...tab, tabId };
|
||||
});
|
||||
return {
|
||||
...node,
|
||||
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
|
||||
};
|
||||
}
|
||||
return { root: repair(root), ambiguousIds };
|
||||
}
|
||||
|
||||
export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
if (!layout || typeof layout !== "object") {
|
||||
return createDefaultLayout();
|
||||
}
|
||||
|
||||
const rawLayout = layout as WorkspaceLayout;
|
||||
const { root, ambiguousIds } = repairDuplicateTabIds(
|
||||
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
|
||||
);
|
||||
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
|
||||
const focusedPaneId =
|
||||
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
|
||||
const resolvedFocusedPaneId =
|
||||
@@ -1098,16 +1047,7 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
|
||||
});
|
||||
|
||||
if (parentTabIdByTabId) {
|
||||
// A duplicated id cannot identify either end of a parent relationship unambiguously.
|
||||
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
|
||||
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
|
||||
delete parentTabIdByTabId[childId];
|
||||
}
|
||||
if (Object.keys(parentTabIdByTabId).length > 0)
|
||||
return { ...normalizedLayout, parentTabIdByTabId };
|
||||
}
|
||||
return normalizedLayout;
|
||||
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
|
||||
}
|
||||
|
||||
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
|
||||
@@ -1424,9 +1364,7 @@ function insertNewTabIntoPane(
|
||||
return null;
|
||||
}
|
||||
|
||||
const occupiedIds = new Set(input.reservedTabIds);
|
||||
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
|
||||
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
|
||||
const tabId = input.createTabId();
|
||||
const nextTab: WorkspaceTab = {
|
||||
tabId,
|
||||
target: input.target,
|
||||
@@ -2346,7 +2284,6 @@ function openEntityTabWithoutFocusing(input: {
|
||||
layout: WorkspaceLayout;
|
||||
target: WorkspaceTabTarget;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
return (
|
||||
insertNewTabIntoPane({
|
||||
@@ -2355,7 +2292,6 @@ function openEntityTabWithoutFocusing(input: {
|
||||
now: Date.now(),
|
||||
placement: AMBIENT_PLACEMENT,
|
||||
explorerSidebarPaneId: input.explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
|
||||
focus: false,
|
||||
})?.layout ?? input.layout
|
||||
@@ -2446,7 +2382,6 @@ function addMissingEntityTabs(input: {
|
||||
hasActivePendingTerminalCreate: boolean;
|
||||
hasActivePendingDraftCreate: boolean;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
const {
|
||||
autoOpenAgentIds,
|
||||
@@ -2477,7 +2412,6 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "agent", agentId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentAgentIds.add(agentId);
|
||||
}
|
||||
@@ -2492,7 +2426,6 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "terminal", terminalId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentTerminalIds.add(terminalId);
|
||||
}
|
||||
@@ -2592,7 +2525,6 @@ export function reconcileWorkspaceTabs(
|
||||
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
|
||||
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
|
||||
explorerSidebarPaneId: state.explorerSidebarPaneId,
|
||||
reservedTabIds: state.reservedTabIds,
|
||||
});
|
||||
|
||||
if (reconciledFocusedTabId) {
|
||||
|
||||
@@ -11,22 +11,6 @@ function createRandomIdValue(): string {
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
export function createWorkspaceTabInstanceId(): string {
|
||||
return `tab_${createRandomIdValue()}`;
|
||||
}
|
||||
|
||||
/** A resource-derived id may still belong to a preview slot showing another target. */
|
||||
export function allocateWorkspaceTabId(
|
||||
preferredId: string,
|
||||
occupiedIds: ReadonlySet<string>,
|
||||
): string {
|
||||
let tabId = preferredId;
|
||||
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
|
||||
tabId = `${preferredId}:${suffix}`;
|
||||
}
|
||||
return tabId;
|
||||
}
|
||||
|
||||
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
|
||||
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
|
||||
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
|
||||
|
||||
@@ -59,84 +59,6 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
|
||||
);
|
||||
});
|
||||
|
||||
it("hydrates a saved preview collision and persists the repaired identities", async () => {
|
||||
const workspaceKey = "server:workspace";
|
||||
const duplicateId = "file_a.ts";
|
||||
const values = new Map([
|
||||
[
|
||||
"workspace-layout-state",
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
state: {
|
||||
layoutByWorkspace: {
|
||||
[workspaceKey]: {
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "split",
|
||||
direction: "horizontal",
|
||||
sizes: [0.5, 0.5],
|
||||
children: [
|
||||
{ id: "main", path: "b.ts" },
|
||||
{ id: "right", path: "a.ts" },
|
||||
].map(({ id, path }) => ({
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id,
|
||||
tabIds: [duplicateId],
|
||||
focusedTabId: duplicateId,
|
||||
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
|
||||
},
|
||||
})),
|
||||
},
|
||||
},
|
||||
focusedPaneId: "right",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
]);
|
||||
const storage: StateStorage = {
|
||||
getItem: (name) => values.get(name) ?? null,
|
||||
setItem: (name, value) => {
|
||||
values.set(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
values.delete(name);
|
||||
},
|
||||
};
|
||||
const store = createWorkspaceLayoutStore(undefined, storage);
|
||||
await store.persist.rehydrate();
|
||||
const layout = store.getState().layoutByWorkspace[workspaceKey];
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
|
||||
"file_b.ts",
|
||||
"file_a.ts",
|
||||
]);
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "b.ts",
|
||||
});
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "a.ts",
|
||||
});
|
||||
store.getState().focusTab(workspaceKey, "file_b.ts");
|
||||
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
|
||||
|
||||
const reloaded = createWorkspaceLayoutStore(undefined, storage);
|
||||
await reloaded.persist.rehydrate();
|
||||
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
|
||||
store.getState().layoutByWorkspace[workspaceKey],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
|
||||
const values = new Map<string, string>();
|
||||
const storage: StateStorage = {
|
||||
|
||||
@@ -906,91 +906,6 @@ describe("workspace-layout-store actions", () => {
|
||||
).toEqual(override);
|
||||
});
|
||||
|
||||
it("keeps reused file tabs unique and focuses the matching split pane", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
const firstTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
|
||||
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
|
||||
targetPaneId: "main",
|
||||
position: "right",
|
||||
});
|
||||
if (!rightPaneId) throw new Error("Expected a right split pane");
|
||||
const rightTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
placement: { mode: "pane", paneId: rightPaneId },
|
||||
})!;
|
||||
|
||||
store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/b.ts" },
|
||||
intent: "reveal",
|
||||
});
|
||||
store.focusTab(workspaceKey, rightTabId);
|
||||
|
||||
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
|
||||
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
|
||||
expect({
|
||||
fileTabCount: fileTabs.length,
|
||||
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
|
||||
fileTargets: fileTabs.map((tab) => tab.target),
|
||||
focusedPaneId: layout.focusedPaneId,
|
||||
}).toEqual({
|
||||
fileTabCount: 2,
|
||||
uniqueFileTabCount: 2,
|
||||
fileTargets: [
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
],
|
||||
focusedPaneId: rightPaneId,
|
||||
});
|
||||
});
|
||||
|
||||
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
|
||||
const store = layoutStore.getState();
|
||||
const fileTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
|
||||
layoutStore.setState({ layoutMode: "compact" });
|
||||
const sheetTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
const selectedSheet = selectSheetTab(layoutStore.getState(), {
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
});
|
||||
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
|
||||
const backgroundTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "background",
|
||||
})!;
|
||||
|
||||
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
|
||||
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
|
||||
expect(
|
||||
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
|
||||
.filter((tab) => tab.target.kind === "file")
|
||||
.map((tab) => tab.target),
|
||||
).toEqual([
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
@@ -3285,75 +3200,6 @@ describe("workspace-layout-store actions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
|
||||
const file = (tabId: string, path: string) => ({
|
||||
tabId,
|
||||
target: { kind: "file", path },
|
||||
createdAt: 1,
|
||||
state: { treeVisible: true, treeWidth: 280 },
|
||||
});
|
||||
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
|
||||
const rightTabs = [
|
||||
file("file_a.ts", "a.ts"),
|
||||
file("file_b.ts", "b.ts"),
|
||||
file("file_b.ts:2", "b.ts"),
|
||||
file("child", "child.ts"),
|
||||
file("parent", "parent.ts"),
|
||||
];
|
||||
const layout = normalizeLayout({
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "root",
|
||||
direction: "horizontal",
|
||||
sizes: [0.4, 0.6],
|
||||
children: [
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabs: leftTabs,
|
||||
tabIds: leftTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "right",
|
||||
tabs: rightTabs,
|
||||
tabIds: rightTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
parentTabIdByTabId: {
|
||||
"file_a.ts": "parent",
|
||||
"file_b.ts": "file_a.ts",
|
||||
child: "parent",
|
||||
},
|
||||
});
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs).toHaveLength(7);
|
||||
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
|
||||
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
|
||||
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
|
||||
expect(tabs.slice(2)).toEqual(rightTabs);
|
||||
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
|
||||
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
|
||||
expect(findPaneById(layout.root, "right")).toMatchObject({
|
||||
hidden: true,
|
||||
focusedTabId: "file_a.ts",
|
||||
});
|
||||
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
|
||||
expect(normalizeLayout(layout)).toEqual(layout);
|
||||
});
|
||||
|
||||
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
|
||||
const tabs = [
|
||||
{
|
||||
@@ -5264,50 +5110,6 @@ describe("compact workspace sheet", () => {
|
||||
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
|
||||
});
|
||||
|
||||
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
const store = createCompactStore();
|
||||
store.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child-a" },
|
||||
intent: "reveal",
|
||||
});
|
||||
const sheetId = requireTopSheet(store).tab.tabId;
|
||||
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
|
||||
store.getState().reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["root", "child-a", "child-b"],
|
||||
autoOpenAgentIds: ["child-a"],
|
||||
knownTerminalIds: ["term-1"],
|
||||
standaloneTerminalIds: ["term-1"],
|
||||
});
|
||||
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
|
||||
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
|
||||
);
|
||||
if (!tab) throw new Error("Expected the root agent's tab");
|
||||
expect(tab.tabId).not.toBe(sheetId);
|
||||
|
||||
store.getState().closeTab(workspaceKey, tab.tabId);
|
||||
expect(requireTopSheet(store).tab).toMatchObject({
|
||||
tabId: sheetId,
|
||||
target: { kind: "agent", agentId: "child-b" },
|
||||
});
|
||||
expect(
|
||||
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
|
||||
).not.toContainEqual(tab);
|
||||
});
|
||||
|
||||
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
|
||||
@@ -7,8 +7,6 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import {
|
||||
allocateWorkspaceTabId,
|
||||
createWorkspaceTabInstanceId,
|
||||
defaultWorkspaceLayoutIds,
|
||||
type WorkspaceLayoutIdSource,
|
||||
} from "@/stores/workspace-layout-ids";
|
||||
@@ -433,6 +431,14 @@ function trimNonEmpty(value: string | null | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function createWorkspaceTabInstanceId(): string {
|
||||
const value =
|
||||
typeof globalThis.crypto?.randomUUID === "function"
|
||||
? globalThis.crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
return `tab_${value}`;
|
||||
}
|
||||
|
||||
function addAgentIdToWorkspaceSet(
|
||||
state: Record<string, Set<string>>,
|
||||
workspaceKey: string,
|
||||
@@ -525,10 +531,7 @@ export function selectExplorerSidebarPaneId(
|
||||
*/
|
||||
export function selectSheetTab(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
|
||||
/** A host outside the sheet stack owns its instance identity. */
|
||||
preferredTabId?: string;
|
||||
},
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
|
||||
): SheetTab | null {
|
||||
const workspaceKey = trimNonEmpty(input.workspaceKey);
|
||||
const target = normalizeWorkspaceTabTarget(input.target);
|
||||
@@ -536,14 +539,9 @@ export function selectSheetTab(
|
||||
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
|
||||
if (!policy) return null;
|
||||
return placeTargetInSheet({
|
||||
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
|
||||
kept: input.preferredTabId
|
||||
? undefined
|
||||
: getSheets(state, workspaceKey).find(
|
||||
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
|
||||
),
|
||||
kept: undefined,
|
||||
target,
|
||||
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
|
||||
intent: "reveal",
|
||||
policy,
|
||||
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
|
||||
state: undefined,
|
||||
@@ -640,7 +638,6 @@ function getOpenTabPlacement(
|
||||
layout: WorkspaceLayout;
|
||||
placement: WorkspaceTabPlacement;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: Set<string>;
|
||||
} {
|
||||
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
|
||||
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
|
||||
@@ -673,7 +670,6 @@ function getOpenTabPlacement(
|
||||
layout,
|
||||
placement: resolvedPlacement,
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -819,23 +815,11 @@ function resolveOpenParentTabId(
|
||||
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
|
||||
}
|
||||
|
||||
function collectWorkspaceTabIds(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
workspaceKey: string,
|
||||
): Set<string> {
|
||||
const layout = state.layoutByWorkspace[workspaceKey];
|
||||
return new Set([
|
||||
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
|
||||
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
|
||||
]);
|
||||
}
|
||||
|
||||
function placeTargetInSheet(input: {
|
||||
occupiedTabIds: ReadonlySet<string>;
|
||||
/** The sheet whose tab the target keeps, if any. */
|
||||
kept: SheetTab | undefined;
|
||||
target: WorkspaceTabTarget;
|
||||
createTabId: () => string;
|
||||
intent: WorkspaceTabOpenIntent;
|
||||
policy: CompactSheetPolicy;
|
||||
parentTabId: string | null;
|
||||
state: JsonValue | undefined;
|
||||
@@ -845,7 +829,10 @@ function placeTargetInSheet(input: {
|
||||
}
|
||||
return {
|
||||
tab: {
|
||||
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
|
||||
tabId:
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(input.target)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
target: input.target,
|
||||
createdAt: Date.now(),
|
||||
...(input.state !== undefined ? { state: input.state } : {}),
|
||||
@@ -866,7 +853,6 @@ function promoteSheetToTab(
|
||||
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
|
||||
const { tab } = sheet;
|
||||
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
|
||||
placement.reservedTabIds.delete(tab.tabId);
|
||||
const input = {
|
||||
...placement,
|
||||
target: tab.target,
|
||||
@@ -1136,13 +1122,9 @@ export function createWorkspaceLayoutStore(
|
||||
const sheets = getSheets(get(), normalizedWorkspaceKey);
|
||||
const { keptIndex } = sheetPlacement;
|
||||
const sheet = placeTargetInSheet({
|
||||
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
|
||||
kept: keptIndex === null ? undefined : sheets[keptIndex],
|
||||
target: normalizedTarget,
|
||||
createTabId: () =>
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(normalizedTarget)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
intent: input.intent,
|
||||
policy: sheetPlacement.policy,
|
||||
parentTabId,
|
||||
state: input.state,
|
||||
@@ -1724,14 +1706,9 @@ export function createWorkspaceLayoutStore(
|
||||
explorerSidebarPaneId,
|
||||
rawLayout.focusedPaneId,
|
||||
);
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const nextState = reconcileWorkspaceTabs(
|
||||
{
|
||||
layout: currentLayout,
|
||||
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
|
||||
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
explorerSidebarPaneId,
|
||||
@@ -1753,6 +1730,10 @@ export function createWorkspaceLayoutStore(
|
||||
);
|
||||
}
|
||||
}
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const sheetAgentGone = fittingSheets.length !== sheets.length;
|
||||
if (
|
||||
state.layoutByWorkspace[normalizedWorkspaceKey] &&
|
||||
|
||||
@@ -138,88 +138,6 @@ describe("useSubagentSheetTab", () => {
|
||||
expect(result.current?.tab.tabId).toBe(tabId);
|
||||
});
|
||||
|
||||
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
const reusedId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
intent: "reveal",
|
||||
asTab: true,
|
||||
});
|
||||
if (!reusedId) throw new Error("Expected a child tab");
|
||||
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheetId = result.current?.tab.tabId;
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(sheetId).not.toBe(reusedId);
|
||||
|
||||
act(() => {
|
||||
store.reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["parent", "child"],
|
||||
autoOpenAgentIds: [],
|
||||
knownTerminalIds: [],
|
||||
standaloneTerminalIds: [],
|
||||
});
|
||||
});
|
||||
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
|
||||
expect(result.current?.tab.tabId).toBe(sheetId);
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
});
|
||||
|
||||
it("promotes a menu sheet to the subagent's own tab", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
|
||||
let promotedId: string | null = null;
|
||||
act(() => {
|
||||
promotedId = store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(promotedId).toBe("agent_child");
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: "agent_child",
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
act(() => {
|
||||
store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
act(() => {
|
||||
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
|
||||
});
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: sheet.tab.tabId,
|
||||
target: { kind: "agent", agentId: "other" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("hands a re-rendered row the same sheet", () => {
|
||||
const row = seedParentWithChild();
|
||||
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
useWorkspaceLayoutStore,
|
||||
type SheetTab,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { SubagentRow } from "./select";
|
||||
|
||||
@@ -33,9 +32,6 @@ export function useSubagentSheetTab(
|
||||
const sheets = useWorkspaceLayoutStore((state) =>
|
||||
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
|
||||
);
|
||||
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
|
||||
// it as a tab lands on that id, and keeps the id it was given across layout updates.
|
||||
const tabIds = useMemo(() => new Map<string, string>(), []);
|
||||
return useMemo(() => {
|
||||
// One answer per row until the state it reads changes, so a re-render of the list hands an
|
||||
// open sheet the same tab rather than a fresh one.
|
||||
@@ -47,19 +43,16 @@ export function useSubagentSheetTab(
|
||||
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
|
||||
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
|
||||
};
|
||||
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
|
||||
const key = `${row.kind}:${row.id}`;
|
||||
const known = answers.get(key);
|
||||
if (known !== undefined) return known;
|
||||
const target = subagentRowTarget(row);
|
||||
const sheet = selectSheetTab(state, {
|
||||
workspaceKey,
|
||||
target,
|
||||
target: subagentRowTarget(row),
|
||||
parentTabId,
|
||||
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
|
||||
});
|
||||
if (sheet) tabIds.set(key, sheet.tab.tabId);
|
||||
answers.set(key, sheet);
|
||||
return sheet;
|
||||
};
|
||||
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
|
||||
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type SqliteValue,
|
||||
} from "@/runtime/replica-cache/row-store-sqlite";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import type { CachedTimeline } from "@/runtime/replica-cache";
|
||||
import {
|
||||
@@ -18,8 +17,6 @@ import {
|
||||
} from "@/stores/session-store";
|
||||
import { useCreateFlowStore, type PendingCreateAttempt } from "@/stores/create-flow-store";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { AgentStreamReducerEvent } from "./session-stream-reducers";
|
||||
import type { ProjectedTimelineForwardFetchPlan } from "./timeline-sync-plan";
|
||||
import { reduceTurnLiveness, type TurnLivenessTransition } from "./turn-liveness";
|
||||
import {
|
||||
createTimelineReplica,
|
||||
@@ -1382,318 +1379,6 @@ describe("create handoff lifetime", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a chat that was empty when it went offline", () => {
|
||||
const EPOCH = "epoch-1";
|
||||
const PROMPT = "stream through a reconnect";
|
||||
const THOUGHT = "Thinking before the reply.";
|
||||
const TURN_ID = "turn-1";
|
||||
const TIMESTAMP = "2026-10-31T10:00:00.000Z";
|
||||
|
||||
/** The daemon's timeline: one row per flushed chunk, read back as projected pages. */
|
||||
class DaemonTimeline {
|
||||
private readonly rows: Array<{ seq: number; item: AgentTimelineItem }> = [];
|
||||
|
||||
record(timelineItem: AgentTimelineItem): AgentStreamReducerEvent {
|
||||
const seq = this.rows.length + 1;
|
||||
this.rows.push({ seq, item: timelineItem });
|
||||
return {
|
||||
event: { type: "timeline", provider: "mock", turnId: TURN_ID, item: timelineItem },
|
||||
seq,
|
||||
epoch: EPOCH,
|
||||
timestamp: new Date(TIMESTAMP),
|
||||
};
|
||||
}
|
||||
|
||||
page(request: ProjectedTimelineForwardFetchPlan): TimelineResponsePayload {
|
||||
const maxSeq = this.rows.at(-1)?.seq ?? 0;
|
||||
const after = request.direction === "after" ? request.cursor.seq : 0;
|
||||
const entries = this.projected().filter((entry) => entry.seqEnd > after);
|
||||
const first = entries[0];
|
||||
const startSeq = request.direction === "after" ? after + 1 : first?.seqStart;
|
||||
return {
|
||||
requestId: `${request.direction}-${after}`,
|
||||
agentId: AGENT_ID,
|
||||
agent: null,
|
||||
direction: request.direction,
|
||||
projection: "projected",
|
||||
reset: false,
|
||||
epoch: EPOCH,
|
||||
window: { minSeq: this.rows[0]?.seq ?? 0, maxSeq, nextSeq: maxSeq + 1 },
|
||||
startCursor: first && startSeq !== undefined ? { epoch: EPOCH, seq: startSeq } : null,
|
||||
endCursor: first ? { epoch: EPOCH, seq: maxSeq } : null,
|
||||
entries,
|
||||
error: null,
|
||||
hasNewer: false,
|
||||
hasOlder: after > 0,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** Contiguous reply and thought chunks read back as one row, like the daemon's projection. */
|
||||
private projected(): TimelineResponsePayload["entries"] {
|
||||
const entries: TimelineResponsePayload["entries"] = [];
|
||||
for (const { seq, item: row } of this.rows) {
|
||||
const previous = entries.at(-1);
|
||||
const continues =
|
||||
previous !== undefined &&
|
||||
((row.type === "assistant_message" &&
|
||||
previous.item.type === "assistant_message" &&
|
||||
previous.item.messageId === row.messageId) ||
|
||||
(row.type === "reasoning" && previous.item.type === "reasoning"));
|
||||
if (
|
||||
continues &&
|
||||
(previous.item.type === "assistant_message" || previous.item.type === "reasoning") &&
|
||||
(row.type === "assistant_message" || row.type === "reasoning")
|
||||
) {
|
||||
previous.item = { ...previous.item, text: `${previous.item.text}${row.text}` };
|
||||
previous.seqEnd = seq;
|
||||
previous.sourceSeqRanges = [{ startSeq: previous.seqStart, endSeq: seq }];
|
||||
previous.collapsed = [
|
||||
row.type === "assistant_message" ? "assistant_merge" : "reasoning_merge",
|
||||
];
|
||||
continue;
|
||||
}
|
||||
entries.push({
|
||||
provider: "mock",
|
||||
item: row,
|
||||
timestamp: TIMESTAMP,
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
turnId: TURN_ID,
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingFetch {
|
||||
request: ProjectedTimelineForwardFetchPlan;
|
||||
/** Delivers a page the way the host runtime does: queued live chunks first, then the page. */
|
||||
deliver(page: TimelineResponsePayload): void;
|
||||
}
|
||||
|
||||
function openChat(storage: TimelineReplicaStorage) {
|
||||
const fetches: PendingFetch[] = [];
|
||||
const errors: unknown[] = [];
|
||||
const fetch = (request: ProjectedTimelineForwardFetchPlan) =>
|
||||
new Promise<{ hasNewer: boolean; endCursor: { epoch: string; seq: number } | null }>(
|
||||
(resolve) => {
|
||||
fetches.push({
|
||||
request,
|
||||
deliver: (page) => {
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
owner.applyTimelineResponse(page);
|
||||
resolve({ hasNewer: page.hasNewer, endCursor: page.endCursor });
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
const replica = createTimelineReplica({
|
||||
serverId: SERVER_ID,
|
||||
storage,
|
||||
prepareAgent: async () => undefined,
|
||||
});
|
||||
const owner = createViewedTimelineOwner({
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => true,
|
||||
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
|
||||
readCursor: (agentId) => {
|
||||
const timeline = selectAgentTimelineState(
|
||||
useSessionStore.getState().sessions[SERVER_ID],
|
||||
agentId,
|
||||
);
|
||||
return timeline.status === "synced" && timeline.range
|
||||
? { epoch: timeline.range.epoch, endSeq: timeline.range.endSeq }
|
||||
: undefined;
|
||||
},
|
||||
fetchPage: (_agentId, request) => fetch(request),
|
||||
fetchLatestTail: () =>
|
||||
fetch({ direction: "tail", limit: 40, projection: "projected", wholeTurns: true }),
|
||||
reportError: (error) => errors.push(error),
|
||||
},
|
||||
});
|
||||
owner.setConnected(true);
|
||||
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
|
||||
return {
|
||||
owner,
|
||||
async nextFetch(): Promise<PendingFetch> {
|
||||
await expect.poll(() => fetches.length).toBeGreaterThan(0);
|
||||
return fetches.shift()!;
|
||||
},
|
||||
live(event: AgentStreamReducerEvent): void {
|
||||
owner.applyStreamEvent(AGENT_ID, event);
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
},
|
||||
/** Answers every catch-up the chat still asks for until it reports itself current. */
|
||||
async settle(daemon: DaemonTimeline): Promise<void> {
|
||||
for (let turn = 0; turn < 20; turn += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(errors).toEqual([]);
|
||||
const next = fetches.shift();
|
||||
if (next) next.deliver(daemon.page(next.request));
|
||||
else if (owner.getAgentTimelineStatus(AGENT_ID) === "ready") return;
|
||||
}
|
||||
throw new Error("The chat never caught up");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function rows(): Array<{ kind: StreamItem["kind"]; text: string }> {
|
||||
const session = useSessionStore.getState().sessions[SERVER_ID];
|
||||
return [
|
||||
...(session?.agentStreamTail.get(AGENT_ID) ?? []),
|
||||
...(session?.agentStreamHead.get(AGENT_ID) ?? []),
|
||||
].map((entry) => ({
|
||||
kind: entry.kind,
|
||||
text: "text" in entry && typeof entry.text === "string" ? entry.text : "",
|
||||
}));
|
||||
}
|
||||
|
||||
const reply = (words: number) =>
|
||||
Array.from({ length: words }, (_unused, index) => `word${index}`).join(" ");
|
||||
const chunk = (index: number) => `${index === 0 ? "" : " "}word${index}`;
|
||||
const replyChunk = (index: number): AgentTimelineItem => ({
|
||||
type: "assistant_message",
|
||||
text: chunk(index),
|
||||
messageId: "reply-1",
|
||||
});
|
||||
|
||||
/**
|
||||
* Opens the chat while its timeline is empty, then drops the connection while the prompt,
|
||||
* an optional thought and the first three reply chunks are recorded.
|
||||
*/
|
||||
async function goOfflineWhileTheReplyStarts(input: {
|
||||
reasoning: boolean;
|
||||
storage: TimelineReplicaStorage;
|
||||
}) {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const daemon = new DaemonTimeline();
|
||||
const chat = openChat(input.storage);
|
||||
const opened = await chat.nextFetch();
|
||||
opened.deliver(daemon.page(opened.request));
|
||||
expect(
|
||||
selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID),
|
||||
).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" });
|
||||
|
||||
chat.owner.setConnected(false);
|
||||
daemon.record({ type: "user_message", text: PROMPT, messageId: "prompt-1" });
|
||||
if (input.reasoning) daemon.record({ type: "reasoning", text: THOUGHT });
|
||||
for (const index of [0, 1, 2]) daemon.record(replyChunk(index));
|
||||
chat.owner.setConnected(true);
|
||||
const catchUp = await chat.nextFetch();
|
||||
return { daemon, chat, catchUp };
|
||||
}
|
||||
|
||||
function expectedRows(reasoning: boolean, words: number) {
|
||||
return [
|
||||
{ kind: "user_message", text: PROMPT },
|
||||
...(reasoning ? [{ kind: "thought", text: THOUGHT }] : []),
|
||||
{ kind: "assistant_message", text: reply(words) },
|
||||
];
|
||||
}
|
||||
|
||||
/** A saved range that starts after the prompt claims history the chat never received. */
|
||||
function expectCoverageFromTheFirstRow(commits: CachedTimeline[]): void {
|
||||
expect(commits.map((commit) => commit.range?.startSeq ?? 1)).toEqual(commits.map(() => 1));
|
||||
}
|
||||
|
||||
it.each([true, false])(
|
||||
"keeps the prompt and the whole reply when live chunks arrive before a page that holds them (reasoning=%s)",
|
||||
async (reasoning) => {
|
||||
const commits: CachedTimeline[] = [];
|
||||
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
|
||||
reasoning,
|
||||
storage: {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
},
|
||||
});
|
||||
try {
|
||||
chat.live(daemon.record(replyChunk(3)));
|
||||
chat.live(daemon.record(replyChunk(4)));
|
||||
catchUp.deliver(daemon.page(catchUp.request));
|
||||
chat.live(daemon.record(replyChunk(5)));
|
||||
await chat.settle(daemon);
|
||||
|
||||
expect(rows()).toEqual(expectedRows(reasoning, 6));
|
||||
expectCoverageFromTheFirstRow(commits);
|
||||
} finally {
|
||||
chat.owner.dispose();
|
||||
}
|
||||
|
||||
// The saved chat paints the same rows after a reload.
|
||||
const saved = commits.at(-1);
|
||||
useSessionStore.getState().clearSession(SERVER_ID);
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const reopened = createOwner({
|
||||
readTimeline: async () => saved,
|
||||
commitTimeline: () => undefined,
|
||||
});
|
||||
try {
|
||||
reopened.replaceVisibleAgentIds("test", [AGENT_ID]);
|
||||
await expect.poll(rows).toEqual(expectedRows(reasoning, 6));
|
||||
} finally {
|
||||
reopened.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the prompt when the page already holds a chunk the chat has not seen live", async () => {
|
||||
const commits: CachedTimeline[] = [];
|
||||
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
|
||||
reasoning: true,
|
||||
storage: {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
},
|
||||
});
|
||||
try {
|
||||
chat.live(daemon.record(replyChunk(3)));
|
||||
const notYetLive = daemon.record(replyChunk(4));
|
||||
catchUp.deliver(daemon.page(catchUp.request));
|
||||
chat.live(notYetLive);
|
||||
chat.live(daemon.record(replyChunk(5)));
|
||||
await chat.settle(daemon);
|
||||
|
||||
expect(rows()).toEqual(expectedRows(true, 6));
|
||||
expectCoverageFromTheFirstRow(commits);
|
||||
} finally {
|
||||
chat.owner.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("finishes the reply when its last chunks arrive while an older page is in flight", async () => {
|
||||
const commits: CachedTimeline[] = [];
|
||||
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
|
||||
reasoning: true,
|
||||
storage: {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
},
|
||||
});
|
||||
try {
|
||||
const olderPage = daemon.page(catchUp.request);
|
||||
chat.live(daemon.record(replyChunk(3)));
|
||||
chat.live(daemon.record(replyChunk(4)));
|
||||
catchUp.deliver(olderPage);
|
||||
await chat.settle(daemon);
|
||||
|
||||
expect(rows()).toEqual(expectedRows(true, 5));
|
||||
expectCoverageFromTheFirstRow(commits);
|
||||
} finally {
|
||||
chat.owner.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function createSqliteCache() {
|
||||
const database = new DatabaseSync(":memory:");
|
||||
let beforeRead = async () => {};
|
||||
|
||||
@@ -53,7 +53,6 @@ it.each([false, true])(
|
||||
(hasAuthoritativeBaseline) => {
|
||||
let head: StreamItem[] = [];
|
||||
let tail: StreamItem[] = [];
|
||||
let cursor: TimelineCursor | undefined;
|
||||
for (const [index, turnId] of ["turn-1", "turn-2"].entries()) {
|
||||
const result = processAgentStreamEvent({
|
||||
event: {
|
||||
@@ -66,13 +65,12 @@ it.each([false, true])(
|
||||
epoch: "epoch-1",
|
||||
currentTail: tail,
|
||||
currentHead: head,
|
||||
currentCursor: cursor,
|
||||
currentCursor: undefined,
|
||||
timestamp: new Date(1000),
|
||||
hasAuthoritativeBaseline,
|
||||
});
|
||||
head = result.head;
|
||||
tail = result.tail;
|
||||
cursor = result.cursor ?? cursor;
|
||||
}
|
||||
expect([...tail, ...head]).toMatchObject([
|
||||
{ kind: "thought", text: "turn-1", turnId: "turn-1" },
|
||||
@@ -2850,7 +2848,7 @@ describe("processTimelineResponse", () => {
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 },
|
||||
currentCursor: undefined,
|
||||
});
|
||||
expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([
|
||||
"First paragraph.\n\nSecond paragraph.",
|
||||
@@ -3679,7 +3677,6 @@ describe("processAgentStreamEvent", () => {
|
||||
event: makeAssistantTimelineEvent("[System Error] failed"),
|
||||
epoch: "timeline-1",
|
||||
seq: 42,
|
||||
currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 },
|
||||
});
|
||||
|
||||
expect(result.head).toEqual([
|
||||
@@ -3900,24 +3897,6 @@ describe("processAgentStreamEvent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("catches up from the first row when a chat that was empty receives a later row", () => {
|
||||
const result = processAgentStreamEvent({
|
||||
...baseStreamInput,
|
||||
event: makeTimelineEvent("word3"),
|
||||
seq: 6,
|
||||
epoch: "epoch-1",
|
||||
currentCursor: undefined,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
head: [],
|
||||
changedHead: false,
|
||||
cursor: null,
|
||||
cursorChanged: false,
|
||||
sideEffects: [{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 0 } }],
|
||||
});
|
||||
});
|
||||
|
||||
it("renders a live row over painted items without creating an authoritative cursor", () => {
|
||||
const result = processAgentStreamEvent({
|
||||
...baseStreamInput,
|
||||
@@ -4108,7 +4087,7 @@ describe("processAgentStreamEvents", () => {
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 },
|
||||
currentCursor: undefined,
|
||||
});
|
||||
|
||||
expect(result.changedTail).toBe(false);
|
||||
@@ -4282,7 +4261,6 @@ describe("processAgentStreamEvents", () => {
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
hasAuthoritativeBaseline: false,
|
||||
timestamp: new Date("2026-05-02T10:00:00.186Z"),
|
||||
});
|
||||
|
||||
@@ -4484,7 +4462,7 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
const scheduler = createManualScheduler();
|
||||
let currentTail: StreamItem[] = [];
|
||||
let currentHead: StreamItem[] = [];
|
||||
let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 };
|
||||
let currentCursor: TimelineCursor | undefined;
|
||||
|
||||
const queue = createAgentStreamReducerQueue({
|
||||
getSnapshot: () => ({
|
||||
@@ -4527,7 +4505,7 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]);
|
||||
expect(currentCursor).toEqual({
|
||||
epoch: "epoch-1",
|
||||
startSeq: 1,
|
||||
startSeq: 2,
|
||||
endSeq: 4,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -289,10 +289,7 @@ function classifySessionTimelineSeq({
|
||||
seq: number;
|
||||
}): SessionTimelineSeqDecision {
|
||||
if (!cursor) {
|
||||
// A synced chat without coverage was empty when it last caught up. Only an epoch's
|
||||
// first row can start coverage; a later row means rows before it were missed, for
|
||||
// example while offline, and a cursor started there would hide them from catch-up.
|
||||
return seq === 1 ? "init" : "gap";
|
||||
return "init";
|
||||
}
|
||||
if (cursor.epoch !== epoch) {
|
||||
return "drop_epoch";
|
||||
@@ -1546,14 +1543,14 @@ function processTimelineSequencingGate(input: {
|
||||
return {
|
||||
...base,
|
||||
shouldApplyStreamEvent: false,
|
||||
sideEffects: [
|
||||
{
|
||||
type: "catch_up",
|
||||
cursor: currentCursor
|
||||
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
|
||||
: { epoch, endSeq: 0 },
|
||||
},
|
||||
],
|
||||
sideEffects: currentCursor
|
||||
? [
|
||||
{
|
||||
type: "catch_up",
|
||||
cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
if (decision === "drop_epoch" && seq === 1) {
|
||||
|
||||
@@ -64,21 +64,6 @@ export function planTimelineResumeFetch(
|
||||
: planTimelineTailFetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* A catch-up that waited behind another starts after the rows applied meanwhile. A forward
|
||||
* page is applied row by row, so asking again for rows the chat already holds repeats them.
|
||||
*/
|
||||
export function planTimelineCatchUpPastApplied(
|
||||
request: ProjectedTimelineForwardFetchPlan,
|
||||
applied: { epoch: string; endSeq: number } | undefined,
|
||||
): ProjectedTimelineForwardFetchPlan {
|
||||
if (request.direction !== "after" || !applied) return request;
|
||||
if (applied.epoch !== request.cursor.epoch || applied.endSeq <= request.cursor.seq) {
|
||||
return request;
|
||||
}
|
||||
return planTimelineCatchUpAfter({ epoch: applied.epoch, seq: applied.endSeq });
|
||||
}
|
||||
|
||||
export function planTimelineOlderFetch(cursor: TimelineSyncCursor) {
|
||||
return {
|
||||
direction: "before",
|
||||
|
||||
@@ -441,96 +441,6 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
});
|
||||
|
||||
test("a gap parked behind a running tail resumes after the rows that tail applied", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
(await world.nextMembership()).succeed();
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 7 });
|
||||
tail.respond({ hasNewer: false, seq: 7 });
|
||||
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
expect(recovery.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 7 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
recovery.respond({ hasNewer: false, seq: 7 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("a chat without coverage that recovers a gap loads the latest tail when history overflows a page", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
(await world.nextMembership()).succeed();
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
|
||||
tail.respond({ hasNewer: false, seq: 0 });
|
||||
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
expect(recovery.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 0 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
recovery.respond({ hasNewer: true, seq: 40 });
|
||||
|
||||
const fallback = await world.nextFetch("agent-a");
|
||||
expect(fallback.request).toEqual({
|
||||
direction: "tail",
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
fallback.respond({ hasNewer: false, seq: 90 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("a recovery's follow-up page starts after rows another fetch applied meanwhile", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
(await world.nextMembership()).succeed();
|
||||
(await world.nextFetch("agent-a")).respond({ hasNewer: false, seq: 0 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
|
||||
const firstPage = await world.nextFetch("agent-a");
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 40 });
|
||||
firstPage.respond({ hasNewer: true, seq: 40 });
|
||||
const latestTail = await world.nextFetch("agent-a");
|
||||
expect(latestTail.request.direction).toBe("tail");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 40 });
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 300 });
|
||||
latestTail.respond({ hasNewer: false, seq: 300 });
|
||||
recovery.respond({ hasNewer: true, seq: 80 });
|
||||
|
||||
const followUp = await world.nextFetch("agent-a");
|
||||
expect(followUp.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 300 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
followUp.respond({ hasNewer: false, seq: 300 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("reports a chat current only once its parked follow-up page completes", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
@@ -975,8 +885,7 @@ test("gap recovery supersedes completed catch-up and pages through the current t
|
||||
const membership = await world.nextMembership();
|
||||
membership.succeed();
|
||||
const initial = await world.nextFetch("agent-a");
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
initial.respond({ hasNewer: false, seq: 10 });
|
||||
initial.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
planTimelineCatchUpAfter,
|
||||
planTimelineCatchUpPastApplied,
|
||||
planTimelineResumeFetch,
|
||||
type ProjectedTimelineForwardFetchPlan,
|
||||
} from "./timeline-sync-plan";
|
||||
@@ -742,10 +741,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
await fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
false,
|
||||
);
|
||||
return;
|
||||
@@ -823,10 +819,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
ensureCacheLoaded(agentId);
|
||||
return;
|
||||
}
|
||||
const applied = ports.readCursor(agentId);
|
||||
const nextRequest = request
|
||||
? planTimelineCatchUpPastApplied(request, applied)
|
||||
: planTimelineResumeFetch(applied);
|
||||
const nextRequest = request ?? planTimelineResumeFetch(ports.readCursor(agentId));
|
||||
const current = catchUps.get(agentId);
|
||||
const decision = decideCatchUp({ current, request: nextRequest, supersede });
|
||||
if (decision === "keep-and-park") {
|
||||
@@ -840,13 +833,11 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
catchUpGenerations.set(agentId, generation);
|
||||
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
|
||||
pendingCatchUps.delete(agentId);
|
||||
// A gap recovery pages forward to keep the coverage it extends. Without coverage there is
|
||||
// nothing to keep, so an overflowing page falls back to the latest tail, as a resume does.
|
||||
void fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
nextRequest,
|
||||
nextRequest.direction === "after" && (request === undefined || applied === undefined),
|
||||
request === undefined && nextRequest.direction === "after",
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -73,18 +73,6 @@ describe("desktop-badge-state", () => {
|
||||
expect(selectMacDockBadgeCount(state)).toBe(3);
|
||||
});
|
||||
|
||||
it("leaves out background workspaces, which the sidebar hides", () => {
|
||||
const hidden = { ...workspace("a", "attention"), background: true };
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden))).toBeUndefined();
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden, workspace("b", "failed")))).toBe(1);
|
||||
});
|
||||
|
||||
it("counts background workspaces while Show background puts them in the sidebar", () => {
|
||||
const hidden = { ...workspace("a", "attention"), background: true };
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden), { showBackground: true })).toBe(1);
|
||||
expect(createMacDockBadgeCountSelector({ showBackground: true })(stateWith(hidden))).toBe(1);
|
||||
});
|
||||
|
||||
it("recounts only when a workspace map is replaced", () => {
|
||||
const select = createMacDockBadgeCountSelector();
|
||||
const state = stateWith(workspace("a", "attention"));
|
||||
|
||||
@@ -19,21 +19,11 @@ export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspa
|
||||
* The macOS dock badge only needs a count, so count here instead of materialising every
|
||||
* workspace status and comparing the whole list on every store write.
|
||||
*/
|
||||
export interface DockBadgeOptions {
|
||||
/** Count background workspaces too, as the sidebar shows them while Show background is on. */
|
||||
showBackground?: boolean;
|
||||
}
|
||||
|
||||
export function selectMacDockBadgeCount(
|
||||
state: WorkspaceStatusSource,
|
||||
options: DockBadgeOptions = {},
|
||||
): number | undefined {
|
||||
export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined {
|
||||
let actionableCount = 0;
|
||||
for (const session of Object.values(state.sessions)) {
|
||||
if (!session) continue;
|
||||
for (const workspace of session.workspaces.values()) {
|
||||
// A hidden background workspace would leave the badge pointing at nothing in the sidebar.
|
||||
if (workspace.background && !options.showBackground) continue;
|
||||
if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1;
|
||||
}
|
||||
}
|
||||
@@ -41,11 +31,11 @@ export function selectMacDockBadgeCount(
|
||||
}
|
||||
|
||||
/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */
|
||||
export function createMacDockBadgeCountSelector(
|
||||
options: DockBadgeOptions = {},
|
||||
): (state: WorkspaceStatusSource) => number | undefined {
|
||||
export function createMacDockBadgeCountSelector(): (
|
||||
state: WorkspaceStatusSource,
|
||||
) => number | undefined {
|
||||
return memoizeOnSessionMaps<WorkspaceStatusSession, WorkspaceStatusSource, number | undefined>(
|
||||
(session) => [session.workspaces],
|
||||
(state) => selectMacDockBadgeCount(state, options),
|
||||
(session) => session.workspaces,
|
||||
selectMacDockBadgeCount,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status";
|
||||
|
||||
function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
@@ -14,21 +14,7 @@ function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
}
|
||||
|
||||
function stateWith(...agents: Agent[]) {
|
||||
return stateWithWorkspaces([], ...agents);
|
||||
}
|
||||
|
||||
function stateWithWorkspaces(
|
||||
workspaces: Array<Pick<WorkspaceDescriptor, "id" | "background">>,
|
||||
...agents: Agent[]
|
||||
) {
|
||||
return {
|
||||
sessions: {
|
||||
srv: {
|
||||
agents: new Map(agents.map((entry) => [entry.id, entry])),
|
||||
workspaces: new Map(workspaces.map((entry) => [entry.id, entry])),
|
||||
},
|
||||
},
|
||||
};
|
||||
return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } };
|
||||
}
|
||||
|
||||
describe("deriveFaviconStatus", () => {
|
||||
@@ -64,37 +50,6 @@ describe("deriveFaviconStatus", () => {
|
||||
),
|
||||
).toBe("none");
|
||||
});
|
||||
|
||||
it("ignores agents in background workspaces, which the sidebar hides", () => {
|
||||
const hidden = { id: "ws-hidden", background: true };
|
||||
expect(
|
||||
deriveFaviconStatus(
|
||||
stateWithWorkspaces(
|
||||
[hidden],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
agent({ id: "b", workspaceId: "ws-hidden", status: "running" }),
|
||||
),
|
||||
),
|
||||
).toBe("none");
|
||||
expect(
|
||||
deriveFaviconStatus(
|
||||
stateWithWorkspaces(
|
||||
[hidden, { id: "ws-shown", background: false }],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", status: "running" }),
|
||||
agent({ id: "b", workspaceId: "ws-shown", requiresAttention: true }),
|
||||
),
|
||||
),
|
||||
).toBe("attention");
|
||||
});
|
||||
|
||||
it("counts agents in background workspaces while Show background puts them in the sidebar", () => {
|
||||
const state = stateWithWorkspaces(
|
||||
[{ id: "ws-hidden", background: true }],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
);
|
||||
expect(deriveFaviconStatus(state, { showBackground: true })).toBe("attention");
|
||||
expect(createFaviconStatusSelector({ showBackground: true })(state)).toBe("attention");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createFaviconStatusSelector", () => {
|
||||
@@ -108,18 +63,6 @@ describe("createFaviconStatusSelector", () => {
|
||||
expect(select({ sessions: { ...state.sessions } })).toBe("running");
|
||||
});
|
||||
|
||||
it("rescans when a workspace map is replaced", () => {
|
||||
const select = createFaviconStatusSelector();
|
||||
const state = stateWithWorkspaces(
|
||||
[],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
);
|
||||
expect(select(state)).toBe("attention");
|
||||
// The agent synced before its workspace; only the workspace map changes.
|
||||
const workspaces = new Map([["ws-hidden", { id: "ws-hidden", background: true }]]);
|
||||
expect(select({ sessions: { srv: { ...state.sessions.srv, workspaces } } })).toBe("none");
|
||||
});
|
||||
|
||||
it("rescans when an agent map is replaced", () => {
|
||||
const select = createFaviconStatusSelector();
|
||||
expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running");
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import { memoizeOnSessionMaps } from "./memoize-on-session-maps";
|
||||
|
||||
export type FaviconStatus = "none" | "running" | "attention";
|
||||
|
||||
interface FaviconAgentSession {
|
||||
agents: ReadonlyMap<string, Agent>;
|
||||
workspaces: ReadonlyMap<string, Pick<WorkspaceDescriptor, "background">>;
|
||||
}
|
||||
|
||||
interface FaviconAgentSource {
|
||||
@@ -17,22 +16,13 @@ interface FaviconAgentSource {
|
||||
* three states here instead of building the aggregated agent list: the list allocates a
|
||||
* projection per agent, deep-compares it and sorts every agent on the host on each update.
|
||||
*/
|
||||
export interface FaviconStatusOptions {
|
||||
/** Count agents in background workspaces too, as the sidebar shows them while Show background is on. */
|
||||
showBackground?: boolean;
|
||||
}
|
||||
|
||||
export function deriveFaviconStatus(
|
||||
state: FaviconAgentSource,
|
||||
options: FaviconStatusOptions = {},
|
||||
): FaviconStatus {
|
||||
export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
|
||||
let hasAttention = false;
|
||||
let hasNeedsInput = false;
|
||||
for (const session of Object.values(state.sessions)) {
|
||||
if (!session) continue;
|
||||
for (const agent of session.agents.values()) {
|
||||
if (agent.background || agent.archivedAt) continue;
|
||||
if (!options.showBackground && isInBackgroundWorkspace(agent, session)) continue;
|
||||
if (agent.status === "running") return "running";
|
||||
if (agent.requiresAttention) hasAttention = true;
|
||||
if (agent.pendingPermissions.length > 0) hasNeedsInput = true;
|
||||
@@ -41,16 +31,10 @@ export function deriveFaviconStatus(
|
||||
return hasAttention || hasNeedsInput ? "attention" : "none";
|
||||
}
|
||||
|
||||
function isInBackgroundWorkspace(agent: Agent, session: FaviconAgentSession): boolean {
|
||||
return agent.workspaceId ? session.workspaces.get(agent.workspaceId)?.background === true : false;
|
||||
}
|
||||
|
||||
/** A session-store selector for the favicon status that rescans only when an agent or workspace map changes. */
|
||||
export function createFaviconStatusSelector(
|
||||
options: FaviconStatusOptions = {},
|
||||
): (state: FaviconAgentSource) => FaviconStatus {
|
||||
/** A session-store selector for the favicon status that rescans only when an agent map changes. */
|
||||
export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus {
|
||||
return memoizeOnSessionMaps<FaviconAgentSession, FaviconAgentSource, FaviconStatus>(
|
||||
(session) => [session.agents, session.workspaces],
|
||||
(state) => deriveFaviconStatus(state, options),
|
||||
(session) => session.agents,
|
||||
deriveFaviconStatus,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,18 +4,18 @@ interface SessionsSource<TSession> {
|
||||
|
||||
/**
|
||||
* Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has
|
||||
* changed. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* a reference check per host instead of a walk over every entry.
|
||||
*/
|
||||
export function memoizeOnSessionMaps<TSession, TState extends SessionsSource<TSession>, TResult>(
|
||||
pickMaps: (session: TSession) => readonly unknown[],
|
||||
pickMap: (session: TSession) => unknown,
|
||||
derive: (state: TState) => TResult,
|
||||
): (state: TState) => TResult {
|
||||
let previousMaps: unknown[] | null = null;
|
||||
let previousResult: TResult;
|
||||
return (state) => {
|
||||
const maps = Object.values(state.sessions).flatMap((session) =>
|
||||
session ? pickMaps(session) : [undefined],
|
||||
const maps = Object.values(state.sessions).map((session) =>
|
||||
session ? pickMap(session) : undefined,
|
||||
);
|
||||
if (
|
||||
previousMaps &&
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user