Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] fc3a47a64f fix(acp): start the optional scan budget with the listing 2026-11-24 08:45:19 +00:00
paseo-bot[bot] 5e80c6b4f0 test(server): wait for the watcher before deleting a file
The native macOS watcher starts delivering events after subscription returns. Use the existing liveness canary before removing the file under test.
2026-11-24 05:12:15 +00:00
paseo-bot[bot] c3f9dba40f test(website): check plugin search parameters by name
Native GET form submission and hydrated navigation serialize the same filters in different orders. Verify the term and ranking window in both flows.
2026-11-24 05:05:04 +00:00
paseo-bot[bot] 5e4d27f4d2 fix(acp): keep import results when extra pages stall
Once the provider supplies enough sessions, bound the time spent looking for newer ones. Return the rows already collected and close the listing connection when the extra scan ends.
2026-11-24 04:52:27 +00:00
paseo-bot[bot] 18004b5419 fix(acp): show the latest sessions in Import Session
ACP peers can return sessions in storage order. Applying the result limit before sorting discards newer sessions before the daemon receives them.
2026-11-24 04:45:45 +00:00
paseo-bot[bot] e03fe0d8e7 test(server): avoid per-file Git work in the diff stream fixture (#10633)
Stage the generated additions so both diff paths can read their patches in bulk while still comparing against HEAD.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 00:01:37 +00:00
Mohamed Boudra ff27da07bf chore(release): reconcile v0.17.4 (#10645) 2026-11-24 06:16:30 +07:00
Mohamed Boudra 1fea66215d Show Push for a branch that was never pushed (#10631)
* fix(git): offer Push for never-pushed branches and non-origin remotes

The Changes pane decided whether to offer Push from two daemon fields that
answered a different question. `aheadOfOrigin` is null both when a branch has
no upstream and when its upstream was deleted, so the app could only treat
null as a first push inside Paseo worktrees; a never-pushed branch in a
regular checkout got no Push. `hasRemote` is true only for a remote named
origin, so a branch tracking any other remote got "not connected to a remote"
while the daemon's push would have used the tracked remote.

The daemon now reports the two facts the decision needs: `upstreamState`
(tracked, none, gone, unknown) and `pushRemote`, resolved by the same
function `pushCurrentBranch` uses, so the button and the push cannot
disagree. A deleted upstream stays out of first-push in regular checkouts
so Paseo does not silently re-publish a branch whose remote copy was removed;
Paseo worktrees keep re-publishing, as before.

Both fields are optional on the wire. Against an older daemon the app keeps
the previous rule, tagged COMPAT(checkoutPushTarget).

* fix(git): keep a published branch out of first push in single-branch clones

A `--single-branch` or `--depth` clone keeps no remote-tracking ref for a
feature branch, so git reports a blank upstream even after `push -u` set
`branch.<name>.remote` and `.merge`. The daemon read that blank as "never
pushed", and a regular checkout then offered Push, which re-created the
branch after it was deleted on the remote.

A blank upstream is now "none" only when no upstream is configured. A
configured upstream git cannot resolve is "unknown". Paseo worktrees keep
publishing in that state, as they did before upstreamState existed.

* fix(git): do not push to the upstream when git pushes the branch elsewhere

With `branch.<name>.pushRemote` or `remote.pushDefault` naming a fork, git
pushes a branch that tracks `upstream/main` to the fork. The daemon ignored a
push remote that has no HEAD push refspec and pushed HEAD to the tracked
branch instead, which is the shared base. Offering Push for remotes not named
origin made that reachable in checkouts that have no origin.

The push target is now empty when git's push remote differs from the remote
the daemon would use, so status reports no push remote and the push refuses
with a message that names git's push remote. Push remotes Paseo configures
itself carry a HEAD push refspec and are unaffected.

* fix(git): withhold Pull and push when Push has no remote to send to

Pull and push checked only that origin exists, so it stayed available when the daemon reports no push remote. It then pulled, which can create a merge commit, and failed at the push. It now uses the same push remote check as Push.

* fix(git): do not extend pushes to a differently named upstream branch

The daemon pushes a tracked branch to its upstream branch whatever that
branch is called, so `feature` tracking `main` pushes to `main`. The app
offered Push only in checkouts that have origin. Reporting a push remote for
any tracked remote made the same push reachable without origin, for example
`feature` tracking `upstream/main`.

Without origin, the upstream is now a push target only when its branch has
the same name as the local branch, which is the push git itself makes by
default. Checkouts that have origin behave as before.

* fix(git): limit the Push fix to never-pushed branches

Push for branches that track a remote other than origin is removed from
this change. Supporting it means following Git's push settings
(branch.<name>.pushRemote, remote.pushDefault, push.default) for every
remote, and each review round found another setup where the push would
have gone to the wrong place.

The daemon's push is the same as before this branch again. What stays is
upstreamState on the checkout status, which lets the app tell a
never-pushed branch from one whose remote copy was deleted, and the app
rule that offers a first push in a regular checkout.

* fix(git): withhold first Push when git pushes the branch to another remote

The daemon publishes a branch with no upstream to origin. Git picks the
remote for a push from branch.<name>.pushRemote, then remote.pushDefault,
so in a fork setup `git push` sends a new branch to the fork while Push
sent it to origin. Offering a first push in regular checkouts made that
reachable there.

The checkout status now reports firstPushRemote: origin when git would
push the branch to origin too, null otherwise. A regular checkout offers
a first push only when it is set. Paseo worktrees and the daemon's push
are unchanged.

The never-pushed browser test read the branch's upstream as soon as the
remote had the branch. Git writes the upstream after that, so the test
now waits for it.

* fix(git): check the first push destination again before pushing

The app offers a first push from a checkout status that can be older
than the git configuration. If remote.pushDefault or
branch.<name>.pushRemote changed after the status loaded, Push still
published the branch to origin.

The daemon now makes the same check when it pushes: in a regular
checkout, a branch with no upstream is published to origin only when git
would push it there too. Otherwise the push is refused with a message
that names git's remote. Paseo worktrees, and branches whose upstream is
a local branch, push as before.

* fix(git): describe a missing upstream without blaming the remote

A branch can track a local branch. When that branch is deleted, git reports the upstream as gone, and the Push menu said the branch was deleted on the remote, which never happened. The message now says the tracked branch no longer exists, which is true for a local and a remote upstream.

* test(server): expect the Paseo home in the session push call

The checkout session now gives pushCurrentBranch the Paseo home, so the push can tell a Paseo worktree from a regular checkout. The session test still asserted the old single argument.

* fix(git): read a branch's Git settings under its real name when a tag shares it

With a tag of the same name, git spells the current branch heads/<name>. The daemon used that spelling to read branch.<name>.* settings and the branch ref, so it found none of them. A never-pushed branch set to push to a fork was reported as publishable to origin and was pushed there, a branch whose remote copy was deleted was reported as never pushed, and a branch tracking a fork was pushed to origin.

The status and push paths now read those settings and the ref under the name from the symbolic HEAD ref. getCurrentBranch, the branch name sent to clients, and the refspec of the first push keep git's short spelling, which is the right one for a revision.
2026-11-24 04:11:09 +07:00
Mohamed Boudra ecb2501458 Show the full command of Hermes terminal calls (#10614)
* fix(hermes): show the full command of Hermes terminal calls

Hermes titles a terminal call with its own summary ("terminal: echo ... + 5
commands") and sends the full command only as "$ <command>" start content,
which the completion update replaces. It sends no rawInput, so the generic
ACP adapter fell back to the title and the full command was never stored.

Hermes now runs as a bundled runAcpProvider plugin. Its terminal transformer
lifts the start text into input.command and carries it across the
completion through context.previous; any other shape passes through, so an
upstream format change shows the title again instead of breaking.

The plugin ACP shim now builds the standard row for each ACP tool kind, so
read/search/fetch rows keep their shape after the move. Transformers still
see raw input, output and content, and a detail they set wins.

Moving Hermes surfaced two regressions, both fixed:
- The activity curator printed "[Shell] null" for typed rows whose name
  looks namespaced (Hermes titles contain ":"); the raw-input fallback now
  applies only to unknown rows.
- Agents saved by the generic adapter stored Hermes session-mode IDs, but
  the shim uses Hermes's edit_approval_policy config option as ACP prefers,
  so resume failed with invalid_params. legacyModes translates them.

Legacy extends:"acp" Hermes configs migrate on load, keeping a custom
command, gated on server_info.features.hermesProvider.

* fix(acp): keep Hermes approvals, Auto Accept, and session import after bundling

Moving Hermes from the generic ACP adapter to the plugin ACP shim dropped
behavior the adapter had:

- Approvals were built without a detail, so the approval card had no diff.
  Approvals with no rawInput also failed with "Invalid params".
- The shim had no unattended mode, and agents that saved the adapter's
  `auto_accept` toggle sent it back to Hermes as an unknown config option.
  Hermes now offers a Full access mode, and a saved `auto_accept: true`
  resumes in it.
- Session listing read only the first page of `session/list`, so the import
  picker lost sessions past the first 50.
- Edit rows whose result is text lost that text instead of showing it as
  the diff, unlike the generic adapter.

* fix(acp): keep a mode chosen after a saved Auto Accept toggle

The generic ACP adapter's `auto_accept` setting stays in the agent's saved
options after the move to a bundled ACP provider. It put the agent back in
the unattended mode on every reopen, even after the user chose another
mode, so approvals stopped asking again after a reload. The toggle now
counts only while the saved mode is one the generic adapter wrote, which
the agent no longer offers.

* fix(acp): keep whitespace-only text in Edit rows

The standard Edit row read old and new text with the same helper as
titles and paths, which skips blank strings. An edit that replaces text
with spaces lost its new text, so the app drew it as a deletion. File
text is now kept as written, as the previous formatter did.
2026-11-23 23:24:12 +07:00
Mohamed Boudra 065e4a95b1 Show OpenCode Go usage for the credential OpenCode serves Go with (#10612)
* fix(usage): follow the OpenCode credential that serves Go

OpenCode 2 serves OpenCode Go with the active credential on the
opencode integration when that Console workspace has Go, and uses the
opencode-go key only otherwise. The usage card now reads the same
credential: a Console sign-in (with its organization) first, then a key
on opencode, then the opencode-go key. Keys read the Console Go status
before the usage API, which floors each percent.

Refs #6428

* fix(usage): keep OpenCode Go usage on the sign-in through outages

A Console outage no longer shows the fallback key's usage, and a slow
Console probe no longer uses up the refresh deadline for a working key.

* fix(usage): skip OpenCode keys saved for another Console

A key on the opencode integration can name its own Console server.
Usage now leaves it alone instead of sending it to opencode.ai.
2026-11-23 23:07:16 +07:00
paseo-bot[bot]andThomas Van 309a44c480 Deliver urgent messages to archived agents (#10611)
* fix(server): deliver urgent messages to archived agents

An out-of-band probe rejected urgent messages before normal dispatch could restore the archived recipient. Decline the probe so the existing dispatch path restores the recipient and delivers the prompt.

Co-authored-by: Thomas Van <9481872+thomasvan@users.noreply.github.com>

* fix(server): deliver urgent messages during agent restore

When restore closes the history session, the stored agent still exists. Let normal dispatch reopen it instead of treating the missing session as a dispatch failure.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Thomas Van <9481872+thomasvan@users.noreply.github.com>
2026-11-23 15:58:52 +00:00
paseo-bot[bot]andIvan Pantic 5f424e2e94 Show OpenCode Go usage for database-stored logins (#8729)
OpenCode 2 keeps logins in opencode.db and never updates auth.json, so the Go usage card was missing or sent a stale key (HTTP 401). The card now reads the selected opencode-go credential from the v2 database, read-only, and keeps auth.json for OpenCode 1. A login OpenCode 2 imports keeps its account identity.

Closes #6428

Co-authored-by: Ivan Pantic <panta@talentkit.io>
2026-11-23 21:54:04 +07:00
paseo-bot[bot] 4d472c2804 test(server): verify image hashing yields to the event loop (#10574)
Observe a loop turn before the first filesystem request. Timer gaps also count CPU work that belongs to other callbacks.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-23 12:43:23 +00:00
Mohamed Boudra 182c1aa192 Keep git commands from adopting bare-repository-shaped directories (#10587)
* fix(server): keep git from adopting bare-repository-shaped directories

Git discovery treats any directory holding `HEAD`, `config`, `objects/` and
`refs/` as a bare repository, at the working directory or in a parent. Daemon
git commands then ran with that directory's config. They now pass
`-c safe.bareRepository=explicit`. The flag is left off only when the working
directory is a bare repository that a linked worktree's `.git` file points back
to, so the bare + linked-worktree layout keeps working.

The diff reader ran `git status` inside every submodule path. An uninitialized
submodule has no `.git`, so git walked up to whatever repository sat above it.
The reader now skips submodules without `.git` and pins `GIT_DIR=.git` for
initialized ones.

The worktree-include plugin spawns git directly and gets the same flags.

* fix(server): stop bare-repository discovery on Git before 2.38

Git releases before 2.38 ignore `safe.bareRepository`, so the runner's flag
did nothing there. On those releases the runner now follows git's discovery
order from `cwd` itself. If it reaches a directory that looks like a bare
repository before any `.git`, it pins `GIT_DIR` to the missing `<cwd>/.git`
and git reports that no repository was found, which matches what newer
releases do with the flag. The git version is read once per process.

The worktree-include plugin needs no fallback: it runs git at a checkout
root, where discovery stops at that checkout's own `.git`.

* test(server): keep fixtures independent of git discovery timing

The fetch fixture ran `update-server-info` from inside a plain bare remote.
With `safe.bareRepository=explicit`, git now refuses that unless the
repository is named, so the fixture passes `--git-dir`.

The slow-cadence poll test let the service read `remote.origin.url` through
real git while timers were faked. The runner now checks the working directory
before it spawns, and fake timers do not wait for that file-system work. The
test now injects the repository host and slug like its neighbors do.

* fix(server): refresh live diffs when an uninitialized submodule's commit changes

Skipping `git status` for an uninitialized submodule left its worktree
identity empty, so staging a different commit kept the same identity. Open
diffs then reused the previous patch. The identity is now the commit that the
comparison's index records for that path.

* fix(server): read an uninitialized submodule's commit at stage 0 explicitly

A path such as `0:sub` made `:<path>` read as stage 0 of `sub`. Naming stage 0 keeps the rest of the argument as the full path.

* test(server): supply repository identity to fake-timer poll tests

The poll tests advance a fake clock, but their repository host and slug
lookups ran real git. Git launches now read the filesystem before
spawning, so that real work could finish after the clock had already
advanced, and the expected reads were missed intermittently.

* fix(server): name a recorded bare repository root explicitly for git

Git commands at a bare repository root used to run only while a linked
worktree pointed back to it. After the last checkout of a bare repository
was archived, that link was gone, so Restore failed with "cannot use bare
repository". A bare repository with no checkouts has the same files on disk
as a bare-repository-shaped directory, so the files cannot tell them apart.

Git now never discovers a bare repository by its directory. Worktree
creation, archive, and Restore receive their repository root from Paseo's
records, and they run inside runWithRepositoryRoot. That scope names a bare
root through GIT_DIR, for commands at that exact root only. It is read when
a command is submitted, because the git scheduler can start the process
from another async context.

* fix(server): list worktrees of a bare repository that only Paseo checkouts use

Archiving by slug or branch lists worktrees at the recorded repository root.
When that root is a bare repository with no `.git`, explicit bare-repository
handling made `git worktree list` fail there. Listing, branch-off preparation
and ref fetching now name the recorded root the same way creating and
removing worktrees already do.

* test(server): give the bare-repository restore fixture a commit identity

A bare clone does not copy the source checkout's local user.name and user.email, so the fixture commit failed on runners without a global identity.

* test(server): make bare-repository tests hold on Windows runners

The tests compared 8.3 short temp paths with the long paths that git and
async realpath report, compared git's forward-slash paths as raw strings, and
read files that the runner's core.autocrlf had converted to CRLF. Temp
directories now resolve through realpathSync.native, git paths go through
path.resolve, and the bare fixtures set their config on the bare repository,
because a bare clone does not copy the source checkout's local config.
2026-11-23 17:50:47 +07:00
paseo-bot[bot] 8fa709532c fix(claude): allow Auto mode on hosted providers (#6904)
Claude Code supports Auto mode on Bedrock and Vertex, but Paseo removed it from the catalog and rejected explicit selections before reaching Claude Code. Remove that obsolete eligibility gate while preserving the existing default modes and SDK error handling.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-23 17:01:22 +07:00
126 changed files with 4932 additions and 3751 deletions
+20
View File
@@ -1,5 +1,25 @@
# 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
+20
View File
@@ -1,5 +1,25 @@
# 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
### 修复
+1 -33
View File
@@ -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. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead.
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`).
### Adding a generic ACP provider
@@ -627,32 +627,6 @@ 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:
@@ -853,12 +827,6 @@ A config.json with multiple custom providers:
"extends": "acp",
"label": "Google Gemini",
"command": ["gemini", "--acp"]
},
"hermes": {
"extends": "acp",
"label": "Hermes",
"command": ["hermes", "acp"]
}
}
}
-16
View File
@@ -146,22 +146,6 @@ quietly relying on:
The fix for transforms is Gotcha 3. The fix for context is Gotcha 7.
### The portal patch
`patches/@gorhom+portal+1.0.14.patch` moves portal state out of the provider's
context value and into a store each `PortalHost` subscribes to. Upstream keeps
every host's portals in one context value at the app root, so each portal mount,
update and unmount changed that value and React searched every mounted fiber
for consumers. That cost grows with the retained panels: a hover card took
about 3 ms of it in a fresh window and 16 ms after a few hours. With the store,
a portal change renders only its own host.
Do not put per-overlay state in a context that wraps the app for the same
reason. Give the consumers a store to subscribe to.
The patch also keys each portal in its host (upstream PR #62). Without the key,
closing one overlay remounted every later overlay in the same host.
## Gotcha 3 — Keyboard layout and portal anchors
`composer/dock` owns the stationary viewport, bottom-anchored surface, composer
+7 -3
View File
@@ -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 and fx use this for catalog opt-in. Add writes `{ "enabled": true }`
under `agents.providers`. Hoplite, fx, goose, and Hermes 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,8 +583,12 @@ 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`. 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
`@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
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 -10
View File
@@ -86,7 +86,7 @@ mounts—never at module evaluation time.
## Dynamic Pixel Styles On Web
Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and inserts a CSS rule into `#unistyles-web` for it, then deletes the rule when the last element using it unmounts. Pointer-driven positioning turns into a rule insert and delete per move.
Avoid feeding changing pixel values such as `{ top, left }`, `{ maxHeight }`, or `{ minWidth }` into the `style` prop of Unistyles-managed React Native components on web. The web runtime hashes each distinct style object by value and appends a CSS rule to `#unistyles-web`; those rules are not reclaimed during the page lifetime, so pointer-driven positioning can turn into steady stylesheet growth.
Use the inline style escape hatch below for high-churn values. Do not split a component into plain/web/native variants just to keep one measured value out of the CSS registry. Raw DOM wrappers are reserved for real DOM infrastructure, such as terminal hosts, virtualized web rows, or third-party drag wrappers.
@@ -224,7 +224,6 @@ Quick confirmation in DevTools console:
```js
[...document.styleSheets]
.flatMap((s) => [...(s.cssRules || [])])
.flatMap((r) => (r.cssRules ? [...r.cssRules] : [r]))
.map((r) => r.cssText)
.filter((t) => t.includes("unistyles") && t.includes("> *"));
```
@@ -367,14 +366,6 @@ colors. Keep this patch until upstream reads the scheme through separate lists.
The desktop browser E2E checks both transition directions in an isolated Electron
process, because Playwright's focus emulation prevents real hidden-page behavior.
The stylesheet patch backports upstream PR #1354 (3.8.0). Unistyles 3.2.4 rewrote
the whole text of `#unistyles-web` whenever a class was added or removed, and
the browser then restyled the entire document: about 5 ms each time, several
times for one hover card. The backport changes one CSSOM rule per class instead.
The tag therefore has no text; read its rules through `sheet.cssRules`. Classes
without a media query sit inside an `@media all` group. Assert on the stylesheet
in E2E with `packages/app/e2e/support/helpers/shared-stylesheet.ts`.
Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in
`patches/` is inert unless that script knows which installed package activates
it.
@@ -0,0 +1,7 @@
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
@@ -0,0 +1,7 @@
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
@@ -0,0 +1,7 @@
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
@@ -0,0 +1,7 @@
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
View File
@@ -1 +1 @@
sha256-W725BRG14xajMsR4t8Y3NmxppMnJ8AUd7Kdb6F7LmMw=
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.3",
"version": "0.17.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.3",
"version": "0.17.4",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37541,7 +37541,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.3",
"version": "0.17.4",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39694,13 +39694,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.3",
"version": "0.17.4",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/server": "0.17.3",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/server": "0.17.4",
"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.3",
"version": "0.17.4",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39963,7 +39963,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"version": "0.17.4",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40252,7 +40252,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.3",
"version": "0.17.4",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40282,7 +40282,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@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.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"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.3",
"version": "0.17.4",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40351,7 +40351,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.17.1",
"version": "0.17.4",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40367,7 +40367,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.3",
"version": "0.17.4",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40589,17 +40589,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"@getpaseo/highlight": "0.17.3",
"@getpaseo/plugin": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@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",
"@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.3",
"version": "0.17.4",
"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.3",
"version": "0.17.4",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.3",
"version": "0.17.4",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -471,6 +471,33 @@ 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) => {
@@ -2122,6 +2149,68 @@ 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,10 +1,17 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
import {
readSharedStylesheetChanges,
rememberSharedStylesheet,
} from "../support/helpers/shared-stylesheet";
interface DragMeasurement {
observer: MutationObserver;
stylesheetMutations: number;
}
declare global {
interface Window {
__PASEO_EXPLORER_DRAG_MEASUREMENT__?: DragMeasurement;
}
}
async function waitForResizePaint(page: Page): Promise<void> {
await page.evaluate(
@@ -16,8 +23,23 @@ async function waitForResizePaint(page: Page): Promise<void> {
}
async function beginResizeMeasurement(page: Page): Promise<void> {
await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__!());
await rememberSharedStylesheet(page);
await page.evaluate(() => {
const stylesheet = document.getElementById("unistyles-web");
if (!stylesheet) throw new Error("Shared stylesheet is missing");
globalThis.__PASEO_RESET_RENDER_PROFILE__!();
const measurement: DragMeasurement = {
stylesheetMutations: 0,
observer: new MutationObserver((records) => {
measurement.stylesheetMutations += records.length;
}),
};
measurement.observer.observe(stylesheet, {
childList: true,
subtree: true,
characterData: true,
});
window.__PASEO_EXPLORER_DRAG_MEASUREMENT__ = measurement;
});
}
async function previewExplorerResize(page: Page, distance: number) {
@@ -39,14 +61,16 @@ async function previewExplorerResize(page: Page, distance: number) {
await waitForResizePaint(page);
}
const during = (await explorer.boundingBox())!.width;
const measurement = {
stylesheetChanges: await readSharedStylesheetChanges(page),
paneRenders: await page.evaluate(() =>
Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {})
const measurement = await page.evaluate(() => {
const state = window.__PASEO_EXPLORER_DRAG_MEASUREMENT__!;
state.observer.disconnect();
return {
stylesheetMutations: state.stylesheetMutations,
paneRenders: Object.entries(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {})
.filter(([id]) => id.startsWith("SplitPaneView:"))
.reduce((sum, [, reasons]) => sum + (reasons.render ?? 0), 0),
),
};
};
});
await page.mouse.up();
await waitForResizePaint(page);
const after = (await explorer.boundingBox())!.width;
@@ -68,7 +92,7 @@ async function expectExplorerWidthSurvivesReload(page: Page, width: number): Pro
await expect.poll(async () => (await explorer.boundingBox())?.width).toBeCloseTo(width, 0);
}
test("Explorer drag previews without rerendering panes or changing the shared stylesheet", async ({
test("Explorer drag previews without rerendering panes or rewriting the shared stylesheet", async ({
page,
withWorkspace,
}) => {
@@ -93,9 +117,9 @@ test("Explorer drag previews without rerendering panes or changing the shared st
).toBe(true);
const grown = await previewExplorerResize(page, -100);
const shrunk = await previewExplorerResize(page, 50);
expect(grown.stylesheetChanges).toEqual({ added: 0, removed: 0, rebuilt: 0 });
expect(grown.stylesheetMutations).toBe(0);
expect(grown.paneRenders).toBe(0);
expect(shrunk.stylesheetChanges).toEqual({ added: 0, removed: 0, rebuilt: 0 });
expect(shrunk.stylesheetMutations).toBe(0);
expect(shrunk.paneRenders).toBe(0);
await expectExplorerWidthSurvivesReload(page, shrunk.width);
});
@@ -25,10 +25,6 @@ import { projectEquivalenceViewKey } from "../support/helpers/project-view-key";
import { escapeRegex } from "../support/helpers/regex";
import { openFilesPanel } from "../support/helpers/workspace-tabs";
import { seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
readSharedStylesheetChanges,
rememberSharedStylesheet,
} from "../support/helpers/shared-stylesheet";
const GITHUB_REMOTE_URL = "https://github.com/test-owner/test-repo.git";
@@ -433,32 +429,6 @@ test.describe("Sidebar workspace list", () => {
}
});
test("workspace hover card opens and closes without rebuilding the shared stylesheet", async ({
page,
}) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-stylesheet-" });
try {
await gotoAppShell(page);
await waitForSidebarProject(page, path.basename(workspace.repoPath));
await movePointerAwayFromWorkspaceHoverCard(page);
await rememberSharedStylesheet(page);
await openWorkspaceHoverCard(page, workspace.workspaceId);
const opened = await readSharedStylesheetChanges(page);
// The card brings styles nothing else on screen uses, so the stylesheet has to grow.
expect(opened.added).toBeGreaterThan(0);
expect(opened.rebuilt).toBe(0);
await rememberSharedStylesheet(page);
await movePointerAwayFromWorkspaceHoverCard(page);
await expectWorkspaceHoverCardClosed(page);
expect((await readSharedStylesheetChanges(page)).rebuilt).toBe(0);
} finally {
await workspace.cleanup();
}
});
test("workspace hover card closes when the pointer leaves a clicked row", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hover-click-leave-" });
@@ -1,60 +0,0 @@
import type { Page } from "@playwright/test";
/**
* The shared stylesheet is `#unistyles-web`: one rule per generated style class, for the whole app.
* Replacing a rule that is still in use makes the browser restyle the entire document, so a spec
* remembers the rules, performs an interaction, and reads back what happened to them.
*/
export interface SharedStylesheetChanges {
/** Rules for classes the interaction introduced. */
added: number;
/** Rules for classes nothing uses any more. */
removed: number;
/** Rules still in use that were thrown away and created again. */
rebuilt: number;
}
declare global {
interface Window {
__PASEO_SHARED_STYLESHEET_RULES__?: Map<string, CSSRule>;
}
}
function readSharedStylesheetRules(): Map<string, CSSRule> {
const tag = document.getElementById("unistyles-web");
if (!(tag instanceof HTMLStyleElement) || !tag.sheet) {
throw new Error("Shared stylesheet is missing");
}
const rules = new Map<string, CSSRule>();
const collect = (list: CSSRuleList, group: string) => {
for (const rule of list) {
if (rule instanceof CSSStyleRule) rules.set(`${group}${rule.selectorText}`, rule);
else if (rule instanceof CSSMediaRule) collect(rule.cssRules, `${rule.conditionText} `);
}
};
collect(tag.sheet.cssRules, "");
return rules;
}
export async function rememberSharedStylesheet(page: Page): Promise<void> {
await page.evaluate(
`window.__PASEO_SHARED_STYLESHEET_RULES__ = (${readSharedStylesheetRules.toString()})()`,
);
}
export async function readSharedStylesheetChanges(page: Page): Promise<SharedStylesheetChanges> {
return page.evaluate(`(() => {
const before = window.__PASEO_SHARED_STYLESHEET_RULES__;
if (!before) throw new Error("Shared stylesheet was not remembered");
const after = (${readSharedStylesheetRules.toString()})();
const changes = { added: 0, removed: 0, rebuilt: 0 };
for (const [selector, rule] of after) {
if (!before.has(selector)) changes.added += 1;
else if (before.get(selector) !== rule) changes.rebuilt += 1;
}
for (const selector of before.keys()) {
if (!after.has(selector)) changes.removed += 1;
}
return changes;
})()`);
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.3",
"version": "0.17.4",
"private": true,
"main": "index.ts",
"scripts": {
@@ -1,27 +1,15 @@
import React, { act, Profiler, useEffect, useState } from "react";
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, expect, test } from "vitest";
import { Portal, PortalHost, PortalProvider } from "@gorhom/portal";
import { Portal, PortalProvider } from "@gorhom/portal";
import { FloatingPanelPortalHost, measureFloatingPanelPortalHost } from "./floating-panel-portal";
async function mount(element: React.ReactElement) {
const container = document.createElement("div");
container.style.cssText = "position:relative;width:800px;height:600px";
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => root.render(element));
return {
container,
render: (next: React.ReactElement) => act(async () => root.render(next)),
unmount: async () => {
await act(async () => root.unmount());
container.remove();
},
};
}
describe("Floating panel host lifetime", () => {
test("removing the newest host preserves the surviving host measurement", async () => {
const container = document.createElement("div");
container.style.cssText = "position:relative;width:800px;height:600px";
document.body.appendChild(container);
const root = createRoot(container);
function Content({ overlap }: { overlap: boolean }) {
return (
<PortalProvider shouldAddRootHost={false}>
@@ -33,106 +21,20 @@ describe("Floating panel host lifetime", () => {
</PortalProvider>
);
}
const view = await mount(<Content overlap={true} />);
try {
await act(async () => root.render(<Content overlap={true} />));
expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({
width: 800,
height: 600,
});
await view.render(<Content overlap={false} />);
await act(async () => root.render(<Content overlap={false} />));
expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({
width: 800,
height: 600,
});
} finally {
await view.unmount();
}
});
});
const rendered: string[] = [];
function record(id: string) {
rendered.push(id);
}
describe("Portal hosts", () => {
test("opening a portal renders its own host and no other", async () => {
let setCardOpen: (open: boolean) => void = () => {};
function Card() {
const [open, setOpen] = useState(false);
setCardOpen = setOpen;
if (!open) return null;
return (
<Portal hostName="sidebar" name="card">
<div data-testid="card">Workspace</div>
</Portal>
);
}
const view = await mount(
<PortalProvider shouldAddRootHost={false}>
<Profiler id="sidebar" onRender={record}>
<PortalHost name="sidebar" />
</Profiler>
<Profiler id="workspace" onRender={record}>
<PortalHost name="workspace" />
</Profiler>
<Card />
</PortalProvider>,
);
try {
rendered.length = 0;
await act(async () => setCardOpen(true));
expect(view.container.querySelector('[data-testid="card"]')?.textContent).toBe("Workspace");
expect(rendered).toContain("sidebar");
expect(rendered).not.toContain("workspace");
rendered.length = 0;
await act(async () => setCardOpen(false));
expect(view.container.querySelector('[data-testid="card"]')).toBeNull();
expect(rendered).not.toContain("workspace");
} finally {
await view.unmount();
}
});
test("closing an earlier portal keeps a later portal mounted", async () => {
let menuMounts = 0;
function Menu() {
useEffect(() => {
menuMounts += 1;
}, []);
return <div data-testid="menu">Menu</div>;
}
function Content({ tooltip }: { tooltip: boolean }) {
return (
<PortalProvider shouldAddRootHost={false}>
<PortalHost name="workspace" />
{tooltip && (
<Portal hostName="workspace" name="tooltip">
<span data-testid="tooltip">Tooltip</span>
</Portal>
)}
<Portal hostName="workspace" name="menu">
<Menu />
</Portal>
</PortalProvider>
);
}
const view = await mount(<Content tooltip={true} />);
try {
expect(view.container.querySelector('[data-testid="tooltip"]')).not.toBeNull();
expect(menuMounts).toBe(1);
await view.render(<Content tooltip={false} />);
expect(view.container.querySelector('[data-testid="tooltip"]')).toBeNull();
expect(view.container.querySelector('[data-testid="menu"]')).not.toBeNull();
expect(menuMounts).toBe(1);
} finally {
await view.unmount();
await act(async () => root.unmount());
container.remove();
}
});
});
@@ -244,6 +244,7 @@ const CATALOG_DATA = [
},
{
id: "hermes",
bundledProvider: { hostFeature: "hermesProvider" },
title: "Hermes",
description: "Nous Research self-improving AI agent",
version: "manual",
+209
View File
@@ -7,6 +7,7 @@ import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readUpstreamState,
type BuildGitActionsInput,
} from "./policy";
import { deriveMergeCapability, type ForgeSpecificStatusFacts } from "./merge-capability";
@@ -76,6 +77,8 @@ function createInput(
pullRequestMergeable: "UNKNOWN",
mergeCapability: deriveMergeCapability(pullRequestGithub),
hasRemote: false,
hasFirstPushRemote: rest.hasRemote ?? false,
upstream: "tracked",
isPaseoOwnedWorktree: false,
isOnBaseBranch: true,
canMergeLocally: true,
@@ -169,6 +172,10 @@ 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");
@@ -346,6 +353,7 @@ describe("git-actions-policy", () => {
const actions = buildGitActions(
createInput({
hasRemote: true,
upstream: "none",
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
aheadCount: 1,
@@ -361,6 +369,207 @@ 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({
+51 -9
View File
@@ -2,7 +2,11 @@ import type { ReactElement } from "react";
import type { ActionStatus } from "@/components/ui/dropdown-menu";
import { i18n } from "@/i18n/i18next";
import type { CheckoutPrMergeMethod, PullRequestMergeable } from "@getpaseo/protocol/messages";
import type {
CheckoutPrMergeMethod,
CheckoutStatusResponse,
PullRequestMergeable,
} from "@getpaseo/protocol/messages";
import type { MergeCapability } from "./merge-capability";
@@ -73,6 +77,25 @@ 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;
@@ -89,6 +112,9 @@ 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;
@@ -554,12 +580,22 @@ function canPush(input: BuildGitActionsInput): boolean {
}
function hasPushableCommits(input: BuildGitActionsInput): boolean {
if ((input.aheadOfOrigin ?? 0) > 0) {
return true;
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;
}
// 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 {
@@ -664,10 +700,16 @@ function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefi
if ((input.behindOfOrigin ?? 0) > 0) {
return i18n.t("workspace.git.actions.unavailable.pushBehind");
}
if (!hasPushableCommits(input)) {
return i18n.t("workspace.git.actions.unavailable.pushNothing");
if (hasPushableCommits(input)) {
return undefined;
}
return undefined;
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");
}
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
+12
View File
@@ -15,9 +15,11 @@ 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";
@@ -129,6 +131,8 @@ interface DerivedGitActionsState {
behindOfOrigin: number | null;
hasPullRequest: boolean;
hasRemote: boolean;
hasFirstPushRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
canMergeLocally: boolean;
@@ -180,6 +184,8 @@ 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),
@@ -668,6 +674,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
behindOfOrigin,
hasPullRequest,
hasRemote,
hasFirstPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
canMergeLocally,
@@ -699,6 +707,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
hasRemote,
hasFirstPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
canMergeLocally,
@@ -807,6 +817,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
}, [
isGit,
hasRemote,
hasFirstPushRemote,
upstream,
hasPullRequest,
prStatus?.url,
prStatus?.state,
@@ -151,20 +151,26 @@ describe("ACP provider catalog", () => {
});
});
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: {},
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: {},
},
},
},
});
});
});
},
);
@@ -24,9 +24,10 @@ 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") {
if (feature !== "gooseProvider" && feature !== "hermesProvider") {
throw new Error(`Update the host to add ${entry.title}.`);
}
}
+1
View File
@@ -912,6 +912,7 @@ export const ar: TranslationResources = {
pushNoRemote: "الدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
pushBehind: "الدفع غير متاح حتى الآن نظرًا لوجود تغييرات أحدث يجب إدخالها أولاً",
pushNothing: "خدمة الدفع غير متاحة لأنه لا يوجد شيء جديد لإرساله",
pushUpstreamGone: "الدفع غير متاح لأن الفرع الذي يتتبعه هذا الفرع لم يعد موجودًا",
pullAndPushNoRemote:
"السحب والدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
pullAndPushDirty:
+2
View File
@@ -913,6 +913,8 @@ 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:
+2
View File
@@ -925,6 +925,8 @@ 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:
+1
View File
@@ -926,6 +926,7 @@ 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:
+2
View File
@@ -919,6 +919,8 @@ export const ja: TranslationResources = {
"このブランチはまだリモートに接続されていないため、プッシュはここでは利用できません",
pushBehind: "取り込む必要がある新しい変更があるため、まだプッシュは利用できません",
pushNothing: "プッシュする変更がないため、プッシュは利用できません",
pushUpstreamGone:
"このブランチが追跡しているブランチが存在しないため、プッシュは利用できません",
pullAndPushNoRemote:
"このブランチはまだリモートに接続されていないため、プル&プッシュはここでは利用できません",
pullAndPushDirty:
+1
View File
@@ -913,6 +913,7 @@ export const ko: TranslationResources = {
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 푸시를 사용할 수 없습니다",
pushBehind: "먼저 가져와야 할 최신 변경 사항이 있어 아직 푸시를 사용할 수 없습니다",
pushNothing: "새로 보낼 항목이 없어 푸시를 사용할 수 없습니다",
pushUpstreamGone: "이 브랜치가 추적하는 브랜치가 더 이상 없어 푸시를 사용할 수 없습니다",
pullAndPushNoRemote:
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 풀 후 푸시를 사용할 수 없습니다",
pullAndPushDirty:
+2
View File
@@ -921,6 +921,8 @@ 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:
+2
View File
@@ -924,6 +924,8 @@ export const ru: TranslationResources = {
"Отправка изменений недоступна: эта ветка ещё не связана с удалённым репозиторием.",
pushBehind: "Отправка изменений пока недоступна: сначала получите более новые изменения.",
pushNothing: "Отправка изменений недоступна: нет новых изменений для отправки.",
pushUpstreamGone:
"Отправка изменений недоступна: ветка, которую отслеживает эта ветка, больше не существует.",
pullAndPushNoRemote:
"Получение и отправка изменений недоступны: эта ветка ещё не связана с удалённым репозиторием.",
pullAndPushDirty:
+1
View File
@@ -908,6 +908,7 @@ 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 的传入变更",
@@ -1,41 +0,0 @@
import React, { act, useState } from "react";
import { createRoot } from "react-dom/client";
import { expect, test } from "vitest";
let setLabel: (label: string) => void = () => {};
function Row({ label }: { label: string }) {
return <div>{label}</div>;
}
function List() {
const [label, setState] = useState("first");
setLabel = setState;
return <Row label={label} />;
}
function reactMeasures(): PerformanceEntry[] {
return performance
.getEntriesByType("measure")
.filter((entry) => JSON.stringify((entry as PerformanceMeasure).detail ?? "").includes("⚛"));
}
// React's development build reports renders to the browser's performance timeline. The browser
// keeps every measure for the life of the page, so a long session held millions of them.
test("React's development render timings do not pile up in the performance timeline", async () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
try {
await act(async () => root.render(<List />));
for (const label of ["second", "third", "fourth"]) {
await act(async () => setLabel(label));
}
expect(container.textContent).toBe("fourth");
expect(reactMeasures()).toHaveLength(0);
} finally {
await act(async () => root.unmount());
container.remove();
}
});
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/server": "0.17.3",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/server": "0.17.4",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"@getpaseo/relay": "0.17.3",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.17.3",
"version": "0.17.4",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.3",
"version": "0.17.4",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.17.3",
"version": "0.17.4",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@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.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/client": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -13,14 +13,15 @@ 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,
@@ -31,6 +32,7 @@ import type {
AcpVendorUpdate,
RunAcpProviderOptions,
} from "../acp.js";
import { standardToolCallDetail } from "./tool-call-detail.js";
import {
PROVIDER_PROTOCOL_VERSION,
ProviderEventSchema,
@@ -48,6 +50,7 @@ import {
type ProviderLaunch,
type ProviderModel,
type ProviderPermissionResponse,
type ProviderToolCallDetail,
type ProviderPersistence,
type ProviderSessionConfig,
type ProviderSetting,
@@ -288,6 +291,7 @@ async function listSessions(
input: Extract<ProviderInput, { type: "sessions" }>,
state: AcpConnectionState,
): Promise<void> {
const extraScanDeadline = performance.now() + EXTRA_SESSION_SCAN_BUDGET_MS;
const runtime = await AcpRuntime.start({
options: state.options,
launch: state.launch,
@@ -296,8 +300,11 @@ async function listSessions(
emit: state.emit,
});
try {
const response = await runtime.listSessions(input.cwd);
const selected = input.limit ? response.sessions.slice(0, input.limit) : response.sessions;
const selected = await runtime.listSessions({
cwd: input.cwd,
limit: input.limit,
extraScanDeadline,
});
state.emit({
type: "sessions",
requestId: input.requestId,
@@ -313,6 +320,10 @@ async function listSessions(
}
}
function sessionUpdatedAt(session: SessionInfo): number {
return Date.parse(session.updatedAt ?? "") || 0;
}
function retireSession(state: AcpConnectionState, sessionId: string): void {
if (state.sessions.delete(sessionId)) {
state.emit({ type: "session.closed", sessionId });
@@ -408,14 +419,15 @@ interface ActivePrompt {
}
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
const SESSION_SCAN_LIMIT = 500;
const EXTRA_SESSION_SCAN_BUDGET_MS = 2_000;
// 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: AcpToolCallSource;
source: AcpToolCallSnapshot;
presentation: AcpToolCallSnapshot;
}
@@ -916,8 +928,38 @@ class AcpRuntime {
return true;
}
listSessions(cwd?: string) {
return this.call(this.connection.listSessions({ cwd }));
/** Selects the most recent sessions from a bounded scan of the provider's pages. */
async listSessions({
cwd,
limit,
extraScanDeadline,
}: {
cwd?: string;
limit?: number;
extraScanDeadline: number;
}): Promise<SessionInfo[]> {
const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT);
const sessions: SessionInfo[] = [];
let cursor: string | undefined;
// ACP does not guarantee that sessions arrive in recency order.
for (let pages = 0; pages < SESSION_SCAN_LIMIT; pages += 1) {
// Once we have enough rows, pages can improve the order only within the original budget.
const remainingMs =
cursor && sessions.length >= wanted ? extraScanDeadline - performance.now() : undefined;
if (remainingMs !== undefined && remainingMs <= 0) break;
const request = this.call(this.connection.listSessions({ cwd, cursor }));
const page =
remainingMs === undefined
? await request
: await withTimeout(request, remainingMs, "ACP listing scan budget expired").catch(
() => undefined,
);
if (!page) break;
sessions.push(...page.sessions.slice(0, SESSION_SCAN_LIMIT - sessions.length));
cursor = page.nextCursor ?? undefined;
if (!cursor || sessions.length === SESSION_SCAN_LIMIT) break;
}
return sessions.sort((a, b) => sessionUpdatedAt(b) - sessionUpdatedAt(a)).slice(0, wanted);
}
async drainNotifications(): Promise<void> {
@@ -1072,17 +1114,41 @@ class AcpRuntime {
const requested: AcpConfigChange[] = [];
if (config.model) requested.push({ target: "model", value: config.model });
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
const mode = config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined);
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));
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(config.settings)) {
for (const [id, value] of Object.entries(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[] {
@@ -1282,6 +1348,7 @@ 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();
@@ -1294,6 +1361,7 @@ 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,
@@ -1562,6 +1630,21 @@ 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,
@@ -1581,25 +1664,7 @@ class AcpRuntime {
current !== undefined &&
this.liveOpenToolIds.has(current.id) &&
this.toolKeepsTurnOpen(current);
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,
},
};
}
const { source, presentation: snapshot } = this.presentToolCall(update);
this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
if (this.replayWindow === null) {
@@ -2179,8 +2244,8 @@ function ownConnectorStream(source: Stream): {
function mergeToolCallSnapshot(
update: ToolCall | ToolCallUpdate,
current: AcpToolCallSource | undefined,
): AcpToolCallSource {
current: AcpToolCallSnapshot | undefined,
): AcpToolCallSnapshot {
return {
id: update.toolCallId,
name: firstText(update.name, current?.name),
@@ -2190,10 +2255,7 @@ 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 ?? [],
diff:
update.content === undefined
? current?.diff
: update.content?.find((item) => item.type === "diff"),
content: update.content === undefined ? current?.content : jsonValue(update.content),
};
}
@@ -2367,21 +2429,12 @@ 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 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 detail = toolCallDetail(snapshot);
const status =
snapshot.status === "in_progress" || snapshot.status === "pending"
? "running"
@@ -2416,6 +2469,7 @@ 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;
@@ -0,0 +1,164 @@
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;
}
+437
View File
@@ -9,6 +9,7 @@ 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";
@@ -6724,3 +6725,439 @@ 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("returns enough sessions and closes the connection when another page stalls", async () => {
const harness = connectorHarness({
capabilities: { sessionCapabilities: { list: {} } },
handleRequest(runtime, request) {
if (request.method !== "session/list") return false;
const { cursor } = request.params as { cursor?: string };
if (!cursor) {
runtime.respond(request, {
sessions: [{ sessionId: "s1", cwd: "/repo", title: "First page" }],
nextCursor: "stalled",
});
}
return true;
},
});
const connection = await runAcpProvider({
id: "stalled-listing",
label: "Stalled listing",
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", limit: 1 });
await expect.poll(() => countRequests(harness.instances[1], "session/list")).toBe(2);
const listed = await waitForEvent(events, (event) => event.type === "sessions");
expect(listed).toMatchObject({ sessions: [{ title: "First page" }] });
await expect.poll(() => harness.instances[1].readsCanceled).toBe(true);
expect(harness.instances[1].writesClosed).toBe(true);
} finally {
const listing = harness.instances[1];
if (listing && !listing.readsCanceled) listing.closeFromAgent();
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();
}
});
});
+11 -1
View File
@@ -117,9 +117,14 @@ 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;
}
@@ -150,9 +155,14 @@ 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[] },
context: AcpContext & {
mcpServerNames?: readonly string[];
/** The call as Paseo last presented it, after every transformer. Absent on its first update. */
previous?: AcpToolCallSnapshot;
},
): AcpToolCallSnapshot;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.17.3",
"version": "0.17.4",
"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"].flatMap((name) =>
["hopliteProvider", "fxProvider", "gooseProvider", "hermesProvider"].flatMap((name) =>
[undefined, false, true].map((value) => [name, value] as const),
),
)("accepts optional bundled provider capability (%s: %s)", (name, value) => {
+13
View File
@@ -4168,6 +4168,8 @@ 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.
@@ -5816,6 +5818,17 @@ 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(),
});
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.17.1",
"version": "0.17.4",
"private": true,
"description": "Markdown-based Rich Text solution for React Native",
"main": "./lib/module/index",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.17.3",
"version": "0.17.4",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.17.3",
"version": "0.17.4",
"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.3",
"@getpaseo/highlight": "0.17.3",
"@getpaseo/plugin": "0.17.3",
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@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",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -237,6 +237,20 @@ 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 : null;
return detail.type === "unknown" ? detail.input : undefined;
}
function projectForCuration(items: readonly AgentTimelineItem[]): AgentTimelineItem[] {
@@ -3168,15 +3168,8 @@ export class AgentManager {
options?: AgentRunOptions,
onAccepted?: () => void,
): Promise<boolean> {
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);
const agent = await this.findOutOfBandRecipient(agentId);
if (!agent) return false;
// 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;
@@ -3222,6 +3215,31 @@ 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,
@@ -3345,13 +3363,22 @@ 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)) {
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));
if (
this.historySessions.has(agent.session) &&
(await this.registry?.get(agentId))?.archivedAt
) {
throw new Error(`Agent is archived: ${agentId}`);
}
return this.requireSessionAgent(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);
}
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
@@ -25,6 +25,7 @@ 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";
@@ -3510,6 +3511,7 @@ 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(
@@ -3701,7 +3703,19 @@ class HeldTurnAgentSession implements AgentSession {
});
}
async close(): Promise<void> {}
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;
}
}
}
class HeldTurnAgentClient implements AgentClient {
@@ -3860,6 +3874,91 @@ 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,31 +3063,34 @@ test("plugin provider import keeps the stats the plugin reported with its histor
}
});
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);
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);
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();
}
});
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();
}
},
);
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
const logger = createTestLogger();
@@ -2245,13 +2245,20 @@ 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);
}
// 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:")) {
if (FORMER_ACP_PROVIDERS.has(handle.provider) && !handle.sessionId.startsWith("plugin:")) {
return { version: 1, data: { sessionId: handle.sessionId } };
}
return decodePersistenceId(handle.sessionId);
@@ -0,0 +1,54 @@
import { expect, test } from "vitest";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
import { ClaudeAgentClient } from "./agent.js";
const hostedEnvironments = [
{ transport: "Bedrock", env: { CLAUDE_CODE_USE_BEDROCK: "1" } },
{ transport: "Vertex", env: { CLAUDE_CODE_USE_VERTEX: "true" } },
];
test.each(hostedEnvironments)(
"offers Auto mode on $transport while preserving its default mode",
async ({ env }) => {
const client = new ClaudeAgentClient({
logger: createTestLogger(),
runtimeSettings: { env },
resolveVersion: async () => "2.1.263",
discoverModels: async () => [],
});
const catalog = await client.fetchCatalog({ cwd: process.cwd() });
expect(catalog.modes?.map((mode) => mode.id)).toContain("auto");
expect(catalog.defaultModeId).toBe("default");
},
);
test.each(hostedEnvironments)(
"passes an explicit Auto selection on $transport to Claude Code",
async ({ env }) => {
const sdkError = new Error("Claude Code rejected this request");
let requestedMode: string | undefined;
let requestedEnv: NodeJS.ProcessEnv | undefined;
const client = new ClaudeAgentClient({
logger: createTestLogger(),
runtimeSettings: { env },
resolveBinary: async () => "/test/claude",
queryFactory: ({ options }) => {
requestedMode = options.permissionMode;
requestedEnv = options.env;
throw sdkError;
},
});
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
try {
await expect(session.setMode("auto")).rejects.toBe(sdkError);
expect(requestedMode).toBe("auto");
expect(requestedEnv).toMatchObject(env);
} finally {
await session.close();
}
},
);
@@ -201,23 +201,6 @@ test("exposes and applies auto permission mode", async () => {
}
});
test("rejects auto mode when Claude Code uses Bedrock", async () => {
const previousBedrock = process.env.CLAUDE_CODE_USE_BEDROCK;
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
const session = await createSession();
try {
await expect(session.setMode("auto")).rejects.toThrow(
"Claude Auto mode requires the Anthropic API and is not supported when Claude Code uses Bedrock",
);
expect(sdkQueryFactory).not.toHaveBeenCalled();
} finally {
restoreEnvValue("CLAUDE_CODE_USE_BEDROCK", previousBedrock);
await session.close();
}
});
test.each([
{ env: {}, expected: "auto" },
{ env: { CLAUDE_CODE_USE_BEDROCK: "1" }, expected: "default" },
@@ -293,40 +276,6 @@ test("allows launch env to disable inherited Bedrock transport for auto mode", a
}
});
test("fails an auto mode turn when Claude Code uses Vertex", async () => {
const previousVertex = process.env.CLAUDE_CODE_USE_VERTEX;
process.env.CLAUDE_CODE_USE_VERTEX = "true";
sdkQueryFactory.mockImplementation(() => {
throw new Error("query should not start");
});
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory: sdkQueryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
modeId: "auto",
});
try {
const events = await collectUntilTerminal(streamSession(session, "hello"));
const failure = events.find(
(event): event is Extract<AgentStreamEvent, { type: "turn_failed" }> =>
event.type === "turn_failed",
);
expect(failure?.error).toContain(
"Claude Auto mode requires the Anthropic API and is not supported when Claude Code uses Vertex",
);
expect(sdkQueryFactory).not.toHaveBeenCalled();
} finally {
restoreEnvValue("CLAUDE_CODE_USE_VERTEX", previousVertex);
await session.close();
}
});
test("switches an auto mode session to another mode when Claude Code uses Bedrock", async () => {
const previousBedrock = process.env.CLAUDE_CODE_USE_BEDROCK;
process.env.CLAUDE_CODE_USE_BEDROCK = "1";
@@ -1056,37 +1056,11 @@ function isTruthyEnvValue(value: string | undefined): boolean {
);
}
function claudeAutoModeUnavailableOn(env: NodeJS.ProcessEnv): "Bedrock" | "Vertex" | null {
if (isTruthyEnvValue(env.CLAUDE_CODE_USE_BEDROCK)) {
return "Bedrock";
}
if (isTruthyEnvValue(env.CLAUDE_CODE_USE_VERTEX)) {
return "Vertex";
}
return null;
}
function assertClaudeModeCanRun(mode: PermissionMode, env: NodeJS.ProcessEnv): void {
if (mode !== "auto") {
return;
}
const transport = claudeAutoModeUnavailableOn(env);
if (transport === null) {
return;
}
throw new Error(
`Claude Auto mode requires the Anthropic API and is not supported when Claude Code uses ${transport}. Select another permission mode or unset the ${transport === "Bedrock" ? "CLAUDE_CODE_USE_BEDROCK" : "CLAUDE_CODE_USE_VERTEX"} environment variable.`,
);
}
function claudeModeCatalog(env: NodeJS.ProcessEnv): {
modes: AgentMode[];
defaultModeId: PermissionMode;
} {
if (claudeAutoModeUnavailableOn(env)) {
return { modes: DEFAULT_MODES.filter((mode) => mode.id !== "auto"), defaultModeId: "default" };
}
return { modes: DEFAULT_MODES, defaultModeId: "auto" };
function claudeDefaultMode(env: NodeJS.ProcessEnv): PermissionMode {
return isTruthyEnvValue(env.CLAUDE_CODE_USE_BEDROCK) ||
isTruthyEnvValue(env.CLAUDE_CODE_USE_VERTEX)
? "default"
: "auto";
}
function coerceSessionMetadata(metadata: AgentMetadata | undefined): Partial<AgentSessionConfig> {
@@ -1813,10 +1787,10 @@ export class ClaudeAgentClient implements AgentClient {
discoveredModelIds,
),
);
const modeCatalog = claudeModeCatalog(env);
return {
models,
...modeCatalog,
modes: DEFAULT_MODES,
defaultModeId: claudeDefaultMode(env),
...(incomplete ? { incomplete } : {}),
};
}
@@ -1826,7 +1800,7 @@ export class ClaudeAgentClient implements AgentClient {
}
async resolveDefaultModeId({ env: launchEnv }: ResolveAgentDefaultModeInput): Promise<string> {
return claudeModeCatalog(this.buildProviderEnv(launchEnv)).defaultModeId;
return claudeDefaultMode(this.buildProviderEnv(launchEnv));
}
private buildProviderEnv(launchEnv?: Record<string, string>): NodeJS.ProcessEnv {
@@ -2951,7 +2925,6 @@ class ClaudeAgentSession implements AgentSession {
}
const normalized = isPermissionMode(modeId) ? modeId : "default";
assertClaudeModeCanRun(normalized, this.harnessEnvironment);
const previousMode = this.currentMode;
const previousQuery = this.query;
const activeQuery = await this.ensureQuery(normalized);
@@ -4011,7 +3984,6 @@ class ClaudeAgentSession implements AgentSession {
const providerOptions = applyClaudeToolPolicy(sdkProviderOptions, this.config.toolPolicy);
const settingsOptions = await this.buildSettingsOptions(providerOptions);
const sdkEnv = this.harnessEnvironment;
assertClaudeModeCanRun(permissionMode, sdkEnv);
const claudeBinary = await this.resolveBinary();
this.logger.debug(
@@ -185,29 +185,39 @@ test("repeated content is reused without rewriting the attachment", async () =>
test("64 MiB materialization leaves the event loop responsive and preserves bytes", async () => {
const bytes = Buffer.alloc(64 * 1024 * 1024, 37);
const data = bytes.toString("base64");
// Main-thread CPU time between ticks bounds the decode and hash work done on the loop;
// wall-clock gaps on shared CI runners also count preemption and timer granularity.
// File writes stay on fs/promises, so they never block the loop.
const threadCpuMs = () => {
const { user, system } = process.threadCpuUsage();
return (user + system) / 1000;
};
let previous = threadCpuMs();
let longest = 0;
const probe = setInterval(() => {
const now = threadCpuMs();
longest = Math.max(longest, now - previous);
previous = now;
}, 1);
const materializing = new AsyncLocalStorage<boolean>();
let loopAdvanced = false;
let yieldedBeforeFilesystem: boolean | undefined;
const hook = createHook({
init(_id, type) {
// The first filesystem request follows hashing. A later turn could
// come from filesystem I/O even if hashing blocked the event loop.
if (
type === "FSREQPROMISE" &&
materializing.getStore() &&
yieldedBeforeFilesystem === undefined
) {
yieldedBeforeFilesystem = loopAdvanced;
}
},
});
const probe = setImmediate(() => {
loopAdvanced = true;
});
hook.enable();
try {
const result = await materializeProviderImage({ data, mimeType: "image/png" });
await new Promise((resolve) => setTimeout(resolve, 5));
console.log(`64 MiB attachment longest blocking stretch: ${longest.toFixed(2)} ms CPU`);
expect(longest).toBeLessThan(50);
expect(readFileSync(result.path).equals(bytes)).toBe(true);
rmSync(result.path, { force: true });
const result = await materializing.run(true, () =>
materializeProviderImage({ data, mimeType: "image/png" }),
);
try {
expect(yieldedBeforeFilesystem).toBe(true);
expect(readFileSync(result.path).equals(bytes)).toBe(true);
} finally {
rmSync(result.path, { force: true });
}
} finally {
clearInterval(probe);
hook.disable();
clearImmediate(probe);
}
});
@@ -67,7 +67,9 @@ 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,
@@ -90,7 +92,9 @@ 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,
@@ -0,0 +1,68 @@
// An ACP peer that returns sessions in storage order, with an optional page boundary.
const readline = require("node:readline");
const { existsSync, renameSync, writeFileSync } = require("node:fs");
const path = require("node:path");
const stalledListing = process.argv.indexOf("--stall-after-first-page");
const controlDir = stalledListing === -1 ? null : process.argv[stalledListing + 1];
if (process.argv.includes("--version")) {
process.stdout.write("1.5.13\n");
process.exit(0);
}
const sessions = Array.from({ length: 317 }, (_, index) => ({
sessionId: `session-${index}`,
cwd: process.cwd(),
title: `September session ${index}`,
updatedAt: "2026-09-08T11:36:19Z",
}));
sessions[42] = {
...sessions[42],
title: "Latest November session",
updatedAt: "2026-11-23T04:07:46Z",
};
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
if (id === undefined) return;
let response;
if (method === "initialize") {
response = {
result: { protocolVersion: 1, agentCapabilities: { sessionCapabilities: { list: {} } } },
};
} else if (method === "session/list") {
if (controlDir) {
if (params.cursor) {
writeFileSync(path.join(controlDir, "second-page"), "");
return;
}
const marker = path.join(controlDir, "first-page");
writeFileSync(marker + ".tmp", String(process.pid));
renameSync(marker + ".tmp", marker);
const gate = setInterval(() => {
if (!existsSync(path.join(controlDir, "release-first-page"))) return;
clearInterval(gate);
process.stdout.write(
JSON.stringify({
jsonrpc: "2.0",
id,
result: { sessions: sessions.slice(0, 42), nextCursor: "next" },
}) + "\n",
);
}, 10);
return;
}
const pageSize = process.argv.includes("--paginated") ? 42 : sessions.length;
response = {
result: params.cursor
? { sessions: sessions.slice(pageSize) }
: {
sessions: sessions.slice(0, pageSize),
nextCursor: pageSize < sessions.length ? "next" : null,
},
};
} else {
response = { error: { code: -32601, message: `Unsupported method ${method}` } };
}
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, ...response }) + "\n");
});
@@ -314,6 +314,8 @@ test("streams whole-file batches and answers a same-socket ping before the revis
).join("\n") + "\n";
writeFileSync(join(cwd, `${file}.ts`), content);
}
// Stage the fixture so Git reads the added files in bulk. They are still new relative to HEAD.
git(cwd, "add", ".");
expect(ctx.client.getLastServerInfoMessage()).toMatchObject({
features: { diffSubscription: true },
});
@@ -1,5 +1,7 @@
import { describe, test, expect } from "vitest";
import { describe, test, expect, vi } from "vitest";
import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import os from "node:os";
import path from "node:path";
import { loadConfig } from "../config.js";
@@ -165,6 +167,122 @@ test("Antigravity creates an agent and answers a prompt with real agy", async ({
}
}, 120000);
test.each(["one page", "two pages"])(
"Antigravity lists the latest importable sessions from %s in storage order",
async (pages) => {
const command = [
process.execPath,
path.resolve(import.meta.dirname, "antigravity-session-list-fixture.cjs"),
];
if (pages === "two pages") command.push("--paginated");
const daemon = await createTestPaseoDaemon({
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: { antigravity: { command, paseoTools: { enabled: false } } },
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.17.3",
});
const providers = ["antigravity"];
try {
await client.connect();
await client.refreshProvidersSnapshot({ cwd: daemon.paseoHome, providers });
const search = await client.fetchRecentProviderSessions({
providers,
limit: 5,
query: "November",
});
expect(search.entries.map((session) => session.title)).toEqual(["Latest November session"]);
const wide = await client.fetchRecentProviderSessions({ providers, limit: 100 });
expect(wide.entries[0]?.title).toBe("Latest November session");
const recent = await client.fetchRecentProviderSessions({ providers });
expect(recent.entries).toHaveLength(20);
expect(recent.entries[0]?.title).toBe("Latest November session");
} finally {
await client.close();
await daemon.close();
}
},
30_000,
);
test("Antigravity returns a late full page before Import Session times out", async () => {
const controlDir = await mkdtemp(path.join(os.tmpdir(), "paseo-antigravity-listing-"));
const command = [
process.execPath,
path.resolve(import.meta.dirname, "antigravity-session-list-fixture.cjs"),
"--stall-after-first-page",
controlDir,
];
const daemon = await createTestPaseoDaemon({
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: { antigravity: { command, paseoTools: { enabled: false } } },
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.17.3",
});
const providers = ["antigravity"];
try {
await client.connect();
await client.refreshProvidersSnapshot({ cwd: daemon.paseoHome, providers });
vi.useFakeTimers({ toFake: ["performance", "setTimeout", "clearTimeout"] });
const result = client.fetchRecentProviderSessions({ providers });
let returned = false;
const markReturned = () => {
returned = true;
};
void result.then(markReturned, markReturned);
const firstPage = path.join(controlDir, "first-page");
await waitForFixture(() => existsSync(firstPage), "first page requested");
const pid = Number(await readFile(firstPage, "utf8"));
await vi.advanceTimersByTimeAsync(59_000);
await writeFile(path.join(controlDir, "release-first-page"), "");
// Let real I/O deliver the page before advancing to the client deadline.
// The provider signals a second request but never answers it.
const secondPage = path.join(controlDir, "second-page");
await waitForFixture(() => returned || existsSync(secondPage), "result or second page request");
await vi.advanceTimersByTimeAsync(1_000);
const recent = await result;
expect(recent.entries.map((session) => session.title)).toEqual(
Array.from({ length: 20 }, (_, index) => `September session ${index}`),
);
await waitForFixture(() => {
try {
process.kill(pid, 0);
return false;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ESRCH") return true;
throw error;
}
}, "listing process exited");
} finally {
if (vi.isFakeTimers()) {
await vi.advanceTimersByTimeAsync(2_000);
vi.useRealTimers();
}
await client.close();
await daemon.close();
await rm(controlDir, { recursive: true, force: true });
}
});
async function waitForFixture(condition: () => boolean, description: string): Promise<void> {
// Use real timers for subprocess I/O while the RPC clock is paused.
const deadline = Date.now() + 10_000;
while (!condition()) {
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
await delay(10);
}
}
test("bundled fx requires a config entry and lists models instead of its providers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-fx-optin-"));
const record = path.join(root, "launches.txt");
@@ -778,3 +778,40 @@ test.each([
}
},
);
test("an uninitialized submodule below a bare repository layout does not fail the comparison", async () => {
const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-submodule-"));
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
const { mkdir } = await import("node:fs/promises");
try {
git("init", "-b", "main");
git("config", "user.name", "Test");
git("config", "user.email", "test@example.com");
await writeFile(join(cwd, "README.md"), "base\n");
git("add", ".");
git("-c", "commit.gpgsign=false", "commit", "-m", "base");
const base = git("rev-parse", "HEAD");
git("update-index", "--add", "--cacheinfo", `160000,${base},vendor/sub`);
git("-c", "commit.gpgsign=false", "commit", "-m", "record submodule");
// `vendor/` holds files shaped like a bare repository; git discovery from the
// uninitialized `vendor/sub` would stop there before reaching the superproject.
git("init", "--bare", "-q", "vendor");
await mkdir(join(cwd, "vendor", "sub"));
const comparison = await listComparison({
cwd,
base: { kind: "rev", rev: base },
head: { kind: "worktree" },
highlight: false,
});
try {
expect(comparison.files.map((file) => [file.entry.path, file.entry.change])).toContainEqual([
"vendor/sub",
"added",
]);
} finally {
await comparison.close();
}
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
+27 -6
View File
@@ -12,7 +12,7 @@ import {
type CheckoutDiffCompare,
} from "../../utils/checkout-git.js";
import { lstat, readFile, readlink } from "node:fs/promises";
import { resolve } from "node:path";
import { join, resolve } from "node:path";
import type { DiffEndpoint, DiffSubscribeRequest } from "@getpaseo/protocol/messages";
import type { DiffEntry, DiffBody } from "@getpaseo/protocol/binary-frames/index";
import { runGitCommand, type GitCommandOptions } from "../../utils/run-git-command.js";
@@ -444,15 +444,36 @@ async function readWorktreeContent({
if (value.isSymbolicLink())
return { hashed: false, literal: `symlink:${await readlink(absolutePath)}` };
if (value.isDirectory() && (header[0] === ":160000" || header[1] === "160000")) {
const submodule = await runGitCommand(
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
{ cwd: absolutePath, envOverlay: { GIT_OPTIONAL_LOCKS: "0" } },
);
return { hashed: false, literal: `submodule:${submodule.stdout}` };
return { hashed: false, literal: await readSubmoduleIdentity(path, absolutePath, options) };
}
return { hashed: value.isFile() && text, literal: null };
}
// An uninitialized submodule has no `.git`; running git there would discover
// whichever repository sits above it. Its content is the commit the index
// records. Pinning GIT_DIR keeps an initialized submodule's status on its own `.git`.
async function readSubmoduleIdentity(
path: string,
submodulePath: string,
options: GitCommandOptions,
): Promise<string> {
try {
await lstat(join(submodulePath, ".git"));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
const recorded = await runGitCommand(["rev-parse", "--verify", "--quiet", `:0:${path}`], {
...options,
acceptExitCodes: [0, 1],
});
return `submodule-uninitialized:${recorded.stdout.trim()}`;
}
const status = await runGitCommand(
["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],
{ cwd: submodulePath, envOverlay: { GIT_DIR: ".git", GIT_OPTIONAL_LOCKS: "0" } },
);
return `submodule:${status.stdout}`;
}
function diffArguments(compare: Compare, baseSha: string, headSha: string): string[] {
const revisions: string[] = [];
if (compare.base.kind !== "index") revisions.push(baseSha);
@@ -534,6 +534,61 @@ test("submodule commits invalidate cached worktree gitlink bodies", async () =>
}
});
// Windows paths cannot contain `:`.
const uninitializedSubmodulePaths = process.platform === "win32" ? ["sub"] : ["sub", "0:sub"];
test.each(uninitializedSubmodulePaths)(
"staged commits invalidate cached bodies for an uninitialized submodule at %s",
async (submodule) => {
const cwd = await mkdtemp(join(tmpdir(), "diff-uninitialized-gitlink-cache-"));
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
const streams = new DiffSubscriptions({
async requestWorkingTreeWatch(root) {
return { repoRoot: root, unsubscribe: async () => {} };
},
});
const frames: DiffFrame[] = [];
const commit = (message: string) => {
git("-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", message);
return git("rev-parse", "HEAD");
};
try {
git("init", "-b", "main");
git("config", "user.name", "Test");
git("config", "user.email", "test@example.com");
const [a, b, c] = [commit("A"), commit("B"), commit("C")];
git("update-index", "--add", "--cacheinfo", `160000,${a},${submodule}`);
git("-c", "commit.gpgsign=false", "commit", "-m", "record A");
await mkdir(join(cwd, submodule));
git("update-index", "--cacheinfo", `160000,${b},${submodule}`);
const subscription = await streams.subscribe(
{ cwd, base: { kind: "rev", rev: "HEAD" }, head: { kind: "worktree" } },
async (frame) => {
frames.push(frame);
},
);
await subscription.start();
expect(frames.at(-1)).toMatchObject({ opcode: DiffOpcode.End, error: null });
frames.length = 0;
git("update-index", "--cacheinfo", `160000,${c},${submodule}`);
await streams.invalidateForCwd(cwd);
await expect
.poll(() => frames.some((frame) => frame.opcode === DiffOpcode.End), { timeout: 5000 })
.toBe(true);
const bodies = frames.flatMap((frame) =>
frame.opcode === DiffOpcode.Bodies ? frame.files : [],
);
expect(bodies.flatMap((file) => file.hunks.flatMap((hunk) => hunk.lines))).toContainEqual(
expect.objectContaining({ type: "add", content: `Subproject commit ${c}` }),
);
await subscription.release();
} finally {
await streams.close();
await rm(cwd, { recursive: true, force: true });
}
},
);
test("stat-only changes reuse cached bodies and send no body frames", async () => {
const { utimes } = await import("node:fs/promises");
const cwd = await mkdtemp(join(tmpdir(), "diff-stat-only-"));
@@ -194,12 +194,14 @@ test("classifies a removed file as deleted", async () => {
const root = await createRoot();
const target = join(root, "removed.txt");
await writeFile(target, "before");
const canary = createWatcherLivenessCanary(root);
const events: FileChange[] = [];
const subscription = await subscribeToFileChanges(root, (error, batch) => {
expect(error).toBeNull();
events.push(...batch);
events.push(...canary.filterEvents(batch));
});
await canary.verify();
await rm(target);
// macOS FSEvents can replay the write above as a create after the subscription starts,
// so the delete is the latest event for the path, not the first. Native recursive delivery
@@ -1091,29 +1091,28 @@ describe("speech provider config normalization", () => {
});
test.each([
["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 },
},
["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 },
},
});
expect(parsed.agents?.providers?.goose).toEqual({
...overrides,
...(command[0] === "goose" ? {} : { command }),
});
},
);
},
});
expect(parsed.agents?.providers?.[provider]).toEqual({
...overrides,
...(binary === provider ? {} : { command }),
});
});
+17 -12
View File
@@ -198,25 +198,30 @@ 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;
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 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;
const usesDefaultCommand =
Array.isArray(command) &&
command.length === 2 &&
command[0] === "goose" &&
command[0] === providerId &&
command[1] === "acp";
rawProviders = {
...value,
goose: {
...overrides,
...(command !== undefined && !usesDefaultCommand ? { command } : {}),
},
rawProviders[providerId] = {
...overrides,
...(command !== undefined && !usesDefaultCommand ? { command } : {}),
};
}
@@ -11,6 +11,7 @@ export const builtinPlugins = [
"fx-provider",
"goose-provider",
"grok-usage-source",
"hermes-provider",
"hoplite-provider",
"kimi-usage-source",
"minimax-usage-source",
+5 -1
View File
@@ -4075,7 +4075,11 @@ describe("session checkout pull and push handling", () => {
requestId: "request-push",
});
expect(checkoutGitMocks.pushCurrentBranch).toHaveBeenCalledWith("/tmp/request-worktree");
expect(checkoutGitMocks.pushCurrentBranch).toHaveBeenCalledWith(
"/tmp/request-worktree",
undefined,
{ paseoHome: "/tmp/paseo-home", worktreesRoot: undefined },
);
expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", {
force: true,
reason: "push",
@@ -10049,6 +10049,8 @@ 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,7 +956,10 @@ export class CheckoutSession {
const { cwd, requestId } = msg;
try {
await pushCurrentBranch(cwd);
await pushCurrentBranch(cwd, undefined, {
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
});
await this.gitMutation.notifyGitMutation(cwd, "push", { invalidateForge: true });
this.host.emit({
type: "checkout_push_response",
@@ -296,8 +296,23 @@ function createGitRepository(): { tempDir: string; repoDir: string } {
return { tempDir, repoDir };
}
async function createBaseRecoveryFixture(baseBranch: string | null) {
const { tempDir, repoDir } = createGitRepository();
async function createBaseRecoveryFixture(
baseBranch: string | null,
options: { bareSource?: boolean } = {},
) {
const { tempDir, repoDir: checkoutDir } = createGitRepository();
const repoDir = options.bareSource ? join(realpathSync(tempDir), "repo.git") : checkoutDir;
if (options.bareSource) {
execFileSync("git", ["clone", "--bare", "-q", checkoutDir, repoDir], { stdio: "pipe" });
// A bare clone does not copy the checkout's local config; its linked worktrees share this one.
for (const [key, value] of [
["user.name", "Paseo Test"],
["user.email", "test@example.com"],
["core.autocrlf", "false"],
]) {
execFileSync("git", ["--git-dir", repoDir, "config", key, value], { stdio: "pipe" });
}
}
const paseoHome = join(tempDir, "paseo-home");
const created = await createWorktree({
cwd: repoDir,
@@ -648,6 +663,23 @@ test("restore rejects a branch checked out elsewhere without inventing another b
).toBe("* feature");
});
test("restores a workspace after the last checkout of a bare repository is archived", async () => {
const fixture = await createBaseRecoveryFixture("main", { bareSource: true });
await fixture.archiveAndRemove();
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
workspaceId: fixture.workspace.workspaceId,
action: "restore",
});
expect(readFileSync(join(fixture.workspace.cwd, "feature.txt"), "utf8")).toBe("feature\n");
expect(
execFileSync("git", ["symbolic-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("refs/heads/feature");
});
test("restores a user-created worktree at its recorded path outside Paseo's root", async () => {
const { tempDir, repoDir } = createGitRepository();
const worktreeRoot = join(realpathSync(tempDir), "external-worktree");
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { basename } from "node:path";
import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
import { runGitCommand } from "../../../utils/run-git-command.js";
import {
@@ -156,7 +157,10 @@ export function createWorkspaceRecoveryService(deps: {
let workspaceToUnarchive = resolved.workspace;
let recreated: { worktreePath: string; pluginId: string | null } | null = null;
if (resolved.kind === "restore") {
recreated = await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
const { workspace, sourceRepoRoot } = resolved;
recreated = await runWithRepositoryRoot(sourceRepoRoot, () =>
recreateArchivedWorktree(workspace, sourceRepoRoot),
);
if ((resolved.workspace.worktreeManagerPluginId ?? null) !== recreated.pluginId) {
const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace;
workspaceToUnarchive = recreated.pluginId
@@ -246,7 +246,9 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna
upstreamRef: null,
aheadOfOrigin: null,
behindOfOrigin: null,
upstreamState: "none",
hasRemote: false,
firstPushRemote: null,
diffStat: null,
},
forge: {
@@ -2242,6 +2244,8 @@ 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.
@@ -190,7 +190,7 @@ async function withAuthenticatedRemote(
{ cwd },
);
await run(["clone", "--bare", cwd, remote], { cwd: root });
await run(["update-server-info"], { cwd: remote });
await run(["--git-dir", remote, "update-server-info"], { cwd: root });
await run(["config", "credential.helper", ""], { cwd });
await run(["config", "core.askPass", askpassCommand], { cwd });
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
@@ -41,6 +41,8 @@ function createFacts(cwd: string): CheckoutSnapshotFacts {
comparisonBaseRef: null,
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -72,6 +72,8 @@ function createCheckoutFacts(cwd: string): CheckoutSnapshotFacts {
comparisonBaseRef: null,
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -1017,7 +1019,8 @@ describe("WorkspaceGitService checkout observation", () => {
comparisonBaseRef: null,
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
};
});
const runGitFetch = vi.fn(async () => ({
@@ -1160,7 +1163,8 @@ describe("WorkspaceGitService checkout observation", () => {
comparisonBaseRef: "refs/heads/main",
branchRemoteName: "origin",
branchMergeRef: `refs/heads/${branch}`,
upstreamStatus: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
} satisfies CheckoutSnapshotFacts;
});
const getCheckoutStatus = vi.fn(async (cwd: string) =>
@@ -80,6 +80,8 @@ function createCheckoutFacts(
comparisonBaseRef: null,
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
...overrides,
};
@@ -171,6 +171,8 @@ function createCheckoutSnapshotFacts(cwd: string): CheckoutSnapshotFacts {
comparisonBaseRef: null,
branchRemoteName: "origin",
branchMergeRef: "refs/heads/main",
upstreamStatus: { state: "none" },
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -7,13 +7,14 @@ 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 } from "../utils/checkout-git.js";
import type { CheckoutContext, UpstreamState } from "../utils/checkout-git.js";
import {
type BranchCheckoutResolution,
type BranchSuggestion,
type CheckoutSnapshotFacts,
type CheckoutDiffCompare,
type CheckoutDiffResult,
configuredUpstreamRef,
getCheckoutDiff,
getCheckoutRefDerivedState,
getCheckoutSnapshotFacts,
@@ -22,6 +23,7 @@ import {
getCheckoutWorktreeState,
getPullRequestStatus,
forgeAuthStateFromError,
projectUpstreamStatus,
hasOriginRemote,
listBranchSuggestions,
resolveRepositoryDefaultBranch,
@@ -181,7 +183,9 @@ 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: {
@@ -2882,7 +2886,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
facts.storedBaseRef,
facts.resolvedBaseRef,
facts.comparisonBaseRef,
facts.upstreamStatus?.ref,
configuredUpstreamRef(facts.upstreamStatus),
];
const usesBranch = dependentRefs.some(
(ref) => ref === branch || ref === `refs/heads/${branch}`,
@@ -2919,7 +2923,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
facts.storedBaseRef,
facts.resolvedBaseRef,
facts.comparisonBaseRef,
facts.upstreamStatus?.ref,
configuredUpstreamRef(facts.upstreamStatus),
configuredRemoteRef,
shortstatRemoteRef,
];
@@ -3684,9 +3688,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
...latestGit,
aheadBehind: derived.aheadBehind,
diffStat: derived.diffStat,
upstreamRef: derived.upstreamStatus?.ref ?? null,
aheadOfOrigin: derived.upstreamStatus?.aheadBehind.ahead ?? null,
behindOfOrigin: derived.upstreamStatus?.aheadBehind.behind ?? null,
...projectUpstreamStatus(derived.upstreamStatus),
};
const loadedAtMs = this.deps.now().getTime();
target.latestGitLoadedAtMs = loadedAtMs;
@@ -3781,7 +3783,9 @@ 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();
@@ -4436,7 +4440,9 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot {
upstreamRef: null,
aheadOfOrigin: null,
behindOfOrigin: null,
upstreamState: "none",
hasRemote: false,
firstPushRemote: null,
diffStat: null,
},
forge: buildForgeUnavailableSnapshot(),
@@ -18,7 +18,9 @@ import { createGitLabService } from "../services/gitlab-service.js";
import {
getCheckoutSnapshotFacts,
getCheckoutStatus,
getMainRepoRoot,
pushCurrentBranch,
resolveRepositoryDefaultBranch,
} from "../utils/checkout-git.js";
import {
getPaseoWorktreeMetadataPath,
@@ -26,6 +28,7 @@ import {
} from "../utils/worktree-metadata.js";
import { validateBeforeRequest, validateBeforeResult } from "./plugins/lifecycle/index.js";
import {
createWorktree,
isPaseoOwnedWorktreeCwd,
listGitWorktrees,
listPaseoWorktrees,
@@ -88,11 +91,13 @@ function createGitHubServiceStub(): ForgeService {
function createCoreDeps(options?: {
github?: ForgeService;
forge?: { forge: string; service: ForgeService };
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
resolveRepoRoot?: (cwd: string) => Promise<string>;
}) {
return {
github: options?.github ?? createGitHubServiceStub(),
workspaceGitService: {
resolveRepoRoot: async (cwd: string) => cwd,
resolveRepoRoot: options?.resolveRepoRoot ?? (async (cwd: string) => cwd),
resolveForge: async () =>
options?.forge
? {
@@ -102,7 +107,7 @@ function createCoreDeps(options?: {
}
: null,
},
resolveDefaultBranch: async () => "main",
resolveDefaultBranch: options?.resolveDefaultBranch ?? (async () => "main"),
};
}
@@ -445,6 +450,39 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
expect(existsSync(first.worktree.worktreePath)).toBe(true);
});
test("creates a workspace from a checkout of a bare repository that only Paseo uses", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
const bareRepo = path.join(tempDir, "repo.git");
execFileSync("git", ["clone", "--bare", "-q", repoDir, bareRepo], { stdio: "pipe" });
const first = await createWorktree({
cwd: bareRepo,
paseoHome,
worktreeSlug: "first",
source: { kind: "branch-off", branchName: "first", baseBranch: "main" },
});
expect(await getMainRepoRoot(first.worktreePath, { paseoHome })).toBe(bareRepo);
const result = await createCoreWorktree(
{ cwd: first.worktreePath, worktreeSlug: "second", paseoHome },
createCoreDeps({
resolveRepoRoot: (cwd) => getMainRepoRoot(cwd, { paseoHome }),
resolveDefaultBranch: async (root) =>
(await resolveRepositoryDefaultBranch(root)) ?? "unresolved",
}),
);
expect(result.repoRoot).toBe(bareRepo);
expect(result.intent).toEqual({
kind: "branch-off",
baseBranch: "main",
branchName: "second",
});
expect(readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8")).toBe(
"hello\n",
);
});
test("creates branch-off worktrees from origin main without tracking origin main", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepoWithOriginMain();
cleanupPaths.push(tempDir);
@@ -27,6 +27,7 @@ import {
} from "./resolve-worktree-creation-intent.js";
import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/protocol/messages";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js";
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
@@ -78,6 +79,16 @@ async function createWorktreeCoreWithPriority(
deps: CreateWorktreeCoreDeps,
): Promise<CreateWorktreeCoreResult> {
const repoRoot = await resolveWorktreeRepoRoot(input, deps.workspaceGitService);
return runWithRepositoryRoot(repoRoot, () =>
createWorktreeAtRepositoryRoot(input, deps, repoRoot),
);
}
async function createWorktreeAtRepositoryRoot(
input: CreateWorktreeCoreInput,
deps: CreateWorktreeCoreDeps,
repoRoot: string,
): Promise<CreateWorktreeCoreResult> {
const requestedWorktreeSlug = input.worktreeSlug
? normalizeWorktreeSlug(input.worktreeSlug)
: undefined;
@@ -907,6 +907,8 @@ describe("ForgeService", () => {
ttlMs: 0,
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => null,
now: () => now,
});
const reads = recordCurrentPullRequestStatusReads(service);
@@ -980,6 +982,8 @@ describe("ForgeService", () => {
ttlMs: 0,
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => null,
now: () => now,
});
const reads = recordCurrentPullRequestStatusReads(service);
@@ -1026,6 +1030,8 @@ describe("ForgeService", () => {
ttlMs: 0,
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => null,
now: () => now,
});
const reads = recordCurrentPullRequestStatusReads(service);
@@ -1069,6 +1075,8 @@ describe("ForgeService", () => {
ttlMs: 0,
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => null,
now: () => now,
});
@@ -1098,6 +1106,8 @@ describe("ForgeService", () => {
ttlMs: 0,
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => null,
now: () => now,
});
@@ -63,9 +63,11 @@ function seedFeatureCheckout(): {
branchRemoteName: "origin",
branchMergeRef: "refs/heads/main",
upstreamStatus: {
state: "tracked",
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 0, behind: 0 },
},
firstPushRemote: "origin",
pullRequestLookupTarget: { headRef: "feature" },
},
};
@@ -105,9 +107,11 @@ function seedMainCheckout(): {
branchRemoteName: "origin",
branchMergeRef: "refs/heads/main",
upstreamStatus: {
state: "tracked",
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 1, behind: 0 },
},
firstPushRemote: "origin",
pullRequestLookupTarget: { headRef: "main" },
},
};
@@ -127,6 +131,7 @@ test("one comparison refresh updates a shared base and upstream ref", async () =
expect(result.aheadBehind).toEqual({ ahead: 1, behind: 0 });
expect(result.upstreamStatus).toEqual({
state: "tracked",
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 1, behind: 0 },
});
@@ -154,6 +159,7 @@ test("an upstream move refreshes the main checkout shortstat", async () => {
aheadBehind: null,
diffStat: null,
upstreamStatus: {
state: "tracked",
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 0, behind: 0 },
},
@@ -166,7 +172,7 @@ test("an origin move refreshes an untracked main checkout shortstat", async () =
...seeded.facts,
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: null,
upstreamStatus: { state: "none" as const },
};
git(seeded.cwd, [
"update-ref",
@@ -181,5 +187,5 @@ test("an origin move refreshes an untracked main checkout shortstat", async () =
{ aheadBehind: null, diffStat: { additions: 1, deletions: 0 } },
new Set(["origin/main"]),
),
).toEqual({ aheadBehind: null, diffStat: null, upstreamStatus: null });
).toEqual({ aheadBehind: null, diffStat: null, upstreamStatus: { state: "none" } });
});
+273 -4
View File
@@ -924,15 +924,23 @@ const x = 1;
});
it("exposes hasRemote when origin is configured", async () => {
const withoutRemote = await getCheckoutStatus(repoDir);
expect(withoutRemote).toMatchObject({
isGit: true,
hasRemote: false,
upstreamState: "none",
});
const remoteDir = join(tempDir, "remote.git");
execFileSync("git", ["init", "--bare", "-b", "main", remoteDir]);
execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
expect(status.isGit).toBe(true);
if (status.isGit) {
expect(status.hasRemote).toBe(true);
}
expect(status).toMatchObject({
isGit: true,
hasRemote: true,
upstreamState: "none",
});
});
it("reports ahead/behind relative to origin on the base branch", async () => {
@@ -1005,6 +1013,7 @@ const x = 1;
return;
}
expect(status.upstreamRef).toBe("refs/remotes/upstream/main");
expect(status.upstreamState).toBe("tracked");
});
it("reports the upstream branch name when it differs from the local branch name", async () => {
@@ -1034,6 +1043,191 @@ const x = 1;
}
expect(status.upstreamRef).toBe("refs/remotes/upstream/main");
expect(status.aheadOfOrigin).toBe(0);
expect(status.hasRemote).toBe(false);
expect(status.upstreamState).toBe("tracked");
});
it("reports origin as the first push remote for a never-pushed branch", async () => {
setupRemoteTrackingMain(repoDir, tempDir);
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: "origin" });
});
// The daemon's first push goes to origin. When git would send the branch to a fork instead,
// the status must not present origin as the place to publish it, and Push must not send it.
it.each([
{ name: "the branch's pushRemote", key: "branch.feature.pushRemote" },
{ name: "remote.pushDefault", key: "remote.pushDefault" },
])("does not publish to origin when $name sends the branch to a fork", async ({ key }) => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir });
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["config", key, "fork"], { cwd: repoDir });
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
await expect(pushCurrentBranch(repoDir)).rejects.toThrow(
"Git is set to push this branch to 'fork'",
);
expect(status).toMatchObject({
upstreamState: "none",
hasRemote: true,
firstPushRemote: null,
});
const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"])
.toString()
.trim();
expect(originBranches).toBe("* main");
});
it("still publishes a branch that tracks a local branch to origin", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
execFileSync("git", ["checkout", "-b", "feature", "--track", "main"], { cwd: repoDir });
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
await pushCurrentBranch(repoDir);
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir })
.toString()
.trim();
const remoteHead = execFileSync("git", [
"--git-dir",
remoteDir,
"rev-parse",
"refs/heads/feature",
])
.toString()
.trim();
expect(remoteHead).toBe(localHead);
});
// With a tag of the same name, git spells the current branch "heads/release". Its settings and
// its ref are still stored under "release".
describe("a branch that shares its name with a tag", () => {
it("does not publish to origin when the branch's pushRemote sends it to a fork", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir });
execFileSync("git", ["checkout", "-b", "release"], { cwd: repoDir });
execFileSync("git", ["config", "branch.release.pushRemote", "fork"], { cwd: repoDir });
commitFile(repoDir, "release.txt", "release\n", "release commit");
execFileSync("git", ["tag", "release"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
await expect(pushCurrentBranch(repoDir)).rejects.toThrow(
"Git is set to push this branch to 'fork'",
);
expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: null });
const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"])
.toString()
.trim();
expect(originBranches).toBe("* main");
});
it("does not report a branch whose remote copy was deleted as never pushed", async () => {
setupRemoteTrackingMain(repoDir, tempDir);
execFileSync("git", ["checkout", "-b", "release"], { cwd: repoDir });
commitFile(repoDir, "release.txt", "release\n", "release commit");
execFileSync("git", ["push", "-u", "origin", "release"], { cwd: repoDir });
execFileSync("git", ["tag", "release"], { cwd: repoDir });
execFileSync("git", ["push", "origin", "--delete", "refs/heads/release"], { cwd: repoDir });
execFileSync("git", ["fetch", "--prune", "origin"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({ upstreamState: "gone", aheadOfOrigin: null });
});
it("pushes a branch that tracks a fork to the fork", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir });
execFileSync("git", ["checkout", "-b", "release"], { cwd: repoDir });
commitFile(repoDir, "release.txt", "release\n", "release commit");
execFileSync("git", ["push", "-u", "fork", "release"], { cwd: repoDir });
execFileSync("git", ["tag", "release"], { cwd: repoDir });
commitFile(repoDir, "release.txt", "release two\n", "second release commit");
await pushCurrentBranch(repoDir);
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir })
.toString()
.trim();
const forkHead = execFileSync("git", [
"--git-dir",
forkDir,
"rev-parse",
"refs/heads/release",
])
.toString()
.trim();
expect(forkHead).toBe(localHead);
const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"])
.toString()
.trim();
expect(originBranches).toBe("* main");
});
});
it("still publishes a never-pushed Paseo worktree branch to origin in a fork setup", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir });
execFileSync("git", ["config", "remote.pushDefault", "fork"], { cwd: repoDir });
const worktree = await createLegacyWorktreeForTest({
branchName: "worktree-feature",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "worktree-feature",
paseoHome,
});
const worktreeDir = worktree.worktreePath;
commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit");
await pushCurrentBranch(worktreeDir, undefined, { paseoHome });
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir })
.toString()
.trim();
const remoteHead = execFileSync("git", [
"--git-dir",
remoteDir,
"rev-parse",
"refs/heads/worktree-feature",
])
.toString()
.trim();
expect(remoteHead).toBe(localHead);
});
// Push's first push targets origin, so without origin a never-pushed branch has nowhere to go.
it("reports a never-pushed branch and refuses its first push when origin is missing", async () => {
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "upstream", forkDir], { cwd: repoDir });
execFileSync("git", ["checkout", "-b", "local-only"], { cwd: repoDir });
commitFile(repoDir, "local-only.txt", "local\n", "local commit");
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({
isGit: true,
upstreamState: "none",
hasRemote: false,
firstPushRemote: null,
});
await expect(pushCurrentBranch(repoDir)).rejects.toThrow("Remote 'origin' is not configured.");
});
// A legal local branch named "origin/main" shadows the short form "origin/main" in git's
@@ -1067,6 +1261,8 @@ const x = 1;
}
expect(status.upstreamRef).toBeNull();
expect(status.aheadOfOrigin).toBeNull();
expect(status.upstreamState).toBe("none");
expect(status.aheadBehind).toEqual({ ahead: 1, behind: 0 });
});
it("reports a PR worktree as not ahead when its branch is pushed to the configured PR remote", async () => {
@@ -1170,6 +1366,79 @@ const x = 1;
}
expect(status.aheadOfOrigin).toBeNull();
expect(status.behindOfOrigin).toBeNull();
expect(status.upstreamRef).toBeNull();
expect(status.upstreamState).toBe("gone");
});
it("does not report a published branch as never pushed when the clone fetches only main", async () => {
setupRemoteTrackingMain(repoDir, tempDir);
// What `git clone --single-branch` and `--depth` leave behind: no tracking ref for other branches.
execFileSync(
"git",
["config", "remote.origin.fetch", "+refs/heads/main:refs/remotes/origin/main"],
{ cwd: repoDir },
);
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
execFileSync("git", ["push", "-u", "origin", "feature"], { cwd: repoDir });
execFileSync("git", ["push", "origin", "--delete", "feature"], { cwd: repoDir });
execFileSync("git", ["fetch", "--prune", "origin"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({
isGit: true,
aheadBehind: { ahead: 1, behind: 0 },
upstreamRef: null,
aheadOfOrigin: null,
upstreamState: "unknown",
});
});
it("re-publishes a Paseo worktree branch whose remote copy was deleted and pruned", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
const worktree = await createLegacyWorktreeForTest({
branchName: "merged-feature",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "merged-feature",
paseoHome,
});
const worktreeDir = worktree.worktreePath;
commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit");
execFileSync("git", ["push", "-u", "origin", "merged-feature"], { cwd: worktreeDir });
execFileSync("git", ["push", "origin", "--delete", "merged-feature"], { cwd: worktreeDir });
execFileSync("git", ["fetch", "--prune", "origin"], { cwd: worktreeDir });
const gone = await getCheckoutStatus(worktreeDir, { paseoHome });
expect(gone).toMatchObject({
isPaseoOwnedWorktree: true,
aheadBehind: { ahead: 1, behind: 0 },
aheadOfOrigin: null,
upstreamState: "gone",
});
await pushCurrentBranch(worktreeDir);
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir })
.toString()
.trim();
const remoteHead = execFileSync("git", [
"--git-dir",
remoteDir,
"rev-parse",
"refs/heads/merged-feature",
])
.toString()
.trim();
expect(remoteHead).toBe(localHead);
const republished = await getCheckoutStatus(worktreeDir, { paseoHome });
expect(republished).toMatchObject({
upstreamRef: "refs/remotes/origin/merged-feature",
upstreamState: "tracked",
aheadOfOrigin: 0,
behindOfOrigin: 0,
});
});
it("does not report full history as unpushed for fresh no-track Paseo worktrees", async () => {
+222 -43
View File
@@ -908,7 +908,9 @@ export interface CheckoutStatusGitNonPaseo {
upstreamRef: string | null;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
upstreamState: UpstreamState;
hasRemote: boolean;
firstPushRemote: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: false;
}
@@ -926,7 +928,9 @@ export interface CheckoutStatusGitPaseo {
upstreamRef: string | null;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
upstreamState: UpstreamState;
hasRemote: boolean;
firstPushRemote: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: true;
}
@@ -983,7 +987,8 @@ export type CheckoutSnapshotFacts =
comparisonBaseRef: string | null;
branchRemoteName: string | null;
branchMergeRef: string | null;
upstreamStatus: UpstreamStatus | null;
upstreamStatus: UpstreamStatus;
firstPushRemote: string | null;
pullRequestLookupTarget: PullRequestStatusLookupTarget | null;
};
@@ -1870,9 +1875,48 @@ async function getAheadBehind(
return getAheadBehindForComparisonRef(cwd, comparisonBaseRef, currentBranch, context);
}
export interface UpstreamStatus {
ref: string;
aheadBehind: AheadBehind;
// How the current branch relates to its upstream. "none" means no upstream is configured: the
// branch was never pushed. "gone" is git's `[gone]`: an upstream is configured but its
// remote-tracking ref no longer exists, as after the remote branch is deleted and pruned.
// "unknown" means git cannot say: the read failed, or an upstream is configured that this clone
// keeps no remote-tracking ref for, as in a `--single-branch` or `--depth` clone.
export type UpstreamStatus =
| { state: "tracked"; ref: string; aheadBehind: AheadBehind }
| { state: "gone"; ref: string }
| { state: "none" }
| { state: "unknown" };
export type UpstreamState = UpstreamStatus["state"];
export interface CheckoutUpstreamFields {
upstreamRef: string | null;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
upstreamState: UpstreamState;
}
// The status fields that describe the upstream. upstreamRef and the counts stay null unless the
// upstream is tracked, as they were before upstreamState existed.
export function projectUpstreamStatus(status: UpstreamStatus): CheckoutUpstreamFields {
if (status.state === "tracked") {
return {
upstreamRef: status.ref,
aheadOfOrigin: status.aheadBehind.ahead,
behindOfOrigin: status.aheadBehind.behind,
upstreamState: "tracked",
};
}
return {
upstreamRef: null,
aheadOfOrigin: null,
behindOfOrigin: null,
upstreamState: status.state,
};
}
// The configured upstream ref, whether or not its remote-tracking ref still exists.
export function configuredUpstreamRef(status: UpstreamStatus): string | null {
return status.state === "tracked" || status.state === "gone" ? status.ref : null;
}
async function getAheadBehindForComparisonRef(
@@ -1894,32 +1938,123 @@ async function getAheadBehindForComparisonRef(
return { ahead, behind };
}
async function getUpstreamStatus(
// The name git stores a branch's settings and ref under. getCurrentBranch returns git's short
// spelling of the branch, which gains a "heads/" prefix when another ref, such as a tag, shares
// the name. That spelling is right for a revision or a refspec and wrong for these lookups.
async function readStoredBranchName(
cwd: string,
currentBranch: string,
context?: CheckoutContext,
): Promise<UpstreamStatus | null> {
): Promise<string> {
const branchRefPrefix = "refs/heads/";
if (!currentBranch.startsWith("heads/") && !currentBranch.startsWith(branchRefPrefix)) {
return currentBranch;
}
try {
const { stdout } = await getRunGitCommand(context)(["symbolic-ref", "--quiet", "HEAD"], {
cwd,
envOverlay: READ_ONLY_GIT_ENV,
});
const headRef = stdout.trim();
return headRef.startsWith(branchRefPrefix)
? headRef.slice(branchRefPrefix.length)
: currentBranch;
} catch {
return currentBranch;
}
}
// What git reports for a branch's upstream: its remote-tracking ref and how the branch tracks it.
// Both are blank when git resolves no upstream.
interface UpstreamTracking {
ref: string;
track: string;
}
async function readUpstreamTracking(
cwd: string,
storedBranchName: string | null,
context?: CheckoutContext,
): Promise<UpstreamTracking | null> {
if (!storedBranchName) {
return { ref: "", track: "" };
}
try {
const { stdout } = await getRunGitCommand(context)(
[
"for-each-ref",
"--format=%(upstream)%00%(upstream:track,nobracket)",
`refs/heads/${currentBranch}`,
`refs/heads/${storedBranchName}`,
],
{ cwd, envOverlay: READ_ONLY_GIT_ENV, logger: context?.logger },
);
const [ref = "", track = ""] = stdout.trim().split("\0", 2);
if (!ref || track === "gone") {
return null;
}
const ahead = Number.parseInt(track.match(/ahead (\d+)/)?.[1] ?? "0", 10);
const behind = Number.parseInt(track.match(/behind (\d+)/)?.[1] ?? "0", 10);
return { ref, aheadBehind: { ahead, behind } };
return { ref, track };
} catch {
return null;
}
}
function resolveUpstreamStatus(
tracking: UpstreamTracking | null,
hasConfiguredUpstream: boolean,
): UpstreamStatus {
if (!tracking) {
return { state: "unknown" };
}
if (!tracking.ref) {
return hasConfiguredUpstream ? { state: "unknown" } : { state: "none" };
}
if (tracking.track === "gone") {
return { state: "gone", ref: tracking.ref };
}
const ahead = Number.parseInt(tracking.track.match(/ahead (\d+)/)?.[1] ?? "0", 10);
const behind = Number.parseInt(tracking.track.match(/behind (\d+)/)?.[1] ?? "0", 10);
return { state: "tracked", ref: tracking.ref, aheadBehind: { ahead, behind } };
}
// The remote git pushes a branch to: branch.<name>.pushRemote, then remote.pushDefault, then the
// branch's own remote, then origin.
async function readGitPushRemote(input: {
cwd: string;
storedBranchName: string;
branchRemoteName: string | null;
context?: CheckoutContext;
}): Promise<string> {
const { cwd, storedBranchName, context } = input;
const [branchPushRemote, pushDefault] = await Promise.all([
getGitConfigValue(cwd, `branch.${storedBranchName}.pushRemote`, context),
getGitConfigValue(cwd, "remote.pushDefault", context),
]);
return branchPushRemote ?? pushDefault ?? input.branchRemoteName ?? "origin";
}
// pushCurrentBranch publishes a branch with no upstream here.
const FIRST_PUSH_REMOTE = "origin";
// Where a first push publishes the branch, when the daemon can confirm git would push it there
// too. When git picks another remote, as in a fork setup, this is null so that clients do not
// offer a first push that lands in a different repository than `git push` would use.
async function readFirstPushRemote(input: {
cwd: string;
storedBranchName: string | null;
branchRemoteName: string | null;
hasOrigin: boolean;
context?: CheckoutContext;
}): Promise<string | null> {
const { cwd, storedBranchName, branchRemoteName, context } = input;
if (!storedBranchName || !input.hasOrigin) {
return null;
}
const gitPushRemote = await readGitPushRemote({
cwd,
storedBranchName,
branchRemoteName,
context,
});
return gitPushRemote === FIRST_PUSH_REMOTE ? FIRST_PUSH_REMOTE : null;
}
interface CheckoutInspectionContext {
worktreeRoot: string;
currentBranch: string | null;
@@ -2210,24 +2345,28 @@ export async function getCheckoutSnapshotFacts(
let branchRemoteName: string | null = null;
let branchMergeRef: string | null = null;
let branchRemoteUrl: string | null = null;
const upstreamStatusPromise = inspected.currentBranch
? getUpstreamStatus(cwd, inspected.currentBranch, context)
: Promise.resolve(null);
if (inspected.currentBranch) {
branchRemoteName = await getGitConfigValue(
cwd,
`branch.${inspected.currentBranch}.remote`,
context,
);
const storedBranchName = inspected.currentBranch
? await readStoredBranchName(cwd, inspected.currentBranch, context)
: null;
const upstreamTrackingPromise = readUpstreamTracking(cwd, storedBranchName, context);
if (storedBranchName) {
branchRemoteName = await getGitConfigValue(cwd, `branch.${storedBranchName}.remote`, context);
if (branchRemoteName) {
[branchMergeRef, branchRemoteUrl] = await Promise.all([
getGitConfigValue(cwd, `branch.${inspected.currentBranch}.merge`, context),
getGitConfigValue(cwd, `branch.${storedBranchName}.merge`, context),
branchRemoteName === "origin"
? inspected.remoteUrl
: resolveGitRemoteUrl({ cwd, remote: branchRemoteName, context }),
]);
}
}
const firstPushRemotePromise = readFirstPushRemote({
cwd,
storedBranchName,
branchRemoteName,
hasOrigin: inspected.remoteUrl !== null,
context,
});
let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
cwd,
inspected,
@@ -2243,7 +2382,10 @@ export async function getCheckoutSnapshotFacts(
pullRequestLookupTarget,
context,
);
const upstreamStatus = await upstreamStatusPromise;
const upstreamStatus = resolveUpstreamStatus(
await upstreamTrackingPromise,
branchRemoteName !== null && branchMergeRef !== null,
);
return {
isGit: true,
@@ -2260,6 +2402,7 @@ export async function getCheckoutSnapshotFacts(
branchRemoteName,
branchMergeRef,
upstreamStatus,
firstPushRemote: await firstPushRemotePromise,
pullRequestLookupTarget,
};
}
@@ -2432,14 +2575,11 @@ export async function getCheckoutStatus(
baseRef && currentBranch
? await getAheadBehind(cwd, baseRef, currentBranch, factsContext)
: null;
const upstreamStatus = facts.upstreamStatus;
// The wire carries the display name: clients label the base with it and send it back to
// request diffs and merges. The exact ref stays in worktree.json and in facts, where the
// comparisons and actions read it.
const displayBaseRef = baseRef ? branchNameFromRef(baseRef) : null;
const upstreamRef = upstreamStatus?.ref ?? null;
const aheadOfOrigin = upstreamStatus?.aheadBehind.ahead ?? null;
const behindOfOrigin = upstreamStatus?.aheadBehind.behind ?? null;
const upstream = projectUpstreamStatus(facts.upstreamStatus);
if (paseoWorktree.isPaseoOwnedWorktree && baseRef) {
return {
@@ -2452,10 +2592,9 @@ export async function getCheckoutStatus(
baseRefExact: baseRef,
comparisonBaseRef,
aheadBehind,
upstreamRef,
aheadOfOrigin,
behindOfOrigin,
...upstream,
hasRemote,
firstPushRemote: facts.firstPushRemote,
remoteUrl,
isPaseoOwnedWorktree: true,
};
@@ -2472,10 +2611,9 @@ export async function getCheckoutStatus(
baseRefExact: baseRef,
comparisonBaseRef,
aheadBehind,
upstreamRef,
aheadOfOrigin,
behindOfOrigin,
...upstream,
hasRemote,
firstPushRemote: facts.firstPushRemote,
remoteUrl,
isPaseoOwnedWorktree: false,
};
@@ -3107,7 +3245,7 @@ export async function getCheckoutShortstat(
export interface CheckoutRefDerivedState {
aheadBehind: AheadBehind | null;
diffStat: CheckoutShortstat | null;
upstreamStatus: UpstreamStatus | null;
upstreamStatus: UpstreamStatus;
}
function normalizeRemoteTrackingRef(ref: string): string {
@@ -3150,7 +3288,8 @@ function getCheckoutRefMovement(
.filter((ref): ref is string => Boolean(ref))
.map(normalizeRemoteTrackingRef)
.some((ref) => normalizedMoves.has(ref));
const upstreamRef = facts.upstreamStatus?.ref ?? checkoutFactsConfiguredRemoteRef(facts);
const upstreamRef =
configuredUpstreamRef(facts.upstreamStatus) ?? checkoutFactsConfiguredRemoteRef(facts);
const upstreamMoved = upstreamRef
? normalizedMoves.has(normalizeRemoteTrackingRef(upstreamRef))
: false;
@@ -3206,10 +3345,11 @@ export async function getCheckoutRefDerivedState(
: await getAheadBehindForComparisonRef(cwd, upstreamRef, currentBranch, context);
upstreamStatus = upstreamAheadBehind
? {
ref: facts.upstreamStatus?.ref ?? `refs/remotes/${normalizedUpstream}`,
state: "tracked",
ref: configuredUpstreamRef(facts.upstreamStatus) ?? `refs/remotes/${normalizedUpstream}`,
aheadBehind: upstreamAheadBehind,
}
: null;
: { state: "unknown" };
}
return { aheadBehind, diffStat, upstreamStatus };
@@ -4192,24 +4332,29 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService
}
}
export async function pushCurrentBranch(cwd: string, forgeService?: ForgeService): Promise<void> {
export async function pushCurrentBranch(
cwd: string,
forgeService?: ForgeService,
context?: CheckoutContext,
): Promise<void> {
await requireGitRepo(cwd);
const currentBranch = await getCurrentBranch(cwd);
if (!currentBranch || currentBranch === "HEAD") {
throw new Error("Unable to determine current branch for push");
}
const configuredPushTarget = await getCurrentBranchConfiguredPushTarget(cwd, currentBranch);
const storedBranchName = await readStoredBranchName(cwd, currentBranch, context);
const configuredPushTarget = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName);
if (configuredPushTarget) {
await runGitCommand(
["push", configuredPushTarget.remoteName, `HEAD:refs/heads/${configuredPushTarget.headRef}`],
{ cwd, timeout: 120_000 },
);
await refreshCurrentBranchTrackedRefAfterPush(cwd, currentBranch, configuredPushTarget);
await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, configuredPushTarget);
forgeService?.invalidate({ cwd });
return;
}
const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, currentBranch);
const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName);
if (upstreamTarget) {
await runGitCommand(
["push", "-u", upstreamTarget.remoteName, `HEAD:refs/heads/${upstreamTarget.headRef}`],
@@ -4223,10 +4368,44 @@ export async function pushCurrentBranch(cwd: string, forgeService?: ForgeService
if (!hasRemote) {
throw new Error("Remote 'origin' is not configured.");
}
await runGitCommand(["push", "-u", "origin", currentBranch], { cwd, timeout: 120_000 });
await requireFirstPushAgreesWithGit(cwd, storedBranchName, context);
await runGitCommand(["push", "-u", FIRST_PUSH_REMOTE, currentBranch], { cwd, timeout: 120_000 });
forgeService?.invalidate({ cwd });
}
// The status a client acted on can be older than the git configuration, so a first push checks
// the destination again before it sends anything. Paseo worktrees always publish to origin.
async function requireFirstPushAgreesWithGit(
cwd: string,
storedBranchName: string,
context?: CheckoutContext,
): Promise<void> {
const [branchRemoteName, branchMergeRef] = await Promise.all([
getGitConfigValue(cwd, `branch.${storedBranchName}.remote`, context),
getGitConfigValue(cwd, `branch.${storedBranchName}.merge`, context),
]);
// A branch with a configured upstream gets here when that upstream is not a remote branch, as
// when it tracks a local branch. That is not a first push, and it goes to origin as before.
if (branchRemoteName !== null && branchMergeRef !== null) {
return;
}
const paseoWorktree = await getPaseoWorktreeForCwd(cwd, { context });
if (paseoWorktree.isPaseoOwnedWorktree) {
return;
}
const gitPushRemote = await readGitPushRemote({
cwd,
storedBranchName,
branchRemoteName,
context,
});
if (gitPushRemote !== FIRST_PUSH_REMOTE) {
throw new Error(
`Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${FIRST_PUSH_REMOTE}'. Push it from a terminal instead.`,
);
}
}
async function getCurrentBranchConfiguredPushTarget(
cwd: string,
currentBranch: string,
@@ -0,0 +1,234 @@
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
parseSafeBareRepositorySupport,
readRepositoryRootGitDir,
resolveGitDiscovery,
runWithRepositoryRoot,
type GitDiscovery,
} from "./git-repository-discovery.js";
const EXPLICIT = ["-c", "safe.bareRepository=explicit"];
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
function git(args: string[], cwd?: string): string {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
}
function makeTempDir(): string {
const dir = realpathSync.native(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-")));
tempDirs.push(dir);
return dir;
}
function createBareRepositoryWithLinkedWorktree(root: string): string {
const source = path.join(root, "source");
git(["init", "-q", "-b", "main", source]);
git(
[
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"-q",
"--allow-empty",
"-m",
"base",
],
source,
);
const bareRepo = path.join(root, "repo.git");
git(["clone", "-q", "--bare", source, bareRepo]);
git(["worktree", "add", "-q", path.join(root, "main"), "main"], bareRepo);
return bareRepo;
}
// Runs git with only the discovery environment, as a Git release that ignores
// `safe.bareRepository` would see it.
function gitDirWithoutConfig(cwd: string, discovery: GitDiscovery): string {
try {
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], {
cwd,
encoding: "utf8",
stdio: "pipe",
env: { ...process.env, ...discovery.envOverlay },
}).trim();
return path.resolve(gitDir);
} catch (error) {
return String((error as { stderr?: string }).stderr).trim();
}
}
describe("resolveGitDiscovery before Git 2.38", () => {
const legacy = {
gitDirSet: false,
repositoryRootGitDir: null,
safeBareRepositorySupported: false,
};
it("stops git at a bare repository layout in the working directory", async () => {
const layout = path.join(makeTempDir(), "layout");
git(["init", "--bare", "-q", layout]);
const discovery = await resolveGitDiscovery({ cwd: layout, ...legacy });
expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(layout, ".git") });
expect(gitDirWithoutConfig(layout, discovery)).toMatch(/not a git repository/);
});
it("stops git at a bare repository layout in a parent directory", async () => {
const layout = path.join(makeTempDir(), "layout");
git(["init", "--bare", "-q", layout]);
const nested = path.join(layout, "a", "b");
mkdirSync(nested, { recursive: true });
const discovery = await resolveGitDiscovery({ cwd: nested, ...legacy });
expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(nested, ".git") });
expect(gitDirWithoutConfig(nested, discovery)).toMatch(/not a git repository/);
});
it("leaves discovery alone when a checkout sits between the directory and the layout", async () => {
const layout = path.join(makeTempDir(), "layout");
git(["init", "--bare", "-q", layout]);
const checkout = path.join(layout, "checkout");
git(["init", "-q", checkout]);
const nested = path.join(checkout, "src");
mkdirSync(nested);
const discovery = await resolveGitDiscovery({ cwd: nested, ...legacy });
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
expect(gitDirWithoutConfig(nested, discovery)).toBe(path.join(checkout, ".git"));
});
it("leaves discovery alone inside a checkout's own .git directory", async () => {
const checkout = path.join(makeTempDir(), "checkout");
git(["init", "-q", checkout]);
const gitDir = path.join(checkout, ".git");
const discovery = await resolveGitDiscovery({ cwd: gitDir, ...legacy });
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
});
it("stops git at a bare repository with linked worktrees unless its root is named", async () => {
const bareRepo = createBareRepositoryWithLinkedWorktree(makeTempDir());
const unnamed = await resolveGitDiscovery({ cwd: bareRepo, ...legacy });
const named = await resolveGitDiscovery({
cwd: bareRepo,
...legacy,
repositoryRootGitDir: bareRepo,
});
expect(unnamed.envOverlay).toEqual({ GIT_DIR: path.join(bareRepo, ".git") });
expect(named).toEqual({ configArgs: EXPLICIT, envOverlay: { GIT_DIR: bareRepo } });
expect(gitDirWithoutConfig(bareRepo, named)).toBe(bareRepo);
});
it("stops git below a bare repository with linked worktrees", async () => {
const bareRepo = createBareRepositoryWithLinkedWorktree(makeTempDir());
const refs = path.join(bareRepo, "refs");
const discovery = await resolveGitDiscovery({ cwd: refs, ...legacy });
expect(discovery.envOverlay).toEqual({ GIT_DIR: path.join(refs, ".git") });
});
it("keeps a GIT_DIR the caller already chose", async () => {
const layout = path.join(makeTempDir(), "layout");
git(["init", "--bare", "-q", layout]);
const discovery = await resolveGitDiscovery({
cwd: layout,
gitDirSet: true,
repositoryRootGitDir: layout,
safeBareRepositorySupported: false,
});
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
});
});
describe("resolveGitDiscovery on Git 2.38 and later", () => {
it("relies on safe.bareRepository instead of walking the directory tree", async () => {
const layout = path.join(makeTempDir(), "layout");
git(["init", "--bare", "-q", layout]);
const discovery = await resolveGitDiscovery({
cwd: layout,
gitDirSet: false,
repositoryRootGitDir: null,
safeBareRepositorySupported: true,
});
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: {} });
});
it("names a bare repository root that the caller scoped", async () => {
const layout = path.join(makeTempDir(), "layout");
git(["init", "--bare", "-q", layout]);
const discovery = await resolveGitDiscovery({
cwd: layout,
gitDirSet: false,
repositoryRootGitDir: layout,
safeBareRepositorySupported: true,
});
expect(discovery).toEqual({ configArgs: EXPLICIT, envOverlay: { GIT_DIR: layout } });
});
});
describe("runWithRepositoryRoot", () => {
it("names a bare repository root only for commands at that root", async () => {
const bareRepo = path.join(makeTempDir(), "repo.git");
git(["init", "--bare", "-q", bareRepo]);
const inside = await runWithRepositoryRoot(bareRepo, async () => ({
root: readRepositoryRootGitDir(bareRepo),
below: readRepositoryRootGitDir(path.join(bareRepo, "refs")),
}));
expect(inside).toEqual({ root: bareRepo, below: null });
expect(readRepositoryRootGitDir(bareRepo)).toBeNull();
});
it("leaves a checkout root to normal discovery", async () => {
const checkout = path.join(makeTempDir(), "checkout");
git(["init", "-q", checkout]);
const named = await runWithRepositoryRoot(checkout, async () =>
readRepositoryRootGitDir(checkout),
);
expect(named).toBeNull();
});
});
describe("parseSafeBareRepositorySupport", () => {
it.each([
["git version 2.53.0", true],
["git version 2.38.0", true],
["git version 2.45.1.windows.1", true],
["git version 3.0.0", true],
["git version 2.37.1 (Apple Git-137)", false],
["git version 2.34.1", false],
["git version 1.9.5", false],
["unexpected output", false],
])("%s → %s", (output, supported) => {
expect(parseSafeBareRepositorySupport(output)).toBe(supported);
});
});
@@ -0,0 +1,172 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { lstat, realpath, stat } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "./spawn.js";
const EXPLICIT_BARE_REPOSITORY = ["-c", "safe.bareRepository=explicit"];
/** How a git command finds its repository. */
export interface GitDiscovery {
configArgs: string[];
envOverlay: ProcessEnvRecord;
}
export interface GitDiscoveryInput {
cwd: string;
/** The command already names its repository through `GIT_DIR`. */
gitDirSet: boolean;
/** From `readRepositoryRootGitDir`, read when the command was submitted. */
repositoryRootGitDir: string | null;
safeBareRepositorySupported: boolean;
}
interface RepositoryRoot {
paths: readonly string[];
gitDir: string;
}
const repositoryRoots = new AsyncLocalStorage<readonly RepositoryRoot[]>();
/**
* Runs `operation` with `root` named as the repository of every git command
* whose cwd is exactly `root`.
*
* Paseo records a bare repository as a repository root when only its linked
* checkouts use it. Git has no `.git` to find there, so those commands receive
* the bare repository through `GIT_DIR`. A root with a `.git` keeps normal
* discovery, and directories below `root` are not affected.
*/
export async function runWithRepositoryRoot<T>(
root: string,
operation: () => Promise<T>,
): Promise<T> {
const current = repositoryRoots.getStore() ?? [];
if (findRepositoryRoot(current, root)) return operation();
const named = await readBareRepositoryRoot(root);
if (!named) return operation();
return repositoryRoots.run([...current, named], operation);
}
/** The bare repository `runWithRepositoryRoot` named for `cwd` in this async context. */
export function readRepositoryRootGitDir(cwd: string): string | null {
return findRepositoryRoot(repositoryRoots.getStore() ?? [], cwd)?.gitDir ?? null;
}
function findRepositoryRoot(
roots: readonly RepositoryRoot[],
cwd: string,
): RepositoryRoot | undefined {
const path = resolve(cwd);
return roots.find((root) => root.paths.includes(path));
}
async function readBareRepositoryRoot(root: string): Promise<RepositoryRoot | null> {
const dotGit = await lstat(join(root, ".git")).catch(() => null);
if (dotGit || !(await looksLikeBareRepository(root))) return null;
const gitDir = await realpath(root).catch(() => null);
if (!gitDir) return null;
return { paths: [...new Set([resolve(root), gitDir])], gitDir };
}
/**
* Keeps git from adopting a directory that only looks like a bare repository
* (`HEAD`, `objects/`, `refs/`), at `cwd` or above it.
*
* A caller that works on a bare repository names it with `GIT_DIR`, directly or
* through `runWithRepositoryRoot`.
*
* - Git 2.38 and later: `safe.bareRepository=explicit`.
* - Earlier releases ignore that setting. When discovery from `cwd` would reach
* such a directory before any `.git`, `GIT_DIR` is pinned to the missing
* `<cwd>/.git`, so git reports that no repository was found.
*/
export async function resolveGitDiscovery(input: GitDiscoveryInput): Promise<GitDiscovery> {
if (!input.gitDirSet && input.repositoryRootGitDir) {
return {
configArgs: EXPLICIT_BARE_REPOSITORY,
envOverlay: { GIT_DIR: input.repositoryRootGitDir },
};
}
if (input.gitDirSet || input.safeBareRepositorySupported) {
return { configArgs: EXPLICIT_BARE_REPOSITORY, envOverlay: {} };
}
if (!(await discoveryReachesImplicitBareRepository(input.cwd))) {
return { configArgs: EXPLICIT_BARE_REPOSITORY, envOverlay: {} };
}
return {
configArgs: EXPLICIT_BARE_REPOSITORY,
envOverlay: { GIT_DIR: join(input.cwd, ".git") },
};
}
/** `safe.bareRepository` arrived in Git 2.38. */
export function parseSafeBareRepositorySupport(versionOutput: string): boolean {
const match = /git version (\d+)\.(\d+)/.exec(versionOutput);
if (!match) return false;
const major = Number(match[1]);
const minor = Number(match[2]);
return major > 2 || (major === 2 && minor >= 38);
}
let safeBareRepositorySupport: Promise<boolean> | null = null;
/** Reads `git --version` once per process. */
export function readSafeBareRepositorySupport(): Promise<boolean> {
safeBareRepositorySupport ??= execCommand("git", ["--version"]).then(
({ stdout }) => parseSafeBareRepositorySupport(stdout),
() => false,
);
return safeBareRepositorySupport;
}
// Follows git's discovery order: `<dir>/.git` first, then `<dir>` itself as a
// bare repository, then the parent. Git itself accepts a bare-looking directory
// that is a checkout's `.git`, or sits in its `worktrees/` or `modules/`.
async function discoveryReachesImplicitBareRepository(cwd: string): Promise<boolean> {
let dir: string;
try {
dir = await realpath(cwd);
} catch {
return false;
}
while (true) {
const dotGit = join(dir, ".git");
if ((await isFile(dotGit)) || (await looksLikeBareRepository(dotGit))) return false;
if (await looksLikeBareRepository(dir)) return !isInsideDotGit(dir);
const parent = dirname(dir);
if (parent === dir) return false;
dir = parent;
}
}
function isInsideDotGit(dir: string): boolean {
const path = dir.replaceAll("\\", "/");
return (
basename(dir) === ".git" || path.includes("/.git/worktrees/") || path.includes("/.git/modules/")
);
}
async function looksLikeBareRepository(dir: string): Promise<boolean> {
return (
(await isFile(join(dir, "HEAD"))) &&
(await isDirectory(join(dir, "objects"))) &&
(await isDirectory(join(dir, "refs")))
);
}
async function isFile(path: string): Promise<boolean> {
try {
return (await stat(path)).isFile();
} catch {
return false;
}
}
async function isDirectory(path: string): Promise<boolean> {
try {
return (await stat(path)).isDirectory();
} catch {
return false;
}
}
@@ -1,8 +1,18 @@
import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
realpathSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { runWithRepositoryRoot } from "./git-repository-discovery.js";
import { runGitCommand } from "./run-git-command.js";
const tempDirs: string[] = [];
@@ -49,3 +59,112 @@ describe("runGitCommand fsmonitor isolation", () => {
expect(result.stdout.trim()).toBe("false");
});
});
function git(args: string[], cwd?: string): string {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
}
function makeTempDir(): string {
const dir = realpathSync.native(mkdtempSync(path.join(tmpdir(), "paseo-git-discovery-")));
tempDirs.push(dir);
return dir;
}
// Files shaped like a bare repository (`HEAD`, `config`, `objects/`, `refs/`) that
// git would adopt implicitly, with a clean filter that leaves a marker when run.
function createBareRepositoryLayout(root: string, name: string): { dir: string; marker: string } {
const dir = path.join(root, name);
git(["init", "--bare", "-q", dir]);
const marker = path.join(root, `${name}.marker`);
writeFileSync(path.join(dir, "info", "attributes"), "* filter=probe\n");
git(["config", "-f", path.join(dir, "config"), "filter.probe.clean", `touch '${marker}'; cat`]);
return { dir, marker };
}
function createBareRepositoryWithLinkedWorktree(root: string): {
bareRepo: string;
worktree: string;
} {
const source = path.join(root, "source");
git(["init", "-q", "-b", "main", source]);
git(
[
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"-q",
"--allow-empty",
"-m",
"base",
],
source,
);
const bareRepo = path.join(root, "repo.git");
git(["clone", "-q", "--bare", source, bareRepo]);
const worktree = path.join(root, "main");
git(["worktree", "add", "-q", worktree, "main"], bareRepo);
return { bareRepo, worktree };
}
function listedWorktreePaths(porcelain: string): string[] {
return porcelain
.split("\n")
.filter((line) => line.startsWith("worktree "))
.map((line) => path.resolve(line.slice("worktree ".length)));
}
describe("runGitCommand repository discovery", () => {
it("does not adopt a bare repository layout at the working directory", async () => {
const root = makeTempDir();
const layout = createBareRepositoryLayout(root, "layout");
writeFileSync(path.join(layout.dir, "f.txt"), "contents\n");
await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: layout.dir });
expect(existsSync(layout.marker)).toBe(false);
await expect(
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: layout.dir }),
).rejects.toThrow(/cannot use bare repository/);
});
it("does not adopt a bare repository layout in a parent directory", async () => {
const root = makeTempDir();
const layout = createBareRepositoryLayout(root, "layout");
const nested = path.join(layout.dir, "nested");
mkdirSync(nested);
writeFileSync(path.join(nested, "f.txt"), "contents\n");
await runGitCommand(["hash-object", "--path=f.txt", "f.txt"], { cwd: nested });
expect(existsSync(layout.marker)).toBe(false);
await expect(
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: nested }),
).rejects.toThrow(/cannot use bare repository/);
});
it("does not adopt a bare repository at the working directory even with linked worktrees", async () => {
const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(makeTempDir());
await expect(
runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo }),
).rejects.toThrow(/cannot use bare repository/);
const fromWorktree = await runGitCommand(["rev-parse", "--git-common-dir"], { cwd: worktree });
expect(path.resolve(worktree, fromWorktree.stdout.trim())).toBe(bareRepo);
});
it("runs at a bare repository root named with runWithRepositoryRoot", async () => {
const { bareRepo, worktree } = createBareRepositoryWithLinkedWorktree(makeTempDir());
const fromRoot = await runWithRepositoryRoot(bareRepo, () =>
runGitCommand(["worktree", "list", "--porcelain"], { cwd: bareRepo }),
);
const belowRoot = await runWithRepositoryRoot(bareRepo, () =>
runGitCommand(["rev-parse", "--absolute-git-dir"], { cwd: path.join(bareRepo, "refs") }),
).catch((error: unknown) => error);
expect(listedWorktreePaths(fromRoot.stdout)).toContain(worktree);
expect(String(belowRoot)).toMatch(/cannot use bare repository/);
});
});
+57 -15
View File
@@ -11,6 +11,11 @@ import {
startGitCommandTrace,
submitGitCommandTrace,
} from "./git-command-trace.js";
import {
readRepositoryRootGitDir,
readSafeBareRepositorySupport,
resolveGitDiscovery,
} from "./git-repository-discovery.js";
import { spawnProcess } from "./spawn.js";
import {
GitProcessScheduler,
@@ -296,13 +301,15 @@ function executeGitCommand<Output>(
submission: GitCommandSubmission,
): Promise<GitCommandResult<Output>> {
const priority = submission.priority ?? gitCommandPriority.getStore() ?? "normal";
// Read at submission: the scheduler may start the process from another async context.
const repositoryRootGitDir = readRepositoryRootGitDir(options.cwd);
const metricsState = submitGitCommandMetric(args, options.cwd, priority);
const commandTrace = submitGitCommandTrace(args, options.cwd, {
active: gitProcessScheduler.activeCount,
pending: gitProcessScheduler.pendingCount,
});
const runtimeMetric = gitRuntimeMetrics.submit(getGitOperation(args), submission.provenance);
const startCommand = () => {
const spawnCommand = (launch: GitLaunch) => {
let releaseProcessSlot!: () => void;
const exited = new Promise<void>((resolve) => {
releaseProcessSlot = resolve;
@@ -317,7 +324,10 @@ function executeGitCommand<Output>(
const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const acceptExitCodes = options.acceptExitCodes ?? [0];
const command = formatGitCommand(args);
const envOverlay = mergeEnvOverlays(options.env, options.envOverlay);
const envOverlay = mergeEnvOverlays(
mergeEnvOverlays(options.env, options.envOverlay),
launch.envOverlay,
);
const startedAt = Date.now();
beginGitCommandMetric(metricsState);
const logger = typeof options.logger?.trace === "function" ? options.logger : undefined;
@@ -407,19 +417,12 @@ function executeGitCommand<Output>(
let child: ReturnType<typeof spawnProcess>;
try {
// `core.quotepath=false` makes git emit raw UTF-8 paths instead of
// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`).
// `core.fsmonitor=false` prevents repository config from launching a command.
child = spawnProcess(
"git",
["-c", "core.quotepath=false", "-c", "core.fsmonitor=false", ...args],
{
cwd: options.cwd,
envOverlay,
shell: false,
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
},
);
child = spawnProcess("git", [...launch.configArgs, ...args], {
cwd: options.cwd,
envOverlay,
shell: false,
stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
});
spawnGitCommandTrace(commandTrace, child.pid);
} catch (error) {
rejectSpawnFailure(error);
@@ -574,6 +577,15 @@ function executeGitCommand<Output>(
});
return { result: resultPromise, exited };
};
// The process slot stays held through the launch lookup because `exited`
// settles only after the spawned process exits. `resolveGitLaunch` never rejects.
const startCommand = () => {
const spawned = resolveGitLaunch(options, repositoryRootGitDir).then(spawnCommand);
return {
result: spawned.then((scheduled) => scheduled.result),
exited: spawned.then((scheduled) => scheduled.exited),
};
};
const promise = gitProcessScheduler.run(startCommand, { priority });
gitRuntimeMetrics.observeLimiter(
gitProcessScheduler.activeCount,
@@ -582,6 +594,36 @@ function executeGitCommand<Output>(
return promise;
}
interface GitLaunch {
configArgs: string[];
envOverlay: ProcessEnvRecord;
}
// `core.quotepath=false` makes git emit raw UTF-8 paths instead of
// octal-escaping non-ASCII bytes (e.g. `测试文件.txt` vs `"\346\265\213..."`).
// `core.fsmonitor=false` prevents repository config from launching a command.
async function resolveGitLaunch(
options: GitCommandOptions,
repositoryRootGitDir: string | null,
): Promise<GitLaunch> {
const discovery = await resolveGitDiscovery({
cwd: options.cwd,
repositoryRootGitDir,
gitDirSet: Boolean(options.envOverlay?.GIT_DIR ?? options.env?.GIT_DIR ?? process.env.GIT_DIR),
safeBareRepositorySupported: await readSafeBareRepositorySupport(),
});
return {
configArgs: [
"-c",
"core.quotepath=false",
"-c",
"core.fsmonitor=false",
...discovery.configArgs,
],
envOverlay: discovery.envOverlay,
};
}
export const runGitCommand: RunGitCommand = (args, options) =>
executeGitCommand(args, options, decodeUtf8, {});
@@ -5,6 +5,7 @@ import {
deletePaseoWorktree,
readWorktreeHead,
isPaseoOwnedWorktreeCwd,
listPaseoWorktrees,
mapWorkspaceCwdToWorktree,
runWorktreeTeardownCommands,
slugify,
@@ -97,6 +98,14 @@ describe("paseo worktree manager", () => {
await rm(tempDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});
function cloneBareRepository(): string {
const bareRepo = join(tempDir, "bare.git");
execFileSync("git", ["clone", "--bare", "-q", repoDir, bareRepo]);
// A bare clone does not copy the checkout's local config; its linked worktrees share this one.
execFileSync("git", ["--git-dir", bareRepo, "config", "core.autocrlf", "false"]);
return bareRepo;
}
it.each([
{ existing: [], preferred: "main/patch-1", expected: "main-1/patch-1" },
{ existing: ["main-1"], preferred: "main/patch-1", expected: "main-2/patch-1" },
@@ -303,6 +312,44 @@ describe("paseo worktree manager", () => {
});
});
it("creates and removes a worktree from a bare repository with no linked checkouts", async () => {
const bareRepo = cloneBareRepository();
const created = await createLegacyWorktreeForTest({
branchName: "from-bare",
cwd: bareRepo,
baseBranch: "main",
worktreeSlug: "from-bare",
paseoHome,
});
expect(readFileSync(join(created.worktreePath, "file.txt"), "utf8")).toBe("hello\n");
await deletePaseoWorktree({ cwd: bareRepo, worktreePath: created.worktreePath, paseoHome });
expect(existsSync(created.worktreePath)).toBe(false);
expect(
execFileSync("git", ["--git-dir", bareRepo, "worktree", "list", "--porcelain"], {
encoding: "utf8",
}),
).not.toContain(created.worktreePath);
});
it("lists the worktrees of a bare repository that only Paseo checkouts use", async () => {
const bareRepo = cloneBareRepository();
const created = await createLegacyWorktreeForTest({
branchName: "listed",
cwd: bareRepo,
baseBranch: "main",
worktreeSlug: "listed",
paseoHome,
});
const worktrees = await listPaseoWorktrees({ cwd: bareRepo, paseoHome });
expect(worktrees.map((entry) => [entry.path, entry.branchName])).toEqual([
[realpathSync.native(created.worktreePath), "listed"],
]);
});
it("deletes a worktree whose .git admin dir has already been removed", async () => {
const created = await createLegacyWorktreeForTest({
branchName: "orphan-delete-branch",
+58 -12
View File
@@ -34,6 +34,7 @@ import {
writePaseoWorktreeMetadata,
writePaseoWorktreeRuntimeMetadata,
} from "./worktree-metadata.js";
import { runWithRepositoryRoot } from "./git-repository-discovery.js";
import { runGitCommand } from "./run-git-command.js";
import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js";
import { spawnProcess } from "./spawn.js";
@@ -1217,15 +1218,23 @@ export async function listGitWorktrees({ cwd }: { cwd: string }): Promise<GitWor
return worktrees;
}
export async function listPaseoWorktrees({
cwd,
paseoHome,
worktreesRoot,
}: {
export interface ListPaseoWorktreesOptions {
cwd: string;
paseoHome?: string;
worktreesRoot?: string;
}): Promise<PaseoWorktreeInfo[]> {
}
export function listPaseoWorktrees(
options: ListPaseoWorktreesOptions,
): Promise<PaseoWorktreeInfo[]> {
return runWithRepositoryRoot(options.cwd, () => listPaseoWorktreesAtRepositoryRoot(options));
}
async function listPaseoWorktreesAtRepositoryRoot({
cwd,
paseoHome,
worktreesRoot,
}: ListPaseoWorktreesOptions): Promise<PaseoWorktreeInfo[]> {
const projectWorktreesRoot = await getPaseoWorktreesRoot(cwd, paseoHome, worktreesRoot);
const { entries } = await readGitWorktreeEntries(cwd);
@@ -1325,7 +1334,12 @@ export async function readWorktreeHeadReference(worktreePath: string): Promise<s
}
}
export async function deletePaseoWorktree({
export function deletePaseoWorktree(options: DeletePaseoWorktreeOptions): Promise<void> {
const operation = () => deletePaseoWorktreeAtRepositoryRoot(options);
return options.cwd ? runWithRepositoryRoot(options.cwd, operation) : operation();
}
async function deletePaseoWorktreeAtRepositoryRoot({
cwd,
worktreePath,
teardownCwds,
@@ -1660,7 +1674,13 @@ export function createWorktree(
export function createWorktree(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
export async function createWorktree({
export function createWorktree(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }> {
return runWithRepositoryRoot(options.cwd, () => createWorktreeAtRepositoryRoot(options));
}
async function createWorktreeAtRepositoryRoot({
cwd,
source,
preparedBranchOff,
@@ -1775,7 +1795,15 @@ export function runPluginWorktreeManagerCheckout(
export function runPluginWorktreeManagerCheckout(
options: RunPluginWorktreeManagerCheckoutOptions,
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null>;
export async function runPluginWorktreeManagerCheckout(
export function runPluginWorktreeManagerCheckout(
options: RunPluginWorktreeManagerCheckoutOptions,
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null> {
return runWithRepositoryRoot(options.cwd, () =>
runPluginWorktreeManagerCheckoutAtRepositoryRoot(options),
);
}
async function runPluginWorktreeManagerCheckoutAtRepositoryRoot(
options: RunPluginWorktreeManagerCheckoutOptions,
): Promise<(Omit<CreatedWorktree, "branchName"> & { branchName: string | null }) | null> {
const {
@@ -2321,7 +2349,17 @@ async function resolveRestoredWorktreeFromBasePlan(
};
}
export async function prepareWorktreeBranchOff(
export function prepareWorktreeBranchOff(
cwd: string,
source: Extract<WorktreeSource, { kind: "branch-off" }>,
previous?: PreparedWorktreeBranchOff,
): Promise<PreparedWorktreeBranchOff> {
return runWithRepositoryRoot(cwd, () =>
prepareWorktreeBranchOffAtRepositoryRoot(cwd, source, previous),
);
}
async function prepareWorktreeBranchOffAtRepositoryRoot(
cwd: string,
source: Extract<WorktreeSource, { kind: "branch-off" }>,
previous?: PreparedWorktreeBranchOff,
@@ -2551,11 +2589,19 @@ async function configureWorktreePushRemote(options: {
* Fetches the first of `sources` a remote serves into the local ref `destination`, and returns
* the name of that remote.
*/
export async function fetchFirstAvailableRef(options: {
export interface FetchFirstAvailableRefOptions {
cwd: string;
sources: WorktreeCheckoutRef[];
destination: string;
}): Promise<string> {
}
export function fetchFirstAvailableRef(options: FetchFirstAvailableRefOptions): Promise<string> {
return runWithRepositoryRoot(options.cwd, () => fetchFirstAvailableRefAtRepositoryRoot(options));
}
async function fetchFirstAvailableRefAtRepositoryRoot(
options: FetchFirstAvailableRefOptions,
): Promise<string> {
let lastResult:
| Awaited<ReturnType<typeof runGitCommand>>
| { stderr: string; stdout: string; exitCode: number | null }
+17 -2
View File
@@ -177,7 +177,7 @@ test("filters by search and clears to all plugins", async ({ page }) => {
test("keeps the directory's ranking window when searching", async ({ page }) => {
await page.goto("/plugins?window=month");
await submitSearch(page, "graphite");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite&window=month$/);
await expectDirectorySearch(page, "graphite", "month");
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
@@ -358,10 +358,16 @@ test.describe("search engine visits without JavaScript", () => {
});
test("renders search results and submits the search form", async ({ page }) => {
await page.goto("/plugins/all?q=graphite");
await page.goto("/plugins?window=month");
await submitSearch(page, "graphite");
await expectDirectorySearch(page, "graphite", "month");
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible();
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
);
await expect(page.getByRole("main").getByRole("link", { name: /Graphite/ })).toBeVisible();
await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0);
@@ -459,6 +465,15 @@ async function submitSearch(page: Page, term: string) {
await page.keyboard.press("Enter");
}
async function expectDirectorySearch(page: Page, term: string, window: string) {
await expect(page).toHaveURL(
(url) =>
url.pathname === "/plugins/all" &&
url.searchParams.get("q") === term &&
url.searchParams.get("window") === window,
);
}
async function typeSearch(page: Page, term: string) {
await page.getByRole("searchbox", { name: "Search plugins" }).pressSequentially(term);
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.17.3",
"version": "0.17.4",
"private": true,
"type": "module",
"scripts": {
-468
View File
@@ -1,468 +0,0 @@
diff --git a/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js b/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js
index 72ba2a7..e2f32a5 100644
--- a/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js
+++ b/node_modules/@gorhom/portal/lib/commonjs/components/portalHost/PortalHost.js
@@ -34,7 +34,11 @@ const PortalHostComponent = ({
}, []); //#endregion
//#region render
- return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state.map(item => item.node)); //#endregion
+ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a
+ // portal shifts the ones after it and React remounts them.
+ return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, state.map(item => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
+ key: item.name
+ }, item.node))); //#endregion
};
const PortalHost = /*#__PURE__*/(0, _react.memo)(PortalHostComponent);
diff --git a/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js b/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js
index 3b2a494..af6616e 100644
--- a/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js
+++ b/node_modules/@gorhom/portal/lib/commonjs/components/portalProvider/PortalProvider.js
@@ -11,9 +11,7 @@ var _PortalHost = require("../portalHost/PortalHost");
var _portal = require("../../contexts/portal");
-var _constants = require("../../state/constants");
-
-var _reducer = require("../../state/reducer");
+var _store = require("../../state/store");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
@@ -24,11 +22,11 @@ const PortalProviderComponent = ({
shouldAddRootHost = true,
children
}) => {
- const [state, dispatch] = (0, _react.useReducer)(_reducer.reducer, _constants.INITIAL_STATE);
+ const [store] = (0, _react.useState)(_store.createPortalStore);
return /*#__PURE__*/_react.default.createElement(_portal.PortalDispatchContext.Provider, {
- value: dispatch
+ value: store.dispatch
}, /*#__PURE__*/_react.default.createElement(_portal.PortalStateContext.Provider, {
- value: state
+ value: store
}, children, shouldAddRootHost && /*#__PURE__*/_react.default.createElement(_PortalHost.PortalHost, {
name: rootHostName
})));
diff --git a/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js b/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js
index 7a18089..77a8e24 100644
--- a/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js
+++ b/node_modules/@gorhom/portal/lib/commonjs/hooks/usePortalState.js
@@ -10,13 +10,15 @@ var _react = require("react");
var _portal = require("../contexts/portal");
const usePortalState = hostName => {
- const state = (0, _react.useContext)(_portal.PortalStateContext);
+ const store = (0, _react.useContext)(_portal.PortalStateContext);
- if (state === null) {
+ if (store === null) {
throw new Error("'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component.");
}
- return state[hostName] || [];
+ const getPortals = () => store.getPortals(hostName);
+
+ return (0, _react.useSyncExternalStore)(store.subscribe, getPortals, getPortals);
};
exports.usePortalState = usePortalState;
diff --git a/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js b/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js
index 158e729..cd50661 100644
--- a/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js
+++ b/node_modules/@gorhom/portal/lib/commonjs/state/reducer.js
@@ -31,17 +31,15 @@ const addUpdatePortal = (state, hostName, portalName, node) => {
*/
- const index = state[hostName].findIndex(item => item.name === portalName);
-
- if (index !== -1) {
- state[hostName][index].node = node;
- } else {
- state[hostName].push({
- name: portalName,
- node
- });
- }
-
+ // Paseo patch: a changed host gets a new array, so the store can hand each host its own
+ // snapshot and only the host whose portals changed renders.
+ const portals = state[hostName];
+ const index = portals.findIndex(item => item.name === portalName);
+ const portal = {
+ name: portalName,
+ node
+ };
+ state[hostName] = index !== -1 ? portals.map(item => item.name === portalName ? portal : item) : [...portals, portal];
return state;
};
@@ -56,7 +54,11 @@ const removePortal = (state, hostName, portalName) => {
}
const index = state[hostName].findIndex(item => item.name === portalName);
- if (index !== -1) state[hostName].splice(index, 1);
+
+ if (index !== -1) {
+ state[hostName] = state[hostName].filter(item => item.name !== portalName);
+ }
+
return state;
};
diff --git a/node_modules/@gorhom/portal/lib/commonjs/state/store.js b/node_modules/@gorhom/portal/lib/commonjs/state/store.js
new file mode 100644
index 0000000..0da9a5c
--- /dev/null
+++ b/node_modules/@gorhom/portal/lib/commonjs/state/store.js
@@ -0,0 +1,34 @@
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+exports.createPortalStore = void 0;
+
+var _constants = require("./constants");
+
+var _reducer = require("./reducer");
+
+const NO_PORTALS = [];
+// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context
+// value it changed on every portal add, update and remove, and React then walked every fiber under
+// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead.
+const createPortalStore = () => {
+ let state = _constants.INITIAL_STATE;
+ const listeners = new Set();
+ return {
+ getPortals: hostName => state[hostName] || NO_PORTALS,
+ dispatch: action => {
+ state = (0, _reducer.reducer)(state, action);
+ listeners.forEach(listener => listener());
+ },
+ subscribe: listener => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ }
+ };
+};
+
+exports.createPortalStore = createPortalStore;
diff --git a/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js b/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js
index d22cc16..e492b4b 100644
--- a/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js
+++ b/node_modules/@gorhom/portal/lib/module/components/portalHost/PortalHost.js
@@ -21,7 +21,11 @@ const PortalHostComponent = ({
}, []); //#endregion
//#region render
- return /*#__PURE__*/React.createElement(React.Fragment, null, state.map(item => item.node)); //#endregion
+ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a
+ // portal shifts the ones after it and React remounts them.
+ return /*#__PURE__*/React.createElement(React.Fragment, null, state.map(item => /*#__PURE__*/React.createElement(React.Fragment, {
+ key: item.name
+ }, item.node))); //#endregion
};
export const PortalHost = /*#__PURE__*/memo(PortalHostComponent);
diff --git a/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js b/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js
index 522a08a..d2e07b6 100644
--- a/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js
+++ b/node_modules/@gorhom/portal/lib/module/components/portalProvider/PortalProvider.js
@@ -1,19 +1,18 @@
-import React, { memo, useReducer } from 'react';
+import React, { memo, useState } from 'react';
import { PortalHost } from '../portalHost/PortalHost';
import { PortalDispatchContext, PortalStateContext } from '../../contexts/portal';
-import { INITIAL_STATE } from '../../state/constants';
-import { reducer } from '../../state/reducer';
+import { createPortalStore } from '../../state/store';
const PortalProviderComponent = ({
rootHostName = 'root',
shouldAddRootHost = true,
children
}) => {
- const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
+ const [store] = useState(createPortalStore);
return /*#__PURE__*/React.createElement(PortalDispatchContext.Provider, {
- value: dispatch
+ value: store.dispatch
}, /*#__PURE__*/React.createElement(PortalStateContext.Provider, {
- value: state
+ value: store
}, children, shouldAddRootHost && /*#__PURE__*/React.createElement(PortalHost, {
name: rootHostName
})));
diff --git a/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js b/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js
index c82cc71..daee3ac 100644
--- a/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js
+++ b/node_modules/@gorhom/portal/lib/module/hooks/usePortalState.js
@@ -1,12 +1,14 @@
-import { useContext } from 'react';
+import { useContext, useSyncExternalStore } from 'react';
import { PortalStateContext } from '../contexts/portal';
export const usePortalState = hostName => {
- const state = useContext(PortalStateContext);
+ const store = useContext(PortalStateContext);
- if (state === null) {
+ if (store === null) {
throw new Error("'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component.");
}
- return state[hostName] || [];
+ const getPortals = () => store.getPortals(hostName);
+
+ return useSyncExternalStore(store.subscribe, getPortals, getPortals);
};
//# sourceMappingURL=usePortalState.js.map
\ No newline at end of file
diff --git a/node_modules/@gorhom/portal/lib/module/state/reducer.js b/node_modules/@gorhom/portal/lib/module/state/reducer.js
index cad5f28..51f7124 100644
--- a/node_modules/@gorhom/portal/lib/module/state/reducer.js
+++ b/node_modules/@gorhom/portal/lib/module/state/reducer.js
@@ -23,17 +23,15 @@ const addUpdatePortal = (state, hostName, portalName, node) => {
*/
- const index = state[hostName].findIndex(item => item.name === portalName);
-
- if (index !== -1) {
- state[hostName][index].node = node;
- } else {
- state[hostName].push({
- name: portalName,
- node
- });
- }
-
+ // Paseo patch: a changed host gets a new array, so the store can hand each host its own
+ // snapshot and only the host whose portals changed renders.
+ const portals = state[hostName];
+ const index = portals.findIndex(item => item.name === portalName);
+ const portal = {
+ name: portalName,
+ node
+ };
+ state[hostName] = index !== -1 ? portals.map(item => item.name === portalName ? portal : item) : [...portals, portal];
return state;
};
@@ -48,7 +46,11 @@ const removePortal = (state, hostName, portalName) => {
}
const index = state[hostName].findIndex(item => item.name === portalName);
- if (index !== -1) state[hostName].splice(index, 1);
+
+ if (index !== -1) {
+ state[hostName] = state[hostName].filter(item => item.name !== portalName);
+ }
+
return state;
};
diff --git a/node_modules/@gorhom/portal/lib/module/state/store.js b/node_modules/@gorhom/portal/lib/module/state/store.js
new file mode 100644
index 0000000..2c94075
--- /dev/null
+++ b/node_modules/@gorhom/portal/lib/module/state/store.js
@@ -0,0 +1,23 @@
+import { INITIAL_STATE } from './constants';
+import { reducer } from './reducer';
+const NO_PORTALS = [];
+// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context
+// value it changed on every portal add, update and remove, and React then walked every fiber under
+// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead.
+export const createPortalStore = () => {
+ let state = INITIAL_STATE;
+ const listeners = new Set();
+ return {
+ getPortals: hostName => state[hostName] || NO_PORTALS,
+ dispatch: action => {
+ state = reducer(state, action);
+ listeners.forEach(listener => listener());
+ },
+ subscribe: listener => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ }
+ };
+};
diff --git a/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx b/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx
index 62a2103..699765e 100644
--- a/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx
+++ b/node_modules/@gorhom/portal/src/components/portalHost/PortalHost.tsx
@@ -20,7 +20,15 @@ const PortalHostComponent = ({ name }: PortalHostProps) => {
//#endregion
//#region render
- return <>{state.map(item => item.node)}</>;
+ // Backport of https://github.com/gorhom/react-native-portal/pull/62: without a key, removing a
+ // portal shifts the ones after it and React remounts them.
+ return (
+ <>
+ {state.map(item => (
+ <React.Fragment key={item.name}>{item.node}</React.Fragment>
+ ))}
+ </>
+ );
//#endregion
};
diff --git a/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx b/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx
index 8350171..f91273a 100644
--- a/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx
+++ b/node_modules/@gorhom/portal/src/components/portalProvider/PortalProvider.tsx
@@ -1,11 +1,10 @@
-import React, { memo, useReducer } from 'react';
+import React, { memo, useState } from 'react';
import { PortalHost } from '../portalHost/PortalHost';
import {
PortalDispatchContext,
PortalStateContext,
} from '../../contexts/portal';
-import { INITIAL_STATE } from '../../state/constants';
-import { reducer } from '../../state/reducer';
+import { createPortalStore } from '../../state/store';
import type { PortalProviderProps } from './types';
const PortalProviderComponent = ({
@@ -13,10 +12,10 @@ const PortalProviderComponent = ({
shouldAddRootHost = true,
children,
}: PortalProviderProps) => {
- const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
+ const [store] = useState(createPortalStore);
return (
- <PortalDispatchContext.Provider value={dispatch}>
- <PortalStateContext.Provider value={state}>
+ <PortalDispatchContext.Provider value={store.dispatch}>
+ <PortalStateContext.Provider value={store}>
{children}
{shouldAddRootHost && <PortalHost name={rootHostName} />}
</PortalStateContext.Provider>
diff --git a/node_modules/@gorhom/portal/src/contexts/portal.ts b/node_modules/@gorhom/portal/src/contexts/portal.ts
index 2e3a46f..85ff020 100644
--- a/node_modules/@gorhom/portal/src/contexts/portal.ts
+++ b/node_modules/@gorhom/portal/src/contexts/portal.ts
@@ -1,10 +1,7 @@
import { createContext } from 'react';
+import type { PortalStore } from '../state/store';
import type { ActionTypes } from '../state/types';
-import type { PortalType } from '../types';
-export const PortalStateContext = createContext<Record<
- string,
- Array<PortalType>
-> | null>(null);
+export const PortalStateContext = createContext<PortalStore | null>(null);
export const PortalDispatchContext =
createContext<React.Dispatch<ActionTypes> | null>(null);
diff --git a/node_modules/@gorhom/portal/src/hooks/usePortalState.ts b/node_modules/@gorhom/portal/src/hooks/usePortalState.ts
index 64bb180..d9877c3 100644
--- a/node_modules/@gorhom/portal/src/hooks/usePortalState.ts
+++ b/node_modules/@gorhom/portal/src/hooks/usePortalState.ts
@@ -1,14 +1,16 @@
-import { useContext } from 'react';
+import { useContext, useSyncExternalStore } from 'react';
import { PortalStateContext } from '../contexts/portal';
export const usePortalState = (hostName: string) => {
- const state = useContext(PortalStateContext);
+ const store = useContext(PortalStateContext);
- if (state === null) {
+ if (store === null) {
throw new Error(
"'PortalStateContext' cannot be null, please add 'PortalProvider' to the root component."
);
}
- return state[hostName] || [];
+ const getPortals = () => store.getPortals(hostName);
+
+ return useSyncExternalStore(store.subscribe, getPortals, getPortals);
};
diff --git a/node_modules/@gorhom/portal/src/state/reducer.ts b/node_modules/@gorhom/portal/src/state/reducer.ts
index 37f2414..1370244 100644
--- a/node_modules/@gorhom/portal/src/state/reducer.ts
+++ b/node_modules/@gorhom/portal/src/state/reducer.ts
@@ -38,15 +38,15 @@ const addUpdatePortal = (
/**
* updated portal, if it was already added.
*/
- const index = state[hostName].findIndex(item => item.name === portalName);
- if (index !== -1) {
- state[hostName][index].node = node;
- } else {
- state[hostName].push({
- name: portalName,
- node,
- });
- }
+ // Paseo patch: a changed host gets a new array, so the store can hand each host its own
+ // snapshot and only the host whose portals changed renders.
+ const portals = state[hostName];
+ const index = portals.findIndex(item => item.name === portalName);
+ const portal = { name: portalName, node };
+ state[hostName] =
+ index !== -1
+ ? portals.map(item => (item.name === portalName ? portal : item))
+ : [...portals, portal];
return state;
};
@@ -65,7 +65,9 @@ const removePortal = (
}
const index = state[hostName].findIndex(item => item.name === portalName);
- if (index !== -1) state[hostName].splice(index, 1);
+ if (index !== -1) {
+ state[hostName] = state[hostName].filter(item => item.name !== portalName);
+ }
return state;
};
diff --git a/node_modules/@gorhom/portal/src/state/store.ts b/node_modules/@gorhom/portal/src/state/store.ts
new file mode 100644
index 0000000..4acf035
--- /dev/null
+++ b/node_modules/@gorhom/portal/src/state/store.ts
@@ -0,0 +1,30 @@
+import { INITIAL_STATE } from './constants';
+import { reducer } from './reducer';
+import type { PortalType } from '../types';
+import type { ActionTypes } from './types';
+
+const NO_PORTALS: Array<PortalType> = [];
+
+// Paseo patch: portal state lives in a store, outside React state. Held in the provider's context
+// value it changed on every portal add, update and remove, and React then walked every fiber under
+// the provider (the whole app) to find the hosts consuming it. Hosts subscribe here instead.
+export const createPortalStore = () => {
+ let state: Record<string, Array<PortalType>> = INITIAL_STATE;
+ const listeners = new Set<() => void>();
+
+ return {
+ getPortals: (hostName: string) => state[hostName] || NO_PORTALS,
+ dispatch: (action: ActionTypes) => {
+ state = reducer(state, action);
+ listeners.forEach(listener => listener());
+ },
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ };
+};
+
+export type PortalStore = ReturnType<typeof createPortalStore>;
-170
View File
@@ -1,170 +0,0 @@
diff --git a/node_modules/react-dom/cjs/react-dom-client.development.js b/node_modules/react-dom/cjs/react-dom-client.development.js
index 771ecad..3d9bf72 100644
--- a/node_modules/react-dom/cjs/react-dom-client.development.js
+++ b/node_modules/react-dom/cjs/react-dom-client.development.js
@@ -4073,6 +4073,8 @@
? "Idle"
: "Other";
}
+ // Paseo backport of React 19.3.0: clear each measure once it is reported. The browser keeps
+ // every measure for the life of the page, so a long development session held millions.
function logComponentTrigger(fiber, startTime, endTime, trigger) {
supportsUserTiming &&
((reusableComponentOptions.start = startTime),
@@ -4088,7 +4090,7 @@
reusableComponentOptions
)
)
- : performance.measure(trigger, reusableComponentOptions));
+ : performance.measure(trigger, reusableComponentOptions), performance.clearMeasures(trigger));
}
function logComponentReappeared(fiber, startTime, endTime) {
logComponentTrigger(fiber, startTime, endTime, "Reconnect");
@@ -4159,7 +4161,7 @@
: performance.measure(
"\u200b" + name,
reusableComponentOptions
- )))
+ ), performance.clearMeasures("\u200b" + name)))
: null != selfTime
? selfTime.run(
console.timeStamp.bind(
@@ -4229,7 +4231,7 @@
? debugTask.run(
performance.measure.bind(performance, "\u200b" + name, fiber)
)
- : performance.measure("\u200b" + name, fiber);
+ : performance.measure("\u200b" + name, fiber), performance.clearMeasures("\u200b" + name);
}
}
}
@@ -4274,7 +4276,7 @@
startTime
)
)
- : performance.measure("\u200b" + name, startTime);
+ : performance.measure("\u200b" + name, startTime), performance.clearMeasures("\u200b" + name);
}
}
} else
@@ -4434,7 +4436,7 @@
? debugTask.run(
performance.measure.bind(performance, "Recovered", startTime)
)
- : performance.measure("Recovered", startTime);
+ : performance.measure("Recovered", startTime), performance.clearMeasures("Recovered");
}
}
function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
@@ -4517,7 +4519,7 @@
? debugTask.run(
performance.measure.bind(performance, "Errored", startTime)
)
- : performance.measure("Errored", startTime);
+ : performance.measure("Errored", startTime), performance.clearMeasures("Errored");
}
}
function logAnimatingPhase(startTime, endTime, debugTask) {
@@ -17111,7 +17113,7 @@
previousRenderStartTime
)
)
- : performance.measure(isSpawnedUpdate, previousRenderStartTime));
+ : performance.measure(isSpawnedUpdate, previousRenderStartTime), performance.clearMeasures(isSpawnedUpdate));
}
blockingUpdateTime = -1.1;
blockingUpdateType = 0;
@@ -17248,7 +17250,7 @@
previousRenderStartTime
)
)
- : performance.measure(debugTask, previousRenderStartTime))),
+ : performance.measure(debugTask, previousRenderStartTime), performance.clearMeasures(debugTask))),
(transitionUpdateTime = transitionStartTime = -1.1),
(transitionUpdateType = 0),
(transitionSuspendedTime = -1.1),
diff --git a/node_modules/react-dom/cjs/react-dom-profiling.development.js b/node_modules/react-dom/cjs/react-dom-profiling.development.js
index c8b583c..7fd2231 100644
--- a/node_modules/react-dom/cjs/react-dom-profiling.development.js
+++ b/node_modules/react-dom/cjs/react-dom-profiling.development.js
@@ -4081,6 +4081,8 @@
? "Idle"
: "Other";
}
+ // Paseo backport of React 19.3.0: clear each measure once it is reported. The browser keeps
+ // every measure for the life of the page, so a long development session held millions.
function logComponentTrigger(fiber, startTime, endTime, trigger) {
supportsUserTiming &&
((reusableComponentOptions.start = startTime),
@@ -4096,7 +4098,7 @@
reusableComponentOptions
)
)
- : performance.measure(trigger, reusableComponentOptions));
+ : performance.measure(trigger, reusableComponentOptions), performance.clearMeasures(trigger));
}
function logComponentReappeared(fiber, startTime, endTime) {
logComponentTrigger(fiber, startTime, endTime, "Reconnect");
@@ -4167,7 +4169,7 @@
: performance.measure(
"\u200b" + name,
reusableComponentOptions
- )))
+ ), performance.clearMeasures("\u200b" + name)))
: null != selfTime
? selfTime.run(
console.timeStamp.bind(
@@ -4237,7 +4239,7 @@
? debugTask.run(
performance.measure.bind(performance, "\u200b" + name, fiber)
)
- : performance.measure("\u200b" + name, fiber);
+ : performance.measure("\u200b" + name, fiber), performance.clearMeasures("\u200b" + name);
}
}
}
@@ -4282,7 +4284,7 @@
startTime
)
)
- : performance.measure("\u200b" + name, startTime);
+ : performance.measure("\u200b" + name, startTime), performance.clearMeasures("\u200b" + name);
}
}
} else
@@ -4442,7 +4444,7 @@
? debugTask.run(
performance.measure.bind(performance, "Recovered", startTime)
)
- : performance.measure("Recovered", startTime);
+ : performance.measure("Recovered", startTime), performance.clearMeasures("Recovered");
}
}
function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
@@ -4525,7 +4527,7 @@
? debugTask.run(
performance.measure.bind(performance, "Errored", startTime)
)
- : performance.measure("Errored", startTime);
+ : performance.measure("Errored", startTime), performance.clearMeasures("Errored");
}
}
function logAnimatingPhase(startTime, endTime, debugTask) {
@@ -17119,7 +17121,7 @@
previousRenderStartTime
)
)
- : performance.measure(isSpawnedUpdate, previousRenderStartTime));
+ : performance.measure(isSpawnedUpdate, previousRenderStartTime), performance.clearMeasures(isSpawnedUpdate));
}
blockingUpdateTime = -1.1;
blockingUpdateType = 0;
@@ -17256,7 +17258,7 @@
previousRenderStartTime
)
)
- : performance.measure(debugTask, previousRenderStartTime))),
+ : performance.measure(debugTask, previousRenderStartTime), performance.clearMeasures(debugTask))),
(transitionUpdateTime = transitionStartTime = -1.1),
(transitionUpdateType = 0),
(transitionSuspendedTime = -1.1),

Some files were not shown because too many files have changed in this diff Show More