Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 7aaff3abcc feat(desktop): add automatic update modes and download progress
Give desktop users control over background updater network traffic with a persisted updates.mode setting (automatic, notify, off; default automatic).

Enforce off and notify behavior in the Electron main process as well as the renderer so automatic checks never leave the machine when opted out, quit-time installs only run in automatic mode, and explicit downloads stream live progress to both the OS window progress bar and the in-app UI.
2026-11-25 10:45:00 +01:00
paseo-bot[bot] cd2e56f1fa Keep Git watcher retries on schedule after reconnect (#10602)
* fix(server): keep watcher retries on schedule after reconnect

A watcher that timed out lost its pending delay when its last observer disconnected. Keep the retry with the watched path so registering the same workspace again uses polling until the scheduled scan.

* fix(server): preserve the scheduled watcher retry deadline

The ordinary recovery delay can exceed the setup-timeout delay when a watcher reports an error before timing out. Retain the scheduled deadline so reopening waits the full interval.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 07:37:02 +00:00
1ff119dc2a feat(app): copy a quote's body with one tap (#10608)
Agents often write drafts as quotes meant to be pasted elsewhere. A plain
quote now has a copy control on web, desktop, Android and iOS. It copies
the quote's body without the `>` markers and with its nested Markdown. A
nested quote, a code block or a Mermaid diagram inside it keeps its own
control. Admonitions get no control.

Web reads the rendered quote at press time, so a streaming quote copies
what it shows, and writes the same two clipboard flavors as selection
copy. A rendered Mermaid diagram copies as the fence it shows, and an
admonition inside a copied quote copies as its `> [!TYPE]` source. Code
blocks and quotes share one copy button with a Copied state and an error
toast when the clipboard refuses the write. On compact layouts the
control is always visible in a band above the quote body. On wide
layouts it shows on hover or focus and the quote keeps a right gutter.

Native code blocks and quotes share one header copy control with the
Lucide Copy glyph. A quote reserves the code block's header band above
its body, so the control never covers text at any font size. Native copy
emits the quote body as written, and a copied fence grows longer than
any fence inside its code.

Supersedes #9429 and #9319. Refs discussion #9303.

Co-authored-by: Pedro Vieira <pedro.vieira@dremio.com>
Co-authored-by: Phieu Dinh <phieu@fiu.one>
2026-11-25 13:36:01 +07:00
Mohamed Boudra 6e6f224e44 Hub login prints a one-click URL, and an uninstalled Muse Code shows as unavailable (#10751)
* fix(cli): print the one-click Hub login URL

`paseo hub login` opened verificationUriComplete in a browser but printed
the bare verificationUri. Over SSH or on a remote host the browser launch
does nothing, so users had to open the bare page and type the code by hand.
Print the URL that carries ?code= and keep the code next to it so the user
can check it matches the Hub approval page.

* fix(providers): report uninstalled plugin providers as unavailable

A fresh host with only Claude Code installed listed Muse Code as an
error ("muse not found on PATH"). The snapshot manager resolves a
provider's catalogue key before it checks availability, and treats any
failure there as an error. For a plugin provider with a command, the key
lookup required a resolved executable and threw when it was missing.

A command that does not resolve has no catalogue identity. Fall back to
the target key so the availability check runs and reports unavailable.

* fix(providers): keep a removed plugin executable off its cached catalogue

The previous fix returned no catalogue key for a missing executable. A
plugin that returns no key asks for a per-workspace catalogue, so after
its executable was removed the next read bound to the catalogue cached
while it was installed and kept reporting ready.

Give a missing executable its own key. Removal now moves the provider to
a fresh catalogue, and its refresh reports unavailable.
2026-11-25 13:30:37 +07:00
Mohamed Boudra 395a5a5f80 Run OpenCode v2 agents with their own MCP servers and env on a shared OpenCode server (#10752)
* refactor(server): share the MCP client connection that providers host

OMP connected MCP servers itself; OpenCode v2 now needs the same client to
host per-session servers. The shared connection also ends Streamable HTTP
sessions explicitly on close, because a stateful server keeps them otherwise.

* fix(opencode): run agent MCP servers and env on shared v2 servers

Agents with MCP servers or a launch environment failed on any OpenCode v2
server Paseo did not start, with "require an isolated server". OpenCode's MCP
configuration is shared by every session in a location, so Paseo answered by
starting a dedicated server, which a reused server cannot do.

Paseo now hosts each session's MCP servers itself and the v2 plugin exposes
their tools only to that session and its descendants, under OpenCode's
`<server>_<tool>` names. The plugin runs OpenCode's permission check before
each call, so preapproved grants still apply; that API exists from OpenCode
2.0.29, and older servers or stale plugins fail at session creation. Launch
env reaches shells through session.environment, which children do not
inherit, so the plugin asks Paseo to adopt each child before its first model
request. No agent gets a dedicated server any more, including on Paseo's own
helper.

A registered service is skipped when the provider env configures the OpenCode
process, so a service.json no longer breaks catalogs and launches for those
setups. An explicit server URL still reports those variables.

Fixes #9669

* fix(opencode): keep user tools, child instructions, and MCP call cleanup on shared servers

- A Paseo MCP tool replaced a same-named tool from the user's own OpenCode
  configuration, and the context hook then removed it from unrelated sessions.
  The plugin now captures that tool when it registers, keeps it for sessions
  without their own Paseo tool, and runs it for them.
- MCP instructions were an instruction entry written when a child was adopted.
  OpenCode loads entries before the context hook runs, so the child's first
  request missed them. The context hook now adds them to every request.
- Structured-only MCP results reached OpenCode with empty content. The bridge
  now adds them as text, as it already does for Paseo tools.
- The bridge listened for the request's `aborted` event, which never fires
  once the body is read, so Stop left the MCP call running. It now aborts when
  the response closes before it finishes.
- Closing an HTTP MCP connection waited on a session DELETE with no deadline.
  It now waits at most two seconds before closing the transport, which aborts
  the DELETE.

* test(server): run daemon OpenCode tests with the bridge the daemon always starts

These tests built the OpenCode v2 client without a bridge, so the client
reported no native Paseo tools and the daemon injected its internal MCP
server instead. OpenCode v2 now hosts agent MCP servers through the bridge
and rejects them without one. The daemon always starts the bridge, so the
tests now do too.

* fix(server): reconnect expired MCP sessions and bound the MCP handshake

- The OpenCode plugin copied a same-named user tool's input schema into the
  shared registration. OpenCode validates arguments against the registration,
  so the agent's own calls failed the user's schema. The registration keeps a
  permissive schema, and the context hook gives each session its own.
- A stateful HTTP MCP server answers 404 after it restarts or expires a
  session, and the SDK kept sending the old session ID. A call that gets 404
  now opens a new session once and retries.
- The SDK times out only the `initialize` request, so a server that never
  answered the `initialized` notification stalled agent creation. The whole
  handshake now has a 10-second deadline.
2026-11-25 13:30:13 +07:00
Mohamed Boudra 12bc84046c Keep iOS chat visible with tall pending cards (#10759)
* fix(app): reveal chat with tall pending cards

The initial scroll can settle inside the footer, where no rows need to be measured. Run the layout readiness check before allowing cached ranges to skip it.

* test(app): cover cached range during initial list placement

Exercise an observed end offset with measured rows in the buffer. Canceling the initial scroll must complete readiness even when the render range is already cached.
2026-11-25 13:24:09 +07:00
paseo-bot[bot]andluke 44d1d6ab29 fix(app): keep long desktop turns virtualized (#8661)
* fix(app): virtualize chat turns that exceed the mounted window

- Desktop web aligns the mounted tail to the current turn, so one long tool run stayed fully mounted and stalled the chat open.
- Cap that rewind at 60 rows for the web virtualizer. A larger minimum still wins, and history paging plus the replica cache still keep a whole turn.

* test(app): read expanded turns across the virtual window

Verify every command remains accessible while scrolling and after older history loads. Requiring all expanded rows in the DOM at once contradicts bounded desktop mounting.

Co-authored-by: luke <luopeihuan@gmail.com>

* Verify older history appears before rechecking turn expansion

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 05:55:20 +00:00
paseo-bot[bot]andOuyang Xingyuan cfcf0dc7d1 fix(server): keep slow direct connections alive during large transfers (#10651)
A direct client sees activity only after a complete WebSocket message arrives. Send large responses in existing transport chunks so the client sees progress while it waits for the full response.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
2026-11-25 04:02:49 +00:00
Mohamed Boudra 0a856ab7fc Surface E2EE relay and privacy posture on homepage and security docs (#10749)
* docs(website): surface E2EE relay and privacy posture on homepage and security docs

Add a quiet trust strip below the homepage desktop hero mockup (EN and zh-CN) so Paseo's no-telemetry, E2EE relay, open-source, and independent posture is visible before the feature chapters.

Update the public security docs, privacy policy, and SECURITY.md to match the current Noise NK relay handshake, replay protection, daemon.relay.requireProtectedSecurity setting, and pairing-link / daemon-password trust model. Sync README.md, README.zh-CN.md, connectivity docs, and the homepage FAQ connectivity link.

* docs(security): clarify two-sided Noise fallback and Unix key permissions

* docs(security): note daemon restart after enabling requireProtectedSecurity
2026-11-25 09:58:26 +07:00
paseo-bot[bot]andMohamed Boudra ad20814ec8 Restore stopped Claude background subagents as canceled after reopening (#9013)
* fix(claude): restore stopped background subagents as canceled

Resolve task-only replay notifications through the parent launch identity so stopped children keep their recorded outcome after reopening. Preserve transcript order across task and tool notifications.

* test(claude): name replay notification fixture options

* fix(claude): restore all children in grouped task notifications

A session-end notification can contain several task IDs. Apply its outcome to each linked child during transcript replay so every stopped child restores as canceled.

* fix(claude): keep quoted notices from changing replayed child status

Claude marks delivered task notifications with an origin. Require that origin for user records and require a standalone notice for queue records so prompts that quote a notice do not override a recorded outcome.

* fix(claude): keep replay task links tied to subagent results

Ignore unrelated tool results when collecting task identities so echoed launch logs cannot overwrite the link used to restore a stopped child.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 08:30:08 +07:00
Maarten den BraberandMohamed Boudra 0688ae83fe fix(server): send Claude MCP servers over stdin to keep tokens out of argv (#10698)
* Keep MCP server headers off the Claude Code command line

The Claude Agent SDK defaults to sending MCP servers in one --mcp-config
flag, so the Paseo MCP server's bearer token (and any user MCP server
headers or env) was readable by every local account through ps or
/proc/<pid>/cmdline. Anyone who read it could call the daemon's agent MCP
endpoint.

Set mcpServersDelivery: "initialize" so the SDK sends the servers over
stdin in the initialize request. The SDK only supports that with the
Claude Code bundled with it (2.1.326) or newer, so an older Claude Code,
or a wrapper command that reports no version, keeps the command-line
delivery and the daemon logs a warning once.

A spawn test feeds Paseo's options to the real SDK and checks that the
token reaches stdin and not the launch arguments.

* fix(server): warn about MCP argv delivery only with configured servers

An empty session used the client's one-time warning before any MCP server headers would be passed to the provider. Warn on the first session that configures a server.

* fix(server): detect MCP delivery support on each provider launch

A running daemon kept selecting command-line delivery after the installed provider gained stdin support. Resolve the installed version when building SDK options for a launch with MCP servers.

* fix(server): probe MCP delivery support in the launch environment

Version-selecting wrappers can run a different binary in the workspace. Use the session working directory and environment when probing the configured command.

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 08:30:01 +07:00
paseo-bot[bot] 311728a780 test(plugins): give npm installation cases separate deadlines (#10726)
Install and reload, reviewed updates, and staging cleanup each run against a fresh service. Their npm subprocesses no longer draw from one test's deadline.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 00:23:46 +00:00
cf1a5a9e73 Stop idle plugin sessions from pinging the daemon (#9363)
* fix(server): stop liveness pings on plugin sessions

Every DaemonClient pings its daemon every 10 s to notice a silently dead socket. A plugin's
session runs over its IPC channel (or an in-process queue for built-in plugins), whose loss is
reported directly, and the daemon already exempts plugin sockets from the application lease those
pings renew. The pings only woke both processes: about 2 wakeups a second in an idle daemon with
nine plugins and the built-ins.

DaemonClient gets a livenessHeartbeat option (default on); the plugin host turns it off.
Explicit verification (ensureConnected({ verify: true })) still pings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): exit a plugin process when its daemon's channel closes

A plugin host only noticed that its daemon worker had died through the liveness ping: about 11 s
later the ping failed and the process exited with code 1. With the pings off it would not notice
at all and kept running as an orphan.

The plugin process now exits as soon as the IPC channel closes without the plugin closing it
itself. A normal shutdown still closes the channel from the plugin side and lets work in flight
(a provider connection that resolves late) finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 15:51:30 +00:00
Mohamed BoudraandTaras Kornichuk e06bfbb94c Redesign host picker with configurable auto-detected icons, connection type, and latency (#10702)
Supersedes #5787.

- Add best-effort daemon hardware detection (macOS ioreg/sysctl, Linux containers, WSL, device-tree boards, cloud/VM DMI, SMBIOS chassis) exposed as optional `machineKind` on `server_info` and `/api/status`.
- Add configurable per-host icons in Host Settings -> Appearance (`Auto` plus 9 icons across all 9 locales), keeping `icon` omitted while untouched for rollback compatibility and preserving unknown future icons on disk.
- Redesign `HostPicker` and `HostChooserModal` with resolved host icons, connection type (`Local`, `Tailscale`, `Relay`, `SSH`, `Direct`, `Via`) + endpoint, on-demand round-trip latency, aligned leading and content rails, and full keyboard navigation.
- Update the website host mockup to match.

Co-authored-by: Taras Kornichuk <dread9ko@gmail.com>
2026-11-24 21:52:39 +07:00
paseo-bot[bot] 7bcd598f09 test(terminal): speed up history setup for pressure recovery (#10683)
Windows timed out while the fixture printed 12,050 rows before signaling readiness. Batch the initial writes and keep the live burst and replay assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 12:01:34 +00:00
Mohamed Boudra c626bf3707 Skip worktree teardown commands for unapproved cross-repository checkouts (#10694)
* fix(server): skip teardown commands when archiving unapproved checkouts

`archiveByScope` previously treated `assertWorkspaceAutomationAllowed` as optional and did not skip `runWorktreeTeardownCommands` when `untrustedBacking` was already true or when archiving an unrecorded worktree directory. Four callers (`CreateAgentLifecycleDispatch`, `archiveIfSafe`, `paseo-tools` `archive_workspace`, and `handlePaseoWorktreeArchiveRequest`) also omitted `assertWorkspaceAutomationAllowed`, letting `paseo.json` teardown commands run during failed agent creation cleanup, first-turn auto-archive, auto-archive on merge, MCP workspace archive, and worktree archive RPCs.

Make `assertWorkspaceAutomationAllowed` and `isCheckoutUntrusted` required on `ArchiveDependencies`, skip teardown whenever the backing checkout is untrusted, any workspace on the checkout is blocked, or no active workspace record exists, and wire the guard through all archive callers.

* fix(server): scope archive teardown check to active checkout workspaces

`isCheckoutUntrusted` scans all workspace records by path, including previously archived records, so gating teardown on it suppressed `paseo.json` teardown for a fresh approved worktree that reused a previously archived unapproved slug path.

Keep teardown approval scoped to the active workspaces sharing the backing checkout at archive start (the records being archived plus active siblings), drop the null-workspace fallback target for unrecorded worktree-scope archives so they never run teardown or flip `untrustedBacking`, and verify caller wiring reaches `assertWorkspaceAutomationAllowed` directly.

* fix(server): inherit untrustedSource when unarchiving onto an active unapproved checkout

Unarchiving a previously approved workspace onto an existing directory that currently holds an active unapproved checkout left the restored workspace without `untrustedSource`. If the unapproved sibling was archived first, the directory remained on disk and archiving the restored workspace could run teardown commands.

Inherit `untrustedSource` from active workspaces sharing the checkout root in `ensureWorkspaceRecordUnarchived`, while ignoring already-archived historical records so restoring an approved checkout onto a reused path stays approved.

* fix(server): bind automation approval state to checkout worktree metadata

Keeping `untrustedSource` only on workspace records meant a retained unapproved worktree directory could lose its teardown block if its last unapproved workspace was archived and an older approved workspace was unarchived onto that path, while scanning archived records by path blocked fresh worktrees that reused a deleted slug.

Persist `untrustedSource` on the checkout itself in `paseo/worktree.json` when creating or restoring an unapproved worktree, clear it in `clearWorkspaceAutomationBlock` when setup is approved, and read it in both `workspace-archive-service` and `workspace-provisioning-service`. Deleting the worktree removes its metadata automatically, so fresh worktrees reusing the path start clean while retained checkouts keep their block across workspace archives and restores.

* fix(server): backfill worktree metadata when archiving retained unapproved checkouts

Unapproved checkouts created before `paseo/worktree.json` stored `untrustedSource` carry their block only in the workspace record. If archive keeps the directory on disk (such as a retained sibling or nested worktree), backfilling `untrustedSource` into `paseo/worktree.json` before removal ensures the retained checkout keeps its block even after its unapproved workspace record is archived.

* fix(server): never propagate archived untrustedSource onto fresh checkouts

Both archive metadata backfill and directory workspace creation previously consulted already-archived records matching a path, allowing an old archived unapproved record to copy `untrustedSource` onto a fresh approved worktree that reused the same slug path.

Ignore `untrustedSource` on already-archived records during archive target resolution and metadata backfill (only backfill when active workspaces are being archived), and share one `resolveCheckoutUntrustedSource` rule across `createWorkspaceForDirectory` and `ensureWorkspaceRecordUnarchived` that checks `paseo/worktree.json` first and falls back only to active workspaces.

* fix(server): align unarchived workspace approval state with the live checkout

Unarchiving an old unapproved workspace onto a path already owned by an active approved checkout kept the old record's stale `untrustedSource`, causing a later re-archive of that workspace to backfill the block onto the fresh checkout's metadata.

Align `ensureWorkspaceRecordUnarchived` symmetrically with the live checkout: adopt `untrustedSource` from `paseo/worktree.json` or active workspaces on the checkout when present, and drop stale `untrustedSource` when live active workspaces own an approved checkout at that path.

* fix(server): preserve block when opening a pre-upgrade retained checkout

Opening a pre-upgrade retained checkout directory whose last unapproved workspace was already archived before this change has no active workspace on the path and no `untrustedSource` in `paseo/worktree.json`.

In `resolveCheckoutUntrustedSource`, prefer `paseo/worktree.json`, then active workspaces on the checkout when any exist (so a fresh approved worktree at a reused path stays approved), and only when zero active workspaces exist on the directory fall back to the most recently archived record for that path.

* fix(server): share one checkout approval lookup across open and unarchive

* fix(server): resolve checkout approval state only from metadata and active workspaces

* fix(server): keep archive read-only on worktree approval metadata

* fix(server): serialize setup approval with archive checkout lock and backfill retained metadata

* fix(server): fail setup approval before clearing records when worktree metadata write fails
2026-11-24 17:46:23 +07:00
Mohamed Boudra 8b2e14f3d2 Run resolved forge CLI executables directly (#10685)
* fix(server): run resolved forge CLI executables directly

The GitHub, GitLab, and Gitea adapters resolved gh, glab, and tea with findExecutable, then discarded the resolved path and spawned the bare command name. On Windows, spawning an extensionless bare name routes through cmd.exe, which resolves commands against cwd first, expands %VAR% references, and truncates multiline arguments such as gh api graphql queries.

Forward the resolved executablePath from each forge adapter and auth probe into the shared runner, resolve bare binary names inside createForgeCliRunner when omitted, and restrict bare-name PATH discovery in findExecutable to absolute PATH directories.

* fix(server): re-resolve cached forge CLI paths if the binary disappears

Cached CLI path resolvers now support targeted invalidation, and forge adapters plus createForgeCliRunner invalidate and retry once when a previously resolved executable disappears at launch time (ENOENT, or a missing Windows batch launcher). This preserves cached lookups on normal runs while recovering automatically when a user uninstalls or relocates an installation while another copy remains on PATH.

* fix(server): refresh cached forge CLI path on any unlaunchable spawn error

Match executable-resolution's unlaunchable spawn error set (ENOENT, EACCES, ENOEXEC, UNKNOWN) when deciding whether to invalidate and re-resolve a cached forge CLI path, so losing execute permission falls back to another working copy on PATH.
2026-11-24 14:37:28 +07:00
Mohamed Boudra da74f7de1f Offer Push and Pull for a branch whose remote is not named origin (#10679)
* fix(git): offer Push and Pull for a branch whose remote is not origin

A checkout whose only remote has another name, with main tracking that
remote's main, got no Push, Pull or Pull and push. The app gated all three
on hasRemote, which is true only when origin is configured, and the
daemon's pull refused to run without origin.

Neither action needs origin. The daemon now reports where each one goes for
the current branch (pullRemote, pushRemote) and the app offers the actions
from those. One resolver picks the push destination for both the status and
the push, so the offer and the push cannot disagree.

Without origin, Push follows the upstream only when the upstream branch has
the branch's own name and git pushes the branch to that remote. A branch
such as feature tracking upstream/main can be pulled and is not pushed.
With origin, every push goes where it went before.

firstPushRemote stays on the wire for apps that predate pushRemote.

* fix(git): follow Git's own push destination when origin is missing

Without origin, Push compared the upstream's remote with the remote Git
pushes the branch to. That missed a push refspec: with
remote.<upstream>.push set, plain `git push` updates another branch, and
Paseo still updated the upstream. A regular checkout with a push refspec on
branch.<name>.pushRemote was pushed there and stayed ahead of its upstream.

Push now asks Git where `git push` sends the branch (%(push)) and follows
the upstream only when that is the upstream. This also covers
push.default. A Paseo worktree keeps the push refspec Paseo configures for
a PR checkout.

Pull no longer requires a configured upstream before it runs. Git decides,
so a branch with no upstream in a single-branch clone pulls again.

* fix(git): compare the push remote by name when origin is missing

Push compared Git's push destination with the upstream as remote-tracking
refs. Two remotes whose fetch refspecs map onto the same tracking namespace
give the same ref for different repositories, so a branch Git pushes to one
remote was sent to the other. The remote Git pushes to is now compared by
name as well.

* fix(git): leave a matching-mode push to the user when origin is missing

Under push.default=matching, git push sends a branch only when the remote still has it. The checkout's remote-tracking ref can outlive a branch deleted on the remote, so the daemon cannot tell from local metadata that the push would go to the upstream, and its explicit push would recreate the branch. Without origin, Push is now refused in that mode.
2026-11-24 14:37:23 +07:00
Mohamed Boudra 767c1efa03 Show OpenCode Go usage from the login store the installed OpenCode uses (#10678)
* fix(usage): read OpenCode Go logins from the store the installed OpenCode uses

The source treated a `credential` table in opencode.db as proof of OpenCode 2
and then ignored auth.json. OpenCode 1.17.5 and newer creates that table too
and leaves it empty, and OpenCode 2 fills it once when it opens the same data
directory. In both cases the Go key in auth.json was dropped and the source
disappeared.

The source no longer reads OpenCode's database. It asks the installed OpenCode
for its version. OpenCode 2 lists its own logins with
`opencode auth export --standalone`, with its own choice of the active one per
integration. OpenCode 1 keeps logins in auth.json. A failed OpenCode 2 listing
throws, so it never reads as "no login". An auth.json key is not used when
OpenCode 2 is installed, because OpenCode 2 never reads that file after its
one-time import.

`--standalone` matters: without it the command starts OpenCode's background
service and leaves it running.

* chore(usage): request a review of the resolved threads

* fix(usage): keep the OpenCode Go card when the version check is cut off

A version check that reached its timeout was read as OpenCode 1. Discovery then
read auth.json, and a login that only OpenCode 2 has was reported as removed.
A check that is cut off does not show which store OpenCode uses, so discovery
now fails and the daemon keeps the account it already knew.

A missing OpenCode, or one that exits with an error, still reads auth.json:
that file is the only store when OpenCode is not installed.

* fix(usage): recognize OpenCode 2 when the daemon's environment forces colors

With FORCE_COLOR set, OpenCode 2 writes its version with ANSI codes even into
a pipe. The version did not parse, the source took OpenCode for version 1, and
a login that only OpenCode 2 has disappeared. The source now runs OpenCode with
NO_COLOR, which gives plain output for the version and the login listing.

* fix(usage): read the auth.json Go key when OpenCode 2 has no Go login

OpenCode 2 imports auth.json only once. A Go key that is saved in the file
after that import is in no other place, so the card was still missing for
the state in #10659 when the installed OpenCode is 2.x: the credential
listing holds only an unrelated login and the Go key is in auth.json.

The order is now: a login OpenCode 2 can serve Go with wins, so a stale key
in the file never replaces it. Without one, the auth.json key is used. A
failed listing still throws, because it does not show that OpenCode 2 has
no Go login.

* fix(usage): read the auth.json Go key behind an OpenCode 2 login without Go

The auth.json fallback applied only when OpenCode 2 listed neither an
`opencode` nor an `opencode-go` login. With an `opencode` login whose
Console workspace has no Go, the card reported "No active OpenCode Go
subscription" while a working Go key was in auth.json.

The file's key now stands in for a missing `opencode-go` login. The
existing order then decides: the `opencode` login is asked first, and the
Go key is asked only when the Console refuses that login. A temporary
failure still keeps the card on the `opencode` login.
2026-11-24 14:37:18 +07: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
280 changed files with 15625 additions and 2729 deletions
-3
View File
@@ -422,7 +422,6 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/headers/screen-header.tsx",
"packages/app/src/components/host-status-dot.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/icons/paseo-logo.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/plan-card.tsx",
@@ -552,9 +551,7 @@
"packages/app/src/components/download-toast.tsx",
"packages/app/src/components/file-explorer-pane.tsx",
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
+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 -1
View File
@@ -48,7 +48,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
- **Multi-provider:** Claude Code, Codex, Copilot, OpenCode, Pi, Antigravity, and Muse Code through the same interface. Pick the right model for each job.
- **Voice control:** Dictate tasks or talk through problems in voice mode. Hands-free when you need it.
- **Cross-device:** iOS, Android, desktop, web, and CLI. Start work at your desk, check in from your phone, script it from the terminal.
- **Privacy-first:** Paseo doesn't have any telemetry, tracking, or forced log-ins.
- **Privacy-first:** No telemetry, tracking, or forced login. Remote access uses an optional end-to-end encrypted relay.
[Run parallel tasks in Paseo](https://paseo.sh/docs/parallel-development): start agents in separate worktrees, review their diffs, run each app, and check it in the built-in browser.
+3 -3
View File
@@ -51,7 +51,7 @@
- **多提供商:** 通过同一个界面使用 Claude Code、Codex、Copilot、OpenCode 和 Pi。为每个任务选择合适的模型。
- **语音控制:** 在语音模式下口述任务或讨论问题。需要免手操作时很方便。
- **跨设备:** 支持 iOS、Android、桌面端、Web 和 CLI。在桌前开始工作,用手机查看进度,也可以从终端脚本化操作。
- **隐私优先:** Paseo 没有遥测、追踪,也不会强制登录。
- **隐私优先**:无遥测、无追踪、不强制登录。远程访问可使用可选的端到端加密中继。
## 赞助商
@@ -93,7 +93,7 @@ npm install -g @getpaseo/cli
paseo
```
终端中会显示一个二维码。你可以从任意客户端连接。这个方式适合服务器和远程机器。
Paseo 启动后会询问是否启用端到端加密中继以进行设备配对。如果拒绝,可以通过 TCP、Tailscale 或其他 VPN 直接连接。这个方式适合服务器和远程机器。
完整安装和配置见:
@@ -140,7 +140,7 @@ Monorepo 包结构速览:
- `packages/app`:Expo 客户端(iOS、Android、Web)
- `packages/cli`:用于 daemon 和 agent 工作流的 `paseo` CLI
- `packages/desktop`:Electron 桌面 app
- `packages/relay`:用于远程连接的 relay 包
- `packages/relay`:daemon 和客户端使用的中继传输与端到端加密包
- `packages/website`:营销站点和文档(`paseo.sh`)
常用命令:
+1 -1
View File
@@ -33,7 +33,7 @@ The relay sees only: IP addresses, timing, message sizes, session IDs, and the p
The daemon requires a valid cryptographic handshake before processing any commands. A compromised relay cannot:
- **Impersonate the daemon to your phone** — Without the daemon's secret key, it cannot derive the shared key, so any traffic it injects fails authenticated decryption on the phone
- **Send commands as you** — The daemon only accepts traffic that decrypts and authenticates under a shared key derived with its own secret key. The phone's keypair is ephemeral per connection, so there is no persistent phone-side secret to steal; protection comes from the daemon's secret key never leaving the daemon.
- **Open a session without pairing** — The daemon's public key is carried only in the pairing offer and is never sent to the relay. With a daemon password configured, the daemon also rejects any relay client that does not send the right password inside the encrypted channel.
- **Read your traffic** — After the handshake every message is encrypted: ChaCha20-Poly1305 in protected mode, XSalsa20-Poly1305 (NaCl box) in legacy mode
- **Forge messages** — Both constructions are authenticated encryption; a tampered message is rejected in either mode
- **Replay old messages** — In protected mode the daemon contributes a fresh ephemeral key to every session and every record carries a strictly increasing counter, so a recorded session cannot be replayed into a new one and a duplicated, reordered, or reflected record closes the session. Legacy mode has neither property: it uses random nonces, and a daemon that still admits legacy clients accepts a recorded legacy transcript (hello, credentials, commands) as a new session. Set `daemon.relay.requireProtectedSecurity: true` to refuse legacy clients once every client you use has updated.
+4 -34
View File
@@ -133,7 +133,9 @@ A configured URL takes precedence even when unreachable; Paseo reports the conne
An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package.
OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service.
Agent MCP servers and per-agent environment work on a reused server with OpenCode 2.0.29 or newer. Paseo connects each agent's MCP servers itself and shows their tools only to that agent and its subagents. Other agents in the same directory and your own OpenCode sessions do not see them. The agent's environment applies to its shell commands, its subagents, and its stdio MCP servers.
The provider `env` configures the OpenCode process. When it sets variables other than the connection variables above and `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, or `OPENCODE_CONFIG_DIR`, Paseo ignores a registered service and starts its own helper. With an explicit URL, Paseo reports those variables as an error.
---
@@ -514,7 +516,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 +629,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 +829,6 @@ A config.json with multiple custom providers:
"extends": "acp",
"label": "Google Gemini",
"command": ["gemini", "--acp"]
},
"hermes": {
"extends": "acp",
"label": "Hermes",
"command": ["hermes", "acp"]
}
}
}
+6 -2
View File
@@ -43,7 +43,11 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
@@ -55,4 +59,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
## Verification
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
+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 -1
View File
@@ -171,7 +171,7 @@ V2.0.4 also removed the activation endpoint that gated a cold location, and a co
Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. V2 discovers definitions from each bound session's catalog: plugin-contributed tools can be absent from the global manifest, and an allowlist cannot register a missing definition. Registration is location-wide, so session filtering and caller-scoped execution must remain in place. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool.
An agent with custom environment variables or user-configured MCP servers gets a dedicated OpenCode server. V2 supports session environment, but its MCP configuration remains location-scoped, so separate servers still prevent one agent from changing another agent's MCP setup. Configure custom MCP with `mcp.add`; do not follow it with `mcp.connect`, which only toggles config-backed servers.
No v2 agent gets a dedicated OpenCode server, because a reused server cannot provide one. OpenCode's MCP configuration is location-scoped, so Paseo never calls `mcp.add` for an agent. The daemon connects the agent's MCP servers itself (`v2/session-mcp.ts`), and the v2 plugin exposes their tools under OpenCode's native `<server>_<tool>` names. Each name registers once per location. The plugin's `context` hook gives each session its own definition and removes the tool from other sessions. If the user's own OpenCode configuration registered a tool with the same name first, other sessions keep that tool and its execution. Execution routes to the calling session's root binding. The hook also adds the servers' instructions to each request. OpenCode loads instruction entries before the hook runs, so an entry written when a child is adopted would miss the child's first request. The plugin calls OpenCode's `permission.assert` before each call, so `toolPolicy.preapproved` grants still apply. That API exists from OpenCode 2.0.29. Bind reports `features.mcpTools`, so an older server or a stale plugin fails the session at creation instead of hiding its tools. Per-agent `launch.env` reaches shells through `session.environment`, which child sessions do not inherit. The plugin asks the daemon to adopt each descendant in its first `context` hook, before its first model request.
OpenCode owns user message IDs. Do not pass Paseo-generated IDs to OpenCode prompt APIs; let OpenCode create `msg*` IDs and record the user timeline item from the `message.updated` event.
@@ -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": [
@@ -757,6 +757,161 @@ test("pasting an assistant selection preserves literal underscores and authored
}
});
const QUOTE_BODY = [
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
"",
"> Nested reply.",
"",
"```ts",
"const quoted = 1;",
"```",
"",
"```mermaid",
"flowchart LR",
" Start --> Done",
"```",
"",
"Thanks!",
].join("\n");
const QUOTE_MARKDOWN = [
"Text before the quote.",
"",
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
"",
"> [!NOTE]",
"> Heads up before you paste.",
"",
"Text after the quote.",
].join("\n");
function assistantQuote(page: Page, index: number): Locator {
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
}
/** A quote's own control is its first, ahead of any nested quote's. */
function quoteCopyControl(quote: Locator): Locator {
return quote.getByRole("button", { name: "Copy quote" }).first();
}
async function copyQuote(quote: Locator): Promise<void> {
await quote.hover();
await quoteCopyControl(quote).click();
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
}
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
await page.evaluate(() => {
const fields = document.createElement("div");
fields.style.cssText = "position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
const plainText = document.createElement("textarea");
plainText.setAttribute("aria-label", "Plain text paste");
const richText = document.createElement("div");
richText.contentEditable = "true";
richText.setAttribute("role", "textbox");
richText.setAttribute("aria-label", "Rich text paste");
fields.append(plainText, richText);
document.body.append(fields);
});
const plain = page.getByRole("textbox", { name: "Plain text paste" });
await plain.focus();
await page.keyboard.press("ControlOrMeta+v");
const rich = page.getByRole("textbox", { name: "Rich text paste" });
await rich.focus();
await page.keyboard.press("ControlOrMeta+v");
return { plain, rich };
}
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "assistant-quote-copy-",
title: "Assistant quote copy",
initialPrompt: "Render the quote fixture.",
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
});
try {
await allowRichClipboard(context);
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const quote = assistantQuote(page, 0);
const nested = assistantQuote(page, 1);
await expect(quote).toContainText("Thanks!");
await test.step("an admonition has no copy control", async () => {
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
await expect(
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
).toHaveCount(2);
});
await test.step("the control appears on hover or keyboard focus", async () => {
const control = quoteCopyControl(quote);
await expect(control).toHaveCSS("opacity", "0");
await quote.hover();
await expect(control).toHaveCSS("opacity", "1");
await page.mouse.move(0, 0);
await expect(control).toHaveCSS("opacity", "0");
await control.focus();
await expect(control).toHaveCSS("opacity", "1");
await control.blur();
});
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
await copyQuote(quote);
const copied = await readRichClipboard(page);
expect(copied.plainText).toBe(QUOTE_BODY);
expect(copied.html).toContain("<strong>ship it</strong>");
expect(copied.html).toContain("<blockquote>");
});
await test.step("the copy pastes as Markdown and as rich text", async () => {
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
await expect(plain).toHaveValue(QUOTE_BODY);
await expect(rich.locator("strong")).toHaveText("ship it");
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
"href",
"https://example.com/notes",
);
await expect(rich).not.toContainText("Text before the quote.");
});
await test.step("a nested quote copies only itself", async () => {
await copyQuote(nested);
await expect
.poll(async () => (await readRichClipboard(page)).plainText)
.toBe("Nested reply.");
});
await test.step("a code block in the quote keeps its own copy", async () => {
const code = quote.getByText("const quoted = 1;", { exact: true });
await code.hover();
await quote.getByRole("button", { name: "Copy code" }).first().click();
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
});
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
await page.mouse.move(0, 0);
await page.setViewportSize({ width: 390, height: 844 });
const control = quoteCopyControl(quote);
await expect(control).toHaveCSS("opacity", "1");
const controlBox = await control.boundingBox();
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
expect(controlBox && firstLine).toBeTruthy();
// The text starts below the control instead of wrapping short of it.
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
});
} finally {
await agent.cleanup();
}
});
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
context,
page,
@@ -1,4 +1,5 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { type Locator, type Page } from "@playwright/test";
@@ -471,6 +472,83 @@ 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 pushes and pulls a branch whose only remote is not named origin", async ({
page,
}) => {
const workspace = await createWorkspaceWithRemote((repoPath) => {
execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath });
// git pull stops on a branch that is both ahead and behind until it is told how to combine them.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath });
});
await openWorkspaceChangesSurface(page, workspace);
const primary = page.getByTestId("changes-primary-cta");
await test.step("a branch that is ahead offers Push and the push updates the remote", async () => {
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
commitAllWithGit(workspace.repoPath, "Local work");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]");
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toContain("Local work");
await expectNoGitActionLeft(page);
});
await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => {
pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(localBranchSubjects(workspace)).toEqual(
expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]),
);
await expectNoGitActionLeft(page);
});
await test.step("a branch that is ahead and behind pulls and then pushes", async () => {
await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n");
commitAllWithGit(workspace.repoPath, "More local work");
pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await page.getByTestId("changes-primary-cta-caret").click();
await page.getByTestId("changes-menu-pull-and-push").click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toEqual(
expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]),
);
await expectNoGitActionLeft(page);
});
});
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
page,
}, testInfo) => {
@@ -2122,6 +2200,141 @@ 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;
}
// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]".
function trackingStatus(workspace: RemoteWorkspace): string {
const status = execFileSync("git", ["status", "-sb"], {
cwd: workspace.repoPath,
encoding: "utf8",
});
return status.split("\n")[0] ?? "";
}
// Neither ahead nor behind, which a push reaches only after the remote accepted it.
async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void> {
await expect
.poll(() => trackingStatus(workspace), { timeout: 30_000 })
.toMatch(/^## [^ ]+\.\.\.[^ ]+$/);
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
function localBranchSubjects(workspace: RemoteWorkspace): string[] {
return commitSubjects(workspace.repoPath, "HEAD");
}
function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] {
return commitSubjects(workspace.remotePath, branch);
}
function commitSubjects(repoPath: string, revision: string): string[] {
const log = execFileSync("git", ["log", "--format=%s", revision], {
cwd: repoPath,
encoding: "utf8",
});
return log.trim().split("\n");
}
// Paseo fetches only origin in the background, so the checkout learns about another remote's
// commits when the user fetches it.
function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void {
execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath });
}
// Lands commits on the remote's main from a second clone, as a teammate's push does.
function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void {
const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-"));
try {
execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]);
for (const subject of subjects) {
execFileSync(
"git",
[
"-c",
"user.name=Teammate",
"-c",
"user.email=teammate@paseo.test",
"-c",
"commit.gpgsign=false",
"commit",
"--quiet",
"--allow-empty",
"-m",
subject,
],
{ cwd: clonePath },
);
}
execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath });
} finally {
rmSync(clonePath, { recursive: true, force: true });
}
}
// 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" }],
@@ -4,6 +4,7 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -115,12 +116,21 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and apply it to the sidebar badge", async () => {
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
await expect(hostRow).toContainText("Direct");
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
await expect(hostRow).not.toContainText(/agents?/i);
await page.keyboard.press("Escape");
});
await test.step("keep the icon-only preference through reload", async () => {
@@ -145,3 +155,30 @@ test("customizes a host badge and preserves its appearance after reload", async
});
});
});
base(
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
async ({ page }) => {
await gotoAppShell(page);
const trigger = page.getByTestId("sidebar-hosts-trigger");
await expect(trigger).toBeVisible();
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
await trigger.click();
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
await expect(addHostButton).toBeVisible();
await addHostButton.focus();
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
await page.keyboard.press("Escape");
await expect(addConnectionDialog).toBeHidden();
// ArrowDown + Enter must also reach Add host from the host list.
await trigger.click();
await expect(addHostButton).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
},
);
@@ -1,7 +1,6 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
chooseProjectWithKeyboard,
connectNewWorkspaceDaemonClient,
expectNewWorkspaceControlsEnabled,
expectNewWorkspaceProjectSelected,
@@ -177,33 +176,6 @@ test.describe("New workspace entry points", () => {
}
});
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
page,
}) => {
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
const composer = page.getByRole("textbox", { name: "Message agent..." });
await page.getByTestId("new-workspace-project-picker-trigger").click();
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
await expect(composer).toBeFocused();
await page.keyboard.press("Control+N");
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
await expect(composer).toBeFocused();
} finally {
await projectA.cleanup();
await projectB.cleanup();
}
});
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
page,
}) => {
@@ -2,7 +2,6 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import {
chooseProjectWithKeyboard,
expectNewWorkspaceDraft,
fillNewWorkspaceDraft,
openNewWorkspaceComposer,
@@ -110,27 +109,6 @@ test.describe("New workspace: launching a terminal", () => {
});
});
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
page,
}) => {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectLaunchOption(page, BARE_PROFILE.id);
await expect(terminalPromptInput(page)).toHaveCount(0);
// The read-only command preview has nothing to type into, so the picker
// hands focus back to the field that opened it.
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
await projectTrigger.focus();
await page.keyboard.press("Enter");
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
await expect(projectTrigger).toBeFocused();
});
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
page,
}) => {
@@ -65,8 +65,7 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
sidebarHostRowButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -566,7 +564,7 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await page.getByTestId("sidebar-hosts-trigger").click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
+39 -4
View File
@@ -1,9 +1,11 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import path from "node:path";
import {
expectTimelinePromptVisible,
holdOlderHistoryPages,
scrollTimelineRowIntoView,
userScrollsTimelineToHistoryStart,
waitForTimelineGeometryToSettle,
} from "../support/helpers/timeline-pagination";
import { getActiveTabTestId } from "../support/helpers/launcher";
import type { Page, Locator } from "@playwright/test";
@@ -491,6 +493,39 @@ async function seedWholeTurnHistory() {
return agent;
}
/** Read every command across the scroll window, without requiring offscreen rows to mount. */
async function expectExpandedCommandsReadable(page: Page, count: number) {
const timeline = page.getByTestId("agent-chat-scroll");
const commands = new Set<number>();
await timeline.hover();
await waitForTimelineGeometryToSettle(page);
for (let step = 0; step < count && commands.size < count; step += 1) {
const labels = await timeline
.getByRole("button", { name: /echo stress-\d+/ })
.allTextContents();
for (const label of labels) {
const command = /echo stress-(\d+)/.exec(label);
if (command) commands.add(Number(command[1]));
}
if (commands.size < count) {
await page.mouse.wheel(0, 300);
await waitForTimelineGeometryToSettle(page);
}
}
expect([...commands].sort((a, b) => a - b)).toEqual(
Array.from({ length: count }, (_, index) => index),
);
}
async function returnToExpandedSummary(page: Page, summary: Locator) {
await page.getByTestId("agent-chat-scroll").hover();
for (let step = 0; step < 120 && !(await summary.isVisible()); step += 1) {
await page.mouse.wheel(0, -300);
await waitForTimelineGeometryToSettle(page);
}
await scrollTimelineRowIntoView(page, summary);
}
async function expectInitialFillIsConcealed(page: Page) {
await expect(page.getByTestId("agent-initial-fill")).toBeVisible();
await expect(page.getByTestId("agent-chat-scroll")).toHaveCSS("opacity", "0");
@@ -564,14 +599,14 @@ test("loads complete long turns and preserves expansion while revealing older hi
).toBeVisible();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
await latest.click();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
await expectExpandedCommandsReadable(page, 120);
await userScrollsTimelineToHistoryStart(page);
await history.expectRequestedPages(3);
history.releasePage(3);
await page.getByTestId("scroll-to-bottom-button").click();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(120);
await expectTimelinePromptVisible(page, "Short 4: emit 1 coalesced agent stream updates");
await expectExpandedCommandsReadable(page, 120);
history.expectNoRepeatedEntries();
await scrollTimelineRowIntoView(page, latest);
await returnToExpandedSummary(page, latest);
await latest.click();
await expect.poll(() => rowsBetweenLatestSummaryAndReply(page)).toBe(0);
} finally {
+10 -1
View File
@@ -132,7 +132,10 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -195,6 +198,12 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
}
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
await page.getByTestId("host-appearance-icon").click();
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
}
export async function chooseHostBadgeDisplay(
page: Page,
option: "Name" | "Icon only" | "Hidden",
@@ -243,14 +243,6 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
await expect(searchInput).toBeFocused();
}
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
const searchInput = page.getByPlaceholder("Search projects");
await expect(searchInput).toBeFocused({ timeout: 30_000 });
await page.keyboard.type(projectName);
await page.keyboard.press("Enter");
await expect(searchInput).toBeHidden({ timeout: 10_000 });
}
export async function expectNewWorkspaceProjectSelected(
page: Page,
projectDisplayName: string,
+4 -14
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,20 +32,10 @@ export async function bindCommandCenterToEnter(page: Page) {
});
}
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
const gear = sidebarHostSettingsButton(page);
await expect(gear).toBeVisible();
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
true,
);
}
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
const host = sidebarHostRowButton(page);
await expect(host).toBeVisible();
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.3",
"version": "0.17.4",
"private": true,
"main": "index.ts",
"scripts": {
@@ -40,7 +40,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -26,14 +26,22 @@ export function getMountedRecentStreamItems(): number {
export function findMountedWindowStart(input: {
items: StreamItem[];
minMountedCount: number;
// Caps how far turn alignment may rewind. History paging and the replica
// cache omit it and still keep a whole turn.
maxMountedCount?: number;
}): number {
const { items, minMountedCount } = input;
if (items.length <= minMountedCount) {
return 0;
}
const mountedLimit =
input.maxMountedCount === undefined
? items.length
: Math.max(minMountedCount, input.maxMountedCount);
const earliestStart = Math.max(0, items.length - mountedLimit);
let startIndex = Math.max(items.length - minMountedCount, 0);
while (startIndex > 0 && continuesTurn(items[startIndex - 1], items[startIndex])) {
while (startIndex > earliestStart && continuesTurn(items[startIndex - 1], items[startIndex])) {
startIndex -= 1;
}
return startIndex;
@@ -2,7 +2,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import React, { act, useSyncExternalStore } from "react";
import { createRoot, type Root } from "react-dom/client";
import { View } from "react-native";
import { afterEach, beforeEach, expect, it } from "vitest";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { disclosureAnchor } from "./native-disclosure-hold";
// The native chat timeline runs on the patched LegendList (patches/@legendapp+list+3.7.1.patch).
@@ -90,7 +90,7 @@ function keyExtractor(item: Row) {
return item.id;
}
function estimateRowSize(item: Row) {
function rowHeight(item: Row) {
return item.height;
}
@@ -289,7 +289,7 @@ it("expands the draw distance of a placed end-anchored list without moving its b
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
recycleItems={false}
getEstimatedItemSize={estimateRowSize}
getEstimatedItemSize={rowHeight}
drawDistance={drawDistance}
alignItemsAtEnd
initialScrollAtEnd
@@ -315,3 +315,96 @@ it("expands the draw distance of a placed end-anchored list without moving its b
expect(expanded?.scroll).toBe(initial?.scroll);
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
});
it.each([2, 4])("reveals an end-anchored list with a footer %sx the viewport", async (scale) => {
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
id: `row-${index}`,
height: 40,
}));
const footerHeight = VIEWPORT_HEIGHT * scale;
const listRef = React.createRef<LegendListRef>();
const footer = React.createElement(View, { style: rowStyle(footerHeight) });
const onReady = vi.fn();
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
getEstimatedItemSize={rowHeight}
drawDistance={50}
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
ListFooterComponent={footer}
onReady={onReady}
style={LIST_STYLE}
/>,
);
});
await expect
.poll(async () => {
await wait(16);
return onReady.mock.calls.length;
})
.toBe(1);
expect(listRef.current?.getState().scroll).toBe(
rows.length * 40 + footerHeight - VIEWPORT_HEIGHT,
);
});
const END_PADDED_CONTENT_STYLE = { paddingBottom: 125 };
it("reveals buffered rows when the scroll view takes over initial end positioning", () => {
const rowSize = 40;
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
id: `row-${index}`,
height: rowSize,
}));
const listRef = React.createRef<LegendListRef>();
const onReady = vi.fn();
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
getFixedItemSize={rowHeight}
drawDistance={120}
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
contentContainerStyle={END_PADDED_CONTENT_STYLE}
onReady={onReady}
style={LIST_STYLE}
/>,
);
});
const list = listRef.current;
if (!list) throw new Error("The list did not mount");
const scroller: unknown = list.getScrollableNode();
if (!(scroller instanceof HTMLElement)) throw new Error("The list has no scroll element");
const endOffset =
rows.length * rowSize + END_PADDED_CONTENT_STYLE.paddingBottom - VIEWPORT_HEIGHT;
act(() => {
// Deliver the scroll view's observed end offset before canceling the list's initial scroll.
// Keep both calls in one task so a later layout pass cannot complete the reveal for them.
scroller.scrollTop = endOffset;
scroller.dispatchEvent(new Event("scroll"));
expect(onReady).not.toHaveBeenCalled();
list.cancelScroll();
});
const state = list.getState();
expect(state.scroll).toBe(endOffset);
expect(state.start).toBeNull();
expect(state.endBuffered).toBe(rows.length - 1);
expect(state.sizeAtIndex(rows.length - 1)).toBe(rowSize);
expect(onReady).toHaveBeenCalledTimes(1);
});
@@ -3,6 +3,7 @@ import type { StreamItem } from "@/types/stream";
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
import { findMountedWindowStart } from "./history-window";
import { buildAgentStreamRenderModel } from "./model";
import { MAX_MOUNTED_WEB_WINDOW_ITEMS } from "./web-virtualization";
function createTimestamp(seed: number): Date {
return new Date(`2026-01-01T00:00:${seed.toString().padStart(2, "0")}.000Z`);
@@ -125,6 +126,30 @@ describe("buildAgentStreamRenderModel", () => {
expect(model.history).not.toContain(head[0]);
});
it("virtualizes a desktop web turn that runs past the mounted cap", () => {
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 80;
const tail = Array.from({ length }, (_, index) => ({
...userMessage(`row-${index}`, index % 60),
turnId: "long-run",
}));
const model = buildAgentStreamRenderModel({
isTurnActive: false,
activeTurnStartedAt: null,
tail,
head: [],
platform: "web",
isMobileBreakpoint: false,
});
expect(model.segments.historyMounted).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
expect(model.segments.historyVirtualized).toHaveLength(80);
expect(model.segments.historyMounted[0]?.id).toBe(
`row-${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`,
);
expect(model.segments.historyVirtualized[0]?.id).toBe("row-0");
});
it("keeps the full committed tail mounted on mobile web", () => {
const tail = [userMessage("u1", 1), assistantMessage("a1", 2)];
const head = [assistantMessage("live-a", 3)];
+5 -1
View File
@@ -2,7 +2,10 @@ import type { ReactNode } from "react";
import { deriveStreamTurnTiming, type StreamTurnTiming } from "@/timeline/turn-time";
import type { StreamItem } from "@/types/stream";
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
import { getWebPartialVirtualizationThreshold } from "./web-virtualization";
import {
getWebPartialVirtualizationThreshold,
MAX_MOUNTED_WEB_WINDOW_ITEMS,
} from "./web-virtualization";
import { orderHeadForStreamRenderStrategy, orderTailForStreamRenderStrategy } from "./strategy";
import { resolveStreamRenderStrategy } from "./strategy-resolver";
@@ -134,6 +137,7 @@ function splitOrderedTail(params: {
const mountedWindowStart = findMountedWindowStart({
items: orderedTail,
minMountedCount: getMountedRecentStreamItems(),
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
});
const split = {
history: orderedTail,
@@ -10,6 +10,7 @@ import {
DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD,
estimateStreamItemHeight,
findMountedWindowStart,
MAX_MOUNTED_WEB_WINDOW_ITEMS,
getWebMountedRecentStreamItems,
getWebPartialVirtualizationThreshold,
splitWebVirtualizedHistory,
@@ -108,6 +109,37 @@ describe("findMountedWindowStart", () => {
}),
).toBe(39);
});
it("keeps a whole turn when the caller does not cap the rewind", () => {
const items = Array.from({ length: MAX_MOUNTED_WEB_WINDOW_ITEMS + 40 }, (_, index) => ({
...toolCall(`t${index}`, index % 60),
turnId: "long",
}));
expect(findMountedWindowStart({ items, minMountedCount: 20 })).toBe(0);
});
it("stops a long turn at the cap and still honors a larger minimum", () => {
const items = Array.from({ length: 200 }, (_, index) => ({
...toolCall(`t${index}`, index % 60),
turnId: "long",
}));
expect(
findMountedWindowStart({
items,
minMountedCount: 20,
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
}),
).toBe(200 - MAX_MOUNTED_WEB_WINDOW_ITEMS);
expect(
findMountedWindowStart({
items,
minMountedCount: 80,
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
}),
).toBe(120);
});
});
describe("splitWebVirtualizedHistory", () => {
@@ -130,6 +162,39 @@ describe("splitWebVirtualizedHistory", () => {
expect(window.mountedEntries[0]?.item.id).toBe("u5");
expect(window.mountedEntries).toHaveLength(50);
});
it("virtualizes the older rows of a turn that is longer than the mounted cap", () => {
const length = MAX_MOUNTED_WEB_WINDOW_ITEMS + 25;
const items = Array.from({ length }, (_, index) => ({
...toolCall(`t${index}`, index % 60),
turnId: "long",
}));
const window = splitWebVirtualizedHistory({
entries: indexEntries(items),
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
});
expect(window.mountedEntries).toHaveLength(MAX_MOUNTED_WEB_WINDOW_ITEMS);
expect(window.virtualizedEntries).toHaveLength(25);
expect(window.mountedEntries[0]?.item.id).toBe(`t${length - MAX_MOUNTED_WEB_WINDOW_ITEMS}`);
expect(window.virtualizedEntries[0]?.item.id).toBe("t0");
});
it("keeps a turn that fits under the cap mounted together", () => {
const items = Array.from({ length: 40 }, (_, index) => ({
...toolCall(`t${index}`, index),
turnId: "short",
}));
const window = splitWebVirtualizedHistory({
entries: indexEntries(items),
minMountedCount: DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS,
});
expect(window.virtualizedEntries).toHaveLength(0);
expect(window.mountedEntries).toHaveLength(40);
});
});
describe("estimateStreamItemHeight", () => {
@@ -8,6 +8,9 @@ import {
export const DEFAULT_WEB_PARTIAL_VIRTUALIZATION_THRESHOLD = 100;
export const DEFAULT_WEB_MOUNTED_RECENT_STREAM_ITEMS = DEFAULT_MOUNTED_RECENT_STREAM_ITEMS;
// Collapsed tool rows are about 40px, so this stays past a desktop viewport.
// Opening a long run mounts that tail and virtualizes the older rows.
export const MAX_MOUNTED_WEB_WINDOW_ITEMS = 60;
const COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE = 40;
type BottomAnchorE2ETestGlobals = typeof globalThis & {
@@ -87,6 +90,7 @@ export function splitWebVirtualizedHistory(input: {
const startIndex = findMountedWindowStart({
items: input.entries.map((entry) => entry.item),
minMountedCount: input.minMountedCount,
maxMountedCount: MAX_MOUNTED_WEB_WINDOW_ITEMS,
});
return {
virtualizedEntries: input.entries.slice(0, startIndex),
@@ -1,5 +1,20 @@
import { afterEach, describe, expect, it } from "vitest";
import { createAssistantSelectionClipboardContent } from "./content.web";
import { createElement as h } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
import { I18nextProvider } from "react-i18next";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
import type { ToastApi } from "@/components/toast-host";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { i18n } from "@/i18n/i18next";
import {
createAssistantSelectionClipboardContent,
createElementClipboardContent,
} from "./content.web";
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
const fixture = `
<div data-testid="assistant-message">
@@ -953,3 +968,158 @@ it("copies a workspace image path instead of its temporary display URL", () => {
"![chart](assets/chart.png)",
);
});
describe("quote copy", () => {
let root: Root | undefined;
let host: HTMLDivElement | undefined;
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
const queryClient = new QueryClient();
afterEach(() => {
const mounted = root;
if (mounted) flushSync(() => mounted.unmount());
root = undefined;
host?.remove();
host = undefined;
});
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
if (!host || !root) {
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
}
const mounted = root;
flushSync(() =>
mounted.render(
h(
QueryClientProvider,
{ client: queryClient },
h(
I18nextProvider,
{ i18n },
h(ToastApiProvider, {
api: toast,
children: h(EnrichedMarkdownText, {
markdown,
flavor: "github",
md4cFlags: { latexMath: false, admonitions: true },
renderers: WEB_RENDERERS,
}),
}),
),
),
),
);
const rendered = host;
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
return rendered;
}
it("copies a quote's body with its formatting and without the quote marker", async () => {
const rendered = await renderMarkdown(
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
"Nested reply",
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe(
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
);
expect(content?.html).toContain("<strong>team</strong>");
expect(content?.html).toContain("<blockquote>");
expect(content?.html).not.toContain("Copy quote");
});
it("gives a nested quote its own control that copies only the nested quote", async () => {
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
const nested = fixtureElement(rendered, "blockquote", 1);
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
});
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
const quote = fixtureElement(rendered, "blockquote");
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
});
it("copies what a streaming quote shows at the time of the copy", async () => {
const first = await renderMarkdown("> First draft", "First draft");
const quote = fixtureElement(first, "blockquote");
const revised = await renderMarkdown("> First draft, revised", "revised");
expect(fixtureElement(revised, "blockquote")).toBe(quote);
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
});
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("literal _word_ stays literal");
expect(content?.html).toContain("literal _word_ stays literal");
expect(content?.html).not.toContain("<em>");
});
it("gives an admonition no copy control", async () => {
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
});
it("copies a nested admonition as its callout source", async () => {
const rendered = await renderMarkdown(
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
"After",
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
});
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
const rendered = await renderMarkdown(
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
"After",
);
rendered.setAttribute("data-testid", "assistant-message");
const body = tokenText(rendered, "Do not deploy.");
expect(
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
).toBe("deploy.\n\nAfter");
expect(
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
?.plainText,
).toBe("Before\n\nWarn");
expect(
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
).not.toContain("[!WARNING]");
});
it("copies a rendered Mermaid diagram as its fence", () => {
const quote = document.createElement("blockquote");
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
expect(createElementClipboardContent(quote)?.plainText).toBe(
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
);
});
it("copies nothing from a quote that holds only its control", () => {
const quote = document.createElement("blockquote");
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
expect(createElementClipboardContent(quote)).toBeNull();
});
});
@@ -6,9 +6,12 @@ import {
type MarkdownClipboardContent,
} from "@/utils/rich-clipboard";
import {
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
MARKDOWN_COPY_ALT_ATTRIBUTE,
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
@@ -91,6 +94,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
} else {
turndown.escape = (text) => text;
}
// An admonition copies as its `> [!TYPE]` source.
turndown.addRule("admonition", {
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
replacement: (content, node) => {
const type = (node as Element)
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
.toUpperCase();
const body = content.replace(/^\n+|\n+$/g, "");
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
},
});
turndown.addRule("gfmStrikethrough", {
filter: ["del", "s"],
replacement: (content) => `~~${content}~~`,
@@ -120,6 +134,53 @@ function isWebUrl(href: string): boolean {
const markdownTurndown = createTurndown("markdown");
const plainTurndown = createTurndown("plain");
/**
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
* its source in an attribute. Put the code block back so the fence is what gets copied.
*/
function restoreFenceSources(container: Element): void {
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
if (source === null) continue;
const pre = document.createElement("pre");
const code = document.createElement("code");
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
if (language) code.className = `language-${language}`;
code.textContent = source;
pre.append(code);
region.replaceWith(pre);
}
}
/**
* Clipboard payload for everything inside `element`, without the element's own syntax:
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
*/
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
const container = document.createElement("div");
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
const originals = element.querySelectorAll("*");
const copies = container.querySelectorAll("*");
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
restoreFenceSources(container);
restoreAdmonitions(container);
restoreMarkdownElements(container);
return clipboardContentFromMarkup(container);
}
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
}
export function createAssistantSelectionClipboardContent(
selection: Selection | null,
): MarkdownClipboardContent | null {
@@ -145,17 +206,7 @@ export function createAssistantSelectionClipboardContent(
container.append(cloneMarkdownSelection(part.range, part.message));
}
restoreMarkdownElements(container);
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
return clipboardContentFromMarkup(container);
}
/**
@@ -702,6 +753,28 @@ function numberOrderedListItems(list: Element, start: number): void {
});
}
/**
* The library renders an admonition as a box with a generated title. Keep it a quote
* with its type, so it copies as its callout source rather than as the title's prose.
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
* whether it holds the whole callout, so it copies the text it shows.
*/
function restoreAdmonitions(container: Element): void {
const admonitions = Array.from(
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
);
for (const admonition of admonitions.toReversed()) {
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
const quote = document.createElement("blockquote");
quote.setAttribute(
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
);
quote.append(...admonition.childNodes);
admonition.replaceWith(quote);
}
}
function unwrapIncompleteTables(container: HTMLElement): void {
for (const table of container.querySelectorAll("table")) {
if (hasUsableTableColumnContract(table)) {
@@ -6,9 +6,13 @@ export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
export const MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE = "data-paseo-markdown-fence-source";
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
export const MARKDOWN_COPY_SRC_ATTRIBUTE = "data-paseo-markdown-src";
export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
/**
* Trailing line breaks, with any indentation that followed the last one.
@@ -1,17 +1,9 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Pressable,
View,
Text,
type StyleProp,
type TextStyle,
type ViewStyle,
} from "react-native";
import { StyleSheet } from "react-native-unistyles";
import React, { useCallback, useMemo, useState } from "react";
import { View, Text, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
import * as Clipboard from "expo-clipboard";
import { Check, Copy } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import type { HighlightToken } from "@getpaseo/highlight";
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
import { isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
@@ -85,6 +77,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
[renderedCode, language],
);
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const [isHovered, setIsHovered] = useState(false);
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
@@ -93,7 +86,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
// Copy the code without its trailing blank lines. A fence body ends in a newline,
// and ends in more than one when the author left a blank line before the closing
// fence; pasting any of them into a terminal runs the last line.
const getCode = useCallback(() => code.replace(TRAILING_CODE_LINE_BREAKS, ""), [code]);
const copyCode = useCallback(async () => {
const content = code.replace(TRAILING_CODE_LINE_BREAKS, "");
if (!content) return false;
return Clipboard.setStringAsync(content);
}, [code]);
return (
<View
@@ -111,7 +108,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
{renderedCode}
</Text>
)}
<CopyButton getCode={getCode} visible={controlsVisible} />
<BlockCopyButton
onCopy={copyCode}
visible={controlsVisible}
label={t("message.actions.copyCode")}
/>
</View>
);
});
@@ -168,87 +169,3 @@ function splitFenceStyle(inheritedStyles: TextStyle, textStyle: TextStyle): Spli
innerTextStyle: [inheritedStyles, textOnly],
};
}
interface CopyButtonProps {
getCode: () => string;
visible: boolean;
}
const COPIED_RESET_MS = 1500;
const CopyButton = React.memo(function CopyButton({ getCode, visible }: CopyButtonProps) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (resetRef.current) clearTimeout(resetRef.current);
},
[],
);
const handlePress = useCallback(async () => {
const content = getCode();
if (!content) return;
await Clipboard.setStringAsync(content);
setCopied(true);
if (resetRef.current) clearTimeout(resetRef.current);
resetRef.current = setTimeout(() => {
setCopied(false);
resetRef.current = null;
}, COPIED_RESET_MS);
}, [getCode]);
const visibilityStyle = visible
? copyButtonStyles.containerVisible
: copyButtonStyles.containerHidden;
const wrapperStyle = useMemo(
() => [copyButtonStyles.container, visibilityStyle],
[visibilityStyle],
);
return (
<Pressable
onPress={handlePress}
style={wrapperStyle}
pointerEvents={visible ? "auto" : "none"}
accessibilityRole="button"
accessibilityLabel={copied ? t("message.actions.copied") : t("message.actions.copyCode")}
hitSlop={8}
dataSet={markdownCopyDataSet.ignore}
>
{({ hovered }) => {
const iconColor = hovered
? copyButtonStyles.iconHoveredColor.color
: copyButtonStyles.iconColor.color;
return copied ? (
<Check size={14} color={iconColor} />
) : (
<Copy size={14} color={iconColor} />
);
}}
</Pressable>
);
});
const copyButtonStyles = StyleSheet.create((theme) => ({
container: {
position: "absolute",
top: theme.spacing[2],
right: theme.spacing[2],
padding: theme.spacing[1],
},
containerVisible: {
opacity: 1,
},
containerHidden: {
opacity: 0,
},
iconColor: {
color: theme.colors.foregroundMuted,
},
iconHoveredColor: {
color: theme.colors.foreground,
},
}));
+304 -139
View File
@@ -1,11 +1,28 @@
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Pressable, View } from "react-native";
import { Plus, Server, Settings } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactElement,
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Check, Plus, Server } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import {
getHostRuntimeStore,
useHostRuntimeConnectionStatus,
useHosts,
} from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { orderHostsLocalFirst } from "@/types/host-connection";
import {
ADD_HOST_OPTION_ID,
@@ -22,7 +39,16 @@ export {
};
const SEARCHABLE_THRESHOLD = 10;
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
const LEADING_RAIL_SIZE = 16;
const HOST_ROW_ICON_SIZE = 14;
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
const ThemedCheck = withUnistyles(Check);
const ThemedPlus = withUnistyles(Plus);
const ThemedServer = withUnistyles(Server);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export interface HostPickerHost {
serverId: string;
label: string;
@@ -36,122 +62,166 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
);
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
// Socket/pipe transports have no host:port — their endpoint is a filesystem
// path, so they read as "Local". TCP and relay show the address being used.
function formatActiveConnectionLabel(connection: ActiveConnection): string {
if (connection.type === "directSocket" || connection.type === "directPipe") {
return "Local";
}
return formatConnectionEndpoint(connection.endpoint);
}
export interface HostPickerOptionProps {
serverId: string;
label: string;
showActiveConnection: boolean;
appearance: HostAppearance;
selected?: boolean;
active: boolean;
onPress: () => void;
onOpenHostSettings?: (serverId: string) => void;
testID?: string;
}
export function HostPickerOption({
serverId,
label,
showActiveConnection,
appearance,
selected,
active,
onPress,
onOpenHostSettings,
testID,
}: HostPickerOptionProps): ReactElement {
const { theme } = useUnistyles();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const connectionLabel =
showActiveConnection && activeConnection
? formatActiveConnectionLabel(activeConnection)
: undefined;
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
const handleSettingsPress = useCallback(() => {
onOpenHostSettings?.(serverId);
}, [onOpenHostSettings, serverId]);
const trailingAction = useMemo(() => {
if (!onOpenHostSettings) return undefined;
return (
<Pressable
onPress={handleSettingsPress}
style={styles.settingsAction}
accessibilityRole="button"
accessibilityLabel={`Open ${label} settings`}
>
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}, [
handleSettingsPress,
label,
onOpenHostSettings,
theme.colors.foregroundMuted,
theme.iconSize.sm,
]);
const status = useHostRuntimeConnectionStatus(serverId);
const detectedMachineKind = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const isOffline = status === "offline" || status === "error";
return (
<ComboboxItem
label={label}
description={connectionLabel}
leadingSlot={leadingSlot}
trailingAction={trailingAction}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<HostStatusDot serverId={serverId} />
</View>
<View style={styles.hostBody}>
<View style={styles.hostHeaderRow}>
<HostIconGlyph
icon={resolvedIcon}
color={appearance.color}
size={HOST_ROW_ICON_SIZE}
style={styles.hostGlyph}
/>
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
{label}
</Text>
</View>
<HostConnectionLine serverId={serverId} />
</View>
<View style={styles.hostTrailing}>
<HostLatencyLabel serverId={serverId} />
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</View>
</PressHighlight>
</View>
);
}
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
add: "Add host",
all: "All hosts",
enableBuiltInDaemon: "Enable built-in daemon",
};
function SystemHostPickerOption({
function AllHostsOption({
active,
selected,
onPress,
kind,
testID,
}: {
active: boolean;
selected?: boolean;
onPress: () => void;
kind: "add" | "all" | "enableBuiltInDaemon";
testID?: string;
}): ReactElement {
const { theme } = useUnistyles();
const Icon = kind === "add" ? Plus : Server;
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
const leadingSlot = useMemo(
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
);
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = t("sidebar.display.hostFilter.all");
return (
<ComboboxItem
label={label}
leadingSlot={leadingSlot}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</PressHighlight>
</View>
);
}
function ActionOptionRow({
kind,
active,
showDivider,
onPress,
testID,
}: {
kind: "add" | "enableBuiltInDaemon";
active: boolean;
showDivider: boolean;
onPress: () => void;
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
return (
<View>
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
{kind === "add" ? (
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
) : (
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
)}
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
</PressHighlight>
</View>
</View>
);
}
@@ -162,14 +232,12 @@ export interface HostPickerProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchorRef: React.RefObject<View | null>;
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
includeAllHost?: boolean;
includeAddHost?: boolean;
onAddHost?: () => void;
includeEnableBuiltInDaemon?: boolean;
onEnableBuiltInDaemon?: () => void;
showActiveConnection?: boolean;
onOpenHostSettings?: (serverId: string) => void;
searchable?: boolean;
title?: string;
desktopPlacement?: ComboboxProps["desktopPlacement"];
@@ -186,80 +254,90 @@ export function HostPicker({
open,
onOpenChange,
anchorRef,
restoreFocusRef,
includeAllHost,
includeAddHost,
onAddHost,
includeEnableBuiltInDaemon,
onEnableBuiltInDaemon,
showActiveConnection,
onOpenHostSettings,
searchable,
title,
desktopPlacement = "bottom-start",
desktopMinWidth,
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
addHostTestID,
hostOptionTestID,
children,
}: HostPickerProps): ReactElement {
const { t } = useTranslation();
const localServerId = useLocalDaemonServerId();
const allHostProfiles = useHosts();
const orderedHosts = useMemo(
() => orderHostsLocalFirst(hosts, localServerId),
[hosts, localServerId],
);
const appearanceByServerId = useMemo(() => {
const map = new Map<string, HostAppearance>();
for (const profile of allHostProfiles) {
map.set(profile.serverId, profile.appearance);
}
return map;
}, [allHostProfiles]);
useEffect(() => {
if (!open) return;
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
}, [open, orderedHosts]);
const options = useMemo(() => {
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
if (includeEnableBuiltInDaemon)
if (includeAllHost) {
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
}
if (includeAddHost) {
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
}
if (includeEnableBuiltInDaemon) {
hostOptions.push({
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
label: "Enable built-in daemon",
label: t("settings.enableBuiltInDaemon"),
});
}
return hostOptions;
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
let firstActionOptionId: string | null = null;
if (includeAddHost) {
firstActionOptionId = ADD_HOST_OPTION_ID;
} else if (includeEnableBuiltInDaemon) {
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
}
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
const resolvedTitle = title ?? t("sidebar.actions.hosts");
const handleSelect = useCallback(
(id: string) => {
if (id === ADD_HOST_OPTION_ID) {
onOpenChange(false);
onAddHost?.();
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onEnableBuiltInDaemon?.();
} else {
onSelect(id);
return;
}
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onOpenChange(false);
onEnableBuiltInDaemon?.();
return;
}
onSelect(id);
onOpenChange(false);
},
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
);
const handleOpenHostSettings = useCallback(
(serverId: string) => {
onOpenHostSettings?.(serverId);
onOpenChange(false);
},
[onOpenHostSettings, onOpenChange],
);
const renderOption = useCallback<RenderHostOption>(
({ option, selected, active, onPress }) => {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption
kind="add"
active={active}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ALL_HOSTS_OPTION_ID) {
return (
<SystemHostPickerOption
kind="all"
<AllHostsOption
active={active}
selected={selected}
onPress={onPress}
@@ -267,30 +345,48 @@ export function HostPicker({
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
<ActionOptionRow
kind="add"
active={active}
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
return (
<ActionOptionRow
kind="enableBuiltInDaemon"
active={active}
showDivider={
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
}
onPress={onPress}
/>
);
}
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
return (
<HostPickerOption
serverId={option.id}
label={option.label}
showActiveConnection={showActiveConnection === true}
appearance={appearance}
selected={selected}
active={active}
onPress={onPress}
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
testID={hostOptionTestID?.(option.id)}
/>
);
},
[
addHostTestID,
appearanceByServerId,
firstActionOptionId,
hostOptionTestID,
onOpenHostSettings,
showActiveConnection,
handleOpenHostSettings,
orderedHosts.length,
],
);
@@ -303,12 +399,11 @@ export function HostPicker({
onSelect={handleSelect}
renderOption={renderOption}
searchable={isSearchable}
searchPlaceholder="Search hosts"
title={title ?? "Host"}
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
title={resolvedTitle}
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
restoreFocusRef={restoreFocusRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
/>
@@ -317,16 +412,86 @@ export function HostPicker({
}
const styles = StyleSheet.create((theme) => ({
settingsAction: {
flex: 1,
justifyContent: "center",
paddingLeft: theme.spacing[1],
paddingRight: theme.spacing[3],
},
statusDotSlot: {
width: theme.iconSize.sm,
height: theme.iconSize.sm,
alignItems: "center",
justifyContent: "center",
},
rowEnvelope: {
position: "relative",
},
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
// centered 16px column aligned to the first line's 18px line-height.
leadingRailSlot: {
width: LEADING_RAIL_SIZE,
height: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
hostRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
rowHighlighted: {
backgroundColor: theme.colors.surface1,
},
hostBody: {
flex: 1,
minWidth: 0,
gap: 2,
},
hostHeaderRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
hostGlyph: {
flexShrink: 0,
},
hostName: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
hostNameMuted: {
color: theme.colors.foregroundMuted,
},
hostTrailing: {
flexDirection: "row",
alignItems: "center",
height: 18,
gap: theme.spacing[2],
flexShrink: 0,
},
actionSectionDivider: {
height: theme.borderWidth[1],
backgroundColor: theme.colors.border,
marginVertical: theme.spacing[1],
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
actionLabel: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
}));
@@ -0,0 +1,32 @@
import Svg, { Circle } from "react-native-svg";
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
[3, 12, 21].map((cx, column) => ({
cx,
cy,
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
solid: row === 1 || (row === 2 && column === 1),
})),
);
export interface TailscaleIconProps {
size?: number;
color?: string;
}
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
{TAILSCALE_DOTS.map((dot) => (
<Circle
key={`${dot.cx}:${dot.cy}`}
cx={dot.cx}
cy={dot.cy}
r={3}
fill={color}
opacity={dot.solid ? 1 : 0.3}
/>
))}
</Svg>
);
}
+2 -2
View File
@@ -388,10 +388,10 @@ function SidebarHostPicker({
includeAddHost
onAddHost={onAddHost}
showActiveConnection
onOpenHostSettings={onOpenHostSettings}
searchable
title={label}
desktopPlacement="top-start"
desktopMinWidth={240}
desktopMinWidth={328}
addHostTestID="sidebar-host-add"
hostOptionTestID={sidebarHostOptionTestID}
>
@@ -0,0 +1,119 @@
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { userEvent } from "vitest/browser";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { I18nextProvider } from "react-i18next";
import type { ToastApi } from "@/components/toast-host";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { i18n } from "@/i18n/i18next";
import { BlockCopyButton } from "./block-copy-button";
const LABEL = "Copy quote";
let errors: string[] = [];
const toast: ToastApi = {
show: () => () => {},
copied: () => {},
error: (message) => errors.push(message),
};
describe("BlockCopyButton", () => {
let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
errors = [];
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(() => {
flushSync(() => root.unmount());
host.remove();
});
function render(onCopy: () => Promise<boolean>, visible = true) {
flushSync(() =>
root.render(
<I18nextProvider i18n={i18n}>
<ToastApiProvider api={toast}>
<BlockCopyButton onCopy={onCopy} visible={visible} label={LABEL} />
</ToastApiProvider>
</I18nextProvider>,
),
);
}
function button(name = LABEL): HTMLElement {
return within(host).getByRole("button", { name });
}
it("shows Copied after a write and returns to its label", async () => {
let calls = 0;
render(async () => {
calls += 1;
return true;
});
await userEvent.click(button());
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
await vi.waitFor(() => expect(button()).toBeTruthy(), { timeout: 2500 });
expect(calls).toBe(1);
expect(errors).toEqual([]);
});
it.each([
["resolves false", async () => false],
[
"rejects",
async (): Promise<boolean> => {
throw new Error("Clipboard denied");
},
],
])("tells the user and never shows Copied when the write %s", async (_case, failure) => {
let calls = 0;
render(() => {
calls += 1;
return calls === 1 ? failure() : Promise.resolve(true);
});
await userEvent.click(button());
await vi.waitFor(() => expect(errors).toEqual(["Unable to copy"]));
expect(within(host).queryByRole("button", { name: "Copied" })).toBeNull();
await userEvent.click(button());
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
expect(calls).toBe(2);
});
it("does not write twice while a write is pending", async () => {
let finish!: (written: boolean) => void;
let calls = 0;
render(() => {
calls += 1;
return new Promise<boolean>((resolve) => {
finish = resolve;
});
});
await userEvent.click(button());
await userEvent.click(button());
expect(calls).toBe(1);
finish(true);
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
expect(calls).toBe(1);
});
it("stays hidden until its block reveals it or it takes keyboard focus", async () => {
render(async () => true, false);
expect(getComputedStyle(button()).opacity).toBe("0");
await userEvent.tab();
expect(document.activeElement).toBe(button());
await vi.waitFor(() => expect(getComputedStyle(button()).opacity).toBe("1"));
});
});
@@ -0,0 +1,109 @@
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { View } from "react-native";
import { Check, Copy } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { markdownCopyDataSet } from "@/assistant-selection-copy/markup";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import type { Theme } from "@/styles/theme";
const ThemedCopy = withUnistyles(Copy, mutedIconColorMapping);
const ThemedCheck = withUnistyles(Check, mutedIconColorMapping);
const COPIED_RESET_MS = 1500;
/** How far the copy glyph sits from the top and trailing edges of its block. */
export function blockCopyGlyphInset(theme: Theme): number {
return theme.spacing[2] + theme.spacing[1];
}
interface BlockCopyButtonProps {
/** Writes the block to the clipboard. Resolves false, or rejects, when nothing was written. */
onCopy: () => Promise<boolean>;
/** The block's own reveal state. Keyboard focus shows the button regardless. */
visible: boolean;
label: string;
}
/**
* The copy control in the top trailing corner of a Markdown block. The block is its
* positioned ancestor.
*/
export const BlockCopyButton = memo(function BlockCopyButton({
onCopy,
visible,
label,
}: BlockCopyButtonProps) {
const { t } = useTranslation();
const toast = useToast();
const compact = useIsCompactFormFactor();
const [copied, setCopied] = useState(false);
const [focused, setFocused] = useState(false);
const writing = useRef(false);
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const focus = useCallback(() => setFocused(true), []);
const blur = useCallback(() => setFocused(false), []);
useEffect(
() => () => {
if (resetRef.current) clearTimeout(resetRef.current);
},
[],
);
const handlePress = useCallback(async () => {
// A slow clipboard must not queue a second write behind the first.
if (writing.current) return;
writing.current = true;
const written = await onCopy()
.catch(() => false)
.finally(() => {
writing.current = false;
});
if (!written) {
toast.error(t("common.errors.unableToCopy"));
return;
}
setCopied(true);
if (resetRef.current) clearTimeout(resetRef.current);
resetRef.current = setTimeout(() => setCopied(false), COPIED_RESET_MS);
}, [onCopy, t, toast]);
const shown = visible || focused;
const Glyph = copied ? ThemedCheck : ThemedCopy;
return (
<View style={styles.corner(compact)} dataSet={markdownCopyDataSet.ignore}>
<ToolbarButton
compact={compact}
label={copied ? t("message.actions.copied") : label}
onPress={handlePress}
onFocus={focus}
onBlur={blur}
style={shown ? styles.shown : styles.hidden}
>
<Glyph size={paneContentToolbarIconSize(compact)} />
</ToolbarButton>
</View>
);
});
const styles = StyleSheet.create((theme) => ({
// The glyph, not the button frame, sits on the inset; the frame overhangs it.
corner: (compact: boolean) => {
const frameOverhang =
(smallIconButtonChromeFrameSize(compact) - paneContentToolbarIconSize(compact)) / 2;
const inset = blockCopyGlyphInset(theme) - frameOverhang;
return {
position: "absolute" as const,
top: inset,
right: inset,
pointerEvents: "box-none" as const,
};
},
shown: { opacity: 1, pointerEvents: "auto" },
hidden: { opacity: 0, pointerEvents: "none" },
}));
@@ -5,6 +5,10 @@ import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import { ZoomableViewport } from "@/components/zoomable-viewport";
import {
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
} from "@/assistant-selection-copy/markup";
import type { Theme } from "@/styles/theme";
import type { MarkdownFenceRendererProps } from "./types";
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
@@ -81,6 +85,16 @@ function MermaidFenceHostImpl({
[visible],
);
const sourceVisible = !diagramVisible;
// A visible diagram stands in for its fence, so copying the surrounding block takes
// the source from here: the revision on screen, which lags `code` while a streamed
// revision renders. The source view copies as its own code block.
const diagramCopyAttributes =
diagramVisible && visible
? {
[MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE]: visible.source,
[MARKDOWN_COPY_LANGUAGE_ATTRIBUTE]: "mermaid",
}
: null;
const viewportStyle = diagramVisible ? diagramStyle : measuringStyle;
return (
@@ -111,7 +125,7 @@ function MermaidFenceHostImpl({
) : null}
</View>
) : null}
<div inert={!diagramVisible} style={boundaryStyle}>
<div inert={!diagramVisible} style={boundaryStyle} {...diagramCopyAttributes}>
<ZoomableViewport
accessibilityLabel={t("message.diagram.diagram")}
actions={actions}
@@ -0,0 +1,71 @@
import { useCallback, useMemo, useRef, useState } from "react";
import { withUnistyles } from "react-native-unistyles";
import type { BlockquoteRendererProps } from "react-native-enriched-markdown";
import { useTranslation } from "react-i18next";
import { createElementClipboardContent } from "@/assistant-selection-copy/content.web";
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
import { paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
import { useIsCompactFormFactor } from "@/constants/layout";
import { writeClipboardContent } from "@/utils/rich-clipboard";
import { getDefaultMarkdownClipboardEnvironment } from "@/utils/rich-clipboard-default-environment";
import { BlockCopyButton, blockCopyGlyphInset } from "./block-copy-button";
interface WebBlockquoteProps extends BlockquoteRendererProps {
copyGlyphInset: number;
}
/**
* Room the quote reserves so the control never covers its text. Compact layouts always
* show the control, so it gets a band above the body and the text keeps the full width.
* Wide layouts reveal it on hover, where a band would leave an empty strip above every
* quote, so the text wraps short of it instead.
*/
function copyRoom(compact: boolean, glyphInset: number) {
if (compact) {
return { paddingTop: glyphInset + paneContentToolbarIconSize(compact) + glyphInset };
}
return { paddingRight: smallIconButtonChromeFrameSize(compact) + glyphInset };
}
/** A quote with a control that copies its body, for drafts an agent wrote to be pasted elsewhere. */
export const WebBlockquote = withUnistyles(
function WebBlockquote({ blockquoteProps, children, copyGlyphInset }: WebBlockquoteProps) {
const { t } = useTranslation();
const quote = useRef<HTMLQuoteElement>(null);
const [hovered, setHovered] = useState(false);
const compact = useIsCompactFormFactor();
const enter = useCallback(() => setHovered(true), []);
const leave = useCallback(() => setHovered(false), []);
const style = useMemo(
() => ({
...blockquoteProps.style,
position: "relative" as const,
...copyRoom(compact, copyGlyphInset),
}),
[blockquoteProps.style, compact, copyGlyphInset],
);
const copy = useCallback(async () => {
// Read the rendered body at press time: a streaming quote copies what it shows now.
const content = quote.current && createElementClipboardContent(quote.current);
if (!content) return false;
return writeClipboardContent(content, getDefaultMarkdownClipboardEnvironment());
}, []);
return (
<blockquote
{...blockquoteProps}
ref={quote}
style={style}
onPointerEnter={enter}
onPointerLeave={leave}
>
<BlockCopyButton
onCopy={copy}
visible={hovered || compact}
label={t("message.actions.copyQuote")}
/>
{children}
</blockquote>
);
},
(theme) => ({ copyGlyphInset: blockCopyGlyphInset(theme) }),
);
@@ -14,6 +14,7 @@ import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import type { Theme } from "@/styles/theme";
import { MermaidFence } from "./fence/mermaid";
import { isRecognizedLink, markdownLinkSource } from "./source";
import { WebBlockquote } from "./quote-block.web";
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
const codeStyle = (theme: Theme) => ({
@@ -111,4 +112,8 @@ const styles = StyleSheet.create((theme) => ({
},
}));
export const WEB_RENDERERS: MarkdownRenderers = { codeBlock: WebCodeBlock, link: WebLink };
export const WEB_RENDERERS: MarkdownRenderers = {
codeBlock: WebCodeBlock,
link: WebLink,
blockquote: WebBlockquote,
};
+60 -18
View File
@@ -73,6 +73,9 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
const IS_WEB = isWeb;
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
const FOOTER_DATASET = { comboboxFooter: true };
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
export type ComboboxOption = ComboboxOptionModel;
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
@@ -138,8 +141,6 @@ export interface ComboboxProps {
/** When true, selecting an option does not close the picker (multi-select mode). */
keepOpenOnSelect?: boolean;
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
children?: ReactNode;
}
@@ -404,6 +405,7 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
interface OptionRowProps {
index: number;
option: ComboboxOption;
selected: boolean;
active: boolean;
@@ -411,20 +413,27 @@ interface OptionRowProps {
renderOption: RenderOptionFn | undefined;
}
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
if (renderOption) {
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
return (
<View dataSet={optionDataset}>
{renderOption({ option, selected, active, onPress: handlePress })}
</View>
);
}
return (
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
<View dataSet={optionDataset}>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
</View>
);
}
@@ -453,6 +462,7 @@ function OptionsList({
{options.map((opt, index) => (
<OptionRow
key={opt.id}
index={index}
option={opt}
selected={opt.id === value}
active={index === activeIndex}
@@ -954,8 +964,9 @@ function dispatchDesktopKey(
return true;
}
if (key === "Enter") {
// Consume the shortcut but keep the browser's default button activation.
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
// Consume the shortcut but keep the browser's default button activation when the user moved
// keyboard focus onto a trailing action or footer button inside the combobox.
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
return true;
}
if (input.orderedVisibleOptions.length === 0) return false;
@@ -1129,7 +1140,12 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
[safeAreaBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
[footer, footerStyle],
);
return (
@@ -1343,7 +1359,11 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
renderOption={props.renderOption}
/>
)}
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
{props.footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{props.footer}
</View>
) : null}
</FloatingSurface>
</View>
</OverlayLayerProvider>
@@ -1404,7 +1424,6 @@ export function Combobox({
footer,
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1600,6 +1619,30 @@ export function Combobox({
setActiveIndex,
);
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
useEffect(() => {
if (!IS_WEB || !isOpen || isMobile) return;
const handleFocusIn = (event: FocusEvent) => {
const target = event.target;
if (!(target instanceof Element)) return;
const optionEl = target.closest("[data-combobox-option-index]");
if (!optionEl) return;
const nextIndex = Number.parseInt(
optionEl.getAttribute("data-combobox-option-index") ?? "",
10,
);
if (
Number.isInteger(nextIndex) &&
nextIndex >= 0 &&
nextIndex < orderedVisibleOptions.length
) {
setActiveIndex(nextIndex);
}
};
document.addEventListener("focusin", handleFocusIn);
return () => document.removeEventListener("focusin", handleFocusIn);
}, [isMobile, isOpen, orderedVisibleOptions.length]);
const handleSelect = useCallback(
(id: string) => {
onSelect(id);
@@ -1670,7 +1713,6 @@ export function Combobox({
layer: floatingLayer,
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
restoreFocusRef,
});
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
@@ -244,6 +244,7 @@ const CATALOG_DATA = [
},
{
id: "hermes",
bundledProvider: { hostFeature: "hermesProvider" },
title: "Hermes",
description: "Nous Research self-improving AI agent",
version: "manual",
@@ -11,8 +11,13 @@ import { i18n } from "@/i18n/i18next";
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
export type DesktopUpdateMode = "automatic" | "notify" | "off";
export interface DesktopSettings {
releaseChannel: ReleaseChannel;
updates: {
mode: DesktopUpdateMode;
};
notifications: {
playSound: boolean;
};
@@ -24,12 +29,16 @@ export interface DesktopSettings {
export interface DesktopSettingsPatch {
releaseChannel?: ReleaseChannel;
updates?: Partial<DesktopSettings["updates"]>;
notifications?: Partial<DesktopSettings["notifications"]>;
daemon?: Partial<DesktopSettings["daemon"]>;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
releaseChannel: "stable",
updates: {
mode: "automatic",
},
notifications: {
playSound: true,
},
@@ -149,13 +158,24 @@ export async function migrateLegacyDesktopSettings(input: {
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
}
function parseUpdateMode(value: unknown): DesktopUpdateMode {
if (value === "automatic" || value === "notify" || value === "off") {
return value;
}
return DEFAULT_DESKTOP_SETTINGS.updates.mode;
}
function parseDesktopSettings(raw: unknown): DesktopSettings {
const record = isRecord(raw) ? raw : {};
const updates = isRecord(record.updates) ? record.updates : {};
const notifications = isRecord(record.notifications) ? record.notifications : {};
const daemon = isRecord(record.daemon) ? record.daemon : {};
return {
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
updates: {
mode: parseUpdateMode(updates.mode),
},
notifications: {
playSound:
typeof notifications.playSound === "boolean"
@@ -181,6 +201,10 @@ function mergeDesktopSettings(
): DesktopSettings {
return {
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
updates: {
...current.updates,
...updates.updates,
},
notifications: {
...current.notifications,
...updates.notifications,
@@ -195,6 +219,7 @@ function mergeDesktopSettings(
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
return {
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
...(updates.updates ? { updates: updates.updates } : {}),
...(updates.notifications ? { notifications: updates.notifications } : {}),
...(updates.daemon ? { daemon: updates.daemon } : {}),
};
@@ -128,6 +128,43 @@ describe("desktop app updater — check", () => {
});
});
it("reports 'available' when an update is available to download without auto-downloading", async () => {
const { updater, port } = createUpdater({ now: () => 42 });
port.nextCheckResult(
buildFakeCheckResult({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.3",
}),
);
await updater.checkForUpdates({ releaseChannel: "stable" });
expect(updater.getSnapshot()).toMatchObject({
status: "available",
availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false },
lastCheckedAt: 42,
});
});
it("tracks download progress updates and clears them once install completes", async () => {
const { updater, port } = createUpdater();
port.nextInstallResult(buildFakeInstallResult({ installed: true }));
updater.setDownloadProgress({
version: "1.2.3",
percent: 42.4,
transferred: 42,
total: 100,
bytesPerSecond: 10,
});
expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4);
await updater.installUpdate({ releaseChannel: "stable" });
expect(updater.getSnapshot().downloadProgress).toBeNull();
});
it("reports 'up-to-date' when the check resolves with no update", async () => {
const { updater, port } = createUpdater();
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
@@ -340,6 +377,26 @@ describe("desktop app updater — install", () => {
expect(updater.getSnapshot().status).toBe("up-to-date");
});
it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => {
const { updater, port } = createUpdater();
port.nextInstallResult(
buildFakeInstallResult({
installed: false,
message: "Update failed: ECONNRESET",
errorMessage: "ECONNRESET",
}),
);
await updater.installUpdate({ releaseChannel: "stable" });
expect(updater.getSnapshot()).toMatchObject({
status: "error",
errorMessage: "ECONNRESET",
downloadProgress: null,
isInstalling: false,
});
});
it("reports the install error and moves to 'error' when the install throws", async () => {
const { updater, port, reportedInstallErrors } = createUpdater();
const error = new Error("install failed");
@@ -462,6 +519,47 @@ describe("formatStatusText", () => {
).toBe("Restart now");
});
it("formats download-available and live download progress status text", () => {
expect(
formatStatusText({
status: "available",
availableUpdate: buildFakeCheckResult({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.3",
}),
installMessage: null,
lastCheckedAt: 42,
formatVersion,
formatLastCheckedAt,
}),
).toBe("Update available: v1.2.3. Last checked at time-42.");
expect(
formatStatusText({
status: "installing",
availableUpdate: buildFakeCheckResult({
hasUpdate: true,
readyToInstall: false,
downloading: false,
latestVersion: "1.2.3",
}),
downloadProgress: {
version: "1.2.3",
percent: 64.6,
transferred: 65,
total: 100,
bytesPerSecond: 10,
},
installMessage: null,
lastCheckedAt: null,
formatVersion,
formatLastCheckedAt,
}),
).toBe("Downloading v1.2.3... 65%");
});
it("uses the active app language for local status wrappers", async () => {
await i18n.changeLanguage("zh-CN");
try {
@@ -1,6 +1,7 @@
import type {
DesktopAppUpdateCheckResult,
DesktopAppUpdateCheckIntent,
DesktopAppUpdateDownloadProgress,
DesktopAppUpdateInstallResult,
DesktopReleaseChannel,
} from "@/desktop/updates/desktop-updates";
@@ -21,6 +22,7 @@ export const PENDING_RECHECK_MS = 10_000;
export interface DesktopAppUpdaterSnapshot {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
installMessage: string | null;
lastCheckedAt: number | null;
@@ -53,6 +55,7 @@ export interface DesktopAppUpdaterDeps {
export interface DesktopAppUpdater {
getSnapshot(): DesktopAppUpdaterSnapshot;
subscribe(listener: () => void): () => void;
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
checkForUpdates(options?: {
releaseChannel: DesktopReleaseChannel;
intent?: DesktopAppUpdateCheckIntent;
@@ -66,6 +69,7 @@ export interface DesktopAppUpdater {
interface InternalState {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
installMessage: string | null;
lastCheckedAt: number | null;
@@ -76,6 +80,7 @@ interface InternalState {
const INITIAL_STATE: InternalState = {
status: "idle",
availableUpdate: null,
downloadProgress: null,
errorMessage: null,
installMessage: null,
lastCheckedAt: null,
@@ -87,6 +92,7 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
return {
status: state.status,
availableUpdate: state.availableUpdate,
downloadProgress: state.downloadProgress,
errorMessage: state.errorMessage,
installMessage: state.installMessage,
lastCheckedAt: state.lastCheckedAt,
@@ -102,9 +108,113 @@ function getErrorMessage(error: unknown): string {
return String(error);
}
function formatInstallingStatusText(input: {
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
formatVersion: (version: string | null | undefined) => string;
}): string {
const { availableUpdate, downloadProgress, formatVersion } = input;
if (downloadProgress == null) {
return i18n.t("desktop.updates.status.installing");
}
const percent = Math.round(downloadProgress.percent);
const version = downloadProgress.version ?? availableUpdate?.latestVersion;
if (version) {
return i18n.t("desktop.updates.status.downloadingVersionProgress", {
version: formatVersion(version),
percent,
});
}
return i18n.t("desktop.updates.status.downloadingProgress", { percent });
}
function formatPendingStatusText(input: {
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
lastCheckedAt: number | null;
formatVersion: (version: string | null | undefined) => string;
formatLastCheckedAt: (timestamp: number) => string;
}): string {
const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } =
input;
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
if (availableUpdate?.latestVersion) {
const version = formatVersion(availableUpdate.latestVersion);
if (downloadProgress != null) {
return i18n.t(
time !== undefined
? "desktop.updates.status.pendingWithVersionProgressAndLastChecked"
: "desktop.updates.status.pendingWithVersionProgress",
{ version, percent: Math.round(downloadProgress.percent), time },
);
}
return i18n.t(
time !== undefined
? "desktop.updates.status.pendingWithVersionAndLastChecked"
: "desktop.updates.status.pendingWithVersion",
{ version, time },
);
}
if (time !== undefined) {
return i18n.t("desktop.updates.status.pendingWithLastChecked", { time });
}
return i18n.t("desktop.updates.status.pending");
}
function formatAvailableStatusText(input: {
availableUpdate: DesktopAppUpdateCheckResult | null;
lastCheckedAt: number | null;
formatVersion: (version: string | null | undefined) => string;
formatLastCheckedAt: (timestamp: number) => string;
}): string {
const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input;
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
const isDownloadRequired =
availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false;
if (availableUpdate?.latestVersion) {
const version = formatVersion(availableUpdate.latestVersion);
if (isDownloadRequired) {
return i18n.t(
time !== undefined
? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked"
: "desktop.updates.status.downloadAvailableWithVersion",
{ version, time },
);
}
return i18n.t(
time !== undefined
? "desktop.updates.status.availableWithVersionAndLastChecked"
: "desktop.updates.status.availableWithVersion",
{ version, time },
);
}
if (isDownloadRequired) {
return time !== undefined
? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time })
: i18n.t("desktop.updates.status.downloadAvailable");
}
return time !== undefined
? i18n.t("desktop.updates.status.availableWithLastChecked", { time })
: i18n.t("desktop.updates.status.available");
}
function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
} {
if (result.readyToInstall || (result.hasUpdate && !result.downloading)) {
return { status: "available", availableUpdate: result };
}
if (result.hasUpdate) {
return { status: "pending", availableUpdate: result };
}
return { status: "up-to-date", availableUpdate: null };
}
export function formatStatusText(input: {
status: DesktopAppUpdateStatus;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
installMessage: string | null;
lastCheckedAt: number | null;
formatVersion: (version: string | null | undefined) => string;
@@ -113,79 +223,45 @@ export function formatStatusText(input: {
const {
status,
availableUpdate,
downloadProgress = null,
installMessage,
lastCheckedAt,
formatVersion,
formatLastCheckedAt,
} = input;
if (status === "checking") {
return i18n.t("desktop.updates.status.checking");
}
if (status === "checking") return i18n.t("desktop.updates.status.checking");
if (status === "installing") {
return i18n.t("desktop.updates.status.installing");
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
}
if (status === "up-to-date") {
if (lastCheckedAt != null) {
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
});
}
return i18n.t("desktop.updates.status.upToDate");
return lastCheckedAt != null
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
})
: i18n.t("desktop.updates.status.upToDate");
}
if (status === "pending") {
if (availableUpdate?.latestVersion) {
return i18n.t(
lastCheckedAt != null
? "desktop.updates.status.pendingWithVersionAndLastChecked"
: "desktop.updates.status.pendingWithVersion",
{
version: formatVersion(availableUpdate.latestVersion),
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
},
);
}
if (lastCheckedAt != null) {
return i18n.t("desktop.updates.status.pendingWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
});
}
return i18n.t("desktop.updates.status.pending");
return formatPendingStatusText({
availableUpdate,
downloadProgress,
lastCheckedAt,
formatVersion,
formatLastCheckedAt,
});
}
if (status === "available") {
if (availableUpdate?.latestVersion) {
return i18n.t(
lastCheckedAt != null
? "desktop.updates.status.availableWithVersionAndLastChecked"
: "desktop.updates.status.availableWithVersion",
{
version: formatVersion(availableUpdate.latestVersion),
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
},
);
}
if (lastCheckedAt != null) {
return i18n.t("desktop.updates.status.availableWithLastChecked", {
time: formatLastCheckedAt(lastCheckedAt),
});
}
return i18n.t("desktop.updates.status.available");
return formatAvailableStatusText({
availableUpdate,
lastCheckedAt,
formatVersion,
formatLastCheckedAt,
});
}
if (status === "installed") {
return installMessage ?? i18n.t("desktop.updates.status.installed");
}
if (status === "error") {
return i18n.t("desktop.updates.status.failed");
}
if (status === "error") return i18n.t("desktop.updates.status.failed");
return i18n.t("desktop.updates.status.idle");
}
@@ -202,6 +278,16 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
}
}
function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void {
if (progress === null && state.downloadProgress === null) {
return;
}
commit({
...state,
downloadProgress: progress,
});
}
async function checkForUpdates(options?: {
releaseChannel: DesktopReleaseChannel;
intent?: DesktopAppUpdateCheckIntent;
@@ -241,6 +327,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
...state,
status: "error",
availableUpdate: null,
downloadProgress: null,
errorMessage: result.errorMessage,
installMessage: null,
lastCheckedAt: nextLastCheckedAt,
@@ -248,24 +335,13 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
return result;
}
let nextStatus: DesktopAppUpdateStatus;
let nextAvailable: DesktopAppUpdateCheckResult | null;
if (result.readyToInstall) {
nextStatus = "available";
nextAvailable = result;
} else if (result.hasUpdate) {
nextStatus = "pending";
nextAvailable = result;
} else {
nextStatus = "up-to-date";
nextAvailable = null;
}
const outcome = resolveCheckOutcome(result);
commit({
...state,
status: nextStatus,
availableUpdate: nextAvailable,
status: outcome.status,
availableUpdate: outcome.availableUpdate,
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
errorMessage: null,
installMessage: null,
lastCheckedAt: nextLastCheckedAt,
@@ -284,6 +360,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: message,
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
});
@@ -307,10 +384,23 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
releaseChannel: options.releaseChannel,
});
const nextLastCheckedAt = deps.now();
if (!result.installed && result.errorMessage) {
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: result.errorMessage,
installMessage: null,
lastCheckedAt: nextLastCheckedAt,
isInstalling: false,
});
return result;
}
commit({
...state,
status: result.installed ? "installed" : "up-to-date",
availableUpdate: null,
downloadProgress: null,
installMessage: result.message,
lastCheckedAt: nextLastCheckedAt,
isInstalling: false,
@@ -326,6 +416,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: message,
isInstalling: false,
});
@@ -341,6 +432,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
listeners.delete(listener);
};
},
setDownloadProgress,
checkForUpdates,
installUpdate,
};
@@ -1,11 +1,21 @@
import { isElectronRuntime } from "@/desktop/host";
import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events";
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
export interface DesktopAppUpdateDownloadProgress {
version: string | null;
percent: number;
transferred: number;
total: number;
bytesPerSecond: number;
}
export interface DesktopAppUpdateCheckResult {
hasUpdate: boolean;
readyToInstall: boolean;
downloading: boolean;
currentVersion: string | null;
latestVersion: string | null;
body: string | null;
@@ -17,6 +27,7 @@ export interface DesktopAppUpdateInstallResult {
installed: boolean;
version: string | null;
message: string;
errorMessage?: string | null;
}
export interface DesktopRuntimeInfo {
@@ -115,9 +126,13 @@ export async function checkDesktopAppUpdate({
throw new Error("Unexpected response while checking desktop updates.");
}
const hasUpdate = result.hasUpdate === true;
const readyToInstall = result.readyToInstall === true;
return {
hasUpdate: result.hasUpdate === true,
readyToInstall: result.readyToInstall === true,
hasUpdate,
readyToInstall,
downloading:
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
currentVersion: toStringOrNull(result.currentVersion),
latestVersion: toStringOrNull(result.latestVersion),
body: toStringOrNull(result.body),
@@ -126,6 +141,36 @@ export async function checkDesktopAppUpdate({
};
}
export function parseDesktopAppUpdateDownloadProgress(
raw: unknown,
): DesktopAppUpdateDownloadProgress | null {
if (!isRecord(raw)) {
return null;
}
const percent = toNumberOr(Number.NaN, raw.percent);
if (!Number.isFinite(percent)) {
return null;
}
return {
version: toStringOrNull(raw.version),
percent: Math.max(0, Math.min(100, percent)),
transferred: toNumberOr(0, raw.transferred),
total: toNumberOr(0, raw.total),
bytesPerSecond: toNumberOr(0, raw.bytesPerSecond),
};
}
export async function subscribeDesktopAppUpdateDownloadProgress(
handler: (progress: DesktopAppUpdateDownloadProgress | null) => void,
): Promise<DesktopEventUnlisten> {
if (!shouldShowDesktopUpdateSection()) {
return () => {};
}
return listenToDesktopEvent<unknown>("app-update-download-progress", (payload) => {
handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload));
});
}
export async function installDesktopAppUpdate({
releaseChannel,
}: {
@@ -136,10 +181,12 @@ export async function installDesktopAppUpdate({
throw new Error("Unexpected response while installing desktop update.");
}
const errorMessage = toStringOrNull(result.errorMessage);
return {
installed: result.installed === true,
version: toStringOrNull(result.version),
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
...(errorMessage ? { errorMessage } : {}),
};
}
@@ -76,6 +76,50 @@ describe("resolveUpdateCalloutDescriptor", () => {
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
});
it("labels the callout as Download when the update has not been downloaded yet", () => {
const descriptor = resolveUpdateCalloutDescriptor(
input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }),
);
expect(descriptor?.title).toBe("Update available");
expect(descriptor?.body).toEqual({
kind: "available",
versionLabel: "v1.2.3",
readyToInstall: false,
});
expect(descriptor?.actions).toEqual([
{ role: "changelog", label: "What's new" },
{ role: "install", label: "Download", variant: "primary", disabled: false },
]);
});
it("shows download progress while downloading an update", () => {
const descriptor = resolveUpdateCalloutDescriptor(
input({
status: "installing",
isInstalling: true,
downloadProgress: {
version: "1.2.3",
percent: 42.2,
transferred: 42,
total: 100,
bytesPerSecond: 10,
},
}),
);
expect(descriptor?.title).toBe("Downloading update");
expect(descriptor?.body).toEqual({
kind: "downloading",
versionLabel: "v1.2.3",
percent: 42,
});
expect(descriptor?.actions).toEqual([
{ role: "changelog", label: "What's new" },
{ role: "install", label: "Downloading...", variant: "primary", disabled: true },
]);
});
it("shows a retry action and surfaces the error message on error", () => {
const descriptor = resolveUpdateCalloutDescriptor(
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
@@ -1,8 +1,10 @@
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates";
import { i18n } from "@/i18n/i18next";
export type UpdateCalloutBody =
| { kind: "available"; versionLabel: string | null }
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
| { kind: "downloading"; versionLabel: string | null; percent: number }
| { kind: "installing" }
| { kind: "error"; message: string };
@@ -31,7 +33,8 @@ export interface ResolveUpdateCalloutInput {
isDesktopApp: boolean;
status: DesktopAppUpdateStatus;
isInstalling: boolean;
availableUpdate: { latestVersion?: string | null } | null;
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
}
@@ -40,6 +43,59 @@ function formatVersionLabel(latestVersion: string | null | undefined): string |
return `v${latestVersion.replace(/^v/i, "")}`;
}
function resolveCalloutPresentation(input: {
isError: boolean;
isInstalling: boolean;
readyToInstall: boolean;
latestVersion: string | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined;
errorMessage: string | null;
}): { title: string; body: UpdateCalloutBody } {
if (input.isInstalling && input.downloadProgress != null) {
return {
title: i18n.t("desktop.updates.callout.downloadingTitle"),
body: {
kind: "downloading",
versionLabel: formatVersionLabel(input.latestVersion),
percent: Math.round(input.downloadProgress.percent),
},
};
}
if (input.isInstalling) {
return {
title: i18n.t("desktop.updates.callout.installingTitle"),
body: { kind: "installing" },
};
}
if (input.isError) {
return {
title: i18n.t("desktop.updates.callout.failedTitle"),
body: {
kind: "error",
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
},
};
}
const versionLabel = formatVersionLabel(input.latestVersion);
return {
title: i18n.t("desktop.updates.callout.availableTitle"),
body: input.readyToInstall
? { kind: "available", versionLabel }
: { kind: "available", versionLabel, readyToInstall: false },
};
}
function resolveInstallActionLabel(input: {
isDownloading: boolean;
isInstalling: boolean;
readyToInstall: boolean;
}): string {
if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction");
if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction");
if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart");
return i18n.t("desktop.updates.callout.downloadAndRestart");
}
export function resolveUpdateCalloutDescriptor(
input: ResolveUpdateCalloutInput,
): UpdateCalloutDescriptor | null {
@@ -50,26 +106,22 @@ export function resolveUpdateCalloutDescriptor(
const isError = input.status === "error";
const isInstalling = input.isInstalling;
const isDownloading = isInstalling && input.downloadProgress != null;
const isAvailable = !isInstalling && !isError;
const readyToInstall = input.availableUpdate?.readyToInstall !== false;
const latestVersion = input.availableUpdate?.latestVersion ?? null;
const latestVersion =
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
let title: string;
let body: UpdateCalloutBody;
if (isInstalling) {
title = i18n.t("desktop.updates.callout.installingTitle");
body = { kind: "installing" };
} else if (isError) {
title = i18n.t("desktop.updates.callout.failedTitle");
body = {
kind: "error",
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
};
} else {
title = i18n.t("desktop.updates.callout.availableTitle");
body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) };
}
const { title, body } = resolveCalloutPresentation({
isError,
isInstalling,
readyToInstall,
latestVersion,
downloadProgress: input.downloadProgress,
errorMessage: input.errorMessage,
});
const actions: UpdateCalloutActionDescriptor[] = [
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
@@ -79,9 +131,7 @@ export function resolveUpdateCalloutDescriptor(
} else {
actions.push({
role: "install",
label: isInstalling
? i18n.t("desktop.updates.callout.installingAction")
: i18n.t("desktop.updates.callout.installAndRestart"),
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
variant: "primary",
disabled: isInstalling,
});
@@ -34,9 +34,12 @@ type InstallOutcome =
function buildCheckResult(
overrides: Partial<DesktopAppUpdateCheckResult> = {},
): DesktopAppUpdateCheckResult {
const hasUpdate = overrides.hasUpdate ?? false;
const readyToInstall = overrides.readyToInstall ?? false;
return {
hasUpdate: false,
readyToInstall: false,
hasUpdate,
readyToInstall,
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
currentVersion: null,
latestVersion: null,
body: null,
@@ -1,7 +1,8 @@
import { Gift } from "lucide-react-native";
import { type ReactNode, useEffect, useRef } from "react";
import { type ReactNode, useEffect, useMemo, useRef } from "react";
import { View } from "react-native";
import { useTranslation } from "react-i18next";
import { useUnistyles } from "react-native-unistyles";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
type SidebarCalloutAction,
SidebarCalloutDescriptionText,
@@ -19,9 +20,24 @@ import { openChangelog } from "@/changelog";
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
if (body.kind === "downloading") {
return (
<UpdateDownloadingDescription
versionLabel={body.versionLabel ?? undefined}
percent={body.percent}
t={t}
/>
);
}
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
if (body.kind === "error") return body.message;
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
return (
<UpdateAvailableDescription
versionLabel={body.versionLabel ?? undefined}
readyToInstall={body.readyToInstall !== false}
t={t}
/>
);
}
function materializeActions(
@@ -42,8 +58,11 @@ export function UpdateCalloutSource() {
const { theme } = useUnistyles();
const {
isDesktopApp,
updateMode,
isLoadingSettings,
status,
availableUpdate,
downloadProgress,
errorMessage,
checkForUpdates,
installUpdate,
@@ -58,7 +77,7 @@ export function UpdateCalloutSource() {
void checkForUpdates();
});
useEffect(() => {
if (!isDesktopApp) return;
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
void checkForUpdates({ intent: "automatic", silent: true });
@@ -71,7 +90,7 @@ export function UpdateCalloutSource() {
clearInterval(intervalRef.current);
}
};
}, [isDesktopApp, checkForUpdates]);
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
useEffect(() => {
const descriptor = resolveUpdateCalloutDescriptor({
@@ -79,6 +98,7 @@ export function UpdateCalloutSource() {
status,
isInstalling,
availableUpdate,
downloadProgress,
errorMessage,
});
if (!descriptor) return;
@@ -103,6 +123,7 @@ export function UpdateCalloutSource() {
}, [
availableUpdate,
callouts,
downloadProgress,
errorMessage,
install,
isDesktopApp,
@@ -117,23 +138,94 @@ export function UpdateCalloutSource() {
return null;
}
function formatAvailableSummary(
t: ReturnType<typeof useTranslation>["t"],
versionLabel: string | undefined,
readyToInstall: boolean,
): string {
if (readyToInstall) {
return versionLabel
? t("desktop.updates.callout.versionReady", { version: versionLabel })
: t("desktop.updates.callout.newVersionReady");
}
return versionLabel
? t("desktop.updates.callout.versionAvailable", { version: versionLabel })
: t("desktop.updates.callout.newVersionAvailable");
}
function UpdateAvailableDescription({
versionLabel,
readyToInstall,
t,
}: {
versionLabel?: string;
readyToInstall: boolean;
t: ReturnType<typeof useTranslation>["t"];
}) {
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
return (
<>
<SidebarCalloutDescriptionText>
{versionLabel
? t("desktop.updates.callout.versionReady", { version: versionLabel })
: t("desktop.updates.callout.newVersionReady")}
</SidebarCalloutDescriptionText>
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
<SidebarCalloutDescriptionText>
{t("desktop.updates.callout.restartWarning")}
</SidebarCalloutDescriptionText>
</>
);
}
function UpdateDownloadingDescription({
versionLabel,
percent,
t,
}: {
versionLabel?: string;
percent: number;
t: ReturnType<typeof useTranslation>["t"];
}) {
const clampedPercent = Math.max(0, Math.min(100, percent));
const accessibilityValue = useMemo(
() => ({ min: 0, max: 100, now: clampedPercent }),
[clampedPercent],
);
const progressFillStyle = useMemo(
() => [styles.progressFill, { width: `${clampedPercent}%` as const }],
[clampedPercent],
);
return (
<View style={styles.progressContainer}>
<SidebarCalloutDescriptionText>
{versionLabel
? t("desktop.updates.callout.downloadingVersionDescription", {
version: versionLabel,
percent: clampedPercent,
})
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
</SidebarCalloutDescriptionText>
<View
style={styles.progressTrack}
accessibilityRole="progressbar"
accessibilityValue={accessibilityValue}
>
<View style={progressFillStyle} />
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
progressContainer: {
gap: theme.spacing[2],
},
progressTrack: {
height: 4,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface3,
overflow: "hidden",
},
progressFill: {
height: "100%",
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.accent,
},
}));
@@ -4,11 +4,13 @@ import {
formatVersionWithPrefix,
installDesktopAppUpdate,
shouldShowDesktopUpdateSection,
subscribeDesktopAppUpdateDownloadProgress,
type DesktopAppUpdateCheckResult,
type DesktopAppUpdateCheckIntent,
type DesktopAppUpdateDownloadProgress,
type DesktopAppUpdateInstallResult,
} from "@/desktop/updates/desktop-updates";
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
import {
PENDING_RECHECK_MS,
@@ -22,9 +24,12 @@ export type { DesktopAppUpdateStatus };
export interface UseDesktopAppUpdaterReturn {
isDesktopApp: boolean;
updateMode: DesktopUpdateMode;
isLoadingSettings: boolean;
status: DesktopAppUpdateStatus;
statusText: string;
availableUpdate: DesktopAppUpdateCheckResult | null;
downloadProgress: DesktopAppUpdateDownloadProgress | null;
errorMessage: string | null;
lastCheckedAt: number | null;
isChecking: boolean;
@@ -38,8 +43,9 @@ export interface UseDesktopAppUpdaterReturn {
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
const isDesktopApp = shouldShowDesktopUpdateSection();
const { settings: desktopSettings } = useDesktopSettings();
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
const releaseChannel = desktopSettings.releaseChannel;
const updateMode = desktopSettings.updates.mode;
const reportError = useDesktopIpcErrorReporter();
const updater = useMemo(
@@ -84,13 +90,40 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
useEffect(() => {
if (!isDesktopApp) {
return undefined;
}
let active = true;
let unlisten: (() => void) | null = null;
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
if (active) {
updater.setDownloadProgress(progress);
}
})
.then((cleanup) => {
if (active) {
unlisten = cleanup;
} else {
cleanup();
}
return undefined;
})
.catch(() => undefined);
return () => {
active = false;
unlisten?.();
};
}, [isDesktopApp, updater]);
useEffect(() => {
if (!isDesktopApp || isLoadingSettings || updateMode === "off") {
return;
}
void checkForUpdates({ intent: "automatic", silent: true });
}, [checkForUpdates, isDesktopApp]);
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
useEffect(() => {
if (!isDesktopApp || snapshot.status !== "pending") {
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
return undefined;
}
@@ -101,20 +134,24 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
return () => {
clearInterval(intervalId);
};
}, [checkForUpdates, isDesktopApp, snapshot.status]);
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
return {
isDesktopApp,
updateMode,
isLoadingSettings,
status: snapshot.status,
statusText: formatStatusText({
status: snapshot.status,
availableUpdate: snapshot.availableUpdate,
downloadProgress: snapshot.downloadProgress,
installMessage: snapshot.installMessage,
lastCheckedAt: snapshot.lastCheckedAt,
formatVersion: formatVersionWithPrefix,
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
}),
availableUpdate: snapshot.availableUpdate,
downloadProgress: snapshot.downloadProgress,
errorMessage: snapshot.errorMessage,
lastCheckedAt: snapshot.lastCheckedAt,
isChecking: snapshot.isChecking,
+347 -2
View File
@@ -7,6 +7,8 @@ import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
} from "./policy";
import { deriveMergeCapability, type ForgeSpecificStatusFacts } from "./merge-capability";
@@ -59,9 +61,11 @@ function githubStatus(overrides: Partial<GithubMergeFactsFixture> = {}): GithubM
function createInput(
overrides: Partial<Omit<BuildGitActionsInput, "mergeCapability">> & {
pullRequestGithub?: unknown;
// Shorthand for a branch that both Pull and Push have a remote for.
hasRemote?: boolean;
} = {},
): BuildGitActionsInput {
const { pullRequestGithub = null, ...rest } = overrides;
const { pullRequestGithub = null, hasRemote = false, ...rest } = overrides;
return {
isGit: true,
githubFeaturesEnabled: true,
@@ -75,7 +79,9 @@ function createInput(
pullRequestIsMerged: false,
pullRequestMergeable: "UNKNOWN",
mergeCapability: deriveMergeCapability(pullRequestGithub),
hasRemote: false,
hasPullRemote: hasRemote,
hasPushRemote: hasRemote,
upstream: "tracked",
isPaseoOwnedWorktree: false,
isOnBaseBranch: true,
canMergeLocally: true,
@@ -169,6 +175,14 @@ function createInput(
};
}
function pushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "push");
}
function pullAndPushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "pull-and-push");
}
describe("git-actions-policy", () => {
afterEach(async () => {
await i18n.changeLanguage("en");
@@ -346,6 +360,7 @@ describe("git-actions-policy", () => {
const actions = buildGitActions(
createInput({
hasRemote: true,
upstream: "none",
isPaseoOwnedWorktree: true,
isOnBaseBranch: false,
aheadCount: 1,
@@ -361,6 +376,336 @@ 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, hasPushRemote: 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",
);
});
});
// The daemon reports where Pull and Push go for the branch, so the remote's name never matters.
describe("a branch that tracks a remote other than origin", () => {
const tracksDorasMono = readSyncRemotes({
hasRemote: false,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("offers Push when the branch is ahead", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
expect(pushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
});
it("offers Pull when the branch is behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 0, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
});
it("offers Pull first and Pull and push when the branch is ahead and behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available yet because there are newer changes to bring in first",
);
});
// `feature` tracking `upstream/main`: the daemon reports a pull remote and no push remote.
const pullOnly = readSyncRemotes({
hasRemote: false,
pullRemote: "upstream",
pushRemote: null,
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("does not offer Push when it would land on a differently named upstream branch", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary?.id).not.toBe("push");
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available here because this branch is not connected to a remote yet",
);
});
it("still offers Pull for that branch, and not Pull and push", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)?.unavailableMessage).toBe(
"Pull and push isn't available here because this branch is not connected to a remote yet",
);
});
});
describe("readSyncRemotes", () => {
it("uses the remotes the daemon reports", () => {
expect(
readSyncRemotes({
hasRemote: true,
pullRemote: null,
pushRemote: "origin",
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
).toEqual({ hasPullRemote: false, hasPushRemote: true });
});
// The rest covers a daemon that predates pullRemote and pushRemote.
const tracked = {
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
} as const;
const neverPushed = {
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
} as const;
it("pulls and pushes a tracked branch on an older daemon only when the checkout has origin", () => {
expect(readSyncRemotes({ ...tracked, hasRemote: true })).toEqual({
hasPullRemote: true,
hasPushRemote: true,
});
expect(readSyncRemotes({ ...tracked, hasRemote: false })).toEqual({
hasPullRemote: false,
hasPushRemote: false,
});
});
it("makes a regular checkout's first push only where an older daemon confirmed it", () => {
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: "origin" }),
).toMatchObject({ hasPushRemote: true });
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: null }),
).toMatchObject({ hasPushRemote: false });
});
it("keeps a Paseo worktree's first push on an older daemon that reports no first push remote", () => {
expect(
readSyncRemotes({
...neverPushed,
hasRemote: true,
firstPushRemote: null,
isPaseoOwnedWorktree: true,
}),
).toMatchObject({ hasPushRemote: true });
});
});
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({
+84 -16
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,7 +77,60 @@ export function canMergeIntoLocalBase(
return currentBranch !== localTarget;
}
export interface BuildGitActionsInput {
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 SyncRemotes {
/** Pull has a remote to fetch the branch from. Not limited to origin. */
hasPullRemote: boolean;
/** Push has a remote to send the branch to. Not limited to origin. */
hasPushRemote: boolean;
}
export function readSyncRemotes(
status: Pick<
CheckoutStatusPayload,
| "pullRemote"
| "pushRemote"
| "hasRemote"
| "firstPushRemote"
| "upstreamState"
| "aheadOfOrigin"
| "isPaseoOwnedWorktree"
>,
): SyncRemotes {
if (status.pullRemote !== undefined && status.pushRemote !== undefined) {
return { hasPullRemote: status.pullRemote !== null, hasPushRemote: status.pushRemote !== null };
}
// COMPAT(checkoutSyncRemotes): added in v0.17.5, remove after 2027-05-24 once the daemon floor
// reports pullRemote and pushRemote. Older daemons pull and push only in checkouts that have
// origin. They make a first push from a Paseo worktree, and from a regular checkout only where
// they report firstPushRemote.
const isFirstPush = readUpstreamState(status) === "none";
const canFirstPush = status.isPaseoOwnedWorktree || (status.firstPushRemote ?? null) !== null;
return {
hasPullRemote: status.hasRemote,
hasPushRemote: status.hasRemote && (!isFirstPush || canFirstPush),
};
}
export interface BuildGitActionsInput extends SyncRemotes {
isGit: boolean;
githubFeaturesEnabled: boolean;
/** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */
@@ -88,7 +145,7 @@ export interface BuildGitActionsInput {
pullRequestIsMerged: boolean;
pullRequestMergeable: PullRequestMergeable;
mergeCapability: MergeCapability | null;
hasRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
canMergeLocally: boolean;
@@ -546,20 +603,28 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable
}
function canPull(input: BuildGitActionsInput): boolean {
return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
}
function canPush(input: BuildGitActionsInput): boolean {
return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
}
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.
return input.aheadCount > 0;
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 {
@@ -642,7 +707,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean {
}
function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasRemote) {
if (!input.hasPullRemote) {
return i18n.t("workspace.git.actions.unavailable.pullNoRemote");
}
if (input.hasUncommittedChanges) {
@@ -658,20 +723,23 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi
}
function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasRemote) {
if (!input.hasPushRemote) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
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");
}
return i18n.t("workspace.git.actions.unavailable.pushNothing");
}
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasRemote) {
if (!input.hasPullRemote || !input.hasPushRemote) {
return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote");
}
if (input.hasUncommittedChanges) {
+19 -6
View File
@@ -15,9 +15,13 @@ import {
isCurrentBranchBase,
canMergeIntoLocalBase,
narrowPullRequestState,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
type GitAction,
type GitActions,
type GitUpstreamState,
type SyncRemotes,
} from "@/git/policy";
import { deriveMergeCapability } from "@/git/merge-capability";
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
@@ -121,14 +125,16 @@ interface DeriveGitActionsStateArgs {
baseRef: string | undefined;
}
interface DerivedGitActionsState {
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
interface DerivedGitActionsState extends SyncRemotes {
actionsDisabled: boolean;
aheadCount: number;
behindBaseCount: number;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
hasPullRequest: boolean;
hasRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
canMergeLocally: boolean;
@@ -179,7 +185,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
actionsDisabled,
...extractGitCommitCounts(gitStatus),
hasPullRequest: Boolean(prStatus?.url),
hasRemote: gitStatus?.hasRemote ?? false,
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
isPaseoOwnedWorktree,
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
@@ -667,7 +674,9 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
aheadOfOrigin,
behindOfOrigin,
hasPullRequest,
hasRemote,
hasPullRemote,
hasPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
canMergeLocally,
@@ -698,7 +707,9 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
pullRequestIsMerged: prStatus?.isMerged ?? false,
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
hasRemote,
hasPullRemote,
hasPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
canMergeLocally,
@@ -806,7 +817,9 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
};
}, [
isGit,
hasRemote,
hasPullRemote,
hasPushRemote,
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}.`);
}
}
@@ -32,6 +32,9 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
const DEFAULT_DESKTOP: DesktopSettings = {
releaseChannel: "stable",
updates: {
mode: "automatic",
},
notifications: {
playSound: true,
},
@@ -656,6 +656,7 @@ describe("loadSettingsFromStorage", () => {
isElectron: true,
settings: {
releaseChannel: "beta",
updates: { mode: "automatic" },
notifications: { playSound: true },
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
},
+94 -8
View File
@@ -4,6 +4,7 @@ import {
defaultHostAppearance,
normalizeStoredHostAppearance,
resolveHostBadgeDisplay,
resolveHostIcon,
selectHostBadges,
} from "@/hosts/appearance";
@@ -16,7 +17,7 @@ function host(
}
describe("normalizeStoredHostAppearance", () => {
it("defaults when the stored registry predates the field or holds junk", () => {
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
const expected = { color: "none", badgeDisplay: null };
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
@@ -24,13 +25,79 @@ describe("normalizeStoredHostAppearance", () => {
expect(normalizeStoredHostAppearance({})).toEqual(expected);
expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected);
expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected);
expect("icon" in defaultHostAppearance()).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
it("preserves an unknown stored icon on disk while falling back at render time", () => {
const normalized = normalizeStoredHostAppearance({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(normalized).toEqual({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(resolveHostIcon({ appearance: normalized })).toBe("server");
expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe(
"laptop",
);
});
it("keeps icon absent on stored entries that predate host icons", () => {
const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" });
expect(normalized).toEqual({
color: "teal",
badgeDisplay: "icon",
});
expect("icon" in normalized).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(
normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }),
).toEqual({
color: "teal",
icon: "laptop",
badgeDisplay: "icon",
});
});
});
describe("resolveHostIcon", () => {
it("prefers an explicit user icon over daemon auto-detection", () => {
expect(
resolveHostIcon({
appearance: { color: "none", icon: "workstation", badgeDisplay: null },
detectedMachineKind: "laptop",
}),
).toBe("workstation");
});
it("uses the daemon-detected machine kind while the user icon is auto (null)", () => {
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "laptop",
}),
).toBe("laptop");
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "container",
}),
).toBe("container");
});
it("falls back to server when the detected machine kind is absent or unknown", () => {
expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }),
).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }),
).toBe("server");
});
});
@@ -50,13 +117,13 @@ describe("resolveHostBadgeDisplay", () => {
it("prefers an explicit choice over either default", () => {
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "icon" },
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
isLocalHost: true,
}),
).toBe("icon");
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "hidden" },
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
isLocalHost: false,
}),
).toBe("hidden");
@@ -72,7 +139,7 @@ describe("resolveHostBadgeDisplay", () => {
).toBeNull();
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "icon" },
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
isLocalHost: false,
localHostResolutionPending: true,
}),
@@ -93,7 +160,7 @@ describe("selectHostBadges", () => {
it("omits a host the user hid and keeps its sibling", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
host("beta", "Beta"),
],
localServerId: null,
@@ -104,13 +171,14 @@ describe("selectHostBadges", () => {
serverId: "beta",
label: "Beta",
color: "none",
icon: "server",
showLabel: true,
});
});
it("keeps an icon-only host in the map without its label", () => {
const badges = selectHostBadges({
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
localServerId: null,
enabled: true,
});
@@ -118,6 +186,7 @@ describe("selectHostBadges", () => {
serverId: "alpha",
label: "Alpha",
color: "teal",
icon: "mini",
showLabel: false,
});
});
@@ -150,4 +219,21 @@ describe("selectHostBadges", () => {
});
expect(badges.size).toBe(0);
});
it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha"),
host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }),
],
localServerId: null,
detectedMachineKindByServerId: new Map([
["alpha", "laptop"],
["beta", "cloud"],
]),
enabled: true,
});
expect(badges.get("alpha")?.icon).toBe("laptop");
expect(badges.get("beta")?.icon).toBe("workstation");
});
});
+65 -4
View File
@@ -6,25 +6,69 @@ export type HostColor = "none" | IdentityColorName;
export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES];
export const HOST_ICONS = [
"server",
"laptop",
"desktop",
"mini",
"workstation",
"cloud",
"container",
"board",
"terminal",
] as const;
export type HostIcon = (typeof HOST_ICONS)[number];
export const DEFAULT_HOST_ICON: HostIcon = "server";
const HOST_ICON_SET = new Set<string>(HOST_ICONS);
export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null {
const trimmed = value?.trim();
if (trimmed && HOST_ICON_SET.has(trimmed)) {
return trimmed as HostIcon;
}
return null;
}
export type HostBadgeDisplay = "name" | "icon" | "hidden";
export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"];
/**
* Per-device host presentation. `badgeDisplay` is null while the user has not chosen,
* because the default differs by host (local hides, remote shows) and local-ness is only
* knowable from a desktop-only async query — never at parse time.
* Per-device host presentation.
* - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible
* with older builds whose stored appearance schema is strict. An unknown icon string written by
* a newer build is preserved on disk and falls back at render time via `resolveHostIcon`.
* - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for
* remote) without baking runtime facts at parse time.
*/
export interface HostAppearance {
color: HostColor;
icon?: string;
badgeDisplay: HostBadgeDisplay | null;
}
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
const StoredHostAppearanceSchema = z.strictObject({
color: z.enum(["none", ...IDENTITY_COLOR_NAMES]),
// Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon
// added by a newer build survives read/write instead of being dropped or overwritten.
icon: z.string().nullable().optional(),
badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(),
});
export const HostAppearanceSchema = StoredHostAppearanceSchema.transform(
(value): HostAppearance => {
const icon = value.icon?.trim();
return {
color: value.color,
...(icon ? { icon } : {}),
badgeDisplay: value.badgeDisplay,
};
},
);
export function defaultHostAppearance(): HostAppearance {
return { color: "none", badgeDisplay: null };
}
@@ -34,6 +78,17 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance {
return result.success ? result.data : defaultHostAppearance();
}
export function resolveHostIcon(input: {
appearance: HostAppearance;
detectedMachineKind?: string | null;
}): HostIcon {
return (
normalizeDetectedHostIcon(input.appearance.icon) ??
normalizeDetectedHostIcon(input.detectedMachineKind) ??
DEFAULT_HOST_ICON
);
}
export function resolveHostBadgeDisplay(input: {
appearance: HostAppearance;
isLocalHost: boolean;
@@ -52,6 +107,7 @@ export interface HostBadgeModel {
serverId: string;
label: string;
color: HostColor;
icon: HostIcon;
showLabel: boolean;
}
@@ -66,6 +122,7 @@ export function selectHostBadges(input: {
hosts: readonly HostAppearanceSource[];
localServerId: string | null;
localHostResolutionPending?: boolean;
detectedMachineKindByServerId?: ReadonlyMap<string, string | null>;
enabled: boolean;
}): ReadonlyMap<string, HostBadgeModel> {
const badges = new Map<string, HostBadgeModel>();
@@ -85,6 +142,10 @@ export function selectHostBadges(input: {
serverId: host.serverId,
label: host.label.trim() || host.serverId,
color: host.appearance.color,
icon: resolveHostIcon({
appearance: host.appearance,
detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null,
}),
showLabel: display === "name",
});
}
@@ -0,0 +1,134 @@
import { describe, expect, it } from "vitest";
import {
describeActiveConnection,
describeHostConnection,
formatConnectionEndpoint,
isTailscaleEndpoint,
} from "./connection-display";
describe("isTailscaleEndpoint", () => {
it("recognizes MagicDNS .ts.net hostnames with or without ports", () => {
expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true);
expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true);
expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true);
expect(isTailscaleEndpoint(".ts.net")).toBe(false);
});
it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => {
expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true);
expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true);
expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true);
expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false);
expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true);
});
it("does not misclassify LAN, localhost, or ordinary domains", () => {
expect(isTailscaleEndpoint("localhost:6767")).toBe(false);
expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false);
expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false);
expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false);
});
});
describe("describeActiveConnection", () => {
it("describes local socket and pipe connections without exposing paths", () => {
expect(
describeActiveConnection({
type: "directSocket",
endpoint: "/tmp/paseo.sock",
display: "socket",
}),
).toEqual({ kind: "local" });
expect(
describeActiveConnection({
type: "directPipe",
endpoint: "\\\\.\\pipe\\paseo",
display: "pipe",
}),
).toEqual({ kind: "local" });
});
it("describes loopback TCP on the local host as local, and remote loopback as direct", () => {
const loopback = {
type: "directTcp",
endpoint: "localhost:6767",
display: "localhost:6767",
} as const;
expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" });
expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({
kind: "direct",
endpoint: "localhost:6767",
});
});
it("strips standard web ports on relay, tailscale, and direct connections", () => {
expect(
describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "devbox.example.com:443",
display: "devbox.example.com:443",
}),
).toEqual({ kind: "direct", endpoint: "devbox.example.com" });
});
it("preserves SSH and routed targets", () => {
expect(
describeActiveConnection({
type: "remoteSsh",
endpoint: "mo@workstation",
display: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
expect(
describeActiveConnection({
type: "routed",
endpoint: "srv_origin",
display: "via srv_origin",
}),
).toEqual({ kind: "routed", endpoint: "srv_origin" });
});
it("strips default HTTP/HTTPS ports only", () => {
expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh");
expect(formatConnectionEndpoint("example.com:80")).toBe("example.com");
expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767");
});
it("describes configured host connections before an active connection is online", () => {
expect(
describeHostConnection({
id: "direct:mac-mini.tail123.ts.net:6767",
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeHostConnection({
id: "relay:wss:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
useTls: true,
daemonPublicKeyB64: "key",
}),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeHostConnection({
id: "ssh:mo%40workstation::",
type: "remoteSsh",
host: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
});
});
@@ -0,0 +1,120 @@
import type { ActiveConnection } from "@/runtime/host-runtime";
import type { HostConnection } from "@/types/host-connection";
export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed";
export interface HostConnectionDisplay {
kind: HostConnectionKind;
/** Address shown beside the connection kind. Omitted for local transports. */
endpoint?: string;
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
export function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
function extractEndpointHost(endpoint: string): string {
const trimmed = endpoint.trim().toLowerCase();
if (!trimmed) return "";
const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
const authority = withoutScheme.split("/")[0] ?? "";
const hostPort = authority.includes("@")
? authority.slice(authority.lastIndexOf("@") + 1)
: authority;
if (hostPort.startsWith("[")) {
const closeBracket = hostPort.indexOf("]");
return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort;
}
const firstColon = hostPort.indexOf(":");
const lastColon = hostPort.lastIndexOf(":");
if (firstColon !== -1 && firstColon === lastColon) {
return hostPort.slice(0, firstColon);
}
return hostPort;
}
function isTailscaleIpv4(host: string): boolean {
const parts = host.split(".");
if (parts.length !== 4) return false;
const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN));
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
return false;
}
// Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10.
return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
}
function isTailscaleIpv6(host: string): boolean {
return host.startsWith("fd7a:115c:a1e0:");
}
export function isTailscaleEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
if (!host) return false;
if (host.endsWith(".ts.net") && host.length > ".ts.net".length) {
return true;
}
return isTailscaleIpv4(host) || isTailscaleIpv6(host);
}
export function isLoopbackEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
return host === "localhost" || host === "127.0.0.1" || host === "::1";
}
export function describeActiveConnection(
connection: ActiveConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.endpoint };
case "routed":
return { kind: "routed", endpoint: connection.endpoint };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
export function describeHostConnection(
connection: HostConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.host };
case "routed":
return { kind: "routed", endpoint: connection.originServerId };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
+8 -29
View File
@@ -1,9 +1,8 @@
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Server } from "lucide-react-native";
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { StyleSheet } from "react-native-unistyles";
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
/**
* The glyph size the badge draws at. Rows that place the badge alongside their own glyphs
@@ -11,30 +10,9 @@ import type { Theme } from "@/styles/theme";
*/
export const HOST_BADGE_ICON_SIZE = 12;
const ThemedServer = withUnistyles(Server);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable mapping per host color for the life of the module — a fresh `uniProps` identity
// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the
// mapping rather than baked in, so a theme change repaints the glyph without a React render.
//
// Glyph and label share one color, so a badge reads as one object rather than a colored icon
// with an unrelated grey word beside it.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
/**
* Which machine something lives on, drawn the same way everywhere it appears: a server glyph
* and, when the host is configured to show one, its name — both in the host's identity color.
* Which machine something lives on, drawn the same way everywhere it appears: the host's device
* glyph and, when the host is configured to show one, its name — both in the host's identity color.
*
* A hostname is the least interesting thing on any line that carries it and the only one whose
* length nobody chose, so the badge yields space before its neighbours rather than alongside
@@ -47,10 +25,11 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
testID={`host-badge-${badge.serverId}`}
accessibilityLabel={badge.label}
>
<ThemedServer
<HostIconGlyph
icon={badge.icon}
color={badge.color}
size={HOST_BADGE_ICON_SIZE}
style={styles.icon}
uniProps={HOST_ICON_MAPPINGS[badge.color]}
/>
{badge.showLabel ? (
<Text style={[styles.label, labelColorStyle(badge.color)]} numberOfLines={1}>
+66 -27
View File
@@ -7,14 +7,16 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { Server } from "lucide-react-native";
import { create } from "zustand";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
import { HostStatusDot } from "@/components/host-status-dot";
import { isWeb } from "@/constants/platform";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { resolveHostIcon } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
import { useHosts } from "@/runtime/host-runtime";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
type HostFilter = (host: HostProfile) => boolean;
@@ -101,36 +103,52 @@ function HostChooserRow({
active: boolean;
onChooseHost: (serverId: string) => void;
}) {
const { theme } = useUnistyles();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
const rowStyle = useCallback(
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
({ pressed }: PressableStateCallbackType) => [
styles.row,
(active || hovered || pressed) && styles.rowActive,
],
[active],
[active, hovered],
);
return (
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDotSlot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
<Text style={styles.rowSubtitle} numberOfLines={1}>
{host.serverId}
</Text>
</View>
<Server size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
<View onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave}>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<View style={styles.rowHeader}>
<HostIconGlyph
icon={resolvedIcon}
color={host.appearance.color}
size={14}
style={styles.rowGlyph}
/>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
</View>
<HostConnectionLine serverId={host.serverId} />
</View>
<View style={styles.rowTrailing}>
<HostLatencyLabel serverId={host.serverId} />
</View>
</Pressable>
</View>
);
}
@@ -161,6 +179,7 @@ export function HostChooserModal() {
useEffect(() => {
if (!request) return;
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
inputRef.current?.replaceText("");
setQuery("");
setActiveIndex(0);
@@ -328,7 +347,7 @@ const styles = StyleSheet.create((theme) => ({
},
row: {
flexDirection: "row",
alignItems: "center",
alignItems: "flex-start",
gap: theme.spacing[3],
minHeight: 56,
paddingHorizontal: theme.spacing[4],
@@ -337,19 +356,39 @@ const styles = StyleSheet.create((theme) => ({
rowActive: {
backgroundColor: theme.colors.surface1,
},
rowTrailing: {
flexDirection: "row",
alignItems: "center",
height: 20,
flexShrink: 0,
},
rowIconSlot: {
width: 18,
width: 16,
height: 20,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
rowText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
rowHeader: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
rowGlyph: {
flexShrink: 0,
},
rowTitle: {
flex: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: 20,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
@@ -0,0 +1,77 @@
import type { ReactElement } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import {
Cloud,
Computer,
Container,
Cpu,
Laptop,
Monitor,
PcCase,
Server,
Terminal,
} from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
const ThemedServer = withUnistyles(Server);
const ThemedLaptop = withUnistyles(Laptop);
const ThemedMonitor = withUnistyles(Monitor);
const ThemedComputer = withUnistyles(Computer);
const ThemedPcCase = withUnistyles(PcCase);
const ThemedCloud = withUnistyles(Cloud);
const ThemedContainer = withUnistyles(Container);
const ThemedCpu = withUnistyles(Cpu);
const ThemedTerminal = withUnistyles(Terminal);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
// mapping keeps theme switches off React's render path.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
export function HostIconGlyph({
icon = DEFAULT_HOST_ICON,
color = "none",
size = 16,
style,
}: {
icon?: HostIcon;
color?: HostColor;
size?: number;
style?: StyleProp<ViewStyle>;
}): ReactElement {
const uniProps = HOST_ICON_MAPPINGS[color];
switch (icon) {
case "laptop":
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
case "desktop":
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
case "mini":
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
case "workstation":
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
case "cloud":
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
case "container":
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
case "board":
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
case "terminal":
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
case "server":
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
}
}
+215
View File
@@ -0,0 +1,215 @@
import { useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TailscaleIcon } from "@/components/icons/tailscale-icon";
import {
describeActiveConnection,
describeHostConnection,
type HostConnectionKind,
} from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { HostProfile } from "@/types/host-connection";
import { formatLatency } from "@/utils/latency";
export { HostIconGlyph };
const CONNECTION_GLYPH_SIZE = 11;
const ThemedMonitor = withUnistyles(Monitor);
const ThemedTerminal = withUnistyles(Terminal);
const ThemedGlobe = withUnistyles(Globe);
const ThemedNetwork = withUnistyles(Network);
const ThemedWaypoints = withUnistyles(Waypoints);
const ThemedTailscale = withUnistyles(TailscaleIcon);
const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement {
switch (kind) {
case "local":
return (
<ThemedMonitor
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "relay":
return (
<ThemedGlobe
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "tailscale":
return <ThemedTailscale size={CONNECTION_GLYPH_SIZE} uniProps={extraMutedMapping} />;
case "ssh":
return (
<ThemedTerminal
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "routed":
return (
<ThemedWaypoints
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "direct":
return (
<ThemedNetwork
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
}
}
function resolvePreferredConnection(host: HostProfile | undefined) {
if (!host || host.connections.length === 0) return null;
if (host.preferredConnectionId) {
const preferred = host.connections.find(
(connection) => connection.id === host.preferredConnectionId,
);
if (preferred) return preferred;
}
return host.connections[0] ?? null;
}
export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const localServerId = useLocalDaemonServerId();
const hosts = useHosts();
const activeConnection = snapshot?.activeConnection ?? null;
const hostProfile = useMemo(
() => hosts.find((candidate) => candidate.serverId === serverId),
[hosts, serverId],
);
const fallbackConnection = useMemo(
() => (activeConnection ? null : resolvePreferredConnection(hostProfile)),
[activeConnection, hostProfile],
);
const described = useMemo(() => {
const options = { isLocalHost: serverId === localServerId };
if (activeConnection) {
return describeActiveConnection(activeConnection, options);
}
if (fallbackConnection) {
return describeHostConnection(fallbackConnection, options);
}
return null;
}, [activeConnection, fallbackConnection, localServerId, serverId]);
if (!described) {
return null;
}
const endpoint =
described.kind === "routed" && described.endpoint
? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint)
: described.endpoint;
return (
<View style={styles.connectionRow}>
<View style={styles.linkIconSlot}>
<ConnectionKindGlyph kind={described.kind} />
</View>
<Text style={styles.connectionKind} numberOfLines={1}>
{t(`settings.host.connectionKinds.${described.kind}`)}
</Text>
{endpoint ? (
<Text style={styles.connectionEndpoint} numberOfLines={1}>
{endpoint}
</Text>
) : null}
</View>
);
}
export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const status = snapshot?.connectionStatus;
const activeConnectionId = snapshot?.activeConnectionId;
const activeProbe = activeConnectionId
? snapshot?.probeByConnectionId.get(activeConnectionId)
: undefined;
const latencyMs =
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
if (latencyMs !== null) {
return (
<Text style={styles.latency} numberOfLines={1}>
{formatLatency(latencyMs)}
</Text>
);
}
if (status === "offline" || status === "error") {
return (
<Text style={styles.statusText} numberOfLines={1}>
{t("common.connectionStatus.offline")}
</Text>
);
}
return null;
}
const styles = StyleSheet.create((theme) => ({
connectionRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
// Matches the 14px host icon width on the row above so connection text aligns on the same rail.
linkIconSlot: {
width: 14,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
linkIcon: {
flexShrink: 0,
},
connectionKind: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
flexShrink: 0,
},
connectionEndpoint: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 1,
minWidth: 0,
},
latency: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
flexShrink: 0,
},
statusText: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 0,
},
}));
+24 -11
View File
@@ -1,11 +1,13 @@
import { useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useHosts } from "@/runtime/host-runtime";
import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance";
import { useSessionStore } from "@/stores/session-store";
/**
* Every host's badge, resolved from the three things that decide one: the host registry, which
* host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* Every host's badge, resolved from the host registry, local-host detection, daemon-reported
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* that has its own reason to hide badges passes false rather than filtering the result, so the
* per-host setting stays the only thing that decides name vs icon vs hidden.
*/
@@ -17,14 +19,25 @@ export function useHostBadges({
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const localDaemon = useLocalDaemonServerIdState();
return useMemo(
() =>
selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
enabled,
}),
[hosts, localDaemon.status, localServerId, enabled],
const detectedMachineKinds = useSessionStore(
useShallow((state) => {
const result: Record<string, string | null> = {};
for (const host of hosts) {
result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null;
}
return result;
}),
);
return useMemo(() => {
const detectedMachineKindByServerId = new Map<string, string | null>(
Object.entries(detectedMachineKinds),
);
return selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
detectedMachineKindByServerId,
enabled,
});
}, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]);
}
+63
View File
@@ -345,6 +345,7 @@ export const ar: TranslationResources = {
viewDiagram: "عرض المخطط",
},
actions: {
copyQuote: "نسخ الاقتباس",
copyCode: "نسخ الرمز",
copyTurn: "نسخ بدوره",
copyMessage: "انسخ الرسالة",
@@ -912,6 +913,7 @@ export const ar: TranslationResources = {
pushNoRemote: "الدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
pushBehind: "الدفع غير متاح حتى الآن نظرًا لوجود تغييرات أحدث يجب إدخالها أولاً",
pushNothing: "خدمة الدفع غير متاحة لأنه لا يوجد شيء جديد لإرساله",
pushUpstreamGone: "الدفع غير متاح لأن الفرع الذي يتتبعه هذا الفرع لم يعد موجودًا",
pullAndPushNoRemote:
"السحب والدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد",
pullAndPushDirty:
@@ -1537,6 +1539,8 @@ export const ar: TranslationResources = {
status: {
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
installing: "جارٍ تثبيت تحديث التطبيق...",
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
upToDate: "التطبيق محدث.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
@@ -1544,6 +1548,14 @@ export const ar: TranslationResources = {
pendingWithVersion: "تم العثور على تحديث: {{version}}. جارٍ التنزيل...",
pendingWithVersionAndLastChecked:
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... آخر فحص في {{time}}.",
pendingWithVersionProgress: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}% آخر فحص في {{time}}.",
downloadAvailableWithVersion: "التحديث متاح: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"التحديث متاح: {{version}}. آخر فحص في {{time}}.",
downloadAvailable: "يتوفر تحديث للتطبيق.",
downloadAvailableWithLastChecked: "يتوفر تحديث للتطبيق. آخر فحص في {{time}}.",
availableWithVersion: "التحديث جاهز:{{version}}",
availableWithVersionAndLastChecked: "التحديث جاهز:{{version}}. آخر فحص في {{time}}.",
available: "تحديث التطبيق جاهز للتثبيت.",
@@ -1554,14 +1566,21 @@ export const ar: TranslationResources = {
},
installError: "غير قادر على تثبيت تحديث تطبيق سطح المكتب.",
callout: {
downloadingTitle: "جارٍ تنزيل التحديث",
installingTitle: "تثبيت التحديث",
failedTitle: "فشل التحديث",
availableTitle: "التحديث متاح",
genericError: "حدث خطأ ما.",
whatsNew: "ما هو الجديد",
downloadingAction: "جارٍ التنزيل...",
installingAction: "جارٍ التثبيت...",
downloadAndRestart: "تنزيل",
installAndRestart: "التثبيت وإعادة التشغيل",
downloadingVersionDescription: "جارٍ تنزيل {{version}}... {{percent}}%",
downloadingDescription: "جارٍ تنزيل التحديث... {{percent}}%",
installingDescription: "التثبيت وإعادة التشغيل...",
versionAvailable: "{{version}} متاح للتنزيل.",
newVersionAvailable: "يتوفر إصدار جديد للتنزيل.",
versionReady: "{{version}}جاهز للتثبيت.",
newVersionReady: "إصدار جديد جاهز للتثبيت.",
restartWarning: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
@@ -2638,9 +2657,28 @@ export const ar: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "التحديثات التلقائية",
options: {
automatic: "تلقائي",
notify: "إشعار",
off: "إيقاف",
},
descriptions: {
automatic: "التحقق من التحديثات وتنزيلها في الخلفية",
notify: "التحقق من التحديثات وتنزيلها فقط عند اختيارك",
off: "عدم التحقق تلقائيًا. يتم التحقق فقط عند النقر على فحص",
},
},
updates: {
label: "تحديثات التطبيق",
readyToInstall: "جاهز للتثبيت:{{version}}",
downloadTitle: "تنزيل تحديث سطح المكتب",
downloadMessage: "سيؤدي هذا إلى تنزيل تحديث Paseo وتثبيته على هذا الكمبيوتر",
downloadConfirm: "تنزيل وتثبيت",
download: "تنزيل",
downloadTo: "تنزيل {{version}}",
downloading: "جارٍ التنزيل...",
installTitle: "تثبيت تحديث سطح المكتب",
installMessage: "يؤدي هذا إلى تحديث Paseo على هذا الكمبيوتر",
installConfirm: "تثبيت التحديث",
@@ -2840,6 +2878,23 @@ export const ar: TranslationResources = {
name: {
label: "الاسم",
},
icon: {
label: "الأيقونة",
accessibilityLabel: "الأيقونة، {{value}}",
auto: "تلقائي",
autoDetected: "تلقائي ({{icon}})",
options: {
server: "خادم",
laptop: "حاسوب محمول",
desktop: "حاسوب مكتبي",
mini: "حاسوب مصغّر",
workstation: "محطة عمل",
cloud: "سحابي",
container: "حاوية",
board: "حاسوب أحادي اللوحة",
terminal: "طرفية",
},
},
color: {
label: "اللون",
accessibilityLabel: "اللون، {{value}}",
@@ -2876,6 +2931,14 @@ export const ar: TranslationResources = {
local: "محلي",
remoteSsh: "SSH عن بُعد",
},
connectionKinds: {
local: "محلي",
relay: "تتابع",
tailscale: "Tailscale",
ssh: "SSH",
direct: "مباشر",
routed: "عبر",
},
connections: {
title: "اتصالات",
removeTitle: "إزالة الاتصال",
+64
View File
@@ -344,6 +344,7 @@ export const en = {
viewDiagram: "View diagram",
},
actions: {
copyQuote: "Copy quote",
copyCode: "Copy code",
copyTurn: "Copy turn",
copyMessage: "Copy message",
@@ -913,6 +914,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:
@@ -1563,6 +1566,8 @@ export const en = {
status: {
checking: "Checking for app updates...",
installing: "Installing app update...",
downloadingVersionProgress: "Downloading {{version}}... {{percent}}%",
downloadingProgress: "Downloading app update... {{percent}}%",
upToDate: "App is up to date.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "We'll let you know when the update is ready.",
@@ -1571,6 +1576,14 @@ export const en = {
pendingWithVersion: "Update found: {{version}}. Downloading...",
pendingWithVersionAndLastChecked:
"Update found: {{version}}. Downloading... Last checked at {{time}}.",
pendingWithVersionProgress: "Update found: {{version}}. Downloading... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Update found: {{version}}. Downloading... {{percent}}% Last checked at {{time}}.",
downloadAvailableWithVersion: "Update available: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Update available: {{version}}. Last checked at {{time}}.",
downloadAvailable: "An app update is available.",
downloadAvailableWithLastChecked: "An app update is available. Last checked at {{time}}.",
availableWithVersion: "Update ready: {{version}}",
availableWithVersionAndLastChecked: "Update ready: {{version}}. Last checked at {{time}}.",
available: "An app update is ready to install.",
@@ -1581,14 +1594,21 @@ export const en = {
},
installError: "Unable to install the desktop app update.",
callout: {
downloadingTitle: "Downloading update",
installingTitle: "Installing update",
failedTitle: "Update failed",
availableTitle: "Update available",
genericError: "Something went wrong.",
whatsNew: "What's new",
downloadingAction: "Downloading...",
installingAction: "Installing...",
downloadAndRestart: "Download",
installAndRestart: "Install & restart",
downloadingVersionDescription: "Downloading {{version}}... {{percent}}%",
downloadingDescription: "Downloading update... {{percent}}%",
installingDescription: "Installing and restarting...",
versionAvailable: "{{version}} is available to download.",
newVersionAvailable: "A new version is available to download.",
versionReady: "{{version}} is ready to install.",
newVersionReady: "A new version is ready to install.",
restartWarning: "Upgrading the app will stop running agents and close terminal sessions.",
@@ -2733,9 +2753,28 @@ export const en = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "Automatic updates",
options: {
automatic: "Auto",
notify: "Notify",
off: "Off",
},
descriptions: {
automatic: "Check and download updates in the background",
notify: "Check for updates, but only download when you choose",
off: "Never check automatically. Only check when you click Check",
},
},
updates: {
label: "App updates",
readyToInstall: "Ready to install: {{version}}",
downloadTitle: "Download desktop update",
downloadMessage: "This downloads and installs the Paseo update on this computer",
downloadConfirm: "Download & install",
download: "Download",
downloadTo: "Download {{version}}",
downloading: "Downloading...",
installTitle: "Install desktop update",
installMessage: "This updates Paseo on this computer",
installConfirm: "Install update",
@@ -2934,6 +2973,23 @@ export const en = {
name: {
label: "Name",
},
icon: {
label: "Icon",
accessibilityLabel: "Icon, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Server",
laptop: "Laptop",
desktop: "Desktop",
mini: "Mini",
workstation: "Workstation",
cloud: "Cloud",
container: "Container",
board: "Single-board PC",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2970,6 +3026,14 @@ export const en = {
local: "Local",
remoteSsh: "Remote SSH",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connections",
removeTitle: "Remove connection",
+66
View File
@@ -350,6 +350,7 @@ export const es: TranslationResources = {
viewDiagram: "Ver diagrama",
},
actions: {
copyQuote: "Copiar cita",
copyCode: "Copiar código",
copyTurn: "Copiar turno",
copyMessage: "Copiar mensaje",
@@ -925,6 +926,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:
@@ -1573,6 +1576,8 @@ export const es: TranslationResources = {
status: {
checking: "Buscando actualizaciones de la aplicación...",
installing: "Instalando actualización de la aplicación...",
downloadingVersionProgress: "Descargando {{version}}... {{percent}}%",
downloadingProgress: "Descargando actualización de la aplicación... {{percent}}%",
upToDate: "La aplicación está actualizada.",
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
pending: "Le avisaremos cuando la actualización esté lista.",
@@ -1581,6 +1586,16 @@ export const es: TranslationResources = {
pendingWithVersion: "Actualización encontrada: {{version}}. Descargando...",
pendingWithVersionAndLastChecked:
"Actualización encontrada: {{version}}. Descargando... Última comprobación a las {{time}}.",
pendingWithVersionProgress:
"Actualización encontrada: {{version}}. Descargando... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Actualización encontrada: {{version}}. Descargando... {{percent}}% Última comprobación a las {{time}}.",
downloadAvailableWithVersion: "Actualización disponible: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Actualización disponible: {{version}}. Última comprobación a las {{time}}.",
downloadAvailable: "Hay una actualización de la aplicación disponible.",
downloadAvailableWithLastChecked:
"Hay una actualización de la aplicación disponible. Última comprobación a las {{time}}.",
availableWithVersion: "Actualización lista:{{version}}",
availableWithVersionAndLastChecked:
"Actualización lista:{{version}}. Última comprobación a las {{time}}.",
@@ -1593,14 +1608,21 @@ export const es: TranslationResources = {
},
installError: "No se puede instalar la actualización de la aplicación de escritorio.",
callout: {
downloadingTitle: "Descargando actualización",
installingTitle: "Instalando actualización",
failedTitle: "La actualización falló",
availableTitle: "Actualización disponible",
genericError: "Algo salió mal.",
whatsNew: "Qué hay de nuevo",
downloadingAction: "Descargando...",
installingAction: "Instalando...",
downloadAndRestart: "Descargar",
installAndRestart: "Instalar y reiniciar",
downloadingVersionDescription: "Descargando {{version}}... {{percent}}%",
downloadingDescription: "Descargando actualización... {{percent}}%",
installingDescription: "Instalando y reiniciando...",
versionAvailable: "{{version}} está disponible para descargar.",
newVersionAvailable: "Una nueva versión está disponible para descargar.",
versionReady: "{{version}}está listo para instalar.",
newVersionReady: "Una nueva versión está lista para instalar.",
restartWarning:
@@ -2658,9 +2680,28 @@ export const es: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "Actualizaciones automáticas",
options: {
automatic: "Auto",
notify: "Notificar",
off: "Desactivado",
},
descriptions: {
automatic: "Buscar y descargar actualizaciones en segundo plano",
notify: "Buscar actualizaciones, pero descargar solo cuando lo elijas",
off: "No buscar automáticamente. Solo buscar al hacer clic en Comprobar",
},
},
updates: {
label: "Actualizaciones de aplicaciones",
readyToInstall: "Listo para instalar:{{version}}",
downloadTitle: "Descargar actualización de escritorio",
downloadMessage: "Esto descarga e instala la actualización de Paseo en esta computadora.",
downloadConfirm: "Descargar e instalar",
download: "Descargar",
downloadTo: "Descargar {{version}}",
downloading: "Descargando...",
installTitle: "Instalar actualización de escritorio",
installMessage: "Esto actualizaPaseoen esta computadora.",
installConfirm: "Instalar actualización",
@@ -2863,6 +2904,23 @@ export const es: TranslationResources = {
name: {
label: "Nombre",
},
icon: {
label: "Icono",
accessibilityLabel: "Icono, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Portátil",
desktop: "Escritorio",
mini: "Mini",
workstation: "Estación de trabajo",
cloud: "Nube",
container: "Contenedor",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2899,6 +2957,14 @@ export const es: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relé",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Directo",
routed: "Vía",
},
connections: {
title: "Conexiones",
removeTitle: "Quitar conexión",
+65
View File
@@ -350,6 +350,7 @@ export const fr: TranslationResources = {
viewDiagram: "Afficher le diagramme",
},
actions: {
copyQuote: "Copier la citation",
copyCode: "Copier le code",
copyTurn: "Copier l’échange",
copyMessage: "Copier le message",
@@ -926,6 +927,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:
@@ -1567,6 +1569,8 @@ export const fr: TranslationResources = {
status: {
checking: "Recherche de mises à jour de l’application…",
installing: "Installation de la mise à jour de l’application…",
downloadingVersionProgress: "Téléchargement de {{version}}… {{percent}} %",
downloadingProgress: "Téléchargement de la mise à jour… {{percent}} %",
upToDate: "L’application est à jour.",
upToDateWithLastChecked: "À jour. Dernière vérification à {{time}}.",
pending: "Nous vous préviendrons quand la mise à jour sera prête.",
@@ -1575,6 +1579,16 @@ export const fr: TranslationResources = {
pendingWithVersion: "Mise à jour trouvée : {{version}}. Téléchargement…",
pendingWithVersionAndLastChecked:
"Mise à jour trouvée : {{version}}. Téléchargement… Dernière vérification à {{time}}.",
pendingWithVersionProgress:
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} %",
pendingWithVersionProgressAndLastChecked:
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} % Dernière vérification à {{time}}.",
downloadAvailableWithVersion: "Mise à jour disponible : {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Mise à jour disponible : {{version}}. Dernière vérification à {{time}}.",
downloadAvailable: "Une mise à jour de l’application est disponible.",
downloadAvailableWithLastChecked:
"Une mise à jour de l’application est disponible. Dernière vérification à {{time}}.",
availableWithVersion: "Mise à jour prête : {{version}}",
availableWithVersionAndLastChecked:
"Mise à jour prête : {{version}}. Dernière vérification à {{time}}.",
@@ -1587,14 +1601,21 @@ export const fr: TranslationResources = {
},
installError: "Impossible d’installer la mise à jour de l’application de bureau.",
callout: {
downloadingTitle: "Téléchargement de la mise à jour",
installingTitle: "Installation de la mise à jour",
failedTitle: "Échec de la mise à jour",
availableTitle: "Mise à jour disponible",
genericError: "Une erreur s’est produite.",
whatsNew: "Nouveautés",
downloadingAction: "Téléchargement…",
installingAction: "Installation…",
downloadAndRestart: "Télécharger",
installAndRestart: "Installer et redémarrer",
downloadingVersionDescription: "Téléchargement de {{version}}… {{percent}} %",
downloadingDescription: "Téléchargement de la mise à jour… {{percent}} %",
installingDescription: "Installation et redémarrage…",
versionAvailable: "La version {{version}} est disponible au téléchargement.",
newVersionAvailable: "Une nouvelle version est disponible au téléchargement.",
versionReady: "La version {{version}} est prête à être installée.",
newVersionReady: "Une nouvelle version est prête à être installée.",
restartWarning:
@@ -2659,9 +2680,28 @@ export const fr: TranslationResources = {
stable: "Stable",
beta: "Bêta",
},
autoUpdate: {
label: "Mises à jour automatiques",
options: {
automatic: "Auto",
notify: "Notifier",
off: "Désactivé",
},
descriptions: {
automatic: "Vérifier et télécharger les mises à jour en arrière-plan",
notify: "Vérifier les mises à jour, mais ne télécharger que lorsque vous choisissez",
off: "Ne jamais vérifier automatiquement. Vérifier uniquement sur clic sur Vérifier",
},
},
updates: {
label: "Mises à jour de l’application",
readyToInstall: "Prête à installer : {{version}}",
downloadTitle: "Télécharger la mise à jour de l’app de bureau",
downloadMessage: "La mise à jour de Paseo sera téléchargée et installée sur cet ordinateur",
downloadConfirm: "Télécharger et installer",
download: "Télécharger",
downloadTo: "Télécharger {{version}}",
downloading: "Téléchargement…",
installTitle: "Installer la mise à jour de l’app de bureau",
installMessage: "Paseo sera mis à jour sur cet ordinateur",
installConfirm: "Installer la mise à jour",
@@ -2866,6 +2906,23 @@ export const fr: TranslationResources = {
name: {
label: "Nom",
},
icon: {
label: "Icône",
accessibilityLabel: "Icône, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Serveur",
laptop: "Portable",
desktop: "Bureau",
mini: "Mini",
workstation: "Station de travail",
cloud: "Cloud",
container: "Conteneur",
board: "Ordinateur monocarte",
terminal: "Terminal",
},
},
color: {
label: "Couleur",
accessibilityLabel: "Couleur, {{value}}",
@@ -2902,6 +2959,14 @@ export const fr: TranslationResources = {
local: "Local",
remoteSsh: "SSH distant",
},
connectionKinds: {
local: "Local",
relay: "Relais",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connexions",
removeTitle: "Supprimer la connexion",
+65
View File
@@ -350,6 +350,7 @@ export const ja: TranslationResources = {
viewDiagram: "図を表示",
},
actions: {
copyQuote: "引用をコピー",
copyCode: "コードをコピー",
copyTurn: "ターンをコピー",
copyMessage: "メッセージをコピー",
@@ -919,6 +920,8 @@ export const ja: TranslationResources = {
"このブランチはまだリモートに接続されていないため、プッシュはここでは利用できません",
pushBehind: "取り込む必要がある新しい変更があるため、まだプッシュは利用できません",
pushNothing: "プッシュする変更がないため、プッシュは利用できません",
pushUpstreamGone:
"このブランチが追跡しているブランチが存在しないため、プッシュは利用できません",
pullAndPushNoRemote:
"このブランチはまだリモートに接続されていないため、プル&プッシュはここでは利用できません",
pullAndPushDirty:
@@ -1551,6 +1554,8 @@ export const ja: TranslationResources = {
status: {
checking: "アプリの更新を確認中...",
installing: "アプリの更新をインストール中...",
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
upToDate: "アプリは最新です。",
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
pending: "更新の準備ができたらお知らせします。",
@@ -1558,6 +1563,15 @@ export const ja: TranslationResources = {
pendingWithVersion: "更新が見つかりました: {{version}}。ダウンロード中...",
pendingWithVersionAndLastChecked:
"更新が見つかりました: {{version}}。ダウンロード中... 最終確認: {{time}}。",
pendingWithVersionProgress:
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}% 最終確認: {{time}}。",
downloadAvailableWithVersion: "利用可能な更新: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"利用可能な更新: {{version}}。最終確認: {{time}}。",
downloadAvailable: "アプリの更新が利用可能です。",
downloadAvailableWithLastChecked: "アプリの更新が利用可能です。最終確認: {{time}}。",
availableWithVersion: "更新の準備ができました: {{version}}",
availableWithVersionAndLastChecked:
"更新の準備ができました: {{version}}。最終確認: {{time}}。",
@@ -1569,14 +1583,21 @@ export const ja: TranslationResources = {
},
installError: "デスクトップアプリの更新をインストールできません。",
callout: {
downloadingTitle: "更新をダウンロード中",
installingTitle: "更新をインストール中",
failedTitle: "更新に失敗しました",
availableTitle: "更新が利用可能",
genericError: "問題が発生しました。",
whatsNew: "新機能",
downloadingAction: "ダウンロード中...",
installingAction: "インストール中...",
downloadAndRestart: "ダウンロード",
installAndRestart: "インストールして再起動",
downloadingVersionDescription: "{{version}} をダウンロード中... {{percent}}%",
downloadingDescription: "更新をダウンロード中... {{percent}}%",
installingDescription: "インストールして再起動中...",
versionAvailable: "{{version}} をダウンロードできます。",
newVersionAvailable: "新しいバージョンをダウンロードできます。",
versionReady: "{{version}}のインストール準備ができました。",
newVersionReady: "新しいバージョンのインストール準備ができました。",
restartWarning:
@@ -2625,9 +2646,28 @@ export const ja: TranslationResources = {
stable: "安定版",
beta: "ベータ",
},
autoUpdate: {
label: "自動更新",
options: {
automatic: "自動",
notify: "通知のみ",
off: "オフ",
},
descriptions: {
automatic: "バックグラウンドで更新を確認してダウンロードします",
notify: "更新を確認しますが、選択したときだけダウンロードします",
off: "自動で更新を確認しません。「確認」をクリックしたときだけ確認します",
},
},
updates: {
label: "アプリの更新",
readyToInstall: "インストール準備完了: {{version}}",
downloadTitle: "デスクトップの更新をダウンロード",
downloadMessage: "このコンピューターにPaseoの更新をダウンロードしてインストールします",
downloadConfirm: "ダウンロードしてインストール",
download: "ダウンロード",
downloadTo: "{{version}}をダウンロード",
downloading: "ダウンロード中...",
installTitle: "デスクトップの更新をインストール",
installMessage: "このコンピューターのPaseoを更新します",
installConfirm: "更新をインストール",
@@ -2831,6 +2871,23 @@ export const ja: TranslationResources = {
name: {
label: "名前",
},
icon: {
label: "アイコン",
accessibilityLabel: "アイコン、{{value}}",
auto: "自動",
autoDetected: "自動 ({{icon}})",
options: {
server: "サーバー",
laptop: "ノート PC",
desktop: "デスクトップ",
mini: "ミニ PC",
workstation: "ワークステーション",
cloud: "クラウド",
container: "コンテナ",
board: "シングルボード PC",
terminal: "ターミナル",
},
},
color: {
label: "色",
accessibilityLabel: "色、{{value}}",
@@ -2867,6 +2924,14 @@ export const ja: TranslationResources = {
local: "ローカル",
remoteSsh: "リモート SSH",
},
connectionKinds: {
local: "ローカル",
relay: "リレー",
tailscale: "Tailscale",
ssh: "SSH",
direct: "ダイレクト",
routed: "経由",
},
connections: {
title: "接続",
removeTitle: "接続を削除",
+64
View File
@@ -346,6 +346,7 @@ export const ko: TranslationResources = {
viewDiagram: "다이어그램 보기",
},
actions: {
copyQuote: "인용문 복사",
copyCode: "코드 복사",
copyTurn: "턴 복사",
copyMessage: "메시지 복사",
@@ -913,6 +914,7 @@ export const ko: TranslationResources = {
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 푸시를 사용할 수 없습니다",
pushBehind: "먼저 가져와야 할 최신 변경 사항이 있어 아직 푸시를 사용할 수 없습니다",
pushNothing: "새로 보낼 항목이 없어 푸시를 사용할 수 없습니다",
pushUpstreamGone: "이 브랜치가 추적하는 브랜치가 더 이상 없어 푸시를 사용할 수 없습니다",
pullAndPushNoRemote:
"이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 풀 후 푸시를 사용할 수 없습니다",
pullAndPushDirty:
@@ -1543,6 +1545,8 @@ export const ko: TranslationResources = {
status: {
checking: "앱 업데이트 확인 중...",
installing: "앱 업데이트 설치 중...",
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
upToDate: "앱이 최신 상태입니다.",
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
pending: "업데이트가 준비되면 알려드리겠습니다.",
@@ -1551,6 +1555,15 @@ export const ko: TranslationResources = {
pendingWithVersion: "업데이트 발견: {{version}}. 다운로드 중...",
pendingWithVersionAndLastChecked:
"업데이트 발견: {{version}}. 다운로드 중... {{time}}에서 마지막으로 확인했습니다.",
pendingWithVersionProgress: "업데이트 발견: {{version}}. 다운로드 중... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"업데이트 발견: {{version}}. 다운로드 중... {{percent}}% {{time}}에서 마지막으로 확인했습니다.",
downloadAvailableWithVersion: "사용 가능한 업데이트: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"사용 가능한 업데이트: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
downloadAvailable: "사용 가능한 앱 업데이트가 있습니다.",
downloadAvailableWithLastChecked:
"사용 가능한 앱 업데이트가 있습니다. {{time}}에서 마지막으로 확인했습니다.",
availableWithVersion: "업데이트 준비됨: {{version}}",
availableWithVersionAndLastChecked:
"업데이트 준비됨: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
@@ -1563,14 +1576,21 @@ export const ko: TranslationResources = {
},
installError: "데스크톱 앱 업데이트를 설치할 수 없습니다.",
callout: {
downloadingTitle: "업데이트 다운로드 중",
installingTitle: "업데이트 설치 중",
failedTitle: "업데이트 실패",
availableTitle: "업데이트 사용 가능",
genericError: "문제가 발생했습니다.",
whatsNew: "새로운 기능",
downloadingAction: "다운로드 중...",
installingAction: "설치 중...",
downloadAndRestart: "다운로드",
installAndRestart: "설치 후 재시작",
downloadingVersionDescription: "{{version}} 다운로드 중... {{percent}}%",
downloadingDescription: "업데이트 다운로드 중... {{percent}}%",
installingDescription: "설치 후 재시작 중...",
versionAvailable: "{{version}} 버전을 다운로드할 수 있습니다.",
newVersionAvailable: "새 버전을 다운로드할 수 있습니다.",
versionReady: "{{version}} 설치가 준비되었습니다.",
newVersionReady: "새 버전 설치가 준비되었습니다.",
restartWarning: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
@@ -2616,9 +2636,28 @@ export const ko: TranslationResources = {
stable: "안정",
beta: "베타",
},
autoUpdate: {
label: "자동 업데이트",
options: {
automatic: "자동",
notify: "알림만",
off: "끄기",
},
descriptions: {
automatic: "백그라운드에서 업데이트를 확인하고 다운로드합니다",
notify: "업데이트를 확인하지만 선택할 때만 다운로드합니다",
off: "자동으로 확인하지 않습니다. 확인 버튼을 누를 때만 확인합니다",
},
},
updates: {
label: "앱 업데이트",
readyToInstall: "설치 준비됨: {{version}}",
downloadTitle: "데스크톱 업데이트 다운로드",
downloadMessage: "이 컴퓨터에 Paseo 업데이트를 다운로드하고 설치합니다",
downloadConfirm: "다운로드 및 설치",
download: "다운로드",
downloadTo: "{{version}} 다운로드",
downloading: "다운로드 중...",
installTitle: "데스크톱 업데이트 설치",
installMessage: "이 컴퓨터의 Paseo를 업데이트합니다",
installConfirm: "업데이트 설치",
@@ -2818,6 +2857,23 @@ export const ko: TranslationResources = {
name: {
label: "이름",
},
icon: {
label: "아이콘",
accessibilityLabel: "아이콘, {{value}}",
auto: "자동",
autoDetected: "자동 ({{icon}})",
options: {
server: "서버",
laptop: "노트북",
desktop: "데스크톱",
mini: "미니",
workstation: "워크스테이션",
cloud: "클라우드",
container: "컨테이너",
board: "싱글보드 PC",
terminal: "터미널",
},
},
color: {
label: "색상",
accessibilityLabel: "색상, {{value}}",
@@ -2854,6 +2910,14 @@ export const ko: TranslationResources = {
local: "로컬",
remoteSsh: "원격 SSH",
},
connectionKinds: {
local: "로컬",
relay: "릴레이",
tailscale: "Tailscale",
ssh: "SSH",
direct: "직접 연결",
routed: "경유",
},
connections: {
title: "연결",
removeTitle: "연결 제거",
+65
View File
@@ -349,6 +349,7 @@ export const ptBR: TranslationResources = {
viewDiagram: "Ver diagrama",
},
actions: {
copyQuote: "Copiar citação",
copyCode: "Copiar código",
copyTurn: "Copiar turno",
copyMessage: "Copiar mensagem",
@@ -921,6 +922,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:
@@ -1563,6 +1566,8 @@ export const ptBR: TranslationResources = {
status: {
checking: "Verificando atualizações do app...",
installing: "Instalando atualização do app...",
downloadingVersionProgress: "Baixando {{version}}... {{percent}}%",
downloadingProgress: "Baixando atualização do app... {{percent}}%",
upToDate: "O app está atualizado.",
upToDateWithLastChecked: "Atualizado. Última verificação às {{time}}.",
pending: "Avisaremos quando a atualização estiver pronta.",
@@ -1571,6 +1576,15 @@ export const ptBR: TranslationResources = {
pendingWithVersion: "Atualização encontrada: {{version}}. Baixando...",
pendingWithVersionAndLastChecked:
"Atualização encontrada: {{version}}. Baixando... Última verificação às {{time}}.",
pendingWithVersionProgress: "Atualização encontrada: {{version}}. Baixando... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Atualização encontrada: {{version}}. Baixando... {{percent}}% Última verificação às {{time}}.",
downloadAvailableWithVersion: "Atualização disponível: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Atualização disponível: {{version}}. Última verificação às {{time}}.",
downloadAvailable: "Há uma atualização do app disponível.",
downloadAvailableWithLastChecked:
"Há uma atualização do app disponível. Última verificação às {{time}}.",
availableWithVersion: "Atualização pronta: {{version}}",
availableWithVersionAndLastChecked:
"Atualização pronta: {{version}}. Última verificação às {{time}}.",
@@ -1583,14 +1597,21 @@ export const ptBR: TranslationResources = {
},
installError: "Não foi possível instalar a atualização do app desktop.",
callout: {
downloadingTitle: "Baixando atualização",
installingTitle: "Instalando atualização",
failedTitle: "Falha na atualização",
availableTitle: "Atualização disponível",
genericError: "Algo deu errado.",
whatsNew: "Novidades",
downloadingAction: "Baixando...",
installingAction: "Instalando...",
downloadAndRestart: "Baixar",
installAndRestart: "Instalar e reiniciar",
downloadingVersionDescription: "Baixando {{version}}... {{percent}}%",
downloadingDescription: "Baixando atualização... {{percent}}%",
installingDescription: "Instalando e reiniciando...",
versionAvailable: "{{version}} está disponível para download.",
newVersionAvailable: "Uma nova versão está disponível para download.",
versionReady: "{{version}} está pronta para instalar.",
newVersionReady: "Uma nova versão está pronta para instalar.",
restartWarning:
@@ -2640,9 +2661,28 @@ export const ptBR: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "Atualizações automáticas",
options: {
automatic: "Auto",
notify: "Notificar",
off: "Desativado",
},
descriptions: {
automatic: "Verificar e baixar atualizações em segundo plano",
notify: "Verificar atualizações, mas baixar apenas quando você escolher",
off: "Nunca verificar automaticamente. Verificar apenas ao clicar em Verificar",
},
},
updates: {
label: "Atualizações do app",
readyToInstall: "Pronta para instalar: {{version}}",
downloadTitle: "Baixar atualização desktop",
downloadMessage: "Isso baixa e instala a atualização do Paseo neste computador",
downloadConfirm: "Baixar e instalar",
download: "Baixar",
downloadTo: "Baixar {{version}}",
downloading: "Baixando...",
installTitle: "Instalar atualização desktop",
installMessage: "Isso atualiza o Paseo neste computador",
installConfirm: "Instalar atualização",
@@ -2844,6 +2884,23 @@ export const ptBR: TranslationResources = {
name: {
label: "Nome",
},
icon: {
label: "Ícone",
accessibilityLabel: "Ícone, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Notebook",
desktop: "Desktop",
mini: "Mini",
workstation: "Estação de trabalho",
cloud: "Nuvem",
container: "Contêiner",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Cor",
accessibilityLabel: "Cor, {{value}}",
@@ -2880,6 +2937,14 @@ export const ptBR: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direto",
routed: "Via",
},
connections: {
title: "Conexões",
removeTitle: "Remover conexão",
+65
View File
@@ -349,6 +349,7 @@ export const ru: TranslationResources = {
viewDiagram: "Показать диаграмму",
},
actions: {
copyQuote: "Копировать цитату",
copyCode: "Скопировать код",
copyTurn: "Скопировать ответ",
copyMessage: "Копировать сообщение",
@@ -924,6 +925,8 @@ export const ru: TranslationResources = {
"Отправка изменений недоступна: эта ветка ещё не связана с удалённым репозиторием.",
pushBehind: "Отправка изменений пока недоступна: сначала получите более новые изменения.",
pushNothing: "Отправка изменений недоступна: нет новых изменений для отправки.",
pushUpstreamGone:
"Отправка изменений недоступна: ветка, которую отслеживает эта ветка, больше не существует.",
pullAndPushNoRemote:
"Получение и отправка изменений недоступны: эта ветка ещё не связана с удалённым репозиторием.",
pullAndPushDirty:
@@ -1557,6 +1560,8 @@ export const ru: TranslationResources = {
status: {
checking: "Проверка обновлений приложения...",
installing: "Установка обновления приложения...",
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
upToDate: "Установлена последняя версия приложения.",
upToDateWithLastChecked:
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
@@ -1566,6 +1571,15 @@ export const ru: TranslationResources = {
pendingWithVersion: "Найдено обновление: {{version}}. Загрузка...",
pendingWithVersionAndLastChecked:
"Найдено обновление: {{version}}. Загрузка... Последняя проверка в {{time}}.",
pendingWithVersionProgress: "Найдено обновление: {{version}}. Загрузка... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"Найдено обновление: {{version}}. Загрузка... {{percent}}% Последняя проверка в {{time}}.",
downloadAvailableWithVersion: "Доступно обновление: {{version}}",
downloadAvailableWithVersionAndLastChecked:
"Доступно обновление: {{version}}. Последняя проверка: {{time}}.",
downloadAvailable: "Доступно обновление приложения.",
downloadAvailableWithLastChecked:
"Доступно обновление приложения. Последняя проверка: {{time}}.",
availableWithVersion: "Обновление готово: {{version}}",
availableWithVersionAndLastChecked:
"Обновление готово: {{version}}. Последняя проверка: {{time}}.",
@@ -1578,14 +1592,21 @@ export const ru: TranslationResources = {
},
installError: "Не удалось установить обновление настольного приложения.",
callout: {
downloadingTitle: "Загрузка обновления",
installingTitle: "Установка обновления",
failedTitle: "Обновление не выполнено",
availableTitle: "Доступно обновление",
genericError: "Что-то пошло не так.",
whatsNew: "Что нового",
downloadingAction: "Загрузка...",
installingAction: "Установка...",
downloadAndRestart: "Скачать",
installAndRestart: "Установить и перезапустить",
downloadingVersionDescription: "Загрузка {{version}}... {{percent}}%",
downloadingDescription: "Загрузка обновления... {{percent}}%",
installingDescription: "Установка и перезапуск...",
versionAvailable: "Версия {{version}} доступна для загрузки.",
newVersionAvailable: "Новая версия доступна для загрузки.",
versionReady: "Версия {{version}} готова к установке.",
newVersionReady: "Новая версия готова к установке.",
restartWarning:
@@ -2647,9 +2668,28 @@ export const ru: TranslationResources = {
stable: "Стабильный",
beta: "Бета",
},
autoUpdate: {
label: "Автообновления",
options: {
automatic: "Авто",
notify: "Уведомлять",
off: "Выкл.",
},
descriptions: {
automatic: "Проверять и загружать обновления в фоновом режиме",
notify: "Проверять обновления, но загружать только по вашему выбору",
off: "Не проверять автоматически. Проверять только по нажатию кнопки Проверить",
},
},
updates: {
label: "Обновления приложения",
readyToInstall: "Версия {{version}} готова к установке",
downloadTitle: "Загрузить обновление настольного приложения",
downloadMessage: "Это загрузит и установит обновление Paseo на этом компьютере.",
downloadConfirm: "Загрузить и установить",
download: "Загрузить",
downloadTo: "Загрузить {{version}}",
downloading: "Загрузка...",
installTitle: "Установить обновление настольного приложения",
installMessage: "Это обновит Paseo на этом компьютере.",
installConfirm: "Установить обновление",
@@ -2852,6 +2892,23 @@ export const ru: TranslationResources = {
name: {
label: "Имя",
},
icon: {
label: "Значок",
accessibilityLabel: "Значок, {{value}}",
auto: "Авто",
autoDetected: "Авто ({{icon}})",
options: {
server: "Сервер",
laptop: "Ноутбук",
desktop: "Компьютер",
mini: "Мини-ПК",
workstation: "Рабочая станция",
cloud: "Облако",
container: "Контейнер",
board: "Одноплатный ПК",
terminal: "Терминал",
},
},
color: {
label: "Цвет",
accessibilityLabel: "Цвет, {{value}}",
@@ -2888,6 +2945,14 @@ export const ru: TranslationResources = {
local: "Локальный",
remoteSsh: "Удалённый SSH",
},
connectionKinds: {
local: "Локальный",
relay: "Ретранслятор",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Прямой",
routed: "Через",
},
connections: {
title: "Подключения",
removeTitle: "Удалить подключение",
+63
View File
@@ -345,6 +345,7 @@ export const zhCN: TranslationResources = {
viewDiagram: "查看图表",
},
actions: {
copyQuote: "复制引用",
copyCode: "复制代码",
copyTurn: "复制回合",
copyMessage: "复制消息",
@@ -908,6 +909,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 的传入变更",
@@ -1524,6 +1526,8 @@ export const zhCN: TranslationResources = {
status: {
checking: "正在检查 app 更新...",
installing: "正在安装 app 更新...",
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
downloadingProgress: "正在下载 app 更新... {{percent}}%",
upToDate: "App 已是最新版本。",
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
pending: "更新准备好后会通知你。",
@@ -1531,6 +1535,14 @@ export const zhCN: TranslationResources = {
pendingWithVersion: "发现更新:{{version}}。正在下载...",
pendingWithVersionAndLastChecked:
"发现更新:{{version}}。正在下载... 上次检查时间:{{time}}。",
pendingWithVersionProgress: "发现更新:{{version}}。正在下载... {{percent}}%",
pendingWithVersionProgressAndLastChecked:
"发现更新:{{version}}。正在下载... {{percent}}% 上次检查时间:{{time}}。",
downloadAvailableWithVersion: "有可用更新:{{version}}",
downloadAvailableWithVersionAndLastChecked:
"有可用更新:{{version}}。上次检查时间:{{time}}。",
downloadAvailable: "有 app 更新可用。",
downloadAvailableWithLastChecked: "有 app 更新可用。上次检查时间:{{time}}。",
availableWithVersion: "更新已就绪:{{version}}",
availableWithVersionAndLastChecked: "更新已就绪:{{version}}。上次检查时间:{{time}}。",
available: "有 app 更新可安装。",
@@ -1541,14 +1553,21 @@ export const zhCN: TranslationResources = {
},
installError: "无法安装 desktop app 更新。",
callout: {
downloadingTitle: "正在下载更新",
installingTitle: "正在安装更新",
failedTitle: "更新失败",
availableTitle: "有可用更新",
genericError: "出了点问题。",
whatsNew: "更新内容",
downloadingAction: "正在下载...",
installingAction: "正在安装...",
downloadAndRestart: "下载",
installAndRestart: "安装并重启",
downloadingVersionDescription: "正在下载 {{version}}... {{percent}}%",
downloadingDescription: "正在下载更新... {{percent}}%",
installingDescription: "正在安装并重启...",
versionAvailable: "{{version}} 可供下载。",
newVersionAvailable: "有新版本可供下载。",
versionReady: "{{version}} 已准备好安装。",
newVersionReady: "新版本已准备好安装。",
restartWarning: "升级 app 会停止正在运行的 agents,并关闭 terminal 会话。",
@@ -2575,9 +2594,28 @@ export const zhCN: TranslationResources = {
stable: "Stable",
beta: "Beta",
},
autoUpdate: {
label: "自动更新",
options: {
automatic: "自动",
notify: "仅通知",
off: "关闭",
},
descriptions: {
automatic: "在后台检查并下载更新",
notify: "检查更新,但仅在你选择时才下载",
off: "从不自动检查,仅在点击检查时检查更新",
},
},
updates: {
label: "应用更新",
readyToInstall: "可安装:{{version}}",
downloadTitle: "下载桌面版更新",
downloadMessage: "这会在此电脑上下载并安装 Paseo 更新",
downloadConfirm: "下载并安装",
download: "下载",
downloadTo: "下载 {{version}}",
downloading: "正在下载...",
installTitle: "安装桌面版更新",
installMessage: "这会更新此电脑上的 Paseo",
installConfirm: "安装更新",
@@ -2774,6 +2812,23 @@ export const zhCN: TranslationResources = {
name: {
label: "名称",
},
icon: {
label: "图标",
accessibilityLabel: "图标,{{value}}",
auto: "自动",
autoDetected: "自动 ({{icon}})",
options: {
server: "服务器",
laptop: "笔记本电脑",
desktop: "台式机",
mini: "迷你主机",
workstation: "工作站",
cloud: "云端",
container: "容器",
board: "单板机",
terminal: "终端",
},
},
color: {
label: "颜色",
accessibilityLabel: "颜色,{{value}}",
@@ -2810,6 +2865,14 @@ export const zhCN: TranslationResources = {
local: "本地",
remoteSsh: "远程 SSH",
},
connectionKinds: {
local: "本地",
relay: "中继",
tailscale: "Tailscale",
ssh: "SSH",
direct: "直连",
routed: "经由",
},
connections: {
title: "连接",
removeTitle: "移除连接",
@@ -9,10 +9,6 @@ export interface OverlayRegistration {
*/
keys: readonly string[];
onKeyDown(event: KeyboardInputEvent): boolean;
/**
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
* to whatever had focus when the overlay opened.
*/
restoreFocusRef?: RefObject<unknown>;
manageFocus?: boolean;
}
@@ -3,29 +3,12 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
import type { OverlayRegistration } from "./overlay-contract";
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
interface FocusTarget {
focus(): void;
}
function isFocusTarget(value: unknown): value is FocusTarget {
return (
typeof value === "object" &&
value !== null &&
typeof (value as Partial<FocusTarget>).focus === "function"
);
}
function canRestoreFocusTo(target: FocusTarget): boolean {
return !(target instanceof HTMLElement) || document.contains(target);
}
interface WebOverlayEntry {
getLayer: () => number;
getKeys: () => readonly string[];
getScope: () => HTMLElement | null;
getKeyHandler: () => WebOverlayKeyHandler;
restoreFocus: FocusTarget | null;
restoreFocus: HTMLElement | null;
manageFocus: boolean;
}
@@ -173,7 +156,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
entry.manageFocus &&
options?.restoreFocus !== false &&
entry.restoreFocus &&
canRestoreFocusTo(entry.restoreFocus)
document.contains(entry.restoreFocus)
) {
entry.restoreFocus.focus();
}
@@ -198,7 +181,7 @@ export function useOverlayRegistration({
keysRef.current = keys;
const layerRef = useRef(layer);
const keyHandlerRef = useRef(onKeyDown);
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
const registeredRef = useRef(false);
@@ -210,7 +193,7 @@ export function useOverlayRegistration({
keyHandlerRef.current = onKeyDown;
if (active && !wasActiveRef.current && typeof document !== "undefined") {
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
if (isFocusTarget(requestedRestoreTarget)) {
if (requestedRestoreTarget instanceof HTMLElement) {
capturedRestoreFocusRef.current = requestedRestoreTarget;
} else {
capturedRestoreFocusRef.current =
+175 -6
View File
@@ -1114,6 +1114,106 @@ describe("HostRuntimeController", () => {
expect(activeClient.latencyMeasurements()).toEqual([]);
});
it("measures active latency on demand when an online host has no sample yet", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const controller = new HostRuntimeController({
host: makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
preferredConnectionId: "direct:lan:6767",
}),
deps: makeDeps({ "direct:lan:6767": 14 }, []),
});
await controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "pending",
latencyMs: null,
});
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
});
it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const relayProbeStarted = createDeferred<void>();
const slowRelayProbe = createDeferred<{
client: DaemonClient;
serverId: string;
hostname: string | null;
}>();
const relayClient = new FakeDaemonClient();
relayClient.setConnectionState({ status: "connected" });
relayClient.ping = async () => ({ rttMs: 90 });
const controller = new HostRuntimeController({
host: makeHost(),
deps: {
...makeDeps({}, []),
connectToDaemon: async ({ host, connection }) => {
if (connection.id === "relay:relay.paseo.sh:443") {
relayProbeStarted.resolve();
return slowRelayProbe.promise;
}
return {
client: initialClient as unknown as DaemonClient,
serverId: host.serverId,
hostname: null,
};
},
},
});
// Startup runs the first probe cycle immediately; wait until the slower relay probe is in
// flight, then measure active latency on demand before the relay probe resolves.
const startPromise = controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
await relayProbeStarted.promise;
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
slowRelayProbe.resolve({
client: relayClient as unknown as DaemonClient,
serverId: "srv_test",
hostname: null,
});
await startPromise;
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({
status: "available",
latencyMs: 90,
});
});
it.each([12, null])(
"falls back to relay when the direct client disconnects with heartbeat RTT %s",
async (heartbeatRtt) => {
@@ -3366,7 +3466,11 @@ describe("HostRuntimeStore", () => {
store.boot();
await registryLoaded;
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "none",
badgeDisplay: null,
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
@@ -3391,6 +3495,7 @@ describe("HostRuntimeStore", () => {
const updated = store.getHosts()[0];
expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null });
expect("icon" in (updated?.appearance ?? {})).toBe(false);
expect(updated?.updatedAt).not.toBe(host.updatedAt);
const persisted = await storage.getItem("@paseo:daemon-registry");
@@ -3402,10 +3507,60 @@ describe("HostRuntimeStore", () => {
store.syncHosts([]);
});
it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "violet", badgeDisplay: "icon" },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
await storage.setItem("@paseo:e2e", "1");
const store = createAppearanceStore(storage);
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
store.boot();
await registryLoaded;
const hostListChanged = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === "laptop",
);
await store.setHostIcon("srv_appearance", "laptop");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const resetToAuto = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === undefined,
);
await store.setHostIcon("srv_appearance", null);
await resetToAuto;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
badgeDisplay: "icon",
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
it("records a chosen badge display without disturbing the color", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "amber", badgeDisplay: null },
appearance: { color: "amber", icon: "server", badgeDisplay: null },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
@@ -3423,11 +3578,16 @@ describe("HostRuntimeStore", () => {
await store.setHostBadgeDisplay("srv_appearance", "icon");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
@@ -3476,16 +3636,25 @@ describe("HostRuntimeStore", () => {
};
const color = store.setHostColor("srv_appearance", "teal");
const icon = store.setHostIcon("srv_appearance", "mini");
const display = store.setHostBadgeDisplay("srv_appearance", "icon");
await Promise.resolve();
expect(writeCount).toBe(1);
firstWrite.resolve();
await Promise.all([color, display]);
await Promise.all([color, icon, display]);
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(persistedHosts[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
store.syncHosts([]);
});
+91 -15
View File
@@ -28,7 +28,12 @@ import {
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
defaultHostAppearance,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -945,6 +950,56 @@ export class HostRuntimeController {
await this.switchToConnection(input);
}
/**
* Measures the active connection's round-trip time when the host is online and no sample has
* landed yet (for example right after connecting, before the first heartbeat interval fires).
*/
async refreshActiveLatency(): Promise<void> {
const activeConnectionId = this.snapshot.activeConnectionId;
const activeClient = this.snapshot.client;
if (
this.snapshot.connectionStatus !== "online" ||
!activeConnectionId ||
!activeClient ||
activeClient.getConnectionState().status !== "connected"
) {
return;
}
const existing = this.snapshot.probeByConnectionId.get(activeConnectionId);
if (existing?.status === "available") {
return;
}
const existingRtt = activeClient.getLastLivenessRttMs();
if (existingRtt !== null) {
this.recordActiveLatencySample(activeConnectionId, existingRtt);
return;
}
try {
const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 });
if (
this.snapshot.activeConnectionId !== activeConnectionId ||
this.snapshot.client !== activeClient ||
this.snapshot.connectionStatus !== "online"
) {
return;
}
this.recordActiveLatencySample(activeConnectionId, rttMs);
} catch {
// A latency probe never drives teardown; the heartbeat owns liveness.
}
}
private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void {
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
probeByConnectionId.set(connectionId, probe);
this.updateSnapshot({ probeByConnectionId });
}
private recordActiveLatencySample(connectionId: string, rttMs: number): void {
this.recordActiveRttSample(rttMs, performance.now());
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
}
async runProbeCycleNow(): Promise<void> {
if (this.probeCycleInFlight) {
return this.probeCycleInFlight;
@@ -1001,30 +1056,32 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const initialProbes = new Map(this.snapshot.probeByConnectionId);
for (const connection of connectionsToProbe) {
this.connectionLastProbedAt.set(connection.id, performance.now());
const existingProbe = probeByConnectionId.get(connection.id);
const existingProbe = initialProbes.get(connection.id);
const shouldPreserveActiveLatency =
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
if (!shouldPreserveActiveLatency) {
probeByConnectionId.set(connection.id, {
initialProbes.set(connection.id, {
status: "pending",
latencyMs: null,
});
}
}
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
this.updateSnapshot({ probeByConnectionId: initialProbes });
let remaining = connectionsToProbe.length;
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
let activationLock: Promise<void> | null = null;
const publishProbeState = (): void => {
// Merge each connection result into the live snapshot map so a slow probe on another
// connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one.
const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => {
if (!this.isCurrentProbeRequest(requestVersion)) {
return;
}
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
this.setConnectionProbe(connectionId, probe);
};
const maybeActivateFirstAvailable = async (
@@ -1053,6 +1110,7 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const currentActiveConnectionId = this.snapshot.activeConnectionId;
if (currentActiveConnectionId) {
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
@@ -1208,11 +1266,10 @@ export class HostRuntimeController {
if (activeClient) {
if (activeClient.getConnectionState().status !== "connected") {
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
return;
}
const rttMs = activeClient.getLastLivenessRttMs();
@@ -1221,11 +1278,10 @@ export class HostRuntimeController {
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
}
return;
}
@@ -1235,11 +1291,10 @@ export class HostRuntimeController {
return;
}
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
} catch (error) {
if (this.isCurrentProbeRequest(requestVersion)) {
const authFailure = getConnectionAuthFailureReason(error);
@@ -1247,11 +1302,10 @@ export class HostRuntimeController {
this.authRejectedConnectionIds.add(connection.id);
probeAuthFailure = authFailure;
}
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
}
} finally {
if (connectedClient && shouldCloseClient) {
@@ -2436,6 +2490,16 @@ export class HostRuntimeStore {
}));
}
async setHostIcon(serverId: string, icon: HostIcon | null): Promise<void> {
await this.updateHostAppearance(serverId, (host) => {
const { icon: _previousIcon, ...rest } = host.appearance;
return {
...host,
appearance: icon ? { ...rest, icon } : rest,
};
});
}
async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise<void> {
await this.updateHostAppearance(serverId, (host) => ({
...host,
@@ -2443,6 +2507,16 @@ export class HostRuntimeStore {
}));
}
refreshActiveLatencies(serverIds?: readonly string[]): void {
const targets = serverIds ?? this.hosts.map((host) => host.serverId);
for (const serverId of targets) {
const controller = this.controllers.get(serverId);
if (controller) {
void controller.refreshActiveLatency();
}
}
}
private updateHostAppearance(
serverId: string,
apply: (host: HostProfile) => HostProfile,
@@ -3296,6 +3370,7 @@ export interface HostMutations {
beginLinkPairing: () => LinkPairing;
renameHost: (serverId: string, label: string) => Promise<void>;
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
removeHost: (serverId: string) => Promise<void>;
removeConnection: (serverId: string, connectionId: string) => Promise<void>;
@@ -3311,6 +3386,7 @@ export function useHostMutations(): HostMutations {
beginLinkPairing: () => store.beginLinkPairing(),
renameHost: (serverId, label) => store.renameHost(serverId, label),
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
setHostBadgeDisplay: (serverId, badgeDisplay) =>
store.setHostBadgeDisplay(serverId, badgeDisplay),
removeHost: (serverId) => store.removeHost(serverId),
@@ -1578,18 +1578,9 @@ export function NewWorkspaceScreen({
? t("newWorkspace.refPicker.searching")
: t("newWorkspace.refPicker.noMatchingRefs");
// The prompt is where the user types; when a field's picker closes, focus returns there rather
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
// shows a read-only command preview, so its pickers keep returning focus to their field.
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
const handleComposerFocusInput = useCallback((focus: () => void) => {
composerFocusRef.current = { focus };
}, []);
const formStack = useNewWorkspaceForm({
isCompact,
isPending,
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
pluginItems: (
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
),
@@ -1691,7 +1682,6 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
error={errorMessage}
/>
) : (
@@ -1722,7 +1712,6 @@ export function NewWorkspaceScreen({
clearDraft={handleClearDraft}
autoFocus
autoFocusKey={launchFocusKey}
onFocusInput={handleComposerFocusInput}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
@@ -67,11 +67,6 @@ export interface NewWorkspaceFormProps {
isPending: boolean;
/** Plugin fields, drawn after the base ref. */
pluginItems: ReactNode;
/**
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
* one, focus returns to the field that opened the picker.
*/
restoreFocusRef?: RefObject<unknown>;
project: PickerControl & {
options: ComboboxOption[];
projectByOptionId: Map<string, HostProjectListItem>;
@@ -378,17 +373,7 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
*/
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
const { t } = useTranslation();
const {
isCompact,
isPending,
pluginItems,
restoreFocusRef,
project,
host,
isolation,
base,
launch,
} = props;
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
const projectPicker = useProjectPicker(project, isPending);
const isolationPicker = useIsolationPicker({
@@ -447,14 +432,13 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
open={host.openState}
onOpenChange={host.onOpenChange}
anchorRef={host.anchorRef}
restoreFocusRef={restoreFocusRef}
includeAddHost
onAddHost={host.onAddHost}
addHostTestID="new-workspace-host-picker-add-host"
searchable={false}
title={t("newWorkspace.fields.host")}
desktopPlacement="bottom-start"
desktopMinWidth={200}
desktopMinWidth={320}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
@@ -541,7 +525,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={project.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText="No projects available."
renderOption={projectPicker.renderOption}
footer={projectPicker.footer}
@@ -556,7 +539,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
desktopPlacement="bottom-start"
anchorRef={isolation.anchorRef}
restoreFocusRef={restoreFocusRef}
desktopMinWidth={280}
renderOption={isolationPicker.renderOption}
/>
@@ -573,7 +555,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={440}
anchorRef={base.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={base.emptyText}
toolbar={refPicker.toolbar}
renderOption={refPicker.renderOption}
@@ -590,7 +571,6 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={worktreePicker.anchorRef}
restoreFocusRef={restoreFocusRef}
emptyText={t("newWorkspace.worktreePicker.empty")}
renderOption={worktreePicker.renderOption}
/>
+136 -20
View File
@@ -83,6 +83,7 @@ import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifi
import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section";
import { IntegrationsSection } from "@/desktop/components/integrations-section";
import { isElectronRuntime } from "@/desktop/host";
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
import { useDesktopAppUpdater } from "@/desktop/updates/use-desktop-app-updater";
import { formatVersionWithPrefix } from "@/desktop/updates/desktop-updates";
import { resolveAppVersion } from "@/utils/app-version";
@@ -609,25 +610,92 @@ function HostVersionRow({
function getUpdateButtonLabel(
t: TFunction,
isInstalling: boolean,
latestVersion: string | null | undefined,
input: {
isInstalling: boolean;
isDownloading: boolean;
isActionable: boolean;
readyToInstall: boolean;
latestVersion: string | null | undefined;
},
): string {
if (isInstalling) return t("settings.about.updates.installing");
if (latestVersion) {
if (input.isInstalling) {
return input.isDownloading
? t("settings.about.updates.downloading")
: t("settings.about.updates.installing");
}
if (input.isActionable && !input.readyToInstall) {
if (input.latestVersion) {
return t("settings.about.updates.downloadTo", {
version: formatVersionWithPrefix(input.latestVersion),
});
}
return t("settings.about.updates.download");
}
if (input.latestVersion) {
return t("settings.about.updates.updateTo", {
version: formatVersionWithPrefix(latestVersion),
version: formatVersionWithPrefix(input.latestVersion),
});
}
return t("settings.about.updates.update");
}
function getUpdateModeDescription(t: TFunction, mode: DesktopUpdateMode): string {
if (mode === "off") return t("settings.about.autoUpdate.descriptions.off");
if (mode === "notify") return t("settings.about.autoUpdate.descriptions.notify");
return t("settings.about.autoUpdate.descriptions.automatic");
}
function getUpdateConfirmDialogCopy(t: TFunction, isUpdateReady: boolean) {
if (isUpdateReady) {
return {
title: t("settings.about.updates.installTitle"),
message: t("settings.about.updates.installMessage"),
confirmLabel: t("settings.about.updates.installConfirm"),
cancelLabel: t("common.actions.cancel"),
};
}
return {
title: t("settings.about.updates.downloadTitle"),
message: t("settings.about.updates.downloadMessage"),
confirmLabel: t("settings.about.updates.downloadConfirm"),
cancelLabel: t("common.actions.cancel"),
};
}
function DesktopUpdateProgressBar({ percent }: { percent: number }) {
const accessibilityValue = useMemo(() => ({ min: 0, max: 100, now: percent }), [percent]);
const fillStyle = useMemo(
() => [styles.aboutUpdateProgressFill, { width: `${percent}%` as const }],
[percent],
);
return (
<View
style={styles.aboutUpdateProgressTrack}
accessibilityRole="progressbar"
accessibilityValue={accessibilityValue}
testID="settings-about-update-progress"
>
<View style={fillStyle} />
</View>
);
}
function DesktopAppUpdateRow() {
const { t } = useTranslation();
const { settings, updateSettings } = useSettings();
const {
settings: desktopSettings,
isLoading: isLoadingDesktopSettings,
updateSettings: updateDesktopSettings,
} = useDesktopSettings();
const updateMode = desktopSettings.updates.mode;
const {
isDesktopApp,
status,
statusText,
availableUpdate,
downloadProgress,
errorMessage,
isChecking,
isInstalling,
@@ -637,12 +705,12 @@ function DesktopAppUpdateRow() {
useFocusEffect(
useCallback(() => {
if (!isDesktopApp) {
if (!isDesktopApp || isLoadingDesktopSettings || updateMode === "off") {
return undefined;
}
void checkForUpdates({ intent: "automatic", silent: true });
return undefined;
}, [checkForUpdates, isDesktopApp]),
}, [checkForUpdates, isDesktopApp, isLoadingDesktopSettings, updateMode]),
);
const handleCheckForUpdates = useCallback(() => {
@@ -666,17 +734,36 @@ function DesktopAppUpdateRow() {
[t],
);
const handleUpdateModeChange = useCallback(
(mode: DesktopUpdateMode) => {
void updateDesktopSettings({ updates: { mode } });
},
[updateDesktopSettings],
);
const updateModeOptions = useMemo(
() => [
{ value: "automatic" as const, label: t("settings.about.autoUpdate.options.automatic") },
{ value: "notify" as const, label: t("settings.about.autoUpdate.options.notify") },
{ value: "off" as const, label: t("settings.about.autoUpdate.options.off") },
],
[t],
);
const isUpdateReady = availableUpdate?.readyToInstall === true;
const isUpdateActionable = status === "available" && availableUpdate?.hasUpdate === true;
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
const actionableVersion = isUpdateActionable ? availableUpdate?.latestVersion : null;
const downloadPercent =
(isInstalling || status === "pending") && downloadProgress
? Math.max(0, Math.min(100, Math.round(downloadProgress.percent)))
: null;
const handleInstallUpdate = useCallback(() => {
if (!isDesktopApp) {
return;
}
void confirmDialog({
title: t("settings.about.updates.installTitle"),
message: t("settings.about.updates.installMessage"),
confirmLabel: t("settings.about.updates.installConfirm"),
cancelLabel: t("common.actions.cancel"),
})
void confirmDialog(getUpdateConfirmDialogCopy(t, isUpdateReady))
.then((confirmed) => {
if (!confirmed) {
return;
@@ -691,10 +778,7 @@ function DesktopAppUpdateRow() {
t("settings.about.updates.alertMessage"),
);
});
}, [installUpdate, isDesktopApp, t]);
const isUpdateReady = availableUpdate?.readyToInstall === true;
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
}, [installUpdate, isDesktopApp, isUpdateReady, t]);
if (!isDesktopApp) {
return null;
@@ -715,6 +799,18 @@ function DesktopAppUpdateRow() {
options={releaseChannelOptions}
/>
</View>
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.about.autoUpdate.label")}</Text>
<Text style={settingsStyles.rowHint}>{getUpdateModeDescription(t, updateMode)}</Text>
</View>
<SegmentedControl
value={updateMode}
onValueChange={handleUpdateModeChange}
options={updateModeOptions}
testID="settings-about-update-mode"
/>
</View>
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.about.updates.label")}</Text>
@@ -726,6 +822,7 @@ function DesktopAppUpdateRow() {
})}
</Text>
) : null}
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
</View>
<View style={styles.aboutUpdateActions}>
@@ -739,9 +836,15 @@ function DesktopAppUpdateRow() {
<Button
variant="default"
onPress={handleInstallUpdate}
disabled={isChecking || isInstalling || !isUpdateReady}
disabled={isChecking || isInstalling || !isUpdateActionable}
>
{getUpdateButtonLabel(t, isInstalling, readyUpdateVersion)}
{getUpdateButtonLabel(t, {
isInstalling,
isDownloading: isInstalling && downloadProgress != null,
isActionable: isUpdateActionable,
readyToInstall: isUpdateReady,
latestVersion: actionableVersion,
})}
</Button>
</View>
</View>
@@ -907,7 +1010,7 @@ function HostPicker({
showActiveConnection
searchable={false}
title={t("settings.hostPicker.switchHost")}
desktopMinWidth={240}
desktopMinWidth={328}
addHostTestID="settings-add-host"
hostOptionTestID={hostOptionTestID}
>
@@ -1506,6 +1609,19 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[2],
},
aboutUpdateProgressTrack: {
marginTop: theme.spacing[2],
height: 4,
maxWidth: 260,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface3,
overflow: "hidden",
},
aboutUpdateProgressFill: {
height: "100%",
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.accent,
},
placeholder: {
flex: 1,
alignItems: "center",
@@ -4,7 +4,12 @@ import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Pencil } from "lucide-react-native";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { AdaptiveRenameModal } from "@/components/rename-modal";
import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row";
@@ -13,12 +18,18 @@ import { SettingsSection } from "@/components/settings/headings/settings-section
import {
HOST_BADGE_DISPLAYS,
HOST_COLORS,
HOST_ICONS,
normalizeDetectedHostIcon,
resolveHostBadgeDisplay,
resolveHostIcon,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { useHostMutations } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { identityColor } from "@/styles/identity-colors";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
@@ -76,10 +87,112 @@ function colorLabel(t: TFunction, color: HostColor): string {
return t(`settings.host.appearance.color.options.${color}`);
}
function iconLabel(t: TFunction, icon: HostIcon): string {
return t(`settings.host.appearance.icon.options.${icon}`);
}
function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string {
if (detectedIcon) {
return t("settings.host.appearance.icon.autoDetected", {
icon: iconLabel(t, detectedIcon),
});
}
return t("settings.host.appearance.icon.auto");
}
function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string {
return t(`settings.host.appearance.badge.options.${display}`);
}
function IconMenuItem({
icon,
color,
selected,
onChange,
}: {
icon: HostIcon;
color: HostColor;
selected: boolean;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const handleSelect = useCallback(() => onChange(icon), [icon, onChange]);
const leading = useMemo(
() => <HostIconGlyph icon={icon} color={color} size={ICON_SIZE.sm} />,
[color, icon],
);
return (
<DropdownMenuItem selected={selected} onSelect={handleSelect} leading={leading}>
{iconLabel(t, icon)}
</DropdownMenuItem>
);
}
function IconRow({
icon,
detectedIcon,
resolvedIcon,
color,
onChange,
}: {
icon: HostIcon | null;
detectedIcon: HostIcon | null;
resolvedIcon: HostIcon;
color: HostColor;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const autoLabel = autoIconLabel(t, detectedIcon);
const selectedLabel = icon ? iconLabel(t, icon) : autoLabel;
const handleSelectAuto = useCallback(() => onChange(null), [onChange]);
const triggerLeading = useMemo(
() => <HostIconGlyph icon={resolvedIcon} color={color} size={ICON_SIZE.sm} />,
[color, resolvedIcon],
);
const autoLeading = useMemo(
() => <HostIconGlyph icon={detectedIcon ?? "server"} color={color} size={ICON_SIZE.sm} />,
[color, detectedIcon],
);
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.host.appearance.icon.label")}</Text>
</View>
<DropdownMenu>
<DropdownTrigger
testID="host-appearance-icon"
accessibilityRole="button"
accessibilityLabel={t("settings.host.appearance.icon.accessibilityLabel", {
value: selectedLabel,
})}
leading={triggerLeading}
>
{selectedLabel}
</DropdownTrigger>
<DropdownMenuContent side="bottom" align="end" width={220}>
<DropdownMenuItem
selected={icon === null}
onSelect={handleSelectAuto}
leading={autoLeading}
>
{autoLabel}
</DropdownMenuItem>
<DropdownMenuSeparator />
{HOST_ICONS.map((option) => (
<IconMenuItem
key={option}
icon={option}
color={color}
selected={option === icon}
onChange={onChange}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
</View>
);
}
function ColorSwatch({ color }: { color: HostColor }) {
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }],
@@ -205,9 +318,11 @@ function BadgeDisplayMenuItem({
*/
function BadgePreview({
host,
resolvedIcon,
badgeDisplay,
}: {
host: HostProfile;
resolvedIcon: HostIcon;
badgeDisplay: HostBadgeDisplay;
}) {
const { t } = useTranslation();
@@ -219,9 +334,10 @@ function BadgePreview({
serverId: host.serverId,
label: host.label,
color: host.appearance.color,
icon: resolvedIcon,
showLabel: badgeDisplay === "name",
},
[badgeDisplay, host.serverId, host.label, host.appearance.color],
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
);
// The real sidebar row, so the preview can't drift from what the setting actually does.
return (
@@ -244,8 +360,14 @@ function BadgePreview({
export function HostAppearanceSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const toast = useToast();
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind);
const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId;
const badgeDisplay = resolveHostBadgeDisplay({
appearance: host.appearance,
@@ -263,6 +385,16 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
},
[host.serverId, setHostColor, t, toast],
);
const handleIconChange = useCallback(
async (icon: HostIcon | null) => {
try {
await setHostIcon(host.serverId, icon);
} catch {
toast.error(t("errors.unableToSave"));
}
},
[host.serverId, setHostIcon, t, toast],
);
const handleBadgeDisplayChange = useCallback(
async (next: HostBadgeDisplay) => {
try {
@@ -288,11 +420,18 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
<HostRenameButton host={host} />
</View>
</View>
<IconRow
icon={selectedIcon}
detectedIcon={detectedIcon}
resolvedIcon={resolvedIcon}
color={host.appearance.color}
onChange={handleIconChange}
/>
<ColorRow color={host.appearance.color} onChange={handleColorChange} />
{badgeDisplay === null ? null : (
<>
<BadgeDisplayRow badgeDisplay={badgeDisplay} onChange={handleBadgeDisplayChange} />
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
</>
)}
</View>
+9
View File
@@ -293,6 +293,7 @@ export interface DaemonServerInfo {
serverId: string;
hostname: string | null;
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
@@ -303,6 +304,7 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
serverId: serverInfo.serverId,
hostname: serverInfo.hostname ?? null,
version: serverInfo.version ?? null,
...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}),
...(serverInfo.desktopManaged !== undefined
? { desktopManaged: serverInfo.desktopManaged }
: {}),
@@ -786,6 +788,7 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo: SessionState["serverInfo"] | undefined;
nextHostname: string | null;
nextVersion: string | null;
nextMachineKind: string | null;
nextDesktopManaged: boolean | undefined;
nextCapabilities: ServerCapabilities | undefined;
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
@@ -795,16 +798,19 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
} = input;
const prevHostname = currentServerInfo?.hostname?.trim() || null;
const prevVersion = currentServerInfo?.version?.trim() || null;
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
return (
currentServerInfo?.serverId === input.nextServerId &&
prevHostname === nextHostname &&
prevVersion === nextVersion &&
prevMachineKind === nextMachineKind &&
currentServerInfo?.desktopManaged === nextDesktopManaged &&
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
@@ -942,6 +948,7 @@ export const useSessionStore = create<SessionStore>()(
const nextHostname = info.hostname?.trim() || null;
const nextVersion = info.version?.trim() || null;
const nextMachineKind = info.machineKind?.trim() || null;
const nextDesktopManaged = info.desktopManaged;
const nextCapabilities = info.capabilities;
const nextFeatures = info.features;
@@ -951,6 +958,7 @@ export const useSessionStore = create<SessionStore>()(
currentServerInfo: session.serverInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
@@ -970,6 +978,7 @@ export const useSessionStore = create<SessionStore>()(
serverId: info.serverId,
hostname: nextHostname,
version: nextVersion,
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
...(nextDesktopManaged !== undefined
? { desktopManaged: nextDesktopManaged }
: {}),
+27 -5
View File
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
});
});
it("gives a host stored before appearance existed the default appearance", () => {
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_old",
connections: [
@@ -161,18 +161,35 @@ describe("normalizeStoredHostProfile", () => {
});
expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(profile && "icon" in profile.appearance).toBe(false);
});
it("loads a stored appearance the user chose", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_new",
appearance: { color: "teal", badgeDisplay: "icon" },
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" });
});
it("preserves an unknown stored icon intact without dropping the saved host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_future_icon",
appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({
color: "violet",
icon: "future-device",
badgeDisplay: "name",
});
});
it("normalizes stored Remote SSH connection parameters", () => {
@@ -340,12 +357,13 @@ describe("upsertHostConnectionInProfiles", () => {
});
expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null });
expect("icon" in profile.appearance).toBe(false);
});
it("keeps the appearance the user chose when the host reconnects", () => {
const existing: HostProfile = {
...makeHost("srv_known"),
appearance: { color: "amber", badgeDisplay: "hidden" },
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
connections: [],
};
@@ -355,7 +373,11 @@ describe("upsertHostConnectionInProfiles", () => {
connection,
});
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
expect(profile.appearance).toEqual({
color: "amber",
icon: "workstation",
badgeDisplay: "hidden",
});
});
it("replaces a direct connection when its settings change", () => {
+45 -2
View File
@@ -5,6 +5,7 @@ import {
createSelectionClipboardContent,
type MarkdownClipboardEnvironment,
type RichClipboardWriter,
writeClipboardContent,
writeMarkdownToRichClipboard,
} from "./rich-clipboard";
@@ -15,9 +16,9 @@ interface RecordingClipboard {
}
function createRecordingClipboard(
options: { supportsHtml?: boolean; richWriteFails?: boolean } = {},
options: { supportsHtml?: boolean; richWriteFails?: boolean; plainWriteResult?: unknown } = {},
): RecordingClipboard {
const { supportsHtml = true, richWriteFails = false } = options;
const { supportsHtml = true, richWriteFails = false, plainWriteResult } = options;
const richWrites: Array<Record<"text/plain" | "text/html", Blob>> = [];
const plainTexts: string[] = [];
@@ -35,6 +36,7 @@ function createRecordingClipboard(
richWriter,
writePlainText: async (text) => {
plainTexts.push(text);
return plainWriteResult;
},
};
@@ -185,3 +187,44 @@ describe("writeMarkdownToRichClipboard", () => {
expect(clipboard.richWrites).toEqual([]);
});
});
describe("writeClipboardContent", () => {
const content = { plainText: "_raw_ draft", html: "<p>\\_raw\\_ draft</p>" };
it("writes both flavors and reports the write", async () => {
const clipboard = createRecordingClipboard();
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
const written = clipboard.richWrites[0];
if (!written) {
throw new Error("Expected rich clipboard data to be written");
}
await expect(written["text/plain"].text()).resolves.toBe(content.plainText);
await expect(written["text/html"].text()).resolves.toBe(content.html);
});
it("falls back to the plain flavor when the rich write fails", async () => {
const clipboard = createRecordingClipboard({ richWriteFails: true });
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
expect(clipboard.plainTexts).toEqual([content.plainText]);
});
it("reports a plain write the host refused", async () => {
const clipboard = createRecordingClipboard({ supportsHtml: false, plainWriteResult: false });
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(false);
});
it("propagates a plain write that throws", async () => {
const environment: MarkdownClipboardEnvironment = {
writePlainText: async () => {
throw new Error("clipboard denied");
},
};
await expect(writeClipboardContent(content, environment)).rejects.toThrow("clipboard denied");
});
});
+14 -3
View File
@@ -86,19 +86,30 @@ export async function writeMarkdownToRichClipboard(
markdown: string,
environment: MarkdownClipboardEnvironment,
): Promise<void> {
await writeClipboardContent(createMarkdownClipboardContent(markdown), environment);
}
/**
* Writes both flavors, or `plainText` alone where the host has no rich clipboard.
* Resolves false when the host refused the write.
*/
export async function writeClipboardContent(
content: MarkdownClipboardContent,
environment: MarkdownClipboardEnvironment,
): Promise<boolean> {
if (environment.richWriter?.supportsHtml()) {
const content = createMarkdownClipboardContent(markdown);
try {
await environment.richWriter.write({
"text/plain": new Blob([content.plainText], { type: "text/plain" }),
"text/html": new Blob([content.html], { type: "text/html" }),
});
return;
return true;
} catch {
// Fall through to the plain-text path. Some webviews expose rich clipboard
// APIs but deny writes depending on focus, permissions, or browser policy.
}
}
await environment.writePlainText(markdown);
// Expo resolves false for a write the host refused, instead of rejecting.
return (await environment.writePlainText(content.plainText)) !== false;
}
@@ -143,3 +143,11 @@ export const Minimize = StubIcon;
export const Rows2 = StubIcon;
export const Gauge = StubIcon;
export const GripVertical = StubIcon;
export const Cloud = StubIcon;
export const Computer = StubIcon;
export const Container = StubIcon;
export const Cpu = StubIcon;
export const Laptop = StubIcon;
export const Network = StubIcon;
export const PcCase = StubIcon;
export const Waypoints = StubIcon;
+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",
@@ -38,7 +38,9 @@ describe("Hub CLI login browser flow", () => {
assert.equal(credential, "paseo_cli_prefix_durable-secret-value");
assert.deepEqual(journey.waits, [5_000, 5_000, 10_000]);
assert.deepEqual(journey.opened, ["https://hub.test/cli-login?code=ABCD-EFGH"]);
assert.deepEqual(journey.instructions, ["https://hub.test/cli-login ABCD-EFGH"]);
assert.deepEqual(journey.instructions, [
"Open https://hub.test/cli-login?code=ABCD-EFGH to approve CLI login (code: ABCD-EFGH)",
]);
});
it("does not open a browser in noninteractive mode", async () => {
@@ -57,7 +59,9 @@ describe("Hub CLI login browser flow", () => {
await journey.authorize();
assert.deepEqual(journey.opened, []);
assert.equal(journey.instructions.length, 1);
assert.deepEqual(journey.instructions, [
"Open https://hub.test/cli-login?code=ABCD-EFGH to approve CLI login (code: ABCD-EFGH)",
]);
});
});
@@ -95,7 +99,7 @@ class LoginJourney {
now: () => this.now,
},
browser: { open: async (url) => void this.opened.push(url) },
instructions: (url, code) => void this.instructions.push(`${url} ${code}`),
instructions: (message) => void this.instructions.push(message),
openBrowser,
});
}
+6 -4
View File
@@ -40,7 +40,7 @@ interface CliLoginFlowOptions {
hub: Pick<HubHttpClient, "startCliAuthorization" | "pollCliAuthorization">;
waiter: LoginWaiter;
browser: BrowserOpener;
instructions(verificationUri: string, userCode: string): void;
instructions(message: string): void;
openBrowser: boolean;
}
@@ -49,7 +49,9 @@ export class CliLoginFlow {
async authorize(origin: string): Promise<string> {
const authorization = await this.options.hub.startCliAuthorization(origin);
this.options.instructions(authorization.verificationUri, authorization.userCode);
this.options.instructions(
`Open ${authorization.verificationUriComplete} to approve CLI login (code: ${authorization.userCode})`,
);
if (this.options.openBrowser) {
await this.options.browser.open(authorization.verificationUriComplete).catch(() => undefined);
}
@@ -84,8 +86,8 @@ export function createCliLoginFlow(hub: HubHttpClient): CliLoginFlow {
now: Date.now,
},
browser: new SystemBrowser(),
instructions(verificationUri, userCode) {
process.stderr.write(`Open ${verificationUri} and enter code ${userCode}\n`);
instructions(message) {
process.stderr.write(`${message}\n`);
},
openBrowser: process.stderr.isTTY === true,
});
+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"
},
+14 -1
View File
@@ -754,13 +754,14 @@ class DaemonClientSession {
private readonly daemon = new FakeDaemon();
private readonly client: DaemonClient;
constructor() {
constructor(options: { livenessHeartbeat?: boolean } = {}) {
this.client = new DaemonClient({
url: "ws://test",
clientId: "clsk_heartbeat_test",
logger: noopLogger,
reconnect: { enabled: false },
transportFactory: () => this.daemon.transport,
...options,
});
clients.push(this.client);
}
@@ -3395,6 +3396,18 @@ test("starts pinging one interval after connecting and holds the cadence", async
expect(session.pingTimestamps()).toEqual(["10s", "20s", "30s"]);
});
test("a client with the liveness heartbeat off never pings on its own", async () => {
useHeartbeatClock();
const session = new DaemonClientSession({ livenessHeartbeat: false });
session.daemonAnswersPingsAfter("fast");
await session.connect();
await session.advance(60_000);
expect(session.state()).toEqual({ status: "connected" });
expect(session.pingTimestamps()).toEqual([]);
});
test("stops pinging once the connection is gone", async () => {
useHeartbeatClock();
const session = new DaemonClientSession();

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