mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-24 17:25:24 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a796e760e9 | ||
|
|
47bcf6e609 | ||
|
|
5b82167872 | ||
|
|
9e1b53c4e9 | ||
|
|
8a892ed4a7 | ||
|
|
40c5accf2a |
@@ -552,7 +552,6 @@
|
||||
"packages/app/src/components/download-toast.tsx",
|
||||
"packages/app/src/components/file-explorer-pane.tsx",
|
||||
"packages/app/src/components/headers/back-header.tsx",
|
||||
"packages/app/src/components/highlighted-code-block.tsx",
|
||||
"packages/app/src/components/hosts/host-filter.tsx",
|
||||
"packages/app/src/components/hosts/host-picker.tsx",
|
||||
"packages/app/src/components/import-session-sheet.tsx",
|
||||
|
||||
@@ -1,25 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 0.17.4 - 2026-11-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android ([#10499](https://github.com/getpaseo/paseo/pull/10499))
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning ([#10586](https://github.com/getpaseo/paseo/pull/10586))
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system ([#10555](https://github.com/getpaseo/paseo/pull/10555) by [@yzim](https://github.com/yzim))
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn ([#10611](https://github.com/getpaseo/paseo/pull/10611) by [@thomasvan](https://github.com/thomasvan))
|
||||
- Fixed Hermes Shell rows omitting part of the command ([#10614](https://github.com/getpaseo/paseo/pull/10614))
|
||||
- Fixed OpenCode Go usage for logins stored in the OpenCode 2 database, including Console sign-ins and API keys ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612))
|
||||
- Fixed existing OpenCode sessions failing to reopen after Paseo tool definitions change ([#10533](https://github.com/getpaseo/paseo/pull/10533) by [@Peanut-HZM](https://github.com/Peanut-HZM))
|
||||
- Fixed Paseo tools missing from agents that use MCP protocol version `2026-07-28` ([#10558](https://github.com/getpaseo/paseo/pull/10558) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed Codex MCP startup failures missing from daemon warning logs ([#10566](https://github.com/getpaseo/paseo/pull/10566))
|
||||
- Fixed the daemon exiting when it closes a session after the plugin process has stopped ([#10585](https://github.com/getpaseo/paseo/pull/10585))
|
||||
- Fixed Git commands selecting the wrong repository when a directory has the layout of a bare repository ([#10587](https://github.com/getpaseo/paseo/pull/10587))
|
||||
- Fixed Claude Auto permission mode being unavailable on Bedrock and Vertex ([#6904](https://github.com/getpaseo/paseo/pull/6904))
|
||||
- Fixed the sidebar host settings button requiring two clicks to open settings ([#10562](https://github.com/getpaseo/paseo/pull/10562) by [@ShalokShalom](https://github.com/ShalokShalom))
|
||||
- Fixed the Changes pane not offering Push for a new branch that was never pushed in a regular checkout ([#10631](https://github.com/getpaseo/paseo/pull/10631))
|
||||
- Fixed the daemon using the wrong model catalog when Hub sends a workspace directory for trigger validation ([#10582](https://github.com/getpaseo/paseo/pull/10582))
|
||||
|
||||
## 0.17.3 - 2026-11-22
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,25 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 0.17.4 - 2026-11-23
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 Android 上嵌套编号列表的编号与正文重叠,以及列表中的引用与后续消息重叠的问题 ([#10499](https://github.com/getpaseo/paseo/pull/10499))
|
||||
- 修复 Android 终端输入,要求键盘不将输入内容用于个性化学习 ([#10586](https://github.com/getpaseo/paseo/pull/10586))
|
||||
- 修复在不区分大小写的文件系统上,目录路径大小写不一致导致对话消失的问题 ([#10555](https://github.com/getpaseo/paseo/pull/10555),贡献者:[@yzim](https://github.com/yzim))
|
||||
- 修复发给已归档 Agent 的中断和引导消息进入队列后未启动新轮次的问题 ([#10611](https://github.com/getpaseo/paseo/pull/10611),贡献者:[@thomasvan](https://github.com/thomasvan))
|
||||
- 修复 Hermes 的 Shell 工具行只显示命令摘要的问题,现在会显示完整命令 ([#10614](https://github.com/getpaseo/paseo/pull/10614))
|
||||
- 修复使用 OpenCode 2 数据库中保存的登录凭据时的 Go 用量显示,涵盖 Console 登录和 API 密钥 ([#8729](https://github.com/getpaseo/paseo/pull/8729), [#10612](https://github.com/getpaseo/paseo/pull/10612))
|
||||
- 修复 Paseo 工具定义变更后无法重新打开已有 OpenCode 会话的问题 ([#10533](https://github.com/getpaseo/paseo/pull/10533),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM))
|
||||
- 修复使用 MCP 协议版本 `2026-07-28` 的 Agent 缺少 Paseo 工具的问题 ([#10558](https://github.com/getpaseo/paseo/pull/10558),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复 Codex MCP 启动失败时 daemon 未记录警告的问题 ([#10566](https://github.com/getpaseo/paseo/pull/10566))
|
||||
- 修复插件进程停止后 daemon 在关闭会话时退出的问题 ([#10585](https://github.com/getpaseo/paseo/pull/10585))
|
||||
- 修复目录结构与裸仓库相同时 Git 命令选错仓库的问题 ([#10587](https://github.com/getpaseo/paseo/pull/10587))
|
||||
- 修复在 Bedrock 和 Vertex 上无法选择 Claude Auto 权限模式的问题 ([#6904](https://github.com/getpaseo/paseo/pull/6904))
|
||||
- 修复侧边栏的主机设置按钮需要点击两次才能打开设置的问题 ([#10562](https://github.com/getpaseo/paseo/pull/10562),贡献者:[@ShalokShalom](https://github.com/ShalokShalom))
|
||||
- 修复普通检出中从未推送过的新分支在“变更”面板中不显示“推送”的问题 ([#10631](https://github.com/getpaseo/paseo/pull/10631))
|
||||
- 修复 Hub 在验证触发器时传入工作区目录后,daemon 使用错误模型目录的问题 ([#10582](https://github.com/getpaseo/paseo/pull/10582))
|
||||
|
||||
## 0.17.3 - 2026-11-22
|
||||
|
||||
### 修复
|
||||
|
||||
@@ -514,7 +514,7 @@ The [Agent Client Protocol (ACP)](https://agentclientprotocol.com) is an open st
|
||||
|
||||
ACP agents communicate over JSON-RPC 2.0 on stdio. Paseo spawns the agent process and talks to it through stdin/stdout.
|
||||
|
||||
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Goose, Hermes, and Hoplite activate their [bundled providers](plugins.md#built-in-plugins) instead. An existing `extends: "acp"` entry for goose or Hermes migrates to the bundled provider on load and keeps a custom command. Hermes agents saved with the old adapter resume with their mode translated (`plugins/hermes-provider/server/legacy-modes.ts`).
|
||||
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead.
|
||||
|
||||
### Adding a generic ACP provider
|
||||
|
||||
@@ -627,6 +627,32 @@ ACP probes use short timeouts and browser-suppression environment variables so a
|
||||
|
||||
Ref: [Gemini CLI ACP mode docs](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/acp-mode.md)
|
||||
|
||||
### Example: Hermes (Nous Research)
|
||||
|
||||
[Hermes](https://github.com/NousResearch/hermes-agent) is an open-source coding agent by Nous Research with persistent memory and multi-provider LLM support. It supports ACP via the `acp` subcommand.
|
||||
|
||||
1. Install: `curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash`
|
||||
2. Install ACP support: `pip install -e '.[acp]'`
|
||||
3. Configure Hermes credentials in `~/.hermes/`
|
||||
4. Add to config.json:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"providers": {
|
||||
"hermes": {
|
||||
"extends": "acp",
|
||||
"label": "Hermes",
|
||||
"description": "Nous Research self-improving AI agent",
|
||||
"command": ["hermes", "acp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ref: [Hermes ACP docs](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp)
|
||||
|
||||
### How ACP providers work in Paseo
|
||||
|
||||
When you launch an agent with an ACP provider:
|
||||
@@ -827,6 +853,12 @@ A config.json with multiple custom providers:
|
||||
"extends": "acp",
|
||||
"label": "Google Gemini",
|
||||
"command": ["gemini", "--acp"]
|
||||
},
|
||||
|
||||
"hermes": {
|
||||
"extends": "acp",
|
||||
"label": "Hermes",
|
||||
"command": ["hermes", "acp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,11 @@ 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 fork 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. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
|
||||
|
||||
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
|
||||
|
||||
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 fork 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. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
|
||||
The fork 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.
|
||||
|
||||
@@ -55,4 +59,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
|
||||
|
||||
## Verification
|
||||
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
|
||||
+3
-7
@@ -118,7 +118,7 @@ appear in the plugin catalog. Editing one in development requires a daemon resta
|
||||
Directory, Git, and npm installs cannot use a built-in ID.
|
||||
|
||||
A provider registration with `requiresConfiguration: true` participates only while its ID exists
|
||||
under `agents.providers`. Hoplite, fx, goose, and Hermes use this for catalog opt-in. Add writes `{ "enabled": true }`
|
||||
under `agents.providers`. Hoplite and fx use this for catalog opt-in. Add writes `{ "enabled": true }`
|
||||
without `extends`, so it selects the bundled adapter. Remove deletes the config entry; setting
|
||||
`enabled: false` keeps the entry. The bundled JavaScript still loads at startup, but an absent
|
||||
provider does not enter executable resolution or catalog discovery.
|
||||
@@ -583,12 +583,8 @@ daemon launch from `connect` and the per-session env and MCP servers from `sessi
|
||||
no provider reload input.
|
||||
|
||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
whole provider event stream. A `toolCall` transformer sees the raw `input`, `output` and `content`, and a
|
||||
`detail` it sets replaces the standard row. Parse vendor display text defensively and return the call
|
||||
unchanged when the shape does not match, so an upstream format change falls back to the standard row
|
||||
(`plugins/hermes-provider/server/terminal-command.ts`). The shim uses the resolved launch for every probe and session, overlaying
|
||||
`@getpaseo/plugin/server/acp`. Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
whole provider event stream. The shim uses the resolved launch for every probe and session, overlaying
|
||||
only the supplied per-session env for sessions. The direct and ACP examples live in
|
||||
`plugin-examples/provider-direct`
|
||||
and `plugin-examples/provider-acp-transformer`.
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -1,7 +0,0 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -1,7 +0,0 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -1,7 +0,0 @@
|
||||
Fixed
|
||||
- Fixed numbered sublists overlapping their text and quotes inside lists overlapping later messages on Android
|
||||
- Fixed Android terminal input so it asks the keyboard to exclude typed text from personalized learning
|
||||
- Fixed conversations disappearing when directory capitalization differs on a case-insensitive file system
|
||||
- Fixed interrupt and steer messages to archived agents being queued without starting a turn
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
sha256-W725BRG14xajMsR4t8Y3NmxppMnJ8AUd7Kdb6F7LmMw=
|
||||
|
||||
Generated
+29
-29
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37541,7 +37541,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39694,13 +39694,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/server": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/server": "0.17.3",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39947,11 +39947,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39963,7 +39963,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40206,7 +40206,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40252,7 +40252,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40282,7 +40282,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40290,8 +40290,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40301,8 +40301,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40324,7 +40324,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40351,7 +40351,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40367,7 +40367,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40589,17 +40589,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/highlight": "0.17.4",
|
||||
"@getpaseo/plugin": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/highlight": "0.17.3",
|
||||
"@getpaseo/plugin": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
@@ -41549,7 +41549,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43160,7 +43160,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -757,6 +757,161 @@ test("pasting an assistant selection preserves literal underscores and authored
|
||||
}
|
||||
});
|
||||
|
||||
const QUOTE_BODY = [
|
||||
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
|
||||
"",
|
||||
"> Nested reply.",
|
||||
"",
|
||||
"```ts",
|
||||
"const quoted = 1;",
|
||||
"```",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" Start --> Done",
|
||||
"```",
|
||||
"",
|
||||
"Thanks!",
|
||||
].join("\n");
|
||||
|
||||
const QUOTE_MARKDOWN = [
|
||||
"Text before the quote.",
|
||||
"",
|
||||
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
|
||||
"",
|
||||
"> [!NOTE]",
|
||||
"> Heads up before you paste.",
|
||||
"",
|
||||
"Text after the quote.",
|
||||
].join("\n");
|
||||
|
||||
function assistantQuote(page: Page, index: number): Locator {
|
||||
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
|
||||
}
|
||||
|
||||
/** A quote's own control is its first, ahead of any nested quote's. */
|
||||
function quoteCopyControl(quote: Locator): Locator {
|
||||
return quote.getByRole("button", { name: "Copy quote" }).first();
|
||||
}
|
||||
|
||||
async function copyQuote(quote: Locator): Promise<void> {
|
||||
await quote.hover();
|
||||
await quoteCopyControl(quote).click();
|
||||
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
|
||||
}
|
||||
|
||||
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
|
||||
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 plain = page.getByRole("textbox", { name: "Plain text paste" });
|
||||
await plain.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
const rich = page.getByRole("textbox", { name: "Rich text paste" });
|
||||
await rich.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
return { plain, rich };
|
||||
}
|
||||
|
||||
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "assistant-quote-copy-",
|
||||
title: "Assistant quote copy",
|
||||
initialPrompt: "Render the quote fixture.",
|
||||
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
|
||||
});
|
||||
|
||||
try {
|
||||
await allowRichClipboard(context);
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await openAgentRoute(page, agent);
|
||||
const quote = assistantQuote(page, 0);
|
||||
const nested = assistantQuote(page, 1);
|
||||
await expect(quote).toContainText("Thanks!");
|
||||
|
||||
await test.step("an admonition has no copy control", async () => {
|
||||
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
|
||||
await expect(
|
||||
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
|
||||
).toHaveCount(2);
|
||||
});
|
||||
|
||||
await test.step("the control appears on hover or keyboard focus", async () => {
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await quote.hover();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await control.focus();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await control.blur();
|
||||
});
|
||||
|
||||
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
|
||||
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
|
||||
await copyQuote(quote);
|
||||
const copied = await readRichClipboard(page);
|
||||
expect(copied.plainText).toBe(QUOTE_BODY);
|
||||
expect(copied.html).toContain("<strong>ship it</strong>");
|
||||
expect(copied.html).toContain("<blockquote>");
|
||||
});
|
||||
|
||||
await test.step("the copy pastes as Markdown and as rich text", async () => {
|
||||
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
|
||||
await expect(plain).toHaveValue(QUOTE_BODY);
|
||||
await expect(rich.locator("strong")).toHaveText("ship it");
|
||||
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com/notes",
|
||||
);
|
||||
await expect(rich).not.toContainText("Text before the quote.");
|
||||
});
|
||||
|
||||
await test.step("a nested quote copies only itself", async () => {
|
||||
await copyQuote(nested);
|
||||
await expect
|
||||
.poll(async () => (await readRichClipboard(page)).plainText)
|
||||
.toBe("Nested reply.");
|
||||
});
|
||||
|
||||
await test.step("a code block in the quote keeps its own copy", async () => {
|
||||
const code = quote.getByText("const quoted = 1;", { exact: true });
|
||||
await code.hover();
|
||||
await quote.getByRole("button", { name: "Copy code" }).first().click();
|
||||
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
|
||||
});
|
||||
|
||||
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
|
||||
await page.mouse.move(0, 0);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
const controlBox = await control.boundingBox();
|
||||
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
|
||||
expect(controlBox && firstLine).toBeTruthy();
|
||||
// The text starts below the control instead of wrapping short of it.
|
||||
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
|
||||
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
|
||||
context,
|
||||
page,
|
||||
|
||||
@@ -471,33 +471,6 @@ test("All changes combines committed and pending edits and preserves an unfinish
|
||||
});
|
||||
});
|
||||
|
||||
test("Changes offers Push for a branch that was never pushed and the push sets its upstream", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await createWorkspaceWithRemote((repoPath) => {
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoPath });
|
||||
});
|
||||
await openWorkspaceChangesSurface(page, workspace);
|
||||
const primary = page.getByTestId("changes-primary-cta");
|
||||
|
||||
await test.step("committing the edit makes Push the primary action", async () => {
|
||||
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
|
||||
commitAllWithGit(workspace.repoPath, "Feature work");
|
||||
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
|
||||
});
|
||||
await test.step("Push sends the branch and sets its upstream", async () => {
|
||||
await primary.click();
|
||||
await expect
|
||||
.poll(() => remoteBranchHead(workspace, "feature"), { timeout: 30_000 })
|
||||
.toBe(localHead(workspace));
|
||||
// git writes the upstream after the remote has the branch, so wait for it too.
|
||||
await expect
|
||||
.poll(() => branchUpstream(workspace, "feature"), { timeout: 30_000 })
|
||||
.toBe("origin/feature");
|
||||
await expect(primary).not.toHaveAccessibleName("Push", { timeout: 30_000 });
|
||||
});
|
||||
});
|
||||
|
||||
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
@@ -2149,68 +2122,6 @@ async function createWorkspaceWithMountedTabDiff(
|
||||
return { id: createdWorkspace.workspace.id, repoPath: repo.path };
|
||||
}
|
||||
|
||||
interface RemoteWorkspace extends DirtyWorkspace {
|
||||
remotePath: string;
|
||||
}
|
||||
|
||||
// A regular checkout with a local bare remote and one uncommitted edit.
|
||||
async function createWorkspaceWithRemote(
|
||||
prepare: (repoPath: string) => void,
|
||||
): Promise<RemoteWorkspace> {
|
||||
const repo = await createTempGitRepo("changes-push-", {
|
||||
withRemote: true,
|
||||
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
|
||||
});
|
||||
const client = await connectSeedClient();
|
||||
cleanupTasks.push({
|
||||
run: async () => {
|
||||
await client.close();
|
||||
await repo.cleanup();
|
||||
},
|
||||
});
|
||||
// The helper keeps the bare remote inside the checkout; keep it out of the status.
|
||||
await writeFile(path.join(repo.path, ".git/info/exclude"), "remote.git/\n");
|
||||
prepare(repo.path);
|
||||
await writeFile(path.join(repo.path, "tracked.ts"), "export const tracked = 2;\n");
|
||||
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
|
||||
if (!created.workspace) {
|
||||
throw new Error(created.error ?? `Failed to create workspace ${repo.path}`);
|
||||
}
|
||||
return {
|
||||
id: created.workspace.id,
|
||||
repoPath: repo.path,
|
||||
remotePath: path.join(repo.path, "remote.git"),
|
||||
};
|
||||
}
|
||||
|
||||
// The app's Commit asks an agent provider for a message, and this harness has none.
|
||||
function commitAllWithGit(repoPath: string, message: string): void {
|
||||
execFileSync("git", ["commit", "-am", message], { cwd: repoPath, stdio: "ignore" });
|
||||
}
|
||||
|
||||
function localHead(workspace: RemoteWorkspace): string {
|
||||
return execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: workspace.repoPath,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
}
|
||||
|
||||
function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string | null {
|
||||
const line = execFileSync("git", ["ls-remote", "--heads", workspace.remotePath, branch], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
return line ? (line.split("\t")[0] ?? null) : null;
|
||||
}
|
||||
|
||||
// Empty until the branch has an upstream.
|
||||
function branchUpstream(workspace: RemoteWorkspace, branch: string): string {
|
||||
return execFileSync(
|
||||
"git",
|
||||
["for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`],
|
||||
{ cwd: workspace.repoPath, encoding: "utf8" },
|
||||
).trim();
|
||||
}
|
||||
|
||||
async function createWorkspaceWithNetDiff(): Promise<DirtyWorkspace> {
|
||||
const repo = await createTempGitRepo("changes-net-", {
|
||||
files: [{ path: "a-tracked.ts", content: "base\n" }],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createAssistantSelectionClipboardContent } from "./content.web";
|
||||
import { createElement as h } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
createAssistantSelectionClipboardContent,
|
||||
createElementClipboardContent,
|
||||
} from "./content.web";
|
||||
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
|
||||
|
||||
const fixture = `
|
||||
<div data-testid="assistant-message">
|
||||
@@ -953,3 +968,158 @@ it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
describe("quote copy", () => {
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement | undefined;
|
||||
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
afterEach(() => {
|
||||
const mounted = root;
|
||||
if (mounted) flushSync(() => mounted.unmount());
|
||||
root = undefined;
|
||||
host?.remove();
|
||||
host = undefined;
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
}
|
||||
const mounted = root;
|
||||
flushSync(() =>
|
||||
mounted.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies a quote's body with its formatting and without the quote marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
|
||||
"Nested reply",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe(
|
||||
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
|
||||
);
|
||||
expect(content?.html).toContain("<strong>team</strong>");
|
||||
expect(content?.html).toContain("<blockquote>");
|
||||
expect(content?.html).not.toContain("Copy quote");
|
||||
});
|
||||
|
||||
it("gives a nested quote its own control that copies only the nested quote", async () => {
|
||||
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
|
||||
const nested = fixtureElement(rendered, "blockquote", 1);
|
||||
|
||||
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
|
||||
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
|
||||
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
|
||||
});
|
||||
|
||||
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
|
||||
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
|
||||
const quote = fixtureElement(rendered, "blockquote");
|
||||
|
||||
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
|
||||
});
|
||||
|
||||
it("copies what a streaming quote shows at the time of the copy", async () => {
|
||||
const first = await renderMarkdown("> First draft", "First draft");
|
||||
const quote = fixtureElement(first, "blockquote");
|
||||
|
||||
const revised = await renderMarkdown("> First draft, revised", "revised");
|
||||
|
||||
expect(fixtureElement(revised, "blockquote")).toBe(quote);
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
|
||||
});
|
||||
|
||||
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
|
||||
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("literal _word_ stays literal");
|
||||
expect(content?.html).toContain("literal _word_ stays literal");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
});
|
||||
|
||||
it("gives an admonition no copy control", async () => {
|
||||
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
|
||||
|
||||
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
|
||||
});
|
||||
|
||||
it("copies a nested admonition as its callout source", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
|
||||
});
|
||||
|
||||
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
rendered.setAttribute("data-testid", "assistant-message");
|
||||
const body = tokenText(rendered, "Do not deploy.");
|
||||
|
||||
expect(
|
||||
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
|
||||
).toBe("deploy.\n\nAfter");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
|
||||
?.plainText,
|
||||
).toBe("Before\n\nWarn");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
|
||||
).not.toContain("[!WARNING]");
|
||||
});
|
||||
|
||||
it("copies a rendered Mermaid diagram as its fence", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
|
||||
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe(
|
||||
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies nothing from a quote that holds only its control", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALT_ATTRIBUTE,
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
|
||||
@@ -91,6 +94,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
} else {
|
||||
turndown.escape = (text) => text;
|
||||
}
|
||||
// An admonition copies as its `> [!TYPE]` source.
|
||||
turndown.addRule("admonition", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
|
||||
replacement: (content, node) => {
|
||||
const type = (node as Element)
|
||||
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
|
||||
.toUpperCase();
|
||||
const body = content.replace(/^\n+|\n+$/g, "");
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -120,6 +134,53 @@ function isWebUrl(href: string): boolean {
|
||||
const markdownTurndown = createTurndown("markdown");
|
||||
const plainTurndown = createTurndown("plain");
|
||||
|
||||
/**
|
||||
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
|
||||
* its source in an attribute. Put the code block back so the fence is what gets copied.
|
||||
*/
|
||||
function restoreFenceSources(container: Element): void {
|
||||
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
|
||||
if (source === null) continue;
|
||||
const pre = document.createElement("pre");
|
||||
const code = document.createElement("code");
|
||||
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
|
||||
if (language) code.className = `language-${language}`;
|
||||
code.textContent = source;
|
||||
pre.append(code);
|
||||
region.replaceWith(pre);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard payload for everything inside `element`, without the element's own syntax:
|
||||
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
|
||||
*/
|
||||
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
|
||||
const container = document.createElement("div");
|
||||
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
|
||||
const originals = element.querySelectorAll("*");
|
||||
const copies = container.querySelectorAll("*");
|
||||
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
|
||||
restoreFenceSources(container);
|
||||
restoreAdmonitions(container);
|
||||
restoreMarkdownElements(container);
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
|
||||
const markdown = markdownTurndown.turndown(container).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);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
export function createAssistantSelectionClipboardContent(
|
||||
selection: Selection | null,
|
||||
): MarkdownClipboardContent | null {
|
||||
@@ -145,17 +206,7 @@ export function createAssistantSelectionClipboardContent(
|
||||
container.append(cloneMarkdownSelection(part.range, part.message));
|
||||
}
|
||||
restoreMarkdownElements(container);
|
||||
|
||||
const markdown = markdownTurndown.turndown(container).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);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -702,6 +753,28 @@ function numberOrderedListItems(list: Element, start: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The library renders an admonition as a box with a generated title. Keep it a quote
|
||||
* with its type, so it copies as its callout source rather than as the title's prose.
|
||||
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
|
||||
* whether it holds the whole callout, so it copies the text it shows.
|
||||
*/
|
||||
function restoreAdmonitions(container: Element): void {
|
||||
const admonitions = Array.from(
|
||||
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
|
||||
);
|
||||
for (const admonition of admonitions.toReversed()) {
|
||||
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.setAttribute(
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
|
||||
);
|
||||
quote.append(...admonition.childNodes);
|
||||
admonition.replaceWith(quote);
|
||||
}
|
||||
}
|
||||
|
||||
function unwrapIncompleteTables(container: HTMLElement): void {
|
||||
for (const table of container.querySelectorAll("table")) {
|
||||
if (hasUsableTableColumnContract(table)) {
|
||||
|
||||
@@ -6,9 +6,13 @@ export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
|
||||
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_FENCE_SOURCE_ATTRIBUTE = "data-paseo-markdown-fence-source";
|
||||
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
|
||||
export const MARKDOWN_COPY_SRC_ATTRIBUTE = "data-paseo-markdown-src";
|
||||
export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
|
||||
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
|
||||
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
|
||||
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
Text,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import React, { useCallback, useMemo, useState } from "react";
|
||||
import { View, Text, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { HighlightToken } from "@getpaseo/highlight";
|
||||
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
|
||||
@@ -85,6 +77,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
[renderedCode, language],
|
||||
);
|
||||
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
@@ -93,7 +86,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
// Copy the code without its trailing blank lines. A fence body ends in a newline,
|
||||
// and ends in more than one when the author left a blank line before the closing
|
||||
// fence; pasting any of them into a terminal runs the last line.
|
||||
const getCode = useCallback(() => code.replace(TRAILING_CODE_LINE_BREAKS, ""), [code]);
|
||||
const copyCode = useCallback(async () => {
|
||||
const content = code.replace(TRAILING_CODE_LINE_BREAKS, "");
|
||||
if (!content) return false;
|
||||
return Clipboard.setStringAsync(content);
|
||||
}, [code]);
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -111,7 +108,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
{renderedCode}
|
||||
</Text>
|
||||
)}
|
||||
<CopyButton getCode={getCode} visible={controlsVisible} />
|
||||
<BlockCopyButton
|
||||
onCopy={copyCode}
|
||||
visible={controlsVisible}
|
||||
label={t("message.actions.copyCode")}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -168,87 +169,3 @@ function splitFenceStyle(inheritedStyles: TextStyle, textStyle: TextStyle): Spli
|
||||
innerTextStyle: [inheritedStyles, textOnly],
|
||||
};
|
||||
}
|
||||
|
||||
interface CopyButtonProps {
|
||||
getCode: () => string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
const CopyButton = React.memo(function CopyButton({ getCode, visible }: CopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
const content = getCode();
|
||||
if (!content) return;
|
||||
await Clipboard.setStringAsync(content);
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
resetRef.current = null;
|
||||
}, COPIED_RESET_MS);
|
||||
}, [getCode]);
|
||||
|
||||
const visibilityStyle = visible
|
||||
? copyButtonStyles.containerVisible
|
||||
: copyButtonStyles.containerHidden;
|
||||
const wrapperStyle = useMemo(
|
||||
() => [copyButtonStyles.container, visibilityStyle],
|
||||
[visibilityStyle],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={wrapperStyle}
|
||||
pointerEvents={visible ? "auto" : "none"}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={copied ? t("message.actions.copied") : t("message.actions.copyCode")}
|
||||
hitSlop={8}
|
||||
dataSet={markdownCopyDataSet.ignore}
|
||||
>
|
||||
{({ hovered }) => {
|
||||
const iconColor = hovered
|
||||
? copyButtonStyles.iconHoveredColor.color
|
||||
: copyButtonStyles.iconColor.color;
|
||||
return copied ? (
|
||||
<Check size={14} color={iconColor} />
|
||||
) : (
|
||||
<Copy size={14} color={iconColor} />
|
||||
);
|
||||
}}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
const copyButtonStyles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[2],
|
||||
right: theme.spacing[2],
|
||||
padding: theme.spacing[1],
|
||||
},
|
||||
containerVisible: {
|
||||
opacity: 1,
|
||||
},
|
||||
containerHidden: {
|
||||
opacity: 0,
|
||||
},
|
||||
iconColor: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
iconHoveredColor: {
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { userEvent } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { BlockCopyButton } from "./block-copy-button";
|
||||
|
||||
const LABEL = "Copy quote";
|
||||
|
||||
let errors: string[] = [];
|
||||
const toast: ToastApi = {
|
||||
show: () => () => {},
|
||||
copied: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
};
|
||||
|
||||
describe("BlockCopyButton", () => {
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
errors = [];
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
|
||||
function render(onCopy: () => Promise<boolean>, visible = true) {
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<BlockCopyButton onCopy={onCopy} visible={visible} label={LABEL} />
|
||||
</ToastApiProvider>
|
||||
</I18nextProvider>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function button(name = LABEL): HTMLElement {
|
||||
return within(host).getByRole("button", { name });
|
||||
}
|
||||
|
||||
it("shows Copied after a write and returns to its label", async () => {
|
||||
let calls = 0;
|
||||
render(async () => {
|
||||
calls += 1;
|
||||
return true;
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
await vi.waitFor(() => expect(button()).toBeTruthy(), { timeout: 2500 });
|
||||
expect(calls).toBe(1);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["resolves false", async () => false],
|
||||
[
|
||||
"rejects",
|
||||
async (): Promise<boolean> => {
|
||||
throw new Error("Clipboard denied");
|
||||
},
|
||||
],
|
||||
])("tells the user and never shows Copied when the write %s", async (_case, failure) => {
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return calls === 1 ? failure() : Promise.resolve(true);
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(errors).toEqual(["Unable to copy"]));
|
||||
expect(within(host).queryByRole("button", { name: "Copied" })).toBeNull();
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("does not write twice while a write is pending", async () => {
|
||||
let finish!: (written: boolean) => void;
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return new Promise<boolean>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await userEvent.click(button());
|
||||
expect(calls).toBe(1);
|
||||
|
||||
finish(true);
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("stays hidden until its block reveals it or it takes keyboard focus", async () => {
|
||||
render(async () => true, false);
|
||||
expect(getComputedStyle(button()).opacity).toBe("0");
|
||||
|
||||
await userEvent.tab();
|
||||
expect(document.activeElement).toBe(button());
|
||||
await vi.waitFor(() => expect(getComputedStyle(button()).opacity).toBe("1"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { markdownCopyDataSet } from "@/assistant-selection-copy/markup";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedCopy = withUnistyles(Copy, mutedIconColorMapping);
|
||||
const ThemedCheck = withUnistyles(Check, mutedIconColorMapping);
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
/** How far the copy glyph sits from the top and trailing edges of its block. */
|
||||
export function blockCopyGlyphInset(theme: Theme): number {
|
||||
return theme.spacing[2] + theme.spacing[1];
|
||||
}
|
||||
|
||||
interface BlockCopyButtonProps {
|
||||
/** Writes the block to the clipboard. Resolves false, or rejects, when nothing was written. */
|
||||
onCopy: () => Promise<boolean>;
|
||||
/** The block's own reveal state. Keyboard focus shows the button regardless. */
|
||||
visible: boolean;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy control in the top trailing corner of a Markdown block. The block is its
|
||||
* positioned ancestor.
|
||||
*/
|
||||
export const BlockCopyButton = memo(function BlockCopyButton({
|
||||
onCopy,
|
||||
visible,
|
||||
label,
|
||||
}: BlockCopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const writing = useRef(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const focus = useCallback(() => setFocused(true), []);
|
||||
const blur = useCallback(() => setFocused(false), []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
// A slow clipboard must not queue a second write behind the first.
|
||||
if (writing.current) return;
|
||||
writing.current = true;
|
||||
const written = await onCopy()
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
writing.current = false;
|
||||
});
|
||||
if (!written) {
|
||||
toast.error(t("common.errors.unableToCopy"));
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
}, [onCopy, t, toast]);
|
||||
|
||||
const shown = visible || focused;
|
||||
const Glyph = copied ? ThemedCheck : ThemedCopy;
|
||||
return (
|
||||
<View style={styles.corner(compact)} dataSet={markdownCopyDataSet.ignore}>
|
||||
<ToolbarButton
|
||||
compact={compact}
|
||||
label={copied ? t("message.actions.copied") : label}
|
||||
onPress={handlePress}
|
||||
onFocus={focus}
|
||||
onBlur={blur}
|
||||
style={shown ? styles.shown : styles.hidden}
|
||||
>
|
||||
<Glyph size={paneContentToolbarIconSize(compact)} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The glyph, not the button frame, sits on the inset; the frame overhangs it.
|
||||
corner: (compact: boolean) => {
|
||||
const frameOverhang =
|
||||
(smallIconButtonChromeFrameSize(compact) - paneContentToolbarIconSize(compact)) / 2;
|
||||
const inset = blockCopyGlyphInset(theme) - frameOverhang;
|
||||
return {
|
||||
position: "absolute" as const,
|
||||
top: inset,
|
||||
right: inset,
|
||||
pointerEvents: "box-none" as const,
|
||||
};
|
||||
},
|
||||
shown: { opacity: 1, pointerEvents: "auto" },
|
||||
hidden: { opacity: 0, pointerEvents: "none" },
|
||||
}));
|
||||
@@ -5,6 +5,10 @@ import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import { ZoomableViewport } from "@/components/zoomable-viewport";
|
||||
import {
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
} from "@/assistant-selection-copy/markup";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { MarkdownFenceRendererProps } from "./types";
|
||||
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
|
||||
@@ -81,6 +85,16 @@ function MermaidFenceHostImpl({
|
||||
[visible],
|
||||
);
|
||||
const sourceVisible = !diagramVisible;
|
||||
// A visible diagram stands in for its fence, so copying the surrounding block takes
|
||||
// the source from here: the revision on screen, which lags `code` while a streamed
|
||||
// revision renders. The source view copies as its own code block.
|
||||
const diagramCopyAttributes =
|
||||
diagramVisible && visible
|
||||
? {
|
||||
[MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE]: visible.source,
|
||||
[MARKDOWN_COPY_LANGUAGE_ATTRIBUTE]: "mermaid",
|
||||
}
|
||||
: null;
|
||||
const viewportStyle = diagramVisible ? diagramStyle : measuringStyle;
|
||||
|
||||
return (
|
||||
@@ -111,7 +125,7 @@ function MermaidFenceHostImpl({
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
<div inert={!diagramVisible} style={boundaryStyle}>
|
||||
<div inert={!diagramVisible} style={boundaryStyle} {...diagramCopyAttributes}>
|
||||
<ZoomableViewport
|
||||
accessibilityLabel={t("message.diagram.diagram")}
|
||||
actions={actions}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import type { BlockquoteRendererProps } from "react-native-enriched-markdown";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createElementClipboardContent } from "@/assistant-selection-copy/content.web";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { writeClipboardContent } from "@/utils/rich-clipboard";
|
||||
import { getDefaultMarkdownClipboardEnvironment } from "@/utils/rich-clipboard-default-environment";
|
||||
import { BlockCopyButton, blockCopyGlyphInset } from "./block-copy-button";
|
||||
|
||||
interface WebBlockquoteProps extends BlockquoteRendererProps {
|
||||
copyGlyphInset: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Room the quote reserves so the control never covers its text. Compact layouts always
|
||||
* show the control, so it gets a band above the body and the text keeps the full width.
|
||||
* Wide layouts reveal it on hover, where a band would leave an empty strip above every
|
||||
* quote, so the text wraps short of it instead.
|
||||
*/
|
||||
function copyRoom(compact: boolean, glyphInset: number) {
|
||||
if (compact) {
|
||||
return { paddingTop: glyphInset + paneContentToolbarIconSize(compact) + glyphInset };
|
||||
}
|
||||
return { paddingRight: smallIconButtonChromeFrameSize(compact) + glyphInset };
|
||||
}
|
||||
|
||||
/** A quote with a control that copies its body, for drafts an agent wrote to be pasted elsewhere. */
|
||||
export const WebBlockquote = withUnistyles(
|
||||
function WebBlockquote({ blockquoteProps, children, copyGlyphInset }: WebBlockquoteProps) {
|
||||
const { t } = useTranslation();
|
||||
const quote = useRef<HTMLQuoteElement>(null);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const compact = useIsCompactFormFactor();
|
||||
const enter = useCallback(() => setHovered(true), []);
|
||||
const leave = useCallback(() => setHovered(false), []);
|
||||
const style = useMemo(
|
||||
() => ({
|
||||
...blockquoteProps.style,
|
||||
position: "relative" as const,
|
||||
...copyRoom(compact, copyGlyphInset),
|
||||
}),
|
||||
[blockquoteProps.style, compact, copyGlyphInset],
|
||||
);
|
||||
const copy = useCallback(async () => {
|
||||
// Read the rendered body at press time: a streaming quote copies what it shows now.
|
||||
const content = quote.current && createElementClipboardContent(quote.current);
|
||||
if (!content) return false;
|
||||
return writeClipboardContent(content, getDefaultMarkdownClipboardEnvironment());
|
||||
}, []);
|
||||
return (
|
||||
<blockquote
|
||||
{...blockquoteProps}
|
||||
ref={quote}
|
||||
style={style}
|
||||
onPointerEnter={enter}
|
||||
onPointerLeave={leave}
|
||||
>
|
||||
<BlockCopyButton
|
||||
onCopy={copy}
|
||||
visible={hovered || compact}
|
||||
label={t("message.actions.copyQuote")}
|
||||
/>
|
||||
{children}
|
||||
</blockquote>
|
||||
);
|
||||
},
|
||||
(theme) => ({ copyGlyphInset: blockCopyGlyphInset(theme) }),
|
||||
);
|
||||
@@ -14,6 +14,7 @@ import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
const codeStyle = (theme: Theme) => ({
|
||||
@@ -111,4 +112,8 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = { codeBlock: WebCodeBlock, link: WebLink };
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
blockquote: WebBlockquote,
|
||||
};
|
||||
|
||||
@@ -244,7 +244,6 @@ const CATALOG_DATA = [
|
||||
},
|
||||
{
|
||||
id: "hermes",
|
||||
bundledProvider: { hostFeature: "hermesProvider" },
|
||||
title: "Hermes",
|
||||
description: "Nous Research self-improving AI agent",
|
||||
version: "manual",
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
buildGitActions,
|
||||
isCurrentBranchBase,
|
||||
canMergeIntoLocalBase,
|
||||
readUpstreamState,
|
||||
type BuildGitActionsInput,
|
||||
} from "./policy";
|
||||
import { deriveMergeCapability, type ForgeSpecificStatusFacts } from "./merge-capability";
|
||||
@@ -77,8 +76,6 @@ function createInput(
|
||||
pullRequestMergeable: "UNKNOWN",
|
||||
mergeCapability: deriveMergeCapability(pullRequestGithub),
|
||||
hasRemote: false,
|
||||
hasFirstPushRemote: rest.hasRemote ?? false,
|
||||
upstream: "tracked",
|
||||
isPaseoOwnedWorktree: false,
|
||||
isOnBaseBranch: true,
|
||||
canMergeLocally: true,
|
||||
@@ -172,10 +169,6 @@ function createInput(
|
||||
};
|
||||
}
|
||||
|
||||
function pushActionOf(actions: ReturnType<typeof buildGitActions>) {
|
||||
return actions.secondary.find((action) => action.id === "push");
|
||||
}
|
||||
|
||||
describe("git-actions-policy", () => {
|
||||
afterEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
@@ -353,7 +346,6 @@ describe("git-actions-policy", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: "none",
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 1,
|
||||
@@ -369,207 +361,6 @@ describe("git-actions-policy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("re-publishes a Paseo worktree branch whose remote copy was deleted", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: "gone",
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 2,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
shipDefault: "pr",
|
||||
}),
|
||||
);
|
||||
const pushAction = actions.secondary.find((action) => action.id === "push");
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
expect(pushAction).toMatchObject({ disabled: false, unavailableMessage: undefined });
|
||||
});
|
||||
|
||||
describe("a never-pushed branch in a regular checkout", () => {
|
||||
const neverPushed = {
|
||||
hasRemote: true,
|
||||
upstream: "none",
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 1,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
} as const;
|
||||
|
||||
it("offers Push first, ahead of Create PR", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, shipDefault: "pr" }));
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
});
|
||||
|
||||
it("offers Push first, ahead of Merge locally", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...neverPushed, githubFeaturesEnabled: false, shipDefault: "merge" }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
});
|
||||
|
||||
it("does not offer Push when it has no commits of its own", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, aheadCount: 0 }));
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available because there is nothing new to send",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not offer Push when the repository has no origin", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, hasRemote: false }));
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not offer Push when Git pushes the branch to another remote", () => {
|
||||
const actions = buildGitActions(createInput({ ...neverPushed, hasFirstPushRemote: false }));
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary?.id).not.toBe("push");
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps offering Push in a Paseo worktree when Git pushes the branch to another remote", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...neverPushed, hasFirstPushRemote: false, isPaseoOwnedWorktree: true }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
});
|
||||
});
|
||||
|
||||
it("does not offer a first push when the branch's remote copy was deleted", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: "gone",
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 2,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
shipDefault: "pr",
|
||||
}),
|
||||
);
|
||||
const pushAction = actions.secondary.find((action) => action.id === "push");
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" });
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available because the branch this one tracks no longer exists",
|
||||
);
|
||||
});
|
||||
|
||||
describe("a published branch whose upstream the daemon cannot read", () => {
|
||||
const unreadableUpstream = {
|
||||
hasRemote: true,
|
||||
upstream: "unknown",
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 2,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
shipDefault: "pr",
|
||||
} as const;
|
||||
|
||||
it("does not offer a first push in a regular checkout", () => {
|
||||
const actions = buildGitActions(createInput(unreadableUpstream));
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" });
|
||||
expect(pushActionOf(actions)?.unavailableMessage).toEqual(expect.any(String));
|
||||
});
|
||||
|
||||
it("keeps offering Push in a Paseo worktree", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({ ...unreadableUpstream, isPaseoOwnedWorktree: true }),
|
||||
);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
|
||||
expect(pushActionOf(actions)).toMatchObject({
|
||||
disabled: false,
|
||||
unavailableMessage: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("readUpstreamState", () => {
|
||||
it("uses the upstream state the daemon reports", () => {
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: "none",
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toBe("none");
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: "gone",
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
}),
|
||||
).toBe("gone");
|
||||
});
|
||||
|
||||
it("keeps the old guess for daemons that predate upstream states", () => {
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: 1,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toBe("tracked");
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: true,
|
||||
}),
|
||||
).toBe("none");
|
||||
expect(
|
||||
readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("keeps an old daemon's never-pushed regular branch off Push", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
hasRemote: true,
|
||||
upstream: readUpstreamState({
|
||||
upstreamState: undefined,
|
||||
aheadOfOrigin: null,
|
||||
isPaseoOwnedWorktree: false,
|
||||
}),
|
||||
isOnBaseBranch: false,
|
||||
aheadCount: 1,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
githubFeaturesEnabled: false,
|
||||
shipDefault: "merge",
|
||||
}),
|
||||
);
|
||||
const pushAction = pushActionOf(actions);
|
||||
|
||||
expect(actions.primary).toMatchObject({ id: "merge-branch" });
|
||||
expect(pushAction?.unavailableMessage).toBe(
|
||||
"Push isn't available because there is nothing new to send",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("prioritizes push over pull request merge when local commits are unpushed", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
|
||||
@@ -2,11 +2,7 @@ import type { ReactElement } from "react";
|
||||
|
||||
import type { ActionStatus } from "@/components/ui/dropdown-menu";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import type {
|
||||
CheckoutPrMergeMethod,
|
||||
CheckoutStatusResponse,
|
||||
PullRequestMergeable,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { CheckoutPrMergeMethod, PullRequestMergeable } from "@getpaseo/protocol/messages";
|
||||
|
||||
import type { MergeCapability } from "./merge-capability";
|
||||
|
||||
@@ -77,25 +73,6 @@ export function canMergeIntoLocalBase(
|
||||
return currentBranch !== localTarget;
|
||||
}
|
||||
|
||||
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
|
||||
|
||||
export type GitUpstreamState = NonNullable<CheckoutStatusPayload["upstreamState"]>;
|
||||
|
||||
export function readUpstreamState(
|
||||
status: Pick<CheckoutStatusPayload, "upstreamState" | "aheadOfOrigin" | "isPaseoOwnedWorktree">,
|
||||
): GitUpstreamState {
|
||||
if (status.upstreamState !== undefined) {
|
||||
return status.upstreamState;
|
||||
}
|
||||
// COMPAT(checkoutUpstreamState): added in v0.17.4, remove after 2027-05-23 once the daemon
|
||||
// floor reports upstreamState. Older daemons send a null upstream for both a never-pushed and
|
||||
// a deleted remote branch. Only a Paseo worktree's null was trusted as never pushed.
|
||||
if (status.aheadOfOrigin !== null) {
|
||||
return "tracked";
|
||||
}
|
||||
return status.isPaseoOwnedWorktree ? "none" : "unknown";
|
||||
}
|
||||
|
||||
export interface BuildGitActionsInput {
|
||||
isGit: boolean;
|
||||
githubFeaturesEnabled: boolean;
|
||||
@@ -112,9 +89,6 @@ export interface BuildGitActionsInput {
|
||||
pullRequestMergeable: PullRequestMergeable;
|
||||
mergeCapability: MergeCapability | null;
|
||||
hasRemote: boolean;
|
||||
/** The daemon confirmed where a first push publishes the branch. */
|
||||
hasFirstPushRemote: boolean;
|
||||
upstream: GitUpstreamState;
|
||||
isPaseoOwnedWorktree: boolean;
|
||||
isOnBaseBranch: boolean;
|
||||
canMergeLocally: boolean;
|
||||
@@ -580,22 +554,12 @@ function canPush(input: BuildGitActionsInput): boolean {
|
||||
}
|
||||
|
||||
function hasPushableCommits(input: BuildGitActionsInput): boolean {
|
||||
switch (input.upstream) {
|
||||
case "tracked":
|
||||
return (input.aheadOfOrigin ?? 0) > 0;
|
||||
case "none":
|
||||
// A first push, which sets the upstream. The commits to send are the ones ahead of the base.
|
||||
// Paseo worktrees always publish to origin. A regular checkout publishes only where the
|
||||
// daemon confirmed Git would push the branch too, so a fork setup is not sent to origin.
|
||||
return input.aheadCount > 0 && (input.isPaseoOwnedWorktree || input.hasFirstPushRemote);
|
||||
case "gone":
|
||||
case "unknown":
|
||||
// The branch has an upstream that is deleted or unreadable, so nothing counts the commits
|
||||
// left to send. Paseo worktrees publish whenever the branch is ahead of its base, for
|
||||
// example after a merged PR. Regular checkouts do not: Push would re-create a branch that
|
||||
// was deleted.
|
||||
return input.isPaseoOwnedWorktree && input.aheadCount > 0;
|
||||
if ((input.aheadOfOrigin ?? 0) > 0) {
|
||||
return true;
|
||||
}
|
||||
// No-upstream Paseo worktrees are first-pushable: the daemon push sets upstream with `git push -u`.
|
||||
// Do not fold this into aheadOfOrigin; null also covers deleted/pruned upstream branches.
|
||||
return input.isPaseoOwnedWorktree && input.aheadOfOrigin === null && input.aheadCount > 0;
|
||||
}
|
||||
|
||||
function canMergeFromBase(input: BuildGitActionsInput): boolean {
|
||||
@@ -700,16 +664,10 @@ function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefi
|
||||
if ((input.behindOfOrigin ?? 0) > 0) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushBehind");
|
||||
}
|
||||
if (hasPushableCommits(input)) {
|
||||
return undefined;
|
||||
if (!hasPushableCommits(input)) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushNothing");
|
||||
}
|
||||
if (input.upstream === "gone") {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushUpstreamGone");
|
||||
}
|
||||
if (input.upstream === "none" && input.aheadCount > 0) {
|
||||
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
|
||||
}
|
||||
return i18n.t("workspace.git.actions.unavailable.pushNothing");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
|
||||
|
||||
@@ -15,11 +15,9 @@ import {
|
||||
isCurrentBranchBase,
|
||||
canMergeIntoLocalBase,
|
||||
narrowPullRequestState,
|
||||
readUpstreamState,
|
||||
type BuildGitActionsInput,
|
||||
type GitAction,
|
||||
type GitActions,
|
||||
type GitUpstreamState,
|
||||
} from "@/git/policy";
|
||||
import { deriveMergeCapability } from "@/git/merge-capability";
|
||||
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
|
||||
@@ -131,8 +129,6 @@ interface DerivedGitActionsState {
|
||||
behindOfOrigin: number | null;
|
||||
hasPullRequest: boolean;
|
||||
hasRemote: boolean;
|
||||
hasFirstPushRemote: boolean;
|
||||
upstream: GitUpstreamState;
|
||||
isPaseoOwnedWorktree: boolean;
|
||||
isOnBaseBranch: boolean;
|
||||
canMergeLocally: boolean;
|
||||
@@ -184,8 +180,6 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
|
||||
...extractGitCommitCounts(gitStatus),
|
||||
hasPullRequest: Boolean(prStatus?.url),
|
||||
hasRemote: gitStatus?.hasRemote ?? false,
|
||||
hasFirstPushRemote: (gitStatus?.firstPushRemote ?? null) !== null,
|
||||
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
|
||||
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
|
||||
@@ -674,8 +668,6 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
behindOfOrigin,
|
||||
hasPullRequest,
|
||||
hasRemote,
|
||||
hasFirstPushRemote,
|
||||
upstream,
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch,
|
||||
canMergeLocally,
|
||||
@@ -707,8 +699,6 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
|
||||
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
|
||||
hasRemote,
|
||||
hasFirstPushRemote,
|
||||
upstream,
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch,
|
||||
canMergeLocally,
|
||||
@@ -817,8 +807,6 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
}, [
|
||||
isGit,
|
||||
hasRemote,
|
||||
hasFirstPushRemote,
|
||||
upstream,
|
||||
hasPullRequest,
|
||||
prStatus?.url,
|
||||
prStatus?.state,
|
||||
|
||||
@@ -151,26 +151,20 @@ describe("ACP provider catalog", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ id: "goose", feature: "gooseProvider" },
|
||||
{ id: "hermes", feature: "hermesProvider" },
|
||||
] as const)(
|
||||
"adds bundled $id on capable hosts and uses the ACP config on older hosts",
|
||||
({ id, feature }) => {
|
||||
const entry = findProvider(id);
|
||||
expect(buildAcpProviderConfigPatch(entry, (supported) => supported === feature)).toEqual({
|
||||
providers: { [id]: { enabled: true } },
|
||||
});
|
||||
expect(buildAcpProviderConfigPatch(entry)).toEqual({
|
||||
providers: {
|
||||
[id]: {
|
||||
extends: "acp",
|
||||
label: entry.title,
|
||||
description: entry.description,
|
||||
command: [id, "acp"],
|
||||
env: {},
|
||||
},
|
||||
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
|
||||
const goose = findProvider("goose");
|
||||
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
|
||||
providers: { goose: { enabled: true } },
|
||||
});
|
||||
expect(buildAcpProviderConfigPatch(goose)).toEqual({
|
||||
providers: {
|
||||
goose: {
|
||||
extends: "acp",
|
||||
label: "goose",
|
||||
description: goose.description,
|
||||
command: ["goose", "acp"],
|
||||
env: {},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,10 +24,9 @@ export function buildAcpProviderConfigPatch(
|
||||
return { providers: { [entry.id]: { enabled: true } } };
|
||||
}
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter.
|
||||
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
|
||||
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
|
||||
if (feature !== "gooseProvider" && feature !== "hermesProvider") {
|
||||
if (feature !== "gooseProvider") {
|
||||
throw new Error(`Update the host to add ${entry.title}.`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,6 +345,7 @@ export const ar: TranslationResources = {
|
||||
viewDiagram: "عرض المخطط",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "نسخ الاقتباس",
|
||||
copyCode: "نسخ الرمز",
|
||||
copyTurn: "نسخ بدوره",
|
||||
copyMessage: "انسخ الرسالة",
|
||||
@@ -912,7 +913,6 @@ export const ar: TranslationResources = {
|
||||
pushNoRemote: "الدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
|
||||
pushBehind: "الدفع غير متاح حتى الآن نظرًا لوجود تغييرات أحدث يجب إدخالها أولاً",
|
||||
pushNothing: "خدمة الدفع غير متاحة لأنه لا يوجد شيء جديد لإرساله",
|
||||
pushUpstreamGone: "الدفع غير متاح لأن الفرع الذي يتتبعه هذا الفرع لم يعد موجودًا",
|
||||
pullAndPushNoRemote:
|
||||
"السحب والدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -344,6 +344,7 @@ export const en = {
|
||||
viewDiagram: "View diagram",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copy quote",
|
||||
copyCode: "Copy code",
|
||||
copyTurn: "Copy turn",
|
||||
copyMessage: "Copy message",
|
||||
@@ -913,8 +914,6 @@ export const en = {
|
||||
"Push isn't available here because this branch is not connected to a remote yet",
|
||||
pushBehind: "Push isn't available yet because there are newer changes to bring in first",
|
||||
pushNothing: "Push isn't available because there is nothing new to send",
|
||||
pushUpstreamGone:
|
||||
"Push isn't available because the branch this one tracks no longer exists",
|
||||
pullAndPushNoRemote:
|
||||
"Pull and push isn't available here because this branch is not connected to a remote yet",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -350,6 +350,7 @@ export const es: TranslationResources = {
|
||||
viewDiagram: "Ver diagrama",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copiar cita",
|
||||
copyCode: "Copiar código",
|
||||
copyTurn: "Copiar turno",
|
||||
copyMessage: "Copiar mensaje",
|
||||
@@ -925,8 +926,6 @@ export const es: TranslationResources = {
|
||||
pushBehind:
|
||||
"Push aún no está disponible porque hay cambios más nuevos que implementar primero",
|
||||
pushNothing: "Push no está disponible porque no hay nada nuevo que enviar",
|
||||
pushUpstreamGone:
|
||||
"Push no está disponible porque la rama que sigue esta rama ya no existe",
|
||||
pullAndPushNoRemote:
|
||||
"Tirar y empujar no está disponible aquí porque esta rama aún no está conectada a un control remoto",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -350,6 +350,7 @@ export const fr: TranslationResources = {
|
||||
viewDiagram: "Afficher le diagramme",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copier la citation",
|
||||
copyCode: "Copier le code",
|
||||
copyTurn: "Copier l’échange",
|
||||
copyMessage: "Copier le message",
|
||||
@@ -926,7 +927,6 @@ export const fr: TranslationResources = {
|
||||
pushBehind:
|
||||
"Push indisponible pour l’instant : des modifications plus récentes doivent d’abord être récupérées",
|
||||
pushNothing: "Push indisponible : il n’y a rien de nouveau à pousser",
|
||||
pushUpstreamGone: "Push indisponible : la branche suivie par cette branche n’existe plus",
|
||||
pullAndPushNoRemote:
|
||||
"Pull et push indisponibles : cette branche n’est pas encore liée à un dépôt distant",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -350,6 +350,7 @@ export const ja: TranslationResources = {
|
||||
viewDiagram: "図を表示",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "引用をコピー",
|
||||
copyCode: "コードをコピー",
|
||||
copyTurn: "ターンをコピー",
|
||||
copyMessage: "メッセージをコピー",
|
||||
@@ -919,8 +920,6 @@ export const ja: TranslationResources = {
|
||||
"このブランチはまだリモートに接続されていないため、プッシュはここでは利用できません",
|
||||
pushBehind: "取り込む必要がある新しい変更があるため、まだプッシュは利用できません",
|
||||
pushNothing: "プッシュする変更がないため、プッシュは利用できません",
|
||||
pushUpstreamGone:
|
||||
"このブランチが追跡しているブランチが存在しないため、プッシュは利用できません",
|
||||
pullAndPushNoRemote:
|
||||
"このブランチはまだリモートに接続されていないため、プル&プッシュはここでは利用できません",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -346,6 +346,7 @@ export const ko: TranslationResources = {
|
||||
viewDiagram: "다이어그램 보기",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "인용문 복사",
|
||||
copyCode: "코드 복사",
|
||||
copyTurn: "턴 복사",
|
||||
copyMessage: "메시지 복사",
|
||||
@@ -913,7 +914,6 @@ export const ko: TranslationResources = {
|
||||
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 푸시를 사용할 수 없습니다",
|
||||
pushBehind: "먼저 가져와야 할 최신 변경 사항이 있어 아직 푸시를 사용할 수 없습니다",
|
||||
pushNothing: "새로 보낼 항목이 없어 푸시를 사용할 수 없습니다",
|
||||
pushUpstreamGone: "이 브랜치가 추적하는 브랜치가 더 이상 없어 푸시를 사용할 수 없습니다",
|
||||
pullAndPushNoRemote:
|
||||
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 풀 후 푸시를 사용할 수 없습니다",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -349,6 +349,7 @@ export const ptBR: TranslationResources = {
|
||||
viewDiagram: "Ver diagrama",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copiar citação",
|
||||
copyCode: "Copiar código",
|
||||
copyTurn: "Copiar turno",
|
||||
copyMessage: "Copiar mensagem",
|
||||
@@ -921,8 +922,6 @@ export const ptBR: TranslationResources = {
|
||||
pushBehind:
|
||||
"Push ainda não está disponível porque há alterações mais recentes para trazer primeiro",
|
||||
pushNothing: "Push não está disponível porque não há nada novo para enviar",
|
||||
pushUpstreamGone:
|
||||
"Push não está disponível porque a branch que esta branch acompanha não existe mais",
|
||||
pullAndPushNoRemote:
|
||||
"Pull e push não estão disponíveis aqui porque esta branch ainda não está conectada a um remoto",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -349,6 +349,7 @@ export const ru: TranslationResources = {
|
||||
viewDiagram: "Показать диаграмму",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Копировать цитату",
|
||||
copyCode: "Скопировать код",
|
||||
copyTurn: "Скопировать ответ",
|
||||
copyMessage: "Копировать сообщение",
|
||||
@@ -924,8 +925,6 @@ export const ru: TranslationResources = {
|
||||
"Отправка изменений недоступна: эта ветка ещё не связана с удалённым репозиторием.",
|
||||
pushBehind: "Отправка изменений пока недоступна: сначала получите более новые изменения.",
|
||||
pushNothing: "Отправка изменений недоступна: нет новых изменений для отправки.",
|
||||
pushUpstreamGone:
|
||||
"Отправка изменений недоступна: ветка, которую отслеживает эта ветка, больше не существует.",
|
||||
pullAndPushNoRemote:
|
||||
"Получение и отправка изменений недоступны: эта ветка ещё не связана с удалённым репозиторием.",
|
||||
pullAndPushDirty:
|
||||
|
||||
@@ -345,6 +345,7 @@ export const zhCN: TranslationResources = {
|
||||
viewDiagram: "查看图表",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "复制引用",
|
||||
copyCode: "复制代码",
|
||||
copyTurn: "复制回合",
|
||||
copyMessage: "复制消息",
|
||||
@@ -908,7 +909,6 @@ export const zhCN: TranslationResources = {
|
||||
pushNoRemote: "此处无法 push,因为此分支尚未连接到 remote",
|
||||
pushBehind: "暂时无法 push,因为需要先拉取更新的变更",
|
||||
pushNothing: "无法 push,因为没有新的内容可发送",
|
||||
pushUpstreamGone: "无法 push,因为此分支跟踪的分支已不存在",
|
||||
pullAndPushNoRemote: "此处无法 pull 并 push,因为此分支尚未连接到 remote",
|
||||
pullAndPushDirty: "有本地变更时无法 pull 并 push,请先 commit 或 stash",
|
||||
pullAndPushNoIncoming: "无法 pull 并 push,因为没有需要先 pull 的传入变更",
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createSelectionClipboardContent,
|
||||
type MarkdownClipboardEnvironment,
|
||||
type RichClipboardWriter,
|
||||
writeClipboardContent,
|
||||
writeMarkdownToRichClipboard,
|
||||
} from "./rich-clipboard";
|
||||
|
||||
@@ -15,9 +16,9 @@ interface RecordingClipboard {
|
||||
}
|
||||
|
||||
function createRecordingClipboard(
|
||||
options: { supportsHtml?: boolean; richWriteFails?: boolean } = {},
|
||||
options: { supportsHtml?: boolean; richWriteFails?: boolean; plainWriteResult?: unknown } = {},
|
||||
): RecordingClipboard {
|
||||
const { supportsHtml = true, richWriteFails = false } = options;
|
||||
const { supportsHtml = true, richWriteFails = false, plainWriteResult } = options;
|
||||
const richWrites: Array<Record<"text/plain" | "text/html", Blob>> = [];
|
||||
const plainTexts: string[] = [];
|
||||
|
||||
@@ -35,6 +36,7 @@ function createRecordingClipboard(
|
||||
richWriter,
|
||||
writePlainText: async (text) => {
|
||||
plainTexts.push(text);
|
||||
return plainWriteResult;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -185,3 +187,44 @@ describe("writeMarkdownToRichClipboard", () => {
|
||||
expect(clipboard.richWrites).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("writeClipboardContent", () => {
|
||||
const content = { plainText: "_raw_ draft", html: "<p>\\_raw\\_ draft</p>" };
|
||||
|
||||
it("writes both flavors and reports the write", async () => {
|
||||
const clipboard = createRecordingClipboard();
|
||||
|
||||
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
|
||||
|
||||
const written = clipboard.richWrites[0];
|
||||
if (!written) {
|
||||
throw new Error("Expected rich clipboard data to be written");
|
||||
}
|
||||
await expect(written["text/plain"].text()).resolves.toBe(content.plainText);
|
||||
await expect(written["text/html"].text()).resolves.toBe(content.html);
|
||||
});
|
||||
|
||||
it("falls back to the plain flavor when the rich write fails", async () => {
|
||||
const clipboard = createRecordingClipboard({ richWriteFails: true });
|
||||
|
||||
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
|
||||
|
||||
expect(clipboard.plainTexts).toEqual([content.plainText]);
|
||||
});
|
||||
|
||||
it("reports a plain write the host refused", async () => {
|
||||
const clipboard = createRecordingClipboard({ supportsHtml: false, plainWriteResult: false });
|
||||
|
||||
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("propagates a plain write that throws", async () => {
|
||||
const environment: MarkdownClipboardEnvironment = {
|
||||
writePlainText: async () => {
|
||||
throw new Error("clipboard denied");
|
||||
},
|
||||
};
|
||||
|
||||
await expect(writeClipboardContent(content, environment)).rejects.toThrow("clipboard denied");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,19 +86,30 @@ export async function writeMarkdownToRichClipboard(
|
||||
markdown: string,
|
||||
environment: MarkdownClipboardEnvironment,
|
||||
): Promise<void> {
|
||||
await writeClipboardContent(createMarkdownClipboardContent(markdown), environment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes both flavors, or `plainText` alone where the host has no rich clipboard.
|
||||
* Resolves false when the host refused the write.
|
||||
*/
|
||||
export async function writeClipboardContent(
|
||||
content: MarkdownClipboardContent,
|
||||
environment: MarkdownClipboardEnvironment,
|
||||
): Promise<boolean> {
|
||||
if (environment.richWriter?.supportsHtml()) {
|
||||
const content = createMarkdownClipboardContent(markdown);
|
||||
try {
|
||||
await environment.richWriter.write({
|
||||
"text/plain": new Blob([content.plainText], { type: "text/plain" }),
|
||||
"text/html": new Blob([content.html], { type: "text/html" }),
|
||||
});
|
||||
return;
|
||||
return true;
|
||||
} catch {
|
||||
// Fall through to the plain-text path. Some webviews expose rich clipboard
|
||||
// APIs but deny writes depending on focus, permissions, or browser policy.
|
||||
}
|
||||
}
|
||||
|
||||
await environment.writePlainText(markdown);
|
||||
// Expo resolves false for a write the host refused, instead of rejecting.
|
||||
return (await environment.writePlainText(content.plainText)) !== false;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -29,9 +29,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/server": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/server": "0.17.3",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -49,8 +49,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -78,8 +78,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -13,15 +13,14 @@ import {
|
||||
type RequestPermissionRequest,
|
||||
type RequestPermissionResponse,
|
||||
type SessionConfigOption,
|
||||
type SessionInfo,
|
||||
type SessionNotification,
|
||||
type SessionUpdate,
|
||||
type ToolCall,
|
||||
type ToolCallContent,
|
||||
type ToolCallUpdate,
|
||||
type Stream,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import { z } from "zod";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
AcpConfigAccess,
|
||||
AcpConfigChange,
|
||||
@@ -32,7 +31,6 @@ import type {
|
||||
AcpVendorUpdate,
|
||||
RunAcpProviderOptions,
|
||||
} from "../acp.js";
|
||||
import { standardToolCallDetail } from "./tool-call-detail.js";
|
||||
import {
|
||||
PROVIDER_PROTOCOL_VERSION,
|
||||
ProviderEventSchema,
|
||||
@@ -50,7 +48,6 @@ import {
|
||||
type ProviderLaunch,
|
||||
type ProviderModel,
|
||||
type ProviderPermissionResponse,
|
||||
type ProviderToolCallDetail,
|
||||
type ProviderPersistence,
|
||||
type ProviderSessionConfig,
|
||||
type ProviderSetting,
|
||||
@@ -299,7 +296,8 @@ async function listSessions(
|
||||
emit: state.emit,
|
||||
});
|
||||
try {
|
||||
const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit });
|
||||
const response = await runtime.listSessions(input.cwd);
|
||||
const selected = input.limit ? response.sessions.slice(0, input.limit) : response.sessions;
|
||||
state.emit({
|
||||
type: "sessions",
|
||||
requestId: input.requestId,
|
||||
@@ -410,14 +408,14 @@ interface ActivePrompt {
|
||||
}
|
||||
|
||||
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
|
||||
const SESSION_SCAN_LIMIT = 500;
|
||||
// COMPAT(acpAutoAccept): added in v0.17.4, remove after 2027-05-23. The generic ACP adapter saves
|
||||
// its Auto Accept toggle as this setting on agents that later moved to a bundled ACP provider.
|
||||
const LEGACY_AUTO_ACCEPT_SETTING = "auto_accept";
|
||||
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
|
||||
|
||||
type AcpToolCallSource = AcpToolCallSnapshot & {
|
||||
diff?: Extract<ToolCallContent, { type: "diff" }>;
|
||||
};
|
||||
|
||||
interface AcpToolCallState {
|
||||
source: AcpToolCallSnapshot;
|
||||
source: AcpToolCallSource;
|
||||
presentation: AcpToolCallSnapshot;
|
||||
}
|
||||
|
||||
@@ -918,17 +916,8 @@ class AcpRuntime {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Follows `nextCursor` until `limit` sessions, the last page, or the scan cap. */
|
||||
async listSessions({ cwd, limit }: { cwd?: string; limit?: number }): Promise<SessionInfo[]> {
|
||||
const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT);
|
||||
const sessions: SessionInfo[] = [];
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const page = await this.call(this.connection.listSessions({ cwd, cursor }));
|
||||
sessions.push(...page.sessions);
|
||||
cursor = page.nextCursor ?? undefined;
|
||||
} while (cursor && sessions.length < wanted);
|
||||
return sessions.slice(0, wanted);
|
||||
listSessions(cwd?: string) {
|
||||
return this.call(this.connection.listSessions({ cwd }));
|
||||
}
|
||||
|
||||
async drainNotifications(): Promise<void> {
|
||||
@@ -1083,41 +1072,17 @@ class AcpRuntime {
|
||||
const requested: AcpConfigChange[] = [];
|
||||
if (config.model) requested.push({ target: "model", value: config.model });
|
||||
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
|
||||
const { settings, legacyAutoAccept } = this.withoutLegacyAutoAccept(config.settings);
|
||||
// The toggle stays saved after a mode is chosen here, so it counts only while the saved mode
|
||||
// is one the generic adapter wrote.
|
||||
const mode =
|
||||
legacyAutoAccept && autoAcceptMode && !this.offersMode(config.mode)
|
||||
? autoAcceptMode.mode.id
|
||||
: (config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined));
|
||||
const mode = config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined);
|
||||
if (mode) requested.push({ target: "mode", value: mode });
|
||||
if (config.thinkingOption) {
|
||||
requested.push({ target: "thinking", value: config.thinkingOption });
|
||||
}
|
||||
for (const [id, value] of Object.entries(settings)) {
|
||||
for (const [id, value] of Object.entries(config.settings)) {
|
||||
requested.push({ target: "setting", id, value });
|
||||
}
|
||||
for (const change of this.inAgentOrder(requested)) await this.applyConfigChange(change);
|
||||
}
|
||||
|
||||
private offersMode(mode: string | undefined): boolean {
|
||||
if (mode === undefined) return false;
|
||||
if (mode === this.options.options.acpOptions?.autoAcceptMode?.mode.id) return true;
|
||||
return toProviderCatalog(this.modes, this.configOptions).modes.some(({ id }) => id === mode);
|
||||
}
|
||||
|
||||
/** Reads the generic ACP adapter's saved Auto Accept toggle unless the agent has such a setting. */
|
||||
private withoutLegacyAutoAccept(settings: Readonly<Record<string, JsonValue>>): {
|
||||
settings: Readonly<Record<string, JsonValue>>;
|
||||
legacyAutoAccept: boolean;
|
||||
} {
|
||||
if (this.configOptions.some((option) => option.id === LEGACY_AUTO_ACCEPT_SETTING)) {
|
||||
return { settings, legacyAutoAccept: false };
|
||||
}
|
||||
const { [LEGACY_AUTO_ACCEPT_SETTING]: saved, ...rest } = settings;
|
||||
return { settings: rest, legacyAutoAccept: saved === true };
|
||||
}
|
||||
|
||||
// One option can reset another: choosing an fx provider also selects that provider's saved
|
||||
// model, so a model applied first would be lost. Agents list the option that decides first.
|
||||
private inAgentOrder(changes: readonly AcpConfigChange[]): AcpConfigChange[] {
|
||||
@@ -1317,7 +1282,6 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
const { presentation } = this.presentToolCall(request.toolCall);
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
@@ -1330,7 +1294,6 @@ class AcpRuntime {
|
||||
kind: "tool",
|
||||
title: request.toolCall.title ?? undefined,
|
||||
input: jsonRecord(request.toolCall.rawInput),
|
||||
detail: toolCallDetail(presentation),
|
||||
actions: request.options.map((option) => ({
|
||||
id: option.optionId,
|
||||
label: option.name,
|
||||
@@ -1599,21 +1562,6 @@ class AcpRuntime {
|
||||
this.pendingCompactions.clear();
|
||||
}
|
||||
|
||||
/** Merges an update into the call's earlier updates and runs it through the transformers. */
|
||||
private presentToolCall(update: ToolCall | ToolCallUpdate): AcpToolCallState {
|
||||
const tool = this.toolCalls.get(update.toolCallId);
|
||||
const source = mergeToolCallSnapshot(update, tool?.source);
|
||||
const context = {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
mcpServerNames: this.mcpServerNames,
|
||||
previous: tool?.presentation,
|
||||
};
|
||||
let presentation: AcpToolCallSnapshot = source;
|
||||
for (const transformer of this.transformers)
|
||||
presentation = transformer.toolCall?.(presentation, context) ?? presentation;
|
||||
return { source, presentation };
|
||||
}
|
||||
|
||||
private reduceToolCall(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
wireSeq: number,
|
||||
@@ -1633,7 +1581,25 @@ class AcpRuntime {
|
||||
current !== undefined &&
|
||||
this.liveOpenToolIds.has(current.id) &&
|
||||
this.toolKeepsTurnOpen(current);
|
||||
const { source, presentation: snapshot } = this.presentToolCall(update);
|
||||
const source = mergeToolCallSnapshot(update, tool?.source);
|
||||
let snapshot: AcpToolCallSnapshot = source;
|
||||
const context = {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
mcpServerNames: this.mcpServerNames,
|
||||
};
|
||||
for (const transformer of this.transformers)
|
||||
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
|
||||
if (!snapshot.detail && source.diff && snapshot.kind === "edit") {
|
||||
snapshot = {
|
||||
...snapshot,
|
||||
detail: {
|
||||
type: "edit",
|
||||
filePath: source.diff.path,
|
||||
oldString: source.diff.oldText ?? undefined,
|
||||
newString: source.diff.newText,
|
||||
},
|
||||
};
|
||||
}
|
||||
this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
|
||||
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
|
||||
if (this.replayWindow === null) {
|
||||
@@ -2213,8 +2179,8 @@ function ownConnectorStream(source: Stream): {
|
||||
|
||||
function mergeToolCallSnapshot(
|
||||
update: ToolCall | ToolCallUpdate,
|
||||
current: AcpToolCallSnapshot | undefined,
|
||||
): AcpToolCallSnapshot {
|
||||
current: AcpToolCallSource | undefined,
|
||||
): AcpToolCallSource {
|
||||
return {
|
||||
id: update.toolCallId,
|
||||
name: firstText(update.name, current?.name),
|
||||
@@ -2224,7 +2190,10 @@ function mergeToolCallSnapshot(
|
||||
input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
|
||||
output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
|
||||
locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [],
|
||||
content: update.content === undefined ? current?.content : jsonValue(update.content),
|
||||
diff:
|
||||
update.content === undefined
|
||||
? current?.diff
|
||||
: update.content?.find((item) => item.type === "diff"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2398,12 +2367,21 @@ function configValues(
|
||||
|
||||
type ToolCallTimelineItem = Extract<ProviderTimelineItem, { type: "tool_call" }>;
|
||||
|
||||
function toolCallDetail(snapshot: AcpToolCallSnapshot): ProviderToolCallDetail {
|
||||
return snapshot.detail ?? standardToolCallDetail(snapshot);
|
||||
}
|
||||
|
||||
function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem {
|
||||
const detail = toolCallDetail(snapshot);
|
||||
const input = jsonRecord(snapshot.input);
|
||||
const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true;
|
||||
const detail =
|
||||
snapshot.detail ??
|
||||
(isEdit
|
||||
? {
|
||||
type: "edit" as const,
|
||||
filePath:
|
||||
typeof input.filePath === "string" ? input.filePath : (snapshot.locations[0] ?? ""),
|
||||
oldString: typeof input.oldString === "string" ? input.oldString : undefined,
|
||||
newString: typeof input.newString === "string" ? input.newString : undefined,
|
||||
unifiedDiff: typeof input.unifiedDiff === "string" ? input.unifiedDiff : undefined,
|
||||
}
|
||||
: { type: "unknown" as const, input: snapshot.input, output: snapshot.output });
|
||||
const status =
|
||||
snapshot.status === "in_progress" || snapshot.status === "pending"
|
||||
? "running"
|
||||
@@ -2438,7 +2416,6 @@ function jsonValue(value: unknown) {
|
||||
}
|
||||
|
||||
function jsonRecord(value: unknown): Record<string, ReturnType<typeof jsonValue>> {
|
||||
if (value === undefined) return {};
|
||||
const parsed = jsonValue(value);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
||||
return parsed;
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { AcpToolCallSnapshot } from "../acp.js";
|
||||
import type { ProviderToolCallDetail } from "../provider.js";
|
||||
|
||||
type JsonRecord = Readonly<Record<string, JsonValue>>;
|
||||
|
||||
interface ToolCallParts {
|
||||
call: AcpToolCallSnapshot;
|
||||
input: JsonRecord;
|
||||
output: JsonRecord;
|
||||
text: string | undefined;
|
||||
}
|
||||
|
||||
type KindDetail = (parts: ToolCallParts) => ProviderToolCallDetail;
|
||||
|
||||
const KIND_DETAILS = new Map<string, KindDetail>(
|
||||
Object.entries({
|
||||
read: ({ call, input, output, text }) => ({
|
||||
type: "read",
|
||||
filePath: call.locations[0] ?? string(input, "path", "filePath", "file") ?? call.title,
|
||||
content: text ?? string(output, "content", "text"),
|
||||
offset: number(input, "offset", "line"),
|
||||
limit: number(input, "limit"),
|
||||
}),
|
||||
edit: editDetail,
|
||||
delete: editDetail,
|
||||
search: ({ call, input, output, text }) => ({
|
||||
type: "search",
|
||||
query: string(input, "query", "pattern") ?? call.title,
|
||||
toolName: "search",
|
||||
content: text ?? string(output, "content", "text"),
|
||||
filePaths: call.locations.length > 0 ? [...call.locations] : undefined,
|
||||
}),
|
||||
execute: ({ call, input, output, text }) => ({
|
||||
type: "shell",
|
||||
command: shellCommand(input) ?? call.title,
|
||||
cwd: string(input, "cwd"),
|
||||
output: text ?? string(output, "output", "text"),
|
||||
exitCode: number(output, "exitCode"),
|
||||
}),
|
||||
fetch: ({ call, input, output, text }) => ({
|
||||
type: "fetch",
|
||||
url: string(input, "url") ?? call.title,
|
||||
prompt: string(input, "prompt"),
|
||||
result: text ?? string(output, "result", "text", "content"),
|
||||
code: number(output, "status", "code"),
|
||||
}),
|
||||
think: ({ call, text }) => ({ type: "plain_text", label: call.title, icon: "brain", text }),
|
||||
switch_mode: ({ call, text }) => ({
|
||||
type: "plain_text",
|
||||
label: call.title,
|
||||
icon: "sparkles",
|
||||
text,
|
||||
}),
|
||||
} satisfies Record<string, KindDetail>),
|
||||
);
|
||||
|
||||
/**
|
||||
* The row for a tool call whose transformers set no detail, read from the call's ACP `kind`,
|
||||
* `rawInput`, `rawOutput`, `content` and `locations` the way the ACP spec defines them.
|
||||
*/
|
||||
export function standardToolCallDetail(call: AcpToolCallSnapshot): ProviderToolCallDetail {
|
||||
const parts: ToolCallParts = {
|
||||
call,
|
||||
input: record(call.input),
|
||||
output: record(call.output),
|
||||
text: contentText(call.content),
|
||||
};
|
||||
const kindDetail = call.kind === undefined ? undefined : KIND_DETAILS.get(call.kind);
|
||||
if (kindDetail) return kindDetail(parts);
|
||||
if (call.name?.toLowerCase().includes("edit")) return editDetail(parts);
|
||||
// Raw input or output is the most a client can show for a tool it does not know.
|
||||
if (parts.text !== undefined && call.input === null && call.output === null) {
|
||||
return { type: "plain_text", label: call.title, icon: "wrench", text: parts.text };
|
||||
}
|
||||
return { type: "unknown", input: call.input, output: call.output };
|
||||
}
|
||||
|
||||
function editDetail({ call, input, text }: ToolCallParts): ProviderToolCallDetail {
|
||||
const diff = contentDiff(call.content);
|
||||
const filePath =
|
||||
diff?.path ?? string(input, "filePath", "path", "file") ?? call.locations[0] ?? "";
|
||||
if (call.kind === "delete") {
|
||||
return {
|
||||
type: "edit",
|
||||
filePath,
|
||||
oldString: diff?.oldText ?? fileText(input, "oldText"),
|
||||
newString: "",
|
||||
unifiedDiff: text,
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "edit",
|
||||
filePath,
|
||||
oldString: diff?.oldText ?? fileText(input, "oldString", "oldText"),
|
||||
newString: diff?.newText ?? fileText(input, "newString", "newText"),
|
||||
unifiedDiff: string(input, "unifiedDiff") ?? text,
|
||||
};
|
||||
}
|
||||
|
||||
function shellCommand(input: JsonRecord): string | undefined {
|
||||
const command = string(input, "command");
|
||||
if (!command) return undefined;
|
||||
const args = Array.isArray(input.args)
|
||||
? input.args.filter((arg): arg is string => typeof arg === "string")
|
||||
: [];
|
||||
return args.length > 0 ? `${command} ${args.join(" ")}` : command;
|
||||
}
|
||||
|
||||
function contentText(content: JsonValue | undefined): string | undefined {
|
||||
const parts = contentBlocks(content).flatMap((block) => {
|
||||
if (block.type !== "content") return [];
|
||||
const body = record(block.content ?? null);
|
||||
return body.type === "text" && typeof body.text === "string" && body.text.length > 0
|
||||
? [body.text]
|
||||
: [];
|
||||
});
|
||||
return parts.length > 0 ? parts.join("\n") : undefined;
|
||||
}
|
||||
|
||||
function contentDiff(
|
||||
content: JsonValue | undefined,
|
||||
): { path?: string; oldText?: string; newText?: string } | undefined {
|
||||
const diff = contentBlocks(content).find((block) => block.type === "diff");
|
||||
if (!diff) return undefined;
|
||||
return {
|
||||
path: string(diff, "path"),
|
||||
oldText: typeof diff.oldText === "string" ? diff.oldText : undefined,
|
||||
newText: typeof diff.newText === "string" ? diff.newText : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function contentBlocks(content: JsonValue | undefined): JsonRecord[] {
|
||||
return Array.isArray(content) ? content.map((block) => record(block)) : [];
|
||||
}
|
||||
|
||||
function record(value: JsonValue): JsonRecord {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
||||
}
|
||||
|
||||
function string(value: JsonRecord, ...keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const entry = value[key];
|
||||
if (typeof entry === "string" && entry.trim().length > 0) return entry;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** File text is kept as written: whitespace or an empty string is the edit itself. */
|
||||
function fileText(value: JsonRecord, ...keys: string[]): string | undefined {
|
||||
for (const key of keys) {
|
||||
const entry = value[key];
|
||||
if (typeof entry === "string") return entry;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function number(value: JsonRecord, ...keys: string[]): number | undefined {
|
||||
for (const key of keys) {
|
||||
const entry = value[key];
|
||||
if (typeof entry === "number" && Number.isFinite(entry)) return entry;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import type { ProviderConnection, ProviderEvent, ProviderInput } from "./provider.js";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
|
||||
import { runAcpProvider, type AcpStreamMessage } from "./acp.js";
|
||||
|
||||
@@ -6725,403 +6724,3 @@ describe("deferTurnOnRunningTools", () => {
|
||||
await connection.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACP tool call rows", () => {
|
||||
function jsonRecord(value: JsonValue | undefined): Readonly<Record<string, JsonValue>> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
||||
}
|
||||
|
||||
function text(value: string) {
|
||||
return [{ type: "content", content: { type: "text", text: value } }];
|
||||
}
|
||||
|
||||
async function toolRows(
|
||||
updates: unknown[],
|
||||
transformers?: Parameters<typeof runAcpProvider>[0]["transformers"],
|
||||
) {
|
||||
const harness = connectorHarness({ promptUpdates: () => updates });
|
||||
const registration = runAcpProvider({
|
||||
id: "tool-rows-acp",
|
||||
label: "Tool rows ACP",
|
||||
connector: harness.connector,
|
||||
transformers,
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "first",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Use a tool" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.turn" && event.state === "completed",
|
||||
);
|
||||
const rows = events.flatMap((event) =>
|
||||
event.type === "timeline.item" && event.item.type === "tool_call" ? [event.item] : [],
|
||||
);
|
||||
for (const row of rows) {
|
||||
expect(AgentTimelineItemPayloadSchema.safeParse(row).success).toBe(true);
|
||||
}
|
||||
return rows;
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
it.each([
|
||||
{
|
||||
kind: "execute",
|
||||
start: { title: "Run tests", rawInput: { command: "npm", args: ["test"], cwd: "/repo" } },
|
||||
end: { content: text("passed"), rawOutput: { exitCode: 0 } },
|
||||
detail: { type: "shell", command: "npm test", cwd: "/repo", output: "passed", exitCode: 0 },
|
||||
},
|
||||
{
|
||||
kind: "execute",
|
||||
start: { title: "Run tests" },
|
||||
end: { content: text("passed") },
|
||||
detail: { type: "shell", command: "Run tests", output: "passed" },
|
||||
},
|
||||
{
|
||||
kind: "read",
|
||||
start: { title: "Read a.ts", locations: [{ path: "/repo/a.ts" }], rawInput: { offset: 3 } },
|
||||
end: { content: text("const a = 1;") },
|
||||
detail: { type: "read", filePath: "/repo/a.ts", content: "const a = 1;", offset: 3 },
|
||||
},
|
||||
{
|
||||
kind: "search",
|
||||
start: { title: "Search TODO", rawInput: { pattern: "TODO" } },
|
||||
end: { content: text("a.ts:1"), locations: [{ path: "/repo/a.ts" }] },
|
||||
detail: {
|
||||
type: "search",
|
||||
query: "TODO",
|
||||
toolName: "search",
|
||||
content: "a.ts:1",
|
||||
filePaths: ["/repo/a.ts"],
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "fetch",
|
||||
start: { title: "Fetch example", rawInput: { url: "https://example.com" } },
|
||||
end: { content: text("Example Domain") },
|
||||
detail: { type: "fetch", url: "https://example.com", result: "Example Domain" },
|
||||
},
|
||||
{
|
||||
kind: "edit",
|
||||
start: {
|
||||
title: "Edit a.ts",
|
||||
content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }],
|
||||
},
|
||||
end: {},
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" },
|
||||
},
|
||||
{
|
||||
kind: "edit",
|
||||
start: { title: "Edit a.ts", locations: [{ path: "/repo/a.ts" }] },
|
||||
end: { content: text("Replaced 1 occurrence") },
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", unifiedDiff: "Replaced 1 occurrence" },
|
||||
},
|
||||
{
|
||||
kind: "edit",
|
||||
start: {
|
||||
title: "Edit a.ts",
|
||||
rawInput: { filePath: "/repo/a.ts", oldString: "remove me", newString: " " },
|
||||
},
|
||||
end: {},
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "remove me", newString: " " },
|
||||
},
|
||||
{
|
||||
kind: "delete",
|
||||
start: { title: "Delete a.ts", locations: [{ path: "/repo/a.ts" }] },
|
||||
end: {},
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", newString: "" },
|
||||
},
|
||||
{
|
||||
kind: "think",
|
||||
start: { title: "Plan" },
|
||||
end: { content: text("First read the tests") },
|
||||
detail: { type: "plain_text", label: "Plan", icon: "brain", text: "First read the tests" },
|
||||
},
|
||||
{
|
||||
kind: "other",
|
||||
start: { title: "Update todos" },
|
||||
end: { content: text("2 open") },
|
||||
detail: { type: "plain_text", label: "Update todos", icon: "wrench", text: "2 open" },
|
||||
},
|
||||
{
|
||||
kind: "other",
|
||||
start: { title: "Custom tool", rawInput: { value: 1 } },
|
||||
end: { content: text("done"), rawOutput: { ok: true } },
|
||||
detail: { type: "unknown", input: { value: 1 }, output: { ok: true } },
|
||||
},
|
||||
])("presents a completed $kind call as its standard row ($start.title)", async (example) => {
|
||||
const rows = await toolRows([
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
kind: example.kind,
|
||||
status: "in_progress",
|
||||
...example.start,
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
...example.end,
|
||||
},
|
||||
]);
|
||||
expect(rows.at(-1)?.detail).toEqual(example.detail);
|
||||
});
|
||||
|
||||
it("gives transformers the call's content and the call as it was last presented", async () => {
|
||||
const commandFromStart: NonNullable<
|
||||
NonNullable<Parameters<typeof runAcpProvider>[0]["transformers"]>[number]["toolCall"]
|
||||
> = (call, { previous }) => {
|
||||
const first = Array.isArray(call.content) ? call.content[0] : undefined;
|
||||
const startText = jsonRecord(jsonRecord(first).content).text;
|
||||
if (typeof startText === "string" && startText.startsWith("$ ")) {
|
||||
return { ...call, input: { command: startText.slice(2) } };
|
||||
}
|
||||
const command = jsonRecord(previous?.input).command;
|
||||
return typeof command === "string" ? { ...call, input: { command } } : call;
|
||||
};
|
||||
const rows = await toolRows(
|
||||
[
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "git status + 1 command",
|
||||
kind: "execute",
|
||||
status: "in_progress",
|
||||
content: text("$ git status && git diff"),
|
||||
},
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
content: text("clean"),
|
||||
},
|
||||
],
|
||||
[{ toolCall: commandFromStart }],
|
||||
);
|
||||
expect(rows.map((row) => row.detail)).toEqual([
|
||||
{ type: "shell", command: "git status && git diff", output: "$ git status && git diff" },
|
||||
{ type: "shell", command: "git status && git diff", output: "clean" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a transformer's own detail over the standard row", async () => {
|
||||
const rows = await toolRows(
|
||||
[
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "Run tests",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawInput: { command: "npm test" },
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
toolCall: (call) => ({
|
||||
...call,
|
||||
detail: { type: "unknown", input: call.input, output: null },
|
||||
}),
|
||||
},
|
||||
],
|
||||
);
|
||||
expect(rows.at(-1)?.detail).toEqual({
|
||||
type: "unknown",
|
||||
input: { command: "npm test" },
|
||||
output: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the call's row on its approval", async () => {
|
||||
const harness = connectorHarness({
|
||||
handleRequest(runtime, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
void runtime.request("session/request_permission", {
|
||||
sessionId: "connector-session",
|
||||
toolCall: {
|
||||
toolCallId: "edit-1",
|
||||
title: "Edit a.ts",
|
||||
kind: "edit",
|
||||
status: "pending",
|
||||
content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow", name: "Allow edit", kind: "allow_once" },
|
||||
{ optionId: "deny", name: "Deny", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "approval-rows",
|
||||
label: "Approval rows",
|
||||
connector: harness.connector,
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "permission"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "edit",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Edit a.ts" }] },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await waitForEvent(events, (event) => event.type === "session.permission"),
|
||||
).toMatchObject({
|
||||
request: {
|
||||
id: "permission:edit-1",
|
||||
title: "Edit a.ts",
|
||||
detail: { type: "edit", filePath: "/repo/a.ts", oldString: "a", newString: "b" },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("lists sessions across every page the agent returns", async () => {
|
||||
const pages: Record<string, { sessions: unknown[]; nextCursor?: string }> = {
|
||||
first: {
|
||||
sessions: [{ sessionId: "s1", cwd: "/repo", title: "One" }],
|
||||
nextCursor: "second",
|
||||
},
|
||||
second: { sessions: [{ sessionId: "s2", cwd: "/repo", title: "Two" }] },
|
||||
};
|
||||
const harness = connectorHarness({
|
||||
capabilities: { sessionCapabilities: { list: {} } },
|
||||
handleRequest(runtime, request) {
|
||||
if (request.method !== "session/list") return false;
|
||||
const { cursor } = request.params as { cursor?: string };
|
||||
runtime.respond(request, pages[cursor ?? "first"]);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "paged-sessions",
|
||||
label: "Paged sessions",
|
||||
connector: harness.connector,
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "session.list"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({ type: "sessions", requestId: "list" });
|
||||
const listed = await waitForEvent(events, (event) => event.type === "sessions");
|
||||
expect(listed.type === "sessions" && listed.sessions.map((session) => session.title)).toEqual(
|
||||
["One", "Two"],
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("resumes the generic ACP adapter's saved Auto Accept toggle in the unattended mode", async () => {
|
||||
const harness = connectorHarness({
|
||||
configOptions: [
|
||||
{
|
||||
id: "edit_approval_policy",
|
||||
name: "Edits",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: "ask",
|
||||
options: [
|
||||
{ value: "ask", name: "Default" },
|
||||
{ value: "session", name: "Don't Ask" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "former-generic",
|
||||
label: "Former generic",
|
||||
connector: harness.connector,
|
||||
acpOptions: {
|
||||
autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" },
|
||||
},
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
const input = openInput();
|
||||
input.config.settings = { auto_accept: true };
|
||||
await connection.send(input);
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
const configs = events.flatMap((event) =>
|
||||
event.type === "session.config" ? [event.config.mode] : [],
|
||||
);
|
||||
expect(configs.at(-1)).toBe("full-access");
|
||||
const sentOptions = harness.instances
|
||||
.flatMap((instance) => instance.requests)
|
||||
.filter((request) => request.method === "session/set_config_option")
|
||||
.map((request) => (request.params as { configId: string }).configId);
|
||||
expect(sentOptions).not.toContain("auto_accept");
|
||||
expect(events.some((event) => event.type === "request.failed")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a mode chosen after the generic ACP adapter's Auto Accept toggle was saved", async () => {
|
||||
const harness = connectorHarness({
|
||||
configOptions: [
|
||||
{
|
||||
id: "edit_approval_policy",
|
||||
name: "Edits",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: "session",
|
||||
options: [
|
||||
{ value: "ask", name: "Default" },
|
||||
{ value: "session", name: "Don't Ask" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await runAcpProvider({
|
||||
id: "former-generic",
|
||||
label: "Former generic",
|
||||
connector: harness.connector,
|
||||
acpOptions: {
|
||||
autoAcceptMode: { mode: { id: "full-access", label: "Full access" }, nativeMode: "ask" },
|
||||
},
|
||||
}).connect({ versions: [1], capabilities: ["prompt.message", "session.configure"] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
const input = openInput();
|
||||
input.config.mode = "ask";
|
||||
input.config.settings = { auto_accept: true };
|
||||
await connection.send(input);
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
const configs = events.flatMap((event) =>
|
||||
event.type === "session.config" ? [event.config.mode] : [],
|
||||
);
|
||||
expect(configs.at(-1)).toBe("ask");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -117,14 +117,9 @@ export interface AcpToolCallSnapshot {
|
||||
title: string;
|
||||
kind?: string;
|
||||
status: "pending" | "in_progress" | "completed" | "failed";
|
||||
/** The call's ACP `rawInput`. */
|
||||
input: JsonValue;
|
||||
/** The call's ACP `rawOutput`. */
|
||||
output: JsonValue;
|
||||
/** The call's ACP `content` blocks. An update that sends `content` replaces them. */
|
||||
content?: JsonValue;
|
||||
locations: readonly string[];
|
||||
/** The row Paseo shows. Without it, Paseo builds the standard row for the call's ACP `kind`. */
|
||||
detail?: ProviderToolCallDetail;
|
||||
}
|
||||
|
||||
@@ -155,14 +150,9 @@ export interface AcpTransformer {
|
||||
notification: { method: string; params: JsonValue },
|
||||
context: AcpContext,
|
||||
): AcpVendorUpdate | readonly AcpVendorUpdate[] | null;
|
||||
/** Rewrites each update of a tool call, merged with the call's earlier updates. */
|
||||
toolCall?(
|
||||
toolCall: AcpToolCallSnapshot,
|
||||
context: AcpContext & {
|
||||
mcpServerNames?: readonly string[];
|
||||
/** The call as Paseo last presented it, after every transformer. Absent on its first update. */
|
||||
previous?: AcpToolCallSnapshot;
|
||||
},
|
||||
context: AcpContext & { mcpServerNames?: readonly string[] },
|
||||
): AcpToolCallSnapshot;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -814,7 +814,7 @@ describe("checkout PR schemas", () => {
|
||||
});
|
||||
|
||||
test.each(
|
||||
["hopliteProvider", "fxProvider", "gooseProvider", "hermesProvider"].flatMap((name) =>
|
||||
["hopliteProvider", "fxProvider", "gooseProvider"].flatMap((name) =>
|
||||
[undefined, false, true].map((value) => [name, value] as const),
|
||||
),
|
||||
)("accepts optional bundled provider capability (%s: %s)", (name, value) => {
|
||||
|
||||
@@ -4168,8 +4168,6 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
fxProvider: z.boolean().optional(),
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
gooseProvider: z.boolean().optional(),
|
||||
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter.
|
||||
hermesProvider: z.boolean().optional(),
|
||||
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
|
||||
importSessionWorkspaceTarget: z.boolean().optional(),
|
||||
// COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02.
|
||||
@@ -5818,17 +5816,6 @@ const CheckoutStatusCommonSchema = z.object({
|
||||
// upstream branch name is not necessarily currentBranch, so composing one is wrong.
|
||||
// aheadOfOrigin/behindOfOrigin are measured against exactly this ref.
|
||||
upstreamRef: z.string().nullable().optional(),
|
||||
// How currentBranch relates to its upstream: "tracked" (upstreamRef and the counts are set),
|
||||
// "none" (never pushed; Push does a first push), "gone" (the upstream's remote-tracking ref no
|
||||
// longer exists, as after the remote branch is deleted), or "unknown" (the daemon cannot tell,
|
||||
// as when the clone keeps no remote-tracking ref for the upstream). Absent from daemons that
|
||||
// predate it, which report all but "tracked" as a null upstreamRef.
|
||||
upstreamState: z.enum(["tracked", "none", "gone", "unknown"]).optional(),
|
||||
// The remote a first push publishes currentBranch to, when the daemon can confirm git would
|
||||
// push the branch there too. Null when there is no such remote, as when origin is missing or
|
||||
// git is set to push the branch to another remote (branch.<name>.pushRemote,
|
||||
// remote.pushDefault). Absent from daemons that predate it.
|
||||
firstPushRemote: z.string().nullable().optional(),
|
||||
forgeWeb: ForgeWebSchema.optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+30
-3
@@ -62,6 +62,9 @@ class BlockquoteContainerView(
|
||||
// Cached markdown source for the "Copy as Markdown" action.
|
||||
private var cachedMarkdown: String = ""
|
||||
|
||||
// Cached markdown of the quote's body, without its own `> ` prefix, for the copy button.
|
||||
private var cachedBodyMarkdown: String = ""
|
||||
|
||||
// Cached plain text for the "Copy" action.
|
||||
private var cachedPlainText: String = ""
|
||||
|
||||
@@ -85,7 +88,15 @@ class BlockquoteContainerView(
|
||||
private val iconPaint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
|
||||
private fun reservedHeaderHeight(): Int = if (admonitionType != null) ceil(admonitionHeaderReservedHeight(blockquoteStyle)).toInt() else 0
|
||||
// A plain quote shows the code block's copy control in a header band of the
|
||||
// same height; an admonition keeps its title band and has no copy control.
|
||||
private val copyButton =
|
||||
HeaderCopyButton(context, parentConfig.style.codeBlockStyle) { parentConfig.dynamicProps.copyLabel }.apply {
|
||||
setOnClickListener { copyBody() }
|
||||
}
|
||||
|
||||
private fun reservedHeaderHeight(): Int =
|
||||
if (admonitionType != null) ceil(admonitionHeaderReservedHeight(blockquoteStyle)).toInt() else copyButton.bandHeight
|
||||
|
||||
// Only the outermost quote carries vertical margins; a quote nested directly
|
||||
// inside another quote is separated by the parent's padding alone (matches the
|
||||
@@ -108,7 +119,12 @@ class BlockquoteContainerView(
|
||||
|
||||
init {
|
||||
setWillNotDraw(false)
|
||||
setPadding(leftInset, verticalInset, rightInset, verticalInset)
|
||||
// The copy control sits in the header band, which top padding reserves.
|
||||
clipToPadding = false
|
||||
setPadding(leftInset, verticalInset + reservedHeaderHeight(), rightInset, verticalInset)
|
||||
// applySegments keeps segment views at the front of the child array, so the
|
||||
// control stays the last child, drawn and hit-tested above the body.
|
||||
addView(copyButton)
|
||||
segmentViewFactory = ChildFactory()
|
||||
trailingMarginEnabled = false
|
||||
isLongClickable = true
|
||||
@@ -125,6 +141,9 @@ class BlockquoteContainerView(
|
||||
// Reserve the header band above the body by enlarging the top padding.
|
||||
setPadding(leftInset, verticalInset + reservedHeaderHeight(), rightInset, verticalInset)
|
||||
|
||||
copyButton.visibility = if (admonitionType == null) View.VISIBLE else View.GONE
|
||||
cachedBodyMarkdown = MarkdownASTSerializer.serializeBlockquoteBody(node)
|
||||
copyButton.isEnabled = cachedBodyMarkdown.isNotEmpty()
|
||||
cachedMarkdown = MarkdownASTSerializer.serializeBlockquote(node)
|
||||
cachedPlainText = MarkdownASTSerializer.plainText(node)
|
||||
|
||||
@@ -143,6 +162,12 @@ class BlockquoteContainerView(
|
||||
requestLayout()
|
||||
}
|
||||
|
||||
private fun copyBody() {
|
||||
if (cachedBodyMarkdown.isEmpty()) return
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("Blockquote", cachedBodyMarkdown))
|
||||
}
|
||||
|
||||
private fun showContextMenu(anchor: View): Boolean {
|
||||
if (!parentConfig.dynamicProps.enableBlockContextMenu) return false
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
@@ -167,6 +192,7 @@ class BlockquoteContainerView(
|
||||
) {
|
||||
val measuredWidth = MeasureSpec.getSize(widthSpec)
|
||||
measureSegmentChildren(measuredWidth)
|
||||
if (copyButton.visibility != View.GONE) copyButton.measureInBand()
|
||||
setMeasuredDimension(measuredWidth, computeSegmentsTotalHeight())
|
||||
}
|
||||
|
||||
@@ -178,6 +204,7 @@ class BlockquoteContainerView(
|
||||
b: Int,
|
||||
) {
|
||||
layoutSegments()
|
||||
if (copyButton.visibility != View.GONE) copyButton.layoutInBand(width)
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -368,7 +395,7 @@ class BlockquoteContainerView(
|
||||
if (node.type == MarkdownASTNode.NodeType.Admonition) {
|
||||
ceil(admonitionHeaderReservedHeight(style))
|
||||
} else {
|
||||
0f
|
||||
CodeBlockContainerView.headerHeight(config.codeBlockStyle).toFloat()
|
||||
}
|
||||
val innerWidth = (width - leftInset - rightInset).coerceAtLeast(1f)
|
||||
|
||||
|
||||
+7
-79
@@ -4,11 +4,8 @@ import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.ColorFilter
|
||||
import android.graphics.Paint
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.os.Build
|
||||
import android.text.Layout
|
||||
@@ -21,8 +18,6 @@ import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.ImageView
|
||||
import androidx.appcompat.widget.AppCompatImageButton
|
||||
import androidx.appcompat.widget.AppCompatTextView
|
||||
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
|
||||
import com.swmansion.enriched.markdown.spans.LineHeightSpan
|
||||
@@ -34,7 +29,6 @@ import com.swmansion.enriched.markdown.utils.text.extensions.applyCodeBlockTextS
|
||||
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
|
||||
import com.swmansion.enriched.markdown.views.ClaimingHorizontalScrollView
|
||||
import com.swmansion.enriched.markdown.views.ContextMenuPopup
|
||||
import com.swmansion.enriched.markdown.views.CopyGlyph
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -125,20 +119,8 @@ class CodeBlockContainerView(
|
||||
setTextColor(secondaryColor(codeBlockStyle.color))
|
||||
}
|
||||
|
||||
// contentDescription reads the shared label live so a runtime label change is
|
||||
// reflected for TalkBack without a push (mirrors the live block-menu reads).
|
||||
private val copyButton =
|
||||
object : AppCompatImageButton(context) {
|
||||
override fun getContentDescription(): CharSequence = dynamicProps.copyLabel
|
||||
}.apply {
|
||||
background = null
|
||||
scaleType = ImageView.ScaleType.CENTER
|
||||
setImageDrawable(
|
||||
CopyIconDrawable(
|
||||
secondaryColor(codeBlockStyle.color),
|
||||
ceil(codeBlockStyle.fontSize * HEADER_ICON_SCALE).toInt(),
|
||||
),
|
||||
)
|
||||
HeaderCopyButton(context, codeBlockStyle) { dynamicProps.copyLabel }.apply {
|
||||
setOnClickListener { copyCode() }
|
||||
}
|
||||
|
||||
@@ -210,10 +192,7 @@ class CodeBlockContainerView(
|
||||
MeasureSpec.makeMeasureSpec((measuredWidth - borderW * 2).coerceAtLeast(0), MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
|
||||
)
|
||||
copyButton.measure(
|
||||
MeasureSpec.makeMeasureSpec(headerH, MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(headerH, MeasureSpec.EXACTLY),
|
||||
)
|
||||
copyButton.measureInBand()
|
||||
val labelMaxWidth = (measuredWidth - inset * 2 - headerH).coerceAtLeast(0)
|
||||
languageView.measure(
|
||||
MeasureSpec.makeMeasureSpec(labelMaxWidth, MeasureSpec.AT_MOST),
|
||||
@@ -230,8 +209,7 @@ class CodeBlockContainerView(
|
||||
bottom: Int,
|
||||
) {
|
||||
val width = right - left
|
||||
// The divider sits halfway into the code pane's top inset.
|
||||
val headerCenterY = (headerH + inset / 2f) / 2f
|
||||
val headerCenterY = copyButton.bandCenterY
|
||||
val labelTop = (headerCenterY - languageView.measuredHeight / 2f).roundToInt()
|
||||
languageView.layout(
|
||||
inset,
|
||||
@@ -240,16 +218,7 @@ class CodeBlockContainerView(
|
||||
labelTop + languageView.measuredHeight,
|
||||
)
|
||||
|
||||
val iconWidth = copyButton.drawable?.intrinsicWidth ?: copyButton.measuredWidth
|
||||
val iconSlack = ((copyButton.measuredWidth - iconWidth) / 2).coerceAtLeast(0)
|
||||
val buttonLeft = (width - inset - copyButton.measuredWidth + iconSlack).coerceAtLeast(0)
|
||||
val buttonTop = (headerCenterY - copyButton.measuredHeight / 2f).roundToInt().coerceAtLeast(0)
|
||||
copyButton.layout(
|
||||
buttonLeft,
|
||||
buttonTop,
|
||||
buttonLeft + copyButton.measuredWidth,
|
||||
buttonTop + copyButton.measuredHeight,
|
||||
)
|
||||
copyButton.layoutInBand(width)
|
||||
|
||||
scrollView.layout(borderW, headerH, width - borderW, bottom - top - borderW)
|
||||
}
|
||||
@@ -305,63 +274,22 @@ class CodeBlockContainerView(
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("Code", text))
|
||||
}
|
||||
|
||||
private class CopyIconDrawable(
|
||||
color: Int,
|
||||
private val size: Int,
|
||||
) : Drawable() {
|
||||
private val paint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = size / 20f
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
this.color = color
|
||||
}
|
||||
|
||||
private val glyph = CopyGlyph()
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
glyph.draw(canvas, bounds.width().toFloat(), paint)
|
||||
}
|
||||
|
||||
override fun getIntrinsicWidth() = size
|
||||
|
||||
override fun getIntrinsicHeight() = size
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
paint.alpha = alpha
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||
paint.colorFilter = colorFilter
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity() = PixelFormat.TRANSLUCENT
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val HEADER_LABEL_SCALE = 0.85f
|
||||
|
||||
// Drawable box for the copy glyph, as a multiple of the code font size.
|
||||
// iOS sizes the SF Symbol by point size (kENRMHeaderIconScale = 0.72) but
|
||||
// the symbol renders roughly half again as tall as its point size; this box
|
||||
// is scaled up to land the drawn glyph at the same on-screen size.
|
||||
private const val HEADER_ICON_SCALE = 1.08f
|
||||
|
||||
private val headerTypeface: Typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
|
||||
|
||||
private fun secondaryColor(color: Int): Int = (color and 0x00FFFFFF) or (0x99 shl 24)
|
||||
internal fun secondaryColor(color: Int): Int = (color and 0x00FFFFFF) or (0x99 shl 24)
|
||||
|
||||
private fun dividerColor(color: Int): Int = (color and 0x00FFFFFF) or (0x33 shl 24)
|
||||
|
||||
private fun contentInset(style: CodeBlockStyle): Int = ceil(style.padding + style.borderWidth).toInt()
|
||||
internal fun contentInset(style: CodeBlockStyle): Int = ceil(style.padding + style.borderWidth).toInt()
|
||||
|
||||
private fun borderPx(style: CodeBlockStyle): Int = ceil(style.borderWidth).toInt()
|
||||
|
||||
// Header is the top content inset plus one label line; the code text
|
||||
// view's own top inset then forms the single gap below the label.
|
||||
private fun headerHeight(style: CodeBlockStyle): Int {
|
||||
internal fun headerHeight(style: CodeBlockStyle): Int {
|
||||
val paint =
|
||||
TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = style.fontSize * HEADER_LABEL_SCALE
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.swmansion.enriched.markdown.segments
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.ColorFilter
|
||||
import android.graphics.Paint
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.widget.ImageView
|
||||
import androidx.appcompat.widget.AppCompatImageButton
|
||||
import com.swmansion.enriched.markdown.styles.CodeBlockStyle
|
||||
import com.swmansion.enriched.markdown.views.CopyGlyph
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* The copy control at the trailing edge of a block's header band. Code blocks
|
||||
* and quotes share it, so the band height, hit box, glyph and placement stay
|
||||
* the same on both. The band is the code block header: one label line above
|
||||
* the content inset.
|
||||
*/
|
||||
internal class HeaderCopyButton(
|
||||
context: Context,
|
||||
style: CodeBlockStyle,
|
||||
private val label: () -> CharSequence,
|
||||
) : AppCompatImageButton(context) {
|
||||
/** Height of the band, and the side of the button's square hit box. */
|
||||
val bandHeight: Int = CodeBlockContainerView.headerHeight(style)
|
||||
|
||||
private val inset: Int = CodeBlockContainerView.contentInset(style)
|
||||
|
||||
/** Vertical center of the band's content; the divider sits halfway into the inset below it. */
|
||||
val bandCenterY: Float = (bandHeight + inset / 2f) / 2f
|
||||
|
||||
init {
|
||||
background = null
|
||||
scaleType = ImageView.ScaleType.CENTER
|
||||
setImageDrawable(
|
||||
CopyIconDrawable(
|
||||
CodeBlockContainerView.secondaryColor(style.color),
|
||||
ceil(style.fontSize * ICON_SCALE).toInt(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Read live so a runtime label change reaches TalkBack without a push.
|
||||
override fun getContentDescription(): CharSequence = label()
|
||||
|
||||
fun measureInBand() {
|
||||
val spec = MeasureSpec.makeMeasureSpec(bandHeight, MeasureSpec.EXACTLY)
|
||||
measure(spec, spec)
|
||||
}
|
||||
|
||||
/** Puts the glyph's trailing edge on the container's content inset. */
|
||||
fun layoutInBand(containerWidth: Int) {
|
||||
val iconWidth = drawable?.intrinsicWidth ?: bandHeight
|
||||
val iconSlack = ((bandHeight - iconWidth) / 2).coerceAtLeast(0)
|
||||
val left = (containerWidth - inset - bandHeight + iconSlack).coerceAtLeast(0)
|
||||
val top = (bandCenterY - bandHeight / 2f).roundToInt().coerceAtLeast(0)
|
||||
layout(left, top, left + bandHeight, top + bandHeight)
|
||||
}
|
||||
|
||||
private class CopyIconDrawable(
|
||||
color: Int,
|
||||
private val size: Int,
|
||||
) : Drawable() {
|
||||
private val paint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
this.color = color
|
||||
}
|
||||
|
||||
private val glyph = CopyGlyph()
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
glyph.draw(canvas, bounds.width().toFloat(), paint)
|
||||
}
|
||||
|
||||
override fun getIntrinsicWidth() = size
|
||||
|
||||
override fun getIntrinsicHeight() = size
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
paint.alpha = alpha
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||
paint.colorFilter = colorFilter
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity() = PixelFormat.TRANSLUCENT
|
||||
}
|
||||
|
||||
private companion object {
|
||||
// Glyph box as a multiple of the code font size; iOS uses the same scale.
|
||||
const val ICON_SCALE = 1.08f
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -42,7 +42,10 @@ object CodeBlockNode {
|
||||
language: String?,
|
||||
fenceChar: String,
|
||||
): String {
|
||||
val fence = fenceChar.repeat(3)
|
||||
// A fence must be longer than any run of its character in the code, or an inner
|
||||
// fence (a Markdown example) closes the block early.
|
||||
val longestRun = Regex("${Regex.escape(fenceChar)}+").findAll(code).maxOfOrNull { it.value.length } ?: 0
|
||||
val fence = fenceChar.repeat(maxOf(3, longestRun + 1))
|
||||
return "$fence${language.orEmpty()}\n$code\n$fence"
|
||||
}
|
||||
|
||||
|
||||
+10
-2
@@ -20,6 +20,12 @@ object MarkdownASTSerializer {
|
||||
return buffer.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes the blocks inside a Blockquote back to markdown, without the
|
||||
* quote's own `> ` prefix. A quote nested inside keeps its prefix.
|
||||
*/
|
||||
fun serializeBlockquoteBody(node: MarkdownASTNode): String = serializeBlockChildren(node).trimEnd('\n')
|
||||
|
||||
/**
|
||||
* Serializes a Blockquote or Admonition node back to markdown, including
|
||||
* the `> ` prefix on every line and `> [!TYPE]` header for admonitions.
|
||||
@@ -31,8 +37,7 @@ object MarkdownASTSerializer {
|
||||
val type = node.getAttribute("admonitionType")?.takeIf { it.isNotEmpty() } ?: "note"
|
||||
sb.append("> [!${type.uppercase(java.util.Locale.ROOT)}]\n")
|
||||
}
|
||||
val body = serializeBlockChildren(node)
|
||||
for (line in body.trimEnd('\n').split("\n")) {
|
||||
for (line in serializeBlockquoteBody(node).split("\n")) {
|
||||
sb.append("> ")
|
||||
sb.append(line)
|
||||
sb.append("\n")
|
||||
@@ -220,6 +225,9 @@ object MarkdownASTSerializer {
|
||||
lines.forEachIndexed { lineIdx, line ->
|
||||
if (lineIdx == 0) {
|
||||
buffer.append(prefix)
|
||||
if (item.getAttribute("isTask") == "true") {
|
||||
buffer.append(if (item.getAttribute("taskChecked") == "true") "[x] " else "[ ] ")
|
||||
}
|
||||
} else {
|
||||
buffer.append(" ".repeat(prefix.length))
|
||||
}
|
||||
|
||||
+2
-2
@@ -185,8 +185,8 @@ object ContextMenuPopup {
|
||||
|
||||
private val copyGlyph = CopyGlyph()
|
||||
|
||||
// COPY mirrors SF Symbol doc.on.doc, DOCUMENT mirrors doc.text; the copy
|
||||
// glyph is shared with the header button in CodeBlockContainerView.
|
||||
// COPY draws Lucide's Copy icon, DOCUMENT mirrors SF Symbol doc.text; the
|
||||
// copy glyph is shared with HeaderCopyButton.
|
||||
override fun draw(canvas: Canvas) {
|
||||
val u = bounds.width() / 24f
|
||||
if (icon == Icon.COPY) {
|
||||
|
||||
+19
-82
@@ -3,40 +3,23 @@ package com.swmansion.enriched.markdown.views
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.PorterDuff
|
||||
import android.graphics.PorterDuffXfermode
|
||||
import android.graphics.RectF
|
||||
|
||||
/**
|
||||
* Draws the copy glyph so Android matches the SF Symbol doc.on.doc rendered on
|
||||
* iOS: two portrait document pages with a folded (dog-eared) top-right corner,
|
||||
* a front page in the lower-left laid over a back page in the upper-right.
|
||||
*
|
||||
* The back page is punched out where the front page (plus a hairline of
|
||||
* clearance) covers it, so the front reads as sitting on top exactly as the SF
|
||||
* Symbol does, instead of both outlines crossing. The clear is done inside an
|
||||
* offscreen layer so the punched region reveals whatever background the drawable
|
||||
* sits on, without the glyph needing to know that color.
|
||||
*
|
||||
* One instance is held per drawable rather than shared: the paths and clear
|
||||
* paint are reused across draws to keep draw() allocation-free, and two drawables
|
||||
* of different sizes must not share those buffers. All coordinates use a 24-unit
|
||||
* grid scaled to the drawable width, matching the grid the iOS symbol is authored
|
||||
* on.
|
||||
* Lucide's Copy icon, the glyph the app's own copy controls use. The outline is
|
||||
* authored on Lucide's 24-unit grid with its 2-unit stroke and scaled to the
|
||||
* drawable width. Copyright Lucide Icons and Contributors (ISC); see COPY-ICON-LICENSE.
|
||||
*/
|
||||
internal class CopyGlyph {
|
||||
private val back = Path()
|
||||
private val front = Path()
|
||||
private val backFold = Path()
|
||||
private val frontFold = Path()
|
||||
|
||||
// Color and colorFilter are irrelevant under PorterDuff.CLEAR; only the
|
||||
// widened stroke (set per draw) matters, so this is configured once.
|
||||
private val clearPaint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.FILL_AND_STROKE
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
|
||||
private val outline =
|
||||
Path().apply {
|
||||
addRoundRect(RectF(8f, 8f, 22f, 22f), 2f, 2f, Path.Direction.CW)
|
||||
moveTo(4f, 16f)
|
||||
cubicTo(2.9f, 16f, 2f, 15.1f, 2f, 14f)
|
||||
lineTo(2f, 4f)
|
||||
cubicTo(2f, 2.9f, 2.9f, 2f, 4f, 2f)
|
||||
lineTo(14f, 2f)
|
||||
cubicTo(15.1f, 2f, 16f, 2.9f, 16f, 4f)
|
||||
}
|
||||
|
||||
fun draw(
|
||||
@@ -44,58 +27,12 @@ internal class CopyGlyph {
|
||||
width: Float,
|
||||
stroke: Paint,
|
||||
) {
|
||||
val u = width / 24f
|
||||
val fold = 4f * u
|
||||
val corner = 2f * u
|
||||
|
||||
buildPage(back, 9 * u, 1 * u, 20 * u, 17 * u, fold, corner)
|
||||
buildPage(front, 3 * u, 7 * u, 14 * u, 23 * u, fold, corner)
|
||||
buildFold(backFold, 20 * u, 1 * u, fold)
|
||||
buildFold(frontFold, 14 * u, 7 * u, fold)
|
||||
clearPaint.strokeWidth = stroke.strokeWidth * 3f
|
||||
|
||||
val saved = canvas.saveLayer(0f, 0f, width, width, null)
|
||||
canvas.drawPath(back, stroke)
|
||||
canvas.drawPath(backFold, stroke)
|
||||
canvas.drawPath(front, clearPaint)
|
||||
canvas.drawPath(front, stroke)
|
||||
canvas.drawPath(frontFold, stroke)
|
||||
val saved = canvas.save()
|
||||
canvas.scale(width / 24f, width / 24f)
|
||||
val callerStrokeWidth = stroke.strokeWidth
|
||||
stroke.strokeWidth = 2f
|
||||
canvas.drawPath(outline, stroke)
|
||||
stroke.strokeWidth = callerStrokeWidth
|
||||
canvas.restoreToCount(saved)
|
||||
}
|
||||
|
||||
// A page outline whose top-right corner is cut back by fold, with the other
|
||||
// three corners rounded by corner.
|
||||
private fun buildPage(
|
||||
path: Path,
|
||||
l: Float,
|
||||
t: Float,
|
||||
r: Float,
|
||||
b: Float,
|
||||
fold: Float,
|
||||
corner: Float,
|
||||
) {
|
||||
path.rewind()
|
||||
path.moveTo(l, t + corner)
|
||||
path.quadTo(l, t, l + corner, t)
|
||||
path.lineTo(r - fold, t)
|
||||
path.lineTo(r, t + fold)
|
||||
path.lineTo(r, b - corner)
|
||||
path.quadTo(r, b, r - corner, b)
|
||||
path.lineTo(l + corner, b)
|
||||
path.quadTo(l, b, l, b - corner)
|
||||
path.close()
|
||||
}
|
||||
|
||||
// The two inner edges of the folded-over corner, at the page's top-right.
|
||||
private fun buildFold(
|
||||
path: Path,
|
||||
r: Float,
|
||||
t: Float,
|
||||
fold: Float,
|
||||
) {
|
||||
path.rewind()
|
||||
path.moveTo(r - fold, t)
|
||||
path.lineTo(r - fold, t + fold)
|
||||
path.lineTo(r, t + fold)
|
||||
}
|
||||
}
|
||||
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.view.ContextThemeWrapper
|
||||
import android.view.View
|
||||
import android.view.View.MeasureSpec
|
||||
import android.widget.ImageButton
|
||||
import com.facebook.react.bridge.JavaOnlyArray
|
||||
import com.facebook.react.bridge.JavaOnlyMap
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibilityLabels
|
||||
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
|
||||
import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType
|
||||
import com.swmansion.enriched.markdown.segments.BlockquoteContainerView
|
||||
import com.swmansion.enriched.markdown.segments.DynamicBlockProps
|
||||
import com.swmansion.enriched.markdown.segments.SegmentViewConfig
|
||||
import com.swmansion.enriched.markdown.styles.StyleConfig
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.listItem
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.taskListItem
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.text
|
||||
import com.swmansion.enriched.markdown.test.TestAstFactory.unorderedList
|
||||
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
/** The copy control on a quote: what it copies, and where it shows. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(manifest = Config.NONE, sdk = [34])
|
||||
class BlockquoteCopyTest {
|
||||
private val context: Context =
|
||||
ContextThemeWrapper(RuntimeEnvironment.getApplication(), androidx.appcompat.R.style.Theme_AppCompat)
|
||||
|
||||
private fun quoteView(): BlockquoteContainerView {
|
||||
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context)
|
||||
// No border or background, so the copy glyph is the only thing a quote paints above its text.
|
||||
val element =
|
||||
JavaOnlyMap.of(
|
||||
"fontFamily", "",
|
||||
"fontWeight", "normal",
|
||||
"fontStyle", "normal",
|
||||
"fontSize", 16.0,
|
||||
"lineHeight", 22.0,
|
||||
"color", Color.BLACK.toDouble(),
|
||||
"backgroundColor", 0.0,
|
||||
"borderColor", 0.0,
|
||||
"borderWidth", 0.0,
|
||||
"borderRadius", 0.0,
|
||||
"padding", 8.0,
|
||||
"gapWidth", 8.0,
|
||||
"marginTop", 0.0,
|
||||
"marginBottom", 0.0,
|
||||
"marginLeft", 20.0,
|
||||
"itemSpacing", 4.0,
|
||||
"bulletColor", Color.BLACK.toDouble(),
|
||||
"bulletSize", 6.0,
|
||||
"markerMinWidth", 0.0,
|
||||
"markerColor", Color.BLACK.toDouble(),
|
||||
"markerFontWeight", "normal",
|
||||
"textAlign", "left",
|
||||
"underline", false,
|
||||
"checkedColor", 0.0,
|
||||
"checkmarkColor", 0.0,
|
||||
"checkedTextColor", 0.0,
|
||||
"checkboxSize", 18.0,
|
||||
"checkboxBorderRadius", 2.0,
|
||||
"checkedStrikethrough", false,
|
||||
"particles", JavaOnlyMap.of("density", 1.0, "speed", 1.0),
|
||||
"solid", JavaOnlyMap.of("borderRadius", 0.0),
|
||||
"fontScale", 0.7,
|
||||
"baselineOffsetScale", 0.3,
|
||||
)
|
||||
val styles = JavaOnlyMap()
|
||||
ELEMENTS.forEach { styles.putMap(it, element) }
|
||||
styles.putArray("linkVariants", JavaOnlyArray())
|
||||
val style = StyleConfig(styles, context, false, 1f)
|
||||
val config =
|
||||
SegmentViewConfig(
|
||||
context = context,
|
||||
style = style,
|
||||
allowFontScaling = false,
|
||||
maxFontSizeMultiplier = 1f,
|
||||
accessibilityLabels = AccessibilityLabels(),
|
||||
selectionMenuConfig = SelectionMenuConfig(),
|
||||
textBreakStrategy = "simple",
|
||||
selectable = true,
|
||||
selectionColor = null,
|
||||
selectionHandleColor = null,
|
||||
contextMenuItemTexts = emptyList(),
|
||||
dynamicProps = DynamicBlockProps().apply { copyLabel = "Copy" },
|
||||
onLinkPress = null,
|
||||
onLinkLongPress = null,
|
||||
onTaskListItemPress = null,
|
||||
onContextMenuItemPress = null,
|
||||
)
|
||||
return BlockquoteContainerView(context, config)
|
||||
}
|
||||
|
||||
private fun node(
|
||||
type: NodeType,
|
||||
vararg children: MarkdownASTNode,
|
||||
attributes: Map<String, String> = emptyMap(),
|
||||
) = MarkdownASTNode(type, attributes = attributes, children = children.toList())
|
||||
|
||||
private fun quote(vararg children: MarkdownASTNode) = node(NodeType.Blockquote, *children)
|
||||
|
||||
private fun BlockquoteContainerView.copyButton(): ImageButton =
|
||||
(0 until childCount).map { getChildAt(it) }.filterIsInstance<ImageButton>().single()
|
||||
|
||||
private fun BlockquoteContainerView.layoutAt(width: Int) {
|
||||
measure(
|
||||
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
|
||||
)
|
||||
layout(0, 0, measuredWidth, measuredHeight)
|
||||
}
|
||||
|
||||
private fun clipboardText(): String? {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
return clipboard.primaryClip?.getItemAt(0)?.text?.toString()
|
||||
}
|
||||
|
||||
@Test fun copyButtonCopiesTheQuoteBodyWithItsFormatting() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(
|
||||
quote(
|
||||
paragraph(
|
||||
node(NodeType.Strong, text("Hello")),
|
||||
text(" team. See "),
|
||||
node(NodeType.Link, text("the PR"), attributes = mapOf("url" to "https://example.com/pr")),
|
||||
text(" - it's ready!"),
|
||||
),
|
||||
quote(paragraph(text("Nested reply"))),
|
||||
unorderedList(
|
||||
taskListItem(true, paragraph(text("Done"))),
|
||||
taskListItem(false, paragraph(text("Pending"))),
|
||||
listItem(paragraph(text("Plain"))),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals("Copy", view.copyButton().contentDescription)
|
||||
view.copyButton().performClick()
|
||||
|
||||
// Prose punctuation stays as written: a plain-text target shows backslashes literally.
|
||||
assertEquals(
|
||||
"**Hello** team. See [the PR](https://example.com/pr) - it's ready!\n\n" +
|
||||
"> Nested reply\n\n" +
|
||||
"- [x] Done\n- [ ] Pending\n- Plain",
|
||||
clipboardText(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun copyButtonCopiesTheLatestStreamedBody() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(quote(paragraph(text("First draft"))))
|
||||
view.applyBlockquoteNode(quote(paragraph(text("Second draft")), paragraph(text("With more"))))
|
||||
|
||||
view.copyButton().performClick()
|
||||
|
||||
assertEquals("Second draft\n\nWith more", clipboardText())
|
||||
}
|
||||
|
||||
@Test fun codeBlockWithAnInnerFenceStaysOneBlock() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(
|
||||
quote(
|
||||
node(
|
||||
NodeType.CodeBlock,
|
||||
text("```js\nrun()\n```\n"),
|
||||
attributes = mapOf("language" to "markdown", "fenceChar" to "`"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
view.copyButton().performClick()
|
||||
|
||||
assertEquals("````markdown\n```js\nrun()\n```\n````", clipboardText())
|
||||
}
|
||||
|
||||
@Test fun nestedQuoteCopiesOnlyItsOwnBody() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(quote(paragraph(text("Outer")), quote(paragraph(text("Inner")))))
|
||||
val nested = (0 until view.childCount).map { view.getChildAt(it) }.filterIsInstance<BlockquoteContainerView>().single()
|
||||
|
||||
nested.copyButton().performClick()
|
||||
|
||||
assertEquals("Inner", clipboardText())
|
||||
}
|
||||
|
||||
@Test fun admonitionHasNoCopyButton() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(
|
||||
node(NodeType.Admonition, paragraph(text("Careful")), attributes = mapOf("admonitionType" to "warning")),
|
||||
)
|
||||
|
||||
assertEquals(View.GONE, view.copyButton().visibility)
|
||||
}
|
||||
|
||||
@Test fun copyGlyphPaintsInsideTheHeaderBandAboveTheBody() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(quote(paragraph(text("Body"))))
|
||||
view.layoutAt(320)
|
||||
val button = view.copyButton()
|
||||
val body = view.getChildAt(0)
|
||||
|
||||
assertTrue("The control sits above the body, not over it", button.bottom <= body.top)
|
||||
assertTrue("The control stays inside the quote", button.left >= 0 && button.right <= view.width && button.top >= 0)
|
||||
|
||||
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(bitmap))
|
||||
val band = IntArray(view.width * body.top)
|
||||
bitmap.getPixels(band, 0, view.width, 0, 0, view.width, body.top)
|
||||
bitmap.recycle()
|
||||
assertTrue("The copy glyph must paint in the header band", band.any { Color.alpha(it) > 0 })
|
||||
}
|
||||
|
||||
@Test fun emptyQuoteDisablesCopy() {
|
||||
val view = quoteView()
|
||||
view.applyBlockquoteNode(quote())
|
||||
|
||||
assertFalse(view.copyButton().isEnabled)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
// Every element style the JS side sends; StyleConfig rejects a map that lacks one it reads.
|
||||
val ELEMENTS =
|
||||
listOf(
|
||||
"paragraph", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "strikethrough", "underline", "link",
|
||||
"code", "blockquote", "list", "codeBlock", "thematicBreak", "image", "inlineImage", "video", "table",
|
||||
"taskList", "math", "inlineMath", "spoiler", "superscript", "subscript", "highlight",
|
||||
)
|
||||
}
|
||||
}
|
||||
+46
-4
@@ -80,11 +80,12 @@ static CGFloat ENRMAdmonitionHeaderToBodyGap(StyleConfig *config)
|
||||
return round(config.blockquoteFontSize * 0.4);
|
||||
}
|
||||
|
||||
// Vertical space reserved above the body for the header (0 for a plain quote).
|
||||
static CGFloat ENRMAdmonitionHeaderReservedHeight(StyleConfig *config, BOOL isAdmonition)
|
||||
// Vertical space reserved above the body: the copy control's header band for a
|
||||
// plain quote, the title band for an admonition.
|
||||
static CGFloat ENRMBlockquoteHeaderReservedHeight(StyleConfig *config, BOOL isAdmonition)
|
||||
{
|
||||
if (!isAdmonition) {
|
||||
return 0;
|
||||
return [ENRMCodeBlockContainerView headerCopyBandHeightForConfig:config];
|
||||
}
|
||||
return ENRMAdmonitionHeaderContentHeight(config) + ENRMAdmonitionHeaderToBodyGap(config);
|
||||
}
|
||||
@@ -93,7 +94,7 @@ static UIEdgeInsets ENRMBlockquoteContentInsetsForNode(StyleConfig *config, BOOL
|
||||
{
|
||||
CGFloat padding = config.blockquotePadding;
|
||||
CGFloat left = ceil(config.blockquoteBorderWidth + config.blockquoteGapWidth + padding);
|
||||
CGFloat top = ceil(padding + ENRMAdmonitionHeaderReservedHeight(config, isAdmonition));
|
||||
CGFloat top = ceil(padding + ENRMBlockquoteHeaderReservedHeight(config, isAdmonition));
|
||||
CGFloat vertical = ceil(padding);
|
||||
CGFloat right = ceil(padding);
|
||||
return UIEdgeInsetsMake(top, left, vertical, right);
|
||||
@@ -112,6 +113,10 @@ static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config)
|
||||
@property (nonatomic, copy, nullable) NSString *admonitionType;
|
||||
@property (nonatomic, copy) NSString *cachedMarkdown;
|
||||
@property (nonatomic, copy) NSString *cachedPlainText;
|
||||
// The quote's body without its own `> ` prefix, for the copy button.
|
||||
@property (nonatomic, copy) NSString *cachedBodyMarkdown;
|
||||
// Shown in the header band of a plain quote; hidden for an admonition.
|
||||
@property (nonatomic, strong) ENRMHeaderCopyButton *headerCopyButton;
|
||||
@end
|
||||
|
||||
#if !TARGET_OS_OSX
|
||||
@@ -139,6 +144,11 @@ static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config)
|
||||
UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self];
|
||||
[self addInteraction:contextMenu];
|
||||
#endif
|
||||
_cachedBodyMarkdown = @"";
|
||||
_headerCopyButton = [ENRMCodeBlockContainerView headerCopyButtonForConfig:config
|
||||
target:self
|
||||
action:@selector(copyBodyToPasteboard)];
|
||||
[self addSubview:_headerCopyButton];
|
||||
self.segmentViewRegistry = [self buildChildRegistry];
|
||||
}
|
||||
return self;
|
||||
@@ -148,18 +158,50 @@ static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config)
|
||||
{
|
||||
self.admonitionType = ENRMAdmonitionTypeForNode(node);
|
||||
self.contentInsets = ENRMBlockquoteContentInsetsForNode(self.config, self.admonitionType != nil);
|
||||
self.cachedBodyMarkdown = markdownFromBlockquoteBody(node);
|
||||
self.headerCopyButton.hidden = self.admonitionType != nil;
|
||||
self.headerCopyButton.enabled = self.cachedBodyMarkdown.length > 0;
|
||||
// The host sets dynamicProps after init, so read the label on each content update.
|
||||
self.headerCopyButton.accessibilityLabel = self.dynamicProps.menuCopyLabel;
|
||||
self.cachedMarkdown = markdownFromBlockquoteNode(node);
|
||||
self.cachedPlainText = plainTextFromASTNode(node);
|
||||
NSArray<ENRMRenderedSegment *> *rendered =
|
||||
ENRMRenderBlockquoteChildren(node, self.config, self.allowFontScaling, self.lineBreakStrategy);
|
||||
[self applySegments:rendered reset:NO];
|
||||
#if !TARGET_OS_OSX
|
||||
// Segment views are added after the control; keep it above them for touches.
|
||||
[self bringSubviewToFront:self.headerCopyButton];
|
||||
[self setNeedsDisplay];
|
||||
#else
|
||||
self.needsDisplay = YES;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !TARGET_OS_OSX
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[super layoutSubviews];
|
||||
[ENRMCodeBlockContainerView layoutHeaderCopyButton:self.headerCopyButton
|
||||
width:self.bounds.size.width
|
||||
config:self.config];
|
||||
}
|
||||
#else
|
||||
- (void)layout
|
||||
{
|
||||
[super layout];
|
||||
[ENRMCodeBlockContainerView layoutHeaderCopyButton:self.headerCopyButton
|
||||
width:self.bounds.size.width
|
||||
config:self.config];
|
||||
}
|
||||
#endif
|
||||
|
||||
- (void)copyBodyToPasteboard
|
||||
{
|
||||
if (self.cachedBodyMarkdown.length > 0) {
|
||||
copyStringToPasteboard(self.cachedBodyMarkdown);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setAccessibilityLabels:(ENRMAccessibilityLabels *)accessibilityLabels
|
||||
{
|
||||
if (_accessibilityLabels == accessibilityLabels) {
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
#if !TARGET_OS_OSX
|
||||
typedef UIButton ENRMHeaderCopyButton;
|
||||
#else
|
||||
typedef NSButton ENRMHeaderCopyButton;
|
||||
#endif
|
||||
|
||||
typedef void (^ENRMCodeBlockCopyBlock)(NSString *code, NSString *language);
|
||||
typedef void (^ENRMCodeBlockPressBlock)(NSString *code, NSString *language);
|
||||
|
||||
@@ -14,6 +20,12 @@ typedef void (^ENRMCodeBlockPressBlock)(NSString *code, NSString *language);
|
||||
|
||||
- (instancetype)initWithConfig:(StyleConfig *)config;
|
||||
|
||||
// The header band and its copy control. Quotes show the same control, so the band
|
||||
// height, hit box, glyph and placement live here for both.
|
||||
+ (CGFloat)headerCopyBandHeightForConfig:(StyleConfig *)config;
|
||||
+ (ENRMHeaderCopyButton *)headerCopyButtonForConfig:(StyleConfig *)config target:(id)target action:(SEL)action;
|
||||
+ (void)layoutHeaderCopyButton:(ENRMHeaderCopyButton *)button width:(CGFloat)width config:(StyleConfig *)config;
|
||||
|
||||
- (void)applyCodeBlockNode:(MarkdownASTNode *)node;
|
||||
|
||||
- (CGFloat)measureHeight:(CGFloat)maxWidth;
|
||||
|
||||
@@ -22,12 +22,34 @@
|
||||
// lines never wrap, the height is independent of the available width.
|
||||
|
||||
static const CGFloat kENRMHeaderLabelScale = 0.85;
|
||||
// The copy glyph reads cleaner a touch smaller than the language label and at a
|
||||
// regular (not medium) weight; sized independently so the two never couple.
|
||||
static const CGFloat kENRMHeaderIconScale = 0.72;
|
||||
// The copy glyph's box as a multiple of the code font size; Android uses the same
|
||||
// scale. Sized independently of the language label so the two never couple.
|
||||
static const CGFloat kENRMHeaderIconScale = 1.08;
|
||||
static const CGFloat kENRMHeaderSecondaryAlpha = 0.6;
|
||||
static const CGFloat kENRMHeaderDividerAlpha = 0.2;
|
||||
|
||||
// Lucide's Copy icon, the glyph the app's own copy controls use, on its 24-unit
|
||||
// grid with its 2-unit stroke. Copyright Lucide Icons and Contributors (ISC); see COPY-ICON-LICENSE.
|
||||
static void ENRMDrawCopyIcon(CGContextRef context, CGFloat size)
|
||||
{
|
||||
CGContextScaleCTM(context, size / 24.0, size / 24.0);
|
||||
CGContextSetLineWidth(context, 2);
|
||||
CGContextSetLineCap(context, kCGLineCapRound);
|
||||
CGContextSetLineJoin(context, kCGLineJoinRound);
|
||||
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);
|
||||
CGMutablePathRef path = CGPathCreateMutable();
|
||||
CGPathAddRoundedRect(path, NULL, CGRectMake(8, 8, 14, 14), 2, 2);
|
||||
CGPathMoveToPoint(path, NULL, 4, 16);
|
||||
CGPathAddCurveToPoint(path, NULL, 2.9, 16, 2, 15.1, 2, 14);
|
||||
CGPathAddLineToPoint(path, NULL, 2, 4);
|
||||
CGPathAddCurveToPoint(path, NULL, 2, 2.9, 2.9, 2, 4, 2);
|
||||
CGPathAddLineToPoint(path, NULL, 14, 2);
|
||||
CGPathAddCurveToPoint(path, NULL, 15.1, 2, 16, 2.9, 16, 4);
|
||||
CGContextAddPath(context, path);
|
||||
CGContextStrokePath(context);
|
||||
CGPathRelease(path);
|
||||
}
|
||||
|
||||
// Height geometry and code-run construction shared by the instance layout path
|
||||
// and the view-free measureHeightForCodeBlockNode:, so the two cannot drift.
|
||||
|
||||
@@ -231,6 +253,52 @@ static BOOL ENRMColorIsDark(RCTUIColor *color)
|
||||
#endif
|
||||
}
|
||||
|
||||
+ (CGFloat)headerCopyBandHeightForConfig:(StyleConfig *)config
|
||||
{
|
||||
return ENRMCodeBlockContentInset(config) + ENRMCodeBlockHeaderLabelLineHeight(ENRMCodeBlockHeaderFont(config));
|
||||
}
|
||||
|
||||
+ (ENRMHeaderCopyButton *)headerCopyButtonForConfig:(StyleConfig *)config target:(id)target action:(SEL)action
|
||||
{
|
||||
#if !TARGET_OS_OSX
|
||||
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
CGFloat size = [config codeBlockFont].pointSize * kENRMHeaderIconScale;
|
||||
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(size, size)];
|
||||
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {
|
||||
ENRMDrawCopyIcon(context.CGContext, size);
|
||||
}];
|
||||
[button setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
|
||||
button.tintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
|
||||
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
|
||||
#else
|
||||
CGFloat size = [config codeBlockFont].pointSize * kENRMHeaderIconScale;
|
||||
NSImage *copyImage = [NSImage imageWithSize:NSMakeSize(size, size) flipped:YES drawingHandler:^BOOL(NSRect rect) {
|
||||
ENRMDrawCopyIcon(NSGraphicsContext.currentContext.CGContext, size);
|
||||
return YES;
|
||||
}];
|
||||
copyImage.template = YES;
|
||||
NSButton *button = [NSButton buttonWithImage:copyImage target:target action:action];
|
||||
button.bordered = NO;
|
||||
button.contentTintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
|
||||
#endif
|
||||
return button;
|
||||
}
|
||||
|
||||
+ (void)layoutHeaderCopyButton:(ENRMHeaderCopyButton *)button width:(CGFloat)width config:(StyleConfig *)config
|
||||
{
|
||||
CGFloat headerH = [self headerCopyBandHeightForConfig:config];
|
||||
CGFloat inset = ENRMCodeBlockContentInset(config);
|
||||
CGFloat iconWidth = button.intrinsicContentSize.width;
|
||||
if (iconWidth <= 0 || iconWidth > headerH) {
|
||||
iconWidth = headerH;
|
||||
}
|
||||
CGFloat iconSlack = (headerH - iconWidth) / 2;
|
||||
CGFloat buttonLeft = MAX(width - inset - headerH + iconSlack, 0);
|
||||
CGFloat headerCenterY = (headerH + inset / 2) / 2;
|
||||
CGFloat buttonTop = MAX(headerCenterY - headerH / 2, 0);
|
||||
button.frame = CGRectMake(buttonLeft, buttonTop, headerH, headerH);
|
||||
}
|
||||
|
||||
- (void)setPending:(BOOL)pending
|
||||
{
|
||||
if (_pending == pending) {
|
||||
@@ -273,28 +341,18 @@ static BOOL ENRMColorIsDark(RCTUIColor *color)
|
||||
UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self];
|
||||
[self addInteraction:contextMenu];
|
||||
|
||||
_copyButton = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
UIImageSymbolConfiguration *symbolConfig =
|
||||
[UIImageSymbolConfiguration configurationWithPointSize:[config codeBlockFont].pointSize * kENRMHeaderIconScale
|
||||
weight:UIImageSymbolWeightRegular];
|
||||
[_copyButton setImage:[UIImage systemImageNamed:@"doc.on.doc" withConfiguration:symbolConfig]
|
||||
forState:UIControlStateNormal];
|
||||
_copyButton.tintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
|
||||
[_copyButton addTarget:self action:@selector(copyCodeToPasteboard) forControlEvents:UIControlEventTouchUpInside];
|
||||
_copyButton = [ENRMCodeBlockContainerView headerCopyButtonForConfig:config
|
||||
target:self
|
||||
action:@selector(copyCodeToPasteboard)];
|
||||
[self addSubview:_copyButton];
|
||||
|
||||
_tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCodeBlockTap:)];
|
||||
_tapRecognizer.delegate = self;
|
||||
[self addGestureRecognizer:_tapRecognizer];
|
||||
#else
|
||||
NSImageSymbolConfiguration *symbolConfig =
|
||||
[NSImageSymbolConfiguration configurationWithPointSize:[config codeBlockFont].pointSize * kENRMHeaderIconScale
|
||||
weight:NSFontWeightRegular];
|
||||
NSImage *copyImage = [[NSImage imageWithSystemSymbolName:@"doc.on.doc"
|
||||
accessibilityDescription:nil] imageWithSymbolConfiguration:symbolConfig];
|
||||
_copyButton = [NSButton buttonWithImage:copyImage target:self action:@selector(copyCodeToPasteboard)];
|
||||
_copyButton.bordered = NO;
|
||||
_copyButton.contentTintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
|
||||
_copyButton = [ENRMCodeBlockContainerView headerCopyButtonForConfig:config
|
||||
target:self
|
||||
action:@selector(copyCodeToPasteboard)];
|
||||
[self addSubview:_copyButton];
|
||||
#endif
|
||||
}
|
||||
@@ -363,15 +421,7 @@ static BOOL ENRMColorIsDark(RCTUIColor *color)
|
||||
|
||||
- (void)layoutHeaderButton
|
||||
{
|
||||
CGFloat headerH = [self headerHeight];
|
||||
CGFloat iconWidth = _copyButton.intrinsicContentSize.width;
|
||||
if (iconWidth <= 0 || iconWidth > headerH) {
|
||||
iconWidth = headerH;
|
||||
}
|
||||
CGFloat iconSlack = (headerH - iconWidth) / 2;
|
||||
CGFloat buttonLeft = MAX(self.bounds.size.width - [self contentInset] - headerH + iconSlack, 0);
|
||||
CGFloat buttonTop = MAX([self headerCenterY] - headerH / 2, 0);
|
||||
_copyButton.frame = CGRectMake(buttonLeft, buttonTop, headerH, headerH);
|
||||
[ENRMCodeBlockContainerView layoutHeaderCopyButton:_copyButton width:self.bounds.size.width config:_config];
|
||||
}
|
||||
|
||||
#if !TARGET_OS_OSX
|
||||
|
||||
@@ -40,7 +40,17 @@ NSString *ENRMCodeBlockFenceChar(MarkdownASTNode *node)
|
||||
|
||||
NSString *ENRMCodeBlockFencedMarkdown(NSString *code, NSString *language, NSString *fenceChar)
|
||||
{
|
||||
NSString *fence = [@"" stringByPaddingToLength:3 withString:fenceChar startingAtIndex:0];
|
||||
// A fence must be longer than any run of its character in the code, or an inner
|
||||
// fence (a Markdown example) closes the block early.
|
||||
unichar fenceUnit = [fenceChar characterAtIndex:0];
|
||||
NSUInteger longestRun = 0;
|
||||
NSUInteger run = 0;
|
||||
for (NSUInteger index = 0; index < code.length; index++) {
|
||||
run = [code characterAtIndex:index] == fenceUnit ? run + 1 : 0;
|
||||
longestRun = MAX(longestRun, run);
|
||||
}
|
||||
NSUInteger fenceLength = MAX((NSUInteger)3, longestRun + 1);
|
||||
NSString *fence = [@"" stringByPaddingToLength:fenceLength withString:fenceChar startingAtIndex:0];
|
||||
return [NSString stringWithFormat:@"%@%@\n%@\n%@", fence, language ?: @"", code, fence];
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,10 @@ NSString *markdownFromASTNode(MarkdownASTNode *node);
|
||||
/// Useful for extracting the markdown content of a container node (e.g. a table cell).
|
||||
NSString *markdownFromASTNodeChildren(MarkdownASTNode *node);
|
||||
|
||||
/// Serializes the blocks inside a Blockquote to markdown, without the quote's own
|
||||
/// `> ` prefix. A quote nested inside keeps its prefix.
|
||||
NSString *markdownFromBlockquoteBody(MarkdownASTNode *node);
|
||||
|
||||
/// Serializes a Blockquote or Admonition node to full markdown, including `> ` line
|
||||
/// prefixes and `> [!TYPE]` header for admonitions.
|
||||
NSString *markdownFromBlockquoteNode(MarkdownASTNode *node);
|
||||
|
||||
@@ -194,6 +194,9 @@ static void appendListMarkdown(MarkdownASTNode *node, NSMutableString *buffer, B
|
||||
NSString *indent = [@"" stringByPaddingToLength:prefix.length withString:@" " startingAtIndex:0];
|
||||
for (NSUInteger l = 0; l < lines.count; l++) {
|
||||
[buffer appendString:(l == 0) ? prefix : indent];
|
||||
if (l == 0 && [item.attributes[@"isTask"] isEqualToString:@"true"]) {
|
||||
[buffer appendString:[item.attributes[@"taskChecked"] isEqualToString:@"true"] ? @"[x] " : @"[ ] "];
|
||||
}
|
||||
[buffer appendString:lines[l]];
|
||||
[buffer appendString:@"\n"];
|
||||
}
|
||||
@@ -327,6 +330,16 @@ NSString *markdownFromASTNodeChildren(MarkdownASTNode *node)
|
||||
return [buffer copy];
|
||||
}
|
||||
|
||||
NSString *markdownFromBlockquoteBody(MarkdownASTNode *node)
|
||||
{
|
||||
if (!node)
|
||||
return @"";
|
||||
|
||||
NSMutableString *body = [NSMutableString string];
|
||||
serializeBlockChildren(node, body);
|
||||
return [body stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
|
||||
}
|
||||
|
||||
NSString *markdownFromBlockquoteNode(MarkdownASTNode *node)
|
||||
{
|
||||
if (!node)
|
||||
@@ -342,11 +355,7 @@ NSString *markdownFromBlockquoteNode(MarkdownASTNode *node)
|
||||
[result appendFormat:@"> [!%@]\n", [type uppercaseString]];
|
||||
}
|
||||
|
||||
NSMutableString *body = [NSMutableString string];
|
||||
serializeBlockChildren(node, body);
|
||||
|
||||
NSString *trimmed = [body stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
|
||||
NSArray<NSString *> *lines = [trimmed componentsSeparatedByString:@"\n"];
|
||||
NSArray<NSString *> *lines = [markdownFromBlockquoteBody(node) componentsSeparatedByString:@"\n"];
|
||||
for (NSString *line in lines) {
|
||||
[result appendString:@"> "];
|
||||
[result appendString:line];
|
||||
|
||||
+14
-1
@@ -46,8 +46,18 @@ function HeadingRenderer({
|
||||
function BlockquoteRenderer({
|
||||
node,
|
||||
styles,
|
||||
renderChildren
|
||||
renderChildren,
|
||||
capabilities
|
||||
}) {
|
||||
const CustomBlockquote = capabilities.renderers?.blockquote;
|
||||
if (CustomBlockquote) {
|
||||
return /*#__PURE__*/_jsx(CustomBlockquote, {
|
||||
blockquoteProps: {
|
||||
style: styles.blockquote
|
||||
},
|
||||
children: renderChildren(node)
|
||||
});
|
||||
}
|
||||
return /*#__PURE__*/_jsx("blockquote", {
|
||||
style: styles.blockquote,
|
||||
children: renderChildren(node)
|
||||
@@ -80,11 +90,14 @@ function AdmonitionRenderer({
|
||||
fontSize: blockquote.fontSize,
|
||||
lineHeight: 1.2
|
||||
};
|
||||
// The data attributes let a copy serializer write `> [!TYPE]` instead of the title.
|
||||
return /*#__PURE__*/_jsxs("div", {
|
||||
className: ENRM_ADMONITION_CLASS,
|
||||
style: boxStyle,
|
||||
"data-enrm-admonition-type": type,
|
||||
children: [/*#__PURE__*/_jsxs("div", {
|
||||
style: headerStyle,
|
||||
"data-enrm-admonition-title": "",
|
||||
children: [/*#__PURE__*/_jsx("svg", {
|
||||
width: iconSize,
|
||||
height: iconSize,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type { MarkdownRenderers, CodeBlockRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
|
||||
export type { MarkdownRenderers, CodeBlockRendererProps, BlockquoteRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
|
||||
export type { LinkVariantStyle, LinkPillStyle } from './types/MarkdownStyle';
|
||||
export type { LinkPillContent } from './types/MarkdownTextProps';
|
||||
export type { LinkContextMenuItem, LinkRecognition, } from './types/MarkdownTextProps';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type { MarkdownRenderers, CodeBlockRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
|
||||
export type { MarkdownRenderers, CodeBlockRendererProps, BlockquoteRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
|
||||
export { EnrichedMarkdownText, default } from './web/EnrichedMarkdownText';
|
||||
export type { EnrichedMarkdownTextProps } from './types/MarkdownTextProps.web';
|
||||
export type { MarkdownStyle, Md4cFlags } from './types/MarkdownStyle';
|
||||
|
||||
+10
-5
@@ -7,14 +7,19 @@ export interface CodeBlockRendererProps {
|
||||
language: string;
|
||||
}
|
||||
export interface LinkRendererProps {
|
||||
link: LinkPressEvent;
|
||||
anchorProps: ComponentProps<'a'>;
|
||||
children: ReactNode;
|
||||
link: LinkPressEvent;
|
||||
anchorProps: ComponentProps<'a'>;
|
||||
children: ReactNode;
|
||||
}
|
||||
/** A plain quote. Admonitions keep the library's own renderer. */
|
||||
export interface BlockquoteRendererProps {
|
||||
blockquoteProps: ComponentProps<'blockquote'>;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** Custom web components. Overrides own their styling and interactions. */
|
||||
export interface MarkdownRenderers {
|
||||
blockquote?: ComponentType<BlockquoteRendererProps>;
|
||||
codeBlock?: ComponentType<CodeBlockRendererProps>;
|
||||
link?: ComponentType<LinkRendererProps>;
|
||||
link?: ComponentType<LinkRendererProps>;
|
||||
}
|
||||
//# sourceMappingURL=MarkdownRenderers.d.ts.map
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-native-enriched-markdown",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.1",
|
||||
"private": true,
|
||||
"description": "Markdown-based Rich Text solution for React Native",
|
||||
"main": "./lib/module/index",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export type {
|
||||
MarkdownRenderers,
|
||||
CodeBlockRendererProps,
|
||||
BlockquoteRendererProps,
|
||||
LinkRendererProps,
|
||||
} from './types/MarkdownRenderers';
|
||||
export type { LinkVariantStyle, LinkPillStyle } from './types/MarkdownStyle';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export type {
|
||||
MarkdownRenderers,
|
||||
CodeBlockRendererProps,
|
||||
BlockquoteRendererProps,
|
||||
LinkRendererProps,
|
||||
} from './types/MarkdownRenderers';
|
||||
export { EnrichedMarkdownText, default } from './web/EnrichedMarkdownText';
|
||||
|
||||
@@ -14,8 +14,15 @@ export interface LinkRendererProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** A plain quote. Admonitions keep the library's own renderer. */
|
||||
export interface BlockquoteRendererProps {
|
||||
blockquoteProps: ComponentProps<'blockquote'>;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** Custom web components. Overrides own their styling and interactions. */
|
||||
export interface MarkdownRenderers {
|
||||
blockquote?: ComponentType<BlockquoteRendererProps>;
|
||||
codeBlock?: ComponentType<CodeBlockRendererProps>;
|
||||
link?: ComponentType<LinkRendererProps>;
|
||||
}
|
||||
|
||||
@@ -37,7 +37,20 @@ function HeadingRenderer({ node, styles, renderChildren }: RendererProps) {
|
||||
return <Tag style={styles[Tag]}>{renderChildren(node)}</Tag>;
|
||||
}
|
||||
|
||||
function BlockquoteRenderer({ node, styles, renderChildren }: RendererProps) {
|
||||
function BlockquoteRenderer({
|
||||
node,
|
||||
styles,
|
||||
renderChildren,
|
||||
capabilities,
|
||||
}: RendererProps) {
|
||||
const CustomBlockquote = capabilities.renderers?.blockquote;
|
||||
if (CustomBlockquote) {
|
||||
return (
|
||||
<CustomBlockquote blockquoteProps={{ style: styles.blockquote }}>
|
||||
{renderChildren(node)}
|
||||
</CustomBlockquote>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<blockquote style={styles.blockquote}>{renderChildren(node)}</blockquote>
|
||||
);
|
||||
@@ -70,9 +83,10 @@ function AdmonitionRenderer({
|
||||
fontSize: blockquote.fontSize,
|
||||
lineHeight: 1.2,
|
||||
};
|
||||
// The data attributes let a copy serializer write `> [!TYPE]` instead of the title.
|
||||
return (
|
||||
<div className={ENRM_ADMONITION_CLASS} style={boxStyle}>
|
||||
<div style={headerStyle}>
|
||||
<div className={ENRM_ADMONITION_CLASS} style={boxStyle} data-enrm-admonition-type={type}>
|
||||
<div style={headerStyle} data-enrm-admonition-title="">
|
||||
<svg
|
||||
width={iconSize}
|
||||
height={iconSize}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.4",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo backend server",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -109,11 +109,11 @@
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.17.4",
|
||||
"@getpaseo/highlight": "0.17.4",
|
||||
"@getpaseo/plugin": "0.17.4",
|
||||
"@getpaseo/protocol": "0.17.4",
|
||||
"@getpaseo/relay": "0.17.4",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/highlight": "0.17.3",
|
||||
"@getpaseo/plugin": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
|
||||
@@ -237,20 +237,6 @@ second line'`,
|
||||
expect(result).toBe('[paseo__create_agent] {"cwd":"/tmp/repo","initialPrompt":"do the thing"}');
|
||||
});
|
||||
|
||||
it("summarizes a typed row by its detail when its name looks external", () => {
|
||||
const timeline: AgentTimelineItem[] = [
|
||||
toolCallItem({
|
||||
callId: "hermes-terminal",
|
||||
name: 'terminal: echo "whoami: $(whoami)" + 1 command',
|
||||
detail: { type: "shell", command: 'echo "whoami: $(whoami)" && uname -s' },
|
||||
}),
|
||||
];
|
||||
|
||||
const result = curateAgentActivity(timeline);
|
||||
|
||||
expect(result).toBe('[Shell] echo "whoami: $(whoami)" && uname -s');
|
||||
});
|
||||
|
||||
it("collapses repeated tool updates by callId", () => {
|
||||
const timeline: AgentTimelineItem[] = [
|
||||
toolCallItem({
|
||||
|
||||
@@ -84,7 +84,7 @@ function formatToolSummary(summary: string | undefined): string | null {
|
||||
function inputFromUnknownDetail(
|
||||
detail: Extract<AgentTimelineItem, { type: "tool_call" }>["detail"],
|
||||
): unknown {
|
||||
return detail.type === "unknown" ? detail.input : undefined;
|
||||
return detail.type === "unknown" ? detail.input : null;
|
||||
}
|
||||
|
||||
function projectForCuration(items: readonly AgentTimelineItem[]): AgentTimelineItem[] {
|
||||
|
||||
@@ -3168,8 +3168,15 @@ export class AgentManager {
|
||||
options?: AgentRunOptions,
|
||||
onAccepted?: () => void,
|
||||
): Promise<boolean> {
|
||||
const agent = await this.findOutOfBandRecipient(agentId);
|
||||
if (!agent) return false;
|
||||
if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) {
|
||||
await this.waitForAgentClose(agentId);
|
||||
await ensureAgentLoaded(agentId, {
|
||||
agentManager: this,
|
||||
agentStorage: this.requireRegistry(),
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
const agent = await this.ensureInteractiveSession(agentId);
|
||||
// Providers parse slash commands from the raw text, so a command another agent sent
|
||||
// must reach them without its sender envelope.
|
||||
const agentMessage = typeof prompt === "string" ? parseAgentMessage(prompt) : null;
|
||||
@@ -3215,31 +3222,6 @@ export class AgentManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
private async findOutOfBandRecipient(agentId: string): Promise<ActiveManagedAgent | null> {
|
||||
const live = this.agents.get(agentId);
|
||||
const collecting = this.collectingRuntimes.has(agentId);
|
||||
if (live?.session && !collecting && !this.historySessions.has(live.session)) {
|
||||
return live;
|
||||
}
|
||||
if (collecting || !live) {
|
||||
await this.waitForAgentClose(agentId);
|
||||
const storage = this.requireRegistry();
|
||||
// Normal dispatch owns unarchiving. Decline without loading archived history.
|
||||
if ((await storage.get(agentId))?.archivedAt) return null;
|
||||
await ensureAgentLoaded(agentId, {
|
||||
agentManager: this,
|
||||
agentStorage: storage,
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const record = await this.registry?.get(agentId);
|
||||
// Restore closes any history session. Normal dispatch can reopen the stored agent.
|
||||
if (record && (record.archivedAt || !this.agents.get(agentId)?.session)) return null;
|
||||
return this.upgradeHistorySessionUnlocked(this.requireSessionAgent(agentId));
|
||||
});
|
||||
}
|
||||
|
||||
async appendTimelineItem(
|
||||
agentId: string,
|
||||
item: AgentTimelineItem,
|
||||
@@ -3363,22 +3345,13 @@ export class AgentManager {
|
||||
/** Inside the agent's lane: a history session is upgraded before anything is applied to it. */
|
||||
private async ensureInteractiveSessionUnlocked(agentId: string): Promise<ActiveManagedAgent> {
|
||||
const agent = this.requireSessionAgent(agentId);
|
||||
if (
|
||||
this.historySessions.has(agent.session) &&
|
||||
(await this.registry?.get(agentId))?.archivedAt
|
||||
) {
|
||||
throw new Error(`Agent is archived: ${agentId}`);
|
||||
if (this.historySessions.has(agent.session)) {
|
||||
const record = await this.registry?.get(agentId);
|
||||
if (record?.archivedAt) throw new Error(`Agent is archived: ${agentId}`);
|
||||
// Reload validates the directory before releasing readable history.
|
||||
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId));
|
||||
}
|
||||
return this.upgradeHistorySessionUnlocked(agent);
|
||||
}
|
||||
|
||||
private async upgradeHistorySessionUnlocked(
|
||||
agent: ActiveManagedAgent,
|
||||
): Promise<ActiveManagedAgent> {
|
||||
if (!this.historySessions.has(agent.session)) return agent;
|
||||
// Reload validates the directory before releasing readable history.
|
||||
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agent.id));
|
||||
return this.requireSessionAgent(agent.id);
|
||||
return this.requireSessionAgent(agentId);
|
||||
}
|
||||
|
||||
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
|
||||
|
||||
@@ -25,7 +25,6 @@ import { z } from "zod";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js";
|
||||
import { createMcpHandler } from "@modelcontextprotocol/server";
|
||||
import { ensureAgentLoaded } from "./agent-loading.js";
|
||||
import { AgentManager, type ManagedAgent } from "./agent-manager.js";
|
||||
import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
@@ -3511,7 +3510,6 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
private turnStartGate: Promise<void> | null = null;
|
||||
private cancelHeldStart: (() => void) | null = null;
|
||||
private interruptGate: Promise<void> | null = null;
|
||||
private closeGate?: { signalStart: () => void; waitForRelease: Promise<void> };
|
||||
private nextStartError: Error | null = null;
|
||||
|
||||
constructor(
|
||||
@@ -3703,19 +3701,7 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
|
||||
holdClose(): { started: Promise<void>; release: () => void } {
|
||||
const started = Promise.withResolvers<void>();
|
||||
const released = Promise.withResolvers<void>();
|
||||
this.closeGate = { signalStart: started.resolve, waitForRelease: released.promise };
|
||||
return { started: started.promise, release: released.resolve };
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closeGate) {
|
||||
this.closeGate.signalStart();
|
||||
await this.closeGate.waitForRelease;
|
||||
}
|
||||
}
|
||||
async close(): Promise<void> {}
|
||||
}
|
||||
|
||||
class HeldTurnAgentClient implements AgentClient {
|
||||
@@ -3874,91 +3860,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ activeTurnBehavior: "interrupt", history: "closed" },
|
||||
{ activeTurnBehavior: "steer", history: "closed" },
|
||||
{ activeTurnBehavior: "queue", history: "closed" },
|
||||
{ activeTurnBehavior: "interrupt", history: "open" },
|
||||
{ activeTurnBehavior: "interrupt", history: "restoring" },
|
||||
] as const)(
|
||||
"an agent-scoped $activeTurnBehavior send starts a turn on an archived agent (history: $history)",
|
||||
async ({ activeTurnBehavior, history }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-archived-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
let mcpClient: Client | undefined;
|
||||
let restore: Promise<boolean> | undefined;
|
||||
let releaseHistoryClose: (() => void) | undefined;
|
||||
try {
|
||||
const sender = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const recipient = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
await manager.archiveAgent(recipient.id);
|
||||
if (history !== "closed") {
|
||||
await ensureAgentLoaded(recipient.id, {
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
const openedSessions = client.sessions.length;
|
||||
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: sender.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
mcpClient = await connectInMemoryMcpClient(server);
|
||||
if (history === "restoring") {
|
||||
const closing = client.sessions.at(-1)!.holdClose();
|
||||
releaseHistoryClose = closing.release;
|
||||
restore = manager.unarchiveSnapshot(recipient.id);
|
||||
await closing.started;
|
||||
}
|
||||
const response = await mcpClient.callTool({
|
||||
name: "send_agent_prompt",
|
||||
arguments: {
|
||||
agentId: recipient.id,
|
||||
prompt: "Start work",
|
||||
notifyOnFinish: false,
|
||||
activeTurnBehavior,
|
||||
},
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior,
|
||||
});
|
||||
const dispatch = serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(recipient.id, AbortSignal.timeout(5_000));
|
||||
releaseHistoryClose?.();
|
||||
await Promise.all([restore, dispatch]);
|
||||
expect((await storage.get(recipient.id))?.archivedAt).toBeNull();
|
||||
expect(manager.getAgent(recipient.id)?.lifecycle).toBe("running");
|
||||
expect(client.sessions).toHaveLength(openedSessions + 1);
|
||||
expect(client.sessions.at(-1)?.prompts.map(parseAgentMessage)).toEqual([
|
||||
expect.objectContaining({ text: "Start work" }),
|
||||
]);
|
||||
} finally {
|
||||
releaseHistoryClose?.();
|
||||
await restore?.catch(() => undefined);
|
||||
await mcpClient?.close();
|
||||
await removeAgentStateDir(manager, storage, workdir);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("tells an agent caller that an idle recipient starts a turn with its queued message", async () => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-idle-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
|
||||
@@ -3063,34 +3063,31 @@ test("plugin provider import keeps the stats the plugin reported with its histor
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["goose", "hermes"])(
|
||||
"resumes a %s session saved by the generic ACP provider",
|
||||
async (provider) => {
|
||||
const logger = createTestLogger();
|
||||
const harness = createProviderHarness();
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([{ ...harness.registration, id: provider }]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const client = registry[provider].createClient(logger);
|
||||
test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
const logger = createTestLogger();
|
||||
const harness = createProviderHarness();
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([{ ...harness.registration, id: "goose" }]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const client = registry.goose.createClient(logger);
|
||||
|
||||
try {
|
||||
const session = await client.resumeSession(
|
||||
{
|
||||
provider,
|
||||
sessionId: "native-session",
|
||||
nativeHandle: "native-session",
|
||||
},
|
||||
{ provider, cwd: "/tmp" },
|
||||
);
|
||||
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
|
||||
persistence: { version: 1, data: { sessionId: "native-session" } },
|
||||
});
|
||||
await session.close();
|
||||
} finally {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
},
|
||||
);
|
||||
try {
|
||||
const session = await client.resumeSession(
|
||||
{
|
||||
provider: "goose",
|
||||
sessionId: "native-goose-session",
|
||||
nativeHandle: "native-goose-session",
|
||||
},
|
||||
{ provider: "goose", cwd: "/tmp" },
|
||||
);
|
||||
expect(harness.inputs.findLast((input) => input.type === "session.open")).toMatchObject({
|
||||
persistence: { version: 1, data: { sessionId: "native-goose-session" } },
|
||||
});
|
||||
await session.close();
|
||||
} finally {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
|
||||
const logger = createTestLogger();
|
||||
|
||||
@@ -2245,20 +2245,13 @@ function encodePersistence(persistence: ProviderPersistence): string {
|
||||
return `plugin:${JSON.stringify(persistence)}`;
|
||||
}
|
||||
|
||||
// Providers whose agents were saved by the generic ACP provider before they became plugins.
|
||||
const FORMER_ACP_PROVIDERS = new Set<string>([
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
|
||||
"goose",
|
||||
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once legacy handles have migrated.
|
||||
"hermes",
|
||||
]);
|
||||
|
||||
function decodePersistence(handle: AgentPersistenceHandle): ProviderPersistence {
|
||||
const fromMetadata = handle.metadata?.pluginProviderPersistence;
|
||||
if (fromMetadata !== undefined) {
|
||||
return ProviderPersistenceSchema.parse(fromMetadata);
|
||||
}
|
||||
if (FORMER_ACP_PROVIDERS.has(handle.provider) && !handle.sessionId.startsWith("plugin:")) {
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy handles have migrated.
|
||||
if (handle.provider === "goose" && !handle.sessionId.startsWith("plugin:")) {
|
||||
return { version: 1, data: { sessionId: handle.sessionId } };
|
||||
}
|
||||
return decodePersistenceId(handle.sessionId);
|
||||
|
||||
@@ -67,9 +67,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
upstreamRef: snapshot.git.upstreamRef ?? null,
|
||||
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
|
||||
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
|
||||
upstreamState: snapshot.git.upstreamState,
|
||||
hasRemote: snapshot.git.hasRemote,
|
||||
firstPushRemote: snapshot.git.firstPushRemote,
|
||||
remoteUrl: snapshot.git.remoteUrl,
|
||||
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
|
||||
isPaseoOwnedWorktree: true,
|
||||
@@ -92,9 +90,7 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
upstreamRef: snapshot.git.upstreamRef ?? null,
|
||||
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
|
||||
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
|
||||
upstreamState: snapshot.git.upstreamState,
|
||||
hasRemote: snapshot.git.hasRemote,
|
||||
firstPushRemote: snapshot.git.firstPushRemote,
|
||||
remoteUrl: snapshot.git.remoteUrl,
|
||||
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
|
||||
isPaseoOwnedWorktree: false,
|
||||
|
||||
@@ -1091,28 +1091,29 @@ describe("speech provider config normalization", () => {
|
||||
});
|
||||
|
||||
test.each([
|
||||
["goose", "goose"],
|
||||
["goose", "/opt/bin/goose"],
|
||||
["hermes", "hermes"],
|
||||
["hermes", "/opt/bin/hermes"],
|
||||
])("migrates the legacy %s entry and preserves command overrides (%s acp)", (provider, binary) => {
|
||||
const command = [binary, "acp"];
|
||||
const overrides = {
|
||||
enabled: false,
|
||||
label: `My ${provider}`,
|
||||
env: { PROVIDER_ENV: "value" },
|
||||
models: [{ id: "primary", label: "Primary" }],
|
||||
additionalModels: [{ id: "secondary", label: "Secondary" }],
|
||||
};
|
||||
const parsed = PersistedConfigSchema.parse({
|
||||
agents: {
|
||||
providers: {
|
||||
[provider]: { ...overrides, extends: "acp", description: "Old description", command },
|
||||
["goose", "acp"],
|
||||
["/opt/bin/goose", "acp"],
|
||||
])(
|
||||
"migrates the legacy goose entry and preserves command overrides (%s %s)",
|
||||
(binary, subcommand) => {
|
||||
const command = [binary, subcommand];
|
||||
const overrides = {
|
||||
enabled: false,
|
||||
label: "My goose",
|
||||
env: { GOOSE_PROVIDER: "openai" },
|
||||
models: [{ id: "primary", label: "Primary" }],
|
||||
additionalModels: [{ id: "secondary", label: "Secondary" }],
|
||||
};
|
||||
const parsed = PersistedConfigSchema.parse({
|
||||
agents: {
|
||||
providers: {
|
||||
goose: { ...overrides, extends: "acp", description: "Old description", command },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parsed.agents?.providers?.[provider]).toEqual({
|
||||
...overrides,
|
||||
...(binary === provider ? {} : { command }),
|
||||
});
|
||||
});
|
||||
});
|
||||
expect(parsed.agents?.providers?.goose).toEqual({
|
||||
...overrides,
|
||||
...(command[0] === "goose" ? {} : { command }),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -198,30 +198,25 @@ function isLegacyProviderEntry(value: unknown): boolean {
|
||||
return typeof (command as Record<string, unknown>).mode === "string";
|
||||
}
|
||||
|
||||
// Catalog providers that moved from `extends: "acp"` to a bundled plugin with the same ID.
|
||||
const BUNDLED_FORMER_ACP_PROVIDERS = [
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy configs have migrated.
|
||||
"goose",
|
||||
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once legacy configs have migrated.
|
||||
"hermes",
|
||||
] as const;
|
||||
|
||||
function normalizeAgentProviders(value: unknown): unknown {
|
||||
if (!isConfigRecord(value)) return value;
|
||||
|
||||
const rawProviders: Record<string, unknown> = { ...value };
|
||||
for (const providerId of BUNDLED_FORMER_ACP_PROVIDERS) {
|
||||
const entry = configRecord(rawProviders[providerId]);
|
||||
if (entry?.extends !== "acp") continue;
|
||||
const { extends: _base, description: _description, command, ...overrides } = entry;
|
||||
let rawProviders = value;
|
||||
const goose = configRecord(value.goose);
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once legacy configs have migrated.
|
||||
if (goose?.extends === "acp") {
|
||||
const { extends: _base, description: _description, command, ...overrides } = goose;
|
||||
const usesDefaultCommand =
|
||||
Array.isArray(command) &&
|
||||
command.length === 2 &&
|
||||
command[0] === providerId &&
|
||||
command[0] === "goose" &&
|
||||
command[1] === "acp";
|
||||
rawProviders[providerId] = {
|
||||
...overrides,
|
||||
...(command !== undefined && !usesDefaultCommand ? { command } : {}),
|
||||
rawProviders = {
|
||||
...value,
|
||||
goose: {
|
||||
...overrides,
|
||||
...(command !== undefined && !usesDefaultCommand ? { command } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ export const builtinPlugins = [
|
||||
"fx-provider",
|
||||
"goose-provider",
|
||||
"grok-usage-source",
|
||||
"hermes-provider",
|
||||
"hoplite-provider",
|
||||
"kimi-usage-source",
|
||||
"minimax-usage-source",
|
||||
|
||||
@@ -4075,11 +4075,7 @@ describe("session checkout pull and push handling", () => {
|
||||
requestId: "request-push",
|
||||
});
|
||||
|
||||
expect(checkoutGitMocks.pushCurrentBranch).toHaveBeenCalledWith(
|
||||
"/tmp/request-worktree",
|
||||
undefined,
|
||||
{ paseoHome: "/tmp/paseo-home", worktreesRoot: undefined },
|
||||
);
|
||||
expect(checkoutGitMocks.pushCurrentBranch).toHaveBeenCalledWith("/tmp/request-worktree");
|
||||
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
|
||||
force: true,
|
||||
reason: "push",
|
||||
|
||||
@@ -10049,8 +10049,6 @@ test("workspace PR status survives session cleanup and reconnect", async () => {
|
||||
comparisonBaseRef: null,
|
||||
branchRemoteName: "origin",
|
||||
branchMergeRef: "refs/heads/feature",
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
pullRequestLookupTarget: { headRef: "feature" },
|
||||
};
|
||||
const githubStub = {
|
||||
|
||||
@@ -956,10 +956,7 @@ export class CheckoutSession {
|
||||
const { cwd, requestId } = msg;
|
||||
|
||||
try {
|
||||
await pushCurrentBranch(cwd, undefined, {
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
});
|
||||
await pushCurrentBranch(cwd);
|
||||
await this.gitMutation.notifyGitMutation(cwd, "push", { invalidateForge: true });
|
||||
this.host.emit({
|
||||
type: "checkout_push_response",
|
||||
|
||||
@@ -246,9 +246,7 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna
|
||||
upstreamRef: null,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
upstreamState: "none",
|
||||
hasRemote: false,
|
||||
firstPushRemote: null,
|
||||
diffStat: null,
|
||||
},
|
||||
forge: {
|
||||
@@ -2244,8 +2242,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
fxProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("fx"),
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
gooseProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("goose"),
|
||||
// COMPAT(hermesProvider): added in v0.17.4, remove after 2027-05-23 once host floor includes the bundled adapter.
|
||||
hermesProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("hermes"),
|
||||
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
|
||||
importSessionWorkspaceTarget: true,
|
||||
// COMPAT(importSessionSearch): added in v0.7.3, remove gate after 2027-03-02.
|
||||
|
||||
@@ -41,8 +41,6 @@ function createFacts(cwd: string): CheckoutSnapshotFacts {
|
||||
comparisonBaseRef: null,
|
||||
branchRemoteName: null,
|
||||
branchMergeRef: null,
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
pullRequestLookupTarget: { headRef: "main" },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -72,8 +72,6 @@ function createCheckoutFacts(cwd: string): CheckoutSnapshotFacts {
|
||||
comparisonBaseRef: null,
|
||||
branchRemoteName: null,
|
||||
branchMergeRef: null,
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
pullRequestLookupTarget: { headRef: "main" },
|
||||
};
|
||||
}
|
||||
@@ -1019,8 +1017,7 @@ describe("WorkspaceGitService checkout observation", () => {
|
||||
comparisonBaseRef: null,
|
||||
branchRemoteName: null,
|
||||
branchMergeRef: null,
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
upstreamStatus: null,
|
||||
};
|
||||
});
|
||||
const runGitFetch = vi.fn(async () => ({
|
||||
@@ -1163,8 +1160,7 @@ describe("WorkspaceGitService checkout observation", () => {
|
||||
comparisonBaseRef: "refs/heads/main",
|
||||
branchRemoteName: "origin",
|
||||
branchMergeRef: `refs/heads/${branch}`,
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
upstreamStatus: null,
|
||||
} satisfies CheckoutSnapshotFacts;
|
||||
});
|
||||
const getCheckoutStatus = vi.fn(async (cwd: string) =>
|
||||
|
||||
@@ -80,8 +80,6 @@ function createCheckoutFacts(
|
||||
comparisonBaseRef: null,
|
||||
branchRemoteName: null,
|
||||
branchMergeRef: null,
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
pullRequestLookupTarget: { headRef: "main" },
|
||||
...overrides,
|
||||
};
|
||||
|
||||
@@ -171,8 +171,6 @@ function createCheckoutSnapshotFacts(cwd: string): CheckoutSnapshotFacts {
|
||||
comparisonBaseRef: null,
|
||||
branchRemoteName: "origin",
|
||||
branchMergeRef: "refs/heads/main",
|
||||
upstreamStatus: { state: "none" },
|
||||
firstPushRemote: null,
|
||||
pullRequestLookupTarget: { headRef: "main" },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,14 +7,13 @@ import pLimit from "p-limit";
|
||||
import type pino from "pino";
|
||||
import type { ForgeWeb, ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages";
|
||||
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import type { CheckoutContext, UpstreamState } from "../utils/checkout-git.js";
|
||||
import type { CheckoutContext } from "../utils/checkout-git.js";
|
||||
import {
|
||||
type BranchCheckoutResolution,
|
||||
type BranchSuggestion,
|
||||
type CheckoutSnapshotFacts,
|
||||
type CheckoutDiffCompare,
|
||||
type CheckoutDiffResult,
|
||||
configuredUpstreamRef,
|
||||
getCheckoutDiff,
|
||||
getCheckoutRefDerivedState,
|
||||
getCheckoutSnapshotFacts,
|
||||
@@ -23,7 +22,6 @@ import {
|
||||
getCheckoutWorktreeState,
|
||||
getPullRequestStatus,
|
||||
forgeAuthStateFromError,
|
||||
projectUpstreamStatus,
|
||||
hasOriginRemote,
|
||||
listBranchSuggestions,
|
||||
resolveRepositoryDefaultBranch,
|
||||
@@ -183,9 +181,7 @@ export interface WorkspaceGitRuntimeSnapshot {
|
||||
upstreamRef: string | null;
|
||||
aheadOfOrigin: number | null;
|
||||
behindOfOrigin: number | null;
|
||||
upstreamState: UpstreamState;
|
||||
hasRemote: boolean;
|
||||
firstPushRemote: string | null;
|
||||
diffStat: { additions: number; deletions: number } | null;
|
||||
};
|
||||
forge: {
|
||||
@@ -2886,7 +2882,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
facts.storedBaseRef,
|
||||
facts.resolvedBaseRef,
|
||||
facts.comparisonBaseRef,
|
||||
configuredUpstreamRef(facts.upstreamStatus),
|
||||
facts.upstreamStatus?.ref,
|
||||
];
|
||||
const usesBranch = dependentRefs.some(
|
||||
(ref) => ref === branch || ref === `refs/heads/${branch}`,
|
||||
@@ -2923,7 +2919,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
facts.storedBaseRef,
|
||||
facts.resolvedBaseRef,
|
||||
facts.comparisonBaseRef,
|
||||
configuredUpstreamRef(facts.upstreamStatus),
|
||||
facts.upstreamStatus?.ref,
|
||||
configuredRemoteRef,
|
||||
shortstatRemoteRef,
|
||||
];
|
||||
@@ -3688,7 +3684,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
...latestGit,
|
||||
aheadBehind: derived.aheadBehind,
|
||||
diffStat: derived.diffStat,
|
||||
...projectUpstreamStatus(derived.upstreamStatus),
|
||||
upstreamRef: derived.upstreamStatus?.ref ?? null,
|
||||
aheadOfOrigin: derived.upstreamStatus?.aheadBehind.ahead ?? null,
|
||||
behindOfOrigin: derived.upstreamStatus?.aheadBehind.behind ?? null,
|
||||
};
|
||||
const loadedAtMs = this.deps.now().getTime();
|
||||
target.latestGitLoadedAtMs = loadedAtMs;
|
||||
@@ -3783,9 +3781,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
upstreamRef: checkoutStatus.upstreamRef,
|
||||
aheadOfOrigin: checkoutStatus.aheadOfOrigin,
|
||||
behindOfOrigin: checkoutStatus.behindOfOrigin,
|
||||
upstreamState: checkoutStatus.upstreamState,
|
||||
hasRemote: checkoutStatus.hasRemote,
|
||||
firstPushRemote: checkoutStatus.firstPushRemote,
|
||||
diffStat,
|
||||
};
|
||||
const loadedAtMs = this.deps.now().getTime();
|
||||
@@ -4440,9 +4436,7 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot {
|
||||
upstreamRef: null,
|
||||
aheadOfOrigin: null,
|
||||
behindOfOrigin: null,
|
||||
upstreamState: "none",
|
||||
hasRemote: false,
|
||||
firstPushRemote: null,
|
||||
diffStat: null,
|
||||
},
|
||||
forge: buildForgeUnavailableSnapshot(),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user