Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andluke 8cd4cf96e9 Name the bare Git fixture explicitly
Co-authored-by: luke <luopeihuan@gmail.com>
2026-12-04 05:12:09 +00:00
paseo-bot[bot] b78548a87a Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-clone 2026-12-04 04:42:55 +00:00
Mohamed Boudra b947c229c6 fix(usage): keep local usage when Claude or Codex carries harmless flags (#11963)
* fix(usage): keep local usage when Claude or Codex carries harmless flags

PR #11154 treated any non-empty launch.args on stock claude or codex as an isolated wrapper launch, hiding local usage cards whenever users configured extra flags such as --chrome (regression reported in #11529).

- Extract a shared isWrapperLaunch helper in @getpaseo/plugin/server/usage and replace the three duplicate copies across provider-env.ts, claude-usage-source, and codex-usage-source.
- Keep renamed wrapper binaries isolated while only isolating stock binaries when args before -- include account/settings/provider-switching flags verified against claude --help (--settings, --setting-sources, --bare) or codex --help / codex app-server --help (-c, --config, -p, --profile, --oss, --local-provider, --remote, --remote-auth-token-env, --startup-sign-out).

Closes #11529

* refactor(usage): accept named input in isWrapperLaunch and test flag parity
2026-12-04 11:36:27 +07:00
Mohamed Boudra 2e3d9b375a feat(devices): fix client identity, expose daemon-observed IP, and polish Devices rows (#11902)
* feat(devices): fix client identity, expose daemon-observed IP, and polish Devices rows

Slice 1 of device identification and IP visibility:

- Extend HelloClientInfoSchema and DaemonSessionSummarySchema with additive optional fields (appKind, osName, osVersion, deviceModel, browserName, deviceKey, remoteIp, ipSource, authMethod).
- Pass clean --paseo-device-name and --paseo-os-version from desktop main into sandboxed preload and emit rich clientInfo across Electron, Web, Android, iOS, CLI, and connected hosts.
- Call resolveAppClientIdentity() in buildClientConfig() and routed probes (with persisted clientId) so probe-adopted Electron and Web sessions no longer report as Mobile.
- Sanitize client-claimed display strings, normalize daemon-observed direct/Tailscale/local remote IPs (stripping ::ffff:, omitting local_ipc/via/relay/hub), record authMethod, and add Electron User-Agent fallback for legacy direct clients.
- Polish Devices rows to show real device names, This device/transport/IP/OS hints, Reconnecting summary, monospace IP address, and plain Full access instead of a 9-pill dump across all 9 locales.

* fix(devices): isolate routed probe scopeId, avoid global window mutation in test, and tag COMPAT shims

* chore(protocol): drop COMPAT tag from permanent HelloClientInfo fields

* fix(devices): align authMethod display labels and test with daemon password auth

* chore(devices): remove duplicate authMethod assignment and dead auth label cases

* chore(devices): include added version in legacyBrowserHostLabel COMPAT tag
2026-12-04 11:34:53 +07:00
Mohamed Boudra 9cb4726c30 fix(finish-subscriptions): exclude finish-notice-only turns and queues from pending work (#11969)
* fix(finish-subscriptions): exclude finish-notice-only turns and queues from pending work

* fix(finish-subscriptions): clean retained turn history and test patterns
2026-12-04 11:34:29 +07:00
Mohamed Boudra 1544282593 Isolate oversized ACP stdout lines to the affected chat (#11894)
* fix(acp): bound ACP stdout lines and plugin IPC payloads at 64 MiB

Share the 64 MiB ProviderLineReader and createBoundedNdJsonStream helper in @getpaseo/protocol so both the direct server ACP reader and the plugin ACP reader fail only the affected request or session on oversized stdout lines instead of buffering unbounded payloads.

Add an iterative 64 MiB byte guard in the plugin worker before process.send/structuredClone so oversized plugin events or RPC payloads cannot crash the daemon worker in v8::ValueDeserializer, and preserve inline session.runtime_failed errors during prompt submission instead of retrying them as stale sessions.

Fixes #11580

* fix(acp): walk containers lazily, count DAG references, and skip non-object stdout

Use cursor/iterator frames in exceedsIpcByteLimit so huge sparse arrays fail before copying entries, count shared DAG references before jsonTransportValue stringifies plugin events, and log/ignore non-object JSON stdout lines in createLoggedNdJsonStream instead of ending the transport.

* fix(acp): race ACP requests only on stream limit and close on read errors

Do not race connection.closed ahead of processError in ACPAgentSession.runACPRequest so early startup exits preserve their stderr diagnostic, and close the readable stream instead of erroring it when closeOnStreamLimit is enabled so @agentclientprotocol/sdk 0.17.1 does not leak unhandled AbortError rejections.

* fix(plugins): send request.failed before closing oversized session open

Deliver request.failed over IPC before calling closeFailedSession on an oversized session.opened reply so inline session.closed events cannot mask the IPC size limit error.

* refactor(acp): drop plugin IPC object walker and keep stdout bounds

Keep only the 64 MiB byte-bounded NDJSON line reader at provider stdout boundaries and revert the plugin IPC payload size walker.
2026-12-04 11:34:22 +07:00
61d2ad1585 feat(plugin): embed an agent's conversation in plugin UI with AgentChat (#9602)
* feat(plugin): render an agent's timeline in plugin surfaces with AgentTimeline

Squash of getpaseo/paseo#9602 (feat/plugin-agent-timeline at fd29216a0) onto main.

Plugins can show an agent's timeline inside their own screens, panels and modals with
`AgentTimeline` from `@getpaseo/plugin/client/ui`. It renders the agent tab's own chain, so
plugin timeline items, history paging, streaming, permissions and the loading, catch-up, error
and archived states match the tab.

Discussion: https://github.com/getpaseo/paseo/discussions/9589

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

* feat(plugin): reshape the embed into AgentChat

Rename the embed to AgentChat. Timeline stays free for a future
data-driven display component with no agent.

- API: <AgentChat agentId hostId? composer?: false | { controls?: "all" | "none", placeholder? } testID? />.
  Per-control maps and composer items are left out; both can be added
  later as optional fields.
- The composer reuses the ComposerInputMode table with a new "message"
  mode (no attachments, voice, autocomplete, controls, usage or client
  commands) instead of a parallel controls-scope context.
- Embed focus follows the workspace pane rule: the embed the user last
  pressed owns the composer keys, while its pane or screen is in front.
  This removes the focus-owner, Portal wrapper and oxlint rule.
- Pane and embed share one AgentComposer, so the embed keeps draft
  revisions and submit loading.
- Example, reference (en, zh-CN), docs and the paseo-plugin skill use
  the new name.

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): give each AgentChat its own composer editing session

Inside a workspace plugin panel, every embed resolved the panel's one
editing session. Fullscreen in one embed expanded all of them, and
command hints and focus restore went to whichever composer attached
last. Each embed now edits in a session of its own, keyed by agent the
way a pane's session follows its target.

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(plugin): say what AgentChat's controls "none" does with draft files

The chat edits the agent's own draft, shared with its tab. "none" removes
every way to add files; files already in the draft show, can be removed,
and are sent.

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

* fix(app): keep pasted forge links as text in a composer without attachments

AgentChat's controls "none" composer still turned a pasted pull request
URL of the agent's repository into an attachment. Forge auto-attach now
follows the input mode, so a mode without attachments sends links as
written.

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

* test(app): stub the lucide icons the agent panel imports

AgentChat's lazy import puts the agent panel in the browser test graph.
Its icons were missing from the lucide stub, so Vite's dependency scan
failed, pre-bundling was skipped, and mid-run reoptimization broke
module imports in seven browser suites.

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

---------

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-04 11:16:14 +07:00
Mohamed Boudra 512f21ba64 Allow native plugin addons on macOS via Plugin Helper entitlements (#11958)
* fix(desktop): scope macOS disable-library-validation to Plugin Helper

Packaged macOS builds run with Hardened Runtime enabled and no
disable-library-validation entitlement, so community plugins that load
third-party native .node addons fail under dlopen.

Scope com.apple.security.cs.disable-library-validation and
com.apple.security.cs.allow-unsigned-executable-memory exclusively to
Paseo Helper (Plugin).app via a custom electron-builder mac.sign hook
while keeping Paseo.app (which holds com.apple.security.device.audio-input)
and the generic, GPU, and Renderer helpers strictly library-validated.
Route packaged macOS ELECTRON_RUN_AS_NODE launches (desktop daemon and
bundled CLI shim) through Paseo Helper (Plugin).app so the daemon and its
forked plugin workers inherit the Plugin Helper entitlements without Dock
icon or UI lifecycle side effects.

* refactor(desktop): keep electron-builder entitlements defaults in mac-sign hook

* test(desktop): use POSIX bundle paths in macOS signing test

* test(desktop): verify macOS helper entitlements and ad-hoc dlopen in packaged smoke

* test(desktop): assert Hardened Runtime flag and handle SIP-disabled macOS CI runners

* test(desktop): require exit 0 for SIP-disabled generic Helper smoke branch
2026-12-04 11:16:08 +07:00
paseo-bot[bot] 646b65e617 fix(app): complete finished replies after reconnect (#11970)
A missed turn-end event leaves the last reply in the live transcript. When catch-up accounts for those rows and the held turn is idle, commit them to history so timeline plugins receive the completed reply.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 04:12:48 +00:00
Ryan大然andMohamed Boudra 302afe1104 Scope window no-drag regions to drag surfaces and overlays (#11830)
* Keep scrolled sidebar, Files and Changes rows from cutting the titlebar

Electron computes the window drag area from app-region boxes without
clipping them to scroll viewports. Rows scrolled out of the sidebar
workspace list, the Files tree and filter results, and the Changes diff
still sat under the titlebar as no-drag boxes, so the blank titlebar
above them stopped moving the window.

These viewports are now window content, like the chat timeline and
sidebar nav rows: they emit no app regions, and their controls keep
normal DOM hit testing.

Fixes #11680

* Scope window no-drag regions to drag surfaces and overlays

The global interactive/tabindex no-drag rule in public/index.html caused
any unexempt scrolled viewport (#11680) and any parked resident browser
webview surface (tabindex=-1 inherited into its 1280x800 webview and
shadow iframe, #11844) to emit unclipped no-drag rectangles over the
titlebar, eventually freezing window movement during normal use.

Invert the rule so controls emit -webkit-app-region: no-drag only when
they can overlap a drag surface: inside TitlebarDragRegion containers,
inline drag surfaces, overlays/modals (#overlay-root, [role=dialog],
[aria-modal=true], [data-window-overlay-host]), or explicit window-owned
chrome controls ([data-window-no-drag]). Remove the per-viewport
data-window-content opt-out markers, and move WindowChromeSafeArea and
TitlebarDragRegion into CompactHeader so narrow desktop layouts remain
draggable (#9797).

Closes #11680
Closes #11844
Closes #9797

* Move desktop titlebar drag E2E spec to packages/desktop/e2e

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-04 10:53:53 +07:00
paseo-bot[bot] b14f61ce27 test(claude): keep the event stream check focused on stale turn output (#11959)
Session totals follow the result, and a background child can update its original tool card after the launching turn ends. Keep rejecting new output under the ended turn ID.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 03:42:52 +00:00
6b808bc67b Preserve literal paths in the commit file list (#11480)
* Preserve literal paths in the commit file list

* Build literal rename path fixtures from Git trees

* Keep signed commits in machine-readable Git history

Apply the regression reported at https://github.com/getpaseo/paseo/pull/11480#issuecomment-7338842841.

Co-authored-by: jamescordrey-ops <335786770+jamescordrey-ops@users.noreply.github.com>

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Shane Su <shane.su@maiscrm.com>
Co-authored-by: jamescordrey-ops <335786770+jamescordrey-ops@users.noreply.github.com>
2026-12-04 10:08:36 +07:00
paseo-bot[bot] 624c26aa91 fix(cli): show permission questions in permit ls (#11954)
Pi sends the question as the request title. Use that title when the request lacks a description so CLI users can read the prompt before responding.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 02:12:50 +00:00
paseo-bot[bot]andBrandon Elliott 476ad7f414 Open desktop plugin links in the system browser (#11951)
* fix(desktop): open plugin links in the system browser

The main renderer relied on Electron’s default popup behavior for links opened with Linking or window.open. Use the same external opener as the plugin SDK for HTTP(S) links.

Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>

* test(desktop): cover Electron popup exceptions

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
2026-12-04 01:12:56 +00:00
paseo-bot[bot] b1a9fe8950 test(cli): keep host provider CLIs out of the status auth daemon (#11952)
daemon status probes every provider CLI on the daemon's PATH, and the
CLI waits 1.5 s for the reply. On a loaded runner the real claude,
codex and opencode probes ran past that, so the terminal cleanup
regression got a timeout note or exit 1. Give the shared daemon an
empty PATH; the slow-provider daemon keeps testing the timeout.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 00:30:20 +00:00
paseo-bot[bot] fe70975e89 fix(server): preserve the non-Git checkout diff error (#11940)
The legacy checkout diff adapter treated a missing Git worktree as an unknown error. Preserve the diff engine’s code so callers can distinguish this case.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 23:43:12 +00:00
SunicemanandShane Su 4df3da2c4e Focus the web window when a notification is clicked (#11445)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-12-03 23:42:39 +00:00
e2d6dc9f70 Keep agent background work running through plugin reloads (#11938)
* fix(server): keep background work running when a plugin changes an agent's launch

When a plugin change alters an agent's launch (env, instructions, MCP
servers or tools), the next idle prompt reopens the provider session.
needsPluginSessionReload only checked for a turn in flight, so an agent
whose turn had ended but whose background shells, monitors or provider
subagents were still running had them killed by the reopen.

The reopen now waits while the agent has provider background work or a
running provider subagent. The session stays stale, so the first idle
prompt after that work ends reopens it. Daemon-owned items such as
heartbeats outlive the session and do not hold the reopen back.

Co-authored-by: Zayooo00 <92038816+Zayooo00@users.noreply.github.com>

* fix(server): use live subagent activity when deferring plugin reload

The provider subagent store now reads persisted history asynchronously. Use the same live activity that AgentManager tracks when closing a session.

* Check provider runtime safety before plugin reopens

---------

Co-authored-by: Zayooo <mrcold135@gmail.com>
Co-authored-by: Zayooo00 <92038816+Zayooo00@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 23:12:58 +00:00
paseo-bot[bot] ea96a126af Keep GitHub Enterprise PR features available when a secondary login expires (#11937)
* fix(server): keep Enterprise PR features available with an expired secondary login

GitHub CLI auth status checks inactive logins too. Probe Enterprise hosts with the same active login as repository commands so an expired secondary login does not block the workspace.

* fix(server): check the active GitHub CLI login on github.com

* test(server): pause at the workspace PR status read

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 22:13:13 +00:00
paseo-bot[bot] f3fc583a76 Update the original row when a Codex background command finishes (#11934)
* fix(server): settle Codex background commands on their original row

A shell command can finish after its turn has ended. Keep the command’s original turn ID so its completion updates the running timeline row.

* test(server): drive background command start through Codex fake

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 22:12:50 +00:00
paseo-bot[bot]andClaude Opus 5.5 32cae04627 Wait for the plugin results route after a directory search (#11939)
The URL changes as soon as the directory submits a search, but the
results route renders only after its registry server call returns. On a
loaded CI runner that call took over 5 s, so the WebKit test failed at
the results heading. Give the directory-to-results transition the same
10 s budget the missed-input-event test already used, in one helper.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 21:18:20 +00:00
Ryan大然andpaseo-bot[bot] a73e1c6a5b End prose file links at CJK and fullwidth punctuation (#11421)
* End prose file links at CJK and fullwidth punctuation

Assistant prose treated CJK punctuation (:,。()「」、…) as path characters,
so `说明:A/B/C/D` linked the whole run and real paths next to such
punctuation, like `修改:src/index.ts,`, were not linked at all. Path
characters now exclude the same punctuation ranges that already end bare
URLs; CJK letters stay allowed, so `docs/说明.md` still links.

Refs #10994

* test(app): cover reported bare file links next to CJK punctuation

Check link targets after the Markdown parser and link recognizer run together. Cover two paths separated by an ideographic comma and preserve a line suffix on a CJK filename.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 20:42:43 +00:00
paseo-ai[bot] 0cdaa292f0 fix: update lockfile signatures and Nix hash [skip ci] 2026-12-03 18:53:53 +00:00
Mohamed Boudra 39d37e1e16 chore(release): reconcile 0.19.1 into main (#11927) 2026-12-04 01:45:26 +07:00
paseo-bot[bot] 7eb6ea9882 Finish daemon shutdown when WebSocket peers stop responding (#11880)
* fix(server): finish daemon shutdown when WebSocket peers stop responding

A silent peer can keep the worker waiting for a WebSocket close event past its shutdown deadline. Bound the handshake for attached and pending sockets so the worker can finish cleanup.

* Run daemon shutdown regression in server integration tests

* Allow slow ACP fixture startup in coalescing test

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 18:13:34 +00:00
SunicemanandShane Su cb9dbce82d fix(acp): select effort levels alongside thinking toggles (#11444)
Co-authored-by: Shane Su <shane.su@maiscrm.com>
2026-12-03 18:12:47 +00:00
Mohamed Boudra ee21a56c7f test(app): keep queued message intact when tapping Send to steer (#11928)
* test(app): keep queued message intact when tapping Send to steer

PR #11915 changed direct steer and interrupt sends to preserve queued messages in the composer queue track instead of sweeping them into the direct prompt. Update the browser E2E step to assert that the queued row remains queued when steering with a tap.

* test(app): wait for steer acknowledgement before asserting queue preservation
2026-12-04 01:06:21 +07:00
15ea9d0f03 Allow slower relay connections in CLI commands and status probes (#11449)
* Allow slower relay connections in CLI commands and status probes

* Test slow relay connections through the CLI

* Use the longer relay budget without a new setting

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Shane Su <shane.su@maiscrm.com>
2026-12-03 16:43:17 +00:00
99b0b5e1ed Generate workspace names for image-only opening messages (#11233)
* Generate workspace names for image-only opening messages

* Name image-only workspaces created through agent.create

Schedule directory workspace naming when the opening prompt contains attachments. Cover both daemon creation requests with an inline screenshot and empty text.

Co-authored-by: jamescordrey-ops <jamescordrey-ops@users.noreply.github.com>

* Keep inline image counts inside workspace naming

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: jamescordrey-ops <jamescordrey-ops@users.noreply.github.com>
2026-12-03 16:42:49 +00:00
paseo-bot[bot] 9f3ac9aca5 fix(server): keep Claude MCP credentials out of launch arguments (#11911)
A failed or unrecognized launch version probe selected inline MCP configuration. Send MCP configuration over stdin and show an update error when the probe identifies an older Claude Code.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 23:22:33 +07:00
paseo-bot[bot]andqwertyzhu eca1149db0 fix(server): resolve unique agent ID prefixes in Paseo agent tools (#8556) (#11920)
Co-authored-by: qwertyzhu <126236314+qwertyzhu@users.noreply.github.com>
2026-12-03 15:43:24 +00:00
KiritoXD 078dcfb1ab fix(cli): preserve sibling paths in worktree listings (#11918) 2026-12-03 15:42:57 +00:00
paseo-bot[bot] 8d87e400b0 Build only the old subpath's imports in the published-entry test (#11922)
The protocol test that checks the 0.11.4 import path compiled the whole
package (97 modules) with tsc before running a consumer against it. On CI
that took 17-20 s of a 30 s limit while other test files ran in parallel,
and it timed out at 32.7 s on main. Compile only the two entries and the
41 modules they import, with the package's own tsconfig.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 15:33:00 +00:00
Mohamed Boudra ca2de1d741 fix(server): preserve queued messages on direct sends and default agent messages to steer (#11915)
* fix(server): preserve queued messages on direct sends and default agent messages to steer

* fix(server): let Send now promote with steer replace non-steering active turns

* fix(server): preserve outer providerMessageId on bundled rewind and move allowReplace into options

* fix(agent): preserve providerMessageId in provider history sync and timeline import

* fix(agent): omit empty steerOptions unless allowReplace is disabled

* fix(agent): address Neon review blockers in delivery and envelope ownership

* fix(agent): keep 10s collecting cap active for finish notices under waiting human messages
2026-12-03 22:21:59 +07:00
KiritoXDandpaseo-bot[bot] e60cd200e8 Resolve relative CLI clone destinations from the caller (#11901)
* fix(cli): resolve relative clone destinations from the caller

* Use the clone fixture Git configuration explicitly

Co-authored-by: KiritoXDone <58523182+KiritoXDone@users.noreply.github.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 14:42:55 +00:00
KiritoXD 005c3c4e65 fix(cli): preserve agent paths outside the home directory (#11906) 2026-12-03 14:13:06 +00:00
Mohamed Boudra f2e5d0d982 Make hello.rejected evolvable with unified in-place refusal recovery (#11895)
* feat(protocol,app): make hello.rejected evolvable with unified HostRefusalSheet

* fix(app): parse short host label for relay pairing link refusals in AddHostModal
2026-12-03 20:31:20 +07:00
paseo-bot[bot]andClaude Opus 5.5 8ebe37558d Wait out reconnect backoff in Settings restart e2e tests (#11910)
The app reads the replacement worker only after it reconnects, and
reconnect attempts back off from 1.5 s to a 30 s cap. A worker that becomes
ready just after an attempt is seen up to 30 s later, so the 30 s wait for
the restart result failed on main run 47056309460.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:47:45 +00:00
Mohamed Boudra dcd10a6029 feat(auth): manage daemon passwords live from Devices UI, RPC, and CLI (#11892)
* feat(auth): manage daemon passwords live from Devices UI, RPC, and CLI

Let users set, change, and remove a daemon's password without restarting the daemon so passwordless hosts can be hardened in place and evicted remote sessions lose access immediately.

- Add DaemonPasswordStore and PasswordAttemptLimiter as the live hash authority across WebSocket handshakes, HTTP bearer endpoints, agent MCP auth, and daemon.config.reload, bounding bcrypt concurrency and pacing repeated failures.
- Add backward-compatible daemon.auth.password.set.request/.response (gated on server_info.features.daemonPasswordManagement and requiring both daemon.manage and access.manage) plus live eviction of non-local active sockets, 90-second retained external sessions, peer host links, and session-tagged network tunnels.
- Update paseo daemon set-password (with --remove) to apply live via RPC when the daemon is running and fall back to persisted config when stopped.
- Add the Access -> Password row and Set/Change/Remove sheet in Settings -> Host -> Devices, plus an inline Set password step inside the Relay pairing sheet so warning alerts and password protection stay visible without stacking modals.
- Use make-before-break reconnects in HostRuntime when updating a host password and avoid persisting plaintext daemon passwords into local-credential-only host profiles.

* fix(auth): address review findings on password rotation, trust isolation, throttling, and CLI fallback

- Track password store version across async header-auth and hello password verification so a rotation during bcrypt comparison rejects the old-password socket instead of attaching it.
- Include auth trust scope (local_credential / hub / remote) in sessionConnectionKey so remote sockets sharing a clientId can never merge into or inherit local_credential trust.
- Propagate throttled password attempts as WebSocket close 1013 ('Too many password attempts') instead of 4401 'Incorrect password'.
- In paseo daemon set-password, only fall back to offline config edits when no daemon process is running, prefer local credentials for local instances even when PASEO_PASSWORD is set in the shell, pass connected password as currentPassword on remote/password sessions, and reuse DAEMON_PASSWORD_MAX_UTF8_BYTES from @getpaseo/server/auth.

* test(cli): use valid PID lock fixture and assert DAEMON_UNREACHABLE in set-password test

* fix(auth): enforce password store version checks inside verify and setPassword
2026-12-03 19:44:59 +07:00
Mohamed Boudra 5e16d70aaa fix(desktop): scope browser automation tabs, uploads, routing, and profile partitions (#11893)
* Scope desktop browser automation tabs, uploads, routing, and profile partitions

- Key registered browser tabs, active tab tracking, and automation commands by (serverId, workspaceId) across Electron main, preload, app runtime, and server browser tools, failing closed when either is absent.
- Scope browser_upload in Electron main to verified local workspace directories using canonical realpathSync regular-file containment and reject uploads when no local uploadRoot is provided.
- Fail closed in classifyHostBrowserRouting when a host profile has no saved connections and no active connection.
- Release removed profile partitions from BrowserProxyManager in paseo:browser:remove-profile so deleted partitions cannot re-attach or hold stale proxy bindings.

* Capture profile release generation before route setup and make race test deterministic
2026-12-03 19:44:22 +07:00
paseo-bot[bot]andClaude Opus 5.5 b89eae1eff Fix red main cli-tests after #11376 and run them on plugin changes (#11882)
* Crash the sigint-supervisor test provider during a turn

#11376 closes an idle resumable ACP session cleanly when its process
exits, so the test's idle crash no longer raises error attention and
main's cli-tests fail. Exit the provider while its turn is open, the
case that still reports an error.

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

* Run cli-tests when the plugin runtime changes

The CLI E2E suite drives ACP providers through packages/plugin, but the
cli path filter skipped it for plugin-only changes, so #11376 merged
without the test it broke.

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

* Wait for the crashing provider to log its prompt before killing it

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:00:56 +00:00
Mohamed Boudra 32496c489e Enforce caller lineage, mode ceilings, and reserved labels on agent MCP tools (#11862)
* Enforce caller lineage, mode ceilings, and reserved labels on agent MCP tools

* Reshape agent caller policy around lineage, ceiling, and label primitives

* Honor inherited same-provider options and require caller policy dependencies
2026-12-03 17:54:37 +07:00
KiritoXD da51ac3d64 fix(cli): resolve local worktree creation paths from the caller (#11870) 2026-12-03 10:42:58 +00:00
KiritoXD 0ec89b5623 fix(cli): resolve script workspaces across all directory matches (#11873) 2026-12-03 10:12:56 +00:00
paseo-bot[bot]andClaude Opus 5.5 12d28ddbc8 Keep the running ring and tool-call shimmer on the same frames (#11863)
* Keep the ring and the shimmer on the same frames at every frame time

The status ring and the tool-call shimmer step on one 30 Hz grid counted
from the document timeline's origin. Each loop computes a step boundary
from its own duration. Every third boundary is a whole millisecond, and
a frame stamped exactly on one can round to before it for the ring and
after it for the shimmer. The two then turn over on consecutive frames,
and the window draws an extra frame. Start the grid 2.5 µs in, so no
boundary falls on a frame stamp.

The idle-chat running-indicators test read the animating elements right
after the chat opened, while the composer's 200 ms border-color
transition could still run. Wait for the page to settle first.

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

* Require a turnover from each loop at every boundary in the grid test

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:00:34 +00:00
Mohamed Boudra f621e31f3e docs(changelog): place Security and Plugins before Fixed in 0.19.0 (#11877) 2026-12-03 15:48:17 +07:00
paseo-bot[bot] c9ba30194c Notify parent agents when a queued Claude steer finishes (#11872)
* fix(server): notify parents after queued Claude steers finish

Claude can run a queued steer as its own turn. Keep the finish subscription active while that steer is pending in the live query.

* test(server): release Claude Stop hook after the steer queues

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 08:43:05 +00:00
Geo Qiao fa185cb063 fix(acp): close idle resumable plugin sessions cleanly (#11376)
Report an unexpected idle exit as a clean session close after a persistent
session is ready and its ACP peer advertises session/load. This lets the
host reopen on the next prompt without adding a failed turn to the timeline.

Keep runtime errors for interrupted work and sessions that cannot reopen.
Track retirement cleanup and retain errors from the existing cancel path.
2026-12-03 08:12:57 +00:00
paseo-ai[bot] 723df269d2 fix: update lockfile signatures and Nix hash [skip ci] 2026-12-03 08:04:59 +00:00
Mohamed Boudra f86c58b42b chore(release): reconcile v0.19.0 (#11868) 2026-12-03 14:55:32 +07:00
paseo-bot[bot] 1cfadda498 fix(server): keep Codex Auto-review after a startup probe timeout (#11865)
A transient version timeout published a ready catalog without Auto-review. Retry once before deciding whether the installed version supports the mode.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-03 07:43:10 +00:00
paseo-bot[bot]andXu Kang 776210b72b fix(server): publish closed agent renames to subscribers (#11856)
A rename saved after the provider runtime closed left subscribed clients displaying stale metadata. Publish the saved record through the existing stored agent state event.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Xu Kang <80628347+xilinshancun@users.noreply.github.com>
2026-12-03 07:14:22 +00:00
SunicemanandShane Su 80bcbdc931 Toggle the direct host SSL checkbox with Space (#11477)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-12-03 07:13:14 +00:00
lukeandRoundRedDot 5dee36e9ae refactor(server): use named Git checkout arguments
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:40:04 +08:00
lukeandRoundRedDot 8af3380124 Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-auth-review
# Conflicts:
#	packages/server/src/server/plugins/managed-source.posix.test.ts

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:23:54 +08:00
lukeandRoundRedDot a14826c8fd fix(server): preserve credentials during filtered plugin checkout
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:20:52 +08:00
lukeandRoundRedDot f00b32dbe6 perf(server): clone Git plugin sources without history blobs
- Use blobless clone filter when fetching Git plugin sources to improve install performance
- Add POSIX test verification for blobless git operations

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 09:22:00 +08:00
318 changed files with 23507 additions and 2629 deletions
+2 -1
View File
@@ -89,8 +89,9 @@ relay:
- "packages/relay/**"
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
# plugins included, so daemon changes run it too.
# plugins and the plugin runtime included, so their changes run it too.
cli:
- "packages/cli/**"
- "packages/server/**"
- "packages/plugin/**"
- "plugins/**"
+21 -21
View File
@@ -32,6 +32,15 @@
- Paseo CLI and daemon now require Node.js 22.16.0 or later ([#11410](https://github.com/getpaseo/paseo/pull/11410))
- Relay connections now require [protected end-to-end encryption](https://paseo.sh/docs/security) by default, so apps older than 0.13.0 cannot connect through the relay ([#11864](https://github.com/getpaseo/paseo/pull/11864))
### Security
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
### Added
- Added Antigravity quota to Usage, refreshed only when you select Refresh ([#11585](https://github.com/getpaseo/paseo/pull/11585))
@@ -65,6 +74,18 @@
- Changed Cmd/Ctrl+click on a sidebar workspace to open it instead of entering select mode ([#11472](https://github.com/getpaseo/paseo/pull/11472))
- Changed agents that already reported to their caller with `send_agent_prompt` to skip the extra finished notice ([#11583](https://github.com/getpaseo/paseo/pull/11583))
### Plugins
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
### Fixed
- Fixed thinking level, mode and model changes on a running agent snapping back to the old value ([#11850](https://github.com/getpaseo/paseo/pull/11850))
@@ -163,27 +184,6 @@
- Fixed `paseo daemon status` leaving out unconfirmed terminal cleanup ([#11658](https://github.com/getpaseo/paseo/pull/11658) by [@chirag127](https://github.com/chirag127))
- Fixed CLI archive, detach and reload scanning all agent history for a full agent ID ([#11617](https://github.com/getpaseo/paseo/pull/11617) by [@maci0](https://github.com/maci0))
### Security
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
### Plugins
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
## 0.18.2 - 2026-11-30
- **Redesigned model picker:** Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings. ([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
+21 -21
View File
@@ -32,6 +32,15 @@
- Paseo CLI 和 daemon 现在需要 Node.js 22.16.0 或更高版本 ([#11410](https://github.com/getpaseo/paseo/pull/11410))
- 中继连接现在默认要求[受保护的端到端加密](https://paseo.sh/zh-CN/docs/security),因此 0.13.0 之前的应用无法再通过中继连接 ([#11864](https://github.com/getpaseo/paseo/pull/11864))
### 安全
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
### 新增
- 在用量中新增 Antigravity 配额,仅在选择 **刷新** 时更新 ([#11585](https://github.com/getpaseo/paseo/pull/11585))
@@ -65,6 +74,18 @@
- 在侧边栏中 Cmd/Ctrl+点击工作区改为打开该工作区,而不再进入选择模式 ([#11472](https://github.com/getpaseo/paseo/pull/11472))
- 已通过 `send_agent_prompt` 向调用方汇报的 Agent 不再额外发送完成通知 ([#11583](https://github.com/getpaseo/paseo/pull/11583))
### 插件
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
### 修复
- 修复更改运行中 Agent 的思考强度、模式和模型后又跳回旧值的问题 ([#11850](https://github.com/getpaseo/paseo/pull/11850))
@@ -163,27 +184,6 @@
- 修复 `paseo daemon status` 遗漏未确认的终端清理的问题 ([#11658](https://github.com/getpaseo/paseo/pull/11658),贡献者:[@chirag127](https://github.com/chirag127))
- 修复 CLI 归档、分离和重新加载时为匹配完整 Agent ID 而扫描全部 Agent 历史记录的问题 ([#11617](https://github.com/getpaseo/paseo/pull/11617),贡献者:[@maci0](https://github.com/maci0))
### 安全
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
### 插件
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
## 0.18.2 - 2026-11-30
- **重新设计的模型选择器**:桌面端采用支持跨 Provider 搜索的双栏视图,手机端合并为带思考强度滑块的单层抽屉,并支持在设置中按 Provider 筛选常用模型。([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
+8 -5
View File
@@ -232,9 +232,11 @@ at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. A child can end its turn with work that will start its next
turn by itself: a running turn, queued messages, a pending provider wake-up
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
crons, change-request watches, and other daemon background items never count: they are external
triggers, not work the caller is waiting for.
wake-ups), or the child's own outstanding finish subscriptions as a caller. Queued finish notices
(`agent-notification`) and turns started only by finish notices do not count as pending work
unless a real prompt is batched into or steered into the turn. Heartbeats, recurring crons,
change-request watches, and other daemon background items never count: they are external triggers,
not work the caller is waiting for.
Every turn end reports `finished` at once, unless the child already sent an agent message to its
caller during that turn and started no further tool work afterwards. In that case the child's
@@ -243,8 +245,9 @@ ends silently, and a watch with pending work keeps following silently until a la
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
pending on an unreported turn end, the notice names it and the subscription follows the child: each
later turn end reports `finished` again, and the child settling with nothing pending sends a final
`finished` and removes the subscription, even when the work drains without another turn. Reporting
later turn end reports `finished` again, except that a turn started only by finish notices while
already following keeps following without another interim notice; the child settling with nothing
pending still sends the final `finished` and removes the subscription, even when the work drains without another turn. Reporting
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
reply. Following is what lets the caller hear the reply a background task wakes up later
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
+13 -1
View File
@@ -445,6 +445,16 @@ workspace only. Location controls hosting, not context. An agent panel target ke
when moved between hosts. Explorer configuration can create workspace-context panels and remove
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
a `ConversationSurface` instead of reading the pane: a pane has a tab to retarget and a pill track,
an embed has neither, so its composer handles `/clear` by opening the agent's workspace and the
track is never mounted. The embed publishes itself as a viewer with `useViewedAgent`, the hook the
workspace sheet uses, so the tab and every embed of one agent share the sync's single observation.
`controls: "none"` is the composer's `message` input mode (`composer/input-mode.ts`). Key focus
follows the pane rule: the embed the user last pressed owns Escape and send, while its pane or
screen is in front.
Command Center callbacks use the selected host's existing `PaseoApi` for normal Paseo operations.
They use typed plugin RPC only for plugin-specific backend work. Surface and panel navigation
belongs to the app; plugins do not receive Expo Router or workspace-layout store access.
@@ -482,7 +492,9 @@ configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpS
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
the provider process, so a reload must not reopen agents the plugin does not change.
the provider process, so a reload must not reopen agents the plugin does not change, and a changed
launch waits until the agent's provider subagents and background work end. If the provider cannot
confirm that its runtime is safe to stop, the session stays open for the prompt.
### Launch wrap
+1 -1
View File
@@ -10,7 +10,7 @@ Two contracts follow from it.
A schema change must not break parsing in either direction. An old app still parses messages from a new daemon. A new daemon still parses messages from an old app.
`hello` carries an optional credential. The daemon accepts a client protocol version from its minimum through newer client versions, selects the lower of client and daemon maximum, and reports it as optional `server_info.protocolVersion`. A `hello.rejected` frame precedes an auth close only when the client sent `hello.auth` or advertised `hello_rejection`; older clients receive the existing WebSocket close code and reason. This avoids sending them a new top-level message their validator does not recognize.
`hello` carries an optional credential. The daemon accepts a client protocol version from its minimum through newer client versions, selects the lower of client and daemon maximum, and reports it as optional `server_info.protocolVersion`. A `hello.rejected` frame precedes a refusal close only when the client sent `hello.auth` or advertised `hello_rejection` or `evolvable_hello_rejection`; older clients receive only the WebSocket close code and reason so their validator does not reject an unknown top-level envelope. Clients advertising `evolvable_hello_rejection` accept open `reason`, optional `accepts`, and optional `message` fields and halt reconnects on any refusal. Reserve `hello.rejected` for refusals that require user or client-version action; transient restarts and temporary unavailability close the socket without `hello.rejected` so clients reconnect automatically. For `hello_rejection`-only clients, the daemon downgrades unknown reasons to `password_required` (when `accepts` includes `"password"`) or `incompatible_protocol`, restricts `accepts` to `["password"]` or `[]`, and omits `message`.
- New fields are `.optional()` with a sensible default.
- Never flip optional to required, remove a field, or narrow a type. `string` to `enum` and nullable to non-null are both narrowing.
+2
View File
@@ -971,6 +971,8 @@ question.
you got wrong, rank every highlight again, and then edit the file. Moving only the named item
leaves the same mistake in the others.
Order sections as `Breaking`, `Security`, `Added`, `Improved`, `Changed`, `Plugins`, `Fixed` (omitting empty sections) so `Security` and `Plugins` stay visible above a long `Fixed` list.
Bullets within each section (Added, Changed, Fixed) follow this order:
1. **User-facing features and changes first** — things users will notice, want to try, or that change their workflow.
+8 -2
View File
@@ -97,13 +97,19 @@ Two more reasons the stylesheet route does not work here:
- Unistyles owns style conversion on web, so React Native Web's `animationKeyframes` is ignored.
- React Native Web's `StyleSheet.create` validation deletes `animationName` in development.
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
Indicators that must move together use `phase: "shared"`, which starts the loop at the step
grid's origin instead of at mount. Every ring and every loader is then at the same point of its
cycle wherever and whenever it mounted. `phase: "own"` starts the loop at the beginning of the
current grid step, so its steps still turn over with the shared loops. A stepped animation sets its easing on the keyframes:
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
even steps. The compositor then draws a frame when a step changes and none in between.
The grid's origin is 2.5 µs after the document timeline's, not at it. Browsers stamp frames on
whole microseconds, and each loop computes a step boundary from its own duration. A boundary that
falls exactly on a frame's stamp can then round to before that frame for the ring and after it for
the shimmer, so they turn over on consecutive frames. With the origin at 0, every third boundary is
a whole millisecond and lands on a stamp. Off by 2.5 µs, no boundary does.
## Native
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
+1 -1
View File
@@ -1 +1 @@
sha256-oBd6CQ8+BhzMHhrpRIwzojuFPUwqXpgc3ZAPqKPs5QQ=
sha256-xt1xi8llKklgr6gn21Ae+Jmdke4bjMZ0F+CnR1bh8UE=
@@ -20,6 +20,9 @@ import {
readTerminalProcessIds,
} from "../support/helpers/daemon-lifecycle";
// Page setup takes up to 30 s, then a restart can take DAEMON_RESTART_TIMEOUT_MS to confirm.
test.describe.configure({ timeout: 120_000 });
test("settings restart waits for a replacement worker while retaining the supervisor", async ({
page,
}, testInfo) => {
@@ -51,16 +51,18 @@ test("lists connected clients with scopes and navigates Pair a device → Relay
});
try {
await openDevicesPage(page, daemon);
await expectConnectedClientRow(page, "This device", "Full access");
await expandConnectedClientRow(page, "This device");
await expect(
page
.getByTestId("devices-connected-clients-card")
.getByText("access.manage", { exact: true }),
).toBeVisible();
await expectConnectedClientRow(page, /^Chrome on /, "Full access");
await expandConnectedClientRow(page, /^Chrome on /);
const card = page.getByTestId("devices-connected-clients-card");
await expect(card.getByText("IP address", { exact: true })).toBeVisible();
await expect(card.getByText("127.0.0.1", { exact: true })).toBeVisible();
await expect(card.getByText("access.manage", { exact: true })).toHaveCount(0);
await viewer.connect();
await expectConnectedClientRow(page, "Test Phone", "Read-only");
await expandConnectedClientRow(page, "Test Phone");
await expect(card.getByText("daemon.read", { exact: true })).toBeVisible();
await expect(card.getByText("workspace.read", { exact: true })).toBeVisible();
await openPairDeviceModal(page);
await expectPairingOffer(page);
@@ -0,0 +1,349 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openCommandCenter } from "../support/helpers/command-center";
import {
openAgentRoute,
seedMockAgentWorkspace,
type MockAgentWorkspace,
} from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-focus-e2e";
const SCREEN_TITLE = "Embeds";
const PHONE = { width: 390, height: 844 };
interface EmbedComposer {
controls?: "all" | "none";
}
/**
* A screen with one `AgentChat` per agent under a header of its own, plus a client slash command
* that a full composer runs and a `controls: "none"` composer sends as text. A button opens the
* first agent's chat in a plugin modal too, and a workspace panel shows the same chats side by side.
*/
function pluginSource(input: { agentIds: string[]; composer: EmbedComposer }): string {
return `import { useCallback } from "react";
import { Pressable, Text, View } from "react-native";
import { AgentChat, Modal, SidebarRow } from "@getpaseo/plugin/client/ui";
import { useState } from "react";
const AGENT_IDS = ${JSON.stringify(input.agentIds)};
const COMPOSER = ${JSON.stringify(input.composer)};
function Embeds() {
const [modalOpen, setModalOpen] = useState(false);
return (
<View style={{ flex: 1 }}>
<Text testID="plugin-header" style={{ padding: 8 }}>Embedded agents</Text>
<Pressable accessibilityRole="button" onPress={() => setModalOpen(true)}>
<Text>Open in modal</Text>
</Pressable>
<Modal title="Agent in a modal" open={modalOpen} onOpenChange={setModalOpen}>
<Modal.Content scrollable={false}>
<AgentChat agentId={AGENT_IDS[0]} composer={COMPOSER} testID="modal-embed" />
</Modal.Content>
</Modal>
<View style={{ flex: 1, flexDirection: "row" }}>
{AGENT_IDS.map((agentId) => (
<View key={agentId} style={{ flex: 1, minWidth: 0 }}>
<AgentChat agentId={agentId} composer={COMPOSER} testID={"embed-" + agentId} />
</View>
))}
</View>
</View>
);
}
function Board() {
return (
<View style={{ flex: 1, flexDirection: "row" }}>
{AGENT_IDS.map((agentId) => (
<View key={agentId} style={{ flex: 1, minWidth: 0 }}>
<AgentChat agentId={agentId} composer={COMPOSER} testID={"panel-embed-" + agentId} />
</View>
))}
</View>
);
}
function EmbedsItem({ currentScreen, openScreen }) {
const open = useCallback(() => openScreen({ screenId: "main" }), [openScreen]);
return <SidebarRow icon="Bot" active={currentScreen?.screenId === "main"} onPress={open} />;
}
export default function contribute(plugin) {
plugin.addScreen({ id: "main", title: "${SCREEN_TITLE}", Component: Embeds });
plugin.addSidebarHeaderItem({ id: "main", title: "${SCREEN_TITLE}", Component: EmbedsItem });
plugin.addWorkspacePanel({ id: "board", title: "Board", icon: "Bot", context: "workspace", Component: Board });
plugin.addCommandCenterItem({
id: "board",
title: "Open embeds board",
icon: "Bot",
context: "workspace",
onSelect({ openPanel }) {
openPanel("board");
},
});
plugin.addSlashCommand({
name: "stamp",
context: "agent",
description: "Stamp the agent",
argumentHint: "",
onSubmit() {},
});
return () => {};
}`;
}
interface Scenario {
agents: MockAgentWorkspace[];
embed(agentId: string): ReturnType<Page["getByTestId"]>;
}
async function withEmbeds(
page: Page,
input: { agents: { title: string; model: string; prompt: string }[]; composer: EmbedComposer },
run: (scenario: Scenario) => Promise<void>,
): Promise<void> {
const agents: MockAgentWorkspace[] = [];
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
const directory = await mkdtemp(path.join(tmpdir(), "paseo-agent-chat-focus-"));
try {
for (const agent of input.agents) {
agents.push(
await seedMockAgentWorkspace({
repoPrefix: "agent-chat-focus-",
title: agent.title,
model: agent.model,
initialPrompt: agent.prompt,
}),
);
}
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
pluginSource({ agentIds: agents.map((agent) => agent.agentId), composer: input.composer }),
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await gotoAppShell(page);
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
for (const agent of agents) {
await expect(embed(agent.agentId).getByTestId("user-message").first()).toBeVisible({
timeout: 30_000,
});
}
await run({ agents, embed });
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
for (const agent of agents) await agent.cleanup();
}
}
async function agentStatus(agent: MockAgentWorkspace): Promise<string | null> {
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
return fetched?.agent.status ?? null;
}
/** Clicks land on text, not on a field, so Escape routes as the interrupt shortcut. */
async function expectEscapeInterruptsOnlyTheFocusedEmbed(
page: Page,
input: { left: MockAgentWorkspace; right: MockAgentWorkspace; embed: Scenario["embed"] },
): Promise<void> {
const { left, right, embed } = input;
await test.step("Escape after a click outside the embeds interrupts neither", async () => {
await page.getByTestId("plugin-header").click();
await page.keyboard.press("Escape");
});
await test.step("Escape after a click in the left embed interrupts only it", async () => {
await embed(left.agentId).getByTestId("user-message").first().click();
await page.keyboard.press("Escape");
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("idle");
// Interrupts go out in order, so a stray one from the first Escape has landed by now.
expect(await agentStatus(right)).toBe("running");
});
await test.step("Escape after a click in the right embed interrupts it", async () => {
await embed(right.agentId).getByTestId("user-message").first().click();
await page.keyboard.press("Escape");
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("idle");
});
}
test('controls: "none" sends a plugin slash command to the agent as typed', async ({ page }) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
await withEmbeds(
page,
{
agents: [{ title: "Slash agent", model: "e2e-fast-stream", prompt: "Say hello." }],
composer: { controls: "none" },
},
async ({ agents: [agent], embed }) => {
await agent.client.waitForFinish(agent.agentId, 30_000);
const box = embed(agent.agentId).getByRole("textbox", { name: "Message agent..." });
await box.fill("/stamp the invoices");
await box.press("Enter");
await expect(embed(agent.agentId).getByTestId("user-message").last()).toContainText(
"/stamp the invoices",
);
},
);
});
test("Escape interrupts only the embed that has focus", async ({ page }) => {
test.setTimeout(240_000);
await page.setViewportSize({ width: 1440, height: 900 });
await withEmbeds(
page,
{
agents: [
{ title: "Left agent", model: "one-minute-stream", prompt: "Keep running left." },
{ title: "Right agent", model: "one-minute-stream", prompt: "Keep running right." },
],
composer: { controls: "none" },
},
async ({ agents: [left, right], embed }) => {
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("running");
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("running");
await expectEscapeInterruptsOnlyTheFocusedEmbed(page, { left, right, embed });
},
);
});
test("a phone-width plugin modal shows an agent's chat", async ({ page }) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
await withEmbeds(
page,
{
agents: [{ title: "Modal agent", model: "e2e-fast-stream", prompt: "Say hello." }],
composer: { controls: "none" },
},
async () => {
// At phone width the modal is a bottom sheet whose body renders under the app's root
// portal host, outside the plugin screen's React tree.
await page.setViewportSize(PHONE);
await page.getByRole("button", { name: "Open in modal", exact: true }).click();
await expect(page.getByText("Agent in a modal", { exact: true })).toBeVisible();
const modalEmbed = page.getByTestId("modal-embed");
await expect(modalEmbed.getByTestId("user-message").first()).toContainText("Say hello.", {
timeout: 30_000,
});
await expect(modalEmbed.getByRole("textbox", { name: "Message agent..." })).toBeVisible();
},
);
});
/** Picks the embed's current mode again from its picker, which draws at the overlay root. */
async function pickCurrentMode(page: Page, embed: ReturnType<Page["getByTestId"]>): Promise<void> {
const trigger = embed.getByRole("button", { name: /^Select agent mode \(/ });
const label = /^Select agent mode \((.+)\)$/.exec(
(await trigger.getAttribute("aria-label")) ?? "",
)?.[1];
expect(label).toBeTruthy();
await trigger.click();
const popup = page.getByTestId("combobox-desktop-container").last();
await expect(popup).toBeVisible({ timeout: 10_000 });
await popup.getByRole("button", { name: label, exact: true }).click();
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
}
test("a full-composer embed applies a slash suggestion picked with the pointer", async ({
page,
}) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
await withEmbeds(
page,
{
agents: [{ title: "Suggestion agent", model: "e2e-fast-stream", prompt: "Say hello." }],
composer: {},
},
async ({ agents: [agent], embed }) => {
await agent.client.waitForFinish(agent.agentId, 30_000);
const box = embed(agent.agentId).getByRole("textbox", { name: "Message agent..." });
await box.click();
await box.pressSequentially("/sta");
// The list draws in the floating-panel portal, outside the embed's own nodes.
const suggestion = page
.getByTestId("composer-autocomplete-popover")
.getByText("/stamp", { exact: true });
await expect(suggestion).toBeVisible({ timeout: 30_000 });
await suggestion.click();
await expect(box).toHaveValue(/^\/stamp\s*$/);
},
);
});
test("a portaled mode picker keeps its embed focused for Escape", async ({ page }) => {
test.setTimeout(240_000);
await page.setViewportSize({ width: 1440, height: 900 });
await withEmbeds(
page,
{
agents: [
{ title: "Left agent", model: "one-minute-stream", prompt: "Keep running left." },
{ title: "Right agent", model: "one-minute-stream", prompt: "Keep running right." },
],
composer: {},
},
async ({ agents: [left, right], embed }) => {
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("running");
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("running");
await pickCurrentMode(page, embed(left.agentId));
await page.keyboard.press("Escape");
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("idle");
expect(await agentStatus(right)).toBe("running");
},
);
});
test("embeds in one workspace panel keep their own composers", async ({ page }) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1440, height: 900 });
await withEmbeds(
page,
{
agents: [
{ title: "Left agent", model: "e2e-fast-stream", prompt: "Say hello left." },
{ title: "Right agent", model: "e2e-fast-stream", prompt: "Say hello right." },
],
composer: {},
},
async ({ agents: [left, right] }) => {
await openAgentRoute(page, left);
const commands = await openCommandCenter(page);
await commands.getByTestId("command-center-input").fill("Open embeds board");
await commands.getByRole("button", { name: "Open embeds board", exact: true }).click();
const leftEmbed = page.getByTestId(`panel-embed-${left.agentId}`);
const rightEmbed = page.getByTestId(`panel-embed-${right.agentId}`);
await expect(leftEmbed.getByTestId("user-message").first()).toBeVisible({ timeout: 30_000 });
await expect(rightEmbed.getByTestId("user-message").first()).toBeVisible({ timeout: 30_000 });
// The fullscreen control shows on a phone once the draft runs past two lines.
await page.setViewportSize(PHONE);
await leftEmbed
.getByRole("textbox", { name: "Message agent..." })
.fill("First line\nSecond line\nThird line\nFourth line");
await leftEmbed.getByRole("button", { name: "Fullscreen", exact: true }).click();
await expect(leftEmbed.getByTestId("composer-fullscreen")).toBeVisible();
await expect(rightEmbed.getByTestId("composer-fullscreen")).toHaveCount(0);
},
);
});
@@ -0,0 +1,118 @@
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-example";
const AGENT_TITLE = "Billing retries";
const FIRST_PROMPT = "Summarize the billing retry failures.";
function embed(page: Page) {
return page.getByTestId("example-agent-chat");
}
async function openAgentInEmbed(page: Page): Promise<void> {
await gotoAppShell(page);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page
.getByTestId("example-agent-list")
.getByRole("button", { name: AGENT_TITLE, exact: true })
.click();
}
async function sendFromEmbed(page: Page, text: string): Promise<void> {
const box = embed(page).getByRole("textbox", { name: "Message agent..." });
await box.fill(text);
await box.press("Enter");
}
test.describe("AgentChat", () => {
test("a plugin screen embeds an agent's chat with the composer it chose", async ({
page,
context,
}) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
const agent = await seedMockAgentWorkspace({
repoPrefix: "plugin-agent-chat-",
title: AGENT_TITLE,
initialPrompt: FIRST_PROMPT,
});
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
const example = await copyPluginExample("agent-chat");
try {
await agent.client.waitForFinish(agent.agentId, 30_000);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(example.directory);
await openAgentInEmbed(page);
await test.step("controls: none is a message box and Send", async () => {
await expect(embed(page).getByTestId("user-message")).toContainText(FIRST_PROMPT);
await expect(embed(page).getByTestId("assistant-message").first()).toBeVisible();
await expect(
embed(page).getByRole("textbox", { name: "Message agent..." }),
).toHaveAttribute("placeholder", "Message this agent");
await expect(embed(page).getByTestId("agent-controls-toolbar")).toHaveCount(0);
await expect(embed(page).getByTestId("message-input-attach-button")).toHaveCount(0);
await expect(embed(page).getByTestId("context-window-meter")).toHaveCount(0);
const choices = await page.getByTestId("example-composer-choices").boundingBox();
const chat = await embed(page).boundingBox();
expect(chat!.y).toBeGreaterThanOrEqual(choices!.y + choices!.height);
});
await test.step("a message sent from the embed streams into it", async () => {
await sendFromEmbed(page, "Check the invoice PDFs next.");
await expect(embed(page).getByTestId("user-message").last()).toContainText(
"Check the invoice PDFs next.",
);
await agent.client.waitForFinish(agent.agentId, 30_000);
});
await test.step("slash text in the simple box reaches the agent as typed", async () => {
await sendFromEmbed(page, "/exit");
await expect(embed(page).getByTestId("user-message").last()).toContainText("/exit");
await agent.client.waitForFinish(agent.agentId, 30_000);
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
expect(fetched?.agent.archivedAt ?? null).toBeNull();
});
await test.step("the full composer is the agent tab's", async () => {
await page.getByRole("button", { name: "Full", exact: true }).click();
await expect(embed(page).getByTestId("agent-controls-toolbar")).toBeVisible();
await expect(embed(page).getByTestId("message-input-attach-button")).toBeVisible();
await expect(embed(page).getByTestId("context-window-meter")).toBeVisible();
});
await test.step("composer={false} shows the conversation without a composer", async () => {
await page.getByRole("button", { name: "No composer", exact: true }).click();
await expect(embed(page).getByTestId("user-message").first()).toContainText(FIRST_PROMPT);
await expect(embed(page).getByRole("textbox", { name: "Message agent..." })).toHaveCount(0);
});
await test.step("the agent's tab and the embed stay live together", async () => {
await page.getByRole("button", { name: "Simple", exact: true }).click();
const tab = await context.newPage();
await openAgentRoute(tab, { workspaceId: agent.workspaceId, agentId: agent.agentId });
const tabBox = tab.getByRole("textbox", { name: "Message agent..." }).first();
await tabBox.fill("Sent from the tab.");
await tabBox.press("Enter");
await expect(embed(page).getByTestId("user-message").last()).toContainText(
"Sent from the tab.",
);
await sendFromEmbed(page, "Sent from the embed.");
await expect(tab.getByTestId("user-message").last()).toContainText("Sent from the embed.");
await tab.close();
});
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
await example.cleanup();
await agent.cleanup();
}
});
});
@@ -131,6 +131,11 @@ test.describe("Running indicators", () => {
test.setTimeout(180_000);
const scene = await openIdleChatBesideRunningAgent(page);
try {
// Once the chat has settled, nothing but rings is moving, so every frame drawn is a ring's.
// A 200 ms border-colour transition in the composer can still be running as the chat opens.
await expect
.poll(async () => new Set(await readAnimatingTargets(page)))
.toEqual(new Set(["status-ring"]));
const animating = await readAnimatingTargets(page);
const activity = await measureSteadyStateActivity({
browser,
@@ -143,8 +148,6 @@ test.describe("Running indicators", () => {
JSON.stringify({ animating, activity, angles }, null, 2),
);
// Nothing but rings is moving, so every frame drawn is a ring's.
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
expect
.soft(activity.compositorFramesPerSecond)
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
@@ -33,9 +33,13 @@ import {
expectHostPageVisible,
seedSavedSettingsHosts,
selectSettingsHost,
expectHostRejectedWithReAddGuidance,
expectNoHostPasswordControls,
removeHostFromHostPage,
expectNoHostRefusalSheet,
expectHostRefusalSheet,
dismissHostRefusalSheet,
expectHostPasswordRefusalInline,
reopenHostPasswordRefusalSheet,
submitHostRefusalPassword,
expectHostRefusalPasswordError,
addDirectHostFromSettings,
expectAddHostFieldDrawnAsInput,
selectHostConnectionType,
@@ -111,7 +115,7 @@ test.describe("Settings host page", () => {
await expect(updateButton).toBeEnabled();
});
test("a host rejected for its password reconnects after being removed and added again with it", async ({
test("a saved host rejected for its password reconnects in place from its settings page", async ({
page,
}) => {
const password = "e2e host password";
@@ -133,16 +137,29 @@ test.describe("Settings host page", () => {
]);
await page.reload();
await openSettings(page);
await openClientHostSettings(page, daemon.serverId);
await test.step("the host page shows the reason and the re-add guidance, with no password UI", async () => {
await expectHostRejectedWithReAddGuidance(page, "Password required");
await expectNoHostPasswordControls(page);
await test.step("background refusal stays quiet until the host page is opened", async () => {
await expectNoHostRefusalSheet(page);
await openClientHostSettings(page, daemon.serverId);
await expectHostRefusalSheet(page, {
title: "Password required",
hostLabel: "Password host",
});
});
await test.step("removing the host and adding it again with the password brings it online", async () => {
await removeHostFromHostPage(page, daemon.serverId);
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port, password });
await test.step("dismissing leaves an inline password prompt that reopens the sheet", async () => {
await dismissHostRefusalSheet(page);
await expectHostPasswordRefusalInline(page, "Password required");
await reopenHostPasswordRefusalSheet(page);
});
await test.step("a wrong password stays inline and the right password brings the host online", async () => {
await submitHostRefusalPassword(page, "wrong password");
await expectHostRefusalPasswordError(page, "Incorrect password");
await submitHostRefusalPassword(page, password);
await expectNoHostRefusalSheet(page);
await expect(page.getByTestId("host-connection-error")).toHaveCount(0);
await selectSettingsHost(page, daemon.serverId);
await openHostSection(page, daemon.serverId, "daemon");
await expectHostOnlineWithoutError(page);
});
@@ -337,6 +354,20 @@ test("Add host draws its text fields as bordered inputs", async ({ page }) => {
});
});
test("Space toggles the focused Use SSL checkbox in the direct host form", async ({ page }) => {
await gotoAppShell(page);
await openSidebarAddHost(page);
await selectHostConnectionType(page, "direct");
const checkbox = page.getByRole("checkbox", { name: "Use SSL", exact: true });
const initial = await checkbox.isChecked();
await checkbox.focus();
await checkbox.press("Space");
await expect(checkbox).toBeChecked({ checked: !initial });
await expect(checkbox).toBeFocused();
await checkbox.press("Space");
await expect(checkbox).toBeChecked({ checked: initial });
});
test("sidebar Add host completes without navigating", async ({ page }) => {
await gotoAppShell(page);
await expect(page).toHaveURL(/\/open-project$/);
@@ -33,16 +33,20 @@ export async function restartDaemonInSettings(
await expect(page.getByRole("button", { name: "Restarting...", exact: true })).toBeDisabled();
}
// The app reads the replacement worker only after it reconnects. Reconnect attempts back off
// (1.5 s doubling to a 30 s cap), so the result can trail a ready worker by up to 30 s.
export const DAEMON_RESTART_TIMEOUT_MS = 75_000;
export async function expectDaemonRestartFailed(page: Page, text: string) {
const error = page.getByTestId("host-page-restart-error");
await expect(error).toBeVisible({ timeout: 30_000 });
await expect(error).toBeVisible({ timeout: DAEMON_RESTART_TIMEOUT_MS });
await expect(error).toContainText(text);
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled();
}
export async function expectDaemonRestartComplete(page: Page) {
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled({
timeout: 30_000,
timeout: DAEMON_RESTART_TIMEOUT_MS,
});
}
@@ -76,19 +76,21 @@ export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<
export async function expectConnectedClientRow(
page: Page,
title: string,
title: string | RegExp,
scopeLabel: string,
): Promise<void> {
const card = page.getByTestId("devices-connected-clients-card");
const row = card.getByRole("button", { name: title, exact: true });
const row = card.getByRole("button", { name: title, exact: typeof title === "string" });
await expect(row).toBeVisible();
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
}
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
export async function expandConnectedClientRow(page: Page, title: string | RegExp): Promise<void> {
const card = page.getByTestId("devices-connected-clients-card");
await card.getByRole("button", { name: title, exact: true }).click();
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
const toggle = card.getByRole("button", { name: title, exact: typeof title === "string" });
await toggle.click();
await expect(toggle).toHaveAttribute("aria-expanded", "true");
await expect(card.getByText("Access", { exact: true }).first()).toBeVisible();
}
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
@@ -188,7 +188,12 @@ export interface SeedDaemonClient {
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
refreshAgent(agentId: string): Promise<unknown>;
fetchAgent(options: { agentId: string }): Promise<{
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
agent: {
id: string;
status: string;
archivedAt?: string | null;
pendingPermissions: Array<{ id: string }>;
};
} | null>;
getLastServerInfoMessage(): {
features?: {
+33 -13
View File
@@ -712,27 +712,47 @@ export async function expectLocalHostEntryFirst(page: Page, _serverId: string):
await expect(picker.getByText(TEST_HOST_LABEL, { exact: true })).toBeVisible();
}
export async function expectHostRejectedWithReAddGuidance(
export async function expectNoHostRefusalSheet(page: Page): Promise<void> {
await expect(page.getByTestId("host-refusal-sheet")).toHaveCount(0);
}
export async function expectHostRefusalSheet(
page: Page,
reason: string,
expected: { title: string; hostLabel: string },
): Promise<void> {
const sheet = page.getByTestId("host-refusal-sheet");
await expect(sheet).toBeVisible();
await expect(sheet.getByTestId("host-refusal-sheet-title")).toHaveText(expected.title);
await expect(sheet.getByTestId("host-refusal-sheet-host")).toHaveText(expected.hostLabel);
}
export async function dismissHostRefusalSheet(page: Page): Promise<void> {
await page.getByTestId("host-refusal-sheet-dismiss").click();
await expectNoHostRefusalSheet(page);
}
export async function expectHostPasswordRefusalInline(page: Page, reason: string): Promise<void> {
const error = page.getByTestId("host-connection-error");
await expect(error).toContainText(reason);
await expect(error).toContainText(
"Remove this host and add it again with the password this daemon asks for.",
);
await expect(error.getByRole("button", { name: "Enter password", exact: true })).toBeVisible();
}
export async function expectNoHostPasswordControls(page: Page): Promise<void> {
await expect(page.getByText("Password", { exact: true })).toHaveCount(0);
await expect(page.locator('input[type="password"]')).toHaveCount(0);
await expect(page.getByRole("button", { name: /password/i })).toHaveCount(0);
export async function reopenHostPasswordRefusalSheet(page: Page): Promise<void> {
await page
.getByTestId("host-connection-error")
.getByRole("button", { name: "Enter password", exact: true })
.click();
await expect(page.getByTestId("host-refusal-sheet")).toBeVisible();
}
export async function removeHostFromHostPage(page: Page, serverId: string): Promise<void> {
await page.getByTestId("host-page-remove-host-button").click();
await page.getByTestId("remove-host-confirm").click();
await expect(page).not.toHaveURL(new RegExp(`/settings/(hosts|device-hosts)/${serverId}`));
export async function submitHostRefusalPassword(page: Page, password: string): Promise<void> {
await page.getByTestId("host-password-input").fill(password);
await page.getByTestId("host-refusal-sheet-submit").click();
}
export async function expectHostRefusalPasswordError(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("host-refusal-sheet")).toBeVisible();
await expect(page.getByTestId("host-password-field")).toContainText(message);
}
export async function expectHostOnlineWithoutError(page: Page): Promise<void> {
+51 -25
View File
@@ -51,35 +51,61 @@
}
</style>
<style>
button,
a,
input,
textarea,
select,
[role="button"],
[role="link"],
[role="textbox"],
[role="combobox"],
[role="tab"],
[role="switch"],
[role="checkbox"],
[role="slider"],
[role="menuitem"],
[tabindex],
/* Only interactive controls that can overlap a window drag surface
emit -webkit-app-region: no-drag. Controls in ordinary window content
rely on normal DOM hit testing so scrolled viewports and parked
browser webviews never emit unclipped no-drag boxes over the titlebar. */
:is(
[data-window-drag-region] ~ *,
[style*="-webkit-app-region: drag"],
[style*="-webkit-app-region:drag"],
#overlay-root,
[data-window-overlay-host],
[role="dialog"],
[aria-modal="true"]
)
:is(
button,
a,
input,
textarea,
select,
[role="button"],
[role="link"],
[role="textbox"],
[role="combobox"],
[role="tab"],
[role="switch"],
[role="checkbox"],
[role="slider"],
[role="menuitem"],
[tabindex],
[contenteditable="true"]
),
[data-window-drag-region]
~ :is(
button,
a,
input,
textarea,
select,
[role="button"],
[role="link"],
[role="textbox"],
[role="combobox"],
[role="tab"],
[role="switch"],
[role="checkbox"],
[role="slider"],
[role="menuitem"],
[tabindex],
[contenteditable="true"]
),
[data-window-no-drag],
[contenteditable="true"] {
[data-window-no-drag] * {
-webkit-app-region: no-drag !important;
}
/* Electron does not clip app-region rectangles to scroll viewports.
Content-only viewports emit no window regions, including from their
controls. Visible controls here use normal DOM hit testing.
Use initial: Blink parses the explicit value none as no-drag. */
[data-window-content],
[data-window-content] * {
-webkit-app-region: initial !important;
}
/* Suppress the browser's default focus outline — it appears on mouse
clicks and looks out of place against our themed surfaces. Keep a
themed ring for keyboard users via :focus-visible. The ring is the active
@@ -0,0 +1,17 @@
import { useCallback, useMemo } from "react";
import type { View, ViewProps } from "react-native";
import type { RefObject } from "react";
/**
* Native: a touch that starts in the embed claims it, as a touch claims a workspace pane. The
* capture handler declines the responder, so the touch still reaches what was pressed.
*/
export function useClaimFocusProps(
claim: () => void,
): Pick<ViewProps, "onStartShouldSetResponderCapture"> & { ref?: RefObject<View | null> } {
const handleTouch = useCallback(() => {
claim();
return false;
}, [claim]);
return useMemo(() => ({ onStartShouldSetResponderCapture: handleTouch }), [handleTouch]);
}
@@ -0,0 +1,24 @@
import { useEffect, useMemo, useRef, type RefObject } from "react";
import type { View, ViewProps } from "react-native";
/**
* Web: a pointer press or focus move in the embed's DOM claims it, as one claims a workspace pane
* (`split-container`). Pickers and menus the embed opens draw outside its DOM, so pressing them
* leaves the claim where it is.
*/
export function useClaimFocusProps(
claim: () => void,
): Pick<ViewProps, "onStartShouldSetResponderCapture"> & { ref?: RefObject<View | null> } {
const ref = useRef<View | null>(null);
useEffect(() => {
const node: unknown = ref.current;
if (!(node instanceof HTMLElement)) return undefined;
node.addEventListener("pointerdown", claim, true);
node.addEventListener("focusin", claim, true);
return () => {
node.removeEventListener("pointerdown", claim, true);
node.removeEventListener("focusin", claim, true);
};
}, [claim]);
return useMemo(() => ({ ref }), []);
}
+62
View File
@@ -0,0 +1,62 @@
import { useCallback, useContext, useEffect, useSyncExternalStore } from "react";
import { NavigationContext } from "expo-router/react-navigation";
import { useEnclosingPaneFocus } from "@/panels/pane-context";
/**
* Which embed owns the composer's key handlers (Escape interrupts, send, mode cycling). Embeds
* follow the workspace's pane rule: the embed the user last pressed or focused owns them until
* the user presses another embed. A press elsewhere, such as in the plugin's own UI or in a
* picker the embed opened, leaves the owner as it is.
*/
let focusedEmbedId: string | null = null;
const listeners = new Set<() => void>();
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
function setFocusedEmbed(next: string | null): void {
if (focusedEmbedId === next) return;
focusedEmbedId = next;
for (const listener of listeners) listener();
}
/** The embed's key focus, and the claim its root calls on a press or focus move inside it. */
export function useEmbedFocus(embedId: string): { isFocused: boolean; claim: () => void } {
const read = useCallback(() => focusedEmbedId === embedId, [embedId]);
const isFocused = useSyncExternalStore(subscribe, read, read);
const claim = useCallback(() => setFocusedEmbed(embedId), [embedId]);
useEffect(
() => () => {
if (focusedEmbedId === embedId) setFocusedEmbed(null);
},
[embedId],
);
return { isFocused, claim };
}
/**
* Whether the surface around the embed is the one the user is on: the pane it sits in, or else
* the screen. A plugin screen stays mounted under the next one, and its embeds must not keep the
* keys there. Outside any screen (a modal at the app root) the surface counts as shown.
*/
export function useEmbedSurfaceActive(): boolean {
const pane = useEnclosingPaneFocus();
const navigation = useContext(NavigationContext);
const subscribeToRoute = useCallback(
(listener: () => void) => {
if (!navigation) return () => {};
const removeFocus = navigation.addListener("focus", listener);
const removeBlur = navigation.addListener("blur", listener);
return () => {
removeFocus();
removeBlur();
};
},
[navigation],
);
const readRoute = useCallback(() => navigation?.isFocused() ?? true, [navigation]);
const isRouteFocused = useSyncExternalStore(subscribeToRoute, readRoute, readRoute);
return pane ? pane.isInteractive : isRouteFocused;
}
+85
View File
@@ -0,0 +1,85 @@
import { useId, useMemo } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { LocalComposerEditingScope } from "@/composer/editing-session";
import {
AgentPanelContent,
type ConversationSurface,
type EmbeddedComposer,
} from "@/panels/agent-panel";
import { createPaneFocusContextValue, PaneFocusProvider } from "@/panels/pane-context";
import { RetainedChatContent } from "@/panels/retained-chat-content";
import { useSessionStore } from "@/stores/session-store";
import { useViewedAgent } from "@/timeline/use-viewed-agent";
import { useClaimFocusProps } from "./claim-focus";
import { useEmbedFocus, useEmbedSurfaceActive } from "./focus";
export type { EmbeddedComposer } from "@/panels/agent-panel";
export interface AgentEmbedProps {
serverId: string;
agentId: string;
/** `null` shows the conversation without a composer. */
composer: EmbeddedComposer | null;
testID?: string;
}
/**
* An agent's conversation outside the workspace: the agent tab's own chain, with its loading,
* catch-up, error and archived states, and no tab chrome.
*
* The embed is a viewer like the workspace sheet, so the agent's timeline stays live while it is
* mounted and shares the tab's observation when the agent is also open in a tab.
*
* Several embeds can share a screen. Like workspace panes, the one the user last pressed owns the
* composer's key handlers, and only while its pane or screen is the one in front. Each embed edits
* in its own composer session, even inside a workspace panel that has one of its own.
*/
export function AgentEmbed({ serverId, agentId, composer, testID }: AgentEmbedProps) {
const viewerId = `embed:${useId()}`;
useViewedAgent({ sourceId: viewerId, serverId, agentId });
const isSurfaceActive = useEmbedSurfaceActive();
const { isFocused, claim } = useEmbedFocus(viewerId);
const claimProps = useClaimFocusProps(claim);
const isPaneFocused = composer !== null && isSurfaceActive && isFocused;
const surface = useMemo<ConversationSurface>(
() => ({ kind: "embed", id: viewerId, composer, isActive: isSurfaceActive }),
[composer, isSurfaceActive, viewerId],
);
const focus = useMemo(
() => createPaneFocusContextValue({ isWorkspaceFocused: isSurfaceActive, isPaneFocused }),
[isPaneFocused, isSurfaceActive],
);
const target = useMemo(() => ({ kind: "agent" as const, agentId }), [agentId]);
const workspaceId = useSessionStore((state) => {
const session = state.sessions[serverId];
return (
session?.agents.get(agentId)?.workspaceId ??
session?.agentDetails.get(agentId)?.workspaceId ??
""
);
});
return (
<View {...claimProps} style={styles.root} testID={testID}>
<PaneFocusProvider value={focus}>
{/* Keyed like a pane's session, which follows its target. */}
<LocalComposerEditingScope key={agentId}>
<RetainedChatContent>
<AgentPanelContent
serverId={serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isPaneFocused}
/>
</RetainedChatContent>
</LocalComposerEditingScope>
</PaneFocusProvider>
</View>
);
}
const styles = StyleSheet.create({
root: { flex: 1, minHeight: 0 },
});
@@ -1702,7 +1702,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
!liveAuxiliary;
return (
<div style={viewportStyle} data-window-content>
<div style={viewportStyle}>
<div
ref={handleScrollContainerRef}
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
+4
View File
@@ -9,6 +9,7 @@ import {
resolveDesktopDivisionLayout,
} from "@/window-layout";
import { AddHostProvider, AddHostFlowHost } from "@/hosts/add-host";
import { HostRefusalSheetHost } from "@/hosts/host-refusal-sheet";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useIsExplorerSidebarOpen } from "@/workspace-tabs/explorer-sidebar";
@@ -53,6 +54,7 @@ import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary"
import { LeftSidebar } from "@/components/left-sidebar";
import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import { DesktopWindowControls } from "@/components/desktop/window-controls";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
@@ -531,6 +533,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<View style={layoutStyles.surfaceFill}>
{workspaceChrome}
<AddHostFlowHost />
<HostRefusalSheetHost />
<WorkspaceArchiveShortcutHandler />
<AppearanceStyleBoundary>
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
@@ -604,6 +607,7 @@ function CompactSidebarHost({
return (
<View
collapsable={false}
dataSet={visible ? WINDOW_OVERLAY_HOST_DATASET : undefined}
style={[
layoutStyles.compactSidebarHost,
{ opacity: visible ? 1 : 0 },
@@ -1,9 +1,11 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useLocalSearchParams, useRouter, type Href } from "expo-router";
import { useIsFocused } from "expo-router/react-navigation";
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
import { useFetchQuery } from "@/data/query";
import { resolveAgentRoute, type AgentRouteLookup } from "@/navigation/agent-route-resolution";
import { AgentRouteResolutionView } from "@/navigation/agent-route-resolution-view";
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
import { useHasHydratedWorkspaces } from "@/stores/session-store-hooks";
import { useDirectoryDemand } from "@/hooks/use-directory-demand";
import { useWorkspaceLayoutStoreHydrated } from "@/stores/workspace-layout-store";
@@ -23,13 +25,14 @@ export default function HostAgentReadyRoute() {
function HostAgentReadyRouteContent() {
const router = useRouter();
const isRouteFocused = useIsFocused();
const params = useLocalSearchParams<{
serverId?: string;
agentId?: string;
}>();
const handledNavigationRef = useRef<string | null>(null);
const serverId = typeof params.serverId === "string" ? params.serverId : "";
const agentId = typeof params.agentId === "string" ? params.agentId : "";
const serverId = readStringParam(params.serverId);
const agentId = readStringParam(params.agentId);
const hosts = useHosts();
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
const client = runtimeSnapshot?.client ?? null;
@@ -47,9 +50,13 @@ function HostAgentReadyRouteContent() {
.prepareAgentRoute(serverId, agentId)
.catch(() => undefined);
}, [agentId, agentWorkspaceId, serverId]);
const shouldLookupAgent = Boolean(
serverId && agentId && client && connectionStatus === "online" && !agentWorkspaceId,
);
const shouldLookupAgent = canLookupAgentRoute({
serverId,
agentId,
hasClient: client !== null,
connectionStatus,
agentWorkspaceId,
});
const lookupQuery = useFetchQuery({
queryKey: ["agentRouteResolution", serverId, agentId, runtimeSnapshot?.clientGeneration ?? 0],
queryFn: async () => {
@@ -98,16 +105,10 @@ function HostAgentReadyRouteContent() {
connectionStatus,
lookup,
});
useActiveRefusalHost(serverId, isRouteFocused && isVisibleAgentRouteResolution(resolution));
useEffect(() => {
let navigationKey: string | null = null;
if (resolution.kind === "invalid") {
navigationKey = "invalid";
} else if (resolution.kind === "resolved") {
navigationKey = `workspace:${resolution.workspaceId}`;
} else if (resolution.kind === "notFound") {
navigationKey = "not-found";
}
const navigationKey = resolveAgentRouteNavigationKey(resolution);
if (!navigationKey || handledNavigationRef.current === navigationKey) {
return;
}
@@ -126,7 +127,7 @@ function HostAgentReadyRouteContent() {
return;
}
if (serverId) {
void getHostRuntimeStore().runProbeCycleNow(serverId);
void getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
}
}, [lookupQuery, resolution.kind, serverId]);
const handleManageHost = useCallback(() => {
@@ -142,18 +143,16 @@ function HostAgentReadyRouteContent() {
router.replace(serverId ? buildHostRootRoute(serverId) : ("/" as Href));
}, [router, serverId]);
if (
resolution.kind === "waitingForHost" ||
resolution.kind === "fetchingAgent" ||
resolution.kind === "lookupError"
) {
if (isVisibleAgentRouteResolution(resolution)) {
// Agent URLs intentionally omit workspaceId. Keep this route mounted while the target host
// reconnects, then resolve the workspace from the authoritative agent record.
return (
<AgentRouteResolutionView
serverId={serverId}
resolution={resolution}
hostName={hostName}
lastHostError={runtimeSnapshot?.lastError ?? null}
helloRejection={runtimeSnapshot?.helloRejection ?? null}
onRetry={handleRetry}
onManageHost={handleManageHost}
onBack={handleBack}
@@ -163,3 +162,45 @@ function HostAgentReadyRouteContent() {
return null;
}
function readStringParam(value: string | undefined): string {
return typeof value === "string" ? value : "";
}
function canLookupAgentRoute(input: {
serverId: string;
agentId: string;
hasClient: boolean;
connectionStatus: string;
agentWorkspaceId: string | null;
}): boolean {
return Boolean(
input.serverId &&
input.agentId &&
input.hasClient &&
input.connectionStatus === "online" &&
!input.agentWorkspaceId,
);
}
function resolveAgentRouteNavigationKey(
resolution: ReturnType<typeof resolveAgentRoute>,
): string | null {
if (resolution.kind === "invalid") return "invalid";
if (resolution.kind === "resolved") return `workspace:${resolution.workspaceId}`;
if (resolution.kind === "notFound") return "not-found";
return null;
}
function isVisibleAgentRouteResolution(
resolution: ReturnType<typeof resolveAgentRoute>,
): resolution is Extract<
ReturnType<typeof resolveAgentRoute>,
{ kind: "waitingForHost" | "fetchingAgent" | "lookupError" }
> {
return (
resolution.kind === "waitingForHost" ||
resolution.kind === "fetchingAgent" ||
resolution.kind === "lookupError"
);
}
@@ -84,4 +84,19 @@ describe("direct connection failure copy", () => {
}),
).toMatchObject({ detail: message, raw: message });
});
it("preserves non-password hello rejections without falling back to generic unableToConnect", () => {
const message = "Incompatible protocol version";
expect(
buildConnectionFailureCopy({
endpoint: "example.test:6767",
error: new DaemonConnectionTestError(message, {
reason: message,
lastError: message,
helloRejection: { reason: "incompatible_protocol", accepts: [] },
}),
labels,
}),
).toMatchObject({ detail: message, raw: message });
});
});
@@ -1,6 +1,6 @@
import {
DaemonConnectionTestError,
getConnectionAuthFailureReason,
getConnectionHelloRejection,
} from "@/utils/test-daemon-connection";
interface ConnectionFailureLabels {
@@ -73,7 +73,7 @@ export function buildConnectionFailureCopy(input: {
const rawLower = raw?.toLowerCase() ?? "";
let detail: string | null = null;
if (getConnectionAuthFailureReason(error)) {
if (getConnectionHelloRejection(error)) {
detail = error instanceof Error ? error.message : raw;
} else if (rawLower.includes("timed out")) {
detail = labels.timedOut;
@@ -10,23 +10,23 @@ import { isNative } from "@/constants/platform";
* - titlebarpart.css:249-260 → top-edge resizer, no-drag, 4px
*
* VS Code's drag region is a static DOM element — no z-index, no pointer-events,
* no state, no event listeners. Interactive elements get no-drag from their own
* CSS (global backstop in index.html). The drag region never re-renders.
* no state, no event listeners. Interactive controls only receive no-drag when
* they sit inside a drag container, an overlay/modal host, or an explicit
* window-owned chrome slot (see public/index.html). Controls in ordinary window
* content emit no app regions and use normal DOM hit testing, so scrolled
* viewports and parked browser webviews cannot subtract unclipped rects from
* the titlebar.
*
* The resizer is Windows/Linux only (titlebarpart.css:249 scopes to .windows/.linux).
* On macOS, Electron handles edge resize natively.
*/
/**
* Marks a scroll viewport as window content: it and its descendants emit no window
* regions, because Electron does not clip app-region rects to scroll viewports.
* See the `[data-window-content]` rule in public/index.html.
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
/** Reserves a clickable area for a window-owned control mounted outside a drag container. */
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
/** Marks an in-app overlay/portal host whose interactive controls can float over the titlebar. */
export const WINDOW_OVERLAY_HOST_DATASET = { "window-overlay-host": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -64,7 +64,7 @@ export function TitlebarDragRegion() {
return (
<>
{/* Drag overlay — VS Code .titlebar-drag-region (titlebarpart.css:57-64) */}
<div style={DRAG_OVERLAY_STYLE} />
<div data-window-drag-region="" style={DRAG_OVERLAY_STYLE} />
{/* Top-edge resizer — VS Code .resizer (titlebarpart.css:249-256) */}
<div style={TOP_RESIZER_STYLE} />
</>
@@ -12,6 +12,7 @@ import {
getDesktopWindowControlsPresentation,
type DesktopWindowControlsPresentation,
} from "@/desktop/window-chrome-presentation";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import { useCustomDesktopWindowControls } from "@/utils/desktop-window";
import type { Theme } from "@/styles/theme";
@@ -143,6 +144,7 @@ export function DesktopWindowControls() {
return (
<View
dataSet={WINDOW_NO_DRAG_DATASET}
style={[styles.controls, { height: presentation.controlHeight }]}
testID="desktop-window-controls"
>
@@ -2,6 +2,7 @@ import { createContext, useContext, useCallback, useState, useId, type ReactNode
import { View, type LayoutChangeEvent } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Portal, PortalHost } from "@gorhom/portal";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { EdgeFade } from "@/components/ui/edge-fade";
@@ -74,7 +75,11 @@ export function FloatingHeaderLayout({ header, floating, children }: FloatingHea
</View>
</View>
) : null}
<View style={styles.statusOverlay} pointerEvents="box-none">
<View
style={styles.statusOverlay}
dataSet={WINDOW_OVERLAY_HOST_DATASET}
pointerEvents="box-none"
>
<PortalHost name={overlayHostName} />
</View>
</View>
@@ -5,6 +5,7 @@ import { router } from "expo-router";
import { ArrowLeft } from "lucide-react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import {
@@ -17,6 +18,7 @@ import {
HEADER_INNER_HEIGHT_MOBILE,
HEADER_TOP_PADDING_MOBILE,
} from "@/constants/layout";
import { WindowChromeSafeArea } from "@/utils/desktop-window";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useTopBand } from "@/window-layout";
@@ -75,27 +77,30 @@ export function CompactHeader({
return (
<IconButtonChromeProvider value="header-island">
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
<WindowChromeSafeArea placement="inline" style={styles.chromeContainer}>
<TitlebarDragRegion />
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
</View>
<View style={styles.titleGroup}>
<CompactHeaderTitle
loading={loading}
title={title}
titleTestID={titleTestID}
subtitle={subtitle}
/>
</View>
{actions ? <View style={styles.island}>{actions}</View> : null}
</View>
<View style={styles.titleGroup}>
<CompactHeaderTitle
loading={loading}
title={title}
titleTestID={titleTestID}
subtitle={subtitle}
/>
</View>
{actions ? <View style={styles.island}>{actions}</View> : null}
</View>
</View>
</WindowChromeSafeArea>
</IconButtonChromeProvider>
);
}
@@ -154,6 +159,9 @@ function BackButton({ onBack }: { onBack?: () => void }) {
}
const styles = StyleSheet.create((theme) => ({
chromeContainer: {
position: "relative",
},
root: {
paddingHorizontal: theme.spacing[3],
},
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { PanelLeft } from "lucide-react-native";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import { HeaderToggleButton, headerIconSlotStyle } from "./header-toggle-button";
import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -50,10 +51,12 @@ function SidebarMenuToggleButton({
tooltipSide = "right",
testID = "menu-button",
nativeID = "menu-button",
dataSet,
}: Omit<SidebarMenuToggleProps, "style"> & {
isMobile: boolean;
extraMutedIdleIcon?: boolean;
resolvedStyle: StyleProp<ViewStyle>;
dataSet?: Record<string, string>;
}) {
const { t } = useTranslation();
const isOpen = usePanelStore((state) => selectIsAgentListOpen(state, { isCompact: isMobile }));
@@ -77,6 +80,7 @@ function SidebarMenuToggleButton({
tooltipSide={tooltipSide}
testID={testID}
nativeID={nativeID}
dataSet={dataSet}
style={resolvedStyle}
accessible
accessibilityRole="button"
@@ -128,6 +132,7 @@ export function WindowSidebarMenuToggle({ style, ...props }: SidebarMenuTogglePr
{...props}
isMobile={false}
extraMutedIdleIcon
dataSet={WINDOW_NO_DRAG_DATASET}
resolvedStyle={resolvedStyle}
/>
);
@@ -0,0 +1,119 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { View } from "react-native";
import { afterEach, expect, it } from "vitest";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
import { type IndicatorLoop, useIndicatorLoop } from "./loop.web";
import { INDICATOR_STEP_MS } from "./steps";
// A ring and a shimmer: two stepped loops of different lengths on the step grid, one counted from
// the timeline's origin and one from the step it started in.
const RING: IndicatorLoop = {
keyframes: [
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` },
{ transform: "rotate(360deg)" },
],
durationMs: STATUS_RING_PERIOD_MS,
phase: "shared",
};
const SHIMMER_STEPS = 42;
const SHIMMER: IndicatorLoop = {
keyframes: [
{ transform: "translateX(-100px)", easing: `steps(${SHIMMER_STEPS})` },
{ transform: "translateX(300px)" },
],
durationMs: SHIMMER_STEPS * INDICATOR_STEP_MS,
phase: "own",
};
function Indicators() {
const ringRef = useIndicatorLoop(RING);
const shimmerRef = useIndicatorLoop(SHIMMER);
return (
<>
<View ref={ringRef} testID="ring" />
<View ref={shimmerRef} testID="shimmer" />
</>
);
}
let root: Root | null = null;
afterEach(() => {
act(() => root?.unmount());
root = null;
document.body.innerHTML = "";
});
function mountIndicators(): { ring: Animation; shimmer: Animation } {
const container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root!.render(<Indicators />));
const animationOf = (testId: string) => {
const element = container.querySelector(`[data-testid="${testId}"]`);
const animation = element?.getAnimations()[0];
if (!animation) throw new Error(`${testId} is not animating`);
return animation;
};
return { ring: animationOf("ring"), shimmer: animationOf("shimmer") };
}
/**
* Steps through every timeline time, on the microsecond marks a browser stamps frames at, around
* each of the grid's next `boundaries` step boundaries. Reports how often each loop turned over and
* the times at which one of the two turned over and the other did not.
*/
function sweepBoundaries(
loops: { ring: Animation; shimmer: Animation },
boundaries: number,
): { ringTurnovers: number; shimmerTurnovers: number; turningOneLoop: number[] } {
const elements = {
ring: loops.ring.effect as KeyframeEffect,
shimmer: loops.shimmer.effect as KeyframeEffect,
};
const startTimes = {
ring: Number(loops.ring.startTime),
shimmer: Number(loops.shimmer.startTime),
};
loops.ring.pause();
loops.shimmer.pause();
const showAt = (timelineMs: number) => {
loops.ring.currentTime = timelineMs - startTimes.ring;
loops.shimmer.currentTime = timelineMs - startTimes.shimmer;
return {
ring: getComputedStyle(elements.ring.target!).transform,
shimmer: getComputedStyle(elements.shimmer.target!).transform,
};
};
const firstStep = Math.ceil(startTimes.shimmer / INDICATOR_STEP_MS) + 1;
const turnovers = { ringTurnovers: 0, shimmerTurnovers: 0, turningOneLoop: [] as number[] };
for (let step = firstStep; step < firstStep + boundaries; step += 1) {
const boundaryUs = Math.round(step * INDICATOR_STEP_MS * 1000);
let previous = showAt((boundaryUs - 20) / 1000);
for (let frameUs = boundaryUs - 19; frameUs <= boundaryUs + 20; frameUs += 1) {
const current = showAt(frameUs / 1000);
const ringTurned = current.ring !== previous.ring;
const shimmerTurned = current.shimmer !== previous.shimmer;
if (ringTurned) turnovers.ringTurnovers += 1;
if (shimmerTurned) turnovers.shimmerTurnovers += 1;
if (ringTurned !== shimmerTurned) {
turnovers.turningOneLoop.push(frameUs / 1000);
}
previous = current;
}
}
return turnovers;
}
it("turns loops of different lengths over on the same frame, whenever the frame is stamped", () => {
const loops = mountIndicators();
// Each loop turns over once at every boundary, and never on a frame without the other.
expect(sweepBoundaries(loops, 300)).toEqual({
ringTurnovers: 300,
shimmerTurnovers: 300,
turningOneLoop: [],
});
});
@@ -2,7 +2,14 @@ import { useLayoutEffect, useRef, type RefObject } from "react";
import type { View } from "react-native";
import { INDICATOR_STEP_MS } from "./steps";
const TIMELINE_ORIGIN_MS = 0;
// Where the step grid starts on the document timeline. Browsers stamp a frame at a whole number of
// microseconds, often coarsened to 5 or 100. Each loop works out a step boundary from its own
// duration, so floating-point rounding can put a boundary that falls exactly on a frame's stamp
// before that frame for one loop and after it for another: the two then turn over on consecutive
// frames, and the window draws one more. Every third boundary of a grid from 0 is a whole number of
// milliseconds and so falls on a stamp. Starting the grid 2.5 µs in keeps every boundary at least
// a sixth of a microsecond from any stamp, far beyond the rounding.
const STEP_GRID_ORIGIN_MS = 0.0025;
export interface IndicatorLoop {
/** One cycle. Keep the array's identity stable: a new array restarts the loop. */
@@ -10,7 +17,7 @@ export interface IndicatorLoop {
durationMs: number;
/**
* `shared` puts every instance at the same point of the cycle, wherever and whenever it mounted:
* the loop counts from the document timeline's origin instead of from its own start. `own` starts
* the loop counts from the step grid's origin instead of from its own start. `own` starts
* the cycle at the step of the indicator step grid the loop starts in, so a stepped loop turns
* over with every other; see `steps.ts`.
*/
@@ -19,8 +26,8 @@ export interface IndicatorLoop {
// The start of the step of the indicator step grid the document timeline is in now.
function currentStepStartMs(): number {
const now = Number(document.timeline.currentTime ?? 0);
return Math.floor(now / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
const sinceOrigin = Number(document.timeline.currentTime ?? 0) - STEP_GRID_ORIGIN_MS;
return STEP_GRID_ORIGIN_MS + Math.floor(sinceOrigin / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
}
/**
@@ -47,7 +54,7 @@ export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | n
iterations: Number.POSITIVE_INFINITY,
});
// An explicit start also keeps loops that start in the same commit exactly together.
animation.startTime = loop.phase === "shared" ? TIMELINE_ORIGIN_MS : currentStepStartMs();
animation.startTime = loop.phase === "shared" ? STEP_GRID_ORIGIN_MS : currentStepStartMs();
return () => {
animation.cancel();
};
+3 -12
View File
@@ -37,10 +37,7 @@ import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-nativ
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
TitlebarDragRegion,
WINDOW_CONTENT_DATASET,
} from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -698,15 +695,13 @@ function MobileSidebar({
interface SidebarNavScrollProps {
closeGestureRef: RefObject<GestureType | undefined>;
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
windowContent?: boolean;
children: ReactNode;
}
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
// divider below it. The divider is a sibling because Unistyles does not patch the
// gesture-handler ScrollView.
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
function SidebarNavScroll({ closeGestureRef, children }: SidebarNavScrollProps) {
return (
<>
{platformIsNative ? (
@@ -723,7 +718,6 @@ function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarN
</GHScrollView>
) : (
<ScrollView
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
@@ -899,11 +893,8 @@ function DesktopSidebar({
</View>
) : null}
</View>
{/* The drag overlay stays above this viewport: Electron does not clip
app-region rects to scroll viewports, so a scrolled-out row would
still claim its no-drag rect. */}
{hasNavRows ? (
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
<SidebarNavScroll closeGestureRef={closeGestureRef}>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
</SidebarNavScroll>
) : null}
@@ -497,6 +497,30 @@ it("recognizes forge references in prose but not in code, links or paths", async
});
});
it.each([
["见 src/app/main.ts,还有", ["src/app/main.ts"]],
["改了 src/a/b/c,然后", ["src/a/b/c"]],
["src/foo.ts、src/bar.ts", ["src/foo.ts", "src/bar.ts"]],
["查看:docs/说明.md:12。", ["docs/说明.md:12"]],
["see src/app/main.ts, ok", ["src/app/main.ts"]],
])("recognizes bare file paths next to sentence punctuation: %s", async (source, expected) => {
const prepared = prepareMarkdownSource(source, "/repo");
const tree = recognizeTextLinks(
await parseMarkdown(prepared.render(), { latexMath: false }),
prepared.linkRecognition.text,
prepared.linkRecognition.inlineCode,
);
const parts = tree.children?.[0]?.children ?? [];
expect(parts.map((node) => node.content ?? node.children?.[0]?.content).join("")).toBe(source);
expect(parts.filter((node) => node.type === "Link").map((node) => node.attributes?.url)).toEqual(
expected,
);
expect(toNativeLinkRecognition(prepared.linkRecognition).text).toMatchObject({
isDisabled: false,
isDefault: false,
});
});
describe("bare URL sentence punctuation", () => {
it.each([".", ",", ";", ":", "!", "?", ")", ").", "...", "?!"])(
"leaves %s outside the link and preserves the rendered sentence",
@@ -1227,6 +1251,18 @@ it.each([
).toEqual([token]);
});
it.each([
["更正此前的进度说明:A/B/C/D 主实验", ["A/B/C/D"]],
["修改:src/index.ts,然后提交。", ["src/index.ts"]],
["见(docs/说明.md)。", ["docs/说明.md"]],
["参考「src/index.ts:12」、「README.md」", ["src/index.ts:12", "README.md"]],
["“./scripts/run”…", ["./scripts/run"]],
["文档在 docs/说明.md 里", ["docs/说明.md"]],
])("ends prose paths at CJK and typographic punctuation: %s", (source, expected) => {
const { linkRecognition } = prepareMarkdownSource(source, "/repo");
expect([...source.matchAll(linkRecognition.text)].map(([text]) => text)).toEqual(expected);
});
it.each([
"before/after",
"and/or",
+48 -6
View File
@@ -9,11 +9,56 @@ import { decodeString } from "micromark-util-decode-string";
import { fromMarkdown } from "mdast-util-from-markdown";
import type { Link, Nodes, Paragraph, PhrasingContent, Root } from "mdast";
// CJK, fullwidth and typographic punctuation (、。,:()【】「」“”…) ends bare URLs and prose
// paths; CJK letters do not.
const PUNCTUATION_BOUNDARY_RANGES: readonly (readonly [number, number])[] = [
[0x2018, 0x2019],
[0x201c, 0x201d],
[0x2026, 0x2026],
[0x3000, 0x3003],
[0x3008, 0x3011],
[0x3014, 0x301f],
[0xff01, 0xff0f],
[0xff1a, 0xff20],
[0xff3b, 0xff40],
[0xff5b, 0xff65],
];
function formatCharacterRanges(ranges: readonly (readonly [number, number])[]): string {
const escape = (codePoint: number) =>
`\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
return ranges
.map(([start, end]) => (start === end ? escape(start) : `${escape(start)}-${escape(end)}`))
.join("");
}
/** The parts of `from`..`to` that no excluded range covers. */
function subtractCharacterRanges(
from: number,
to: number,
excluded: readonly (readonly [number, number])[],
): [number, number][] {
const kept: [number, number][] = [];
let next = from;
for (const [start, end] of excluded) {
if (start > next) kept.push([next, start - 1]);
next = end + 1;
}
if (next <= to) kept.push([next, to]);
return kept;
}
const URL_BOUNDARY = formatCharacterRanges(PUNCTUATION_BOUNDARY_RANGES);
// Non-ASCII characters a path can contain: everything from U+0080 except boundary punctuation.
const PATH_NON_ASCII = formatCharacterRanges(
subtractCharacterRanges(0x80, 0xffff, PUNCTUATION_BOUNDARY_RANGES),
);
// Keep this regex in the syntax shared by JavaScript, ICU and java.util.regex.
// The Unicode flag makes Metro expand it to escapes rejected by native engines.
const PATH_CHARACTER = String.raw`[a-zA-Z0-9\u0080-\uFFFF_@.%+-]`;
const PATH_CHARACTER = String.raw`[a-zA-Z0-9${PATH_NON_ASCII}_@.%+-]`;
const PATH_LETTER = String.raw`[a-zA-Z]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9\u0080-\uFFFF_@%+-]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9${PATH_NON_ASCII}_@%+-]`;
const LINE_SUFFIX = String.raw`(?::\d+(?::\d+)?(?:-\d+(?::\d+)?)?)?`;
const FILE_EXTENSIONS = [...ASSISTANT_FILE_EXTENSIONS]
.map((extension) => extension.replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`))
@@ -30,16 +75,13 @@ function createTextPattern(path: string, forgeReferencePattern?: string): RegExp
const forgeReference = forgeReferencePattern ? `|${forgeReferencePattern}` : "";
// The native adapter mistakes a literal + in lookbehind for a quantifier; use its hex escape.
return new RegExp(
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9\u0080-\uFFFF_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9\u0080-\uFFFF_@%+:/\\-]|\.${PATH_CHARACTER}))`,
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9${PATH_NON_ASCII}_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9${PATH_NON_ASCII}_@%+:/\\-]|\.${PATH_CHARACTER}))`,
"g",
);
}
// Matches bare URLs that MD4C does not autolink, like single-label or bracketed hosts.
// Quotes and unbalanced closing parentheses end the URL. Trailing sentence punctuation stays outside.
// CJK, fullwidth and typographic punctuation (、。,()【】「」“”…) also ends it; CJK letters do not.
const URL_BOUNDARY =
"\\u2018\\u2019\\u201C\\u201D\\u2026\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65";
const URL_CHARACTER = String.raw`[^\s<>()"'\x60${URL_BOUNDARY}]`;
const URL_GROUP = String.raw`\(${URL_CHARACTER}*\)`;
const BARE_URL = String.raw`https?://(?:${URL_CHARACTER}|${URL_GROUP})*(?:[^\s<>()"'\x60.,;:!?${URL_BOUNDARY}]|${URL_GROUP})`;
@@ -252,13 +252,7 @@ export function SplitContainer({
const renderRoot = useMemo(() => wrapRootPaneForStableMount(splitRoot.root), [splitRoot.root]);
const panesShareWorkspaceHeader = hasMultipleVisiblePanes(splitRoot.root);
const sharedCompactHeader = useMemo(
() =>
panesShareWorkspaceHeader ? (
<WindowChromeSafeArea placement="inline">
<TitlebarDragRegion />
{renderCompactHeader(null)}
</WindowChromeSafeArea>
) : null,
() => (panesShareWorkspaceHeader ? renderCompactHeader(null) : null),
[panesShareWorkspaceHeader, renderCompactHeader],
);
return (
@@ -800,16 +794,13 @@ const SplitPaneView = memo(function SplitPaneView({
});
const compactHeader = useMemo(
() =>
ownsWorkspaceHeader ? (
<WindowChromeSafeArea placement="inline">
<TitlebarDragRegion />
{renderCompactHeader({
ownsWorkspaceHeader
? renderCompactHeader({
tabs: paneTabs,
activeTabKey: activeTabDescriptor?.key ?? "",
actions: compactHeaderActions,
})}
</WindowChromeSafeArea>
) : null,
})
: null,
[
ownsWorkspaceHeader,
renderCompactHeader,
+16 -12
View File
@@ -18,6 +18,21 @@ export function Checkbox({ checked }: { checked: boolean }) {
);
}
/** React Native Web checkboxes need an explicit Space handler when built on Pressable. */
export function useCheckboxSpaceKey(onToggle: () => void, disabled: boolean) {
return useMemo(() => {
if (!isWeb || disabled) return {};
return {
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
onToggle();
}
},
};
}, [disabled, onToggle]);
}
interface HoverState {
hovered?: boolean;
}
@@ -48,18 +63,7 @@ export function CheckboxRow({
({ hovered }: HoverState) => [style, hovered && !disabled ? styles.hovered : null],
[disabled, style],
);
const keyProps = useMemo(() => {
if (!isWeb || disabled) return {};
return {
// React Native Web's Pressable activates Space only for role="button", not checkbox.
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
onToggle();
}
},
};
}, [disabled, onToggle]);
const keyProps = useCheckboxSpaceKey(onToggle, disabled);
return (
<PressHighlight
@@ -8,6 +8,7 @@ import {
} from "react";
import { StyleSheet, View } from "react-native";
import { PortalHost } from "@gorhom/portal";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import {
createFloatingPanelHosts,
type FloatingPanelHostRect,
@@ -57,7 +58,13 @@ export function FloatingPanelPortalHost({
}, [name]);
return (
<View ref={hostRef} collapsable={false} pointerEvents="box-none" style={styles.host}>
<View
ref={hostRef}
collapsable={false}
dataSet={WINDOW_OVERLAY_HOST_DATASET}
pointerEvents="box-none"
style={styles.host}
>
<PortalHost name={name} />
</View>
);
@@ -185,6 +185,13 @@ export function ComposerEditingScope({
const scope = useMemo(() => ({ tabId, targetKey }), [tabId, targetKey]);
return <ScopeContext.Provider value={scope}>{children}</ScopeContext.Provider>;
}
/**
* Composers inside edit in sessions of their own, apart from the workspace tab around them: a
* plugin's `AgentChat` in a panel must not share the panel's fullscreen, caret or command target.
*/
export function LocalComposerEditingScope({ children }: { children: ReactNode }) {
return <ScopeContext.Provider value={null}>{children}</ScopeContext.Provider>;
}
export function useComposerEditingSession(
purpose: ComposerInputMode,
provided?: ComposerEditingSession,
@@ -80,6 +80,7 @@ interface SearchCall {
}
interface HarnessInput {
enabled?: boolean;
initialAttachments?: UserComposerAttachment[];
initialCwd?: string;
initialText?: string;
@@ -137,6 +138,7 @@ function useHarness(client: ForgeSearchClient, input: HarnessInput = {}) {
input.initialAttachments ?? [],
);
const autoAttach = useComposerForgeAutoAttach({
enabled: input.enabled ?? true,
text,
remoteUrl: input.remote ?? remoteUrl,
attachments,
@@ -190,6 +192,27 @@ describe("useComposerForgeAutoAttach", () => {
vi.useRealTimers();
});
it("leaves pasted links as text in a composer that takes no attachments", async () => {
vi.useFakeTimers();
const client = createSearchClient([pr101]);
const onChangeRequestDetected = vi.fn();
const { result } = renderHook(
() => useHarness(client, { enabled: false, onChangeRequestDetected }),
{ wrapper: createWrapper() },
);
act(() => {
result.current.setText("Please review https://github.com/acme/paseo/pull/101");
});
expect(result.current.isResolving).toBe(false);
await flushDebounce();
expect(result.current.attachments).toEqual([]);
expect(onChangeRequestDetected).not.toHaveBeenCalled();
expect(client.calls).toEqual([]);
vi.useRealTimers();
});
it("adds a matching pasted GitLab MR URL as a composer attachment", async () => {
vi.useFakeTimers();
const client = createSearchClient([gitlabMr73]);
+14 -9
View File
@@ -19,6 +19,8 @@ import { forgeItemKey } from "./attachments/forge-item-key";
const AUTO_ATTACH_DEBOUNCE_MS = 300;
interface ComposerForgeAutoAttachInput {
/** Whether links in the text become attachments: off for a composer that takes none. */
enabled: boolean;
text: string;
remoteUrl: string | null | undefined;
attachments: UserComposerAttachment[];
@@ -164,6 +166,11 @@ export function useComposerForgeAutoAttach(
);
}
/** The forge links in the text that auto-attach would act on. */
function linkedForgeRefs(params: ComposerForgeAutoAttachInput): ForgeRef[] {
return params.enabled ? extractForgeRefs(params.text, params.remoteUrl) : [];
}
function getLookupCandidateKey(
params: ComposerForgeAutoAttachInput,
removedRefKeys: ReadonlySet<string>,
@@ -175,7 +182,7 @@ function getLookupCandidateRefs(
params: ComposerForgeAutoAttachInput,
removedRefKeys: ReadonlySet<string>,
): ForgeRef[] {
return extractForgeRefs(params.text, params.remoteUrl).filter((ref) => {
return linkedForgeRefs(params).filter((ref) => {
const key = forgeRefKey(ref);
return !removedRefKeys.has(key) && !hasForgeAttachment(params.attachments, ref);
});
@@ -196,7 +203,7 @@ function getLookupRelevanceKey(
params: ComposerForgeAutoAttachInput,
removedRefKeys: ReadonlySet<string>,
): string {
return extractForgeRefs(params.text, params.remoteUrl)
return linkedForgeRefs(params)
.map(forgeRefKey)
.filter((key) => !removedRefKeys.has(key))
.sort()
@@ -204,7 +211,7 @@ function getLookupRelevanceKey(
}
function getPresentChangeRequestKey(params: ComposerForgeAutoAttachInput): string {
return extractForgeRefs(params.text, params.remoteUrl)
return linkedForgeRefs(params)
.filter((ref) => ref.kind === "change_request")
.map(forgeRefKey)
.sort()
@@ -248,7 +255,7 @@ function suppressRefsCarriedAcrossTargets({
previousTargetRef.current = { serverId: params.serverId, cwd: params.cwd };
if (!targetChanged) return;
for (const ref of extractForgeRefs(params.text, params.remoteUrl)) {
for (const ref of linkedForgeRefs(params)) {
removedRefKeys.add(forgeRefKey(ref));
}
}
@@ -261,7 +268,7 @@ function notifyNewChangeRequestRefs({
presentChangeRequestKeysRef: RefObject<Set<string>>;
}): void {
const currentKeys = new Set(
extractForgeRefs(params.text, params.remoteUrl)
linkedForgeRefs(params)
.filter((ref) => ref.kind === "change_request")
.map(forgeRefKey),
);
@@ -449,7 +456,7 @@ function refsReadyForLookup({
return [];
}
return extractForgeRefs(params.text, params.remoteUrl).filter((ref) => {
return linkedForgeRefs(params).filter((ref) => {
const key = forgeRefKey(ref);
return (
!removedRefKeys.has(key) &&
@@ -489,9 +496,7 @@ async function fetchForgeRefSearch({
}
function isRefStillPresent(ref: ForgeRef, params: ComposerForgeAutoAttachInput): boolean {
return extractForgeRefs(params.text, params.remoteUrl).some(
(candidate) => forgeRefKey(candidate) === forgeRefKey(ref),
);
return linkedForgeRefs(params).some((candidate) => forgeRefKey(candidate) === forgeRefKey(ref));
}
function isSameLookupTarget(
+44 -48
View File
@@ -123,7 +123,10 @@ import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { AutocompletePopover } from "@/components/ui/autocomplete-popover";
import type { AutocompleteOption } from "@/components/ui/autocomplete";
import { useAgentAutocomplete } from "@/hooks/use-agent-autocomplete";
import { usePluginClientSlashCommands } from "@/plugins/client-slash-commands";
import {
type PluginClientSlashCommand,
usePluginClientSlashCommands,
} from "@/plugins/client-slash-commands";
import {
executePluginClientSlashCommand,
resolvePluginClientSlashCommand,
@@ -226,6 +229,7 @@ type AttachmentListUpdater =
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
const EMPTY_ATTACHMENT_SCOPE_KEYS: readonly string[] = [];
const NO_PLUGIN_CLIENT_SLASH_COMMANDS: PluginClientSlashCommand[] = [];
function noop() {}
const noopCallback = () => {};
@@ -1402,6 +1406,8 @@ function ComposerContentImpl({
const [isForgeResolving, setIsForgeResolving] = useState(false);
const forgeConfiguration = useMemo(
() => ({
// A mode without attachments sends text as written, so links stay text.
enabled: mode.showAttachments,
remoteUrl: resolveCheckoutRemoteUrl(checkoutStatusQuery.status),
attachments,
client,
@@ -1414,6 +1420,7 @@ function ComposerContentImpl({
onChangeRequestAdded: onForgeChangeRequestAutoAttach,
}),
[
mode.showAttachments,
checkoutStatusQuery.status,
attachments,
client,
@@ -1456,11 +1463,16 @@ function ComposerContentImpl({
onChangeAttachments: setSelectedAttachments,
anchorRef: attachButtonRef,
});
const pluginClientSlashCommands = usePluginClientSlashCommands({
const installedPluginClientSlashCommands = usePluginClientSlashCommands({
serverId,
workspaceId,
agentId,
});
// One switch for every client-side command, built-in or plugin, on the send and queue paths.
const handlesClientCommands = mode.runsClientCommands;
const pluginClientSlashCommands = handlesClientCommands
? installedPluginClientSlashCommands
: NO_PLUGIN_CLIENT_SLASH_COMMANDS;
const isComposerLocked = resolveIsComposerLocked(submitBehavior, isSubmitLoading);
const keyboardHandlerIdRef = useRef(
`message-input:${serverId}:${agentId}:${Math.random().toString(36).slice(2)}`,
@@ -1569,6 +1581,7 @@ function ComposerContentImpl({
const runClientSlashCommand = useCallback(
(command: ClientSlashCommand): boolean => {
if (!handlesClientCommands) return false;
if (command.execution !== "immediate" || !onClientSlashCommand) {
return false;
}
@@ -1595,6 +1608,7 @@ function ComposerContentImpl({
[
blurOnSubmit,
clearDraft,
handlesClientCommands,
onClientSlashCommand,
resetSuppression,
setSelectedAttachments,
@@ -1631,6 +1645,22 @@ function ComposerContentImpl({
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
);
/** Runs `text` as a client command when it is one; false sends it to the agent. */
const runComposerClientCommand = useCallback(
(text: string, hasAttachments: boolean): boolean => {
const clientSlashCommand = resolveClientSlashCommand({ text, hasAttachments });
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) return true;
const pluginSlashCommand = resolvePluginClientSlashCommand({
text,
commands: pluginClientSlashCommands,
});
if (!pluginSlashCommand) return false;
runPluginClientSlashCommand(pluginSlashCommand, hasAttachments);
return true;
},
[pluginClientSlashCommands, runClientSlashCommand, runPluginClientSlashCommand],
);
const { pickImages } = useImageAttachmentPicker();
const { pickFiles } = useFilePicker();
const agentIdRef = useRef(agentId);
@@ -1923,21 +1953,7 @@ function ComposerContentImpl({
const handleSubmit = useCallback(
(payload: MessagePayload) => {
const outgoingAttachments = buildOutgoingAttachments(attachments);
const clientSlashCommand = resolveClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
});
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) {
return;
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (runComposerClientCommand(payload.text, outgoingAttachments.length > 0)) return;
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -1948,9 +1964,7 @@ function ComposerContentImpl({
attachments,
blurOnSubmit,
buildOutgoingAttachments,
runClientSlashCommand,
pluginClientSlashCommands,
runPluginClientSlashCommand,
runComposerClientCommand,
sendMessageWithContent,
],
);
@@ -2191,31 +2205,10 @@ function ComposerContentImpl({
const handleQueue = useCallback(
(payload: MessagePayload) => {
const outgoingAttachments = buildOutgoingAttachments(attachments);
const clientSlashCommand = resolveClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
});
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) {
return;
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (runComposerClientCommand(payload.text, outgoingAttachments.length > 0)) return;
void sendMessageWithContent(payload.text, outgoingAttachments);
},
[
attachments,
buildOutgoingAttachments,
pluginClientSlashCommands,
runClientSlashCommand,
runPluginClientSlashCommand,
sendMessageWithContent,
],
[attachments, buildOutgoingAttachments, runComposerClientCommand, sendMessageWithContent],
);
// An open autocomplete owns the arrows; otherwise they may recall sent messages.
@@ -2305,9 +2298,10 @@ function ComposerContentImpl({
],
);
const showsUsage = mode.showUsage;
const beforeVoiceContent = useMemo(
() =>
hasAgent ? (
hasAgent && showsUsage ? (
<View style={styles.contextWindowMeterSlot}>
<ContextWindowMeter
serverId={serverId}
@@ -2322,6 +2316,7 @@ function ComposerContentImpl({
) : null,
[
hasAgent,
showsUsage,
serverId,
agentId,
agentState.contextWindowMaxTokens,
@@ -2615,7 +2610,8 @@ function ComposerContentImpl({
onGenericFiles: handleGenericFilesDropped,
onWorkspaceFile: handleWorkspaceFileDropped,
},
{ disabled: isSubmitLoadingVisible },
// A mode without attachments refuses files by any route, not only the button.
{ disabled: isSubmitLoadingVisible || !mode.showAttachments },
);
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
@@ -2713,9 +2709,9 @@ function ComposerContentImpl({
cwd={cwd}
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteFiles={handlePasteFiles}
onPasteImages={handleNativePasteImages}
onAddImages={mode.showAttachments ? addImages : undefined}
onPasteFiles={mode.showAttachments ? handlePasteFiles : undefined}
onPasteImages={mode.showAttachments ? handleNativePasteImages : undefined}
client={client}
isReadyForDictation={isDictationReady}
placeholder={messagePlaceholder}
+25 -3
View File
@@ -1,13 +1,16 @@
/**
* What a composer is being used for. `Composer` and `MessageInput` are one
* component with two jobs, not two components: a terminal prompt still wants
* component with several jobs, not several components: a terminal prompt still wants
* the same bordered surface, grow-on-newline, submit button, focus handling,
* and keyboard shift that a chat message gets.
*
* `message` is a chat composer reduced to a text box and Send: what the user types
* reaches the agent as written, with nothing the app interprets on the way.
*
* Callers pick a mode and nothing else. What a mode implies lives here, so the
* two presentations cannot drift apart one prop at a time.
* presentations cannot drift apart one prop at a time.
*/
export type ComposerInputMode = "chat" | "terminal";
export type ComposerInputMode = "chat" | "message" | "terminal";
export interface ComposerInputModePresentation {
/** Attachments, dictation/voice, slash-and-@ autocomplete, and the model/mode
@@ -16,6 +19,11 @@ export interface ComposerInputModePresentation {
showVoice: boolean;
showAutocomplete: boolean;
showAgentControls: boolean;
/** The context window and cost meter beside Send. */
showUsage: boolean;
/** Client slash commands, built-in (`/exit`, `/clear`) and plugin, run in the
* app instead of being sent. */
runsClientCommands: boolean;
/** Argv is read character by character, so it gets the terminal's own font. */
isMonospace: boolean;
/** i18n key for the text input's accessible name. */
@@ -28,6 +36,18 @@ const PRESENTATION_BY_MODE: Record<ComposerInputMode, ComposerInputModePresentat
showVoice: true,
showAutocomplete: true,
showAgentControls: true,
showUsage: true,
runsClientCommands: true,
isMonospace: false,
accessibilityLabelKey: "composer.input.accessibilityLabel",
},
message: {
showAttachments: false,
showVoice: false,
showAutocomplete: false,
showAgentControls: false,
showUsage: false,
runsClientCommands: false,
isMonospace: false,
accessibilityLabelKey: "composer.input.accessibilityLabel",
},
@@ -36,6 +56,8 @@ const PRESENTATION_BY_MODE: Record<ComposerInputMode, ComposerInputModePresentat
showVoice: false,
showAutocomplete: false,
showAgentControls: false,
showUsage: false,
runsClientCommands: true,
isMonospace: true,
accessibilityLabelKey: "composer.input.terminalAccessibilityLabel",
},
@@ -2,8 +2,9 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { createJSONStorage, type StateStorage } from "zustand/middleware";
import { mountBrowserAutomationHandler, type BrowserAutomationHandlerOptions } from "./handler";
import type { DesktopHostBridge } from "@/desktop/host";
import type { DesktopAutomationExecutionContext, DesktopHostBridge } from "@/desktop/host";
import { useBrowserStore } from "@/desktop/browser/store";
import { useSessionStore } from "@/stores/session-store";
import { findPaneById } from "@/stores/workspace-layout-actions";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
@@ -72,9 +73,11 @@ class FakeDaemonClient {
class FakeBrowserBridge {
public readonly executedRequests: BrowserAutomationExecuteRequest[] = [];
public readonly executedContexts: DesktopAutomationExecutionContext[] = [];
public readonly unregisteredWorkspaceBrowsers: string[] = [];
public readonly activeWorkspaceBrowsers: Array<{
browserId: string | null;
serverId: string;
workspaceId: string;
}> = [];
public response: BrowserAutomationResponsePayload | null = null;
@@ -82,8 +85,10 @@ class FakeBrowserBridge {
public executeAutomationCommand = async (
request: BrowserAutomationExecuteRequest,
context: DesktopAutomationExecutionContext,
): Promise<BrowserAutomationResponsePayload> => {
this.executedRequests.push(request);
this.executedContexts.push(context);
if (this.thrownError) {
throw this.thrownError;
}
@@ -96,6 +101,7 @@ class FakeBrowserBridge {
public setWorkspaceActiveBrowser = async (input: {
browserId: string | null;
serverId: string;
workspaceId: string;
}): Promise<void> => {
this.activeWorkspaceBrowsers.push(input);
@@ -105,6 +111,7 @@ class FakeBrowserBridge {
class FakeResidentBrowser {
public readonly ensuredWebviews: Array<{
browserId: string;
serverId: string;
workspaceId: string;
url: string;
partition?: string;
@@ -112,6 +119,7 @@ class FakeResidentBrowser {
public ensure = (input: {
browserId: string;
serverId: string;
workspaceId: string;
url: string;
partition?: string;
@@ -131,20 +139,22 @@ class BrowserAutomationHandlerHarness {
input: {
serverId?: string;
host?: DesktopHostBridge | null;
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"];
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"] | null;
prepareHostBrowserPartition?: BrowserAutomationHandlerOptions["prepareHostBrowserPartition"];
registrationWaitTimeoutMs?: number;
registrationPollIntervalMs?: number;
} = {},
): void {
const readHostBrowserRouting =
input.readHostBrowserRouting === null
? undefined
: (input.readHostBrowserRouting ?? (() => ({ kind: "local" as const })));
this.unsubscribe = mountBrowserAutomationHandler({
client: this.client,
...(input.serverId ? { serverId: input.serverId } : {}),
getHost: () => (input.host === undefined ? { browser: this.browser } : input.host),
ensureResidentBrowserWebview: this.resident.ensure,
...(input.readHostBrowserRouting
? { readHostBrowserRouting: input.readHostBrowserRouting }
: {}),
...(readHostBrowserRouting ? { readHostBrowserRouting } : {}),
...(input.prepareHostBrowserPartition
? { prepareHostBrowserPartition: input.prepareHostBrowserPartition }
: {}),
@@ -167,10 +177,14 @@ class BrowserAutomationHandlerHarness {
}
}
function browserAutomationRequest(): BrowserAutomationExecuteRequest {
function browserAutomationRequest(input?: {
workspaceId?: string;
}): BrowserAutomationExecuteRequest {
const workspaceId = input && "workspaceId" in input ? input.workspaceId : "wks_workspace_a";
return {
type: "browser.automation.execute.request",
requestId: "req-1",
...(workspaceId ? { workspaceId } : {}),
command: { command: "list_tabs", args: {} },
};
}
@@ -294,6 +308,7 @@ describe("mountBrowserAutomationHandler", () => {
browserAutomationStorage.clear();
useBrowserStore.setState({ browsersById: {} });
useWorkspaceLayoutStore.setState({ layoutByWorkspace: {} });
useSessionStore.setState({ sessions: {} });
});
test("browser_new_tab creates a workspace browser tab without stealing focus", async () => {
@@ -338,6 +353,7 @@ describe("mountBrowserAutomationHandler", () => {
expect(browser.resident.ensuredWebviews).toEqual([
{
browserId: result.browserId,
serverId: "server-1",
workspaceId: "wks_workspace_a",
url: "https://example.com",
},
@@ -543,13 +559,14 @@ describe("mountBrowserAutomationHandler", () => {
ok: true,
result: { command: "list_tabs", tabs: [] },
};
browser.mount();
browser.mount({ serverId: "server-1" });
const request = browserAutomationRequest();
browser.receive(request);
await flushAsyncWork();
expect(browser.browser.executedRequests).toEqual([request]);
expect(browser.browser.executedContexts).toEqual([{ serverId: "server-1", uploadRoot: null }]);
expect(browser.client.sentResponses).toEqual([
{
type: "browser.automation.execute.response",
@@ -564,7 +581,7 @@ describe("mountBrowserAutomationHandler", () => {
test("missing desktop bridge sends browser_unsupported", async () => {
const browser = new BrowserAutomationHandlerHarness();
browser.mount({ host: null });
browser.mount({ serverId: "server-1", host: null });
browser.receive(browserAutomationRequest());
await flushAsyncWork();
@@ -592,7 +609,7 @@ describe("mountBrowserAutomationHandler", () => {
message: "Browser tab browser-1 was not found.",
retryable: false,
};
browser.mount();
browser.mount({ serverId: "server-1" });
browser.receive(browserAutomationRequest());
await flushAsyncWork();
@@ -618,7 +635,7 @@ describe("mountBrowserAutomationHandler", () => {
browser.browser.thrownError = new Error(
'No handler registered for "paseo:browser:execute-automation-command"',
);
browser.mount();
browser.mount({ serverId: "server-1" });
browser.receive(browserAutomationRequest());
await flushAsyncWork();
@@ -641,7 +658,7 @@ describe("mountBrowserAutomationHandler", () => {
test("unsubscribe stops handling browser automation requests", async () => {
const browser = new BrowserAutomationHandlerHarness();
browser.mount();
browser.mount({ serverId: "server-1" });
browser.unmount();
browser.receive(browserAutomationRequest());
@@ -680,6 +697,7 @@ describe("mountBrowserAutomationHandler", () => {
expect(browser.resident.ensuredWebviews).toEqual([
{
browserId: result.browserId,
serverId: "remote-1",
workspaceId: "wks_workspace_a",
url: "http://localhost:5173",
partition: "persist:paseo-browser-host-0123456789abcdef",
@@ -687,6 +705,165 @@ describe("mountBrowserAutomationHandler", () => {
]);
});
test("browser_resize fails closed when workspaceId is omitted", async () => {
const browser = new BrowserAutomationHandlerHarness();
browser.mount({ serverId: "server-1" });
browser.receive(browserNewTabRequest());
await vi.waitFor(() => expect(browser.client.sentResponses).toHaveLength(1));
const result = newTabResultFrom(browser.client.payloadAt(0));
browser.receive({
type: "browser.automation.execute.request",
requestId: "req-resize-no-ws",
agentId: "agent-1",
command: {
command: "resize",
args: { browserId: result.browserId, width: 800, height: 600 },
},
});
await flushAsyncWork();
expect(browser.client.payloadAt(1)).toEqual({
requestId: "req-resize-no-ws",
ok: false,
error: {
code: "browser_denied",
message: expect.stringMatching(/workspace/i),
retryable: false,
},
});
expect(useBrowserStore.getState().browsersById[result.browserId]?.viewport).toEqual({
mode: "responsive",
});
});
test("forwarded commands fail closed when workspaceId is omitted", async () => {
const browser = new BrowserAutomationHandlerHarness();
browser.mount({ serverId: "server-1" });
browser.receive(browserAutomationRequest({ workspaceId: "" }));
await flushAsyncWork();
expect(browser.browser.executedRequests).toEqual([]);
expect(browser.client.payloadAt(0)).toEqual({
requestId: "req-1",
ok: false,
error: {
code: "browser_denied",
message: expect.stringMatching(/workspace/i),
retryable: false,
},
});
});
test("passes uploadRoot from session-store for local hosts and null for remote hosts", async () => {
const store = useSessionStore.getState();
store.initializeSession("local-1", null);
store.mergeWorkspaces("local-1", [
{
id: "wks_workspace_a",
projectId: "proj-1",
projectDisplayName: "Project",
projectRootPath: "/Users/dev/project",
workspaceDirectory: "/Users/dev/project",
projectKind: "git",
workspaceKind: "directory",
name: "Project",
title: "Project",
status: "done",
statusEnteredAt: null,
createdAt: null,
lastUserMessageAt: null,
archivingAt: null,
diffStat: null,
scripts: [],
},
]);
store.initializeSession("remote-1", null);
store.mergeWorkspaces("remote-1", [
{
id: "wks_workspace_a",
projectId: "proj-2",
projectDisplayName: "Remote Project",
projectRootPath: "/home/remote/project",
workspaceDirectory: "/home/remote/project",
projectKind: "git",
workspaceKind: "directory",
name: "Remote Project",
title: "Remote Project",
status: "done",
statusEnteredAt: null,
createdAt: null,
lastUserMessageAt: null,
archivingAt: null,
diffStat: null,
scripts: [],
},
]);
const uploadRequest: BrowserAutomationExecuteRequest = {
type: "browser.automation.execute.request",
requestId: "req-upload",
workspaceId: "wks_workspace_a",
cwd: "/Users/dev/project",
command: {
command: "upload",
args: {
browserId: "11111111-1111-4111-8111-111111111111",
ref: "@e1",
filePaths: ["a.txt"],
},
},
};
const localHarness = new BrowserAutomationHandlerHarness();
localHarness.mount({
serverId: "local-1",
readHostBrowserRouting: () => ({ kind: "local" }),
});
localHarness.receive(uploadRequest);
await flushAsyncWork();
expect(localHarness.browser.executedContexts).toEqual([
{ serverId: "local-1", uploadRoot: "/Users/dev/project" },
]);
const remoteHarness = new BrowserAutomationHandlerHarness();
remoteHarness.mount({
serverId: "remote-1",
readHostBrowserRouting: () => ({
kind: "remote",
support: "supported",
target: "tcp://10.0.0.5:6767",
}),
});
remoteHarness.receive(uploadRequest);
await flushAsyncWork();
expect(remoteHarness.browser.executedContexts).toEqual([
{ serverId: "remote-1", uploadRoot: null },
]);
});
test("browser_new_tab on an unhydrated host fails closed without opening a local webview", async () => {
const browser = new BrowserAutomationHandlerHarness();
browser.mount({
serverId: "unhydrated-host-id",
readHostBrowserRouting: null,
});
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
await flushAsyncWork();
expect(browser.resident.ensuredWebviews).toEqual([]);
expect(browser.client.payloadAt(0)).toMatchObject({
requestId: "req-new",
ok: false,
error: {
code: "browser_unsupported",
},
});
});
test("remote agent browser_new_tab fails closed without creating a webview when host proxy cannot prepare", async () => {
const browser = new BrowserAutomationHandlerHarness();
browser.mount({
@@ -1,7 +1,11 @@
import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { getDesktopHost, type DesktopHostBridge } from "@/desktop/host";
import {
getDesktopHost,
type DesktopAutomationExecutionContext,
type DesktopHostBridge,
} from "@/desktop/host";
import {
ensureResidentBrowserWebview as ensureResidentBrowserWebviewDefault,
removeResidentBrowserWebview,
@@ -20,6 +24,7 @@ import {
useBrowserStore,
waitForBrowserHydration,
} from "@/desktop/browser/store";
import { useSessionStore } from "@/stores/session-store";
import { collectAllTabs, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
@@ -213,17 +218,70 @@ async function handleBrowserAutomationRequest(params: {
return;
}
client.sendBrowserAutomationExecuteResponse({
type: "browser.automation.execute.response",
payload: await forwardAutomationRequest({
request,
serverId,
executeAutomationCommand,
readHostBrowserRouting,
}),
});
}
function resolveWorkspaceUploadRoot(input: {
serverId: string;
workspaceId: string;
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
}): string | null {
if (input.readHostBrowserRouting(input.serverId).kind !== "local") {
return null;
}
const directory = useSessionStore
.getState()
.sessions[input.serverId]?.workspaces.get(input.workspaceId)
?.workspaceDirectory?.trim();
return directory || null;
}
async function forwardAutomationRequest(params: {
request: BrowserAutomationExecuteRequest;
serverId?: string;
executeAutomationCommand: NonNullable<DesktopHostBridge["browser"]>["executeAutomationCommand"];
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
}): Promise<BrowserAutomationResponsePayload> {
const { request, serverId, executeAutomationCommand, readHostBrowserRouting } = params;
const normalizedServerId = serverId?.trim();
const normalizedWorkspaceId = request.workspaceId?.trim();
if (!normalizedServerId || !normalizedWorkspaceId) {
return browserAutomationFailure({
requestId: request.requestId,
code: "browser_denied",
message: "Browser automation requires a server and workspace context.",
});
}
if (!executeAutomationCommand) {
return browserAutomationFailure({
requestId: request.requestId,
code: "browser_unsupported",
message: "Browser automation is not available in this app runtime.",
});
}
const uploadRoot = resolveWorkspaceUploadRoot({
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
readHostBrowserRouting,
});
try {
const payload = await executeAutomationCommand(request);
client.sendBrowserAutomationExecuteResponse({
type: "browser.automation.execute.response",
payload: normalizeBridgePayload(request.requestId, payload),
const payload = await executeAutomationCommand(request, {
serverId: normalizedServerId,
uploadRoot,
});
return normalizeBridgePayload(request.requestId, payload);
} catch (error) {
client.sendBrowserAutomationExecuteResponse({
type: "browser.automation.execute.response",
payload: normalizeThrownBridgeError(request.requestId, error),
});
return normalizeThrownBridgeError(request.requestId, error);
}
}
@@ -237,16 +295,24 @@ function resizeBrowserTabForRequest(params: {
{ command: "resize" }
>;
const browserId = command.args.browserId;
if (!getBrowserRecord(browserId)) {
const normalizedServerId = serverId?.trim();
const normalizedWorkspaceId = request.workspaceId?.trim();
if (!normalizedServerId || !normalizedWorkspaceId) {
return browserAutomationFailure({
requestId: request.requestId,
code: "browser_tab_not_found",
message: `No browser tab found for ID: ${browserId}`,
code: "browser_denied",
message: "Cannot resize a browser tab without a workspace context.",
});
}
const workspaceId = request.workspaceId;
if (serverId && workspaceId && !findWorkspaceBrowserTab({ serverId, workspaceId, browserId })) {
if (
!findWorkspaceBrowserTab({
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
browserId,
}) ||
!getBrowserRecord(browserId)
) {
return browserAutomationFailure({
requestId: request.requestId,
code: "browser_tab_not_found",
@@ -434,6 +500,7 @@ async function openBrowserTabForRequest(params: {
try {
ensureResidentBrowserWebview({
browserId,
serverId,
workspaceId,
url: normalizedUrl,
...(targetPartition ? { partition: targetPartition } : {}),
@@ -441,6 +508,7 @@ async function openBrowserTabForRequest(params: {
registered = await waitForBrowserRegistration({
request,
browserId,
serverId,
workspaceId,
executeAutomationCommand: browserHost.executeAutomationCommand,
...(registrationWaitTimeoutMs !== undefined
@@ -473,23 +541,31 @@ async function openBrowserTabForRequest(params: {
async function waitForBrowserRegistration(params: {
request: BrowserAutomationExecuteRequest;
browserId: string;
serverId: string;
workspaceId: string;
executeAutomationCommand: (
request: BrowserAutomationExecuteRequest,
context: DesktopAutomationExecutionContext,
) => Promise<BrowserAutomationResponsePayload>;
timeoutMs?: number;
pollIntervalMs?: number;
}): Promise<boolean> {
const deadline = Date.now() + (params.timeoutMs ?? 5_000);
while (Date.now() < deadline) {
const payload = await params.executeAutomationCommand({
type: "browser.automation.execute.request",
requestId: `${params.request.requestId}:list_tabs`,
agentId: params.request.agentId,
cwd: params.request.cwd,
workspaceId: params.workspaceId,
command: { command: "list_tabs", args: {} },
});
const payload = await params.executeAutomationCommand(
{
type: "browser.automation.execute.request",
requestId: `${params.request.requestId}:list_tabs`,
agentId: params.request.agentId,
cwd: params.request.cwd,
workspaceId: params.workspaceId,
command: { command: "list_tabs", args: {} },
},
{
serverId: params.serverId,
uploadRoot: null,
},
);
if (payload.ok && payload.result.command === "list_tabs") {
if (payload.result.tabs.some((tab) => tab.browserId === params.browserId)) {
return true;
@@ -774,6 +774,7 @@ function deviceSizeIdForViewport(viewport: BrowserViewport): DeviceSizeId | null
function acquirePartitionedWebview(input: {
browserId: string;
serverId: string;
workspaceId: string;
partition: string;
initialUrl: string;
@@ -791,6 +792,7 @@ function acquirePartitionedWebview(input: {
const webview = document.createElement("webview") as ElectronWebview;
prepareBrowserWebview(webview, {
browserId: input.browserId,
serverId: input.serverId,
workspaceId: input.workspaceId,
initialUrl: input.initialUrl,
partition: input.partition,
@@ -985,6 +987,7 @@ export function BrowserPane({
);
const webview = acquirePartitionedWebview({
browserId,
serverId,
workspaceId,
partition: activePartition,
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : currentUrl,
@@ -173,6 +173,27 @@ describe("classifyHostBrowserRouting", () => {
).toEqual({ kind: "remote", support: "host_connecting" });
});
it.each([
["idle", "host_connecting"],
["connecting", "host_connecting"],
["offline", "host_offline"],
] as const)(
"fails closed when host profile has no saved connections and is %s",
(connectionStatus, expectedSupport) => {
expect(
classifyHostBrowserRouting({
serverId: "unhydrated-host",
connections: [],
activeConnection: null,
activeConnectionId: null,
connectionStatus,
features: null,
origin: null,
}),
).toEqual({ kind: "remote", support: expectedSupport });
},
);
it("routes only loopback URLs on supported remote hosts in Electron to a proxied browser tab", () => {
const supportedRemote = {
kind: "remote" as const,
@@ -216,9 +216,9 @@ export function classifyHostBrowserRouting(
if (originServerId) {
return classifyRoutedHost(host, originServerId, origin);
}
} else if (connections.length === 0 || connections.some(isLocalHostConnection)) {
// No active connection yet (connecting/offline). Distinguish local hosts from remote
// hosts using saved connection definitions so remote tabs fail closed during startup.
} else if (connections.some(isLocalHostConnection)) {
// No active connection yet (connecting/offline). Classify as local only when saved
// connections positively identify a local host; unhydrated or unknown hosts fail closed.
return { kind: "local" };
}
@@ -21,7 +21,9 @@ import {
const RESIDENT_HOST_ID = "paseo-browser-resident-webviews";
const attachedBrowsers: Array<{
browserId: string;
serverId: string;
workspaceId: string;
partition: string;
webContentsId: number;
}> = [];
const profileHost: BrowserWebviewProfileHost = {
@@ -32,11 +34,13 @@ const profileHost: BrowserWebviewProfileHost = {
function ensureTestBrowser(input: {
browserId: string;
serverId?: string;
workspaceId: string;
url: string;
}): HTMLElement | null {
return ensureResidentBrowserWebview({
partition: "persist:paseo-browser",
serverId: "server-a",
...input,
profileHost,
});
@@ -44,9 +48,14 @@ function ensureTestBrowser(input: {
function prepareTestBrowser(
webview: HTMLElement,
input: { browserId: string; workspaceId: string; initialUrl?: string | null },
input: { browserId: string; serverId?: string; workspaceId: string; initialUrl?: string | null },
): void {
prepareBrowserWebview(webview, { partition: "persist:paseo-browser", ...input, profileHost });
prepareBrowserWebview(webview, {
partition: "persist:paseo-browser",
serverId: "server-a",
...input,
profileHost,
});
}
function residentHost(): HTMLElement {
@@ -230,7 +239,13 @@ describe("resident browser webviews", () => {
});
it("reuses a resident browser on the same partition and replaces it when the partition changes", () => {
const input = { browserId: "first", workspaceId: "workspace", url: "about:blank", profileHost };
const input = {
browserId: "first",
serverId: "server-a",
workspaceId: "workspace",
url: "about:blank",
profileHost,
};
const first = ensureTestBrowser(input);
expect(ensureResidentBrowserWebview({ ...input, partition: "persist:paseo-browser" })).toBe(
first,
@@ -275,12 +290,14 @@ describe("resident browser webviews", () => {
expect(attachedBrowsers).toEqual([
{
browserId: "browser-first",
serverId: "server-a",
workspaceId: "workspace-a",
partition: "persist:paseo-browser",
webContentsId: 101,
},
{
browserId: "browser-second",
serverId: "server-a",
workspaceId: "workspace-b",
partition: "persist:paseo-browser",
webContentsId: 202,
@@ -25,6 +25,7 @@ interface BrowserWebviewElement extends HTMLElement {
interface BrowserWebviewIdentity {
partition: string;
browserId: string;
serverId: string;
workspaceId: string;
}
@@ -80,6 +81,7 @@ function registerBrowserWhenAttached(
await browser.registerAttachedBrowser({
partition: identity.partition,
browserId: identity.browserId,
serverId: identity.serverId,
workspaceId: identity.workspaceId,
webContentsId,
});
@@ -327,6 +329,7 @@ export function prepareBrowserWebview(
webview: HTMLElement,
input: {
browserId: string;
serverId: string;
workspaceId: string;
initialUrl?: string | null;
partition?: string;
@@ -348,6 +351,7 @@ export function prepareBrowserWebview(
{
partition: targetPartition,
browserId: input.browserId,
serverId: input.serverId,
workspaceId: input.workspaceId,
},
browser,
@@ -360,6 +364,7 @@ export function getResidentBrowserWebviewPartition(webview: HTMLElement): string
export function ensureResidentBrowserWebview(input: {
browserId: string;
serverId: string;
workspaceId: string;
url: string;
partition?: string;
@@ -400,6 +405,7 @@ export function ensureResidentBrowserWebview(input: {
const webview = ownerDocument.createElement("webview") as BrowserWebviewElement;
prepareBrowserWebview(webview, {
browserId,
serverId: input.serverId,
workspaceId: input.workspaceId,
initialUrl: input.url,
partition: desiredPartition,
+10
View File
@@ -145,10 +145,16 @@ export interface DesktopBrowserNewTabRequestEvent {
export interface DesktopAttachedBrowserRegistration {
partition: string;
browserId: string;
serverId: string;
workspaceId: string;
webContentsId: number;
}
export interface DesktopAutomationExecutionContext {
serverId: string;
uploadRoot: string | null;
}
export type BrowserProfileColor = IdentityColorName;
export interface BrowserProfileEntry {
@@ -206,6 +212,7 @@ export interface DesktopBrowserBridge {
registerAttachedBrowser?: (input: DesktopAttachedBrowserRegistration) => Promise<void>;
unregisterWorkspaceBrowser?: (browserId: string) => Promise<void>;
setWorkspaceActiveBrowser?: (input: {
serverId: string;
workspaceId: string;
browserId: string | null;
}) => Promise<void>;
@@ -232,6 +239,7 @@ export interface DesktopBrowserBridge {
}) => Promise<void>;
executeAutomationCommand?: (
request: BrowserAutomationExecuteRequest,
context: DesktopAutomationExecutionContext,
) => Promise<BrowserAutomationExecuteResponse["payload"]>;
acknowledgeFocusGuard?: (input: { token: string; composing: boolean }) => void;
/** Capture a PNG screenshot of the guest viewport cropped to `rect`. */
@@ -249,6 +257,8 @@ export interface DesktopInvokeBridge {
export interface DesktopHostBridge {
platform?: string;
deviceName?: string;
osVersion?: string;
windowChromeMode?: string;
browserHostLabel?: string;
browserHostInstanceId?: string;
@@ -0,0 +1,249 @@
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
export interface AppClientIdentity {
clientType: "mobile" | "browser";
clientInfo: HelloClientInfo;
}
export interface DesktopIdentityInput {
platform?: string;
deviceName?: string;
osVersion?: string;
browserHostLabel?: string;
}
export interface WebNavigatorUserAgentData {
platform?: string;
brands?: ReadonlyArray<{ brand: string; version?: string }>;
}
export interface WebIdentityInput {
userAgent?: string;
userAgentData?: WebNavigatorUserAgentData;
}
export interface NativePlatformConstantsInput {
Model?: string;
Manufacturer?: string;
Brand?: string;
Release?: string;
systemName?: string;
osVersion?: string;
interfaceIdiom?: string;
}
export interface NativeIdentityInput {
os: string;
version?: string | number;
constants?: NativePlatformConstantsInput;
deviceName?: string | null;
}
const LEGACY_WINDOW_SUFFIX_PATTERN = /\s*·\s*Window\s+\d+(?:\s*\([0-9A-Fa-f]+\))?$/;
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
const normalized = raw?.toLowerCase();
if (normalized === "darwin" || normalized === "macos") return "macos";
if (normalized === "linux") return "linux";
if (normalized === "win32" || normalized === "windows") return "windows";
return "unknown";
}
function osNameForDesktopPlatform(platform: HelloClientPlatform): string | undefined {
if (platform === "macos") return "macOS";
if (platform === "linux") return "Linux";
if (platform === "windows") return "Windows";
return undefined;
}
function normalizeNonEmpty(
value: string | null | undefined,
maxLength: number,
): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed.slice(0, maxLength) : undefined;
}
function cleanDesktopName(desktop: DesktopIdentityInput): string | undefined {
const explicit = normalizeNonEmpty(desktop.deviceName, 128);
if (explicit) return explicit;
// COMPAT(legacyBrowserHostLabel): added in v0.19.x, strip window suffix from older Electron preloads without --paseo-device-name; remove after 2027-06-15.
const stripped = desktop.browserHostLabel?.replace(LEGACY_WINDOW_SUFFIX_PATTERN, "").trim();
return stripped ? stripped.slice(0, 128) : undefined;
}
export function resolveDesktopClientIdentity(desktop: DesktopIdentityInput): AppClientIdentity {
const platform = mapDesktopPlatform(desktop.platform);
const osName = osNameForDesktopPlatform(platform);
const name = cleanDesktopName(desktop);
const osVersion = normalizeNonEmpty(desktop.osVersion, 48);
return {
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform,
...(name ? { name } : {}),
...(osName ? { osName } : {}),
...(osVersion ? { osVersion } : {}),
},
};
}
function parseBrowserNameFromBrands(
brands: ReadonlyArray<{ brand: string; version?: string }> | undefined,
): string | undefined {
if (!brands || brands.length === 0) return undefined;
const names = brands.map((entry) => entry.brand);
if (names.some((brand) => /Microsoft Edge/i.test(brand))) return "Edge";
if (names.some((brand) => /Opera/i.test(brand))) return "Opera";
if (names.some((brand) => /Brave/i.test(brand))) return "Brave";
if (names.some((brand) => /Google Chrome/i.test(brand))) return "Chrome";
if (names.some((brand) => /Chromium/i.test(brand))) return "Chrome";
return undefined;
}
function parseBrowserNameFromUserAgent(userAgent: string | undefined): string | undefined {
if (!userAgent) return undefined;
if (/Edg(?:A|iOS)?\//.test(userAgent)) return "Edge";
if (/OPR\//.test(userAgent)) return "Opera";
if (/(?:Firefox|FxiOS)\//.test(userAgent)) return "Firefox";
if (/(?:Chrome|CriOS)\//.test(userAgent) && !/Edg(?:A|iOS)?\//.test(userAgent)) return "Chrome";
if (/Safari\//.test(userAgent) && !/(?:Chrome|CriOS)\//.test(userAgent)) return "Safari";
return undefined;
}
function parseOsNameFromPlatformHint(platform: string | undefined): string | undefined {
if (!platform) return undefined;
const normalized = platform.trim().toLowerCase();
if (normalized === "macos" || normalized === "mac os" || normalized === "macintel")
return "macOS";
if (normalized === "windows" || normalized === "win32") return "Windows";
if (normalized === "linux") return "Linux";
if (normalized === "android") return "Android";
if (normalized === "ios") return "iOS";
if (normalized === "chrome os" || normalized === "chromeos") return "ChromeOS";
return undefined;
}
function parseOsNameFromUserAgent(userAgent: string | undefined): string | undefined {
if (!userAgent) return undefined;
if (/iPhone|iPad|iPod/.test(userAgent)) return "iOS";
if (/Android/.test(userAgent)) return "Android";
if (/CrOS/.test(userAgent)) return "ChromeOS";
if (/Windows NT|Win64|WOW64/.test(userAgent)) return "Windows";
if (/Macintosh|Mac OS X/.test(userAgent)) return "macOS";
if (/Linux|X11/.test(userAgent)) return "Linux";
return undefined;
}
export function resolveWebClientIdentity(input: WebIdentityInput): AppClientIdentity {
const browserName =
parseBrowserNameFromBrands(input.userAgentData?.brands) ??
parseBrowserNameFromUserAgent(input.userAgent);
const osName =
parseOsNameFromPlatformHint(input.userAgentData?.platform) ??
parseOsNameFromUserAgent(input.userAgent);
const name = browserName && osName ? `${browserName} on ${osName}` : browserName;
return {
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
...(name ? { name: name.slice(0, 128) } : {}),
...(browserName ? { browserName: browserName.slice(0, 48) } : {}),
...(osName ? { osName: osName.slice(0, 48) } : {}),
},
};
}
function cleanAndroidModel(
manufacturer: string | undefined,
model: string | undefined,
): string | undefined {
const cleanModel = model?.trim();
if (!cleanModel) return undefined;
const cleanManufacturer = manufacturer?.trim();
if (
!cleanManufacturer ||
cleanModel.toLowerCase().startsWith(cleanManufacturer.toLowerCase()) ||
cleanModel.toLowerCase().startsWith("pixel")
) {
return cleanModel.slice(0, 96);
}
const formattedManufacturer =
cleanManufacturer === cleanManufacturer.toLowerCase()
? `${cleanManufacturer[0]?.toUpperCase() ?? ""}${cleanManufacturer.slice(1)}`
: cleanManufacturer;
return `${formattedManufacturer} ${cleanModel}`.slice(0, 96);
}
function resolveAndroidClientIdentity(
input: NativeIdentityInput,
explicitName: string | undefined,
): AppClientIdentity {
const constants = input.constants;
const deviceModel = cleanAndroidModel(
constants?.Manufacturer ?? constants?.Brand,
constants?.Model,
);
const rawVersion =
constants?.Release ?? (input.version !== undefined ? String(input.version) : undefined);
const osVersion = normalizeNonEmpty(rawVersion, 48);
const name = explicitName ?? deviceModel;
return {
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "android",
osName: "Android",
...(osVersion ? { osVersion } : {}),
...(deviceModel ? { deviceModel } : {}),
...(name ? { name } : {}),
},
};
}
function resolveIosClientIdentity(
input: NativeIdentityInput,
explicitName: string | undefined,
): AppClientIdentity {
const constants = input.constants;
const isPad = constants?.interfaceIdiom === "pad";
const deviceModel = isPad ? "iPad" : "iPhone";
const osName = normalizeNonEmpty(constants?.systemName, 48) ?? (isPad ? "iPadOS" : "iOS");
const rawVersion =
constants?.osVersion ?? (input.version !== undefined ? String(input.version) : undefined);
const osVersion = normalizeNonEmpty(rawVersion, 48);
const name = explicitName ?? deviceModel;
return {
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "ios",
osName,
...(osVersion ? { osVersion } : {}),
deviceModel,
...(name ? { name } : {}),
},
};
}
export function resolveNativeClientIdentity(input: NativeIdentityInput): AppClientIdentity {
const explicitName = normalizeNonEmpty(input.deviceName, 128);
if (input.os === "android") {
return resolveAndroidClientIdentity(input, explicitName);
}
if (input.os === "ios") {
return resolveIosClientIdentity(input, explicitName);
}
return {
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "unknown",
...(explicitName ? { name: explicitName } : {}),
},
};
}
+12 -19
View File
@@ -1,23 +1,16 @@
import Constants from "expo-constants";
import { Platform } from "react-native";
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
import {
resolveNativeClientIdentity,
type AppClientIdentity,
type NativePlatformConstantsInput,
} from "./client-info-parsers";
function mapNativePlatform(os: string): HelloClientPlatform {
if (os === "ios") return "ios";
if (os === "android") return "android";
return "unknown";
}
export function resolveAppClientIdentity(): {
clientType: "mobile" | "browser";
clientInfo: HelloClientInfo;
} {
const deviceName = Constants.deviceName?.trim();
return {
clientType: "mobile",
clientInfo: {
platform: mapNativePlatform(Platform.OS),
...(deviceName ? { name: deviceName.slice(0, 128) } : {}),
},
};
export function resolveAppClientIdentity(): AppClientIdentity {
return resolveNativeClientIdentity({
os: Platform.OS,
version: Platform.Version,
constants: Platform.constants as NativePlatformConstantsInput | undefined,
deviceName: Constants.deviceName,
});
}
@@ -0,0 +1,252 @@
import { describe, expect, it } from "vitest";
import { resolveAppClientIdentity } from "./client-info";
import { resolveNativeClientIdentity } from "./client-info-parsers";
describe("resolveAppClientIdentity (Electron and Web)", () => {
it("identifies Electron Desktop on macOS, Linux, and Windows with clean deviceName and osVersion", () => {
expect(
resolveAppClientIdentity({
desktop: {
platform: "darwin",
deviceName: "MacBook Pro",
osVersion: "15.3.1",
browserHostLabel: "MacBook Pro · Window 1 (ABCDEF)",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "macos",
name: "MacBook Pro",
osName: "macOS",
osVersion: "15.3.1",
},
});
expect(
resolveAppClientIdentity({
desktop: {
platform: "linux",
deviceName: "workstation",
osVersion: "Ubuntu 24.04.1 LTS",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "linux",
name: "workstation",
osName: "Linux",
osVersion: "Ubuntu 24.04.1 LTS",
},
});
expect(
resolveAppClientIdentity({
desktop: {
platform: "win32",
deviceName: "DEV-PC",
osVersion: "10.0.22631",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "windows",
name: "DEV-PC",
osName: "Windows",
osVersion: "10.0.22631",
},
});
});
it("strips legacy Window N (HEX) suffix if older Electron preload only provides browserHostLabel", () => {
expect(
resolveAppClientIdentity({
desktop: {
platform: "linux",
browserHostLabel: "devbox · Window 2 (9F0A1B)",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "linux",
name: "devbox",
osName: "Linux",
},
});
});
it("identifies web browsers and operating systems from userAgent and userAgentData", () => {
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Chrome",
osName: "macOS",
name: "Chrome on macOS",
},
});
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Firefox",
osName: "Windows",
name: "Firefox on Windows",
},
});
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15",
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Safari",
osName: "macOS",
name: "Safari on macOS",
},
});
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
userAgentData: {
platform: "Linux",
brands: [{ brand: "Microsoft Edge", version: "131" }],
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Edge",
osName: "Linux",
name: "Edge on Linux",
},
});
});
});
describe("resolveNativeClientIdentity (Android and iOS)", () => {
it("extracts Android model, manufacturer, and release from RN Platform.constants", () => {
expect(
resolveNativeClientIdentity({
os: "android",
constants: {
Manufacturer: "Google",
Model: "Pixel 9 Pro",
Release: "15",
},
deviceName: undefined,
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "android",
osName: "Android",
osVersion: "15",
deviceModel: "Pixel 9 Pro",
name: "Pixel 9 Pro",
},
});
expect(
resolveNativeClientIdentity({
os: "android",
constants: {
Manufacturer: "samsung",
Model: "SM-S928B",
Release: "14",
},
deviceName: "Mo's Galaxy",
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "android",
osName: "Android",
osVersion: "14",
deviceModel: "Samsung SM-S928B",
name: "Mo's Galaxy",
},
});
});
it("extracts iOS and iPadOS metadata from RN Platform.constants", () => {
expect(
resolveNativeClientIdentity({
os: "ios",
constants: {
systemName: "iOS",
osVersion: "18.3",
interfaceIdiom: "phone",
},
deviceName: "iPhone",
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "ios",
osName: "iOS",
osVersion: "18.3",
deviceModel: "iPhone",
name: "iPhone",
},
});
expect(
resolveNativeClientIdentity({
os: "ios",
constants: {
systemName: "iPadOS",
osVersion: "18.3",
interfaceIdiom: "pad",
},
deviceName: undefined,
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "ios",
osName: "iPadOS",
osVersion: "18.3",
deviceModel: "iPad",
name: "iPad",
},
});
});
});
+38 -37
View File
@@ -1,47 +1,48 @@
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
import { getIsElectron } from "@/constants/platform";
import { getDesktopHost } from "@/desktop/host";
import {
resolveDesktopClientIdentity,
resolveWebClientIdentity,
type AppClientIdentity,
type DesktopIdentityInput,
type WebNavigatorUserAgentData,
} from "./client-info-parsers";
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
const normalized = raw?.toLowerCase();
if (normalized === "darwin" || normalized === "macos") return "macos";
if (normalized === "linux") return "linux";
if (normalized === "win32" || normalized === "windows") return "windows";
return "unknown";
interface WebRuntimeEnv {
desktop?: DesktopIdentityInput | null;
userAgent?: string;
userAgentData?: WebNavigatorUserAgentData;
}
function parseBrowserName(userAgent: string | undefined): string | undefined {
if (!userAgent) return undefined;
if (/Edg\//.test(userAgent)) return "Edge";
if (/Firefox\//.test(userAgent)) return "Firefox";
if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome";
if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari";
return undefined;
function readNavigatorUserAgentData(): WebNavigatorUserAgentData | undefined {
if (typeof navigator === "undefined") return undefined;
const candidate = (navigator as Navigator & { userAgentData?: WebNavigatorUserAgentData })
.userAgentData;
return candidate && typeof candidate === "object" ? candidate : undefined;
}
export function resolveAppClientIdentity(): {
clientType: "mobile" | "browser";
clientInfo: HelloClientInfo;
} {
if (getIsElectron()) {
const desktop = getDesktopHost();
const label = desktop?.browserHostLabel?.trim();
return {
clientType: "mobile",
clientInfo: {
platform: mapDesktopPlatform(desktop?.platform),
...(label ? { name: label.slice(0, 128) } : {}),
},
};
function resolveDesktopInput(env?: WebRuntimeEnv): DesktopIdentityInput | null {
if (env && "desktop" in env) {
return env.desktop ?? null;
}
return getIsElectron() ? getDesktopHost() : null;
}
function resolveUserAgentInput(env?: WebRuntimeEnv): string | undefined {
if (env && "userAgent" in env) {
return env.userAgent;
}
return typeof navigator !== "undefined" ? navigator.userAgent : undefined;
}
export function resolveAppClientIdentity(env?: WebRuntimeEnv): AppClientIdentity {
const desktop = resolveDesktopInput(env);
if (desktop) {
return resolveDesktopClientIdentity(desktop);
}
const browserName =
typeof navigator !== "undefined" ? parseBrowserName(navigator.userAgent) : undefined;
return {
clientType: "browser",
clientInfo: {
platform: "web",
...(browserName ? { name: browserName } : {}),
},
};
return resolveWebClientIdentity({
userAgent: resolveUserAgentInput(env),
userAgentData: env && "userAgentData" in env ? env.userAgentData : readNavigatorUserAgentData(),
});
}
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
@@ -6,23 +6,32 @@ import type { TFunction } from "i18next";
import type {
DaemonClientsSnapshot,
DaemonSessionSummary,
DaemonSessionTransport,
WSClientType,
} from "@getpaseo/protocol/daemon-clients";
import type { DaemonPermission } from "@getpaseo/protocol/messages";
import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
import {
SettingsCard,
SettingsCollapsibleRow,
SettingsDetailRow,
SettingsRow,
SettingsSection,
} from "@/components/settings";
import { StatusBadge } from "@/components/ui/status-badge";
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
import {
formatAppDetail,
formatAuthMethodLabel,
formatDeviceDetail,
formatSessionHint,
formatSessionTitle,
formatTransportLabel,
} from "./device-display";
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
import { DaemonPasswordSheet } from "./daemon-password-sheet";
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
const RELATIVE_TIME_REFRESH_MS = 60_000;
type StatusDotTone = "online" | "warning" | "error" | "offline";
@@ -49,6 +58,17 @@ const STATUS_DOTS: Record<StatusDotTone, React.ReactNode> = {
offline: <StatusDot tone="offline" />,
};
function useMinuteTick(): number {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => {
setNowMs(Date.now());
}, RELATIVE_TIME_REFRESH_MS);
return () => clearInterval(timer);
}, []);
return nowMs;
}
function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[]; t: TFunction }) {
const summary = summarizePermissions(permissions);
let label: string;
@@ -64,15 +84,23 @@ function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[
return <StatusBadge label={label} variant="muted" size="xs" />;
}
function PermissionPillsRow({
function AccessDetailRow({
permissions,
t,
}: {
permissions: readonly DaemonPermission[];
t: TFunction;
}) {
const summary = summarizePermissions(permissions);
if (summary.kind === "full") {
return (
<SettingsRow label={t("devices.details.access")}>
<Text style={styles.nestedValue}>{t("devices.scopes.fullAccess")}</Text>
</SettingsRow>
);
}
return (
<SettingsRow label={t("devices.details.permissions")}>
<SettingsRow label={t("devices.details.access")}>
<View style={styles.scopePills}>
{permissions.length > 0 ? (
permissions.map((permission) => (
@@ -86,9 +114,13 @@ function PermissionPillsRow({
);
}
function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFunction): string | null {
function formatDurationLabel(
isoTimestamp: string | null | undefined,
nowMs: number,
t: TFunction,
): string | null {
if (!isoTimestamp) return null;
const duration = formatConnectedDuration(isoTimestamp);
const duration = formatConnectedDuration(isoTimestamp, nowMs);
if (!duration) return null;
if (duration.kind === "just_now") return t("devices.time.justNow");
if (duration.kind === "minutes") return t("devices.time.minutesAgo", { count: duration.count });
@@ -96,77 +128,26 @@ function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFuncti
return t("devices.time.daysAgo", { count: duration.count });
}
function formatTransportLabel(
transport: DaemonSessionTransport,
viaHostName: string | null,
t: TFunction,
): string {
switch (transport) {
case "local_ipc":
case "local":
return t("devices.transport.local");
case "tailscale":
return t("devices.transport.tailscale");
case "relay":
return t("devices.transport.relay");
case "hub":
return t("devices.transport.hub");
case "via":
return viaHostName
? t("devices.transport.via", { host: viaHostName })
: t("devices.transport.viaHost");
case "direct":
return t("devices.transport.direct");
}
}
function formatClientPlatformLabel(
clientType: WSClientType,
platform: string | null,
t: TFunction,
): string {
if (platform === "ios") return "iOS";
if (platform === "android") return "Android";
if (platform === "macos" || platform === "linux" || platform === "windows") {
return t("devices.kind.desktop");
}
if (clientType === "browser" || platform === "web") return t("devices.kind.web");
if (clientType === "mobile") return t("devices.kind.mobile");
if (clientType === "hub") return t("devices.kind.hub");
if (clientType === "cli") return "CLI";
return "MCP";
}
function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
if (session.isCurrentSession) return t("devices.connected.thisDevice");
if (session.name) return session.name;
return formatClientPlatformLabel(session.clientType, session.platform, t);
}
function formatSessionHint(
session: DaemonSessionSummary,
viaHostName: string | null,
t: TFunction,
): string {
const transport = formatTransportLabel(session.transport, viaHostName, t);
const platform = formatClientPlatformLabel(session.clientType, session.platform, t);
const detail = session.appVersion ? `${platform} ${session.appVersion}` : platform;
return detail === transport ? transport : `${transport} · ${detail}`;
}
function ConnectedClientRow({
session,
viaHostName,
nowMs,
}: {
session: DaemonSessionSummary;
viaHostName: string | null;
nowMs: number;
}) {
const { t } = useTranslation();
const tone: StatusDotTone = session.socketCount > 0 ? "online" : "warning";
const connectedLabel = formatDurationLabel(session.connectedAt, t);
const isReconnecting = session.socketCount === 0;
const tone: StatusDotTone = isReconnecting ? "warning" : "online";
const deviceDetail = formatDeviceDetail(session);
const appDetail = formatAppDetail(session, t);
const connectionLabel = formatTransportLabel(session.transport, viaHostName, t);
const authLabel = formatAuthMethodLabel(session.authMethod, t);
const connectedLabel = formatDurationLabel(session.connectedAt, nowMs, t);
const trailing = useMemo(
() => <ScopePill permissions={session.permissions} t={t} />,
[session.permissions, t],
() => (isReconnecting ? undefined : <ScopePill permissions={session.permissions} t={t} />),
[isReconnecting, session.permissions, t],
);
return (
@@ -174,20 +155,37 @@ function ConnectedClientRow({
label={formatSessionTitle(session, t)}
leading={STATUS_DOTS[tone]}
hint={formatSessionHint(session, viaHostName, t)}
summary={isReconnecting ? t("devices.status.reconnecting") : undefined}
trailing={trailing}
testID={`devices-client-${session.sessionId}`}
>
<PermissionPillsRow permissions={session.permissions} t={t} />
{deviceDetail ? (
<SettingsRow label={t("devices.details.device")}>
<Text style={styles.nestedValue}>{deviceDetail}</Text>
</SettingsRow>
) : null}
<SettingsRow label={t("devices.details.app")}>
<Text style={styles.nestedValue}>{appDetail}</Text>
</SettingsRow>
<SettingsRow label={t("devices.details.connection")}>
<Text style={styles.nestedValue}>{connectionLabel}</Text>
</SettingsRow>
{session.remoteIp ? (
<SettingsRow label={t("devices.details.ipAddress")}>
<Text style={styles.nestedMonoValue}>{session.remoteIp}</Text>
</SettingsRow>
) : null}
{authLabel ? (
<SettingsRow label={t("devices.details.auth")}>
<Text style={styles.nestedValue}>{authLabel}</Text>
</SettingsRow>
) : null}
<AccessDetailRow permissions={session.permissions} t={t} />
{connectedLabel ? (
<SettingsRow label={t("devices.details.connected")}>
<Text style={styles.nestedValue}>{connectedLabel}</Text>
</SettingsRow>
) : null}
{session.socketCount === 0 ? (
<SettingsRow label={t("devices.details.status")}>
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
</SettingsRow>
) : null}
</SettingsCollapsibleRow>
);
}
@@ -195,22 +193,25 @@ function ConnectedClientRow({
function InboundDaemonRow({
daemon,
routedSessions,
nowMs,
}: {
daemon: DaemonSessionSummary;
routedSessions: readonly DaemonSessionSummary[];
nowMs: number;
}) {
const { t } = useTranslation();
const tone: StatusDotTone = daemon.socketCount > 0 ? "online" : "warning";
const isReconnecting = daemon.socketCount === 0;
const tone: StatusDotTone = isReconnecting ? "warning" : "online";
const label = daemon.name ?? t("devices.hosts.unnamed");
const transport = formatTransportLabel(daemon.transport, null, t);
const hintParts = [t("devices.hosts.inbound"), transport];
if (routedSessions.length > 0) {
hintParts.push(t("devices.hosts.routedCount", { count: routedSessions.length }));
}
const connectedLabel = formatDurationLabel(daemon.connectedAt, t);
const connectedLabel = formatDurationLabel(daemon.connectedAt, nowMs, t);
const trailing = useMemo(
() => <ScopePill permissions={daemon.permissions} t={t} />,
[daemon.permissions, t],
() => (isReconnecting ? undefined : <ScopePill permissions={daemon.permissions} t={t} />),
[daemon.permissions, isReconnecting, t],
);
return (
@@ -218,10 +219,11 @@ function InboundDaemonRow({
label={label}
leading={STATUS_DOTS[tone]}
hint={hintParts.join(" · ")}
summary={isReconnecting ? t("devices.status.reconnecting") : undefined}
trailing={trailing}
testID={`devices-inbound-host-${daemon.sessionId}`}
>
<PermissionPillsRow permissions={daemon.permissions} t={t} />
<AccessDetailRow permissions={daemon.permissions} t={t} />
{routedSessions.map((routed) => (
<SettingsRow
key={routed.sessionId}
@@ -231,6 +233,11 @@ function InboundDaemonRow({
<ScopePill permissions={routed.permissions} t={t} />
</SettingsRow>
))}
{daemon.remoteIp ? (
<SettingsRow label={t("devices.details.ipAddress")}>
<Text style={styles.nestedMonoValue}>{daemon.remoteIp}</Text>
</SettingsRow>
) : null}
{daemon.appVersion ? (
<SettingsRow label={t("devices.details.version")}>
<Text style={styles.nestedValue}>{daemon.appVersion}</Text>
@@ -241,11 +248,6 @@ function InboundDaemonRow({
<Text style={styles.nestedValue}>{connectedLabel}</Text>
</SettingsRow>
) : null}
{daemon.socketCount === 0 ? (
<SettingsRow label={t("devices.details.status")}>
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
</SettingsRow>
) : null}
</SettingsCollapsibleRow>
);
}
@@ -279,13 +281,13 @@ function outboundHostStatusLabel(status: HostSummary["status"], t: TFunction): s
}
}
function OutboundHostRow({ host }: { host: HostSummary }) {
function OutboundHostRow({ host, nowMs }: { host: HostSummary; nowMs: number }) {
const { t } = useTranslation();
const tone = outboundHostTone(host.status);
const label = host.label ?? host.serverId ?? host.targetDescription;
const hintParts = [t("devices.hosts.outbound"), host.targetDescription];
const statusSummary = outboundHostStatusLabel(host.status, t);
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, t);
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, nowMs, t);
const trailing = useMemo(
() =>
host.status === "online" && host.permissions ? (
@@ -304,7 +306,7 @@ function OutboundHostRow({ host }: { host: HostSummary }) {
trailing={trailing}
testID={`devices-outbound-host-${host.registrationId}`}
>
{host.permissions ? <PermissionPillsRow permissions={host.permissions} t={t} /> : null}
{host.permissions ? <AccessDetailRow permissions={host.permissions} t={t} /> : null}
{host.error ? (
<SettingsRow label={t("devices.details.error")}>
<Text style={styles.nestedError}>{host.error.message}</Text>
@@ -426,6 +428,7 @@ function ConnectedClientsCardBody({
clientsState,
connectedClients,
hostNameBySessionId,
nowMs,
}: {
isOnline: boolean;
hasServerInfo: boolean;
@@ -434,6 +437,7 @@ function ConnectedClientsCardBody({
clientsState: ConnectedClientsLoadState;
connectedClients: readonly DaemonSessionSummary[];
hostNameBySessionId: ReadonlyMap<string, string | null>;
nowMs: number;
}) {
const { t } = useTranslation();
const updateLink = useMemo(
@@ -484,14 +488,84 @@ function ConnectedClientsCardBody({
viaHostName={
entry.viaSessionId ? (hostNameBySessionId.get(entry.viaSessionId) ?? null) : null
}
nowMs={nowMs}
/>
))}
</>
);
}
function DevicesAccessSection({
serverId,
isOnline,
serverInfo,
}: {
serverId: string;
isOnline: boolean;
serverInfo: DaemonServerInfo | null;
}) {
const { t } = useTranslation();
const [passwordSheetMode, setPasswordSheetMode] = useState<"set" | "change" | null>(null);
const passwordConfigured = serverInfo?.passwordConfigured === true;
const passwordManagedByEnv = serverInfo?.passwordManagedByEnv === true;
const handleOpenPasswordSheet = useCallback(() => {
setPasswordSheetMode(passwordConfigured ? "change" : "set");
}, [passwordConfigured]);
const handleClosePasswordSheet = useCallback(() => {
setPasswordSheetMode(null);
}, []);
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
const supportsPasswordManagement = serverInfo?.features?.daemonPasswordManagement === true;
const canManagePassword =
!serverInfo?.permissions ||
(serverInfo.permissions.includes("daemon.manage") &&
serverInfo.permissions.includes("access.manage"));
if (!isOnline || !supportsPasswordManagement || !canManagePassword) {
return null;
}
let passwordSummary: string;
let passwordHint: string;
if (passwordManagedByEnv) {
passwordSummary = t("devices.access.passwordEnvSummary");
passwordHint = t("devices.access.passwordEnvHint");
} else if (passwordConfigured) {
passwordSummary = t("devices.access.passwordSetSummary");
passwordHint = t("devices.access.passwordSetHint");
} else {
passwordSummary = t("devices.access.passwordNotSetSummary");
passwordHint = t("devices.access.passwordNotSetHint");
}
return (
<>
<SettingsSection title={t("devices.access.title")}>
<SettingsCard testID="devices-access-card">
<SettingsDetailRow
label={t("devices.access.passwordLabel")}
summary={passwordSummary}
hint={passwordHint}
disabled={passwordManagedByEnv}
onPress={handleOpenPasswordSheet}
testID="devices-password-row"
/>
</SettingsCard>
</SettingsSection>
<DaemonPasswordSheet
serverId={serverId}
visible={passwordSheetMode !== null}
initialMode={passwordSheetMode ?? "set"}
onClose={handleClosePasswordSheet}
/>
</>
);
}
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const nowMs = useMinuteTick();
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
@@ -538,6 +612,8 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
return (
<View>
<DevicesAccessSection serverId={serverId} isOnline={isOnline} serverInfo={serverInfo} />
<SettingsSection title={t("devices.connected.title")}>
<SettingsCard testID="devices-connected-clients-card">
<ConnectedClientsCardBody
@@ -548,6 +624,7 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
clientsState={clientsState}
connectedClients={connectedClients}
hostNameBySessionId={hostNameBySessionId}
nowMs={nowMs}
/>
</SettingsCard>
</SettingsSection>
@@ -560,10 +637,11 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
key={daemon.sessionId}
daemon={daemon}
routedSessions={routedByHostSessionId.get(daemon.sessionId) ?? EMPTY_SESSIONS}
nowMs={nowMs}
/>
))}
{outboundHosts.map((host) => (
<OutboundHostRow key={host.registrationId} host={host} />
<OutboundHostRow key={host.registrationId} host={host} nowMs={nowMs} />
))}
</SettingsCard>
</SettingsSection>
@@ -605,6 +683,11 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
nestedMonoValue: {
fontSize: theme.fontSize.sm,
fontFamily: theme.fontFamily.mono,
color: theme.colors.foregroundMuted,
},
nestedError: {
fontSize: theme.fontSize.sm,
color: theme.colors.statusDanger,
@@ -0,0 +1,181 @@
import { describe, expect, test } from "vitest";
import {
DAEMON_PASSWORD_MAX_BYTES,
DAEMON_PASSWORD_MIN_CHARS,
openDaemonPasswordForm,
shouldSyncHostProfilePassword,
} from "./daemon-password-form-model";
describe("daemon password form model", () => {
test("set mode validates min 8 chars, max 72 UTF-8 bytes, and confirmation match", () => {
const form = openDaemonPasswordForm({
mode: "set",
isLocalCredential: false,
});
expect(form.getState()).toMatchObject({
step: "set",
isLocalCredential: false,
submitting: false,
});
// 7 chars fails min length.
form.setNewPassword("1234567");
form.setConfirmPassword("1234567");
expect(form.beginSubmit()).toEqual({ valid: false });
expect(form.getState().fieldErrors.newPassword).toBe("too_short");
// 8 chars with mismatch fails confirm.
form.setNewPassword("12345678");
form.setConfirmPassword("87654321");
expect(form.beginSubmit()).toEqual({ valid: false });
expect(form.getState().fieldErrors.newPassword).toBeNull();
expect(form.getState().fieldErrors.confirmPassword).toBe("mismatch");
// 73 UTF-8 bytes fails (including multibyte UTF-8 under 72 chars).
const over72Bytes = "🔐".repeat(19); // 76 UTF-8 bytes
expect(over72Bytes.length).toBeLessThan(DAEMON_PASSWORD_MAX_BYTES);
form.setNewPassword(over72Bytes);
form.setConfirmPassword(over72Bytes);
expect(form.beginSubmit()).toEqual({ valid: false });
expect(form.getState().fieldErrors.newPassword).toBe("too_long");
// Exact 72 UTF-8 bytes succeeds.
const exact72 = "a".repeat(DAEMON_PASSWORD_MAX_BYTES);
form.setNewPassword(exact72);
form.setConfirmPassword(exact72);
expect(form.beginSubmit()).toEqual({
valid: true,
payload: { password: exact72 },
});
expect(form.getState().submitting).toBe(true);
form.finishSubmitSuccess();
expect(form.getState().submitting).toBe(false);
// Exact 8 chars succeeds.
const exact8 = "a".repeat(DAEMON_PASSWORD_MIN_CHARS);
form.setNewPassword(exact8);
form.setConfirmPassword(exact8);
expect(form.beginSubmit()).toEqual({
valid: true,
payload: { password: exact8 },
});
});
test("change mode requires current password on remote sessions and maps server incorrect_password to field error", () => {
const form = openDaemonPasswordForm({
mode: "change",
isLocalCredential: false,
});
form.setNewPassword("new-secret-123");
form.setConfirmPassword("new-secret-123");
expect(form.beginSubmit()).toEqual({ valid: false });
expect(form.getState().fieldErrors.currentPassword).toBe("current_password_required");
form.setCurrentPassword("wrong-current");
expect(form.beginSubmit()).toEqual({
valid: true,
payload: { password: "new-secret-123", currentPassword: "wrong-current" },
});
form.finishSubmitError({
code: "incorrect_password",
message: "Current password is incorrect",
});
expect(form.getState().submitting).toBe(false);
expect(form.getState().fieldErrors.currentPassword).toBe("incorrect_password");
expect(form.getState().submitError).toBeNull();
// Preserves inputs so the user does not retype.
expect(form.getState().newPassword).toBe("new-secret-123");
expect(form.getState().confirmPassword).toBe("new-secret-123");
// Network/generic error goes to submitError.
form.finishSubmitError({ message: "Network timeout" });
expect(form.getState().submitError).toBe("Network timeout");
});
test("change mode omits currentPassword on local-credential sessions", () => {
const form = openDaemonPasswordForm({
mode: "change",
isLocalCredential: true,
});
form.setNewPassword("recovered-secret");
form.setConfirmPassword("recovered-secret");
expect(form.beginSubmit()).toEqual({
valid: true,
payload: { password: "recovered-secret" },
});
});
test("remote remove step seeds currentPassword from change step and submits password=null", () => {
const form = openDaemonPasswordForm({
mode: "change",
isLocalCredential: false,
});
form.setCurrentPassword("my-current-pw");
form.enterRemoveStep();
expect(form.getState().step).toBe("remove");
expect(form.getState().currentPassword).toBe("my-current-pw");
expect(form.beginSubmit()).toEqual({
valid: true,
payload: { password: null, currentPassword: "my-current-pw" },
});
form.finishSubmitError({
code: "incorrect_password",
message: "Current password is incorrect",
});
expect(form.getState().fieldErrors.currentPassword).toBe("incorrect_password");
form.backToChangeStep();
expect(form.getState().step).toBe("change");
});
test("shouldSyncHostProfilePassword skips persisting password on local-only profiles when using localCredentialAuth", () => {
expect(
shouldSyncHostProfilePassword({
localCredentialAuth: true,
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
}),
).toBe(false);
expect(
shouldSyncHostProfilePassword({
localCredentialAuth: true,
connections: [
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
],
}),
).toBe(false);
// Local desktop profile that also has a relay or remote route DOES sync so remote routes stay usable.
expect(
shouldSyncHostProfilePassword({
localCredentialAuth: true,
connections: [
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
{
id: "relay:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
daemonPublicKeyB64: "pk",
},
],
}),
).toBe(true);
// Non-local browser session always syncs even on localhost so reload stays authenticated.
expect(
shouldSyncHostProfilePassword({
localCredentialAuth: false,
connections: [
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
],
}),
).toBe(true);
});
});
@@ -0,0 +1,269 @@
import { isLoopbackEndpoint } from "@/hosts/connection-display";
import type { HostConnection } from "@/types/host-connection";
export const DAEMON_PASSWORD_MIN_CHARS = 8;
export const DAEMON_PASSWORD_MAX_BYTES = 72;
export type DaemonPasswordFormStep = "set" | "change" | "remove";
export type DaemonPasswordFieldErrorCode =
| "current_password_required"
| "incorrect_password"
| "too_short"
| "too_long"
| "mismatch"
| "invalid_password";
export interface DaemonPasswordFormFieldErrors {
currentPassword: DaemonPasswordFieldErrorCode | null;
newPassword: DaemonPasswordFieldErrorCode | null;
confirmPassword: DaemonPasswordFieldErrorCode | null;
}
export interface DaemonPasswordFormState {
step: DaemonPasswordFormStep;
isLocalCredential: boolean;
currentPassword: string;
newPassword: string;
confirmPassword: string;
showCurrentPassword: boolean;
showNewPassword: boolean;
showConfirmPassword: boolean;
submitting: boolean;
fieldErrors: DaemonPasswordFormFieldErrors;
submitError: string | null;
}
export interface DaemonPasswordFormSnapshot {
mode: "set" | "change";
isLocalCredential: boolean;
}
export type DaemonPasswordSubmitResult =
| { valid: false }
| { valid: true; payload: { password: string | null; currentPassword?: string } };
export interface DaemonPasswordFormModel {
getState(): DaemonPasswordFormState;
subscribe(listener: () => void): () => void;
setCurrentPassword(value: string): void;
setNewPassword(value: string): void;
setConfirmPassword(value: string): void;
toggleShowCurrentPassword(): void;
toggleShowNewPassword(): void;
toggleShowConfirmPassword(): void;
enterRemoveStep(): void;
backToChangeStep(): void;
beginSubmit(): DaemonPasswordSubmitResult;
finishSubmitSuccess(): void;
finishSubmitError(error: { code?: string; message: string }): void;
}
const textEncoder = new TextEncoder();
export function utf8ByteLength(value: string): number {
return textEncoder.encode(value).byteLength;
}
export function isLocalOnlyHostConnection(connection: HostConnection): boolean {
if (connection.type === "directSocket" || connection.type === "directPipe") {
return true;
}
if (connection.type === "directTcp") {
return isLoopbackEndpoint(connection.endpoint);
}
return false;
}
export function shouldSyncHostProfilePassword(input: {
localCredentialAuth: boolean;
connections: readonly HostConnection[];
}): boolean {
if (!input.localCredentialAuth) {
return true;
}
return input.connections.some((connection) => !isLocalOnlyHostConnection(connection));
}
const EMPTY_FIELD_ERRORS: DaemonPasswordFormFieldErrors = {
currentPassword: null,
newPassword: null,
confirmPassword: null,
};
export function openDaemonPasswordForm(
snapshot: DaemonPasswordFormSnapshot,
): DaemonPasswordFormModel {
const listeners = new Set<() => void>();
let state: DaemonPasswordFormState = {
step: snapshot.mode,
isLocalCredential: snapshot.isLocalCredential,
currentPassword: "",
newPassword: "",
confirmPassword: "",
showCurrentPassword: false,
showNewPassword: false,
showConfirmPassword: false,
submitting: false,
fieldErrors: { ...EMPTY_FIELD_ERRORS },
submitError: null,
};
const publish = (next: DaemonPasswordFormState) => {
state = next;
for (const listener of listeners) {
listener();
}
};
return {
getState: () => state,
subscribe(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
setCurrentPassword(value) {
publish({
...state,
currentPassword: value,
fieldErrors: { ...state.fieldErrors, currentPassword: null },
submitError: null,
});
},
setNewPassword(value) {
publish({
...state,
newPassword: value,
fieldErrors: { ...state.fieldErrors, newPassword: null, confirmPassword: null },
submitError: null,
});
},
setConfirmPassword(value) {
publish({
...state,
confirmPassword: value,
fieldErrors: { ...state.fieldErrors, confirmPassword: null },
submitError: null,
});
},
toggleShowCurrentPassword() {
publish({ ...state, showCurrentPassword: !state.showCurrentPassword });
},
toggleShowNewPassword() {
publish({ ...state, showNewPassword: !state.showNewPassword });
},
toggleShowConfirmPassword() {
publish({ ...state, showConfirmPassword: !state.showConfirmPassword });
},
enterRemoveStep() {
if (state.step !== "change" || state.submitting) return;
publish({
...state,
step: "remove",
fieldErrors: { ...EMPTY_FIELD_ERRORS },
submitError: null,
});
},
backToChangeStep() {
if (state.step !== "remove" || state.submitting) return;
publish({
...state,
step: "change",
fieldErrors: { ...EMPTY_FIELD_ERRORS },
submitError: null,
});
},
beginSubmit() {
if (state.submitting) {
return { valid: false };
}
const fieldErrors: DaemonPasswordFormFieldErrors = { ...EMPTY_FIELD_ERRORS };
const needsCurrentPassword =
(state.step === "change" || state.step === "remove") && !state.isLocalCredential;
if (needsCurrentPassword && state.currentPassword.length === 0) {
fieldErrors.currentPassword = "current_password_required";
}
if (state.step !== "remove") {
if (state.newPassword.length < DAEMON_PASSWORD_MIN_CHARS) {
fieldErrors.newPassword = "too_short";
} else if (utf8ByteLength(state.newPassword) > DAEMON_PASSWORD_MAX_BYTES) {
fieldErrors.newPassword = "too_long";
} else if (state.confirmPassword !== state.newPassword) {
fieldErrors.confirmPassword = "mismatch";
}
}
if (
fieldErrors.currentPassword !== null ||
fieldErrors.newPassword !== null ||
fieldErrors.confirmPassword !== null
) {
publish({
...state,
fieldErrors,
submitError: null,
});
return { valid: false };
}
publish({
...state,
submitting: true,
fieldErrors: { ...EMPTY_FIELD_ERRORS },
submitError: null,
});
return {
valid: true,
payload: {
password: state.step === "remove" ? null : state.newPassword,
...(needsCurrentPassword ? { currentPassword: state.currentPassword } : {}),
},
};
},
finishSubmitSuccess() {
publish({
...state,
submitting: false,
fieldErrors: { ...EMPTY_FIELD_ERRORS },
submitError: null,
});
},
finishSubmitError(error) {
const fieldErrors: DaemonPasswordFormFieldErrors = { ...EMPTY_FIELD_ERRORS };
let submitError: string | null = null;
if (error.code === "incorrect_password") {
fieldErrors.currentPassword = "incorrect_password";
} else if (error.code === "current_password_required") {
fieldErrors.currentPassword = "current_password_required";
} else if (error.code === "invalid_password") {
fieldErrors.newPassword = "invalid_password";
} else {
submitError = error.message;
}
publish({
...state,
submitting: false,
fieldErrors,
submitError,
});
},
};
}
@@ -0,0 +1,532 @@
import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
import { View } from "react-native";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { Eye, EyeOff } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
import { DaemonRpcError } from "@getpaseo/client";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Field, FormTextInput } from "@/components/ui/form-field";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-context";
import { useHostMutations, useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { confirmDialog } from "@/utils/confirm-dialog";
import {
openDaemonPasswordForm,
shouldSyncHostProfilePassword,
type DaemonPasswordFieldErrorCode,
type DaemonPasswordFormModel,
} from "./daemon-password-form-model";
const FLEX_ONE_STYLE = { flex: 1 } as const;
const SNAP_POINTS: string[] = ["72%", "92%"];
function translateFieldError(
code: DaemonPasswordFieldErrorCode | null,
t: TFunction,
): string | null {
switch (code) {
case "current_password_required":
return t("devices.password.errors.currentRequired");
case "incorrect_password":
return t("devices.password.errors.currentIncorrect");
case "too_short":
return t("devices.password.errors.tooShort");
case "too_long":
case "invalid_password":
return t("devices.password.errors.tooLong");
case "mismatch":
return t("devices.password.errors.mismatch");
default:
return null;
}
}
function formatSuccessToast(
action: "set" | "change" | "remove",
disconnectedSessionCount: number,
t: TFunction,
): string {
if (action === "remove") {
return t("devices.password.toast.removed");
}
if (action === "set") {
if (disconnectedSessionCount === 1) {
return t("devices.password.toast.setDisconnectedOne");
}
if (disconnectedSessionCount > 1) {
return t("devices.password.toast.setDisconnectedOther", { count: disconnectedSessionCount });
}
return t("devices.password.toast.set");
}
if (disconnectedSessionCount === 1) {
return t("devices.password.toast.updatedDisconnectedOne");
}
if (disconnectedSessionCount > 1) {
return t("devices.password.toast.updatedDisconnectedOther", {
count: disconnectedSessionCount,
});
}
return t("devices.password.toast.updated");
}
function extractRpcError(
error: unknown,
fallbackMessage: string,
): {
code?: string;
message: string;
} {
if (error instanceof DaemonRpcError) {
return { code: error.code, message: error.userMessage || error.message };
}
if (error instanceof Error) {
return { message: error.message || fallbackMessage };
}
return { message: fallbackMessage };
}
function resolvePrimaryButtonLabel(
step: "set" | "change" | "remove",
submitting: boolean,
t: TFunction,
): string {
if (step === "set") {
return submitting ? t("devices.password.setting") : t("devices.password.setAction");
}
if (step === "change") {
return submitting ? t("devices.password.saving") : t("devices.password.saveAction");
}
return submitting ? t("devices.password.removing") : t("devices.password.removeAction");
}
function DaemonPasswordStepBanner({
step,
t,
}: {
step: "set" | "change" | "remove";
t: TFunction;
}) {
if (step === "remove") {
return (
<Alert
size="sm"
variant="warning"
description={t("devices.password.removeWarning")}
testID="daemon-password-remove-warning"
/>
);
}
return (
<Alert
size="sm"
variant="info"
description={
step === "set" ? t("devices.password.setInfo") : t("devices.password.changeInfo")
}
testID="daemon-password-info"
/>
);
}
interface PasswordInputFieldProps {
label: string;
initialValue: string;
showPassword: boolean;
onChangeText: (value: string) => void;
onToggleShow: () => void;
onSubmitEditing?: () => void;
error: string | null;
disabled: boolean;
autoFocus?: boolean;
size: "sm" | "md";
returnKeyType?: "next" | "done";
testID: string;
}
function PasswordInputField({
label,
initialValue,
showPassword,
onChangeText,
onToggleShow,
onSubmitEditing,
error,
disabled,
autoFocus,
size,
returnKeyType = "next",
testID,
}: PasswordInputFieldProps) {
const { t } = useTranslation();
return (
<Field label={label} error={error} testID={`${testID}-field`}>
<View style={styles.passwordRow}>
<View style={styles.passwordInputWrap}>
<FormTextInput
initialValue={initialValue}
onChangeText={onChangeText}
onSubmitEditing={onSubmitEditing}
secureTextEntry={!showPassword}
autoCapitalize="none"
autoCorrect={false}
autoComplete="off"
autoFocus={autoFocus}
editable={!disabled}
invalid={Boolean(error)}
size={size}
returnKeyType={returnKeyType}
testID={testID}
/>
</View>
<Button
variant="outline"
size={size}
leftIcon={showPassword ? EyeOff : Eye}
onPress={onToggleShow}
disabled={disabled}
accessibilityLabel={
showPassword ? t("devices.password.hide") : t("devices.password.show")
}
testID={`${testID}-toggle`}
/>
</View>
</Field>
);
}
export interface DaemonPasswordFormContentProps {
serverId: string;
initialMode: "set" | "change";
model?: DaemonPasswordFormModel;
onCancel: () => void;
onCompleted: () => void;
}
export function DaemonPasswordFormContent({
serverId,
initialMode,
model: externalModel,
onCancel,
onCompleted,
}: DaemonPasswordFormContentProps) {
const { t } = useTranslation();
const toast = useToast();
const isCompact = useIsCompactFormFactor();
const fieldSize = isCompact ? "md" : "sm";
const client = useHostRuntimeClient(serverId);
const hosts = useHosts();
const { setHostPassword } = useHostMutations();
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
const host = useMemo(
() => hosts.find((item) => item.serverId === serverId) ?? null,
[hosts, serverId],
);
const isLocalCredential = serverInfo?.localCredentialAuth === true;
const [internalModel] = useState(() =>
openDaemonPasswordForm({
mode: initialMode,
isLocalCredential,
}),
);
const model = externalModel ?? internalModel;
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
const syncProfilePasswordIfNeeded = useCallback(
async (nextPassword: string | null) => {
if (
!shouldSyncHostProfilePassword({
localCredentialAuth: serverInfo?.localCredentialAuth === true,
connections: host?.connections ?? [],
})
) {
return;
}
await setHostPassword(serverId, nextPassword ?? "");
},
[host?.connections, serverId, serverInfo?.localCredentialAuth, setHostPassword],
);
const executeMutation = useCallback(
async (
action: "set" | "change" | "remove",
payload: {
password: string | null;
currentPassword?: string;
},
) => {
if (!client) {
model.finishSubmitError({ message: t("workspace.terminal.hostDisconnected") });
return;
}
try {
const result = await client.setDaemonPassword(payload);
await syncProfilePasswordIfNeeded(payload.password);
model.finishSubmitSuccess();
toast.show(formatSuccessToast(action, result.disconnectedSessionCount, t), {
variant: "success",
});
onCompleted();
} catch (error) {
model.finishSubmitError(extractRpcError(error, t("errors.unableToSave")));
}
},
[client, model, onCompleted, syncProfilePasswordIfNeeded, t, toast],
);
const handleSubmit = useCallback(() => {
const attempt = model.beginSubmit();
if (!attempt.valid) return;
void executeMutation(state.step, attempt.payload);
}, [executeMutation, model, state.step]);
const handleRequestRemove = useCallback(() => {
if (state.submitting) return;
if (!state.isLocalCredential) {
model.enterRemoveStep();
return;
}
void (async () => {
const confirmed = await confirmDialog({
title: t("devices.password.removeTitle"),
message: t("devices.password.removeWarning"),
confirmLabel: t("devices.password.removeAction"),
cancelLabel: t("common.actions.cancel"),
destructive: true,
});
if (!confirmed) return;
model.enterRemoveStep();
const attempt = model.beginSubmit();
if (!attempt.valid) return;
await executeMutation("remove", attempt.payload);
})();
}, [executeMutation, model, state.isLocalCredential, state.submitting, t]);
const showCurrentPassword =
(state.step === "change" || state.step === "remove") && !state.isLocalCredential;
const primaryLabel = resolvePrimaryButtonLabel(state.step, state.submitting, t);
return (
<View style={styles.form} testID={`daemon-password-form-${state.step}`}>
<DaemonPasswordStepBanner step={state.step} t={t} />
{showCurrentPassword ? (
<PasswordInputField
key={`current-${state.step}`}
label={t("devices.password.fields.current")}
initialValue={state.currentPassword}
showPassword={state.showCurrentPassword}
onChangeText={model.setCurrentPassword}
onToggleShow={model.toggleShowCurrentPassword}
onSubmitEditing={state.step === "remove" ? handleSubmit : undefined}
error={translateFieldError(state.fieldErrors.currentPassword, t)}
disabled={state.submitting}
autoFocus
size={fieldSize}
returnKeyType={state.step === "remove" ? "done" : "next"}
testID="daemon-password-current-input"
/>
) : null}
{state.step !== "remove" ? (
<>
<PasswordInputField
key={`new-${state.step}`}
label={t("devices.password.fields.new")}
initialValue={state.newPassword}
showPassword={state.showNewPassword}
onChangeText={model.setNewPassword}
onToggleShow={model.toggleShowNewPassword}
error={translateFieldError(state.fieldErrors.newPassword, t)}
disabled={state.submitting}
autoFocus={!showCurrentPassword}
size={fieldSize}
testID="daemon-password-new-input"
/>
<PasswordInputField
key={`confirm-${state.step}`}
label={
state.step === "set"
? t("devices.password.fields.confirm")
: t("devices.password.fields.confirmNew")
}
initialValue={state.confirmPassword}
showPassword={state.showConfirmPassword}
onChangeText={model.setConfirmPassword}
onToggleShow={model.toggleShowConfirmPassword}
onSubmitEditing={handleSubmit}
error={translateFieldError(state.fieldErrors.confirmPassword, t)}
disabled={state.submitting}
size={fieldSize}
returnKeyType="done"
testID="daemon-password-confirm-input"
/>
</>
) : null}
{state.submitError ? (
<Alert
size="sm"
variant="error"
description={state.submitError}
testID="daemon-password-submit-error"
/>
) : null}
<View style={styles.actions}>
<Button
variant="secondary"
style={FLEX_ONE_STYLE}
onPress={state.step === "remove" ? model.backToChangeStep : onCancel}
disabled={state.submitting}
testID="daemon-password-cancel-button"
>
{t("common.actions.cancel")}
</Button>
<Button
variant={state.step === "remove" ? "destructive" : "default"}
style={FLEX_ONE_STYLE}
loading={state.submitting}
disabled={state.submitting}
onPress={handleSubmit}
testID="daemon-password-submit-button"
>
{primaryLabel}
</Button>
</View>
{state.step === "change" ? (
<View style={styles.removeSection}>
<View style={styles.divider} />
<Button
variant="ghost"
onPress={handleRequestRemove}
disabled={state.submitting}
textStyle={styles.removeButtonText}
testID="daemon-password-remove-trigger"
>
{t("devices.password.removeAction")}
</Button>
</View>
) : null}
</View>
);
}
export interface DaemonPasswordSheetProps {
serverId: string;
visible: boolean;
initialMode: "set" | "change";
onClose: () => void;
}
export function DaemonPasswordSheet({
serverId,
visible,
initialMode,
onClose,
}: DaemonPasswordSheetProps) {
if (!visible) return null;
return (
<DaemonPasswordSheetOpen
key={`${serverId}:${initialMode}`}
serverId={serverId}
initialMode={initialMode}
onClose={onClose}
/>
);
}
function DaemonPasswordSheetOpen({
serverId,
initialMode,
onClose,
}: Omit<DaemonPasswordSheetProps, "visible">) {
const { t } = useTranslation();
const isLocalCredential = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.localCredentialAuth === true,
);
const [model] = useState(() =>
openDaemonPasswordForm({
mode: initialMode,
isLocalCredential,
}),
);
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
const handleClose = useCallback(() => {
if (state.submitting) return;
onClose();
}, [onClose, state.submitting]);
const header = useMemo<SheetHeader>(() => {
if (state.step === "remove") {
return {
title: t("devices.password.removeTitle"),
back: {
onPress: model.backToChangeStep,
label: t("common.actions.back"),
},
};
}
return {
title:
state.step === "set" ? t("devices.password.setTitle") : t("devices.password.changeTitle"),
};
}, [model.backToChangeStep, state.step, t]);
return (
<AdaptiveModalSheet
header={header}
visible
onClose={handleClose}
snapPoints={SNAP_POINTS}
desktopMaxWidth={440}
testID="daemon-password-sheet"
>
<DaemonPasswordFormContent
serverId={serverId}
initialMode={initialMode}
model={model}
onCancel={handleClose}
onCompleted={onClose}
/>
</AdaptiveModalSheet>
);
}
const styles = StyleSheet.create((theme) => ({
form: {
gap: theme.spacing[4],
},
passwordRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
passwordInputWrap: {
flex: 1,
minWidth: 0,
},
actions: {
flexDirection: "row",
gap: theme.spacing[3],
marginTop: theme.spacing[1],
},
removeSection: {
gap: theme.spacing[3],
marginTop: theme.spacing[1],
},
divider: {
height: theme.borderWidth[1],
backgroundColor: theme.colors.border,
},
removeButtonText: {
color: theme.colors.destructive,
},
}));
@@ -0,0 +1,168 @@
import { describe, expect, it } from "vitest";
import type { TFunction } from "i18next";
import type { DaemonSessionSummary } from "@getpaseo/protocol/daemon-clients";
import {
formatAppDetail,
formatAuthMethodLabel,
formatDeviceDetail,
formatSessionHint,
formatSessionTitle,
} from "./device-display";
const translations: Record<string, string> = {
"devices.connected.thisDevice": "This device",
"devices.transport.local": "Local",
"devices.transport.tailscale": "Tailscale",
"devices.transport.relay": "Relay",
"devices.transport.hub": "Hub",
"devices.transport.direct": "Direct",
"devices.transport.viaHost": "Via host",
"devices.kind.desktop": "Desktop",
"devices.kind.mobile": "Mobile",
"devices.kind.web": "Web",
"devices.kind.hub": "Hub",
"devices.kind.plugin": "Plugin",
"devices.kind.host": "Host",
"devices.auth.localMachine": "Local machine",
"devices.auth.password": "Password",
"devices.auth.openAccess": "Open access",
"devices.auth.hub": "Hub",
};
const t = ((key: string, options?: { host?: string }) => {
if (key === "devices.transport.via" && options?.host) {
return `Via ${options.host}`;
}
return translations[key] ?? key;
}) as unknown as TFunction;
function makeSession(overrides: Partial<DaemonSessionSummary> = {}): DaemonSessionSummary {
return {
sessionId: "sess_1",
principalId: "owner",
isCurrentSession: false,
name: null,
platform: null,
clientType: "browser",
appVersion: "0.19.0",
transport: "local",
permissions: ["daemon.read", "workspace.read"],
connectedAt: "2026-12-01T10:00:00.000Z",
socketCount: 1,
...overrides,
};
}
describe("device-display formatting", () => {
it("shows real machine name, This device hint, macOS version, and omits 127.0.0.1 on Local Electron", () => {
const session = makeSession({
isCurrentSession: true,
name: "MacBook Pro",
appKind: "desktop",
platform: "macos",
osName: "macOS",
osVersion: "15.3.1",
transport: "local",
remoteIp: "127.0.0.1",
ipSource: "direct",
authMethod: "local_credential",
});
expect(formatSessionTitle(session, t)).toBe("MacBook Pro");
expect(formatSessionHint(session, null, t)).toBe("This device · Local · macOS 15.3");
expect(formatDeviceDetail(session)).toBe("MacBook Pro · macOS 15.3.1");
expect(formatAppDetail(session, t)).toBe("Desktop 0.19.0");
expect(formatAuthMethodLabel(session.authMethod, t)).toBe("Local machine");
});
it("shows observed IP and OS on Tailscale Android and omits OS repetition on Web", () => {
const android = makeSession({
name: "Pixel 9 Pro",
clientType: "mobile",
appKind: "mobile",
platform: "android",
osName: "Android",
osVersion: "15",
deviceModel: "Pixel 9 Pro",
transport: "tailscale",
remoteIp: "100.84.12.9",
ipSource: "direct",
authMethod: "password",
});
expect(formatSessionTitle(android, t)).toBe("Pixel 9 Pro");
expect(formatSessionHint(android, null, t)).toBe("Tailscale · 100.84.12.9 · Android 15");
expect(formatDeviceDetail(android)).toBe("Pixel 9 Pro · Android 15");
expect(formatAppDetail(android, t)).toBe("Mobile 0.19.0");
const web = makeSession({
isCurrentSession: true,
name: "Chrome on macOS",
clientType: "browser",
appKind: "web",
platform: "web",
browserName: "Chrome",
osName: "macOS",
transport: "relay",
remoteIp: null,
ipSource: null,
});
expect(formatSessionTitle(web, t)).toBe("Chrome on macOS");
expect(formatSessionHint(web, null, t)).toBe("This device · Relay");
expect(formatDeviceDetail(web)).toBe("Chrome · macOS");
expect(formatAppDetail(web, t)).toBe("Web 0.19.0");
});
it("shows Linux in collapsed hint and distro name in expanded Device detail", () => {
const linux = makeSession({
name: "workstation",
appKind: "desktop",
platform: "linux",
osName: "Linux",
osVersion: "Ubuntu 24.04.1 LTS",
transport: "direct",
remoteIp: "192.168.1.42",
ipSource: "direct",
});
expect(formatSessionHint(linux, null, t)).toBe("Direct · 192.168.1.42 · Linux");
expect(formatDeviceDetail(linux)).toBe("workstation · Ubuntu 24.04.1 LTS");
});
it("falls back cleanly for unnamed legacy 0.18.2 clients and Hub", () => {
const legacy = makeSession({
isCurrentSession: true,
name: null,
clientType: "mobile",
platform: null,
appVersion: "0.18.2",
transport: "relay",
});
expect(formatSessionTitle(legacy, t)).toBe("This device");
expect(formatSessionHint(legacy, null, t)).toBe("Relay · Mobile 0.18.2");
expect(formatDeviceDetail(legacy)).toBeNull();
const hub = makeSession({
name: "Paseo Hub",
clientType: "hub",
appKind: "hub",
appVersion: null,
transport: "hub",
authMethod: "hub",
});
expect(formatSessionTitle(hub, t)).toBe("Paseo Hub");
expect(formatSessionHint(hub, null, t)).toBe("Hub");
expect(formatDeviceDetail(hub)).toBeNull();
expect(formatAppDetail(hub, t)).toBe("Hub");
expect(formatAuthMethodLabel(hub.authMethod, t)).toBe("Hub");
});
it("maps every daemon SessionAuthMethod value cleanly", () => {
expect(formatAuthMethodLabel("local_credential", t)).toBe("Local machine");
expect(formatAuthMethodLabel("password", t)).toBe("Password");
expect(formatAuthMethodLabel("header_bearer", t)).toBe("Password");
expect(formatAuthMethodLabel("unprotected", t)).toBe("Open access");
expect(formatAuthMethodLabel("hub", t)).toBe("Hub");
expect(formatAuthMethodLabel("plugin", t)).toBe("Plugin");
expect(formatAuthMethodLabel(null, t)).toBeNull();
});
});
+209
View File
@@ -0,0 +1,209 @@
import type { TFunction } from "i18next";
import type {
DaemonSessionSummary,
DaemonSessionTransport,
} from "@getpaseo/protocol/daemon-clients";
function osNameFromPlatform(platform: string | null | undefined): string | null {
switch (platform) {
case "macos":
return "macOS";
case "linux":
return "Linux";
case "windows":
return "Windows";
case "ios":
return "iOS";
case "android":
return "Android";
default:
return null;
}
}
function shortenNumericVersion(version: string): string {
const match = version.match(/^(\d+(?:\.\d+)?)/);
return match?.[1] ?? version;
}
export function formatTransportLabel(
transport: DaemonSessionTransport,
viaHostName: string | null,
t: TFunction,
): string {
switch (transport) {
case "local_ipc":
case "local":
return t("devices.transport.local");
case "tailscale":
return t("devices.transport.tailscale");
case "relay":
return t("devices.transport.relay");
case "hub":
return t("devices.transport.hub");
case "via":
return viaHostName
? t("devices.transport.via", { host: viaHostName })
: t("devices.transport.viaHost");
case "direct":
return t("devices.transport.direct");
}
}
export function formatAppKindLabel(
session: Pick<DaemonSessionSummary, "appKind" | "clientType" | "platform">,
t: TFunction,
): string {
switch (session.appKind) {
case "desktop":
return t("devices.kind.desktop");
case "mobile":
return t("devices.kind.mobile");
case "web":
return t("devices.kind.web");
case "hub":
return t("devices.kind.hub");
case "cli":
return "CLI";
case "mcp":
return "MCP";
case "plugin":
return t("devices.kind.plugin");
case "daemon":
return t("devices.kind.host");
}
if (
session.platform === "macos" ||
session.platform === "linux" ||
session.platform === "windows"
) {
return t("devices.kind.desktop");
}
if (session.platform === "ios" || session.platform === "android") {
return t("devices.kind.mobile");
}
if (session.clientType === "browser" || session.platform === "web") {
return t("devices.kind.web");
}
if (session.clientType === "mobile") return t("devices.kind.mobile");
if (session.clientType === "hub") return t("devices.kind.hub");
if (session.clientType === "cli") return "CLI";
return "MCP";
}
export function formatOsLabel(
session: Pick<DaemonSessionSummary, "osName" | "osVersion" | "platform">,
options: { compact: boolean },
): string | null {
const osName = session.osName ?? osNameFromPlatform(session.platform);
const osVersion = session.osVersion ?? null;
if (!osName) return osVersion;
if (options.compact) {
if (
osVersion &&
(osName === "macOS" || osName === "iOS" || osName === "iPadOS" || osName === "Android") &&
/^\d/.test(osVersion)
) {
return `${osName} ${shortenNumericVersion(osVersion)}`;
}
return osName;
}
if (!osVersion) return osName;
if (osName === "Linux" && !/^\d/.test(osVersion)) {
return osVersion;
}
return `${osName} ${osVersion}`;
}
export function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
if (session.name) return session.name;
if (session.isCurrentSession) return t("devices.connected.thisDevice");
return formatAppKindLabel(session, t);
}
export function formatSessionHint(
session: DaemonSessionSummary,
viaHostName: string | null,
t: TFunction,
): string {
const title = formatSessionTitle(session, t);
const thisDeviceLabel = t("devices.connected.thisDevice");
const transport = formatTransportLabel(session.transport, viaHostName, t);
const parts: string[] = [];
if (session.isCurrentSession && title !== thisDeviceLabel) {
parts.push(thisDeviceLabel);
}
parts.push(transport);
if (
session.remoteIp &&
(session.transport === "tailscale" ||
session.transport === "direct" ||
session.transport === "relay")
) {
parts.push(session.remoteIp);
}
const shortOs = formatOsLabel(session, { compact: true });
if (shortOs && !title.toLowerCase().includes(shortOs.toLowerCase())) {
parts.push(shortOs);
} else if (
!shortOs &&
!session.name &&
session.appVersion &&
session.transport !== "hub" &&
session.clientType !== "hub"
) {
const kind = formatAppKindLabel(session, t);
const fallbackDetail = `${kind} ${session.appVersion}`;
if (fallbackDetail !== title) {
parts.push(fallbackDetail);
}
}
return parts.join(" · ");
}
export function formatDeviceDetail(session: DaemonSessionSummary): string | null {
const osDetail = formatOsLabel(session, { compact: false });
const primary =
session.deviceModel ??
session.browserName ??
(session.appKind === "desktop" ? session.name : null);
if (primary && osDetail) {
if (primary.toLowerCase() === osDetail.toLowerCase()) return primary;
return `${primary} · ${osDetail}`;
}
return primary ?? osDetail;
}
export function formatAppDetail(session: DaemonSessionSummary, t: TFunction): string {
const kind = formatAppKindLabel(session, t);
return session.appVersion ? `${kind} ${session.appVersion}` : kind;
}
export function formatAuthMethodLabel(
authMethod: string | null | undefined,
t: TFunction,
): string | null {
switch (authMethod) {
case "local_credential":
return t("devices.auth.localMachine");
case "password":
case "header_bearer":
return t("devices.auth.password");
case "unprotected":
return t("devices.auth.openAccess");
case "hub":
return t("devices.auth.hub");
case "plugin":
return t("devices.kind.plugin");
default:
return null;
}
}
@@ -6,9 +6,10 @@ import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-moda
import { Button } from "@/components/ui/button";
import type { Theme } from "@/styles/theme";
import { PairDeviceSection } from "./pair-device-section";
import { DaemonPasswordFormContent } from "./daemon-password-sheet";
import { WaysToConnect } from "./ways-to-connect";
const SNAP_POINTS: string[] = ["72%", "92%"];
const SNAP_POINTS: string[] = ["80%", "92%"];
const ThemedPlus = withUnistyles(Plus);
const iconProps = (theme: Theme) => ({
size: theme.iconSize.sm,
@@ -16,7 +17,7 @@ const iconProps = (theme: Theme) => ({
});
const plusIcon = <ThemedPlus uniProps={iconProps} />;
type PairStep = "ways" | "relay";
type PairStep = "ways" | "relay" | "password";
export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
const { t } = useTranslation();
@@ -35,22 +36,59 @@ export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
}, []);
const handleOpenRelay = useCallback(() => setStep("relay"), []);
const handleBackToWays = useCallback(() => setStep("ways"), []);
const handleOpenPassword = useCallback(() => setStep("password"), []);
const handleBackToRelay = useCallback(() => setStep("relay"), []);
const header = useMemo<SheetHeader>(
() =>
step === "relay"
? {
title: t("devices.relay.title"),
back: {
onPress: handleBackToWays,
label: t("common.actions.back"),
},
}
: {
title: t("settings.host.pairDevices.rowTitle"),
},
[handleBackToWays, step, t],
);
const header = useMemo<SheetHeader>(() => {
if (step === "password") {
return {
title: t("devices.password.setTitle"),
back: {
onPress: handleBackToRelay,
label: t("common.actions.back"),
},
};
}
if (step === "relay") {
return {
title: t("devices.relay.title"),
back: {
onPress: handleBackToWays,
label: t("common.actions.back"),
},
};
}
return {
title: t("settings.host.pairDevices.rowTitle"),
};
}, [handleBackToRelay, handleBackToWays, step, t]);
let sheetTestID = "devices-pair-sheet";
if (step === "relay") sheetTestID = "devices-relay-pairing";
else if (step === "password") sheetTestID = "devices-pair-password-step";
let sheetContent: React.ReactNode;
if (step === "password") {
sheetContent = (
<DaemonPasswordFormContent
key={`${serverId}:pair-password`}
serverId={serverId}
initialMode="set"
onCancel={handleBackToRelay}
onCompleted={handleBackToRelay}
/>
);
} else if (step === "relay") {
sheetContent = (
<PairDeviceSection
serverId={serverId}
onClose={handleClose}
onOpenPassword={handleOpenPassword}
/>
);
} else {
sheetContent = <WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />;
}
return (
<>
@@ -69,14 +107,10 @@ export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
onDismiss={handleDismiss}
snapPoints={SNAP_POINTS}
desktopMaxWidth={480}
desktopHeight={520}
testID={step === "relay" ? "devices-relay-pairing" : "devices-pair-sheet"}
desktopHeight={560}
testID={sheetTestID}
>
{step === "relay" ? (
<PairDeviceSection serverId={serverId} onClose={handleClose} />
) : (
<WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />
)}
{sheetContent}
</AdaptiveModalSheet>
</>
);
+36 -5
View File
@@ -1,7 +1,8 @@
import { useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { PairDeviceSection } from "@/devices/pair-device-section";
import { DaemonPasswordFormContent } from "@/devices/daemon-password-sheet";
export interface PairDeviceModalProps {
serverId: string;
@@ -10,13 +11,28 @@ export interface PairDeviceModalProps {
testID?: string;
}
const SNAP_POINTS: string[] = ["72%", "92%"];
const SNAP_POINTS: string[] = ["80%", "92%"];
export function PairDeviceModal({ serverId, visible, onClose, testID }: PairDeviceModalProps) {
const { t } = useTranslation();
const [step, setStep] = useState<"relay" | "password">("relay");
const handleOpenPassword = useCallback(() => setStep("password"), []);
const handleBackToRelay = useCallback(() => setStep("relay"), []);
const handleDismiss = useCallback(() => setStep("relay"), []);
const header = useMemo<SheetHeader>(
() => ({ title: t("settings.host.pairDevices.rowTitle") }),
[t],
() =>
step === "password"
? {
title: t("devices.password.setTitle"),
back: {
onPress: handleBackToRelay,
label: t("common.actions.back"),
},
}
: { title: t("settings.host.pairDevices.rowTitle") },
[handleBackToRelay, step, t],
);
return (
@@ -24,11 +40,26 @@ export function PairDeviceModal({ serverId, visible, onClose, testID }: PairDevi
header={header}
visible={visible}
onClose={onClose}
onDismiss={handleDismiss}
snapPoints={SNAP_POINTS}
desktopMaxWidth={480}
testID={testID}
>
<PairDeviceSection serverId={serverId} onClose={onClose} />
{step === "password" ? (
<DaemonPasswordFormContent
key={`${serverId}:modal-password`}
serverId={serverId}
initialMode="set"
onCancel={handleBackToRelay}
onCompleted={handleBackToRelay}
/>
) : (
<PairDeviceSection
serverId={serverId}
onClose={onClose}
onOpenPassword={handleOpenPassword}
/>
)}
</AdaptiveModalSheet>
);
}
@@ -15,6 +15,7 @@ import { useFetchQuery } from "@/data/query";
import { daemonPairingOfferQueryKey } from "@/data/daemon-pairing";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
import type { Theme } from "@/styles/theme";
import {
EditingTextInput as TextInput,
@@ -33,24 +34,42 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
});
const accentBrightColorMapping = (theme: Theme) => ({ color: theme.colors.accentBright });
function canOfferSetPassword(
serverInfo: DaemonServerInfo | null,
serverFeatures: DaemonServerInfo["features"] | undefined,
onOpenPassword: (() => void) | undefined,
): boolean {
if (!onOpenPassword) return false;
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
if (serverFeatures?.daemonPasswordManagement !== true) return false;
if (serverInfo?.passwordManagedByEnv === true) return false;
const permissions = serverInfo?.permissions;
if (!permissions) return true;
return permissions.includes("daemon.manage") && permissions.includes("access.manage");
}
export interface PairDeviceSectionProps {
serverId: string;
onClose: () => void;
onOpenPassword?: () => void;
}
export function PairDeviceSection({ serverId, onClose }: PairDeviceSectionProps) {
export function PairDeviceSection({ serverId, onClose, onOpenPassword }: PairDeviceSectionProps) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
const isConnected = runtimeSnapshot?.connectionStatus === "online";
const isDisconnected =
runtimeSnapshot?.connectionStatus === "offline" ||
runtimeSnapshot?.connectionStatus === "error";
const { patchConfig } = useDaemonConfig(serverId);
const [copied, setCopied] = useState(false);
const serverFeatures = client?.getLastServerInfoMessage()?.features;
const serverFeatures = serverInfo?.features ?? client?.getLastServerInfoMessage()?.features;
const supportsPairingRpc = serverFeatures?.daemonStatusRpc === true;
const canConfigureRelay = supportsPairingRpc && serverFeatures?.relayConfig === true;
const passwordConfigured = serverInfo?.passwordConfigured === true;
const canSetPassword = canOfferSetPassword(serverInfo, serverFeatures, onOpenPassword);
const pairingQuery = useFetchQuery({
queryKey: daemonPairingOfferQueryKey(serverId),
@@ -123,6 +142,9 @@ export function PairDeviceSection({ serverId, onClose }: PairDeviceSectionProps)
onEnableRelay={handleEnableRelay}
onClose={onClose}
onCopy={handleCopyPress}
passwordConfigured={passwordConfigured}
canSetPassword={canSetPassword}
onOpenPassword={onOpenPassword}
/>
</View>
);
@@ -143,6 +165,9 @@ interface PairDeviceBodyProps {
onEnableRelay: () => void;
onClose: () => void;
onCopy: () => void;
passwordConfigured: boolean;
canSetPassword: boolean;
onOpenPassword?: () => void;
}
function PairDeviceBody(props: PairDeviceBodyProps) {
@@ -267,7 +292,32 @@ function PairingOffer(props: PairDeviceBodyProps & { offer: { url: string } }) {
{props.copied ? t("pairing.device.copied") : t("pairing.device.copy")}
</Button>
</View>
<Alert size="sm" variant="warning" description={t("pairing.device.securityWarning")} />
{props.passwordConfigured ? (
<Alert
size="sm"
variant="info"
description={t("pairing.device.passwordProtected")}
testID="pairing-password-protected-alert"
/>
) : (
<Alert
size="sm"
variant="warning"
description={t("pairing.device.securityWarning")}
testID="pairing-no-password-alert"
>
{props.canSetPassword && props.onOpenPassword ? (
<Button
variant="secondary"
size="sm"
onPress={props.onOpenPassword}
testID="pairing-set-password-button"
>
{t("devices.password.setAction")}
</Button>
) : null}
</Alert>
)}
</View>
);
}
@@ -353,7 +403,7 @@ const styles = StyleSheet.create((theme) => ({
lineHeight: theme.fontSize.sm * 1.5,
},
offer: {
gap: theme.spacing[4],
gap: theme.spacing[3],
},
offerHint: {
color: theme.colors.foregroundMuted,
@@ -364,7 +414,7 @@ const styles = StyleSheet.create((theme) => ({
alignSelf: "center",
alignItems: "center",
justifyContent: "center",
width: 304,
width: 224,
maxWidth: "100%",
aspectRatio: 1,
padding: theme.spacing[3],
@@ -733,4 +733,23 @@ describe("deriveAgentScreenViewState", () => {
expect(ready.source).toBe("authoritative");
expect(ready.sync).toEqual({ status: "catching_up", ui: "overlay" });
});
it("stays idle instead of reconnecting when the host connection was refused", () => {
const result = deriveAgentScreenViewState({
input: {
...createBaseInput(),
agent: createAgent("agent-1"),
isConnected: false,
isConnectionRefused: true,
hasHydratedHistoryBefore: true,
},
memory: createBaseMemory({
hasRenderedReady: true,
lastReadyAgent: createAgent("agent-1"),
}),
});
const ready = expectReadyState(result.state);
expect(ready.sync).toEqual({ status: "idle" });
});
});
@@ -43,6 +43,7 @@ export interface AgentScreenMachineInput {
isArchived: boolean;
missingAgentState: AgentScreenMissingState;
isConnected: boolean;
isConnectionRefused?: boolean;
isArchivingCurrentAgent: boolean;
isHistorySyncing: boolean;
needsAuthoritativeSync: boolean;
@@ -181,6 +182,9 @@ function resolveAgentScreenSync(args: {
) {
return { status: "idle" };
}
if (input.isConnectionRefused) {
return { status: "idle" };
}
// A reconnected chat is not back until the daemon answers whether it is current.
if (
(!input.isConnected || input.visibilityCatchUpStatus === "reattaching") &&
@@ -1,3 +1,4 @@
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -15,8 +16,15 @@ import {
} from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { getIsElectron, isWeb } from "@/constants/platform";
import {
isPasswordRefusal,
resolveHostRefusal,
type HostRefusalPresentation,
} from "@/hosts/host-refusal";
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
import { useHardwareKeyboardPresent } from "@/keyboard/availability";
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
import {
canSwitchToForm,
editForm,
@@ -27,6 +35,7 @@ import {
promptForPassword,
resolveConnection,
switchMode,
uriHostLabel,
type DirectConnectionForm,
type DirectConnectionInput,
type DirectConnectionMode,
@@ -168,6 +177,9 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
const [input, setInput] = useState<DirectConnectionInput>(openDirectConnection);
const [isSaving, setIsSaving] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
null,
);
// Switching modes mounts the other mode's fields. They take focus when the user was typing
// or has a keyboard, so a phone's keyboard stays up instead of closing on the switch.
const [focusModeBody, setFocusModeBody] = useState(false);
@@ -225,6 +237,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
if (next.mode !== input.mode) {
setFocusModeBody(keyboardPresent || fieldFocused.current);
setErrorMessage("");
setRefusalPresentation(null);
}
setInput(next);
},
@@ -284,6 +297,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
try {
setIsSaving(true);
setErrorMessage("");
setRefusalPresentation(null);
const result = await connect(connection);
if (!result) return;
const { profile, serverId, hostname } = result;
@@ -291,13 +305,29 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
onSaved?.({ profile, serverId, hostname, isNewHost });
handleClose();
} catch (error) {
const message = describeFailure(connection, error);
setErrorMessage(message);
// URI mode has no Password field, so a rejected password is asked for here.
if (input.mode === "uri" && getConnectionAuthFailureReason(error)) {
setInput((current) => promptForPassword(current));
const rejection = getConnectionHelloRejection(error);
if (rejection) {
const targetHostName =
connection.kind === "relay"
? (uriHostLabel(connection.link) ?? "host")
: connection.endpoint;
setRefusalPresentation(
resolveHostRefusal({
rejection,
hostName: targetHostName,
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
}),
);
// URI mode has no Password field, so a password refusal asks for it here.
if (input.mode === "uri" && isPasswordRefusal(rejection)) {
setInput((current) => promptForPassword(current));
}
return;
}
const message = describeFailure(connection, error);
setErrorMessage(message);
if (connection.kind === "direct" && !isMobile) {
Alert.alert(t("pairing.direct.errors.failedTitle"), message);
}
@@ -417,6 +447,9 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
)}
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
{refusalPresentation ? (
<HostRefusalInlineAlert presentation={refusalPresentation} testID="direct-host-refusal" />
) : null}
</AdaptiveModalSheet>
);
}
@@ -470,6 +503,7 @@ function DirectFormFields({
if (isSaving) return;
onChange(editForm(input, { useTls: !input.useTls }));
}, [input, isSaving, onChange]);
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
const handleTogglePasswordVisibility = useCallback(() => {
setIsPasswordVisible((current) => !current);
}, []);
@@ -530,6 +564,7 @@ function DirectFormFields({
accessibilityState={useTlsAccessibilityState}
aria-checked={input.useTls}
testID="direct-ssl-toggle"
{...tlsCheckboxKeyProps}
>
<View style={checkboxStyle}>
{input.useTls ? (
@@ -21,7 +21,13 @@ import {
resolveControlInteractionStyles,
} from "@/components/ui/control-geometry";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { DaemonConnectionTestError } from "@/utils/test-daemon-connection";
import { getIsElectron, isWeb } from "@/constants/platform";
import { resolveHostRefusal, type HostRefusalPresentation } from "@/hosts/host-refusal";
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
import {
DaemonConnectionTestError,
getConnectionHelloRejection,
} from "@/utils/test-daemon-connection";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
const FLEX_ONE_STYLE = { flex: 1 } as const;
@@ -105,6 +111,9 @@ export function AddRemoteSshHostModal({
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
null,
);
const header = useMemo<SheetHeader>(() => ({ title: t("pairing.remoteSsh.title") }), [t]);
const clear = useCallback(() => {
@@ -114,6 +123,7 @@ export function AddRemoteSshHostModal({
passwordInputRef.current?.replaceText("");
setIsPasswordVisible(false);
setErrorMessage("");
setRefusalPresentation(null);
}, []);
const handleClose = useCallback(() => {
@@ -148,11 +158,25 @@ export function AddRemoteSshHostModal({
try {
setIsSaving(true);
setErrorMessage("");
setRefusalPresentation(null);
result = await probeAndUpsertRemoteSshConnection({
...target,
password: passwordRef.current === "" ? undefined : passwordRef.current,
});
} catch (error) {
const rejection = getConnectionHelloRejection(error);
if (rejection) {
setRefusalPresentation(
resolveHostRefusal({
rejection,
hostName: target.host,
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
}),
);
return;
}
const message =
error instanceof DaemonConnectionTestError
? t("pairing.remoteSsh.errors.failedToConnect", { detail: error.message })
@@ -264,6 +288,9 @@ export function AddRemoteSshHostModal({
</PressHighlight>
</View>
</Field>
{refusalPresentation ? (
<HostRefusalInlineAlert presentation={refusalPresentation} testID="remote-ssh-refusal" />
) : null}
<View style={styles.actions}>
<Button
style={FLEX_ONE_STYLE}
@@ -9,6 +9,7 @@ import {
promptForPassword,
resolveConnection,
switchMode,
uriHostLabel,
type DirectConnectionForm,
type DirectConnectionInput,
} from "./direct-connection";
@@ -267,4 +268,11 @@ describe("resolving the connection", () => {
password: "pw",
});
});
it("extracts a short host label from pairing links without exposing query credentials", () => {
const relayWithPassword = `${RELAY_LINK}&password=top-secret`;
expect(uriHostLabel(relayWithPassword)).toBe("srv_abc");
expect(uriHostLabel(OFFER_LINK)).toBe("srv_offer");
expect(uriHostLabel("relay://invalid?password=top-secret")).toBeNull();
});
});
@@ -163,7 +163,7 @@ function uriToForm(uri: string): DirectConnectionForm {
};
}
function uriHostLabel(uri: string): string | null {
export function uriHostLabel(uri: string): string | null {
const trimmed = uri.trim();
if (isPairingLink(trimmed)) {
try {
@@ -6,14 +6,20 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { Link } from "lucide-react-native";
import type { HostProfile } from "@/types/host-connection";
import { useHosts, useHostMutations, type PasswordRequiredPairing } from "@/runtime/host-runtime";
import { parseRelayConnectionUri } from "@/utils/daemon-endpoints";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
import { uriHostLabel } from "./direct-connection";
import {
AdaptiveModalSheet,
AdaptiveTextInput,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
import { getIsElectron, isWeb } from "@/constants/platform";
import {
isPasswordRefusal,
resolveHostRefusal,
type HostRefusalPresentation,
} from "@/hosts/host-refusal";
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
import { PairingTargetTracker } from "@/components/pair-link-credentials";
import { Button } from "@/components/ui/button";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
@@ -21,14 +27,7 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
const FLEX_ONE_STYLE = { flex: 1 } as const;
function parsedHostLabel(input: string): string {
try {
if (input.startsWith("relay://") || input.includes("#connect=")) {
return parseRelayConnectionUri(input).offer.serverId;
}
return parseConnectionOfferFromUrl(input)?.serverId ?? "host";
} catch {
return "host";
}
return uriHostLabel(input) ?? "host";
}
const styles = StyleSheet.create((theme) => ({
@@ -116,6 +115,9 @@ function PairLinkModalContent({
const inputRef = useRef<EditingTextInputHandle>(null);
const [isSaving, setIsSaving] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
null,
);
const [password, setPassword] = useState("");
const [needsPassword, setNeedsPassword] = useState(passwordRequired !== undefined);
const [passwordResetKey, resetPasswordInput] = useReducer((key: number) => key + 1, 0);
@@ -126,6 +128,7 @@ function PairLinkModalContent({
inputRef.current?.replaceText("");
setPassword("");
setNeedsPassword(false);
setRefusalPresentation(null);
resetPasswordInput();
}, []);
@@ -161,6 +164,7 @@ function PairLinkModalContent({
try {
setIsSaving(true);
setErrorMessage("");
setRefusalPresentation(null);
const result = await pairing.submit(raw, password || undefined);
if (result.status === "cancelled") return;
const { profile, serverId, hostname } = result;
@@ -168,13 +172,22 @@ function PairLinkModalContent({
onSaved?.({ profile, serverId, hostname, isNewHost });
handleClose();
} catch (error) {
const rejection = getConnectionHelloRejection(error);
if (rejection) {
const presentation = resolveHostRefusal({
rejection,
hostName: parsedHostLabel(raw),
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
});
setRefusalPresentation(presentation);
setNeedsPassword(isPasswordRefusal(rejection));
return;
}
const message =
error instanceof Error ? error.message : t("pairing.link.errors.unableToPair");
setErrorMessage(message);
if (getConnectionAuthFailureReason(error)) {
setNeedsPassword(true);
return;
}
if (!isMobile) {
Alert.alert(t("pairing.link.alert.failedTitle"), message);
}
@@ -191,6 +204,7 @@ function PairLinkModalContent({
setNeedsPassword(false);
resetPasswordInput();
setErrorMessage("");
setRefusalPresentation(null);
}
offerUrlRef.current = next;
}, []);
@@ -227,6 +241,9 @@ function PairLinkModalContent({
keyboardType="url"
/>
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
{refusalPresentation ? (
<HostRefusalInlineAlert presentation={refusalPresentation} testID="pair-link-refusal" />
) : null}
</View>
{needsPassword ? (
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { DaemonHelloRejectedError } from "@getpaseo/client/internal/daemon-client";
import type { ConnectionLinkImport, LinkPairing } from "@/runtime/host-runtime";
import { openPairScan, type PairScanModel } from "./pair-scan-model";
@@ -91,10 +92,35 @@ describe("openPairScan", () => {
await settled(scan);
scan.scan(LINK);
expect(scan.getState()).toEqual({ status: "stopped", error: "Server disconnected" });
expect(scan.getState()).toEqual({
status: "stopped",
error: "Server disconnected",
helloRejection: null,
hostName: "host",
});
expect(imports).toEqual([LINK]);
});
it("stops with structured helloRejection for non-password refusals", async () => {
const rejection = {
reason: "pairing_required",
accepts: ["invite"],
message: "Re-pair device",
};
const { scan, imports } = createScanner([new DaemonHelloRejectedError(rejection)]);
scan.scan("relay://relay.example:443/srv_alpha?key=AAAA");
await settled(scan);
expect(scan.getState()).toEqual({
status: "stopped",
error: "Connection refused (pairing_required)",
helloRejection: rejection,
hostName: "srv_alpha",
});
expect(imports).toEqual(["relay://relay.example:443/srv_alpha?key=AAAA"]);
});
it("does not navigate for an attempt that finishes after the screen closed", async () => {
let finish: (outcome: ConnectionLinkImport) => void = () => {};
const connected: string[] = [];
@@ -1,4 +1,8 @@
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
import type { ConnectionLinkImport, PasswordRequiredPairing } from "@/runtime/host-runtime";
import { parseRelayConnectionUri } from "@/utils/daemon-endpoints";
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
/**
* One visit to the QR scan screen. The camera reports every frame that shows
@@ -11,7 +15,12 @@ export type PairScanState =
| { status: "scanning" }
| { status: "pairing" }
| { status: "passwordRequired"; passwordRequired: PasswordRequiredPairing }
| { status: "stopped"; error: string | null }
| {
status: "stopped";
error: string | null;
helloRejection?: DaemonHelloRejection | null;
hostName?: string;
}
| { status: "connected" };
export interface PairScanModel {
@@ -61,7 +70,13 @@ export function openPairScan(deps: PairScanDependencies): PairScanModel {
}
publish({ status: "stopped", error: null });
} catch (error) {
publish({ status: "stopped", error: error instanceof Error ? error.message : String(error) });
const helloRejection = getConnectionHelloRejection(error);
publish({
status: "stopped",
error: error instanceof Error ? error.message : String(error),
helloRejection,
hostName: hostNameFromLink(link),
});
}
}
@@ -101,3 +116,14 @@ function pairingLinkFromScan(data: string): string | null {
}
return null;
}
function hostNameFromLink(link: string): string {
try {
if (link.startsWith("relay://") || link.includes("#connect=")) {
return parseRelayConnectionUri(link).offer.serverId;
}
return parseConnectionOfferFromUrl(link)?.serverId ?? "host";
} catch {
return "host";
}
}
@@ -6,8 +6,10 @@ import { StyleSheet } from "react-native-unistyles";
import { CameraView, useCameraPermissions } from "expo-camera";
import type { BarcodeScanningResult, BarcodeSettings } from "expo-camera";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { openPairScan } from "./pair-scan-model";
import { isWeb } from "@/constants/platform";
import { openPairScan, type PairScanState } from "./pair-scan-model";
import { getIsElectron, isWeb } from "@/constants/platform";
import { resolveHostRefusal } from "@/hosts/host-refusal";
import { HostRefusalBody } from "@/hosts/host-refusal-body";
import { PairLinkModal } from "./pair-link-modal";
import { Button } from "@/components/ui/button";
@@ -81,6 +83,12 @@ const styles = StyleSheet.create((theme) => ({
textAlign: "center",
fontSize: theme.fontSize.base,
},
refusalBox: {
marginTop: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
alignItems: "center",
gap: theme.spacing[1],
},
permissionCard: {
marginTop: theme.spacing[6],
padding: theme.spacing[6],
@@ -202,9 +210,7 @@ export function PairScanContent({
{scanState.status === "pairing" ? (
<Text style={styles.helperText}>{t("pairing.scan.pairing")}</Text>
) : null}
{scanState.status === "stopped" && scanState.error ? (
<Text style={styles.helperText}>{scanState.error}</Text>
) : null}
<PairScanStoppedError scanState={scanState} />
{scanState.status === "stopped" ? (
<Button
style={styles.scanAgainButton}
@@ -231,3 +237,34 @@ export function PairScanContent({
}
const BARCODE_SCANNER_SETTINGS: BarcodeSettings = { barcodeTypes: ["qr"] };
function PairScanStoppedError({ scanState }: { scanState: PairScanState }) {
const { t } = useTranslation();
if (scanState.status !== "stopped") return null;
if (scanState.helloRejection) {
const presentation = resolveHostRefusal({
rejection: scanState.helloRejection,
hostName: scanState.hostName ?? "host",
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
});
return (
<View style={styles.refusalBox} testID="pair-scan-refusal">
<Text style={styles.helperText}>{presentation.title}</Text>
<HostRefusalBody
presentation={presentation}
centered
numberOfLines={3}
testIDPrefix="pair-scan-refusal"
/>
</View>
);
}
if (!scanState.error) return null;
return (
<Text style={styles.helperText} dataDetectorType="none">
{scanState.error}
</Text>
);
}
+9 -1
View File
@@ -10,6 +10,7 @@ import {
type HostConnectionKind,
} from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { resolveHostRefusal } from "@/hosts/host-refusal";
import { HostStatusIcon } from "@/hosts/host-status-icon";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
@@ -160,9 +161,16 @@ export function HostLatencyLabel({ serverId }: { serverId: string }): ReactEleme
}
if (status === "offline" || status === "error") {
const label = snapshot?.helloRejection
? resolveHostRefusal({
rejection: snapshot.helloRejection,
hostName: serverId,
t,
}).shortStatus
: t("common.connectionStatus.offline");
return (
<Text style={styles.statusText} numberOfLines={1}>
{t("common.connectionStatus.offline")}
{label}
</Text>
);
}
@@ -0,0 +1,221 @@
import { useCallback, useMemo } from "react";
import { useRouter, type Href } from "expo-router";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Settings } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import { Alert as InlineAlert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { getIsElectron, isWeb } from "@/constants/platform";
import { useAddHost } from "@/hosts/add-host";
import { openHostRefusalSheet } from "@/hosts/host-refusal-sheet-state";
import {
getHostRefusalActionLabel,
resolveHostRefusal,
type HostRefusalAction,
} from "@/hosts/host-refusal";
import { HostRefusalBody, HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { buildSettingsSectionRoute } from "@/utils/host-routes";
export { HostRefusalBody, HostRefusalInlineAlert };
export function useHostRefusalAction(serverId: string): (action: HostRefusalAction) => void {
const router = useRouter();
const openPairLink = useAddHost({ method: "link" });
const openScanQr = useAddHost({ method: "scan" });
return useCallback(
(action: HostRefusalAction) => {
switch (action.kind) {
case "enter_password":
if (serverId) openHostRefusalSheet(serverId);
return;
case "pair_link":
openPairLink();
return;
case "scan_qr":
openScanQr();
return;
case "update_app":
router.push(buildSettingsSectionRoute("about") as Href);
return;
case "retry":
if (serverId) {
void getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
}
return;
}
},
[openPairLink, openScanQr, router, serverId],
);
}
function useHostRefusalBindings(
serverId: string,
hostName: string,
rejection: DaemonHelloRejection,
) {
const { t } = useTranslation();
const runAction = useHostRefusalAction(serverId);
const presentation = useMemo(
() =>
resolveHostRefusal({
rejection,
hostName,
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
}),
[hostName, rejection, t],
);
const handlePrimary = useCallback(() => {
runAction(presentation.primaryAction);
}, [presentation.primaryAction, runAction]);
const handleSecondary = useCallback(() => {
if (presentation.secondaryAction) {
runAction(presentation.secondaryAction);
}
}, [presentation.secondaryAction, runAction]);
return { t, presentation, handlePrimary, handleSecondary };
}
export function HostRefusalAlert({
serverId,
hostName,
rejection,
testID,
}: {
serverId: string;
hostName: string;
rejection: DaemonHelloRejection;
testID?: string;
}) {
const { t, presentation, handlePrimary, handleSecondary } = useHostRefusalBindings(
serverId,
hostName,
rejection,
);
const description = useMemo(
() =>
presentation.description || presentation.hostMessage ? (
<HostRefusalBody presentation={presentation} numberOfLines={3} testIDPrefix={testID} />
) : undefined,
[presentation, testID],
);
return (
<InlineAlert
size="sm"
variant="error"
title={presentation.title}
description={description}
testID={testID}
>
<Button
size="sm"
variant="default"
onPress={handlePrimary}
testID={testID ? `${testID}-primary-action` : undefined}
>
{getHostRefusalActionLabel(presentation.primaryAction, t)}
</Button>
{presentation.secondaryAction ? (
<Button
size="sm"
variant="outline"
onPress={handleSecondary}
testID={testID ? `${testID}-secondary-action` : undefined}
>
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
</Button>
) : null}
</InlineAlert>
);
}
/** Centered full-view refusal state shared by unreachable workspace and agent routes. */
export function HostRefusalEmptyState({
serverId,
hostName,
rejection,
onManageHost,
testID,
testIDPrefix,
}: {
serverId: string;
hostName: string;
rejection: DaemonHelloRejection;
onManageHost: () => void;
testID?: string;
testIDPrefix?: string;
}) {
const { t, presentation, handlePrimary, handleSecondary } = useHostRefusalBindings(
serverId,
hostName,
rejection,
);
return (
<View style={styles.emptyState} testID={testID}>
<View style={styles.textStack}>
<Text style={styles.title}>{presentation.title}</Text>
<HostRefusalBody presentation={presentation} centered testIDPrefix={testIDPrefix} />
</View>
<View style={styles.actions}>
<Button
variant="default"
onPress={handlePrimary}
testID={testIDPrefix ? `${testIDPrefix}-primary-action` : undefined}
>
{getHostRefusalActionLabel(presentation.primaryAction, t)}
</Button>
{presentation.secondaryAction ? (
<Button
variant="outline"
onPress={handleSecondary}
testID={testIDPrefix ? `${testIDPrefix}-secondary-action` : undefined}
>
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
</Button>
) : null}
<Button variant="outline" leftIcon={Settings} onPress={onManageHost}>
{t("workspace.route.manageHost")}
</Button>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
emptyState: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: theme.spacing[6],
gap: theme.spacing[4],
},
textStack: {
alignItems: "center",
gap: theme.spacing[2],
maxWidth: 420,
},
title: {
fontSize: theme.fontSize.lg,
fontWeight: theme.fontWeight.semibold,
color: theme.colors.foreground,
textAlign: "center",
},
actions: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[2],
},
}));
@@ -0,0 +1,93 @@
import { useMemo } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Alert as InlineAlert } from "@/components/ui/alert";
import type { HostRefusalPresentation } from "@/hosts/host-refusal";
export function HostRefusalBody({
presentation,
centered = false,
numberOfLines,
testIDPrefix,
}: {
presentation: HostRefusalPresentation;
centered?: boolean;
numberOfLines?: number;
testIDPrefix?: string;
}) {
if (!presentation.description && !presentation.hostMessage) return null;
return (
<View style={[styles.body, centered && styles.bodyCentered]}>
{presentation.description ? (
<Text
dataDetectorType="none"
numberOfLines={numberOfLines}
style={[styles.description, centered && styles.textCentered]}
testID={testIDPrefix ? `${testIDPrefix}-description` : undefined}
>
{presentation.description}
</Text>
) : null}
{presentation.hostMessage ? (
<Text
dataDetectorType="none"
numberOfLines={numberOfLines}
style={[styles.hostMessage, centered && styles.textCentered]}
testID={testIDPrefix ? `${testIDPrefix}-host-message` : undefined}
>
{presentation.hostMessage}
</Text>
) : null}
</View>
);
}
/** Inline refusal alert without action buttons (used in pairing sheets). */
export function HostRefusalInlineAlert({
presentation,
testID,
}: {
presentation: HostRefusalPresentation;
testID?: string;
}) {
const description = useMemo(
() =>
presentation.description || presentation.hostMessage ? (
<HostRefusalBody presentation={presentation} numberOfLines={3} testIDPrefix={testID} />
) : undefined,
[presentation, testID],
);
return (
<InlineAlert
size="sm"
variant="error"
title={presentation.title}
description={description}
testID={testID}
/>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[1],
},
bodyCentered: {
alignItems: "center",
},
description: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: Math.round(theme.fontSize.sm * 1.4),
},
hostMessage: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: Math.round(theme.fontSize.sm * 1.4),
},
textCentered: {
textAlign: "center",
},
}));
@@ -0,0 +1,286 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import {
dismissHostRefusalSheet,
getActiveRefusalHostServerId,
openHostRefusalSheet,
registerActiveRefusalHost,
resetHostRefusalSheetState,
resolveHostRefusalSheetTarget,
setHostRefusalFailed,
setHostRefusalSubmitting,
useHostRefusalSheetStore,
type HostRefusalSnapshotSummary,
} from "./host-refusal-sheet-state";
const PASSWORD_REJECTION: DaemonHelloRejection = {
reason: "incorrect_password",
accepts: ["password"],
};
const EMPTY_SNAPSHOT: HostRefusalSnapshotSummary = {
rejection: null,
episode: 0,
isOnline: false,
};
describe("host-refusal-sheet-state", () => {
beforeEach(() => {
resetHostRefusalSheetState();
});
it("auto-pops for the active host when refused and stays quiet when no host is active", () => {
expect(
resolveHostRefusalSheetTarget({
activeServerId: null,
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes: {},
hasPendingConfirmation: false,
}),
).toBeNull();
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes: {},
hasPendingConfirmation: false,
}),
).toEqual({
serverId: "srv_active",
rejection: PASSWORD_REJECTION,
episode: 1,
isManual: false,
actionErrorMessage: null,
});
});
it("stays dismissed for the same refusal episode and re-pops on a new episode", () => {
dismissHostRefusalSheet("srv_active", 1);
const { dismissedEpisodes } = useHostRefusalSheetStore.getState();
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes,
hasPendingConfirmation: false,
}),
).toBeNull();
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 2 },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes,
hasPendingConfirmation: false,
}),
).toEqual({
serverId: "srv_active",
rejection: PASSWORD_REJECTION,
episode: 2,
isManual: false,
actionErrorMessage: null,
});
});
it("never cross-contaminates an online active host when another host has a stale manualOpen and refuses in background", () => {
openHostRefusalSheet("srv_staging", 1);
const state = useHostRefusalSheetStore.getState();
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_local",
activeSnapshot: EMPTY_SNAPSHOT,
manualOpen: state.manualOpen,
manualSnapshot: { rejection: PASSWORD_REJECTION, episode: 3 },
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes: state.dismissedEpisodes,
hasPendingConfirmation: false,
}),
).toBeNull();
});
it("reopens a dismissed episode when opened explicitly and keeps submitting mounted across transient clears", () => {
dismissHostRefusalSheet("srv_active", 1);
openHostRefusalSheet("srv_active", 1);
const state = useHostRefusalSheetStore.getState();
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
manualOpen: state.manualOpen,
manualSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes: state.dismissedEpisodes,
hasPendingConfirmation: false,
}),
).toEqual({
serverId: "srv_active",
rejection: PASSWORD_REJECTION,
episode: 1,
isManual: true,
actionErrorMessage: null,
});
setHostRefusalSubmitting("srv_active");
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: EMPTY_SNAPSHOT,
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: "srv_active",
submittingSnapshot: { rejection: null, episode: 1 },
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes: state.dismissedEpisodes,
hasPendingConfirmation: false,
}),
).toEqual({
serverId: "srv_active",
rejection: null,
episode: 1,
isManual: false,
actionErrorMessage: null,
});
});
it("keeps the sheet open with an actionable error after a failed retry or submit and expires once the host recovers", () => {
setHostRefusalFailed({
serverId: "srv_active",
message: "Unable to connect to host",
rejection: PASSWORD_REJECTION,
connectionEpoch: 1,
});
const { failedAction } = useHostRefusalSheetStore.getState();
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: EMPTY_SNAPSHOT,
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction,
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 1, isOnline: false },
dismissedEpisodes: {},
hasPendingConfirmation: false,
}),
).toEqual({
serverId: "srv_active",
rejection: PASSWORD_REJECTION,
episode: 1,
isManual: true,
actionErrorMessage: "Unable to connect to host",
});
// Auto-closes once the host comes back online (connectionEpoch increments to 2).
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_active",
activeSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: true },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction,
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: true },
dismissedEpisodes: {},
hasPendingConfirmation: false,
}),
).toBeNull();
// Even if that host later disconnects normally (still epoch 2, offline, no refusal), the stale
// failedAction from epoch 1 never reactivates or blocks another host's refusal sheet.
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_other",
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1, connectionEpoch: 0 },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction,
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: false },
dismissedEpisodes: {},
hasPendingConfirmation: false,
}),
).toEqual({
serverId: "srv_other",
rejection: PASSWORD_REJECTION,
episode: 1,
isManual: false,
actionErrorMessage: null,
});
// Explicitly opening another host's sheet also clears any prior failedAction immediately.
openHostRefusalSheet("srv_other", 1);
expect(useHostRefusalSheetStore.getState().failedAction).toBeNull();
});
it("defers when a HostConfirmationSheet is active and stacks active scopes cleanly", () => {
const unregisterFirst = registerActiveRefusalHost("srv_local");
const unregisterSecond = registerActiveRefusalHost("srv_staging");
expect(getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes)).toBe(
"srv_staging",
);
expect(
resolveHostRefusalSheetTarget({
activeServerId: "srv_staging",
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
manualOpen: null,
manualSnapshot: EMPTY_SNAPSHOT,
submittingServerId: null,
submittingSnapshot: EMPTY_SNAPSHOT,
failedAction: null,
failedSnapshot: EMPTY_SNAPSHOT,
dismissedEpisodes: {},
hasPendingConfirmation: true,
}),
).toBeNull();
unregisterSecond();
expect(getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes)).toBe(
"srv_local",
);
unregisterFirst();
expect(
getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes),
).toBeNull();
});
});
@@ -0,0 +1,234 @@
import { useEffect } from "react";
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import { create } from "zustand";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
export interface ActiveRefusalHostScope {
id: number;
serverId: string;
}
export interface ManualRefusalSheetOpen {
serverId: string;
episode: number;
}
export interface FailedRefusalSheetAction {
serverId: string;
message: string;
rejection: DaemonHelloRejection;
connectionEpoch: number;
}
export interface HostRefusalSnapshotSummary {
rejection: DaemonHelloRejection | null;
episode: number;
connectionEpoch?: number;
isOnline?: boolean;
}
export interface HostRefusalSheetState {
activeScopes: ActiveRefusalHostScope[];
manualOpen: ManualRefusalSheetOpen | null;
submittingServerId: string | null;
failedAction: FailedRefusalSheetAction | null;
dismissedEpisodes: Record<string, number>;
}
export interface ResolveHostRefusalSheetTargetInput {
activeServerId: string | null;
activeSnapshot: HostRefusalSnapshotSummary;
manualOpen: ManualRefusalSheetOpen | null;
manualSnapshot: HostRefusalSnapshotSummary;
submittingServerId: string | null;
submittingSnapshot: HostRefusalSnapshotSummary;
failedAction: FailedRefusalSheetAction | null;
failedSnapshot: HostRefusalSnapshotSummary;
dismissedEpisodes: Readonly<Record<string, number>>;
hasPendingConfirmation: boolean;
}
export interface HostRefusalSheetTarget {
serverId: string;
rejection: DaemonHelloRejection | null;
episode: number;
isManual: boolean;
actionErrorMessage: string | null;
}
let nextScopeId = 1;
function createInitialState(): HostRefusalSheetState {
return {
activeScopes: [],
manualOpen: null,
submittingServerId: null,
failedAction: null,
dismissedEpisodes: {},
};
}
export const useHostRefusalSheetStore = create<HostRefusalSheetState>(() => createInitialState());
export function getActiveRefusalHostServerId(
activeScopes: readonly ActiveRefusalHostScope[],
): string | null {
return activeScopes.length > 0 ? activeScopes[activeScopes.length - 1].serverId : null;
}
export function resolveHostRefusalSheetTarget(
input: ResolveHostRefusalSheetTargetInput,
): HostRefusalSheetTarget | null {
if (input.hasPendingConfirmation) return null;
if (input.submittingServerId) {
return {
serverId: input.submittingServerId,
rejection: input.submittingSnapshot.rejection,
episode: input.submittingSnapshot.episode,
isManual: input.manualOpen?.serverId === input.submittingServerId,
actionErrorMessage: null,
};
}
if (
input.failedAction &&
!input.failedSnapshot.isOnline &&
(input.failedSnapshot.connectionEpoch ?? 0) === input.failedAction.connectionEpoch
) {
return {
serverId: input.failedAction.serverId,
rejection: input.failedSnapshot.rejection ?? input.failedAction.rejection,
episode: input.failedSnapshot.episode,
isManual: true,
actionErrorMessage: input.failedAction.message,
};
}
if (
input.manualOpen &&
input.manualSnapshot.rejection !== null &&
input.manualSnapshot.episode === input.manualOpen.episode
) {
return {
serverId: input.manualOpen.serverId,
rejection: input.manualSnapshot.rejection,
episode: input.manualSnapshot.episode,
isManual: true,
actionErrorMessage: null,
};
}
if (
input.activeServerId &&
input.activeSnapshot.rejection !== null &&
input.dismissedEpisodes[input.activeServerId] !== input.activeSnapshot.episode
) {
return {
serverId: input.activeServerId,
rejection: input.activeSnapshot.rejection,
episode: input.activeSnapshot.episode,
isManual: false,
actionErrorMessage: null,
};
}
return null;
}
export function registerActiveRefusalHost(serverId: string): () => void {
const normalized = serverId.trim();
if (!normalized) return () => {};
const id = nextScopeId++;
useHostRefusalSheetStore.setState((state) => ({
activeScopes: [...state.activeScopes, { id, serverId: normalized }],
}));
return () => {
useHostRefusalSheetStore.setState((state) => ({
activeScopes: state.activeScopes.filter((entry) => entry.id !== id),
}));
};
}
export function useActiveRefusalHost(serverId: string | null | undefined, enabled = true): void {
const normalized = serverId?.trim() ?? "";
useEffect(() => {
if (!enabled || !normalized) return;
return registerActiveRefusalHost(normalized);
}, [enabled, normalized]);
}
export function openHostRefusalSheet(serverId: string, episode?: number): void {
const normalized = serverId.trim();
if (!normalized) return;
const resolvedEpisode =
episode ?? getHostRuntimeStore().getSnapshot(normalized)?.helloRejectionEpisode ?? 0;
useHostRefusalSheetStore.setState((state) => {
const nextDismissed = { ...state.dismissedEpisodes };
delete nextDismissed[normalized];
return {
manualOpen: { serverId: normalized, episode: resolvedEpisode },
failedAction: null,
dismissedEpisodes: nextDismissed,
};
});
}
export function dismissHostRefusalSheet(serverId: string, episode: number): void {
const normalized = serverId.trim();
if (!normalized) return;
useHostRefusalSheetStore.setState((state) => ({
manualOpen: state.manualOpen?.serverId === normalized ? null : state.manualOpen,
submittingServerId: state.submittingServerId === normalized ? null : state.submittingServerId,
failedAction: state.failedAction?.serverId === normalized ? null : state.failedAction,
dismissedEpisodes: {
...state.dismissedEpisodes,
[normalized]: episode,
},
}));
}
export function setHostRefusalSubmitting(serverId: string | null): void {
useHostRefusalSheetStore.setState((state) => ({
submittingServerId: serverId,
failedAction:
serverId !== null && state.failedAction?.serverId === serverId ? null : state.failedAction,
}));
}
export function setHostRefusalFailed(input: {
serverId: string;
message: string;
rejection: DaemonHelloRejection;
connectionEpoch?: number;
}): void {
const normalized = input.serverId.trim();
if (!normalized) return;
const connectionEpoch =
input.connectionEpoch ?? getHostRuntimeStore().getSnapshot(normalized)?.connectionEpoch ?? 0;
useHostRefusalSheetStore.setState({
failedAction: {
serverId: normalized,
message: input.message,
rejection: input.rejection,
connectionEpoch,
},
});
}
export function clearHostRefusalFailed(serverId: string): void {
useHostRefusalSheetStore.setState((state) =>
state.failedAction?.serverId === serverId ? { failedAction: null } : state,
);
}
export function clearManualHostRefusalOpen(serverId: string): void {
useHostRefusalSheetStore.setState((state) =>
state.manualOpen?.serverId === serverId ? { manualOpen: null } : state,
);
}
export function resetHostRefusalSheetState(): void {
nextScopeId = 1;
useHostRefusalSheetStore.setState(createInitialState());
}
@@ -0,0 +1,611 @@
import { useCallback, useMemo, useReducer, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Text,
View,
type PressableStateCallbackType,
type StyleProp,
type ViewStyle,
} from "react-native";
import { AlertTriangle, Eye, EyeOff } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import {
AdaptiveModalSheet,
SheetHeaderSubtitle,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
import { Alert as InlineAlert } from "@/components/ui/alert";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { Button } from "@/components/ui/button";
import {
CONTROL_HEIGHTS,
createControlGeometry,
resolveControlInteractionStyles,
} from "@/components/ui/control-geometry";
import { Field, FormTextInput } from "@/components/ui/form-field";
import { iconButtonChromeGlyphSize } from "@/components/ui/icon-button-chrome";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useIsCompactFormFactor } from "@/constants/layout";
import { getIsElectron, isWeb } from "@/constants/platform";
import {
getHostRefusalActionLabel,
isPasswordRefusal,
resolveHostRefusal,
type HostRefusalAction,
} from "@/hosts/host-refusal";
import { useHostRefusalAction } from "@/hosts/host-refusal-alert";
import {
clearHostRefusalFailed,
clearManualHostRefusalOpen,
dismissHostRefusalSheet,
getActiveRefusalHostServerId,
openHostRefusalSheet,
resolveHostRefusalSheetTarget,
setHostRefusalFailed,
setHostRefusalSubmitting,
useHostRefusalSheetStore,
} from "@/hosts/host-refusal-sheet-state";
import {
getHostRuntimeStore,
useHostConfirmation,
useHostMutations,
useHostRuntimeHelloRejection,
useHostRuntimeSnapshot,
useHosts,
} from "@/runtime/host-runtime";
import type { ShortcutKey } from "@/utils/format-shortcut";
const FLEX_ONE_STYLE = { flex: 1 } as const;
const NO_SHORTCUT: ShortcutKey[] = [];
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedAlertTriangle = withUnistyles(AlertTriangle, (theme) => ({
color: theme.colors.destructive,
}));
function toRefusalSnapshotSummary(snapshot: ReturnType<typeof useHostRuntimeSnapshot>): {
rejection: DaemonHelloRejection | null;
episode: number;
connectionEpoch: number;
isOnline: boolean;
} {
return {
rejection: snapshot?.helloRejection ?? null,
episode: snapshot?.helloRejectionEpisode ?? 0,
connectionEpoch: snapshot?.connectionEpoch ?? 0,
isOnline: snapshot?.connectionStatus === "online",
};
}
/**
* Mount once at the app root. Auto-pops for the active host when refused, stays quiet for
* background hosts, and reopens on explicit user action.
*/
export function HostRefusalSheetHost() {
const activeScopes = useHostRefusalSheetStore((state) => state.activeScopes);
const manualOpen = useHostRefusalSheetStore((state) => state.manualOpen);
const submittingServerId = useHostRefusalSheetStore((state) => state.submittingServerId);
const failedAction = useHostRefusalSheetStore((state) => state.failedAction);
const dismissedEpisodes = useHostRefusalSheetStore((state) => state.dismissedEpisodes);
const { pending: pendingConfirmation } = useHostConfirmation();
const activeServerId = getActiveRefusalHostServerId(activeScopes);
const activeSnapshot = useHostRuntimeSnapshot(activeServerId ?? "");
const manualSnapshot = useHostRuntimeSnapshot(manualOpen?.serverId ?? "");
const submittingSnapshot = useHostRuntimeSnapshot(submittingServerId ?? "");
const failedSnapshot = useHostRuntimeSnapshot(failedAction?.serverId ?? "");
const target = resolveHostRefusalSheetTarget({
activeServerId,
activeSnapshot: toRefusalSnapshotSummary(activeSnapshot),
manualOpen,
manualSnapshot: toRefusalSnapshotSummary(manualSnapshot),
submittingServerId,
submittingSnapshot: toRefusalSnapshotSummary(submittingSnapshot),
failedAction,
failedSnapshot: toRefusalSnapshotSummary(failedSnapshot),
dismissedEpisodes,
hasPendingConfirmation: pendingConfirmation !== null,
});
if (!target) return null;
return (
<HostRefusalSheet
key={target.serverId}
serverId={target.serverId}
rejection={target.rejection}
episode={target.episode}
actionErrorMessage={target.actionErrorMessage}
/>
);
}
/** Compact warning icon button in workspace headers that reopens `HostRefusalSheet`. */
export function HostRefusalHeaderButton({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const rejection = useHostRuntimeHelloRejection(serverId);
const hosts = useHosts();
const hostName = useMemo(
() => hosts.find((entry) => entry.serverId === serverId)?.label?.trim() || serverId,
[hosts, serverId],
);
const handlePress = useCallback(() => {
if (serverId) openHostRefusalSheet(serverId);
}, [serverId]);
if (!serverId || !rejection) return null;
const presentation = resolveHostRefusal({
rejection,
hostName,
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
});
return (
<HeaderToggleButton
onPress={handlePress}
tooltipLabel={presentation.shortStatus}
tooltipKeys={NO_SHORTCUT}
tooltipSide="bottom"
accessibilityRole="button"
accessibilityLabel={presentation.shortStatus}
testID="workspace-refusal-header-button"
>
<ThemedAlertTriangle size={iconButtonChromeGlyphSize("large")} />
</HeaderToggleButton>
);
}
interface HostRefusalSheetProps {
serverId: string;
rejection: DaemonHelloRejection | null;
episode: number;
actionErrorMessage: string | null;
}
function HostRefusalSheet({
serverId,
rejection,
episode,
actionErrorMessage,
}: HostRefusalSheetProps) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const hosts = useHosts();
const { submitHostPassword } = useHostMutations();
const runRefusalAction = useHostRefusalAction(serverId);
const hostName = useMemo(
() => hosts.find((entry) => entry.serverId === serverId)?.label?.trim() || serverId,
[hosts, serverId],
);
const controlSize = isCompact ? "md" : "sm";
const [retainedRejection, setRetainedRejection] = useState<DaemonHelloRejection | null>(
rejection,
);
if (rejection !== null && rejection !== retainedRejection) {
setRetainedRejection(rejection);
}
const effectiveRejection = rejection ?? retainedRejection;
const [password, setPassword] = useState("");
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [resetCount, bumpResetCount] = useReducer((count: number) => count + 1, 0);
const presentation = useMemo(
() =>
effectiveRejection
? resolveHostRefusal({
rejection: effectiveRejection,
hostName,
t,
canUpdateApp: getIsElectron(),
canScanQr: !isWeb,
})
: null,
[effectiveRejection, hostName, t],
);
const showPasswordForm = effectiveRejection !== null && isPasswordRefusal(effectiveRejection);
const header = useMemo<SheetHeader>(
() => ({
title: presentation?.title ?? "",
titleTestID: "host-refusal-sheet-title",
subtitle: <SheetHeaderSubtitle text={hostName} testID="host-refusal-sheet-host" />,
}),
[hostName, presentation?.title],
);
const handleDismiss = useCallback(() => {
if (isSubmitting) return;
dismissHostRefusalSheet(serverId, episode);
}, [episode, isSubmitting, serverId]);
const handlePasswordChange = useCallback((value: string) => {
setPassword(value);
setErrorMessage(null);
}, []);
const handleToggleVisibility = useCallback(() => {
setIsPasswordVisible((visible) => !visible);
}, []);
const handlePasswordSubmit = useCallback(async () => {
if (isSubmitting) return;
if (password.length === 0) {
setErrorMessage(t("hostRefusal.passwordSheet.requiredError"));
return;
}
setIsSubmitting(true);
setHostRefusalSubmitting(serverId);
setErrorMessage(null);
try {
const result = await submitHostPassword(serverId, password);
if (result.status === "online") {
clearManualHostRefusalOpen(serverId);
clearHostRefusalFailed(serverId);
return;
}
if (result.status === "rejected") {
clearHostRefusalFailed(serverId);
if (useHostRefusalSheetStore.getState().manualOpen?.serverId === serverId) {
openHostRefusalSheet(serverId);
}
if (result.rejection.reason === "incorrect_password") {
setPassword("");
bumpResetCount();
setErrorMessage(t("hostRefusal.incorrectPassword.title"));
return;
}
setErrorMessage(null);
return;
}
const message = result.message || t("pairing.direct.errors.unableToConnect");
if (effectiveRejection) {
setHostRefusalFailed({ serverId, message, rejection: effectiveRejection });
}
setErrorMessage(message);
} finally {
setHostRefusalSubmitting(null);
setIsSubmitting(false);
}
}, [effectiveRejection, isSubmitting, password, serverId, submitHostPassword, t]);
const handleSubmitPress = useCallback(() => {
void handlePasswordSubmit();
}, [handlePasswordSubmit]);
const executeNonPasswordAction = useCallback(
async (action: HostRefusalAction) => {
if (isSubmitting) return;
if (action.kind === "retry") {
setIsSubmitting(true);
setHostRefusalSubmitting(serverId);
try {
await getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
const next = getHostRuntimeStore().getSnapshot(serverId);
if (next?.connectionStatus === "online") {
clearManualHostRefusalOpen(serverId);
clearHostRefusalFailed(serverId);
} else if (next?.helloRejection) {
clearHostRefusalFailed(serverId);
} else {
const message = next?.lastError?.trim() || t("pairing.direct.errors.unableToConnect");
if (effectiveRejection) {
setHostRefusalFailed({
serverId,
message,
rejection: effectiveRejection,
connectionEpoch: next?.connectionEpoch,
});
}
}
} finally {
setHostRefusalSubmitting(null);
setIsSubmitting(false);
}
return;
}
dismissHostRefusalSheet(serverId, episode);
runRefusalAction(action);
},
[effectiveRejection, episode, isSubmitting, runRefusalAction, serverId, t],
);
const handlePrimaryPress = useCallback(() => {
if (!presentation) return;
void executeNonPasswordAction(presentation.primaryAction);
}, [executeNonPasswordAction, presentation]);
const handleSecondaryPress = useCallback(() => {
if (!presentation?.secondaryAction) return;
void executeNonPasswordAction(presentation.secondaryAction);
}, [executeNonPasswordAction, presentation]);
const primaryButtonLabel = useMemo(() => {
if (isSubmitting) return t("hostRefusal.passwordSheet.connecting");
if (showPasswordForm) return t("hostRefusal.passwordSheet.connect");
return presentation ? getHostRefusalActionLabel(presentation.primaryAction, t) : "";
}, [isSubmitting, presentation, showPasswordForm, t]);
const footer = useMemo(
() => (
<View style={styles.footer}>
<Button
style={FLEX_ONE_STYLE}
variant="secondary"
size={controlSize}
onPress={handleDismiss}
disabled={isSubmitting}
testID="host-refusal-sheet-dismiss"
>
{t("common.actions.dismiss")}
</Button>
<Button
style={FLEX_ONE_STYLE}
variant="default"
size={controlSize}
onPress={showPasswordForm ? handleSubmitPress : handlePrimaryPress}
disabled={isSubmitting}
testID={
showPasswordForm ? "host-refusal-sheet-submit" : "host-refusal-sheet-primary-action"
}
>
{primaryButtonLabel}
</Button>
</View>
),
[
controlSize,
handleDismiss,
handlePrimaryPress,
handleSubmitPress,
isSubmitting,
primaryButtonLabel,
showPasswordForm,
t,
],
);
if (!effectiveRejection || !presentation) return null;
return (
<AdaptiveModalSheet
header={header}
visible
onClose={handleDismiss}
footer={footer}
testID="host-refusal-sheet"
>
<View style={styles.content}>
{presentation.description ? (
<Text
dataDetectorType="none"
style={styles.description}
testID="host-refusal-sheet-description"
>
{presentation.description}
</Text>
) : null}
{presentation.hostMessage ? (
<View style={styles.hostMessageCard}>
<Text
dataDetectorType="none"
style={styles.hostMessage}
testID="host-refusal-sheet-host-message"
>
{presentation.hostMessage}
</Text>
</View>
) : null}
{showPasswordForm ? (
<HostRefusalPasswordField
serverId={serverId}
controlSize={controlSize}
resetCount={resetCount}
errorMessage={errorMessage ?? actionErrorMessage}
isPasswordVisible={isPasswordVisible}
isSubmitting={isSubmitting}
onChangeText={handlePasswordChange}
onToggleVisibility={handleToggleVisibility}
onSubmit={handleSubmitPress}
/>
) : null}
{!showPasswordForm && actionErrorMessage ? (
<InlineAlert
size="sm"
variant="error"
title={actionErrorMessage}
testID="host-refusal-sheet-error"
/>
) : null}
{!showPasswordForm && presentation.secondaryAction ? (
<Button
variant="outline"
size={controlSize}
onPress={handleSecondaryPress}
disabled={isSubmitting}
testID="host-refusal-sheet-secondary-action"
>
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
</Button>
) : null}
</View>
</AdaptiveModalSheet>
);
}
function HostRefusalPasswordField({
serverId,
controlSize,
resetCount,
errorMessage,
isPasswordVisible,
isSubmitting,
onChangeText,
onToggleVisibility,
onSubmit,
}: {
serverId: string;
controlSize: "sm" | "md";
resetCount: number;
errorMessage: string | null;
isPasswordVisible: boolean;
isSubmitting: boolean;
onChangeText: (value: string) => void;
onToggleVisibility: () => void;
onSubmit: () => void;
}) {
const { t } = useTranslation();
const iconButtonStyle = useCallback(
(
state: PressableStateCallbackType & { hovered?: boolean; focused?: boolean },
): StyleProp<ViewStyle> => [
styles.iconButton,
controlSize === "sm" ? styles.iconButtonSm : styles.iconButtonMd,
resolveControlInteractionStyles(
{
controlRest: styles.controlRest,
controlHover: styles.controlHover,
controlActive: styles.controlActive,
controlDisabled: styles.controlDisabled,
},
{
hovered: state.hovered,
pressed: state.pressed,
focused: state.focused,
disabled: isSubmitting,
},
),
],
[controlSize, isSubmitting],
);
return (
<Field
label={t("hostRefusal.passwordSheet.label")}
error={errorMessage}
testID="host-password-field"
>
<View style={styles.passwordRow}>
<View style={styles.passwordInputWrap}>
<FormTextInput
testID="host-password-input"
nativeID="host-password-input"
size={controlSize}
resetKey={`host-password-${serverId}-${resetCount}`}
initialValue=""
accessibilityLabel={t("hostRefusal.passwordSheet.label")}
placeholder={t("hostRefusal.passwordSheet.placeholder")}
onChangeText={onChangeText}
autoFocus
secureTextEntry={!isPasswordVisible}
autoCapitalize="none"
autoCorrect={false}
editable={!isSubmitting}
invalid={errorMessage !== null}
returnKeyType="done"
onSubmitEditing={onSubmit}
/>
</View>
<PressHighlight
style={iconButtonStyle}
onPress={onToggleVisibility}
disabled={isSubmitting}
accessibilityRole="button"
accessibilityLabel={
isPasswordVisible
? t("pairing.direct.passwordVisibility.hide")
: t("pairing.direct.passwordVisibility.show")
}
testID="host-password-visibility-toggle"
>
{isPasswordVisible ? <ThemedEyeOff size={18} /> : <ThemedEye size={18} />}
</PressHighlight>
</View>
</Field>
);
}
const styles = StyleSheet.create((theme) => {
const geometry = createControlGeometry(theme);
return {
content: {
gap: theme.spacing[4],
},
description: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
lineHeight: Math.round(theme.fontSize.base * 1.45),
},
hostMessageCard: {
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[3],
},
hostMessage: {
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
lineHeight: Math.round(theme.fontSize.sm * 1.45),
},
passwordRow: {
flexDirection: "row",
alignItems: "center",
alignSelf: "stretch",
width: "100%",
gap: theme.spacing[2],
},
passwordInputWrap: {
flex: 1,
minWidth: 0,
},
iconButton: {
alignItems: "center",
justifyContent: "center",
borderRadius: theme.borderRadius.lg,
backgroundColor: theme.colors.surface2,
},
iconButtonSm: {
minHeight: CONTROL_HEIGHTS.sm,
width: CONTROL_HEIGHTS.sm,
},
iconButtonMd: {
minHeight: CONTROL_HEIGHTS.md,
width: CONTROL_HEIGHTS.md,
},
controlRest: {
...geometry.controlRest,
},
controlHover: {
...geometry.controlHover,
},
controlActive: {
...geometry.controlActive,
},
controlDisabled: {
...geometry.controlDisabled,
},
footer: {
flex: 1,
flexDirection: "row",
gap: theme.spacing[3],
},
};
});
+231
View File
@@ -0,0 +1,231 @@
import { describe, expect, it } from "vitest";
import type { TFunction } from "i18next";
import { en } from "@/i18n/resources/en";
import {
SUPPORTED_CREDENTIAL_KINDS,
getHostRefusalActionLabel,
isPasswordRefusal,
resolveHostRefusal,
} from "./host-refusal";
function createTestT(): TFunction {
const resolveKey = (key: string): string => {
const parts = key.split(".");
let current: unknown = en;
for (const part of parts) {
if (current && typeof current === "object" && part in current) {
current = (current as Record<string, unknown>)[part];
} else {
throw new Error(`Missing i18n key in en: ${key}`);
}
}
if (typeof current !== "string") {
throw new Error(`Expected string for i18n key: ${key}`);
}
return current;
};
return ((key: string, params?: Record<string, unknown>) => {
let text = resolveKey(key);
if (params) {
for (const [name, value] of Object.entries(params)) {
text = text.replaceAll(`{{${name}}}`, String(value));
}
}
return text;
}) as unknown as TFunction;
}
describe("resolveHostRefusal", () => {
const t = createTestT();
it("uses trusted localized copy and ignores host message for known reasons", () => {
const passwordRequired = resolveHostRefusal({
rejection: {
reason: "password_required",
accepts: ["password"],
message: "Visit https://evil.test for password",
},
hostName: "Dev Box",
t,
});
expect(passwordRequired).toEqual({
title: "Password required",
description: "Enter this host's password to connect.",
hostMessage: null,
shortStatus: "Password required",
primaryAction: { kind: "enter_password" },
});
const incorrectPassword = resolveHostRefusal({
rejection: {
reason: "incorrect_password",
accepts: ["password"],
message: "Phishing text",
},
hostName: "Dev Box",
t,
});
expect(incorrectPassword).toEqual({
title: "Incorrect password",
description: "The saved password was rejected by this host.",
hostMessage: null,
shortStatus: "Password required",
primaryAction: { kind: "enter_password" },
});
const incompatibleDesktop = resolveHostRefusal({
rejection: {
reason: "incompatible_protocol",
accepts: [],
message: "Download from https://evil.test",
},
hostName: "Dev Box",
t,
canUpdateApp: true,
});
expect(incompatibleDesktop).toEqual({
title: "Update Paseo to connect",
description: "This host requires a newer version of Paseo.",
hostMessage: null,
shortStatus: "Update required",
primaryAction: { kind: "update_app" },
});
const incompatibleWeb = resolveHostRefusal({
rejection: {
reason: "incompatible_protocol",
accepts: [],
},
hostName: "Dev Box",
t,
canUpdateApp: false,
});
expect(incompatibleWeb.primaryAction).toEqual({ kind: "retry" });
});
it("offers password recovery when an unknown reason accepts password", () => {
const result = resolveHostRefusal({
rejection: {
reason: "password_expired",
accepts: ["password"],
message: "Rotate your password.",
},
hostName: "Staging",
t,
});
expect(result).toEqual({
title: "Password required",
description: null,
hostMessage: "Message from Staging: “Rotate your password.”",
shortStatus: "Password required",
primaryAction: { kind: "enter_password" },
});
expect(isPasswordRefusal({ reason: "password_expired", accepts: ["password"] })).toBe(true);
});
it("asks to update Paseo when an unknown reason requires an unsupported credential kind", () => {
expect(SUPPORTED_CREDENTIAL_KINDS).toEqual(["password"]);
const result = resolveHostRefusal({
rejection: {
reason: "pairing_required",
accepts: ["invite"],
message: "Visit https://evil.test",
},
hostName: "Prod Box",
t,
canUpdateApp: true,
});
expect(result).toEqual({
title: "Update Paseo to connect",
description: "This host requires a sign-in method this version of Paseo does not support.",
hostMessage: "Message from Prod Box: “Visit https://evil.test”",
shortStatus: "Update required",
primaryAction: { kind: "update_app" },
});
expect(isPasswordRefusal({ reason: "pairing_required", accepts: ["invite"] })).toBe(false);
});
it("automatically offers pairing actions once invite is in supportedCredentials", () => {
const mobile = resolveHostRefusal({
rejection: {
reason: "pairing_required",
accepts: ["invite", "password"],
message: "Device access expired.",
},
hostName: "Prod Box",
t,
supportedCredentials: ["password", "invite"],
canScanQr: true,
});
expect(mobile).toEqual({
title: "Pairing required",
description: null,
hostMessage: "Message from Prod Box: “Device access expired.”",
shortStatus: "Pairing required",
primaryAction: { kind: "scan_qr" },
secondaryAction: { kind: "pair_link" },
});
const desktop = resolveHostRefusal({
rejection: {
reason: "pairing_required",
accepts: ["invite", "password"],
},
hostName: "Prod Box",
t,
supportedCredentials: ["password", "invite"],
canScanQr: false,
});
expect(desktop).toEqual({
title: "Pairing required",
description: "Pair this device with the host again to connect.",
hostMessage: null,
shortStatus: "Pairing required",
primaryAction: { kind: "pair_link" },
secondaryAction: { kind: "enter_password" },
});
});
it("frames unknown non-credential refusals as host speech with Retry", () => {
const withMessage = resolveHostRefusal({
rejection: {
reason: "maintenance",
accepts: [],
message: "Back in 5m",
},
hostName: "Build Server",
t,
});
expect(withMessage).toEqual({
title: "Connection refused by Build Server",
description: null,
hostMessage: "Message from Build Server: “Back in 5m”",
shortStatus: "Refused",
primaryAction: { kind: "retry" },
});
const withoutMessage = resolveHostRefusal({
rejection: {
reason: "maintenance",
accepts: [],
},
hostName: "Build Server",
t,
});
expect(withoutMessage).toEqual({
title: "Connection refused by Build Server",
description: "Check this host's settings and try again.",
hostMessage: null,
shortStatus: "Refused",
primaryAction: { kind: "retry" },
});
});
it("maps every HostRefusalAction to a localized label", () => {
expect(getHostRefusalActionLabel({ kind: "enter_password" }, t)).toBe("Enter password");
expect(getHostRefusalActionLabel({ kind: "pair_link" }, t)).toBe("Paste pairing link");
expect(getHostRefusalActionLabel({ kind: "scan_qr" }, t)).toBe("Scan QR code");
expect(getHostRefusalActionLabel({ kind: "update_app" }, t)).toBe("Check for updates");
expect(getHostRefusalActionLabel({ kind: "retry" }, t)).toBe("Retry");
});
});
+169
View File
@@ -0,0 +1,169 @@
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import type { TFunction } from "i18next";
export const SUPPORTED_CREDENTIAL_KINDS = ["password"] as const;
export type SupportedCredentialKind = (typeof SUPPORTED_CREDENTIAL_KINDS)[number];
export type HostRefusalAction =
| { kind: "enter_password" }
| { kind: "pair_link" }
| { kind: "scan_qr" }
| { kind: "update_app" }
| { kind: "retry" };
export interface HostRefusalPresentation {
readonly title: string;
readonly description: string | null;
readonly hostMessage: string | null;
readonly shortStatus: string;
readonly primaryAction: HostRefusalAction;
readonly secondaryAction?: HostRefusalAction;
}
export interface ResolveHostRefusalOptions {
readonly rejection: DaemonHelloRejection;
readonly hostName: string;
readonly t: TFunction;
readonly supportedCredentials?: readonly string[];
readonly canUpdateApp?: boolean;
readonly canScanQr?: boolean;
}
export function isPasswordRefusal(
rejection: DaemonHelloRejection,
supportedCredentials: readonly string[] = SUPPORTED_CREDENTIAL_KINDS,
): boolean {
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
return true;
}
if (rejection.reason === "incompatible_protocol") {
return false;
}
return supportedCredentials.includes("password") && rejection.accepts.includes("password");
}
function resolveKnownHostRefusal(
reason: string,
t: TFunction,
canUpdateApp: boolean,
): HostRefusalPresentation | null {
// Known reasons ignore rejection.message completely and render only trusted client copy.
if (reason === "password_required") {
return {
title: t("hostRefusal.passwordRequired.title"),
description: t("hostRefusal.passwordRequired.description"),
hostMessage: null,
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
primaryAction: { kind: "enter_password" },
};
}
if (reason === "incorrect_password") {
return {
title: t("hostRefusal.incorrectPassword.title"),
description: t("hostRefusal.incorrectPassword.description"),
hostMessage: null,
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
primaryAction: { kind: "enter_password" },
};
}
if (reason === "incompatible_protocol") {
return {
title: t("hostRefusal.updateRequired.title"),
description: t("hostRefusal.updateRequired.incompatibleDescription"),
hostMessage: null,
shortStatus: t("hostRefusal.shortStatus.updateRequired"),
primaryAction: canUpdateApp ? { kind: "update_app" } : { kind: "retry" },
};
}
return null;
}
function resolveInviteSecondaryAction(
canScanQr: boolean,
acceptsPassword: boolean,
): HostRefusalAction | undefined {
if (canScanQr) return { kind: "pair_link" };
if (acceptsPassword) return { kind: "enter_password" };
return undefined;
}
export function resolveHostRefusal(options: ResolveHostRefusalOptions): HostRefusalPresentation {
const {
rejection,
hostName,
t,
supportedCredentials = SUPPORTED_CREDENTIAL_KINDS,
canUpdateApp = false,
canScanQr = false,
} = options;
const known = resolveKnownHostRefusal(rejection.reason, t, canUpdateApp);
if (known) return known;
const supportedSet = new Set<string>(supportedCredentials);
const supportedAccepts = rejection.accepts.filter((kind) => supportedSet.has(kind));
const hostMessage = rejection.message
? t("hostRefusal.messageFromHost", { hostName, message: rejection.message })
: null;
if (supportedAccepts.includes("invite")) {
const primaryAction: HostRefusalAction = canScanQr
? { kind: "scan_qr" }
: { kind: "pair_link" };
const secondaryAction = resolveInviteSecondaryAction(
canScanQr,
supportedAccepts.includes("password"),
);
return {
title: t("hostRefusal.pairingRequired.title"),
description: hostMessage ? null : t("hostRefusal.pairingRequired.description"),
hostMessage,
shortStatus: t("hostRefusal.shortStatus.pairingRequired"),
primaryAction,
...(secondaryAction ? { secondaryAction } : {}),
};
}
if (supportedAccepts.includes("password")) {
return {
title: t("hostRefusal.passwordRequired.title"),
description: hostMessage ? null : t("hostRefusal.passwordRequired.description"),
hostMessage,
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
primaryAction: { kind: "enter_password" },
};
}
if (rejection.accepts.length > 0 && supportedAccepts.length === 0) {
return {
title: t("hostRefusal.updateRequired.title"),
description: t("hostRefusal.updateRequired.unsupportedAuthDescription"),
hostMessage,
shortStatus: t("hostRefusal.shortStatus.updateRequired"),
primaryAction: canUpdateApp ? { kind: "update_app" } : { kind: "retry" },
};
}
return {
title: t("hostRefusal.refusedByHost.title", { hostName }),
description: hostMessage ? null : t("hostRefusal.refusedByHost.description"),
hostMessage,
shortStatus: t("hostRefusal.shortStatus.refused"),
primaryAction: { kind: "retry" },
};
}
export function getHostRefusalActionLabel(action: HostRefusalAction, t: TFunction): string {
switch (action.kind) {
case "enter_password":
return t("hostRefusal.actions.enterPassword");
case "pair_link":
return t("hostRefusal.actions.pairLink");
case "scan_qr":
return t("hostRefusal.actions.scanQr");
case "update_app":
return t("hostRefusal.actions.checkForUpdates");
case "retry":
return t("common.actions.retry");
}
}
+117 -8
View File
@@ -2019,17 +2019,67 @@ export const ar: TranslationResources = {
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
confirmAction: "إيقاف",
},
access: {
title: "الوصول",
passwordLabel: "كلمة المرور",
passwordNotSetSummary: "غير مضبوطة",
passwordNotSetHint: "يمكن لأي شخص لديه رابط اقتران الاتصال",
passwordSetSummary: "مضبوطة",
passwordSetHint: "مطلوبة للاتصالات البعيدة",
passwordEnvSummary: "مضبوطة عبر البيئة",
passwordEnvHint: "يتم التحكم بها عبر PASEO_PASSWORD على هذا المضيف",
},
password: {
setTitle: "تعيين كلمة المرور",
changeTitle: "تغيير كلمة المرور",
removeTitle: "إزالة كلمة المرور",
setAction: "تعيين كلمة المرور",
setting: "جارٍ التعيين...",
saveAction: "حفظ كلمة المرور",
saving: "جارٍ الحفظ...",
removeAction: "إزالة كلمة المرور",
removing: "جارٍ الإزالة...",
show: "إظهار كلمة المرور",
hide: "إخفاء كلمة المرور",
setInfo:
"سيتم قطع اتصال الأجهزة البعيدة الأخرى فورًا وستحتاج إلى كلمة المرور هذه. سيبقى هذا الجهاز متصلًا.",
changeInfo:
"سيتم قطع اتصال الأجهزة البعيدة الأخرى فورًا وستحتاج إلى كلمة المرور الجديدة. سيبقى هذا الجهاز متصلًا.",
removeWarning: "سيتمكن أي شخص لديه رابط اقتران أو وصول إلى الشبكة من الاتصال دون كلمة مرور.",
fields: {
current: "كلمة المرور الحالية",
new: "كلمة المرور الجديدة",
confirm: "تأكيد كلمة المرور",
confirmNew: "تأكيد كلمة المرور الجديدة",
},
errors: {
currentRequired: "أدخل كلمة المرور الحالية.",
currentIncorrect: "كلمة المرور الحالية غير صحيحة.",
tooShort: "استخدم 8 أحرف على الأقل.",
tooLong: "يجب أن تكون كلمة المرور 72 بايت أو أقل.",
mismatch: "كلمتا المرور غير متطابقتين.",
},
toast: {
set: "تم تعيين كلمة المرور.",
setDisconnectedOne: "تم تعيين كلمة المرور. تم قطع اتصال جهاز آخر واحد.",
setDisconnectedOther: "تم تعيين كلمة المرور. تم قطع اتصال {{count}} أجهزة أخرى.",
updated: "تم تحديث كلمة المرور.",
updatedDisconnectedOne: "تم تحديث كلمة المرور. تم قطع اتصال جهاز آخر واحد.",
updatedDisconnectedOther: "تم تحديث كلمة المرور. تم قطع اتصال {{count}} أجهزة أخرى.",
removed: "تمت إزالة كلمة المرور.",
},
},
connected: {
title: "العملاء المتصلون",
title: "الأجهزة",
thisDevice: "هذا الجهاز",
loading: "جارٍ تحميل العملاء المتصلين...",
empty: "لا يوجد عملاء متصلون",
unavailable: "تعذّر تحميل العملاء المتصلين",
updateTitle: "حدّث هذا المضيف لعرض العملاء المتصلين",
updateHint: "هذا المضيف لا يبلّغ عن العملاء المتصلين بعد",
loading: "جارٍ تحميل الأجهزة...",
empty: "لا توجد أجهزة متصلة",
unavailable: "تعذّر تحميل الأجهزة",
updateTitle: "حدّث هذا المضيف لعرض الأجهزة المتصلة",
updateHint: "هذا المضيف لا يبلّغ عن الأجهزة المتصلة بعد",
permissionTitle: "مطلوب إذن إدارة الوصول",
permissionHint: "جلستك لا تملك إذن عرض العملاء المتصلين",
errorTitle: "تعذّر تحميل العملاء المتصلين",
permissionHint: "جلستك لا تملك إذن عرض الأجهزة المتصلة",
errorTitle: "تعذّر تحميل الأجهزة",
},
hosts: {
title: "المضيفون المتصلون",
@@ -2062,8 +2112,21 @@ export const ar: TranslationResources = {
hub: "Hub",
plugin: "إضافة",
client: "عميل",
host: "مضيف",
},
auth: {
localMachine: "الجهاز المحلي",
password: "كلمة المرور",
openAccess: "وصول مفتوح",
hub: "Hub",
},
details: {
device: "الجهاز",
app: "التطبيق",
connection: "الاتصال",
ipAddress: "عنوان IP",
auth: "المصادقة",
access: "الوصول",
permissions: "الأذونات",
connected: "متصل",
lastSeen: "آخر اتصال",
@@ -2085,6 +2148,50 @@ export const ar: TranslationResources = {
daysAgo: "منذ {{count}} ي",
},
},
hostRefusal: {
passwordRequired: {
title: "كلمة المرور مطلوبة",
description: "أدخل كلمة مرور هذا المضيف للاتصال.",
},
incorrectPassword: {
title: "كلمة مرور غير صحيحة",
description: "رفض هذا المضيف كلمة المرور المحفوظة.",
},
updateRequired: {
title: "حدّث Paseo للاتصال",
incompatibleDescription: "يتطلب هذا المضيف إصدارًا أحدث من Paseo.",
unsupportedAuthDescription: "يتطلب هذا المضيف طريقة تسجيل دخول لا يدعمها هذا الإصدار من Paseo.",
},
pairingRequired: {
title: "الإقران مطلوب",
description: "أعد إقران هذا الجهاز مع المضيف للاتصال.",
},
refusedByHost: {
title: "رفض {{hostName}} الاتصال",
description: "تحقق من إعدادات هذا المضيف ثم حاول مجددًا.",
},
messageFromHost: "رسالة من {{hostName}}: «{{message}}»",
shortStatus: {
passwordRequired: "كلمة المرور مطلوبة",
updateRequired: "التحديث مطلوب",
pairingRequired: "الإقران مطلوب",
refused: "مرفوض",
},
actions: {
enterPassword: "إدخال كلمة المرور",
pairLink: "لصق رابط الإقران",
scanQr: "مسح رمز QR",
checkForUpdates: "التحقق من التحديثات",
},
passwordSheet: {
title: "كلمة مرور {{hostName}}",
label: "كلمة المرور",
placeholder: "أدخل كلمة مرور المضيف",
connect: "اتصال",
connecting: "جارٍ الاتصال...",
requiredError: "أدخل كلمة مرور للمتابعة.",
},
},
pairing: {
hostPassword: {
title: "كلمة المرور لـ {{host}}",
@@ -2249,6 +2356,8 @@ export const ar: TranslationResources = {
hint: "قم بمسح رمز QR هذا باستخدام Paseo على هاتفك، أو انسخ الرابط أدناه.",
securityWarning:
"تعامل مع رابط الاقتران هذا ككلمة مرور. يمكن لأي شخص يملكه الوصول إلى هذا البرنامج الخفي.",
passwordProtected:
"كلمة المرور مطلوبة. ستقوم الأجهزة التي تمسح هذا الرمز بإدخال كلمة مرور هذا المضيف.",
qrUnavailable: "رمز QR غير متاح.",
qrAccessibility: "رمز QR للإقران",
retry: "أعد المحاولة",
+119 -8
View File
@@ -2049,17 +2049,68 @@ export const en = {
"This device is connected through Tailscale and will lose its connection to the host.",
confirmAction: "Turn off",
},
access: {
title: "Access",
passwordLabel: "Password",
passwordNotSetSummary: "Not set",
passwordNotSetHint: "Anyone with a pairing link can connect",
passwordSetSummary: "Set",
passwordSetHint: "Required for remote connections",
passwordEnvSummary: "Set by environment",
passwordEnvHint: "Controlled by PASEO_PASSWORD on this host",
},
password: {
setTitle: "Set password",
changeTitle: "Change password",
removeTitle: "Remove password",
setAction: "Set password",
setting: "Setting...",
saveAction: "Save password",
saving: "Saving...",
removeAction: "Remove password",
removing: "Removing...",
show: "Show password",
hide: "Hide password",
setInfo:
"Other remote devices disconnect immediately and will need this password. This device stays connected.",
changeInfo:
"Other remote devices disconnect immediately and will need the new password. This device stays connected.",
removeWarning:
"Anyone with a pairing link or network access will be able to connect without a password.",
fields: {
current: "Current password",
new: "New password",
confirm: "Confirm password",
confirmNew: "Confirm new password",
},
errors: {
currentRequired: "Enter the current password.",
currentIncorrect: "Current password is incorrect.",
tooShort: "Use at least 8 characters.",
tooLong: "Password must be 72 bytes or fewer.",
mismatch: "Passwords do not match.",
},
toast: {
set: "Password set.",
setDisconnectedOne: "Password set. Disconnected 1 other device.",
setDisconnectedOther: "Password set. Disconnected {{count}} other devices.",
updated: "Password updated.",
updatedDisconnectedOne: "Password updated. Disconnected 1 other device.",
updatedDisconnectedOther: "Password updated. Disconnected {{count}} other devices.",
removed: "Password removed.",
},
},
connected: {
title: "Connected clients",
title: "Devices",
thisDevice: "This device",
loading: "Loading connected clients...",
empty: "No connected clients",
unavailable: "Unable to load connected clients",
updateTitle: "Update this host to view connected clients",
updateHint: "This host does not report connected clients yet",
loading: "Loading devices...",
empty: "No connected devices",
unavailable: "Unable to load devices",
updateTitle: "Update this host to view connected devices",
updateHint: "This host does not report connected devices yet",
permissionTitle: "Access management required",
permissionHint: "Your session does not have permission to view connected clients",
errorTitle: "Could not load connected clients",
permissionHint: "Your session does not have permission to view connected devices",
errorTitle: "Could not load devices",
},
hosts: {
title: "Connected hosts",
@@ -2092,8 +2143,21 @@ export const en = {
hub: "Hub",
plugin: "Plugin",
client: "Client",
host: "Host",
},
auth: {
localMachine: "Local machine",
password: "Password",
openAccess: "Open access",
hub: "Hub",
},
details: {
device: "Device",
app: "App",
connection: "Connection",
ipAddress: "IP address",
auth: "Auth",
access: "Access",
permissions: "Permissions",
connected: "Connected",
lastSeen: "Last online",
@@ -2115,6 +2179,51 @@ export const en = {
daysAgo: "{{count}}d ago",
},
},
hostRefusal: {
passwordRequired: {
title: "Password required",
description: "Enter this host's password to connect.",
},
incorrectPassword: {
title: "Incorrect password",
description: "The saved password was rejected by this host.",
},
updateRequired: {
title: "Update Paseo to connect",
incompatibleDescription: "This host requires a newer version of Paseo.",
unsupportedAuthDescription:
"This host requires a sign-in method this version of Paseo does not support.",
},
pairingRequired: {
title: "Pairing required",
description: "Pair this device with the host again to connect.",
},
refusedByHost: {
title: "Connection refused by {{hostName}}",
description: "Check this host's settings and try again.",
},
messageFromHost: "Message from {{hostName}}: “{{message}}”",
shortStatus: {
passwordRequired: "Password required",
updateRequired: "Update required",
pairingRequired: "Pairing required",
refused: "Refused",
},
actions: {
enterPassword: "Enter password",
pairLink: "Paste pairing link",
scanQr: "Scan QR code",
checkForUpdates: "Check for updates",
},
passwordSheet: {
title: "Password for {{hostName}}",
label: "Password",
placeholder: "Enter host password",
connect: "Connect",
connecting: "Connecting...",
requiredError: "Enter a password to continue.",
},
},
pairing: {
hostPassword: {
title: "Password for {{host}}",
@@ -2279,6 +2388,8 @@ export const en = {
hint: "Scan this QR code with Paseo on your phone, or copy the link below.",
securityWarning:
"Treat this pairing link like a password. Anyone with it can access this daemon.",
passwordProtected:
"Password required. Devices scanning this code will enter this host's password.",
qrUnavailable: "QR code unavailable.",
qrAccessibility: "Pairing QR code",
retry: "Retry",
+121 -8
View File
@@ -2073,17 +2073,70 @@ export const es: TranslationResources = {
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
confirmAction: "Desactivar",
},
access: {
title: "Acceso",
passwordLabel: "Contraseña",
passwordNotSetSummary: "Sin configurar",
passwordNotSetHint: "Cualquiera con un enlace de emparejamiento puede conectarse",
passwordSetSummary: "Configurada",
passwordSetHint: "Obligatoria para conexiones remotas",
passwordEnvSummary: "Definida por el entorno",
passwordEnvHint: "Controlada por PASEO_PASSWORD en este host",
},
password: {
setTitle: "Establecer contraseña",
changeTitle: "Cambiar contraseña",
removeTitle: "Eliminar contraseña",
setAction: "Establecer contraseña",
setting: "Estableciendo...",
saveAction: "Guardar contraseña",
saving: "Guardando...",
removeAction: "Eliminar contraseña",
removing: "Eliminando...",
show: "Mostrar contraseña",
hide: "Ocultar contraseña",
setInfo:
"Los demás dispositivos remotos se desconectarán de inmediato y necesitarán esta contraseña. Este dispositivo seguirá conectado.",
changeInfo:
"Los demás dispositivos remotos se desconectarán de inmediato y necesitarán la nueva contraseña. Este dispositivo seguirá conectado.",
removeWarning:
"Cualquiera con un enlace de emparejamiento o acceso a la red podrá conectarse sin contraseña.",
fields: {
current: "Contraseña actual",
new: "Nueva contraseña",
confirm: "Confirmar contraseña",
confirmNew: "Confirmar nueva contraseña",
},
errors: {
currentRequired: "Introduce la contraseña actual.",
currentIncorrect: "La contraseña actual es incorrecta.",
tooShort: "Usa al menos 8 caracteres.",
tooLong: "La contraseña debe tener 72 bytes o menos.",
mismatch: "Las contraseñas no coinciden.",
},
toast: {
set: "Contraseña establecida.",
setDisconnectedOne: "Contraseña establecida. Se desconectó otro dispositivo.",
setDisconnectedOther:
"Contraseña establecida. Se desconectaron otros {{count}} dispositivos.",
updated: "Contraseña actualizada.",
updatedDisconnectedOne: "Contraseña actualizada. Se desconectó otro dispositivo.",
updatedDisconnectedOther:
"Contraseña actualizada. Se desconectaron otros {{count}} dispositivos.",
removed: "Contraseña eliminada.",
},
},
connected: {
title: "Clientes conectados",
title: "Dispositivos",
thisDevice: "Este dispositivo",
loading: "Cargando clientes conectados...",
empty: "No hay clientes conectados",
unavailable: "No se pudieron cargar los clientes conectados",
updateTitle: "Actualiza este host para ver los clientes conectados",
updateHint: "Este host todavía no informa de los clientes conectados",
loading: "Cargando dispositivos...",
empty: "No hay dispositivos conectados",
unavailable: "No se pudieron cargar los dispositivos",
updateTitle: "Actualiza este host para ver los dispositivos conectados",
updateHint: "Este host todavía no informa de los dispositivos conectados",
permissionTitle: "Se requiere gestión de acceso",
permissionHint: "Tu sesión no tiene permiso para ver los clientes conectados",
errorTitle: "No se pudieron cargar los clientes conectados",
permissionHint: "Tu sesión no tiene permiso para ver los dispositivos conectados",
errorTitle: "No se pudieron cargar los dispositivos",
},
hosts: {
title: "Hosts conectados",
@@ -2116,8 +2169,21 @@ export const es: TranslationResources = {
hub: "Hub",
plugin: "Plugin",
client: "Cliente",
host: "Host",
},
auth: {
localMachine: "Equipo local",
password: "Contraseña",
openAccess: "Acceso abierto",
hub: "Hub",
},
details: {
device: "Dispositivo",
app: "Aplicación",
connection: "Conexión",
ipAddress: "Dirección IP",
auth: "Autenticación",
access: "Acceso",
permissions: "Permisos",
connected: "Conectado",
lastSeen: "Última conexión",
@@ -2139,6 +2205,51 @@ export const es: TranslationResources = {
daysAgo: "hace {{count}} d",
},
},
hostRefusal: {
passwordRequired: {
title: "Contraseña requerida",
description: "Introduce la contraseña de este host para conectar.",
},
incorrectPassword: {
title: "Contraseña incorrecta",
description: "Este host rechazó la contraseña guardada.",
},
updateRequired: {
title: "Actualiza Paseo para conectar",
incompatibleDescription: "Este host requiere una versión más reciente de Paseo.",
unsupportedAuthDescription:
"Este host requiere un método de inicio de sesión que esta versión de Paseo no admite.",
},
pairingRequired: {
title: "Emparejamiento requerido",
description: "Vuelve a emparejar este dispositivo con el host para conectar.",
},
refusedByHost: {
title: "Conexión rechazada por {{hostName}}",
description: "Revisa la configuración de este host e inténtalo de nuevo.",
},
messageFromHost: "Mensaje de {{hostName}}: «{{message}}»",
shortStatus: {
passwordRequired: "Contraseña requerida",
updateRequired: "Actualización requerida",
pairingRequired: "Emparejamiento requerido",
refused: "Rechazado",
},
actions: {
enterPassword: "Introducir contraseña",
pairLink: "Pegar enlace de emparejamiento",
scanQr: "Escanear código QR",
checkForUpdates: "Buscar actualizaciones",
},
passwordSheet: {
title: "Contraseña para {{hostName}}",
label: "Contraseña",
placeholder: "Introduce la contraseña del host",
connect: "Conectar",
connecting: "Conectando...",
requiredError: "Introduce una contraseña para continuar.",
},
},
pairing: {
hostPassword: {
title: "Contraseña de {{host}}",
@@ -2305,6 +2416,8 @@ export const es: TranslationResources = {
hint: "Escanee este códigoQRconPaseoen su teléfono o copie el enlace a continuación.",
securityWarning:
"Trata este enlace de emparejamiento como una contraseña. Cualquiera que lo tenga puede acceder a este daemon.",
passwordProtected:
"Contraseña obligatoria. Los dispositivos que escaneen este código deberán introducir la contraseña de este host.",
qrUnavailable: "CódigoQRno disponible.",
qrAccessibility: "Código QR de emparejamiento",
retry: "Rever",
+120 -8
View File
@@ -2070,17 +2070,69 @@ export const fr: TranslationResources = {
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
confirmAction: "Désactiver",
},
access: {
title: "Accès",
passwordLabel: "Mot de passe",
passwordNotSetSummary: "Non défini",
passwordNotSetHint: "Toute personne disposant d’un lien d’association peut se connecter",
passwordSetSummary: "Défini",
passwordSetHint: "Requis pour les connexions distantes",
passwordEnvSummary: "Défini par l’environnement",
passwordEnvHint: "Contrôlé par PASEO_PASSWORD sur cet hôte",
},
password: {
setTitle: "Définir le mot de passe",
changeTitle: "Modifier le mot de passe",
removeTitle: "Supprimer le mot de passe",
setAction: "Définir le mot de passe",
setting: "Configuration...",
saveAction: "Enregistrer le mot de passe",
saving: "Enregistrement...",
removeAction: "Supprimer le mot de passe",
removing: "Suppression...",
show: "Afficher le mot de passe",
hide: "Masquer le mot de passe",
setInfo:
"Les autres appareils distants seront immédiatement déconnectés et devront saisir ce mot de passe. Cet appareil reste connecté.",
changeInfo:
"Les autres appareils distants seront immédiatement déconnectés et devront saisir le nouveau mot de passe. Cet appareil reste connecté.",
removeWarning:
"Toute personne disposant d’un lien d’association ou d’un accès réseau pourra se connecter sans mot de passe.",
fields: {
current: "Mot de passe actuel",
new: "Nouveau mot de passe",
confirm: "Confirmer le mot de passe",
confirmNew: "Confirmer le nouveau mot de passe",
},
errors: {
currentRequired: "Saisissez le mot de passe actuel.",
currentIncorrect: "Le mot de passe actuel est incorrect.",
tooShort: "Utilisez au moins 8 caractères.",
tooLong: "Le mot de passe doit faire 72 octets ou moins.",
mismatch: "Les mots de passe ne correspondent pas.",
},
toast: {
set: "Mot de passe défini.",
setDisconnectedOne: "Mot de passe défini. 1 autre appareil déconnecté.",
setDisconnectedOther: "Mot de passe défini. {{count}} autres appareils déconnectés.",
updated: "Mot de passe mis à jour.",
updatedDisconnectedOne: "Mot de passe mis à jour. 1 autre appareil déconnecté.",
updatedDisconnectedOther:
"Mot de passe mis à jour. {{count}} autres appareils déconnectés.",
removed: "Mot de passe supprimé.",
},
},
connected: {
title: "Clients connectés",
title: "Appareils",
thisDevice: "Cet appareil",
loading: "Chargement des clients connectés...",
empty: "Aucun client connecté",
unavailable: "Impossible de charger les clients connectés",
updateTitle: "Mettez cet hôte à jour pour voir les clients connectés",
updateHint: "Cet hôte ne signale pas encore les clients connectés",
loading: "Chargement des appareils...",
empty: "Aucun appareil connecté",
unavailable: "Impossible de charger les appareils",
updateTitle: "Mettez cet hôte à jour pour voir les appareils connectés",
updateHint: "Cet hôte ne signale pas encore les appareils connectés",
permissionTitle: "Gestion des accès requise",
permissionHint: "Votre session n’est pas autorisée à voir les clients connectés",
errorTitle: "Impossible de charger les clients connectés",
permissionHint: "Votre session n’est pas autorisée à voir les appareils connectés",
errorTitle: "Impossible de charger les appareils",
},
hosts: {
title: "Hôtes connectés",
@@ -2113,8 +2165,21 @@ export const fr: TranslationResources = {
hub: "Hub",
plugin: "Plugin",
client: "Client",
host: "Hôte",
},
auth: {
localMachine: "Machine locale",
password: "Mot de passe",
openAccess: "Accès ouvert",
hub: "Hub",
},
details: {
device: "Appareil",
app: "Application",
connection: "Connexion",
ipAddress: "Adresse IP",
auth: "Authentification",
access: "Accès",
permissions: "Autorisations",
connected: "Connecté",
lastSeen: "Dernière connexion",
@@ -2136,6 +2201,51 @@ export const fr: TranslationResources = {
daysAgo: "il y a {{count}} j",
},
},
hostRefusal: {
passwordRequired: {
title: "Mot de passe requis",
description: "Saisissez le mot de passe de cet hôte pour vous connecter.",
},
incorrectPassword: {
title: "Mot de passe incorrect",
description: "Le mot de passe enregistré a été refusé par cet hôte.",
},
updateRequired: {
title: "Mettez à jour Paseo pour vous connecter",
incompatibleDescription: "Cet hôte nécessite une version plus récente de Paseo.",
unsupportedAuthDescription:
"Cet hôte nécessite une méthode de connexion non prise en charge par cette version de Paseo.",
},
pairingRequired: {
title: "Appairage requis",
description: "Associez de nouveau cet appareil à l'hôte pour vous connecter.",
},
refusedByHost: {
title: "Connexion refusée par {{hostName}}",
description: "Vérifiez les paramètres de cet hôte et réessayez.",
},
messageFromHost: "Message de {{hostName}} : « {{message}} »",
shortStatus: {
passwordRequired: "Mot de passe requis",
updateRequired: "Mise à jour requise",
pairingRequired: "Appairage requis",
refused: "Refusé",
},
actions: {
enterPassword: "Saisir le mot de passe",
pairLink: "Coller le lien d'appairage",
scanQr: "Scanner le code QR",
checkForUpdates: "Rechercher des mises à jour",
},
passwordSheet: {
title: "Mot de passe pour {{hostName}}",
label: "Mot de passe",
placeholder: "Saisissez le mot de passe de l'hôte",
connect: "Se connecter",
connecting: "Connexion…",
requiredError: "Saisissez un mot de passe pour continuer.",
},
},
pairing: {
hostPassword: {
title: "Mot de passe pour {{host}}",
@@ -2302,6 +2412,8 @@ export const fr: TranslationResources = {
hint: "Scannez ce code QR avec Paseo sur votre téléphone, ou copiez le lien ci-dessous.",
securityWarning:
"Traitez ce lien d’association comme un mot de passe. Toute personne qui le possède peut accéder à ce daemon.",
passwordProtected:
"Mot de passe requis. Les appareils qui scannent ce code devront saisir le mot de passe de cet hôte.",
qrUnavailable: "Code QR indisponible.",
qrAccessibility: "Code QR d’association",
retry: "Réessayer",
+120 -8
View File
@@ -2040,17 +2040,69 @@ export const ja: TranslationResources = {
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
confirmAction: "オフにする",
},
access: {
title: "アクセス",
passwordLabel: "パスワード",
passwordNotSetSummary: "未設定",
passwordNotSetHint: "ペアリングリンクを知る誰でも接続できます",
passwordSetSummary: "設定済み",
passwordSetHint: "リモート接続に必須",
passwordEnvSummary: "環境変数で設定",
passwordEnvHint: "このホストの PASEO_PASSWORD で管理されています",
},
password: {
setTitle: "パスワードを設定",
changeTitle: "パスワードを変更",
removeTitle: "パスワードを削除",
setAction: "パスワードを設定",
setting: "設定中...",
saveAction: "パスワードを保存",
saving: "保存中...",
removeAction: "パスワードを削除",
removing: "削除中...",
show: "パスワードを表示",
hide: "パスワードを隠す",
setInfo:
"他のリモートデバイスは即座に切断され、このパスワードが必要になります。このデバイスは接続を維持します。",
changeInfo:
"他のリモートデバイスは即座に切断され、新しいパスワードが必要になります。このデバイスは接続を維持します。",
removeWarning:
"ペアリングリンクまたはネットワークアクセスを持つ誰でもパスワードなしで接続できるようになります。",
fields: {
current: "現在のパスワード",
new: "新しいパスワード",
confirm: "パスワードの確認",
confirmNew: "新しいパスワードの確認",
},
errors: {
currentRequired: "現在のパスワードを入力してください。",
currentIncorrect: "現在のパスワードが正しくありません。",
tooShort: "8文字以上入力してください。",
tooLong: "パスワードは72バイト以下にしてください。",
mismatch: "パスワードが一致しません。",
},
toast: {
set: "パスワードを設定しました。",
setDisconnectedOne: "パスワードを設定しました。他の1台のデバイスを切断しました。",
setDisconnectedOther: "パスワードを設定しました。他の{{count}}台のデバイスを切断しました。",
updated: "パスワードを更新しました。",
updatedDisconnectedOne: "パスワードを更新しました。他の1台のデバイスを切断しました。",
updatedDisconnectedOther:
"パスワードを更新しました。他の{{count}}台のデバイスを切断しました。",
removed: "パスワードを削除しました。",
},
},
connected: {
title: "接続中のクライアント",
title: "デバイス",
thisDevice: "このデバイス",
loading: "接続中のクライアントを読み込み中...",
empty: "接続中のクライアントはありません",
unavailable: "接続中のクライアントを読み込めません",
updateTitle: "接続中のクライアントを表示するにはこのホストを更新してください",
updateHint: "このホストはまだ接続中のクライアントの報告に対応していません",
loading: "デバイスを読み込み中...",
empty: "接続中のデバイスはありません",
unavailable: "デバイスを読み込めません",
updateTitle: "接続中のデバイスを表示するにはこのホストを更新してください",
updateHint: "このホストはまだ接続中のデバイスの報告に対応していません",
permissionTitle: "アクセス管理権限が必要です",
permissionHint: "このセッションには接続中のクライアントを表示する権限がありません",
errorTitle: "接続中のクライアントを読み込めませんでした",
permissionHint: "このセッションには接続中のデバイスを表示する権限がありません",
errorTitle: "デバイスを読み込めませんでした",
},
hosts: {
title: "接続されたホスト",
@@ -2083,8 +2135,21 @@ export const ja: TranslationResources = {
hub: "Hub",
plugin: "プラグイン",
client: "クライアント",
host: "ホスト",
},
auth: {
localMachine: "ローカルマシン",
password: "パスワード",
openAccess: "オープンアクセス",
hub: "Hub",
},
details: {
device: "デバイス",
app: "アプリ",
connection: "接続",
ipAddress: "IPアドレス",
auth: "認証",
access: "アクセス",
permissions: "権限",
connected: "接続時間",
lastSeen: "最終オンライン",
@@ -2106,6 +2171,51 @@ export const ja: TranslationResources = {
daysAgo: "{{count}}日前",
},
},
hostRefusal: {
passwordRequired: {
title: "パスワードが必要です",
description: "接続するにはこのホストのパスワードを入力してください。",
},
incorrectPassword: {
title: "パスワードが正しくありません",
description: "保存されたパスワードがこのホストによって拒否されました。",
},
updateRequired: {
title: "接続するにはPaseoを更新してください",
incompatibleDescription: "このホストには新しいバージョンのPaseoが必要です。",
unsupportedAuthDescription:
"このホストには、このバージョンのPaseoでサポートされていないサインイン方法が必要です。",
},
pairingRequired: {
title: "ペアリングが必要です",
description: "接続するには、このデバイスをホストと再度ペアリングしてください。",
},
refusedByHost: {
title: "{{hostName}} によって接続が拒否されました",
description: "このホストの設定を確認して、もう一度お試しください。",
},
messageFromHost: "{{hostName}} からのメッセージ: 「{{message}}」",
shortStatus: {
passwordRequired: "パスワードが必要",
updateRequired: "更新が必要",
pairingRequired: "ペアリングが必要",
refused: "拒否されました",
},
actions: {
enterPassword: "パスワードを入力",
pairLink: "ペアリングリンクを貼り付け",
scanQr: "QRコードをスキャン",
checkForUpdates: "アップデートを確認",
},
passwordSheet: {
title: "{{hostName}} のパスワード",
label: "パスワード",
placeholder: "ホストのパスワードを入力",
connect: "接続",
connecting: "接続中...",
requiredError: "続行するにはパスワードを入力してください。",
},
},
pairing: {
hostPassword: {
title: "{{host}} のパスワード",
@@ -2272,6 +2382,8 @@ export const ja: TranslationResources = {
hint: "スマートフォンのPaseoでこのQRコードをスキャンするか、以下のリンクをコピーしてください。",
securityWarning:
"このペアリングリンクはパスワードと同様に扱ってください。リンクを知っている人は誰でもこのデーモンにアクセスできます。",
passwordProtected:
"パスワードが必要です。このコードをスキャンしたデバイスはこのホストのパスワードを入力します。",
qrUnavailable: "QRコードが利用できません。",
qrAccessibility: "ペアリング QR コード",
retry: "再試行",
+122 -8
View File
@@ -2031,17 +2031,71 @@ export const ko: TranslationResources = {
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
confirmAction: "끄기",
},
access: {
title: "접근",
passwordLabel: "비밀번호",
passwordNotSetSummary: "설정되지 않음",
passwordNotSetHint: "페어링 링크를 가진 누구나 연결할 수 있습니다",
passwordSetSummary: "설정됨",
passwordSetHint: "원격 연결에 필요",
passwordEnvSummary: "환경 변수로 설정됨",
passwordEnvHint: "이 호스트의 PASEO_PASSWORD로 제어됩니다",
},
password: {
setTitle: "비밀번호 설정",
changeTitle: "비밀번호 변경",
removeTitle: "비밀번호 제거",
setAction: "비밀번호 설정",
setting: "설정 중...",
saveAction: "비밀번호 저장",
saving: "저장 중...",
removeAction: "비밀번호 제거",
removing: "제거 중...",
show: "비밀번호 표시",
hide: "비밀번호 숨기기",
setInfo:
"다른 원격 기기는 즉시 연결이 해제되며 이 비밀번호가 필요합니다. 이 기기는 연결이 유지됩니다.",
changeInfo:
"다른 원격 기기는 즉시 연결이 해제되며 새 비밀번호가 필요합니다. 이 기기는 연결이 유지됩니다.",
removeWarning:
"페어링 링크나 네트워크 접근 권한이 있는 누구나 비밀번호 없이 연결할 수 있게 됩니다.",
fields: {
current: "현재 비밀번호",
new: "새 비밀번호",
confirm: "비밀번호 확인",
confirmNew: "새 비밀번호 확인",
},
errors: {
currentRequired: "현재 비밀번호를 입력하세요.",
currentIncorrect: "현재 비밀번호가 올바르지 않습니다.",
tooShort: "8자 이상 입력하세요.",
tooLong: "비밀번호는 72바이트 이하여야 합니다.",
mismatch: "비밀번호가 일치하지 않습니다.",
},
toast: {
set: "비밀번호가 설정되었습니다.",
setDisconnectedOne: "비밀번호가 설정되었습니다. 다른 기기 1대의 연결을 해제했습니다.",
setDisconnectedOther:
"비밀번호가 설정되었습니다. 다른 기기 {{count}}대의 연결을 해제했습니다.",
updated: "비밀번호가 업데이트되었습니다.",
updatedDisconnectedOne:
"비밀번호가 업데이트되었습니다. 다른 기기 1대의 연결을 해제했습니다.",
updatedDisconnectedOther:
"비밀번호가 업데이트되었습니다. 다른 기기 {{count}}대의 연결을 해제했습니다.",
removed: "비밀번호가 제거되었습니다.",
},
},
connected: {
title: "연결된 클라이언트",
title: "기기",
thisDevice: "이 기기",
loading: "연결된 클라이언트를 불러오는 중...",
empty: "연결된 클라이언트가 없습니다",
unavailable: "연결된 클라이언트를 불러올 수 없습니다",
updateTitle: "연결된 클라이언트를 보려면 이 호스트를 업데이트하세요",
updateHint: "이 호스트는 아직 연결된 클라이언트 보고를 지원하지 않습니다",
loading: "기기를 불러오는 중...",
empty: "연결된 기기가 없습니다",
unavailable: "기기를 불러올 수 없습니다",
updateTitle: "연결된 기기를 보려면 이 호스트를 업데이트하세요",
updateHint: "이 호스트는 아직 연결된 기기 보고를 지원하지 않습니다",
permissionTitle: "접근 관리 권한이 필요합니다",
permissionHint: "현재 세션에는 연결된 클라이언트를 볼 권한이 없습니다",
errorTitle: "연결된 클라이언트를 불러오지 못했습니다",
permissionHint: "현재 세션에는 연결된 기기를 볼 권한이 없습니다",
errorTitle: "기기를 불러오지 못했습니다",
},
hosts: {
title: "연결된 호스트",
@@ -2074,8 +2128,21 @@ export const ko: TranslationResources = {
hub: "Hub",
plugin: "플러그인",
client: "클라이언트",
host: "호스트",
},
auth: {
localMachine: "로컬 기기",
password: "비밀번호",
openAccess: "열린 접근",
hub: "Hub",
},
details: {
device: "기기",
app: "앱",
connection: "연결",
ipAddress: "IP 주소",
auth: "인증",
access: "접근",
permissions: "권한",
connected: "연결됨",
lastSeen: "마지막 온라인",
@@ -2097,6 +2164,51 @@ export const ko: TranslationResources = {
daysAgo: "{{count}}일 전",
},
},
hostRefusal: {
passwordRequired: {
title: "비밀번호가 필요합니다",
description: "연결하려면 이 호스트의 비밀번호를 입력하세요.",
},
incorrectPassword: {
title: "비밀번호가 올바르지 않습니다",
description: "저장된 비밀번호가 이 호스트에서 거부되었습니다.",
},
updateRequired: {
title: "연결하려면 Paseo를 업데이트하세요",
incompatibleDescription: "이 호스트에는 최신 버전의 Paseo가 필요합니다.",
unsupportedAuthDescription:
"이 호스트에는 현재 버전의 Paseo에서 지원하지 않는 로그인 방식이 필요합니다.",
},
pairingRequired: {
title: "페어링이 필요합니다",
description: "연결하려면 이 기기를 호스트와 다시 페어링하세요.",
},
refusedByHost: {
title: "{{hostName}}에서 연결을 거부했습니다",
description: "이 호스트의 설정을 확인한 후 다시 시도하세요.",
},
messageFromHost: "{{hostName}}의 메시지: “{{message}}”",
shortStatus: {
passwordRequired: "비밀번호 필요",
updateRequired: "업데이트 필요",
pairingRequired: "페어링 필요",
refused: "거부됨",
},
actions: {
enterPassword: "비밀번호 입력",
pairLink: "페어링 링크 붙여넣기",
scanQr: "QR 코드 스캔",
checkForUpdates: "업데이트 확인",
},
passwordSheet: {
title: "{{hostName}} 비밀번호",
label: "비밀번호",
placeholder: "호스트 비밀번호 입력",
connect: "연결",
connecting: "연결 중...",
requiredError: "계속하려면 비밀번호를 입력하세요.",
},
},
pairing: {
hostPassword: {
title: "{{host}}의 비밀번호",
@@ -2261,6 +2373,8 @@ export const ko: TranslationResources = {
hint: "휴대폰의 Paseo로 이 QR 코드를 스캔하거나 아래 링크를 복사하세요.",
securityWarning:
"이 페어링 링크는 비밀번호처럼 취급하세요. 링크를 가진 사람은 누구나 이 데몬에 접근할 수 있습니다.",
passwordProtected:
"비밀번호가 필요합니다. 이 코드를 스캔하는 기기는 이 호스트의 비밀번호를 입력해야 합니다.",
qrUnavailable: "QR 코드를 사용할 수 없습니다.",
qrAccessibility: "페어링 QR 코드",
retry: "다시 시도",
+119 -8
View File
@@ -2057,17 +2057,68 @@ export const ptBR: TranslationResources = {
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
confirmAction: "Desativar",
},
access: {
title: "Acesso",
passwordLabel: "Senha",
passwordNotSetSummary: "Não definida",
passwordNotSetHint: "Qualquer pessoa com um link de pareamento pode conectar",
passwordSetSummary: "Definida",
passwordSetHint: "Obrigatória para conexões remotas",
passwordEnvSummary: "Definida pelo ambiente",
passwordEnvHint: "Controlada por PASEO_PASSWORD neste host",
},
password: {
setTitle: "Definir senha",
changeTitle: "Alterar senha",
removeTitle: "Remover senha",
setAction: "Definir senha",
setting: "Definindo...",
saveAction: "Salvar senha",
saving: "Salvando...",
removeAction: "Remover senha",
removing: "Removendo...",
show: "Mostrar senha",
hide: "Ocultar senha",
setInfo:
"Outros dispositivos remotos desconectam imediatamente e precisarão desta senha. Este dispositivo permanece conectado.",
changeInfo:
"Outros dispositivos remotos desconectam imediatamente e precisarão da nova senha. Este dispositivo permanece conectado.",
removeWarning:
"Qualquer pessoa com um link de pareamento ou acesso à rede poderá conectar sem senha.",
fields: {
current: "Senha atual",
new: "Nova senha",
confirm: "Confirmar senha",
confirmNew: "Confirmar nova senha",
},
errors: {
currentRequired: "Digite a senha atual.",
currentIncorrect: "A senha atual está incorreta.",
tooShort: "Use pelo menos 8 caracteres.",
tooLong: "A senha deve ter 72 bytes ou menos.",
mismatch: "As senhas não coincidem.",
},
toast: {
set: "Senha definida.",
setDisconnectedOne: "Senha definida. 1 outro dispositivo desconectado.",
setDisconnectedOther: "Senha definida. {{count}} outros dispositivos desconectados.",
updated: "Senha atualizada.",
updatedDisconnectedOne: "Senha atualizada. 1 outro dispositivo desconectado.",
updatedDisconnectedOther: "Senha atualizada. {{count}} outros dispositivos desconectados.",
removed: "Senha removida.",
},
},
connected: {
title: "Clientes conectados",
title: "Dispositivos",
thisDevice: "Este dispositivo",
loading: "Carregando clientes conectados...",
empty: "Nenhum cliente conectado",
unavailable: "Não foi possível carregar os clientes conectados",
updateTitle: "Atualize este host para ver clientes conectados",
updateHint: "Este host ainda não informa clientes conectados",
loading: "Carregando dispositivos...",
empty: "Nenhum dispositivo conectado",
unavailable: "Não foi possível carregar os dispositivos",
updateTitle: "Atualize este host para ver dispositivos conectados",
updateHint: "Este host ainda não informa dispositivos conectados",
permissionTitle: "Gerenciamento de acesso necessário",
permissionHint: "Sua sessão não tem permissão para ver clientes conectados",
errorTitle: "Não foi possível carregar os clientes conectados",
permissionHint: "Sua sessão não tem permissão para ver dispositivos conectados",
errorTitle: "Não foi possível carregar os dispositivos",
},
hosts: {
title: "Hosts conectados",
@@ -2100,8 +2151,21 @@ export const ptBR: TranslationResources = {
hub: "Hub",
plugin: "Plugin",
client: "Cliente",
host: "Host",
},
auth: {
localMachine: "Máquina local",
password: "Senha",
openAccess: "Acesso aberto",
hub: "Hub",
},
details: {
device: "Dispositivo",
app: "Aplicativo",
connection: "Conexão",
ipAddress: "Endereço IP",
auth: "Autenticação",
access: "Acesso",
permissions: "Permissões",
connected: "Conectado",
lastSeen: "Última vez online",
@@ -2123,6 +2187,51 @@ export const ptBR: TranslationResources = {
daysAgo: "há {{count}}d",
},
},
hostRefusal: {
passwordRequired: {
title: "Senha necessária",
description: "Digite a senha deste host para conectar.",
},
incorrectPassword: {
title: "Senha incorreta",
description: "A senha salva foi recusada por este host.",
},
updateRequired: {
title: "Atualize o Paseo para conectar",
incompatibleDescription: "Este host requer uma versão mais recente do Paseo.",
unsupportedAuthDescription:
"Este host requer um método de login não suportado por esta versão do Paseo.",
},
pairingRequired: {
title: "Pareamento necessário",
description: "Pareie este dispositivo novamente com o host para conectar.",
},
refusedByHost: {
title: "Conexão recusada por {{hostName}}",
description: "Verifique as configurações deste host e tente novamente.",
},
messageFromHost: "Mensagem de {{hostName}}: “{{message}}”",
shortStatus: {
passwordRequired: "Senha necessária",
updateRequired: "Atualização necessária",
pairingRequired: "Pareamento necessário",
refused: "Recusado",
},
actions: {
enterPassword: "Digitar senha",
pairLink: "Colar link de pareamento",
scanQr: "Escanear código QR",
checkForUpdates: "Verificar atualizações",
},
passwordSheet: {
title: "Senha para {{hostName}}",
label: "Senha",
placeholder: "Digite a senha do host",
connect: "Conectar",
connecting: "Conectando...",
requiredError: "Digite uma senha para continuar.",
},
},
pairing: {
hostPassword: {
title: "Senha de {{host}}",
@@ -2289,6 +2398,8 @@ export const ptBR: TranslationResources = {
hint: "Escaneie este QR code com o Paseo no seu celular ou copie o link abaixo.",
securityWarning:
"Trate este link de pareamento como uma senha. Qualquer pessoa com o link pode acessar este daemon.",
passwordProtected:
"Senha obrigatória. Os dispositivos que escanearem este código precisarão inserir a senha deste host.",
qrUnavailable: "QR code indisponível.",
qrAccessibility: "Código QR de pareamento",
retry: "Tentar novamente",
+119 -8
View File
@@ -2056,17 +2056,68 @@ export const ru: TranslationResources = {
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
confirmAction: "Выключить",
},
access: {
title: "Доступ",
passwordLabel: "Пароль",
passwordNotSetSummary: "Не задан",
passwordNotSetHint: "Подключиться может любой, у кого есть ссылка для сопряжения",
passwordSetSummary: "Задан",
passwordSetHint: "Требуется для удалённых подключений",
passwordEnvSummary: "Задан через окружение",
passwordEnvHint: "Управляется переменной PASEO_PASSWORD на этом хосте",
},
password: {
setTitle: "Задать пароль",
changeTitle: "Изменить пароль",
removeTitle: "Удалить пароль",
setAction: "Задать пароль",
setting: "Сохранение...",
saveAction: "Сохранить пароль",
saving: "Сохранение...",
removeAction: "Удалить пароль",
removing: "Удаление...",
show: "Показать пароль",
hide: "Скрыть пароль",
setInfo:
"Другие удалённые устройства немедленно отключатся и потребуют этот пароль. Это устройство останется подключённым.",
changeInfo:
"Другие удалённые устройства немедленно отключатся и потребуют новый пароль. Это устройство останется подключённым.",
removeWarning:
"Любой, у кого есть ссылка для сопряжения или доступ к сети, сможет подключаться без пароля.",
fields: {
current: "Текущий пароль",
new: "Новый пароль",
confirm: "Подтвердите пароль",
confirmNew: "Подтвердите новый пароль",
},
errors: {
currentRequired: "Введите текущий пароль.",
currentIncorrect: "Неверный текущий пароль.",
tooShort: "Используйте не менее 8 символов.",
tooLong: "Пароль должен быть не длиннее 72 байт.",
mismatch: "Пароли не совпадают.",
},
toast: {
set: "Пароль задан.",
setDisconnectedOne: "Пароль задан. Отключено 1 другое устройство.",
setDisconnectedOther: "Пароль задан. Отключено других устройств: {{count}}.",
updated: "Пароль обновлён.",
updatedDisconnectedOne: "Пароль обновлён. Отключено 1 другое устройство.",
updatedDisconnectedOther: "Пароль обновлён. Отключено других устройств: {{count}}.",
removed: "Пароль удалён.",
},
},
connected: {
title: "Подключённые клиенты",
title: "Устройства",
thisDevice: "Это устройство",
loading: "Загрузка подключённых клиентов...",
empty: "Нет подключённых клиентов",
unavailable: "Не удалось загрузить подключённых клиентов",
updateTitle: "Обновите этот хост, чтобы видеть подключённых клиентов",
updateHint: "Этот хост ещё не передаёт список подключённых клиентов",
loading: "Загрузка устройств...",
empty: "Нет подключённых устройств",
unavailable: "Не удалось загрузить устройства",
updateTitle: "Обновите этот хост, чтобы видеть подключённые устройства",
updateHint: "Этот хост ещё не передаёт список подключённых устройств",
permissionTitle: "Требуются права управления доступом",
permissionHint: "У текущей сессии нет прав для просмотра подключённых клиентов",
errorTitle: "Не удалось загрузить подключённых клиентов",
permissionHint: "У текущей сессии нет прав для просмотра подключённых устройств",
errorTitle: "Не удалось загрузить устройства",
},
hosts: {
title: "Подключённые хосты",
@@ -2099,8 +2150,21 @@ export const ru: TranslationResources = {
hub: "Hub",
plugin: "Плагин",
client: "Клиент",
host: "Хост",
},
auth: {
localMachine: "Локальная машина",
password: "Пароль",
openAccess: "Открытый доступ",
hub: "Hub",
},
details: {
device: "Устройство",
app: "Приложение",
connection: "Подключение",
ipAddress: "IP-адрес",
auth: "Аутентификация",
access: "Доступ",
permissions: "Разрешения",
connected: "Подключено",
lastSeen: "Последний раз в сети",
@@ -2122,6 +2186,51 @@ export const ru: TranslationResources = {
daysAgo: "{{count}} дн назад",
},
},
hostRefusal: {
passwordRequired: {
title: "Требуется пароль",
description: "Введите пароль этого хоста для подключения.",
},
incorrectPassword: {
title: "Неверный пароль",
description: "Сохранённый пароль был отклонён этим хостом.",
},
updateRequired: {
title: "Обновите Paseo для подключения",
incompatibleDescription: "Для этого хоста требуется более новая версия Paseo.",
unsupportedAuthDescription:
"Этот хост требует способ входа, который не поддерживается этой версией Paseo.",
},
pairingRequired: {
title: "Требуется сопряжение",
description: "Повторно выполните сопряжение этого устройства с хостом для подключения.",
},
refusedByHost: {
title: "Подключение отклонено хостом {{hostName}}",
description: "Проверьте настройки этого хоста и повторите попытку.",
},
messageFromHost: "Сообщение от {{hostName}}: «{{message}}»",
shortStatus: {
passwordRequired: "Требуется пароль",
updateRequired: "Требуется обновление",
pairingRequired: "Требуется сопряжение",
refused: "Отклонено",
},
actions: {
enterPassword: "Ввести пароль",
pairLink: "Вставить ссылку сопряжения",
scanQr: "Сканировать QR-код",
checkForUpdates: "Проверить обновления",
},
passwordSheet: {
title: "Пароль для {{hostName}}",
label: "Пароль",
placeholder: "Введите пароль хоста",
connect: "Подключиться",
connecting: "Подключение...",
requiredError: "Введите пароль, чтобы продолжить.",
},
},
pairing: {
hostPassword: {
title: "Пароль для {{host}}",
@@ -2289,6 +2398,8 @@ export const ru: TranslationResources = {
hint: "Отсканируйте этот QR-код с помощью Paseo на телефоне или скопируйте ссылку ниже.",
securityWarning:
"Обращайтесь с этой ссылкой для сопряжения как с паролем. Любой, у кого она есть, может получить доступ к этому демону.",
passwordProtected:
"Требуется пароль. Устройства, сканирующие этот код, должны будут ввести пароль этого хоста.",
qrUnavailable: "QR-код недоступен.",
qrAccessibility: "QR-код сопряжения",
retry: "Повторить попытку",
+114 -8
View File
@@ -2001,17 +2001,65 @@ export const zhCN: TranslationResources = {
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
confirmAction: "关闭",
},
access: {
title: "访问",
passwordLabel: "密码",
passwordNotSetSummary: "未设置",
passwordNotSetHint: "任何拥有配对链接的人都可以连接",
passwordSetSummary: "已设置",
passwordSetHint: "远程连接必填",
passwordEnvSummary: "由环境变量设置",
passwordEnvHint: "由此主机上的 PASEO_PASSWORD 控制",
},
password: {
setTitle: "设置密码",
changeTitle: "更改密码",
removeTitle: "移除密码",
setAction: "设置密码",
setting: "正在设置...",
saveAction: "保存密码",
saving: "正在保存...",
removeAction: "移除密码",
removing: "正在移除...",
show: "显示密码",
hide: "隐藏密码",
setInfo: "其他远程设备会立即断开连接,并需要输入此密码。当前设备保持连接。",
changeInfo: "其他远程设备会立即断开连接,并需要输入新密码。当前设备保持连接。",
removeWarning: "任何拥有配对链接或网络访问权限的人都可以无需密码连接。",
fields: {
current: "当前密码",
new: "新密码",
confirm: "确认密码",
confirmNew: "确认新密码",
},
errors: {
currentRequired: "请输入当前密码。",
currentIncorrect: "当前密码不正确。",
tooShort: "请至少使用 8 个字符。",
tooLong: "密码不能超过 72 字节。",
mismatch: "两次输入的密码不一致。",
},
toast: {
set: "密码已设置。",
setDisconnectedOne: "密码已设置。已断开 1 台其他设备。",
setDisconnectedOther: "密码已设置。已断开 {{count}} 台其他设备。",
updated: "密码已更新。",
updatedDisconnectedOne: "密码已更新。已断开 1 台其他设备。",
updatedDisconnectedOther: "密码已更新。已断开 {{count}} 台其他设备。",
removed: "密码已移除。",
},
},
connected: {
title: "已连接的客户端",
title: "设备",
thisDevice: "此设备",
loading: "正在加载已连接的客户端...",
empty: "没有已连接的客户端",
unavailable: "无法加载已连接的客户端",
updateTitle: "更新此主机以查看已连接的客户端",
updateHint: "此主机暂不支持报告已连接的客户端",
loading: "正在加载设备...",
empty: "没有已连接的设备",
unavailable: "无法加载设备",
updateTitle: "更新此主机以查看已连接的设备",
updateHint: "此主机暂不支持报告已连接的设备",
permissionTitle: "需要访问管理权限",
permissionHint: "当前会话无权查看已连接的客户端",
errorTitle: "无法加载已连接的客户端",
permissionHint: "当前会话无权查看已连接的设备",
errorTitle: "无法加载设备",
},
hosts: {
title: "已连接的主机",
@@ -2044,8 +2092,21 @@ export const zhCN: TranslationResources = {
hub: "Hub",
plugin: "插件",
client: "客户端",
host: "主机",
},
auth: {
localMachine: "本机",
password: "密码",
openAccess: "开放访问",
hub: "Hub",
},
details: {
device: "设备",
app: "应用",
connection: "连接",
ipAddress: "IP 地址",
auth: "认证",
access: "访问权限",
permissions: "权限",
connected: "连接时间",
lastSeen: "上次在线",
@@ -2067,6 +2128,50 @@ export const zhCN: TranslationResources = {
daysAgo: "{{count}} 天前",
},
},
hostRefusal: {
passwordRequired: {
title: "需要密码",
description: "输入此主机的密码以连接。",
},
incorrectPassword: {
title: "密码错误",
description: "已保存的密码被此主机拒绝。",
},
updateRequired: {
title: "更新 Paseo 以连接",
incompatibleDescription: "此主机需要更新版本的 Paseo。",
unsupportedAuthDescription: "此主机需要当前版本的 Paseo 不支持的登录方式。",
},
pairingRequired: {
title: "需要配对",
description: "请将此设备重新与此主机配对以连接。",
},
refusedByHost: {
title: "连接被 {{hostName}} 拒绝",
description: "请检查此主机的设置并重试。",
},
messageFromHost: "来自 {{hostName}} 的消息:“{{message}}”",
shortStatus: {
passwordRequired: "需要密码",
updateRequired: "需要更新",
pairingRequired: "需要配对",
refused: "已拒绝",
},
actions: {
enterPassword: "输入密码",
pairLink: "粘贴配对链接",
scanQr: "扫描二维码",
checkForUpdates: "检查更新",
},
passwordSheet: {
title: "{{hostName}} 的密码",
label: "密码",
placeholder: "输入主机密码",
connect: "连接",
connecting: "正在连接...",
requiredError: "请输入密码以继续。",
},
},
pairing: {
hostPassword: {
title: "{{host}} 的密码",
@@ -2225,6 +2330,7 @@ export const zhCN: TranslationResources = {
unavailable: "配对 offer 不可用。",
hint: "用手机上的 Paseo 扫描此二维码,或复制下方链接。",
securityWarning: "请像保管密码一样保管此配对链接。任何获得此链接的人都可以访问此守护进程。",
passwordProtected: "需要密码。扫描此二维码的设备将输入此主机的密码。",
qrUnavailable: "二维码不可用。",
qrAccessibility: "配对二维码",
retry: "重试",
@@ -1,9 +1,11 @@
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import { Text, View } from "react-native";
import { ArrowLeftToLine, RotateCw, Settings } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { HostRefusalEmptyState } from "@/hosts/host-refusal-alert";
import type { AgentRouteResolution } from "@/navigation/agent-route-resolution";
import { formatConnectionStatus } from "@/utils/daemons";
import type { Theme } from "@/styles/theme";
@@ -19,16 +21,20 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
});
export function AgentRouteResolutionView({
serverId,
resolution,
hostName,
lastHostError,
helloRejection,
onRetry,
onManageHost,
onBack,
}: {
serverId: string;
resolution: VisibleAgentRouteResolution;
hostName: string;
lastHostError: string | null;
helloRejection?: DaemonHelloRejection | null;
onRetry: () => void;
onManageHost: () => void;
onBack: () => void;
@@ -70,6 +76,20 @@ export function AgentRouteResolutionView({
const isConnecting =
resolution.connectionStatus === "connecting" || resolution.connectionStatus === "idle";
if (!isConnecting && helloRejection) {
return (
<HostRefusalEmptyState
serverId={serverId}
hostName={hostName}
rejection={helloRejection}
onManageHost={onManageHost}
testID="agent-route-refusal"
testIDPrefix="agent-route-refusal"
/>
);
}
let title = t("workspace.route.cannotReachHost", { hostName });
if (isConnecting) {
title = t("agentPanel.unavailable.connecting", { serverLabel: hostName });
@@ -112,36 +132,35 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
paddingHorizontal: theme.spacing[6],
gap: theme.spacing[4],
},
textStack: {
alignItems: "center",
gap: theme.spacing[2],
maxWidth: 520,
maxWidth: 420,
},
title: {
fontSize: theme.fontSize.lg,
fontWeight: theme.fontWeight.semibold,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
textAlign: "center",
},
description: {
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
textAlign: "center",
},
error: {
fontSize: theme.fontSize.sm,
color: theme.colors.destructive,
fontSize: theme.fontSize.base,
lineHeight: Math.round(theme.fontSize.base * 1.4),
textAlign: "center",
},
actions: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "center",
flexWrap: "wrap",
gap: theme.spacing[2],
},
}));
+255 -72
View File
@@ -3,7 +3,7 @@ import { useNativeSplashHold } from "@/native-splash";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { LoadingState } from "@/components/ui/loading-state";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { DaemonClient, DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
import type { TFunction } from "i18next";
import { SquarePen } from "lucide-react-native";
import React, {
@@ -31,6 +31,7 @@ import { FileDropZone } from "@/components/file-drop/file-drop-zone";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { RetainedChatContent } from "./retained-chat-content";
import { Composer } from "@/composer";
import type { ComposerInputMode } from "@/composer/input-mode";
import { AgentCommandsProvider } from "@/agent-commands";
import {
useComposerEditingSession,
@@ -74,15 +75,18 @@ import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { reconcileMissingAgentStateWithPresentAgent } from "@/panels/agent-panel-load-state";
import { TimelineSyncStatus } from "@/timeline/sync-status";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import type { PaneHost } from "@/panels/panel-manifest";
import { useAgentFactsLine } from "@/panels/agent-facts-line";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel } from "@/panels/panel-registry";
import { RenderProfile } from "@/utils/render-profiler";
import { buildDraftPanelDescriptor } from "@/panels/draft-panel-descriptor";
import { HostRefusalAlert } from "@/hosts/host-refusal-alert";
import {
type HostRuntimeConnectionStatus,
useHostRuntimeClient,
useHostRuntimeConnectionStatus,
useHostRuntimeHelloRejection,
useHostRuntimeIsConnected,
useHostRuntimeLastError,
useHosts,
@@ -109,6 +113,7 @@ import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey, type WorkspaceTabTarget } from "@/workspace-tabs/model";
import { openWorkspaceChanges } from "@/workspace-tabs/open-supporting-view";
import { useSettings } from "@/hooks/use-settings";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import type { Theme } from "@/styles/theme";
import type { PendingPermission } from "@/types/shared";
import type { StreamItem } from "@/types/stream";
@@ -348,13 +353,58 @@ function resolveConversationAgentId(target: ConversationTarget): string | undefi
return target.kind === "agent" ? target.agentId.trim() || undefined : undefined;
}
/**
* Where a conversation is shown. A pane is a workspace tab or sheet; an embed is a plugin's
* `AgentChat`, which has no tab to retarget or close and shows a composer only when asked.
* `id` names the viewer: the tab in a pane, the embed instance otherwise.
*/
export type ConversationSurface =
| { kind: "pane"; id: string; host: PaneHost }
| {
kind: "embed";
id: string;
composer: EmbeddedComposer | null;
/** The pane or screen around the embed is the one in front. */
isActive: boolean;
};
export interface EmbeddedComposer {
/** `chat` is the agent tab's composer; `message` is a text box and Send. */
inputMode: Extract<ComposerInputMode, "chat" | "message">;
/** Replaces the default placeholder. */
placeholder: string | undefined;
}
/**
* An embed with a composer is where the user acts on the agent, so while it is in front it clears
* "needs attention" without key focus. One without a composer is a preview: a plugin can show many
* at once, and a glance is not the user handling the agent.
*/
function surfaceClearsAttention(surface: ConversationSurface, isPaneFocused: boolean): boolean {
return surface.kind === "embed" ? surface.composer !== null && surface.isActive : isPaneFocused;
}
/** The track's pills open tabs and sheets of the workspace, which an embed is not in. */
function surfaceShowsTrack(surface: ConversationSurface, hasActiveComposer: boolean): boolean {
return hasActiveComposer && surface.kind === "pane";
}
function surfaceShowsComposer(surface: ConversationSurface): boolean {
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
return surface.kind === "pane" ? surface.host !== "sheet" : surface.composer !== null;
}
/**
* Drafts and agents render through one chain so the timeline stays mounted when the draft's
* first prompt creates the agent and the tab retargets. The agent gates are idle for a draft.
*/
export function AgentConversationPanel() {
const { serverId, workspaceId, target, openFileInWorkspace } = usePaneContext();
const { serverId, workspaceId, target, openFileInWorkspace, tabId, host } = usePaneContext();
const { isInteractive } = usePaneFocus();
const surface = useMemo<ConversationSurface>(
() => ({ kind: "pane", id: tabId, host }),
[host, tabId],
);
invariant(
target.kind === "agent" || target.kind === "draft",
"AgentConversationPanel requires an agent or draft target",
@@ -366,6 +416,7 @@ export function AgentConversationPanel() {
serverId={serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isInteractive}
onOpenWorkspaceFile={openFileInWorkspace}
/>
@@ -444,16 +495,18 @@ type AgentLookupState =
| { tag: "not_found"; message: string }
| { tag: "error"; message: string };
function AgentPanelContent({
export function AgentPanelContent({
serverId,
workspaceId,
target,
surface,
isPaneFocused,
onOpenWorkspaceFile,
}: {
serverId: string;
workspaceId: string;
target: ConversationTarget;
surface: ConversationSurface;
isPaneFocused: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
@@ -466,6 +519,7 @@ function AgentPanelContent({
const runtimeIsConnected = useHostRuntimeIsConnected(runtimeServerId);
const runtimeConnectionStatus = useHostRuntimeConnectionStatus(runtimeServerId);
const runtimeLastError = useHostRuntimeLastError(runtimeServerId);
const runtimeHelloRejection = useHostRuntimeHelloRejection(runtimeServerId);
const hasCachedAgent = useSessionStore((state) => {
if (!resolvedServerId || !resolvedAgentId) return false;
const session = state.sessions[resolvedServerId];
@@ -490,9 +544,11 @@ function AgentPanelContent({
if (target.kind === "agent" && (!resolvedServerId || (!runtimeClient && !hasCachedAgent))) {
return (
<AgentSessionUnavailableState
serverId={resolvedServerId ?? null}
serverLabel={serverLabel}
connectionStatus={connectionStatus}
lastError={lastConnectionError}
helloRejection={runtimeHelloRejection}
isUnknownDaemon={isUnknownDaemon}
t={t}
/>
@@ -504,9 +560,11 @@ function AgentPanelContent({
serverId={resolvedServerId ?? serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isPaneFocused}
client={runtimeClient}
isConnected={runtimeIsConnected}
isConnectionRefused={runtimeHelloRejection !== null}
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
);
@@ -516,17 +574,21 @@ function AgentPanelBody({
serverId,
workspaceId,
target,
surface,
isPaneFocused,
client,
isConnected,
isConnectionRefused,
onOpenWorkspaceFile,
}: {
serverId: string;
workspaceId: string;
target: ConversationTarget;
surface: ConversationSurface;
isPaneFocused: boolean;
client: ReturnType<typeof useHostRuntimeClient>;
isConnected: boolean;
isConnectionRefused: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
@@ -655,9 +717,11 @@ function AgentPanelBody({
serverId={serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isPaneFocused}
client={client}
isConnected={isConnected}
isConnectionRefused={isConnectionRefused}
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
);
@@ -707,21 +771,25 @@ function ChatAgentContent({
serverId,
workspaceId,
target,
surface,
isPaneFocused,
client,
isConnected,
isConnectionRefused,
onOpenWorkspaceFile,
}: {
serverId: string;
workspaceId: string;
target: ConversationTarget;
surface: ConversationSurface;
isPaneFocused: boolean;
client: ReturnType<typeof useHostRuntimeClient>;
isConnected: boolean;
isConnectionRefused: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
const { tabId } = usePaneContext();
const tabId = surface.id;
const agentId = resolveConversationAgentId(target);
const isPaneVisible = useRetainedPanelActive();
const { api: toastApi, toast: toastState, dismiss: dismissToast } = useToastHost();
@@ -830,7 +898,7 @@ function ChatAgentContent({
isAgentDataReady: agentHistorySyncGeneration === historySyncGeneration,
requiresAttention: agentState.requiresAttention,
attentionReason: agentState.attentionReason,
isScreenFocused: isPaneFocused,
isScreenFocused: surfaceClearsAttention(surface, isPaneFocused),
focusRequest,
onError: reportAttentionError,
});
@@ -878,6 +946,7 @@ function ChatAgentContent({
isArchived: agentState.archivedAt !== null,
missingAgentState,
isConnected,
isConnectionRefused,
isArchivingCurrentAgent,
isHistorySyncing,
needsAuthoritativeSync,
@@ -1063,6 +1132,7 @@ function ChatAgentContent({
workspaceId={workspaceId}
agentId={agentId ?? tabId}
draft={draft}
surface={surface}
isPaneFocused={isPaneFocused}
isArchivingCurrentAgent={isArchivingCurrentAgent}
agentState={agentState}
@@ -1094,6 +1164,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
workspaceId,
agentId,
draft,
surface,
isPaneFocused,
isArchivingCurrentAgent,
agentState,
@@ -1122,6 +1193,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
/** The agent's id, or the tab id while a draft has no agent yet. */
agentId: string;
draft: DraftConversation | null;
surface: ConversationSurface;
isPaneFocused: boolean;
isArchivingCurrentAgent: boolean;
agentState: ChatAgentSelectedState;
@@ -1146,9 +1218,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
const paneHost = usePaneContext().host;
const showsComposer = draft !== null || paneHost !== "sheet";
const showsComposer = draft !== null || surfaceShowsComposer(surface);
// The dock lays out fullscreen for the same session the composer edits in.
const composerEditingSession = useComposerEditingSession("chat");
const isComposerFullscreen = useComposerFullscreen(composerEditingSession);
@@ -1158,6 +1228,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
agentId,
});
const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent;
const showsTrack = surfaceShowsTrack(surface, hasActiveComposer);
const focusRestoredComposer = useStableEvent(() => {
if (isPaneFocused && showsComposer && hasActiveComposer) {
composerEditingSession.focus();
@@ -1234,6 +1305,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
<AgentComposerSection
agentId={agentId}
serverId={serverId}
surface={surface}
isPaneFocused={isPaneFocused}
isArchivingCurrentAgent={isArchivingCurrentAgent}
isWorkspaceRestoring={isWorkspaceRestoring}
@@ -1291,13 +1363,13 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
isInitialHistoryLoading={isInitialHistoryLoading}
revealInitialHistory={hasCachedHistory || showHistorySyncError}
reservesTrack={showsTrack}
onInitialHistoryVisibilityChange={handleInitialHistoryVisibilityChange}
hasActiveComposer={hasActiveComposer}
toast={toastApi}
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
</RenderProfile>
{hasActiveComposer && !draft ? (
{showsTrack && !draft ? (
<AgentTracks
serverId={serverId}
workspaceId={workspaceId}
@@ -1528,8 +1600,8 @@ const AgentStreamSection = memo(function AgentStreamSection({
hasAppliedAuthoritativeHistory,
isInitialHistoryLoading,
revealInitialHistory,
reservesTrack,
onInitialHistoryVisibilityChange,
hasActiveComposer,
toast,
onOpenWorkspaceFile,
}: {
@@ -1542,18 +1614,19 @@ const AgentStreamSection = memo(function AgentStreamSection({
hasAppliedAuthoritativeHistory: boolean;
isInitialHistoryLoading: boolean;
revealInitialHistory: boolean;
/** Whether the composer's track bar sits over the bottom of the stream. */
reservesTrack: boolean;
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
hasActiveComposer: boolean;
toast: ReturnType<typeof useToastHost>["api"];
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const isCompactFormFactor = useIsCompactFormFactor();
// The track bar's space is reserved whenever the bar is mounted, pills or not: pills come and go
// every turn, and the transcript must not jump with them.
const bottomOverlayTailClearance = hasActiveComposer
const bottomOverlayTailClearance = reservesTrack
? resolveComposerTrackTailClearance(isCompactFormFactor)
: 0;
const bottomOverlayControlClearance = hasActiveComposer
const bottomOverlayControlClearance = reservesTrack
? resolveComposerTrackControlClearance(isCompactFormFactor)
: 0;
const streamItemsRaw = useAgentStreamTail(serverId, agentId);
@@ -1687,6 +1760,7 @@ function DraftComposerSection({
const AgentComposerSection = memo(function AgentComposerSection({
agentId,
serverId,
surface,
isPaneFocused,
isArchivingCurrentAgent,
isWorkspaceRestoring,
@@ -1702,6 +1776,7 @@ const AgentComposerSection = memo(function AgentComposerSection({
}: {
agentId?: string;
serverId: string;
surface: ConversationSurface;
isPaneFocused: boolean;
isArchivingCurrentAgent: boolean;
isWorkspaceRestoring: boolean;
@@ -1731,36 +1806,28 @@ const AgentComposerSection = memo(function AgentComposerSection({
return null;
}
return (
<ActiveAgentComposer
agentId={agentId}
serverId={serverId}
isPaneFocused={isPaneFocused}
cwd={cwd}
isSubmitLoading={isSubmitLoading}
agentInputDraft={agentInputDraft}
editingSession={editingSession}
onAttentionInputFocus={onAttentionInputFocus}
onAttentionPromptSend={onAttentionPromptSend}
onComposerHeightChange={onComposerHeightChange}
onMessageSent={onMessageSent}
/>
);
const composer: AgentComposerProps = {
agentId,
serverId,
isPaneFocused,
cwd,
isSubmitLoading,
agentInputDraft,
editingSession,
onAttentionInputFocus,
onAttentionPromptSend,
onComposerHeightChange,
onMessageSent,
};
if (surface.kind === "embed") {
return surface.composer ? (
<EmbeddedAgentComposer {...composer} options={surface.composer} />
) : null;
}
return <PaneAgentComposer {...composer} />;
});
function ActiveAgentComposer({
agentId,
serverId,
isPaneFocused,
cwd,
isSubmitLoading,
agentInputDraft,
editingSession,
onAttentionInputFocus,
onAttentionPromptSend,
onComposerHeightChange,
onMessageSent,
}: {
interface AgentComposerProps {
agentId: string;
serverId: string;
isPaneFocused: boolean;
@@ -1772,12 +1839,83 @@ function ActiveAgentComposer({
onAttentionPromptSend: () => void;
onComposerHeightChange: (height: number) => void;
onMessageSent: () => void;
}) {
}
/** What differs between the composer of a workspace tab and that of an embed. */
interface AgentComposerSurfaceProps {
workspaceId: string | null;
onClientSlashCommand: (command: ClientSlashCommand) => Promise<void>;
attachmentScopeKeys?: readonly string[];
onOpenWorkspaceAttachment?: (attachment: WorkspaceComposerAttachment) => void;
autoFocus: boolean;
inputMode?: ComposerInputMode;
placeholder?: string;
}
function AgentComposer({
agentId,
serverId,
isPaneFocused,
cwd,
isSubmitLoading,
agentInputDraft,
editingSession,
onAttentionInputFocus,
onAttentionPromptSend,
onComposerHeightChange,
onMessageSent,
workspaceId,
onClientSlashCommand,
attachmentScopeKeys,
onOpenWorkspaceAttachment,
autoFocus,
inputMode,
placeholder,
}: AgentComposerProps & AgentComposerSurfaceProps) {
const isCompactFormFactor = useIsCompactFormFactor();
const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow(
COMPACT_CONTENT_WIDTH,
{ initialIsBelow: isCompactFormFactor },
);
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
<Composer
agentId={agentId}
serverId={serverId}
workspaceId={workspaceId}
blurOnSubmit={isNative}
isPaneFocused={isPaneFocused}
textSource={agentInputDraft.textSource}
onChangeText={agentInputDraft.editText}
textReplacement={agentInputDraft.textReplacement}
attachments={agentInputDraft.attachments}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={onOpenWorkspaceAttachment}
onChangeAttachments={agentInputDraft.setAttachments}
cwd={cwd}
getDraftRevision={agentInputDraft.getRevision}
clearDraft={agentInputDraft.clear}
editingSession={editingSession}
autoFocus={autoFocus}
autoFocusKey={String(agentInputDraft.attachmentFocusRequestId)}
isSubmitLoading={isSubmitLoading}
onAttentionInputFocus={onAttentionInputFocus}
onAttentionPromptSend={onAttentionPromptSend}
onComposerHeightChange={onComposerHeightChange}
onMessageSent={onMessageSent}
onClientSlashCommand={onClientSlashCommand}
inputMode={inputMode}
placeholder={placeholder}
isCompactLayout={isCompactComposerLayout}
/>
</View>
);
}
/** A workspace tab's composer: `/exit` and `/clear` close or retarget the tab. */
function PaneAgentComposer(props: AgentComposerProps) {
const { agentId, serverId, cwd } = props;
const isCompactFormFactor = useIsCompactFormFactor();
const paneContext = usePaneContext();
const openInSidePane = useSettings((settings) => settings.openInSidePane);
const { workspaceId, tabId, retargetCurrentTab } = paneContext;
@@ -1847,48 +1985,78 @@ function ActiveAgentComposer({
);
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
<Composer
agentId={agentId}
serverId={serverId}
workspaceId={workspaceId}
blurOnSubmit={isNative}
isPaneFocused={isPaneFocused}
textSource={agentInputDraft.textSource}
onChangeText={agentInputDraft.editText}
textReplacement={agentInputDraft.textReplacement}
attachments={agentInputDraft.attachments}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={agentInputDraft.setAttachments}
cwd={cwd}
getDraftRevision={agentInputDraft.getRevision}
clearDraft={agentInputDraft.clear}
editingSession={editingSession}
autoFocus
autoFocusKey={String(agentInputDraft.attachmentFocusRequestId)}
isSubmitLoading={isSubmitLoading}
onAttentionInputFocus={onAttentionInputFocus}
onAttentionPromptSend={onAttentionPromptSend}
onComposerHeightChange={onComposerHeightChange}
onMessageSent={onMessageSent}
onClientSlashCommand={handleClientSlashCommand}
isCompactLayout={isCompactComposerLayout}
/>
</View>
<AgentComposer
{...props}
workspaceId={workspaceId}
onClientSlashCommand={handleClientSlashCommand}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
autoFocus
/>
);
}
/**
* The composer of an embed. It has no tab: `/clear` archives the agent and opens a fresh draft in
* the agent's workspace, as forking to a tab does. It does not take focus on mount; the plugin's
* screen decides where the user starts.
*/
function EmbeddedAgentComposer({
options,
...props
}: AgentComposerProps & { options: EmbeddedComposer }) {
const { agentId, serverId } = props;
const workspaceId = useSessionStore(
(state) => resolveChatAgentFromSession(state, serverId, agentId)?.workspaceId ?? null,
);
const { archiveAgent } = useArchiveAgent();
const handleClientSlashCommand = useCallback(
async (command: ClientSlashCommand) => {
const agent = resolveChatAgentFromSession(useSessionStore.getState(), serverId, agentId);
if (!agent) {
throw new Error("Agent not found");
}
if (command.kind === "replace-agent-with-draft") {
if (!agent.workspaceId) {
throw new Error("This agent has no workspace to start a draft in");
}
navigateToWorkspace({
serverId,
workspaceId: agent.workspaceId,
target: { kind: "draft", draftId: generateDraftId(), setup: buildDraftAgentSetup(agent) },
});
}
await archiveAgent({ serverId, agentId });
},
[agentId, archiveAgent, serverId],
);
return (
<AgentComposer
{...props}
workspaceId={workspaceId}
onClientSlashCommand={handleClientSlashCommand}
autoFocus={false}
inputMode={options.inputMode}
placeholder={options.placeholder}
/>
);
}
function AgentSessionUnavailableState({
serverId,
serverLabel,
connectionStatus,
lastError,
helloRejection,
isUnknownDaemon = false,
t,
}: {
serverId: string | null;
serverLabel: string;
connectionStatus: HostRuntimeConnectionStatus;
lastError: string | null;
helloRejection: DaemonHelloRejection | null;
isUnknownDaemon?: boolean;
t: TFunction;
}) {
@@ -1905,6 +2073,21 @@ function AgentSessionUnavailableState({
);
}
if (helloRejection && serverId) {
return (
<View style={styles.container}>
<View style={styles.centerState}>
<HostRefusalAlert
serverId={serverId}
hostName={serverLabel}
rejection={helloRejection}
testID="agent-panel-refusal-alert"
/>
</View>
</View>
);
}
const isConnecting = connectionStatus === "connecting";
const isPreparingSession = connectionStatus === "online";
+5
View File
@@ -84,3 +84,8 @@ export function usePaneFocus(): PaneFocusContextValue {
invariant(value, "PaneFocusContext is required");
return value;
}
/** The focus of the pane around this component, or null on a screen with no panes. */
export function useEnclosingPaneFocus(): PaneFocusContextValue | null {
return useContext(PaneFocusContext);
}
+2 -1
View File
@@ -836,7 +836,8 @@ describe("evaluatePluginClientBundle", () => {
`(function(require) {
const shared = require("@getpaseo/plugin");
const client = require("@getpaseo/plugin/client");
const { ExternalLink, Loading, Markdown } = require("@getpaseo/plugin/client/ui");
const { AgentChat, ExternalLink, Loading, Markdown } = require("@getpaseo/plugin/client/ui");
if (typeof AgentChat !== "function") throw new Error("AgentChat");
if (typeof Markdown !== "function") throw new Error("Markdown");
if (typeof ExternalLink !== "function") throw new Error("ExternalLink");
if (typeof Loading !== "function") throw new Error("Loading");
@@ -0,0 +1,35 @@
import type { AgentChatProps } from "@getpaseo/plugin/client/ui";
import { lazy, Suspense, useMemo } from "react";
import type { EmbeddedComposer } from "@/agent-embed";
import { FilePanelLoading } from "@/file-panels/loading";
import { usePluginInstallationServerId } from "../installation-provider";
/**
* The embed renders the agent tab's chain, composer included. The plugin runtime loads this
* module with the host runtime, so a static import would put the whole chat surface in the host
* runtime's import graph. Only the first chat of a session waits for it.
*/
const AgentEmbed = lazy(async () => ({ default: (await import("@/agent-embed")).AgentEmbed }));
const LOADING = <FilePanelLoading />;
export function AgentChat({ agentId, hostId, composer, testID }: AgentChatProps) {
const installationServerId = usePluginInstallationServerId();
const serverId = hostId ?? installationServerId;
const hasComposer = composer !== false;
const inputMode = composer && composer.controls === "none" ? "message" : "chat";
const placeholder = composer ? composer.placeholder : undefined;
const embedComposer = useMemo<EmbeddedComposer | null>(
() => (hasComposer ? { inputMode, placeholder } : null),
[hasComposer, inputMode, placeholder],
);
if (!serverId) {
throw new Error("AgentChat needs a hostId outside a plugin surface");
}
return (
<Suspense fallback={LOADING}>
<AgentEmbed serverId={serverId} agentId={agentId} composer={embedComposer} testID={testID} />
</Suspense>
);
}

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