Compare commits

..
Author SHA1 Message Date
Mohamed Boudra af36a85a8f Share workspace services through tunnel providers and remove the service proxy (#11490)
* feat(scripts): share workspace services through tunnel providers

Workspace services now show their real address, http://localhost:<port>,
and you can expose a running service at a public URL by picking a tunnel
provider from the Scripts menu. The *.localhost friendly-URL proxy is
removed.

The proxy shared the daemon's HTTP server, so service WebSocket upgrades
were handled twice and dev servers lost HMR (#638). Tunnel providers
(#11036) already give a public URL with one owner per exposure, so the
proxy no longer earns its upgrade routing, host classification, and
config surface.

daemon.serviceProxy and PASEO_SERVICE_PROXY_* are now ignored with a
startup warning instead of failing startup (COMPAT(serviceProxyRemoved)).
Script payloads keep the legacy proxy URL fields on the wire so older
clients still parse them. PASEO_URL and PASEO_SERVICE_<NAME>_URL now
point at http://localhost:<port>.

Closes #638

* fix(scripts): let the daemon open workspace service tunnels

The app opened service tunnels with the generic tunnel RPC and a fixed
127.0.0.1 target. Two things broke:

- v0.18 daemons already advertise tunnelProviders, so the app showed the
  tunnel picker there, but those daemons never report a script's tunnel or
  close it when the service stops. The tunnel ran with no way to see,
  copy, or stop it.
- A service that listens only on ::1 got a tunnel to 127.0.0.1, so the
  public URL failed while health showed the service as healthy.

The daemon now owns the workflow through workspace.script.tunnel.open and
workspace.script.tunnel.close, gated on a new workspaceScriptTunnels
feature. It probes which loopback address the service accepts, and it
builds the exposure ID and slug, so clients no longer construct them.

* test(server): drop removed service proxy constructor slots

Removing the serviceProxy and serviceProxyPublicBaseUrl parameters shifted the positional VoiceAssistantWebSocketServer arguments in four test harnesses, so providerSnapshotManager and the push sender landed in the wrong slots. The runtime store also goes back to storing entries as given, since port is optional and every reader checks its type.

* fix(scripts): show a service tunnel as an address of its service

The Scripts menu drew the tunnel as a full menu row with its own icon,
so it read as a second service. It now sits on the host rail under
localhost:<port>: "Tunnel ›" when there is none, one host row with
Open, Copy and Stop when ready, and one status row while connecting or
failed. The full URL, provider and errors move into tooltips.

The provider picker lists names only. An unavailable provider shows
"Unavailable", and its reason and fix sit behind an info tip.

Submenu flyouts now open on the left when the right side has no room,
so the picker no longer covers a menu at the right edge of the window.
The side is chosen once, when the flyout opens. useMenuSubTrigger gives
custom rows the same anchor, hover intent and navigation as
MenuSubTrigger.

The compact sheet stops repeating the tunnel URL under Copy.

* fix(scripts): show tunnel details to touch users

On touch, the tunnel host row tooltip now opens on press, and the compact
sheet notes a temporary tunnel URL next to the host.
2026-12-01 11:32:24 +07:00
c3c86b9d18 perf(app): turn the status ring thirty times a second, not once per display frame (#11474)
A window is composed and presented again every time something in it
moves. The ring on a running workspace turned with the display, so a
visible ring held the whole window at 60 or 120 frames a second for as
long as any agent ran, even while the chat on screen was idle. On macOS
that work lands in WindowServer; on Android in RenderThread.

The ring now takes 27 positions per 900 ms turn, which is 30 a second.
Each is a position the smooth turn passes through, 1.2 px apart on the
12 px ring. On web the keyframes use steps(27), and the compositor draws
a frame only when the step changes. On native the shared clock holds its
position at each step; a view whose transform did not change is not
invalidated, so nothing is drawn between steps.

The native clock starts on a frame and advances whole frames, so a step
that is a whole number of frames long would turn over exactly on a
frame, and rounding would pick the side. Each step turns over an eighth
of a step early, which is between two frames at 60, 90 and 120 Hz.

The tool-call shimmer still moves every frame, so a chat with a running
tool call in view draws at the display's rate as before.

Refs #5429, #7559, #3971

Co-authored-by: Wanno Drijfhout <git@wanno.eu>
Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: Daniel JB Clark <djbclark@gmail.com>
2026-12-01 11:00:05 +07:00
Mohamed Boudra 5140065373 fix(app): send with hardware-keyboard Return on iPhone (#11537)
The composer's Return key command was registered only for the iPad
idiom, so an iPhone with a keyboard attached inserted a newline instead.
A key command runs only for physical key presses, so the on-screen
keyboard's Return needs no gate.
2026-12-01 10:54:50 +07:00
Mohamed Boudra 0f3ed9118b fix(app): stop Cmd/Ctrl+click from entering sidebar select mode (#11472)
Holding Cmd to preview sidebar jump badges or rolling off shortcuts like Cmd+Tab or Cmd+B before clicking a workspace row accidentally entered sticky multi-select mode. Outside select mode, only Shift+click (without Cmd/Ctrl) and the row menu now enter select mode; once select mode is active, Cmd/Ctrl+click and plain clicks continue to toggle rows and Shift+click continues to adjust ranges.

Also make readPressModifiers trust explicit boolean modifier flags on non-touch pointer events instead of ORing with the held-key tracker, so a swallowed key-up cannot cause phantom modifier clicks on desktop while keeping the fallback for native and touch-synthesized presses.
2026-12-01 10:45:24 +07:00
paseo-bot[bot]andStelath 66b57ed3b3 fix(pi): keep the turn open when an extension sends context before Pi answers the prompt (#11533)
Pi answers the prompt RPC only after extension preflight. A custom message an
extension sends from before_agent_start therefore reaches Paseo before the
response and before agent_start. The adapter treated that message as an
extension command's output and completed the turn. The run then continued
without a turn, and Pi's echo of the prompt arrived without the client message
ID, so the chat showed the user's message twice.

A custom message no longer completes a turn whose prompt is unanswered. Once Pi
answers, the adapter asks Pi for its state, as it already does for slash
commands, and completes the turn only if no run is starting.

Co-authored-by: Stelath <25530613+Stelath@users.noreply.github.com>
2026-12-01 03:13:28 +00:00
b9bd2a2b05 fix(acp): report thinking changes returned by mode selection (#11478)
* fix(acp): report thinking changes returned by mode selection

* Verify ACP mode changes through the daemon

---------

Co-authored-by: Shane Su <shane.su@maiscrm.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 03:12:52 +00:00
748972b982 fix(antigravity): fail ACP turns ending with silent executor errors (#10885)
* fix(antigravity): fail ACP turns ending with silent executor errors

* fix(antigravity): narrow turnEnd and keep queued follow-ups after a failed one

AcpTransformer.turnEnd now returns a ProviderError and no longer exposes the
last wire chunk, so ACP chunk boundaries stay inside @getpaseo/plugin. The
Antigravity provider matches the error frame on the whole assistant message.

A tool call update now clears lastAssistantMessage. When a follow-up reply
fails while later follow-ups are queued, Paseo reports it as a notice and
sends the rest instead of dropping them.

Refs #10776

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

---------

Co-authored-by: V <vecsat@foxmail.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
Co-authored-by: luke <luopeihuan@gmail.com>
2026-12-01 10:00:23 +07:00
paseo-bot[bot]andPatrick Motard 1f6b2493f0 Load project resources in trusted Pi chats (#11527)
* fix(pi): trust project resources for user sessions

* fix(pi): respect workspace trust for project resources

* test(agent): cover trusted lazy resume

* fix(agent): fail explicitly on workspace-trust lookup errors

Swallowing lookup failures and defaulting to untrusted hid infrastructure
errors behind a degraded session instead of surfacing them, per the
server's fail-explicit error-handling convention.

* refactor(agent): name resume options type

* Keep Pi project approval on trusted session launches

Co-authored-by: Patrick Motard <motard19@gmail.com>

* Share Pi approval arguments across create and resume

* Approve project resources for custom Pi providers

---------

Co-authored-by: Patrick Motard <motard19@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 02:43:10 +00:00
paseo-bot[bot]andStelath 2575621974 fix(pi): wait for the prompt response while Pi runs extension preflight (#11525)
Pi answers the prompt RPC only after extension preflight. An extension can ask
the user a question or compact the session there, which can take minutes. The
adapter gave the request the control-plane deadline, failed the turn with
"Pi RPC request timed out phase=prompt", and Pi then ran the prompt anyway:
the reply arrived outside any turn and the user's message appeared twice.

The prompt request now waits for a response, process death or close, as the
compact request already does. Stop still interrupts a prompt that never
answers.

Co-authored-by: Stelath <25530613+Stelath@users.noreply.github.com>
2026-12-01 02:42:41 +00:00
paseo-bot[bot]andphanthawas.jir c51431fc98 fix(server): list commands without starting an archived agent's runtime (#11521)
A timeline read loads an archived agent as a history session. The list
commands handler checked archivedAt only for agents that were not loaded,
so it called listCommands on that session and started the provider
process. Read the stored record for loaded agents too.

Co-authored-by: phanthawas.jir <phanthawas.jir@dappmaker.co.th>
2026-12-01 02:12:51 +00:00
paseo-bot[bot]andWaterChen 7454db9b0d Show when a worktree archive is pending (#11519)
* fix(app): show a worktree archive as pending while the host checks it

Since #9625 an archive of a worktree first asks the host for its checkout
status, then warns or archives. The row only showed its pending state once
that answer arrived, so on a slow host the press looked like it did nothing
and people pressed again.

runWorkspaceArchiveAttempt already tracks the in-flight attempt per
workspace. Make it observable and have the sidebar rows and the git actions
treat it as archiving, so the pending ring and disabled state show from the
press until the archive starts or the warning is cancelled.

Closes #10366

* Update archive pending tests for the force option

Co-authored-by: WaterChen <chenxxyy299@gmail.com>

---------

Co-authored-by: WaterChen <chenxxyy299@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 01:13:12 +00:00
kotusenka c00398cd10 fix(server): keep scheduled worktree runs in their project (#10378) 2026-12-01 01:12:44 +00:00
paseo-bot[bot] 6e1dbe31af fix(server): build the OpenCode tool manifest only when it is requested (#11518)
Since #11189, one daemon config reload runs the tools, mcp.injectIntoAgents
and browserTools.enabled listeners, and each one rebuilt the full agent tool
manifest on the main thread. A reload that turns on browser tools blocked the
event loop for 30-78 ms on CI runners, and the password-protected config
reload gate (< 50 ms) in plugin-paseo-api.e2e failed on main and on PRs.

The manifest is only read when OpenCode asks the bridge for the unbound tool
list. The provider runtime now passes the bridge a catalog factory; the bridge
builds the catalog on the first request and reuses it until the factory is
replaced. A config change now only swaps a closure.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 00:36:44 +00:00
SunicemanandShane Su 0437922aff fix(app): preserve filesystem roots in Explorer paths (#11206)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 23:42:42 +00:00
paseo-bot[bot] eaa4589e07 fix(server): keep GitHub check details when a job log fails (#11509)
A job log is optional context. Keep the annotations and failed jobs available when GitHub CLI cannot return one of the logs.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 22:42:42 +00:00
paseo-bot[bot] 4c480c9afe Show when an HTML file is too large to preview on desktop (#11504)
* fix(app): explain when an HTML file is too large to preview

Electron leaves the preview blank when the encoded document URL exceeds its 2 MiB limit. Show the existing file size message before trying to load a URL that Electron will reject.

* fix(app): theme the oversized HTML preview message

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 21:42:39 +00:00
paseo-bot[bot] 39709a4a97 test(website): wait for hydration before focusing the Pro seat help (#11508)
Hydration scrolls the window back to the top. When the Hub page hydrated
after the test had scrolled the Pro card into view and focused its help,
the tooltip stayed open but off screen, and toBeInViewport failed on
webkit in main CI run 46454713101.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 21:21:03 +00:00
SunicemanandShane Su 85b68cb062 Load GitHub check annotations and workflow jobs with GET (#11476)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 21:12:42 +00:00
Matchy d399c82f51 fix(server): keep plugin entries other writers put in config.json (#11501)
The daemon owns plugin source entries and `paseo reload` does not pick up
edits to `plugins`, so its in-memory copy goes stale when config.json is
edited while it runs. Every plugin operation (install, enable, disable,
update, remove) then wrote that whole stale map back to disk. A hand-added
entry was silently deleted by the next operation on any other plugin, and
an entry removed by hand was written back. Local directory plugins hit
this most, since they are the ones people add by editing config.json.

Persisting a plugins patch now applies only the entries that changed
relative to the in-memory copy onto the plugins read from disk. Reload
still ignores plugin edits; they now survive until the next restart loads
them, as docs/plugins.md describes.

Verified with new DaemonConfigStore tests covering a hand-added entry, a
hand-removed entry, and removing one plugin while another sits on disk;
all three failed before the change.
2026-11-30 19:42:40 +00:00
SunicemanandShane Su 9a520f0adc Keep attached plugin slash commands out of the agent conversation (#11483)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 17:12:44 +00:00
Mohamed Boudra 81357c6e7b fix(app): keep the Restoring screen up until a restored workspace is ready (#11486)
Two separate races let the restore gate drop early.

The daemon sends the workspace_update before the restore reply, but the
app batched workspace updates to the next animation frame. The reply
resolved first, the route never saw "restoring with the workspace
present", no post-restore handoff started, and the chat mounted while it
was still loading. Buffered workspace updates now flush when any reply
arrives, so a caller that reads the store after its reply sees the update.
Unsolicited updates keep their per-frame batching.

The handoff released after a fixed three frames, but the desktop tab row
shows tabs only after RN-web onLayout measures every label, which runs
through ResizeObserver and setTimeout and can land later. The gate then
dropped onto an empty tab strip. On-screen chrome behind the gate can now
hold the reveal; the tab row holds until its measured track matches its
labels. The 2.5s handoff timeout still bounds the hold.
2026-11-30 23:56:14 +07:00
Mohamed Boudra 95cc11ab7b Put agent tools behind one Enable tools setting with tool groups (#11189)
* feat(server,app): group agent tools under one Enable tools setting

Replace the separate "Enable Paseo tools" and "Browser tools" settings with
one `daemon.tools` configuration: an `enabled` switch plus per-group switches
for orchestration, schedules, PR watching, and browser. Every built-in tool
now declares its group, scope, and daemon permission in one registry, so
native providers and the loopback MCP endpoint filter the same catalog.

Tools are on by default for hosts that never set the legacy injection flag.
Hosts that set `daemon.mcp.injectIntoAgents: false` keep tools off. Legacy
`daemon.mcp.*` and `daemon.browserTools.enabled` are still read when
`daemon.tools` is absent; those shims are tagged COMPAT.

Voice mode now requires tools. When tools are off it refuses with reasonCode
"tools_disabled" and the voice settings page offers a one-click Enable tools
action. Dictation is unaffected.

* fix(app): keep the host's tool groups when setup is shown again

The Orchestration step started its tool groups from the defaults and wrote
all four on Continue, so a host with Browser on or Schedules off lost those
choices when the user opened setup again. The groups sit in a collapsed row,
so the user never saw the switches. Setup now shows the host's groups and
writes only the groups the user changed.

The compact-layout setup test assumed the host starts with tools off; it now
turns them off first, since tools are on by default.

* fix(server): keep wire schemas out of the configuration entry point

tools-config.ts imported the default tool groups from protocol/messages,
which pulled every wire schema into @getpaseo/server/configuration. The
group constants now live in the Zod-free protocol/tool-groups module, and
messages re-exports them.

The WebSocket server read the config store behind a guard that only
existed for incomplete test stubs. The store is a required dependency, so
the guard is gone and the stubs provide get().

* feat(app): show only the Enable tools switch in setup

Setup is for getting started, so the Orchestration step shows a plain
Enable tools switch next to skills and the CLI. Tool groups stay in
Settings > Tools & prompts. Setup writes only the main switch, so the
groups a host already saved are never touched.

* fix(server,app): let voice mode deliver speak when agent tools are off

Main now delivers a speak-only tool set to an agent in voice mode when
agent tools are off (#11161). This branch refused voice mode in that case
with reasonCode "tools_disabled", which blocked that path.

Voice mode no longer checks the Enable tools setting. The master switch
still removes every built-in and plugin tool, except speak for an active
voice session. The voice settings alert, its Enable tools button, the
"Required for voice mode" hint, and the tools_disabled server capability
are removed.

Also removes a duplicate DaemonClient import that the rebase onto main
left in agent-mcp.e2e.test.ts.
2026-11-30 23:42:56 +07:00
paseo-bot[bot] 93c883a398 test(server): restore the live Codex smoke prompt (#11473)
The smoke test stopped before sending its prompt because it read the retired features property. Check the Plan toggle in session controls to exercise the current provider interface.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 16:42:47 +00:00
SunicemanandShane Su d5880784e2 Return the browser URL after creating a GitHub pull request (#11439)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 16:12:45 +00:00
paseo-bot[bot]andClaude Opus 5.5 5d4a1b4ed7 test(server): give the Windows socket-overflow burst room to finish (#11470)
The socket-overflow restore test stalls the daemon until the PTY has
accepted an 8 MiB burst, with a 10 s limit. On Windows, ConPTY takes
2-6 s for that write on a normal run, and a loaded runner went past
10 s. Wait up to 30 s, and raise the test timeout to 60 s to match.

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-11-30 15:49:13 +00:00
paseo-bot[bot]andbearyjd e350293d13 fix(app): apply content font size to existing chat messages (#11469)
Existing user text keeps its generated web font class after the theme changes. Subscribe the message text to appearance changes so the open chat can refresh it in place.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: bearyjd <28201062+bearyjd@users.noreply.github.com>
2026-11-30 15:13:02 +00:00
Konrad Karkosz 69563e111b fix(claude): keep the SDK version so Claude Code writes chat titles (#11057)
Paseo clears CLAUDE_AGENT_SDK_VERSION from the Claude process env along
with the parent-session vars. Without it, and with no explicit entrypoint,
Claude Code labels the process a bare `claude -p` run (`sdk-cli`) and never
writes the automatic chat title (`ai-title`) to the transcript. Keep the
version the SDK sets for its own child.
2026-11-30 14:42:41 +00:00
215 changed files with 9565 additions and 5930 deletions
-1
View File
@@ -45,7 +45,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
| [docs/service-proxy.md](docs/service-proxy.md) | Service proxy: exposing workspace scripts at public URLs, DNS setup, reverse proxy config |
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
+7 -4
View File
@@ -249,7 +249,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
mcp: { enabled: boolean, injectIntoAgents: boolean },
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -351,12 +352,14 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
+8 -10
View File
@@ -440,15 +440,13 @@ that reads what it needs from `process.env` and invoke it as
Every `scripts` entry with `"type": "service"` receives these environment variables:
| Variable | Value |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `PASEO_SERVICE_<NAME>_URL` | Proxied URL for a declared peer service. Prefer this for peer discovery; it survives peer restarts. |
| `PASEO_SERVICE_<NAME>_PORT` | Raw ephemeral port for a declared peer service. Use only as a bypass escape hatch; it can go stale if that peer restarts. |
| `PASEO_URL` | Self alias for `PASEO_SERVICE_<SELF>_URL`. |
| `PASEO_PORT` | Self alias for `PASEO_SERVICE_<SELF>_PORT`. |
| `HOST` | Bind host for the service process. |
Service proxy hostnames use the double-dash shape: `web--feature-auth--project.localhost` or, on the default branch, `web--project.localhost`. Optional public aliases use the same leftmost label under the configured public base host.
| Variable | Value |
| --------------------------- | ---------------------------------------------------------------- |
| `PASEO_SERVICE_<NAME>_URL` | Local `http://localhost:<port>` URL for a declared peer service. |
| `PASEO_SERVICE_<NAME>_PORT` | Allocated port for a declared peer service. |
| `PASEO_URL` | Self alias for `PASEO_SERVICE_<SELF>_URL`. |
| `PASEO_PORT` | Self alias for `PASEO_SERVICE_<SELF>_PORT`. |
| `HOST` | Bind host for the service process. |
`<NAME>` is normalized from the script name by uppercasing it, replacing each run of non-`A-Z0-9` characters with `_`, and trimming leading or trailing `_`. For example, `app-server` and `app.server` both normalize to `APP_SERVER`; that collision fails at spawn time with an actionable error.
@@ -505,7 +503,7 @@ Or persist it in `config.json`:
}
```
When enabled, opening the daemon HTTP origin (for example `http://localhost:6767/`) serves the web app. The same HTTP server continues to serve `/api/*`, `/mcp/*`, `/public/*`, the WebSocket upgrade, and service-proxy routes. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth.
When enabled, opening the daemon HTTP origin (for example `http://localhost:6767/`) serves the web app. The same HTTP server continues to serve `/api/*`, `/mcp/*`, `/public/*`, and the WebSocket upgrade. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth.
The served app auto-bootstraps a connection to the same origin, so opening `http://localhost:6767/` directly usually skips the Add Host step.
+8
View File
@@ -32,6 +32,11 @@ text controls do not type them. Android takes no claims: a focused `EditText`
types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned
press is still observed by the window.
Register composer Return on every iOS device. Only a physical key press runs a
`UIKeyCommand`, so the on-screen keyboard's Return still inserts a newline. Do not
gate it on the interface idiom, which excludes iPhones with a keyboard attached, or
on `GCKeyboard`, which the command does not need.
The source spike used an iPad Pro 11-inch (M4) simulator on iOS 18.6 with a
`UITextView` first responder. Both `UIWindow.sendEvent` and the root controller's
`pressesBegan` received Cmd+B, Cmd+P and Escape. With Escape registered as a
@@ -48,6 +53,9 @@ through rebinds. For numeric injection, use AppleScript physical key codes (for
25 for 9); `keystroke "9"` did not deliver a digit in the QA session.
Simulator exposes a virtual `GCKeyboard` even with Connect Hardware Keyboard off.
Verify the iOS absence case on a physical iPhone.
Xcode 27.2 has Device Hub in place of Simulator. AppleScript keystrokes reach the
device only while its view has Mac focus. Give it focus with a real mouse click
(a `CGEvent`); keystrokes sent elsewhere drive Device Hub's own controls.
Never register Backspace: it would take deletion away from text fields. Changes
to the native module require a native rebuild; an over-the-air JavaScript update
+10
View File
@@ -72,6 +72,11 @@ matches:
</MenuSurface>
```
A row that cannot be drawn as a `MenuItem`, such as the compact Tunnel sub-row in the Scripts
menu, takes the same anchor, hover intent and navigation from `useMenuSubTrigger` and draws its
own look. Put the anchor on a `View` that spans the surface. A narrower anchor adds its inset to
the flyout's overlap.
Pages are data rather than nested children because the popover renders them as _siblings_ of the
root surface — a flyout nested inside the root's box would be clipped by its `overflow: hidden`.
Declaring them separately is what lets one model drive both presentations.
@@ -127,6 +132,11 @@ of backdrop between the two that belongs to neither surface, and every pixel of
dismiss the menu you are reaching for. Overlapping deletes the strip; don't reintroduce the gap
and try to cover it with a longer timer.
A flyout opens on the right of its row. If the right side has no room and the left has more, it
opens on the left, so a menu at the right edge of the window is not covered by its own flyout. It
chooses its side once, when it is first placed. Content that arrives later does not move it out
from under the pointer.
On top of that, a flyout opens after the pointer rests ~90ms, closes ~260ms after it leaves, and
cancels its own pending close while the pointer is inside it. The grace still matters because the
pointer crosses sibling rows on the way down into the flyout.
+38 -6
View File
@@ -22,6 +22,31 @@ value.
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
## Frames
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
the platform composes and presents the whole window again: `RenderThread` on Android, the GPU
process and macOS's WindowServer on desktop. An indicator that moves with the display holds the
window at 60 or 120 frames a second for as long as an agent runs, with nothing else changing.
So an indicator moves in steps, and the step count is its frame rate:
| Indicator | Positions | Frames a second |
| ----------------- | ----------------------------------- | --------------- |
| Loader | 6 per 950 ms | 6 |
| Status ring | 27 per 900 ms (`STATUS_RING_STEPS`) | 30 |
| Tool-call shimmer | every display frame | 60 or 120 |
The ring is the one that matters most: it is on screen in the sidebar and the tab bar whenever any
agent runs, including while you read an idle chat. Its steps are positions the smooth turn passes
through, 1.2 px apart on a 12 px ring. Fewer steps start to read as ticking and buy little: measured
on an Android emulator with one ring on screen, the app used 12–15% of a core with a smooth ring,
8–10% with 27 steps, and 6–7% with either 18 or 12, because the native driver's own tick is what is
left.
Two indicators only share frames when their steps turn over at the same instants. The shimmer still
moves every frame, so a chat with a running tool call in view draws at the display's rate.
## Web
`useIndicatorLoop` runs a keyframe loop through the Web Animations API (`element.animate`). The
@@ -41,8 +66,9 @@ Two more reasons the stylesheet route does not work here:
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
cycle wherever and whenever it mounted. A stepped animation sets `easing: "step-end"` on each
keyframe; the compositor then draws a frame when a step changes and none in between.
cycle wherever and whenever it mounted. 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.
## Native
@@ -57,6 +83,9 @@ its value from the frame timestamp instead of replaying a 60 fps recording, so i
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
rotation or a translation, all inside the native driver.
`cycle(periodMs, steps)` holds the position at each step. The driver still ticks every frame, but a
view whose transform did not change is not invalidated, so nothing is drawn between steps.
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
@@ -69,7 +98,8 @@ Do not apply Unistyles dynamic styles to these `Animated.View`s; see
`e2e/browser/running-indicators.spec.ts` holds the web budgets: animation-frame callbacks, style
recalculations, paints and main-thread commits per second on a quiet running turn, React renders of
the indicator components, the loader's cadence, reduced motion, and a hidden tab. Run it with
the indicator components, the loader's and the ring's cadence, the frames a ring draws beside an
idle chat, reduced motion, and a hidden tab. Run it with
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
points of its cycle, for a pixel comparison across a change.
@@ -77,6 +107,8 @@ To hold a turn in the running state without streaming, send the mock load-test a
`Hold a running shell tool call for <N>ms`.
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
`/proc/<pid>/task/*/stat` over a fixed window. The UI thread (`sh.paseo.debug`) is the one a
regression shows up on; `RenderThread` draws 60 frames a second whenever a ring or a shimmer is on
screen, and that part is the cost of the motion itself.
`/proc/<pid>/task/*/stat` over a fixed window. A regression in how an indicator is driven shows up
on the UI thread (`sh.paseo.debug`); one in how often it moves shows up as frames rendered and on
`RenderThread`. `dumpsys gfxinfo <package> framestats` lists each frame's vsync, which shows whether
the steps are evenly spaced. On the emulator gfxinfo counts every frame that follows an idle vsync
as janky; read the frame count and the percentiles instead.
-141
View File
@@ -1,141 +0,0 @@
# Service Proxy
Paseo proxies HTTP traffic to services running inside your workspaces. Localhost service URLs are always enabled; optional public aliases and a separate service-only listener can be layered on through config.
## How it works
When a `paseo.json` script of `"type": "service"` starts, Paseo assigns it a local port and registers a route in the service proxy. Incoming requests whose `Host` header matches the script's generated hostname are forwarded to that port. HTTP requests, WebSocket upgrades, and service health checks select the reachable IPv4 or IPv6 loopback address. Services can bind to `127.0.0.1` or `::1` without changing their proxy URL.
The generated hostname is built from the script name, branch, and project:
```
<script>--<branch>--<project>.localhost
```
If the branch is `main` or `master`, the branch segment is omitted:
```
<script>--<project>.localhost
```
**Example:** a script named `dev` in the `miniweb` project on branch `feature/auth` would be reachable at:
```
dev--feature-auth--miniweb.localhost
```
Local and public routes use one combined leftmost label (`script--branch--project`). This keeps the hostname compatible with normal single-level wildcard DNS and TLS. If the combined label would exceed DNS's 63-character label limit, Paseo truncates it with a deterministic hash suffix to avoid collisions.
## Managing workspace scripts
Configured `paseo.json` scripts can be managed without addressing their backing terminal directly:
```bash
paseo script ls [--cwd <path> | --workspace <workspace-id>]
paseo script start <name> [--cwd <path> | --workspace <workspace-id>]
paseo script stop <name> [--cwd <path> | --workspace <workspace-id>]
```
The commands return the same script metadata shown by the workspace: lifecycle, service port, proxy URLs, health, exit code, and supervised terminal ID. `stop` terminates the managed terminal rather than only removing the proxy route, so normal script lifecycle cleanup remains authoritative. MCP exposes matching `list_workspace_scripts`, `start_workspace_script`, and `stop_workspace_script` tools; those require an explicit workspace ID.
## Configuration
Add a `serviceProxy` block under `daemon` in `~/.paseo/config.json`:
```json
{
"version": 1,
"daemon": {
"serviceProxy": {
"listen": "0.0.0.0:8080",
"publicBaseUrl": "https://paseoapps.my.domain.com"
}
}
}
```
| Field | Required | Description |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `listen` | No | Starts a separate service-only listener at this address. If omitted, services are still reachable on the daemon listener via localhost hosts. |
| `publicBaseUrl` | No | Adds public service host aliases and public service links. If omitted, links use localhost addresses only. |
`enabled` is accepted for old configs but no longer enables a mode. `enabled: false` suppresses optional `listen`/`publicBaseUrl` layers only; localhost service proxying remains always enabled.
## DNS and reverse proxy setup
For generated URLs to be reachable, you need wildcard DNS pointing to the machine running the Paseo daemon.
**Example:** to expose services at `https://dev--miniweb.paseoapps.my.domain.com` where the daemon host is `10.1.1.1`:
1. Configure a wildcard DNS record:
```
*.paseoapps.my.domain.com → 10.1.1.1
```
2. Set `publicBaseUrl` to `https://paseoapps.my.domain.com` in your config.
3. If you put a reverse proxy (nginx, Caddy, Traefik, etc.) in front of Paseo, point it at either the daemon listener or the optional service-only listener and ensure it forwards the `Host` header unchanged. The proxy uses the `Host` header to route requests to the correct service — rewriting it will break routing.
Public service URLs expose the workspace service itself. Daemon password authentication protects daemon APIs; it does not protect proxied dev services.
If the same reverse proxy serves the daemon web UI over HTTPS, it must also set `X-Forwarded-Proto` so the web UI can auto-connect with `wss://`. The daemon trusts forwarded headers from loopback proxies by default. If your proxy reaches the daemon from another address, configure the proxy ranges explicitly:
```json
{
"version": 1,
"daemon": {
"trustedProxies": ["loopback", "172.16.0.0/12"]
}
}
```
`PASEO_TRUSTED_PROXIES` accepts the same comma-separated values, for example `loopback,172.16.0.0/12`. Use `true` only when the final trusted proxy overwrites client-supplied `X-Forwarded-*` headers.
Nginx example:
```nginx
server {
listen 443 ssl;
server_name *.paseoapps.my.domain.com;
location / {
proxy_pass http://10.1.1.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Nginx's `$host` drops the port. If you terminate on a non-default port, use `$http_host` instead so the port survives — that is what "forwards the `Host` header unchanged" means here.
## Forwarded headers
Paseo sets these when it forwards a request to a workspace service:
| Header | Value |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Forwarded-Host` | The `Host` header verbatim, including the port when the client used one |
| `X-Forwarded-Proto` | The request scheme (`http` on the WebSocket upgrade path) |
| `X-Forwarded-For` | The immediate peer address. Replaces any existing chain, so behind your own reverse proxy this is the proxy's address, not the client's |
| `X-Forwarded-Port` | The port from the `Host` header when it has one, otherwise whatever your proxy already set |
`X-Forwarded-Port` follows the same trust rule as `X-Forwarded-Host`: the authority Paseo observed wins. When the `Host` header carries a port, that port is reported and replaces any inbound `X-Forwarded-Port`, so a client cannot forge one. When `Host` carries no port there is nothing to observe, so a value your reverse proxy set survives untouched — that is the case where nginx's `$host` drops the port and `X-Forwarded-Port` is the only source. Paseo never derives the port from the scheme. Any other `X-Forwarded-*` header your proxy sends is passed through untouched.
Services that build absolute URLs should prefer `Host` or `X-Forwarded-Host`.
### The forwarded authority is not authenticated
Route lookup normalizes the port away before matching a service hostname, so a client can address the daemon with any port in `Host` and still reach the service. That port is what lands in `X-Forwarded-Host` and `X-Forwarded-Port`. Paseo also does not check whether an inbound `X-Forwarded-Port` came from a proxy in `trustedProxies` — when `Host` carries no port, a client-supplied value is passed through.
Treat the forwarded authority as client-influenced input. A service that builds password reset links, absolute redirects, or cached URLs from it should pin its own public origin in configuration rather than deriving one from request headers. This is not specific to `X-Forwarded-Port`: the `Host` header has always carried a client-chosen port.
## Environment variables
The listen address and public base URL can also be set via environment variables, which take precedence over `config.json`:
| Variable | Description |
| ------------------------------------- | ------------------------------------------------------------------------- |
| `PASEO_SERVICE_PROXY_ENABLED` | Compatibility shim; `false` suppresses optional public/listen layers only |
| `PASEO_SERVICE_PROXY_LISTEN` | Starts the optional service-only listener, e.g. `0.0.0.0:8080` |
| `PASEO_SERVICE_PROXY_PUBLIC_BASE_URL` | Adds public service aliases and links |
@@ -2,7 +2,8 @@ import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { openSettingsSection } from "../support/helpers/settings";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
test("shows Pure black in the appearance picker", async ({ page }, testInfo) => {
await page.goto("/settings");
@@ -96,3 +97,43 @@ test("applies the interface font size to settings text", async ({ page }) => {
await expect(contentSizeInput).toHaveValue("21");
await expect(sectionTitle).toHaveCSS("font-size", "10px");
});
test("applies the content font size to an already-open chat", async ({ page }) => {
const agent = await seedMockAgentWorkspace({ repoPrefix: "chat-font-size-", title: "Font size" });
const prompt = "Existing message for the font size check";
try {
await agent.client.sendAgentMessage(agent.agentId, prompt);
await agent.client.waitForFinish(agent.agentId, 30_000);
await openAgentRoute(page, agent);
const userText = page.getByText(prompt, { exact: true });
const assistantText = page.getByTestId("assistant-message").first().locator("p").first();
const initialSize = await test.step("Read both messages at the default size", async () => {
await expect(userText).toBeVisible();
await expect(assistantText).toBeVisible();
return userText.evaluate((element) => getComputedStyle(element).fontSize);
});
const timeOrigin = await page.evaluate(() => performance.timeOrigin);
await test.step("Increase Content font size and return to the same chat", async () => {
await page.getByTestId("sidebar-settings").filter({ visible: true }).first().click();
await openSettingsSection(page, "appearance");
const size = page.getByRole("textbox", { name: "Content font size", exact: true });
await size.fill("21");
await size.press("Tab");
await expect(size).toHaveValue("21");
await clickSettingsBackToWorkspace(page);
});
await test.step("Read both messages at the new size without reloading", async () => {
expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
await expect(assistantText).not.toHaveCSS("font-size", initialSize);
const updatedSize = await assistantText.evaluate(
(element) => getComputedStyle(element).fontSize,
);
await expect(userText).toHaveCSS("font-size", updatedSize);
});
} finally {
await agent.cleanup();
}
});
@@ -1,5 +1,11 @@
import { expect, test, type Page } from "../support/fixtures";
import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSessionRowArchived,
@@ -140,6 +146,47 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
}
test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit");
+28 -1
View File
@@ -10,6 +10,7 @@ import {
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser,
openRelayPairingFromSetup,
closeRelayPairing,
@@ -24,6 +25,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setHostTools,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
@@ -426,6 +428,30 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
}
});
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
const host = await startSetupHost("tool-groups");
try {
await setHostTools(host, { groups: { schedules: false, browser: true } });
await openAppAsNewUser(page, host);
await expectSetupStep(page, "Welcome to Paseo");
await goToSetupStep(page, "Orchestration");
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
// Setup offers only the main switch; tool groups live in Settings.
await expect(
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
).toHaveCount(0);
await continueSetup(page);
await expectSetupStep(page, "Take your agents with you");
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
} finally {
await host.close();
}
});
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills");
@@ -463,6 +489,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
@@ -471,7 +498,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects");
await primary("Continue").click();
// The setup host starts with Paseo tools off; the switch starts on.
// The host has tools off; the setup switch still starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -8,11 +8,13 @@ import {
import {
captureLoaderSteps,
freezeAnimationsAt,
openIdleChatBesideRunningAgent,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordLoaderStepChanges,
recordRingAngles,
runningToolCall,
statusRings,
workingLoader,
@@ -45,6 +47,10 @@ const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
const LOADER_PERIOD_MS = 950;
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
const STATUS_RING_PERIOD_MS = 900;
const STATUS_RING_STEPS = 27;
// Thirty ring positions a second, plus the few frames a second the rest of the page draws. A ring
// that turns with the display draws sixty or more.
const RING_ONLY_FRAMES_PER_SECOND_BUDGET = 36;
// React renders these once when the indicator appears. Rendering again while the turn is quiet
// means the animation is being driven through React.
@@ -109,6 +115,45 @@ test.describe("Running indicators", () => {
}
});
test("a ring beside an idle chat redraws the window thirty times a second", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
const scene = await openIdleChatBesideRunningAgent(page);
try {
const animating = await readAnimatingTargets(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const angles = await recordRingAngles(page, STATUS_RING_PERIOD_MS * 3);
await writeFile(
testInfo.outputPath("evidence.json"),
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);
// The cadence is part of the design: the quarter is only ever at one of its even steps.
const stepDegrees = 360 / STATUS_RING_STEPS;
const offStep = angles.filter((angle) => {
const stepsAlong = angle / stepDegrees;
return Math.abs(stepsAlong - Math.round(stepsAlong)) * stepDegrees > 0.05;
});
expect.soft(offStep).toEqual([]);
expect.soft(angles.length).toBeGreaterThan(STATUS_RING_STEPS / 2);
expect.soft(angles.length).toBeLessThanOrEqual(STATUS_RING_STEPS);
} finally {
await scene.cleanup();
}
});
test("hold still when the system asks for reduced motion", async ({
page,
browser,
@@ -52,17 +52,28 @@ async function exitSelection(page: Page) {
}
/**
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
* Walks the sidebar selection click matrix on four rows: Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click)
* from normal mode navigates instead of entering select mode, Shift+click enters select mode on the
* clicked row alone, Cmd/Ctrl+click and plain clicks toggle while select mode is active, and
* Shift+click extends, shrinks, and flips a range from the anchor.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
// Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode navigate normally.
await third.click({ modifiers: [MOD] });
await expect(third).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
await first.click({ modifiers: [MOD, "Shift"] });
await expect(first).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
const openWorkspaceUrl = page.url();
await third.click({ modifiers: [MOD] });
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle.
await third.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
@@ -102,7 +113,7 @@ test.describe("sidebar workspace selection clicks", () => {
seeded = null;
});
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
@@ -111,7 +122,9 @@ test.describe("sidebar workspace selection clicks", () => {
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
@@ -99,6 +99,10 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
await rowArchiveButton(page, workspaceId).click();
}
function rowArchivePendingIndicator(page: Page, workspaceId: string) {
return workspaceRow(page, workspaceId).getByTestId("workspace-status-indicator-loading");
}
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
if (!rowBeforeThemeChange)
@@ -363,10 +367,33 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
expect(warning.message()).toContain("1 unpushed commit");
await expectWorktreeKept(page, worktree);
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
expect(relay.archiveRequests()).toBe(0);
expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true);
});
test("the row shows the archive as pending from the press until the host answers", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk-pending");
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
await openSidebarRow(page, worktree.workspaceId);
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
statusRequest.arm();
await clickRowArchiveButton(page, worktree.workspaceId);
await statusRequest.waitForHeld();
try {
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toBeVisible();
expect(statusRequest.archiveRequests()).toBe(0);
} finally {
statusRequest.release();
}
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
await expect(undoButton(page)).toBeVisible();
});
test("a worktree holding only new files warns when the repository hides untracked files", async ({
page,
}) => {
+36 -2
View File
@@ -4,6 +4,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import type {
MutableDaemonToolGroups,
MutableDaemonToolsConfigPatch,
} from "@getpaseo/protocol/messages";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -138,7 +142,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
}
export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
return scope.getByRole("switch", { name: "Enable tools", exact: true });
}
/** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -147,7 +151,37 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
const config = (await client.getDaemonConfig()).config;
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
}
/** The host's saved tool groups, read from the host itself. */
export async function hostToolGroups(host: {
port: number;
}): Promise<MutableDaemonToolGroups | undefined> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.tools?.groups;
} finally {
await client.close();
}
}
/** Saves tool settings on the host, the way Settings does. */
export async function setHostTools(
host: { port: number },
tools: MutableDaemonToolsConfigPatch,
): Promise<void> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
await client.patchDaemonConfig({ tools });
} finally {
await client.close();
}
@@ -50,6 +50,76 @@ export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspa
}
}
/**
* Opens an idle chat while an agent runs in another workspace: the only thing moving on screen is
* the running workspace's status ring in the sidebar.
*/
export async function openIdleChatBesideRunningAgent(page: Page): Promise<{
cleanup(): Promise<void>;
}> {
const running = await seedMockAgentWorkspace({
repoPrefix: "running-beside-",
title: "Running beside",
initialPrompt: HELD_TOOL_CALL_PROMPT,
});
try {
const idle = await seedMockAgentWorkspace({ repoPrefix: "idle-chat-", title: "Idle chat" });
const cleanup = async () => {
await idle.cleanup();
await running.cleanup();
};
try {
await openAgentRoute(page, { workspaceId: idle.workspaceId, agentId: idle.agentId });
await expectComposerVisible(page);
await expect(statusRings(page).first()).toBeVisible({ timeout: 30_000 });
await expect(workingLoader(page)).toHaveCount(0);
await page.mouse.move(900, 300);
return { cleanup };
} catch (error) {
await cleanup();
throw error;
}
} catch (error) {
await running.cleanup().catch(() => undefined);
throw error;
}
}
/** Every angle the first visible status ring's quarter is seen at over the window, in degrees. */
export async function recordRingAngles(page: Page, windowMs: number): Promise<number[]> {
return statusRings(page)
.first()
.evaluate(
(ring, sampleWindowMs) =>
new Promise<number[]>((resolve, reject) => {
const turning = document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && ring.contains(effect.target));
const quarter = turning?.target;
if (!quarter) {
reject(new Error("The status ring is not turning"));
return;
}
const angles = new Set<number>();
const startedAt = performance.now();
const sample = () => {
const { a, b } = new DOMMatrixReadOnly(getComputedStyle(quarter).transform);
const degrees = (Math.atan2(b, a) * 180) / Math.PI;
angles.add(Math.round(((degrees + 360) % 360) * 100) / 100);
if (performance.now() - startedAt >= sampleWindowMs) {
resolve([...angles].sort((first, second) => first - second));
return;
}
requestAnimationFrame(sample);
};
sample();
}),
windowMs,
);
}
/** The loader's current step, or null while the dots are between two readable states. */
export async function readLoaderStep(page: Page): Promise<number | null> {
const opacities = await loaderDots(page).evaluateAll((dots) =>
+1 -1
View File
@@ -519,7 +519,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
}
function idleAgentReleaseSwitch(page: Page) {
@@ -180,9 +180,7 @@ public final class PaseoHardwareKeyboardWindow: UIWindow {
}
public override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText()
&& UIDevice.current.userInterfaceIdiom == .pad
{
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText() {
commands.append(makeSubmitCommand())
}
if !isComposingText() {
@@ -156,8 +156,6 @@ function mountTimeline(
};
return {
rowElement,
scrollContainer,
render: (
segments: Partial<StreamRenderInput["segments"]>,
overrides?: Partial<Omit<StreamRenderInput, "segments">>,
@@ -195,30 +193,6 @@ function mountTimeline(
};
}
it("defers scrolling until layout when output grows inside a message", async () => {
const timeline = mountTimeline(Array.from({ length: 8 }, (_, index) => row(index)));
await timeline.settle();
let scrollCalls = 0;
timeline.scrollContainer.scrollTo = new Proxy(timeline.scrollContainer.scrollTo, {
apply(scrollTo, element, args) {
scrollCalls++;
return Reflect.apply(scrollTo, element, args);
},
});
const extraContent = document.createElement("div");
extraContent.style.height = "40px";
await act(async () => {
timeline.rowElement("message-7").append(extraContent);
await Promise.resolve();
expect(scrollCalls).toBe(0);
});
await timeline.settle();
expect(scrollCalls).toBeGreaterThan(0);
expect(timeline.distanceFromEnd()).toBe(0);
});
describe("web disclosure hold", () => {
it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])(
"keeps the reading position when mounted history becomes virtualized (compact: $isMobileBreakpoint)",
@@ -0,0 +1,79 @@
import { Animated } from "react-native";
import { describe, expect, test } from "vitest";
import { createIndicatorClock } from "./clock";
const PERIOD_MS = 900;
const STEPS = 27;
const STEP_MS = PERIOD_MS / STEPS;
// Animated only pushes a derived value to a mounted view, so this asks the node for it the way the
// view's props do.
function read(node: object): number {
if (!("__getValue" in node) || typeof node.__getValue !== "function") {
throw new Error("Not an Animated node");
}
return Number(node.__getValue());
}
// Where the cycle is at each of the given clock readings.
function positionsAt(elapsed: number[], steps?: number): number[] {
const elapsedMs = new Animated.Value(0);
const position = createIndicatorClock(elapsedMs).cycle(PERIOD_MS, steps);
return elapsed.map((ms) => {
elapsedMs.setValue(ms);
return Math.round(read(position) * 1e6) / 1e6;
});
}
// A display's frames, as the native driver's clock counts them: whole frames from zero.
function frames(hz: number, count: number): number[] {
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
}
describe("indicator clock", () => {
test("a cycle without steps advances with every frame", () => {
expect(positionsAt([0, 16, 450, 899, 900, 916])).toEqual([0, 16, 450, 899, 0, 16]);
});
test("a stepped cycle only ever sits on one of its even steps", () => {
const positions = positionsAt(frames(60, 3 * 54), STEPS);
expect(new Set(positions).size).toBe(STEPS);
for (const position of positions) {
expect(position / STEP_MS).toBeCloseTo(Math.round(position / STEP_MS), 4);
expect(position).toBeLessThan(PERIOD_MS);
}
});
test.each([60, 90, 120])("at %i Hz every step is held for the same number of frames", (hz) => {
const positions = positionsAt(frames(hz, hz * 3), STEPS);
const heldFor: number[] = [];
let run = 1;
for (let frame = 1; frame < positions.length; frame += 1) {
if (positions[frame] === positions[frame - 1]) {
run += 1;
} else {
heldFor.push(run);
run = 1;
}
}
// The first step is cut short by the lead; every step after it is whole.
expect(new Set(heldFor.slice(1))).toEqual(new Set([hz / 30]));
});
test("a frame that lands a hair early or late shows the same step", () => {
const onTime = positionsAt(frames(60, 120), STEPS);
const early = positionsAt(
frames(60, 120).map((ms) => ms - 0.2),
STEPS,
).slice(1);
const late = positionsAt(
frames(60, 120).map((ms) => ms + 0.2),
STEPS,
);
expect(early).toEqual(onTime.slice(1));
expect(late).toEqual(onTime);
});
});
@@ -7,6 +7,12 @@ import { Animated } from "react-native";
// rate and never ends or loops.
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
// that is a whole number of frames long would turn over exactly on a frame, and rounding would
// decide frame by frame which side of the step it fell on. Turning each step over this fraction of
// a step early puts the turn between two frames at all three rates.
const STEP_LEAD = 1 / 8;
/**
* Milliseconds, counted on the UI thread by React Native's native animation driver.
*
@@ -15,20 +21,31 @@ const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: tr
* on every frame it changes.
*/
export interface IndicatorClock {
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
cycle(periodMs: number): Animated.AnimatedModulo<number>;
/**
* Where a cycle of `periodMs` currently is, as milliseconds into the cycle.
*
* With `steps`, the position holds at each of that many even steps instead of advancing every
* frame. A view bound to a held position is not redrawn until the step turns over.
*/
cycle(periodMs: number, steps?: number): Animated.AnimatedInterpolation<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
run(): () => void;
}
export function createIndicatorClock(): IndicatorClock {
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
export function createIndicatorClock(
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
): IndicatorClock {
let runners = 0;
let ticking: Animated.CompositeAnimation | null = null;
return {
cycle(periodMs) {
return Animated.modulo(elapsedMs, periodMs);
cycle(periodMs, steps) {
if (!steps) {
return Animated.modulo(elapsedMs, periodMs);
}
const stepMs = periodMs / steps;
const position = Animated.modulo(Animated.add(elapsedMs, stepMs * STEP_LEAD), periodMs);
return Animated.subtract(position, Animated.modulo(position, stepMs));
},
run() {
runners += 1;
+7 -2
View File
@@ -1,3 +1,4 @@
import { AppearanceText } from "@/appearance/text";
import { useDisclosureHold } from "@/agent-stream/disclosure";
import { MessagePreview, MessageSender } from "@/components/user-message";
import { useStableEvent } from "@/hooks/use-stable-event";
@@ -570,9 +571,13 @@ export const UserMessage = memo(function UserMessage({
</View>
) : null}
{hasText ? (
<Text selectable style={userMessageStylesheet.text} dataSet={MESSAGE_TEXT_DATASET}>
<AppearanceText
selectable
style={userMessageStylesheet.text}
dataSet={MESSAGE_TEXT_DATASET}
>
{message}
</Text>
</AppearanceText>
) : null}
</MessagePreview>
</View>
@@ -2,12 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native";
import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children";
import { SettingsRowHeader } from "./row-header";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
interface SettingsCollapsibleRowProps {
label: string;
/** A line under the label explaining the group. */
hint?: string;
hintStatus?: SettingsRowHintStatus;
/** A short status shown before the chevron, so the row says something while collapsed. */
summary?: string;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
accessibilityLabel?: string;
defaultExpanded?: boolean;
testID?: string;
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
@@ -21,7 +28,11 @@ interface SettingsCollapsibleRowProps {
*/
export function SettingsCollapsibleRow({
label,
hint,
hintStatus,
summary,
control,
accessibilityLabel,
defaultExpanded = false,
testID,
children,
@@ -39,7 +50,11 @@ export function SettingsCollapsibleRow({
<View testID={testID}>
<SettingsRowHeader
label={label}
hint={hint}
hintStatus={hintStatus}
summary={summary}
control={control}
accessibilityLabel={accessibilityLabel}
onPress={toggle}
expanded={expanded}
accessibilityState={accessibilityState}
@@ -1287,7 +1287,6 @@ function WorkspaceRowWithMenu({
const toast = useToast();
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const rename = useSidebarWorkspaceRename(workspace);
const isArchiving = workspace.archivingAt !== null || isHidingWorkspace;
const redirectAfterArchive = useCallback(() => {
redirectIfArchivingActiveWorkspace({
serverId: workspace.serverId,
@@ -1306,6 +1305,8 @@ function WorkspaceRowWithMenu({
onArchiveStarted: redirectAfterArchive,
onSetHiding: setIsHidingWorkspace,
});
const isArchiving =
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
const handleArchive = useCallback(() => {
if (isArchiving) {
@@ -720,7 +720,6 @@ function StatusWorkspaceRowWithMenu({
const toast = useToast();
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const rename = useSidebarWorkspaceRename(workspace);
const isArchiving = workspace.archivingAt !== null || isHidingWorkspace;
const redirectAfterArchive = useCallback(() => {
redirectIfArchivingActiveWorkspace({
@@ -742,6 +741,8 @@ function StatusWorkspaceRowWithMenu({
onArchiveStarted: redirectAfterArchive,
onSetHiding: setIsHidingWorkspace,
});
const isArchiving =
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
const handleArchive = useCallback(() => {
if (isArchiving) return;
@@ -31,6 +31,12 @@ export const STATUS_RING_HEAD_OPACITY = 0.9;
// already turning.
export const STATUS_RING_PERIOD_MS = 900;
// The quarter takes thirty positions a second, not one per display refresh. A window is redrawn
// every time the ring moves, so a ring that moves with the display holds the whole window at the
// display's rate for as long as an agent runs. Each position is one the smooth turn passes through,
// 1.2 px further along a 12 px ring.
export const STATUS_RING_STEPS = 27;
/**
* Re-anchors a corner status dot's offset for the ring that replaces it.
*
@@ -8,11 +8,11 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
// rings already turning.
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS, STATUS_RING_STEPS).interpolate({
inputRange: [0, STATUS_RING_PERIOD_MS],
outputRange: ["0deg", "360deg"],
});
@@ -8,12 +8,15 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
// A sidebar full of agents can hold dozens of rings at once; the shared phase keeps them turning as
// one, and a row that appears mid-flight lands in step with the rings already turning.
const TURNING: IndicatorLoop = {
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
keyframes: [
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` },
{ transform: "rotate(360deg)" },
],
durationMs: STATUS_RING_PERIOD_MS,
phase: "shared",
};
+4 -3
View File
@@ -36,8 +36,9 @@ export function measureElement(element: View): Promise<Rect> {
* there is more room above. Both conditions matter: flipping into a side that is equally
* cramped just moves the clipping, so a surface taller than the whole viewport stays put.
*
* Horizontal flipping is opt-in for hover cards. Submenus choose their direction up front so
* they do not move out from under the pointer travelling toward them.
* Horizontal flipping is opt-in. Hover cards and submenu flyouts use it; a flyout chooses its
* side once, when it opens, so it does not move out from under the pointer travelling toward it
* (see `useAnchoredPosition`).
*/
function flipPlacement(input: {
placement: Placement;
@@ -156,7 +157,7 @@ export function computePosition({
placement: Placement;
alignment: Alignment;
offset: number;
/** Hover cards can choose either side; submenu direction is owned by the menu. */
/** Lets a left or right placement open on the other side when its own has no room. */
flipHorizontal?: boolean;
}): { x: number; y: number; actualPlacement: Placement } {
const actualPlacement = flipPlacement({
@@ -35,7 +35,10 @@ export type {
MenuItemProps as DropdownMenuItemProps,
} from "@/components/ui/menu";
export type { MenuPageDefinition } from "@/components/ui/menu";
export { MenuSubTrigger as DropdownMenuSubTrigger } from "@/components/ui/menu";
export {
MenuSubTrigger as DropdownMenuSubTrigger,
useMenuSubTrigger as useDropdownMenuSubTrigger,
} from "@/components/ui/menu";
export function DropdownMenuContent(props: MenuSurfaceProps): ReactElement | null {
return <MenuSurface {...props} />;
+1 -1
View File
@@ -17,7 +17,7 @@ export {
type MenuPageDefinition,
type MenuSurfaceProps,
} from "./menu-surface";
export { MenuSubTrigger } from "./menu-sub";
export { MenuSubTrigger, useMenuSubTrigger, type MenuSubTriggerBinding } from "./menu-sub";
export {
MenuCheckboxItem,
MenuHint,
@@ -192,3 +192,61 @@ describe("submenu flyout on a touch screen", () => {
expect(document.querySelector('[data-testid="show-option"]')).not.toBeNull();
});
});
/**
* A flyout overlaps its parent by a few points (`SUBMENU_OVERLAP`, plus the surface border on the
* left side). It must stop short of the 13pt inset where the parent's labels start.
*/
const MAX_OVERLAP = 12;
/** Past the hover-open delay and the surface's first placement. */
const FLYOUT_PLACED_MS = 400;
const AT_RIGHT_EDGE = { position: "absolute", top: 40, right: 8 } as const;
const AWAY_FROM_EDGE = { position: "absolute", top: 40, left: 40 } as const;
function mountSubmenuAt(position: typeof AT_RIGHT_EDGE | typeof AWAY_FROM_EDGE): void {
mount(
<View style={position}>
<MenuRoot>
<MenuTrigger testID="pill" accessibilityLabel="Open menu">
<Text>Open menu</Text>
</MenuTrigger>
<MenuSurface pages={SUB_PAGES} align="end" minWidth={220} testID="panel">
<MenuSubTrigger id="show" testID="show-row">
Show
</MenuSubTrigger>
</MenuSurface>
</MenuRoot>
</View>,
);
act(() => element("pill").click());
}
describe("submenu flyout side", () => {
beforeEach(async () => {
await page.viewport(1280, 900);
});
it("opens to the left of a menu at the right edge instead of covering it", async () => {
mountSubmenuAt(AT_RIGHT_EDGE);
await wait(FLYOUT_PLACED_MS);
act(() => element("show-row").click());
await wait(FLYOUT_PLACED_MS);
const panel = element("panel").getBoundingClientRect();
const flyout = element("panel-show").getBoundingClientRect();
expect(flyout.right).toBeLessThanOrEqual(panel.left + MAX_OVERLAP);
expect(flyout.left).toBeGreaterThanOrEqual(0);
});
it("opens to the right when there is room", async () => {
mountSubmenuAt(AWAY_FROM_EDGE);
await wait(FLYOUT_PLACED_MS);
act(() => element("show-row").click());
await wait(FLYOUT_PLACED_MS);
const panel = element("panel").getBoundingClientRect();
const flyout = element("panel-show").getBoundingClientRect();
expect(flyout.left).toBeGreaterThanOrEqual(panel.right - MAX_OVERLAP);
});
});
@@ -7,6 +7,7 @@ import {
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactElement,
type RefObject,
@@ -101,6 +102,7 @@ export function useAnchoredPosition({
offset,
scrollable,
maxHeight,
flipHorizontal = false,
}: {
open: boolean;
anchorRect: Rect | null;
@@ -110,11 +112,18 @@ export function useAnchoredPosition({
offset: number;
scrollable: boolean;
maxHeight?: number;
/**
* Lets a side placement open on the other side when its own side has no room. The side is
* chosen at the first placement and held while the surface is open, so content that grows
* later never moves the surface out from under a pointer travelling toward it.
*/
flipHorizontal?: boolean;
}) {
const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
const [contentSize, setContentSize] = useState<Size | null>(null);
const [position, setPosition] = useState<SurfacePosition | null>(null);
const [actualPlacement, setActualPlacement] = useState<Placement>(side);
const heldSideRef = useRef<Placement | null>(null);
const visibleContentSize = useMemo(() => {
if (!contentSize) return null;
@@ -136,6 +145,7 @@ export function useAnchoredPosition({
setTriggerRect(null);
setContentSize(null);
setPosition(null);
heldSideRef.current = null;
return undefined;
}
@@ -169,18 +179,21 @@ export function useAnchoredPosition({
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
// measureInWindow and Modal both use full-screen coordinates, so the display area starts at 0.
const heldSide = heldSideRef.current;
const result = computePosition({
triggerRect,
contentSize: visibleContentSize,
displayArea: { x: 0, y: 0, width: screenWidth, height: screenHeight },
placement: side,
placement: heldSide ?? side,
alignment: align,
offset,
flipHorizontal: flipHorizontal && heldSide === null,
});
if (flipHorizontal) heldSideRef.current = result.actualPlacement;
setPosition(holdSurfaceEdge(result, visibleContentSize.height));
setActualPlacement(result.actualPlacement);
}, [triggerRect, visibleContentSize, side, align, offset]);
}, [triggerRect, visibleContentSize, side, align, offset, flipHorizontal]);
const onContentLayout = useCallback(
(event: { nativeEvent: { layout: { width: number; height: number } } }) => {
@@ -214,6 +227,8 @@ export interface AnchoredSurfaceProps {
scrollable?: boolean;
/** A submenu sits inside its parent's overlay and must not paint a second backdrop. */
backdrop?: boolean;
/** See `useAnchoredPosition`. Submenus set it so a flyout near the edge opens on the far side. */
flipHorizontal?: boolean;
/**
* Hover tracking for the surface box, per docs/hover.md: plain View, pointer events, never
* a Pressable. Web-only by nature, which is all a flyout needs.
@@ -246,6 +261,7 @@ export function AnchoredSurface({
horizontalPadding = 16,
scrollable = false,
backdrop = true,
flipHorizontal = false,
onPointerEnter,
onPointerLeave,
testID,
@@ -263,6 +279,7 @@ export function AnchoredSurface({
offset,
scrollable,
maxHeight,
flipHorizontal,
});
// The surface is placed once both measurements land. Until then it sits off-screen so it can
@@ -5,6 +5,7 @@ import {
useRef,
type PropsWithChildren,
type ReactElement,
type RefObject,
} from "react";
import { Text, View, type PointerEvent } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -53,6 +54,56 @@ export function MenuSubTrigger({
disabled?: boolean;
testID?: string;
}>): ReactElement {
const { anchorRef, isOpen, open, anchorProps } = useMenuSubTrigger({ id, disabled });
const trailing = useMemo(
() => <MenuSubTrailing value={value} indicator={indicator} />,
[value, indicator],
);
return (
<View ref={anchorRef} collapsable={false} {...anchorProps}>
<MenuItem
active={isOpen}
closeOnSelect={false}
disabled={disabled}
onSelect={open}
leading={leading}
trailing={trailing}
testID={testID}
>
{children}
</MenuItem>
</View>
);
}
export interface MenuSubTriggerBinding {
/** Goes on the `View` the flyout anchors to. Span the surface's width so the flyout clears it. */
anchorRef: RefObject<View | null>;
/** Spread on that same `View`: hover intent on web popovers, nothing elsewhere. */
anchorProps: {
onPointerEnter?: (event: PointerEvent) => void;
onPointerLeave?: (event: PointerEvent) => void;
};
/** The page this trigger leads to is open. */
isOpen: boolean;
/** Opens the page. Call it from the row's press. */
open: () => void;
}
/**
* The wiring behind `MenuSubTrigger`, for a row that cannot be drawn as a `MenuItem`, such as a
* compact sub-row under a custom header. The row keeps the engine's anchor, hover intent and
* page navigation; only its look is its own.
*/
export function useMenuSubTrigger({
id,
disabled = false,
}: {
id: string;
disabled?: boolean;
}): MenuSubTriggerBinding {
const menu = useMenuContext("MenuSubTrigger");
const depth = useMenuDepth();
const { registerSubAnchor, hoverOpen, hoverClose, cancelHoverClose } =
@@ -64,11 +115,12 @@ export function MenuSubTrigger({
}, [id, registerSubAnchor]);
const isOpen = isSubPageOpen(menu.path, { id, depth });
const isPopover = menu.presentation === "popover";
const tracksHover = menu.presentation === "popover" && !disabled;
const { openSub } = menu;
const handleSelect = useCallback(() => {
menu.openSub({ id, depth });
}, [menu, id, depth]);
const open = useCallback(() => {
openSub({ id, depth });
}, [openSub, id, depth]);
const handlePointerEnter = useCallback(
(event: PointerEvent) => {
@@ -87,31 +139,13 @@ export function MenuSubTrigger({
[hoverClose, depth],
);
const trailing = useMemo(
() => <MenuSubTrailing value={value} indicator={indicator} />,
[value, indicator],
const anchorProps = useMemo(
() =>
tracksHover ? { onPointerEnter: handlePointerEnter, onPointerLeave: handlePointerLeave } : {},
[tracksHover, handlePointerEnter, handlePointerLeave],
);
return (
<View
ref={anchorRef}
collapsable={false}
onPointerEnter={isPopover && !disabled ? handlePointerEnter : undefined}
onPointerLeave={isPopover && !disabled ? handlePointerLeave : undefined}
>
<MenuItem
active={isOpen}
closeOnSelect={false}
disabled={disabled}
onSelect={handleSelect}
leading={leading}
trailing={trailing}
testID={testID}
>
{children}
</MenuItem>
</View>
);
return { anchorRef, anchorProps, isOpen, open };
}
function MenuSubTrailing({
@@ -351,6 +351,7 @@ function MenuFlyout({
anchorRect={null}
anchorRef={anchorRef}
side="right"
flipHorizontal
align="start"
offset={-SUBMENU_OVERLAP}
minWidth={minWidth}
+19 -7
View File
@@ -1671,7 +1671,16 @@ function ComposerContentImpl({
);
const runPluginClientSlashCommand = useCallback(
(resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string }): boolean => {
(
resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string },
hasAttachments: boolean,
) => {
if (hasAttachments) {
setSendError(
t("composer.errors.removePluginCommandAttachments", { command: resolved.command.name }),
);
return;
}
if (blurOnSubmit) messageInputRef.current?.blur();
clearDraft("sent");
replaceUserInput("");
@@ -1686,9 +1695,8 @@ function ComposerContentImpl({
toastErrorRef.current(error instanceof Error ? error.message : String(error));
},
});
return true;
},
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments],
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
);
const { pickImages } = useImageAttachmentPicker();
@@ -1988,10 +1996,12 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -2261,10 +2271,12 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
queueMessage(payload.text, outgoingAttachments);
},
[
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { render } from "@testing-library/react";
import { render, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { FileHtmlPreview } from "./html-preview.web";
@@ -15,4 +15,24 @@ describe("FileHtmlPreview on web", () => {
expect(changedFrame).not.toBe(firstFrame);
expect(decodeURIComponent(changedFrame.getAttribute("src") ?? "")).toContain("Changed plan");
});
it("reports oversized desktop previews using the encoded URL length", () => {
window.paseoDesktop = { platform: "linux" };
try {
// Percent encoding puts this document over the limit even though its source is smaller.
const html = `<h1>Slides</h1><!--${" ".repeat(750_000)}-->`;
const view = render(<FileHtmlPreview html={html} testID="preview" />);
const preview = within(view.container);
const status = preview.getByRole("status");
const message = within(status).getByText("panels.file.tooLargeToDisplay");
expect(getComputedStyle(message).color).toBe("rgb(102, 102, 102)");
expect(preview.queryByTestId("preview")).toBeNull();
view.rerender(<FileHtmlPreview html="<h1>Slides</h1>" testID="preview" />);
expect(preview.getByTestId("preview").getAttribute("sandbox")).toBe("allow-scripts");
} finally {
delete window.paseoDesktop;
}
});
});
@@ -1,5 +1,8 @@
import { useMemo } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { isElectronRuntime } from "@/desktop/host";
import { withPreviewCsp } from "./html-preview-csp";
// `allow-scripts` alone: the file gets an opaque origin, so a plan page can run
@@ -16,6 +19,9 @@ import { withPreviewCsp } from "./html-preview-csp";
// over with a directive browsers ignore.
const SANDBOX = "allow-scripts";
// Electron rejects iframe navigations above 2 MiB of encoded URL bytes.
const MAX_DESKTOP_PREVIEW_URL_LENGTH = 2 * 1024 * 1024;
const iframeStyle = {
flex: 1,
minHeight: 0,
@@ -23,6 +29,20 @@ const iframeStyle = {
backgroundColor: "white",
} as const;
const styles = StyleSheet.create((theme) => ({
status: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: theme.spacing[4],
},
statusText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
textAlign: "center",
},
}));
export function FileHtmlPreview({ html, testID }: { html: string; testID?: string }) {
const { t } = useTranslation();
// A document URL lets the browser resolve fragment links within the preview.
@@ -31,6 +51,13 @@ export function FileHtmlPreview({ html, testID }: { html: string; testID?: strin
() => `data:text/html;charset=utf-8,${encodeURIComponent(withPreviewCsp(html))}`,
[html],
);
if (source.length > MAX_DESKTOP_PREVIEW_URL_LENGTH && isElectronRuntime()) {
return (
<View role="status" style={styles.status}>
<Text style={styles.statusText}>{t("panels.file.tooLargeToDisplay")}</Text>
</View>
);
}
return (
// Each document loads in a new frame. The Source view keeps this preview mounted and hidden,
// and it gets a changed document in the same render that shows it again. Chromium can leave a
+2 -1
View File
@@ -289,7 +289,8 @@ function useWorkspaceScreenArchiveController({
return {
...controller,
isArchiving: workspaceDescriptor?.archivingAt != null || isHidingWorkspace,
isArchiving:
workspaceDescriptor?.archivingAt != null || isHidingWorkspace || controller.isConfirming,
canArchive: canArchiveWorkspace(workspaceDescriptor, archiveRisk),
};
}
+1 -1
View File
@@ -385,7 +385,7 @@ describe("translation resources", () => {
expect(en.settings.host.notFound).toBe("Host not found");
expect(en.settings.host.connections.title).toBe("Connections");
expect(en.settings.host.daemon.restart.title).toBe("Restart daemon");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable Paseo tools");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable tools");
expect(en.settings.providers.title).toBe("Providers");
expect(en.settings.providers.models.addModel).toBe("Add model");
expect(en.settings.providers.diagnostic.title).toBe("Diagnostic");
+45 -10
View File
@@ -195,6 +195,7 @@ export const ar: TranslationResources = {
removeReview: "إزالة مرفق المراجعة",
},
errors: {
removePluginCommandAttachments: "أزل المرفقات لتشغيل الأمر /{{command}}.",
failedToSend: "فشل في إرسال الرسالة",
failedToCreateAgent: "فشل في إنشاء الوكيل",
noHostSelected: "لم يتم تحديد مضيف",
@@ -856,7 +857,6 @@ export const ar: TranslationResources = {
scripts: {
title: "البرامج النصية",
actions: {
chooseUrl: "اختيار الرابط",
copyUrl: "نسخ الرابط",
openService: "عرض الخدمة",
restart: "إعادة التشغيل",
@@ -872,13 +872,28 @@ export const ar: TranslationResources = {
stopScript: "إيقاف{{scriptName}}",
restartScript: "إعادة تشغيل{{scriptName}}",
copyUrl: "نسخ عنوان URL لـ{{scriptName}}",
chooseUrl: "اختيار رابط {{scriptName}}",
openTunnelUrl: "فتح رابط النفق لـ {{scriptName}}",
copyTunnelUrl: "نسخ رابط النفق لـ {{scriptName}}",
stopTunnel: "إيقاف نفق {{scriptName}}",
tunnel: "نفق {{scriptName}}",
script: "البرنامج النصي{{scriptName}}",
},
routes: {
public: "الوكيل العكسي",
paseo: "Memorable",
direct: "مباشر",
tunnel: {
title: "نفق",
connecting: "جارٍ الاتصال...",
reconnecting: "جارٍ إعادة الاتصال...",
ephemeralNote: "رابط مؤقت",
openUrl: "فتح رابط النفق",
copyUrl: "نسخ رابط النفق",
stop: "إيقاف النفق",
loadingProviders: "جارٍ التحقق من مزوّدي الأنفاق...",
noProviders: "لا يوجد مزوّدو أنفاق متاحون.",
providersLoadFailed: "فشل تحميل مزوّدي الأنفاق.",
retry: "إعادة المحاولة",
openFailed: "فشل فتح النفق لـ {{scriptName}}",
stopFailed: "فشل إيقاف النفق لـ {{scriptName}}",
errorFallback: "فشل النفق.",
unavailable: "غير متاح",
},
states: {
exitCode: "الخروج من{{code}}",
@@ -3147,15 +3162,35 @@ export const ar: TranslationResources = {
tools: {
instructionsTitle: "التعليمات",
toolsTitle: "أدوات الوكلاء",
pluginNote: "الأدوات التي تضيفها الإضافات تتبع أيضًا خيار تمكين الأدوات",
updateHostForGroups: "حدّث هذا المضيف لضبط مجموعات الأدوات الفردية",
groups: {
orchestration: {
title: "التنسيق",
hint: "إدارة مساحات العمل والوكلاء والطرفيات والسكربتات",
},
schedules: {
title: "الجداول الزمنية",
hint: "إنشاء وإدارة الجداول الزمنية ونبضات المتابعة",
},
changeRequests: {
title: "مراقبة طلبات السحب",
hint: "مراقبة تحديثات طلبات السحب والدمج",
},
browser: {
title: "المتصفح",
hint: "التحكم في علامات تبويب متصفح Paseo بما في ذلك الجلسات المسجّل الدخول إليها. فعّل هذا الخيار فقط للوكلاء الموثوقين.",
},
},
},
orchestration: {
title: "التنسيق",
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
enableTools: {
title: "تمكين أدوات Paseo",
hint: "سيتمكن الوكلاء من إدارة أشجار العمل والوكلاء والجداول الزمنية",
accessibilityLabel: "حقن أدوات Paseo",
updateFailed: "تعذر تحديث أدوات Paseo.",
title: "تمكين الأدوات",
hint: "يسمح لـ Paseo والإضافات بتوفير الأدوات للوكلاء.",
accessibilityLabel: "تمكين الأدوات",
updateFailed: "تعذر تحديث الأدوات.",
},
systemPrompt: {
title: "موجه النظام",
+45 -10
View File
@@ -193,6 +193,7 @@ export const en = {
removeReview: "Remove review attachment",
},
errors: {
removePluginCommandAttachments: "Remove attachments to run /{{command}}.",
failedToSend: "Failed to send message",
failedToCreateAgent: "Failed to create agent",
noHostSelected: "No host selected",
@@ -853,7 +854,6 @@ export const en = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Choose URL",
copyUrl: "Copy URL",
openService: "View service",
restart: "Restart",
@@ -869,13 +869,28 @@ export const en = {
stopScript: "Stop {{scriptName}}",
restartScript: "Restart {{scriptName}}",
copyUrl: "Copy {{scriptName}} URL",
chooseUrl: "Choose URL for {{scriptName}}",
openTunnelUrl: "Open {{scriptName}} tunnel URL",
copyTunnelUrl: "Copy {{scriptName}} tunnel URL",
stopTunnel: "Stop {{scriptName}} tunnel",
tunnel: "{{scriptName}} tunnel",
script: "{{scriptName}} script",
},
routes: {
public: "Reverse proxy",
paseo: "Memorable",
direct: "Direct",
tunnel: {
title: "Tunnel",
connecting: "Connecting...",
reconnecting: "Reconnecting...",
ephemeralNote: "Temporary URL",
openUrl: "Open tunnel URL",
copyUrl: "Copy tunnel URL",
stop: "Stop tunnel",
loadingProviders: "Checking tunnel providers...",
noProviders: "No tunnel providers available.",
providersLoadFailed: "Failed to load tunnel providers.",
retry: "Retry",
openFailed: "Failed to open tunnel for {{scriptName}}",
stopFailed: "Failed to stop tunnel for {{scriptName}}",
errorFallback: "Tunnel failed.",
unavailable: "Unavailable",
},
states: {
exitCode: "exit {{code}}",
@@ -3247,15 +3262,35 @@ export const en = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Agent tools",
pluginNote: "Tools added by plugins also follow Enable tools",
updateHostForGroups: "Update this host to configure individual tool groups",
groups: {
orchestration: {
title: "Orchestration",
hint: "Manage workspaces, agents, terminals, and scripts",
},
schedules: {
title: "Schedules",
hint: "Create and manage schedules and heartbeats",
},
changeRequests: {
title: "PR watching",
hint: "Watch pull requests and merge requests for updates",
},
browser: {
title: "Browser",
hint: "Control Paseo browser tabs, including logged-in state. Enable only for agents you trust.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connect to this host to manage orchestration",
enableTools: {
title: "Enable Paseo tools",
hint: "Agents will be able to manage worktrees, agents and schedules",
accessibilityLabel: "Inject Paseo tools",
updateFailed: "Unable to update Paseo tools.",
title: "Enable tools",
hint: "Let Paseo and plugins give tools to agents.",
accessibilityLabel: "Enable tools",
updateFailed: "Unable to update tools.",
},
systemPrompt: {
title: "System prompt",
+45 -10
View File
@@ -196,6 +196,7 @@ export const es: TranslationResources = {
removeReview: "Eliminar archivo adjunto de reseña",
},
errors: {
removePluginCommandAttachments: "Quita los archivos adjuntos para ejecutar /{{command}}.",
failedToSend: "No se pudo enviar el mensaje",
failedToCreateAgent: "No se pudo crear el agente",
noHostSelected: "Ningún anfitrión seleccionado",
@@ -864,7 +865,6 @@ export const es: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Elegir URL",
copyUrl: "Copiar URL",
openService: "Ver servicio",
restart: "Reiniciar",
@@ -880,13 +880,28 @@ export const es: TranslationResources = {
stopScript: "Detener{{scriptName}}",
restartScript: "Reiniciar{{scriptName}}",
copyUrl: "Copiar URL de{{scriptName}}",
chooseUrl: "Elegir URL para {{scriptName}}",
openTunnelUrl: "Abrir URL del túnel de {{scriptName}}",
copyTunnelUrl: "Copiar URL del túnel de {{scriptName}}",
stopTunnel: "Detener túnel de {{scriptName}}",
tunnel: "Túnel de {{scriptName}}",
script: "Guión{{scriptName}}",
},
routes: {
public: "Proxy inverso",
paseo: "Memorable",
direct: "Directa",
tunnel: {
title: "Túnel",
connecting: "Conectando...",
reconnecting: "Reconectando...",
ephemeralNote: "URL temporal",
openUrl: "Abrir URL del túnel",
copyUrl: "Copiar URL del túnel",
stop: "Detener túnel",
loadingProviders: "Comprobando proveedores de túnel...",
noProviders: "No hay proveedores de túnel disponibles.",
providersLoadFailed: "No se pudieron cargar los proveedores de túnel.",
retry: "Reintentar",
openFailed: "No se pudo abrir el túnel para {{scriptName}}",
stopFailed: "No se pudo detener el túnel para {{scriptName}}",
errorFallback: "Error en el túnel.",
unavailable: "No disponible",
},
states: {
exitCode: "salir de{{code}}",
@@ -3180,15 +3195,35 @@ export const es: TranslationResources = {
tools: {
instructionsTitle: "Instrucciones",
toolsTitle: "Herramientas de agentes",
pluginNote: "Las herramientas de los plugins también siguen Habilitar herramientas",
updateHostForGroups: "Actualiza este host para configurar grupos de herramientas",
groups: {
orchestration: {
title: "Orquestación",
hint: "Gestiona workspaces, agentes, terminales y scripts",
},
schedules: {
title: "Programaciones",
hint: "Crea y gestiona programaciones y heartbeats",
},
changeRequests: {
title: "Seguimiento de PR",
hint: "Supervisa pull requests y merge requests para ver actualizaciones",
},
browser: {
title: "Navegador",
hint: "Controla las pestañas del navegador de Paseo, incluido el estado con sesión iniciada. Actívalo solo para agentes de confianza.",
},
},
},
orchestration: {
title: "Orquestación",
unavailable: "Conéctese a este host para administrar la orquestación",
enableTools: {
title: "Habilitar herramientasPaseo",
hint: "Los agentes podrán gestionar árboles de trabajo, agentes y horarios.",
accessibilityLabel: "Inyectar herramientasPaseo",
updateFailed: "No se pudieron actualizar las herramientas de Paseo.",
title: "Habilitar herramientas",
hint: "Permite que Paseo y los plugins proporcionen herramientas a los agentes.",
accessibilityLabel: "Habilitar herramientas",
updateFailed: "No se pudieron actualizar las herramientas.",
},
systemPrompt: {
title: "Aviso del sistema",
+45 -10
View File
@@ -197,6 +197,7 @@ export const fr: TranslationResources = {
removeReview: "Retirer la revue jointe",
},
errors: {
removePluginCommandAttachments: "Retirez les pièces jointes pour exécuter /{{command}}.",
failedToSend: "Impossible d’envoyer le message",
failedToCreateAgent: "Impossible de créer l’agent",
noHostSelected: "Aucun hôte sélectionné",
@@ -865,7 +866,6 @@ export const fr: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Choisir l’URL",
copyUrl: "Copier l’URL",
openService: "Voir le service",
restart: "Redémarrer",
@@ -881,13 +881,28 @@ export const fr: TranslationResources = {
stopScript: "Arrêter {{scriptName}}",
restartScript: "Redémarrer {{scriptName}}",
copyUrl: "Copier l’URL de {{scriptName}}",
chooseUrl: "Choisir l’URL de {{scriptName}}",
openTunnelUrl: "Ouvrir l’URL du tunnel de {{scriptName}}",
copyTunnelUrl: "Copier l’URL du tunnel de {{scriptName}}",
stopTunnel: "Arrêter le tunnel de {{scriptName}}",
tunnel: "Tunnel de {{scriptName}}",
script: "Script {{scriptName}}",
},
routes: {
public: "Proxy inverse",
paseo: "Mémorable",
direct: "Directe",
tunnel: {
title: "Tunnel",
connecting: "Connexion...",
reconnecting: "Reconnexion...",
ephemeralNote: "URL temporaire",
openUrl: "Ouvrir l’URL du tunnel",
copyUrl: "Copier l’URL du tunnel",
stop: "Arrêter le tunnel",
loadingProviders: "Vérification des fournisseurs de tunnel...",
noProviders: "Aucun fournisseur de tunnel disponible.",
providersLoadFailed: "Impossible de charger les fournisseurs de tunnel.",
retry: "Réessayer",
openFailed: "Impossible d’ouvrir le tunnel pour {{scriptName}}",
stopFailed: "Impossible d’arrêter le tunnel pour {{scriptName}}",
errorFallback: "Échec du tunnel.",
unavailable: "Indisponible",
},
states: {
exitCode: "sortie {{code}}",
@@ -3182,15 +3197,35 @@ export const fr: TranslationResources = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Outils des agents",
pluginNote: "Les outils ajoutés par les plugins suivent aussi Activer les outils",
updateHostForGroups: "Mettez à jour cet hôte pour configurer chaque groupe d'outils",
groups: {
orchestration: {
title: "Orchestration",
hint: "Gérer les workspaces, les agents, les terminaux et les scripts",
},
schedules: {
title: "Planifications",
hint: "Créer et gérer des planifications et des heartbeats",
},
changeRequests: {
title: "Suivi des PR",
hint: "Surveiller les pull requests et merge requests",
},
browser: {
title: "Navigateur",
hint: "Contrôler les onglets du navigateur Paseo, y compris les sessions connectées. Activez uniquement pour des agents de confiance.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
enableTools: {
title: "Activer les outils Paseo",
hint: "Les agents pourront gérer les worktrees, les agents et les planifications",
accessibilityLabel: "Injecter les outils Paseo",
updateFailed: "Impossible de mettre à jour les outils Paseo.",
title: "Activer les outils",
hint: "Autorise Paseo et les plugins à fournir des outils aux agents.",
accessibilityLabel: "Activer les outils",
updateFailed: "Impossible de mettre à jour les outils.",
},
systemPrompt: {
title: "Prompt système",
+45 -10
View File
@@ -196,6 +196,7 @@ export const ja: TranslationResources = {
removeReview: "レビュー添付ファイルを削除",
},
errors: {
removePluginCommandAttachments: "/{{command}} を実行するには添付ファイルを削除してください。",
failedToSend: "メッセージの送信に失敗しました",
failedToCreateAgent: "エージェントの作成に失敗しました",
noHostSelected: "ホストが選択されていません",
@@ -860,7 +861,6 @@ export const ja: TranslationResources = {
scripts: {
title: "スクリプト",
actions: {
chooseUrl: "URLを選択",
copyUrl: "URLをコピー",
openService: "サービスを表示",
restart: "再起動",
@@ -876,13 +876,28 @@ export const ja: TranslationResources = {
stopScript: "{{scriptName}}を停止",
restartScript: "{{scriptName}}を再起動",
copyUrl: "{{scriptName}}のURLをコピー",
chooseUrl: "{{scriptName}}のURLを選択",
openTunnelUrl: "{{scriptName}}のトンネルURLを開く",
copyTunnelUrl: "{{scriptName}}のトンネルURLをコピー",
stopTunnel: "{{scriptName}}のトンネルを停止",
tunnel: "{{scriptName}}のトンネル",
script: "{{scriptName}}スクリプト",
},
routes: {
public: "リバースプロキシ",
paseo: "Memorable",
direct: "直接接続",
tunnel: {
title: "トンネル",
connecting: "接続中...",
reconnecting: "再接続中...",
ephemeralNote: "一時URL",
openUrl: "トンネルURLを開く",
copyUrl: "トンネルURLをコピー",
stop: "トンネルを停止",
loadingProviders: "トンネルプロバイダーを確認中...",
noProviders: "利用可能なトンネルプロバイダーがありません。",
providersLoadFailed: "トンネルプロバイダーの読み込みに失敗しました。",
retry: "再試行",
openFailed: "{{scriptName}}のトンネル開始に失敗しました",
stopFailed: "{{scriptName}}のトンネル停止に失敗しました",
errorFallback: "トンネルエラーが発生しました。",
unavailable: "利用不可",
},
states: {
exitCode: "終了コード: {{code}}",
@@ -3142,15 +3157,35 @@ export const ja: TranslationResources = {
tools: {
instructionsTitle: "指示",
toolsTitle: "エージェントツール",
pluginNote: "プラグインが追加するツールもこのスイッチに従います",
updateHostForGroups: "ツールグループを個別に設定するにはホストを更新してください",
groups: {
orchestration: {
title: "オーケストレーション",
hint: "ワークスペース、エージェント、ターミナル、スクリプトを管理します",
},
schedules: {
title: "スケジュール",
hint: "スケジュールとハートビートを作成・管理します",
},
changeRequests: {
title: "PRの監視",
hint: "プルリクエストやマージリクエストの更新を監視します",
},
browser: {
title: "ブラウザ",
hint: "ログイン状態を含む Paseo のブラウザタブを操作します。信頼できるエージェントにのみ有効にしてください。",
},
},
},
orchestration: {
title: "オーケストレーション",
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
enableTools: {
title: "Paseoツールを有効にする",
hint: "エージェントがワークツリー、エージェント、スケジュールを管理できるようになります",
accessibilityLabel: "Paseoツールを有効にする",
updateFailed: "Paseoツールを更新できませんでした。",
title: "ツールを有効にする",
hint: "Paseo とプラグインからエージェントへツールを提供します。",
accessibilityLabel: "ツールを有効にする",
updateFailed: "ツールを更新できませんでした。",
},
systemPrompt: {
title: "システムプロンプト",
+45 -10
View File
@@ -195,6 +195,7 @@ export const ko: TranslationResources = {
removeReview: "리뷰 첨부 제거",
},
errors: {
removePluginCommandAttachments: "/{{command}} 명령을 실행하려면 첨부 파일을 제거하세요.",
failedToSend: "메시지를 보내지 못했습니다",
failedToCreateAgent: "에이전트를 생성하지 못했습니다",
noHostSelected: "선택된 호스트가 없습니다",
@@ -856,7 +857,6 @@ export const ko: TranslationResources = {
scripts: {
title: "스크립트",
actions: {
chooseUrl: "URL를 선택하세요",
copyUrl: "URL 복사",
openService: "서비스 보기",
restart: "다시 시작",
@@ -872,13 +872,28 @@ export const ko: TranslationResources = {
stopScript: "{{scriptName}} 중지",
restartScript: "{{scriptName}} 다시 시작",
copyUrl: "{{scriptName}} URL 복사",
chooseUrl: "{{scriptName}}의 URL 선택",
openTunnelUrl: "{{scriptName}} 터널 URL 열기",
copyTunnelUrl: "{{scriptName}} 터널 URL 복사",
stopTunnel: "{{scriptName}} 터널 중지",
tunnel: "{{scriptName}} 터널",
script: "{{scriptName}} 스크립트",
},
routes: {
public: "역방향 프록시",
paseo: "간편 주소",
direct: "직접",
tunnel: {
title: "터널",
connecting: "연결 중...",
reconnecting: "다시 연결 중...",
ephemeralNote: "임시 URL",
openUrl: "터널 URL 열기",
copyUrl: "터널 URL 복사",
stop: "터널 중지",
loadingProviders: "터널 공급자 확인 중...",
noProviders: "사용 가능한 터널 공급자가 없습니다.",
providersLoadFailed: "터널 공급자를 불러오지 못했습니다.",
retry: "다시 시도",
openFailed: "{{scriptName}}의 터널을 열지 못했습니다",
stopFailed: "{{scriptName}}의 터널을 중지하지 못했습니다",
errorFallback: "터널에 실패했습니다.",
unavailable: "사용할 수 없음",
},
states: {
exitCode: "종료 {{code}}",
@@ -3126,15 +3141,35 @@ export const ko: TranslationResources = {
tools: {
instructionsTitle: "지침",
toolsTitle: "에이전트 도구",
pluginNote: "플러그인이 추가한 도구도 도구 활성화 스위치를 따릅니다",
updateHostForGroups: "개별 도구 그룹을 설정하려면 이 호스트를 업데이트하세요",
groups: {
orchestration: {
title: "오케스트레이션",
hint: "워크스페이스, 에이전트, 터미널, 스크립트 관리",
},
schedules: {
title: "일정",
hint: "일정 및 하트비트 생성과 관리",
},
changeRequests: {
title: "PR 감시",
hint: "풀 리퀘스트와 머지 리퀘스트 업데이트 감시",
},
browser: {
title: "브라우저",
hint: "로그인된 상태를 포함해 Paseo 브라우저 탭을 제어합니다. 신뢰하는 에이전트에만 활성화하세요.",
},
},
},
orchestration: {
title: "오케스트레이션",
unavailable: "오케스트레이션을 관리하려면 이 호스트에 연결하세요",
enableTools: {
title: "Paseo 도구 활성화",
hint: "에이전트가 워크트리, 에이전트, 일정을 관리할 수 있습니다",
accessibilityLabel: "Paseo 도구 주입",
updateFailed: "Paseo 도구를 업데이트할 수 없습니다.",
title: "도구 활성화",
hint: "Paseo와 플러그인이 에이전트에 도구를 제공할 수 있게 합니다.",
accessibilityLabel: "도구 활성화",
updateFailed: "도구를 업데이트할 수 없습니다.",
},
systemPrompt: {
title: "시스템 프롬프트",
+45 -10
View File
@@ -196,6 +196,7 @@ export const ptBR: TranslationResources = {
removeReview: "Remover anexo de revisão",
},
errors: {
removePluginCommandAttachments: "Remova os anexos para executar /{{command}}.",
failedToSend: "Falha ao enviar mensagem",
failedToCreateAgent: "Falha ao criar agente",
noHostSelected: "Nenhum host selecionado",
@@ -860,7 +861,6 @@ export const ptBR: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Escolher URL",
copyUrl: "Copiar URL",
openService: "Ver serviço",
restart: "Reiniciar",
@@ -876,13 +876,28 @@ export const ptBR: TranslationResources = {
stopScript: "Parar {{scriptName}}",
restartScript: "Reiniciar {{scriptName}}",
copyUrl: "Copiar URL de {{scriptName}}",
chooseUrl: "Escolher URL para {{scriptName}}",
openTunnelUrl: "Abrir URL do túnel de {{scriptName}}",
copyTunnelUrl: "Copiar URL do túnel de {{scriptName}}",
stopTunnel: "Parar túnel de {{scriptName}}",
tunnel: "Túnel de {{scriptName}}",
script: "script {{scriptName}}",
},
routes: {
public: "Proxy reverso",
paseo: "Memorable",
direct: "Direta",
tunnel: {
title: "Túnel",
connecting: "Conectando...",
reconnecting: "Reconectando...",
ephemeralNote: "URL temporária",
openUrl: "Abrir URL do túnel",
copyUrl: "Copiar URL do túnel",
stop: "Parar túnel",
loadingProviders: "Verificando provedores de túnel...",
noProviders: "Nenhum provedor de túnel disponível.",
providersLoadFailed: "Falha ao carregar provedores de túnel.",
retry: "Tentar novamente",
openFailed: "Falha ao abrir túnel para {{scriptName}}",
stopFailed: "Falha ao parar túnel para {{scriptName}}",
errorFallback: "Falha no túnel.",
unavailable: "Indisponível",
},
states: {
exitCode: "saída {{code}}",
@@ -3161,15 +3176,35 @@ export const ptBR: TranslationResources = {
tools: {
instructionsTitle: "Instruções",
toolsTitle: "Ferramentas de agentes",
pluginNote: "Ferramentas adicionadas por plugins também seguem Ativar ferramentas",
updateHostForGroups: "Atualize este host para configurar grupos de ferramentas",
groups: {
orchestration: {
title: "Orquestração",
hint: "Gerencie workspaces, agentes, terminais e scripts",
},
schedules: {
title: "Agendamentos",
hint: "Crie e gerencie agendamentos e heartbeats",
},
changeRequests: {
title: "Monitoramento de PR",
hint: "Acompanhe atualizações de pull requests e merge requests",
},
browser: {
title: "Navegador",
hint: "Controle abas do navegador do Paseo, incluindo sessões conectadas. Ative apenas para agentes confiáveis.",
},
},
},
orchestration: {
title: "Orquestração",
unavailable: "Conecte-se a este host para gerenciar a orquestração",
enableTools: {
title: "Ativar ferramentas do Paseo",
hint: "Agentes poderão gerenciar worktrees, agentes e agendamentos",
accessibilityLabel: "Injetar ferramentas do Paseo",
updateFailed: "Não foi possível atualizar as ferramentas do Paseo.",
title: "Ativar ferramentas",
hint: "Permite que o Paseo e plugins forneçam ferramentas aos agentes.",
accessibilityLabel: "Ativar ferramentas",
updateFailed: "Não foi possível atualizar as ferramentas.",
},
systemPrompt: {
title: "Prompt do sistema",
+45 -10
View File
@@ -196,6 +196,7 @@ export const ru: TranslationResources = {
removeReview: "Удалить вложение проверки",
},
errors: {
removePluginCommandAttachments: "Чтобы выполнить /{{command}}, удалите вложения.",
failedToSend: "Не удалось отправить сообщение",
failedToCreateAgent: "Не удалось создать агента.",
noHostSelected: "Хост не выбран",
@@ -865,7 +866,6 @@ export const ru: TranslationResources = {
scripts: {
title: "Скрипты",
actions: {
chooseUrl: "Выбрать URL",
copyUrl: "Скопировать URL",
openService: "Открыть сервис",
restart: "Перезапустить",
@@ -881,13 +881,28 @@ export const ru: TranslationResources = {
stopScript: "Остановить скрипт {{scriptName}}",
restartScript: "Перезапустить скрипт {{scriptName}}",
copyUrl: "Скопировать URL скрипта {{scriptName}}",
chooseUrl: "Выбрать URL для {{scriptName}}",
openTunnelUrl: "Открыть URL туннеля {{scriptName}}",
copyTunnelUrl: "Скопировать URL туннеля {{scriptName}}",
stopTunnel: "Остановить туннель {{scriptName}}",
tunnel: "Туннель {{scriptName}}",
script: "Скрипт {{scriptName}}",
},
routes: {
public: "Обратный прокси",
paseo: "Запоминающийся адрес",
direct: "Прямой адрес",
tunnel: {
title: "Туннель",
connecting: "Подключение...",
reconnecting: "Переподключение...",
ephemeralNote: "Временный URL",
openUrl: "Открыть URL туннеля",
copyUrl: "Скопировать URL туннеля",
stop: "Остановить туннель",
loadingProviders: "Проверка провайдеров туннелей...",
noProviders: "Нет доступных провайдеров туннелей.",
providersLoadFailed: "Не удалось загрузить провайдеров туннелей.",
retry: "Повторить",
openFailed: "Не удалось открыть туннель для {{scriptName}}",
stopFailed: "Не удалось остановить туннель для {{scriptName}}",
errorFallback: "Ошибка туннеля.",
unavailable: "Недоступно",
},
states: {
exitCode: "Код выхода: {{code}}",
@@ -3169,15 +3184,35 @@ export const ru: TranslationResources = {
tools: {
instructionsTitle: "Инструкции",
toolsTitle: "Инструменты агентов",
pluginNote: "Инструменты плагинов также зависят от переключателя «Включить инструменты»",
updateHostForGroups: "Обновите этот хост, чтобы настраивать отдельные группы инструментов",
groups: {
orchestration: {
title: "Оркестрация",
hint: "Управление рабочими пространствами, агентами, терминалами и скриптами",
},
schedules: {
title: "Расписания",
hint: "Создание и управление расписаниями и heartbeat",
},
changeRequests: {
title: "Отслеживание PR",
hint: "Отслеживание обновлений pull request и merge request",
},
browser: {
title: "Браузер",
hint: "Управление вкладками браузера Paseo, включая авторизованные сессии. Включайте только для доверенных агентов.",
},
},
},
orchestration: {
title: "Оркестрация",
unavailable: "Подключитесь к этому хосту, чтобы управлять оркестрацией.",
enableTools: {
title: "Включить инструменты Paseo",
hint: "Агенты смогут управлять worktree, агентами и расписаниями.",
accessibilityLabel: "Добавить инструменты Paseo",
updateFailed: "Не удалось обновить инструменты Paseo.",
title: "Включить инструменты",
hint: "Позволяет Paseo и плагинам предоставлять агентам инструменты.",
accessibilityLabel: "Включить инструменты",
updateFailed: "Не удалось обновить инструменты.",
},
systemPrompt: {
title: "Системный промпт",
+45 -10
View File
@@ -195,6 +195,7 @@ export const zhCN: TranslationResources = {
removeReview: "移除 review 附件",
},
errors: {
removePluginCommandAttachments: "请先移除附件,再运行 /{{command}}。",
failedToSend: "发送消息失败",
failedToCreateAgent: "创建 Agent 失败",
noHostSelected: "未选择 Host",
@@ -852,7 +853,6 @@ export const zhCN: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "选择 URL",
copyUrl: "复制 URL",
openService: "查看服务",
restart: "重启",
@@ -868,13 +868,28 @@ export const zhCN: TranslationResources = {
stopScript: "停止 {{scriptName}}",
restartScript: "重启 {{scriptName}}",
copyUrl: "复制 {{scriptName}} 的 URL",
chooseUrl: "选择 {{scriptName}} 的 URL",
openTunnelUrl: "打开 {{scriptName}} 的隧道 URL",
copyTunnelUrl: "复制 {{scriptName}} 的隧道 URL",
stopTunnel: "停止 {{scriptName}} 的隧道",
tunnel: "{{scriptName}} 的隧道",
script: "{{scriptName}} script",
},
routes: {
public: "反向代理",
paseo: "Memorable",
direct: "直接地址",
tunnel: {
title: "隧道",
connecting: "正在连接...",
reconnecting: "正在重新连接...",
ephemeralNote: "临时 URL",
openUrl: "打开隧道 URL",
copyUrl: "复制隧道 URL",
stop: "停止隧道",
loadingProviders: "正在检查隧道提供程序...",
noProviders: "没有可用的隧道提供程序。",
providersLoadFailed: "无法加载隧道提供程序。",
retry: "重试",
openFailed: "无法为 {{scriptName}} 打开隧道",
stopFailed: "无法停止 {{scriptName}} 的隧道",
errorFallback: "隧道连接失败。",
unavailable: "不可用",
},
states: {
exitCode: "exit {{code}}",
@@ -3080,15 +3095,35 @@ export const zhCN: TranslationResources = {
tools: {
instructionsTitle: "指令",
toolsTitle: "代理工具",
pluginNote: "插件提供的工具同样受“启用工具”开关控制",
updateHostForGroups: "更新此 Host 以单独配置各个工具组",
groups: {
orchestration: {
title: "编排",
hint: "管理工作区、智能体、终端和脚本",
},
schedules: {
title: "计划任务",
hint: "创建和管理计划任务与心跳",
},
changeRequests: {
title: "PR 监控",
hint: "监控 Pull Request 和 Merge Request 的更新",
},
browser: {
title: "浏览器",
hint: "控制 Paseo 浏览器标签页,包括已登录状态。仅对受信任的智能体启用。",
},
},
},
orchestration: {
title: "编排",
unavailable: "连接到这个 Host 以管理编排",
enableTools: {
title: "启用 Paseo tools",
hint: "Agent 将能够管理 worktree、Agent 和计划",
accessibilityLabel: "注入 Paseo tools",
updateFailed: "无法更新 Paseo 工具。",
title: "启用工具",
hint: "允许 Paseo 和插件为智能体提供工具。",
accessibilityLabel: "启用工具",
updateFailed: "无法更新工具设置。",
},
systemPrompt: {
title: "System prompt",
@@ -93,19 +93,54 @@ export function readPressModifiers(
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
const trustEventFlags = !isTouchPressEvent(event);
return {
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
shift: resolveModifierFlag(event, "shiftKey", "Shift", trustEventFlags, context.held),
mod: resolveModifierFlag(event, MODIFIER_FLAGS[modKey], modKey, trustEventFlags, context.held),
};
}
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
if (typeof event !== "object" || event === null) return false;
if (Reflect.get(event, flag) === true) return true;
function resolveModifierFlag(
event: unknown,
flag: "shiftKey" | "metaKey" | "ctrlKey",
heldKey: HeldModifierKey,
trustEventFlags: boolean,
held: Pick<HeldModifierTracker, "isDown">,
): boolean {
const eventFlag = readPressFlag(event, flag);
if (trustEventFlags && eventFlag !== undefined) {
return eventFlag;
}
return eventFlag === true || held.isDown(heldKey);
}
function readPressFlag(
event: unknown,
flag: "shiftKey" | "metaKey" | "ctrlKey",
): boolean | undefined {
if (typeof event !== "object" || event === null) return undefined;
const direct = Reflect.get(event, flag);
if (typeof direct === "boolean") return direct;
const nativeEvent = Reflect.get(event, "nativeEvent");
if (typeof nativeEvent !== "object" || nativeEvent === null) return undefined;
const nativeFlag = Reflect.get(nativeEvent, flag);
return typeof nativeFlag === "boolean" ? nativeFlag : undefined;
}
function isTouchPressEvent(event: unknown): boolean {
if (typeof event !== "object" || event === null) return false;
return isTouchEventRecord(event) || isTouchEventRecord(Reflect.get(event, "nativeEvent"));
}
function isTouchEventRecord(record: unknown): boolean {
if (typeof record !== "object" || record === null) return false;
if (Reflect.get(record, "pointerType") === "touch") return true;
const type = Reflect.get(record, "type");
if (typeof type === "string" && type.startsWith("touch")) return true;
const sourceCapabilities = Reflect.get(record, "sourceCapabilities");
return (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
typeof sourceCapabilities === "object" &&
sourceCapabilities !== null &&
Reflect.get(sourceCapabilities, "firesTouchEvents") === true
);
}
@@ -407,6 +407,45 @@ describe("press modifiers", () => {
mod: false,
});
});
it("trusts explicit boolean flags on non-touch pointer events over stale held keys", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
// Simulate a missed key-up (e.g. OS overlay or native menu swallowing release).
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { shiftKey: true, metaKey: true }));
const mouseClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "mouse" },
};
expect(readPressModifiers(mouseClick, { isMac: true, held })).toEqual({
shift: false,
mod: false,
});
// Touch-synthesized clicks on web may report false modifier flags while a hardware key is held.
const touchPointerClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "touch" },
};
expect(readPressModifiers(touchPointerClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
const touchCapabilityClick = {
nativeEvent: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
sourceCapabilities: { firesTouchEvents: true },
},
};
expect(readPressModifiers(touchCapabilityClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
});
});
describe("non-TextInput native focus registration", () => {
@@ -9,6 +9,11 @@ import {
import { useToast } from "@/contexts/toast-context";
import { useCliInstall } from "@/desktop/hooks/use-install-status";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import {
createOnboardingAgentToolsPatch,
isHostAgentToolsEnabled,
} from "@/screens/settings/agent-tools-config";
export type OrchestrationChoice = "tools" | "skills" | "cli";
type Choices = Record<OrchestrationChoice, boolean>;
@@ -39,6 +44,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const toast = useToast();
const skills = useAgentSkills(serverId);
const cli = useCliInstall();
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const [chosen, setChosen] = useState<Choices>(ALL_ON);
// With nothing picked there is nothing to install, so skills read as off, as they do in Settings.
@@ -60,7 +66,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
// What the host and this computer have now, or null while it is still being read. A choice is
// skipped only when it is known to match; an unknown state is always written.
const toolsOn = config ? config.mcp.injectIntoAgents !== false : null;
const toolsEnabled = config ? isHostAgentToolsEnabled(config) : null;
const skillsInstalled = skills.status ? areSkillsInstalled(skills.status) : null;
const cliInstalled = cli.status ? cli.status.installed : null;
const { reconcile, uninstall } = skills;
@@ -68,16 +74,21 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const offersSkills = offered.skills;
const offersCli = offered.cli;
const setTools = useCallback(
(on: boolean) =>
patchConfig({ mcp: { injectIntoAgents: on } })
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
}),
[patchConfig, t, toast],
);
const applyTools = useCallback(() => {
const patch = createOnboardingAgentToolsPatch({
enabled: choices.tools,
currentEnabled: toolsEnabled,
supportsToolsConfig,
});
if (!patch) return Promise.resolve(true);
return patchConfig(patch)
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
});
}, [choices.tools, toolsEnabled, patchConfig, supportsToolsConfig, t, toast]);
const setSkillsInstalled = useCallback(
(on: boolean) => (on ? reconcile() : uninstall()),
[reconcile, uninstall],
@@ -87,7 +98,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(true);
try {
const results = await Promise.all([
choices.tools === toolsOn ? true : setTools(choices.tools),
applyTools(),
!offersSkills || choices.skills === skillsInstalled
? true
: setSkillsInstalled(choices.skills),
@@ -98,16 +109,23 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(false);
}
}, [
choices,
toolsOn,
setTools,
offersSkills,
applyTools,
choices.cli,
choices.skills,
skillsInstalled,
setSkillsInstalled,
offersSkills,
offersCli,
cliInstalled,
setCliInstalled,
]);
return { choices, setChoice, offered, skills, isApplying, apply };
return {
choices,
setChoice,
offered,
skills,
isApplying,
apply,
};
}
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { AgentSkillsRow } from "@/agent-skills";
import { SettingsCard } from "@/components/settings";
import { CommandLineRow } from "@/desktop/components/integrations-section";
import { PaseoToolsRow } from "@/screens/settings/paseo-tools-card";
import { EnableToolsSwitchRow } from "@/screens/settings/agent-tools-row";
import type { OrchestrationSetupController } from "../orchestration-setup";
/** Three switches, all on to start; Continue applies them. */
@@ -13,7 +13,7 @@ export function OrchestrationStep({ setup }: { setup: OrchestrationSetupControll
const setCli = useCallback((on: boolean) => setChoice("cli", on), [setChoice]);
return (
<SettingsCard>
<PaseoToolsRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
<EnableToolsSwitchRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
{offered.skills ? (
<AgentSkillsRow
skills={setup.skills}
@@ -33,14 +33,12 @@ describe("plugin client slash commands", () => {
expect(
resolvePluginClientSlashCommand({
text: " /review foo bar ",
hasAttachments: false,
commands: [command],
}),
).toEqual({ command, args: "foo bar" });
expect(
resolvePluginClientSlashCommand({
text: "/review foo",
hasAttachments: true,
text: "/another-command foo",
commands: [command],
}),
).toBeNull();
@@ -47,10 +47,8 @@ export function mergeSlashCommandSources<
export function resolvePluginClientSlashCommand<Command extends SlashCommandDescriptor>(input: {
text: string;
hasAttachments: boolean;
commands: readonly Command[];
}): { command: Command; args: string } | null {
if (input.hasAttachments) return null;
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(input.text.trim());
if (!match) return null;
const command = input.commands.find((candidate) => candidate.name === match[1]);
@@ -73,10 +73,29 @@ class FakeDirectoryClient {
return () => handlers.delete(registered);
}
private readonly rawListeners = new Set<(message: SessionOutboundMessage) => void>();
private readonly replyWaiters = new Map<string, () => void>();
subscribeRawMessages(handler: (message: SessionOutboundMessage) => void): () => void {
this.rawListeners.add(handler);
return () => this.rawListeners.delete(handler);
}
/** Resolves when a reply carrying `requestId` arrives, after every listener saw it. */
awaitReply(requestId: string): Promise<void> {
return new Promise((resolve) => this.replyWaiters.set(requestId, resolve));
}
emit<TType extends SessionOutboundMessage["type"]>(
message: Extract<SessionOutboundMessage, { type: TType }>,
): void {
for (const listener of this.rawListeners) listener(message);
for (const handler of this.handlers.get(message.type) ?? []) handler(message);
if (!("payload" in message)) return;
const requestId = (message.payload as { requestId?: unknown }).requestId;
if (typeof requestId !== "string") return;
this.replyWaiters.get(requestId)?.();
this.replyWaiters.delete(requestId);
}
holdWorkspaceFetch(): (result: WorkspaceFetchResult) => void {
@@ -2417,3 +2436,40 @@ it("coalesces duplicate upserts and removals within a single workspace_update ba
directory.dispose();
}
});
it("applies workspace updates the host sent before a reply by the time the reply resolves", async () => {
const serverId = "workspace-update-before-reply";
const { client, directory } = createDirectory(serverId);
const store = useSessionStore.getState();
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
store.updateSessionServerInfo(serverId, {
serverId,
hostname: null,
version: "test",
features: { workspaceMultiplicity: true, directorySync: true },
});
directory.setDemand({}, true);
await directory.refreshDemand();
try {
const restored = client.awaitReply("restore-1");
client.emit({
type: "workspace_update",
payload: {
kind: "upsert",
workspace: createWorkspaceEntry("ws-restored"),
generation: "gen-restore",
seq: 1,
},
});
client.emit({
type: "workspace.recovery.restore.response",
payload: { requestId: "restore-1", workspaceId: "ws-restored", accepted: true, error: null },
});
await restored;
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has("ws-restored")).toBe(true);
} finally {
directory.dispose();
}
});
@@ -4,7 +4,7 @@ import type {
FetchAgentsEntry,
FetchAgentsOptions,
} from "@getpaseo/client/internal/daemon-client";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { fetchAgentTimelineOnce } from "@/timeline/fetch-agent-timeline-once";
import {
normalizeProjectDescriptor,
@@ -49,6 +49,17 @@ interface WorkspaceDeltaFlushHandle {
cancel: () => void;
}
function isReply(message: SessionOutboundMessage): boolean {
if (!("payload" in message)) return false;
const payload: unknown = message.payload;
return (
typeof payload === "object" &&
payload !== null &&
"requestId" in payload &&
typeof payload.requestId === "string"
);
}
function scheduleWorkspaceDeltaFlush(callback: () => void): WorkspaceDeltaFlushHandle {
let done = false;
let rafId: number | null = null;
@@ -204,6 +215,7 @@ export class DirectorySync {
delta: WorkspaceDirectoryDelta;
}> = [];
private workspaceDeltaFlush: WorkspaceDeltaFlushHandle | null = null;
private stopObservingReplies: (() => void) | null = null;
constructor(
private readonly serverId: string,
@@ -235,10 +247,13 @@ export class DirectorySync {
this.flushAbortedTransactions();
this.releaseSubscriptions();
this.releaseScriptStatusEvents();
this.stopObservingReplies?.();
this.stopObservingReplies = null;
workspaceLabels.disconnect(this.serverId);
this.connection = connection;
this.abortPendingSessionWaits();
if (!connection.client || connection.status !== "online") return true;
this.stopObservingReplies = this.applyWorkspaceUpdatesBeforeReplies(connection.client);
if (this.scriptStatusDemand.size > 0) this.observeScriptStatusEvents();
// Reattach labels here because route-only demand can satisfy the epoch before full demand requests them.
void this.connectWorkspaceLabels().catch(() => undefined);
@@ -294,6 +309,8 @@ export class DirectorySync {
}
dispose(): void {
this.stopObservingReplies?.();
this.stopObservingReplies = null;
this.cancelPendingWorkspaceDeltas();
this.flushAbortedTransactions();
this.abortPendingSessionWaits();
@@ -357,6 +374,16 @@ export class DirectorySync {
this.applyWorkspaceDeltas([{ source, delta }]);
}
/**
* The host sends a workspace update before the reply to the request that caused it, so a
* caller reading the store after its reply must see the update. Buffered updates end at a reply.
*/
private applyWorkspaceUpdatesBeforeReplies(client: DaemonClient): () => void {
return client.subscribeRawMessages((message) => {
if (isReply(message)) this.flushPendingWorkspaceDeltas();
});
}
private flushPendingWorkspaceDeltas(): void {
if (this.workspaceDeltaFlush) {
this.workspaceDeltaFlush.cancel();
@@ -206,6 +206,10 @@ class FakeDaemonClient {
this.setConnectionState({ status: "connected" });
}
subscribeRawMessages(_handler: (message: SessionOutboundMessage) => void): () => void {
return () => {};
}
subscribeConnectionStatus(listener: (status: ConnectionState) => void): () => void {
this.listeners.add(listener);
listener(this.state);
@@ -873,6 +873,7 @@ function serializeWorkspace(workspace: WorkspaceDescriptor): StoredWorkspace {
...(script.localProxyUrl !== undefined ? { localProxyUrl: script.localProxyUrl } : {}),
...(script.publicProxyUrl !== undefined ? { publicProxyUrl: script.publicProxyUrl } : {}),
proxyUrl: script.proxyUrl,
...(script.tunnel !== undefined ? { tunnel: script.tunnel } : {}),
lifecycle: script.lifecycle,
health: script.health,
exitCode: script.exitCode,
@@ -0,0 +1,178 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
createAgentToolGroupPatch,
createAgentToolsMasterPatch,
createOnboardingAgentToolsPatch,
DEFAULT_AGENT_TOOL_GROUPS,
isHostAgentToolsEnabled,
resolveAgentToolsState,
} from "./agent-tools-config";
function makeConfig(overrides: Partial<MutableDaemonConfig> = {}): MutableDaemonConfig {
return {
relay: { enabled: false },
mcp: { injectIntoAgents: true },
browserTools: { enabled: false },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
...overrides,
};
}
describe("agent tools UI state and legacy daemon compatibility", () => {
it("reads unified daemon.tools state from a modern daemon", () => {
const state = resolveAgentToolsState({
config: makeConfig({
tools: {
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
},
mcp: { injectIntoAgents: true },
browserTools: { enabled: true },
}),
supportsToolsConfig: true,
});
expect(state).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
supportsGroupControls: true,
});
});
it("preserves saved group values when master enabled is false", () => {
const state = resolveAgentToolsState({
config: makeConfig({
tools: {
enabled: false,
groups: {
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
},
},
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
supportsToolsConfig: true,
});
expect(state.enabled).toBe(false);
expect(state.groups).toEqual({
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
});
});
it("falls back cleanly to legacy mcp.injectIntoAgents and browserTools.enabled on older daemons", () => {
const state = resolveAgentToolsState({
config: makeConfig({
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
supportsToolsConfig: false,
});
expect(state).toEqual({
enabled: false,
groups: {
...DEFAULT_AGENT_TOOL_GROUPS,
browser: true,
},
supportsGroupControls: false,
});
});
it("builds tools.* patches for modern daemons and legacy mcp/browserTools patches for older daemons", () => {
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: true })).toEqual({
tools: { enabled: false },
});
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: false })).toEqual({
mcp: { injectIntoAgents: false },
});
expect(
createAgentToolGroupPatch({
group: "schedules",
enabled: false,
supportsToolsConfig: true,
}),
).toEqual({
tools: { groups: { schedules: false } },
});
expect(
createAgentToolGroupPatch({
group: "browser",
enabled: true,
supportsToolsConfig: false,
}),
).toEqual({
browserTools: { enabled: true },
});
expect(
createAgentToolGroupPatch({
group: "orchestration",
enabled: false,
supportsToolsConfig: false,
}),
).toBeNull();
});
it("setup writes only the main switch, and only when it differs from the host", () => {
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: true,
supportsToolsConfig: true,
}),
).toBeNull();
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: false,
supportsToolsConfig: true,
}),
).toEqual({ tools: { enabled: true } });
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: null,
supportsToolsConfig: true,
}),
).toEqual({ tools: { enabled: true } });
expect(
createOnboardingAgentToolsPatch({
enabled: false,
currentEnabled: true,
supportsToolsConfig: false,
}),
).toEqual({ mcp: { injectIntoAgents: false } });
});
it("reports whether host agent tools are enabled", () => {
expect(isHostAgentToolsEnabled(null)).toBe(true);
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: true } }))).toBe(true);
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: false } }))).toBe(false);
expect(isHostAgentToolsEnabled(makeConfig({ mcp: { injectIntoAgents: false } }))).toBe(false);
});
});
@@ -0,0 +1,85 @@
import {
BUILTIN_TOOL_GROUPS,
DEFAULT_DAEMON_TOOL_GROUPS,
type BuiltInToolGroup,
type MutableDaemonConfig,
type MutableDaemonConfigPatch,
} from "@getpaseo/protocol/messages";
export type AgentToolGroupId = BuiltInToolGroup;
export type AgentToolGroupsState = Record<AgentToolGroupId, boolean>;
export const AGENT_TOOL_GROUP_ORDER: readonly AgentToolGroupId[] = BUILTIN_TOOL_GROUPS;
export const DEFAULT_AGENT_TOOL_GROUPS: AgentToolGroupsState = { ...DEFAULT_DAEMON_TOOL_GROUPS };
export interface ResolvedAgentToolsState {
enabled: boolean;
groups: AgentToolGroupsState;
supportsGroupControls: boolean;
}
export function isHostAgentToolsEnabled(config: MutableDaemonConfig | null | undefined): boolean {
if (!config) return true;
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
}
export function resolveAgentToolsState(input: {
config: MutableDaemonConfig | null | undefined;
supportsToolsConfig: boolean;
}): ResolvedAgentToolsState {
const { config, supportsToolsConfig } = input;
const enabled = isHostAgentToolsEnabled(config);
const groups: AgentToolGroupsState = {
orchestration: config?.tools?.groups?.orchestration ?? DEFAULT_AGENT_TOOL_GROUPS.orchestration,
schedules: config?.tools?.groups?.schedules ?? DEFAULT_AGENT_TOOL_GROUPS.schedules,
changeRequests:
config?.tools?.groups?.changeRequests ?? DEFAULT_AGENT_TOOL_GROUPS.changeRequests,
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
browser: config?.tools?.groups?.browser ?? config?.browserTools.enabled === true,
};
return {
enabled,
groups,
supportsGroupControls: supportsToolsConfig,
};
}
export function createAgentToolsMasterPatch(input: {
enabled: boolean;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch {
if (input.supportsToolsConfig) {
return { tools: { enabled: input.enabled } };
}
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
return { mcp: { injectIntoAgents: input.enabled } };
}
export function createAgentToolGroupPatch(input: {
group: AgentToolGroupId;
enabled: boolean;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch | null {
if (input.supportsToolsConfig) {
return { tools: { groups: { [input.group]: input.enabled } } };
}
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
if (input.group === "browser") {
return { browserTools: { enabled: input.enabled } };
}
return null;
}
/**
* Setup only sets the main switch. It never writes tool groups, so the host keeps the groups saved
* in Settings. An unknown host state is always written.
*/
export function createOnboardingAgentToolsPatch(input: {
enabled: boolean;
currentEnabled: boolean | null;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch | null {
if (input.currentEnabled === input.enabled) return null;
return createAgentToolsMasterPatch(input);
}
@@ -0,0 +1,147 @@
import React, { act, useCallback, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { I18nextProvider } from "react-i18next";
import { SettingsCard } from "@/components/settings";
import { i18n } from "@/i18n/i18next";
import {
DEFAULT_AGENT_TOOL_GROUPS,
type AgentToolGroupId,
type AgentToolGroupsState,
} from "./agent-tools-config";
import { AgentToolsRow } from "./agent-tools-row";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function Harness({
initialEnabled = true,
initialGroups = DEFAULT_AGENT_TOOL_GROUPS,
supportsGroupControls = true,
}: {
initialEnabled?: boolean;
initialGroups?: AgentToolGroupsState;
supportsGroupControls?: boolean;
}) {
const [enabled, setEnabled] = useState(initialEnabled);
const [groups, setGroups] = useState<AgentToolGroupsState>(initialGroups);
const handleGroupChange = useCallback((group: AgentToolGroupId, next: boolean) => {
setGroups((current) => ({ ...current, [group]: next }));
}, []);
return (
<I18nextProvider i18n={i18n}>
<SettingsCard>
<AgentToolsRow
enabled={enabled}
groups={groups}
supportsGroupControls={supportsGroupControls}
onEnabledChange={setEnabled}
onGroupChange={handleGroupChange}
/>
</SettingsCard>
</I18nextProvider>
);
}
function mount(props?: React.ComponentProps<typeof Harness>) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(<Harness {...props} />);
});
}
function byTestId(testID: string): HTMLElement | null {
return document.querySelector(`[data-testid="${testID}"]`);
}
function expandButton(): HTMLElement {
const row = byTestId("host-page-tools-row-toggle");
const button = row?.querySelector('[role="button"]');
if (!(button instanceof HTMLElement)) {
throw new Error("Expected expand button in host-page-tools-row-toggle");
}
return button;
}
describe("AgentToolsRow collapsible behavior", () => {
it("starts collapsed, expands to show all four groups, and preserves selections when toggled off and on", () => {
mount({
initialEnabled: true,
initialGroups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
});
const masterSwitch = byTestId("host-page-tools-master-switch");
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
// Expand the row
act(() => {
expandButton().click();
});
expect(byTestId("host-page-tool-group-orchestration")).not.toBeNull();
expect(byTestId("host-page-tool-group-schedules")).not.toBeNull();
expect(byTestId("host-page-tool-group-changeRequests")).not.toBeNull();
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
expect(document.body.textContent).toContain("Tools added by plugins also follow Enable tools");
expect(document.body.textContent).not.toContain("MCP");
const browserSwitch = byTestId("host-page-browser-tools-switch")!;
const schedulesSwitch = byTestId("host-page-tool-group-schedules-switch")!;
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
// Turn master switch off: stays expanded, disables group switches, preserves selections
act(() => {
masterSwitch?.click();
});
expect(masterSwitch?.getAttribute("aria-checked")).toBe("false");
expect(browserSwitch.getAttribute("aria-disabled")).toBe("true");
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-disabled")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
// Turn master switch back on: group switches become interactive again with saved state
act(() => {
masterSwitch?.click();
});
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
});
it("shows only Browser and an update hint on older daemons without daemonToolsConfig", () => {
mount({ supportsGroupControls: false });
act(() => {
expandButton().click();
});
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
expect(byTestId("host-page-tool-group-schedules")).toBeNull();
expect(byTestId("host-page-tool-group-changeRequests")).toBeNull();
expect(document.body.textContent).toContain(
"Update this host to configure individual tool groups",
);
});
});
@@ -0,0 +1,272 @@
import { useMutation } from "@tanstack/react-query";
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { MutableDaemonConfigPatch } from "@getpaseo/protocol/messages";
import { SettingsCollapsibleRow, SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
AGENT_TOOL_GROUP_ORDER,
createAgentToolGroupPatch,
createAgentToolsMasterPatch,
resolveAgentToolsState,
type AgentToolGroupId,
type AgentToolGroupsState,
} from "./agent-tools-config";
const GROUP_TRANSLATION_KEYS: Record<
AgentToolGroupId,
{
title:
| "settings.host.tools.groups.orchestration.title"
| "settings.host.tools.groups.schedules.title"
| "settings.host.tools.groups.changeRequests.title"
| "settings.host.tools.groups.browser.title";
hint:
| "settings.host.tools.groups.orchestration.hint"
| "settings.host.tools.groups.schedules.hint"
| "settings.host.tools.groups.changeRequests.hint"
| "settings.host.tools.groups.browser.hint";
}
> = {
orchestration: {
title: "settings.host.tools.groups.orchestration.title",
hint: "settings.host.tools.groups.orchestration.hint",
},
schedules: {
title: "settings.host.tools.groups.schedules.title",
hint: "settings.host.tools.groups.schedules.hint",
},
changeRequests: {
title: "settings.host.tools.groups.changeRequests.title",
hint: "settings.host.tools.groups.changeRequests.hint",
},
browser: {
title: "settings.host.tools.groups.browser.title",
hint: "settings.host.tools.groups.browser.hint",
},
};
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function resolveHintStatus(
error: string | null | undefined,
isPending: boolean | undefined,
): "error" | "busy" | undefined {
if (error) return "error";
if (isPending) return "busy";
return undefined;
}
/** The host's expandable "Enable tools" row, bound to the host's config, for composing inside a SettingsCard. */
export function HostAgentToolsRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const state = useMemo(
() => resolveAgentToolsState({ config, supportsToolsConfig }),
[config, supportsToolsConfig],
);
const mutation = useMutation({
mutationFn: async (patch: MutableDaemonConfigPatch) => {
const result = await patchConfig(patch);
if (!result) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return result;
},
});
const handleEnabledChange = useCallback(
(enabled: boolean) => {
mutation.mutate(createAgentToolsMasterPatch({ enabled, supportsToolsConfig }));
},
[mutation, supportsToolsConfig],
);
const handleGroupChange = useCallback(
(group: AgentToolGroupId, enabled: boolean) => {
const patch = createAgentToolGroupPatch({ group, enabled, supportsToolsConfig });
if (!patch) return;
mutation.mutate(patch);
},
[mutation, supportsToolsConfig],
);
if (!isConnected) return null;
return (
<AgentToolsRow
enabled={state.enabled}
groups={state.groups}
supportsGroupControls={state.supportsGroupControls}
onEnabledChange={handleEnabledChange}
onGroupChange={handleGroupChange}
isPending={mutation.isPending}
error={mutation.error ? toErrorMessage(mutation.error) : null}
/>
);
}
/** Plain "Enable tools" switch with no group controls, for setup. Groups stay in Settings. */
export function EnableToolsSwitchRow({
value,
onValueChange,
disabled,
}: {
value: boolean;
onValueChange: (enabled: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
return (
<SettingsRow
label={t("settings.host.orchestration.enableTools.title")}
hint={t("settings.host.orchestration.enableTools.hint")}
>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
/>
</SettingsRow>
);
}
/** Expandable "Enable tools" row on its own, for callers that control the state. */
export function AgentToolsRow({
enabled,
groups,
supportsGroupControls,
onEnabledChange,
onGroupChange,
disabled,
isPending,
error,
}: {
enabled: boolean;
groups: AgentToolGroupsState;
supportsGroupControls: boolean;
onEnabledChange: (enabled: boolean) => void;
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
disabled?: boolean;
isPending?: boolean;
error?: string | null;
}) {
const { t } = useTranslation();
const visibleGroups: readonly AgentToolGroupId[] = supportsGroupControls
? AGENT_TOOL_GROUP_ORDER
: ["browser"];
const controlsDisabled = Boolean(disabled || isPending);
const hint = error ?? t("settings.host.orchestration.enableTools.hint");
const hintStatus = resolveHintStatus(error, isPending);
const masterControl = useMemo(
() => (
<Switch
value={enabled}
onValueChange={onEnabledChange}
disabled={controlsDisabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
testID="host-page-tools-master-switch"
/>
),
[controlsDisabled, enabled, onEnabledChange, t],
);
return (
<SettingsCollapsibleRow
label={t("settings.host.orchestration.enableTools.title")}
hint={hint}
hintStatus={hintStatus}
control={masterControl}
testID="host-page-tools-row"
>
{visibleGroups.map((group) => (
<ToolGroupSwitchRow
key={group}
group={group}
value={groups[group]}
disabled={controlsDisabled || !enabled}
dimmed={!enabled}
onGroupChange={onGroupChange}
/>
))}
<View style={styles.noteRow}>
<Text style={settingsStyles.rowHint}>
{supportsGroupControls
? t("settings.host.tools.pluginNote")
: t("settings.host.tools.updateHostForGroups")}
</Text>
</View>
</SettingsCollapsibleRow>
);
}
function ToolGroupSwitchRow({
group,
value,
disabled,
dimmed,
onGroupChange,
}: {
group: AgentToolGroupId;
value: boolean;
disabled: boolean;
dimmed: boolean;
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
}) {
const { t } = useTranslation();
const keys = GROUP_TRANSLATION_KEYS[group];
const label = t(keys.title);
const handleChange = useCallback(
(next: boolean) => {
onGroupChange(group, next);
},
[group, onGroupChange],
);
return (
<View style={dimmed ? styles.disabledGroup : undefined}>
<SettingsRow
label={label}
hint={t(keys.hint)}
testID={
group === "browser" ? "host-page-browser-tools-card" : `host-page-tool-group-${group}`
}
>
<Switch
value={value}
onValueChange={handleChange}
disabled={disabled}
accessibilityLabel={label}
testID={
group === "browser"
? "host-page-browser-tools-switch"
: `host-page-tool-group-${group}-switch`
}
/>
</SettingsRow>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
disabledGroup: {
opacity: theme.opacity[50],
},
noteRow: {
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[2],
},
}));
@@ -1,74 +0,0 @@
import React, { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
createBrowserToolsPatch,
getBrowserToolsCardState,
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
export function BrowserToolsRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const state = getBrowserToolsCardState({ isConnected, config });
const mutation = useMutation({
mutationFn: async (next: boolean) => {
const result = await patchConfig(createBrowserToolsPatch(next));
if (!result) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return result;
},
});
const mutationView = getBrowserToolsMutationViewState({
isPending: mutation.isPending,
error: mutation.error,
});
const handleValueChange = useCallback(
(next: boolean) => {
mutation.mutate(next);
},
[mutation],
);
const hint = useMemo(
() => (
<View>
<Text style={settingsStyles.rowHint}>{state.warning}</Text>
{mutationView.loadingText ? (
<Text style={settingsStyles.rowHint} testID="host-page-browser-tools-loading">
{mutationView.loadingText}
</Text>
) : null}
</View>
),
[mutationView.loadingText, state.warning],
);
if (!state.isVisible) return null;
return (
<SettingsRow
label={state.title}
hint={hint}
error={mutationView.errorText ?? undefined}
testID="host-page-browser-tools-card"
>
<Switch
value={state.isEnabled}
onValueChange={handleValueChange}
disabled={mutationView.isSwitchDisabled}
accessibilityLabel="Enable browser tools"
testID="host-page-browser-tools-switch"
/>
</SettingsRow>
);
}
@@ -1,71 +0,0 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
BROWSER_TOOLS_WARNING,
createBrowserToolsPatch,
getBrowserToolsCardState,
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
function makeConfig(browserToolsEnabled = false): MutableDaemonConfig {
return {
relay: { enabled: false },
mcp: { injectIntoAgents: false },
browserTools: { enabled: browserToolsEnabled },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
};
}
describe("browser tools opt-in config", () => {
it("shows the card with the logged-in browser state warning when connected", () => {
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(false) })).toEqual({
isVisible: true,
isEnabled: false,
title: "Browser tools",
warning: BROWSER_TOOLS_WARNING,
});
});
it("reads enabled state from daemon config", () => {
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(true) })).toMatchObject(
{
isEnabled: true,
},
);
});
it("hides the card when the host is disconnected", () => {
expect(
getBrowserToolsCardState({ isConnected: false, config: makeConfig(true) }),
).toMatchObject({
isVisible: false,
});
});
it("writes daemon.browserTools.enabled when toggled", () => {
expect(createBrowserToolsPatch(true)).toEqual({ browserTools: { enabled: true } });
expect(createBrowserToolsPatch(false)).toEqual({ browserTools: { enabled: false } });
});
it("shows loading and disables the toggle while browser tool settings save", () => {
expect(getBrowserToolsMutationViewState({ isPending: true, error: null })).toEqual({
isSwitchDisabled: true,
loadingText: "Updating browser tools…",
errorText: null,
});
});
it("shows the save error when browser tool settings fail", () => {
expect(
getBrowserToolsMutationViewState({ isPending: false, error: new Error("Disk full") }),
).toEqual({
isSwitchDisabled: false,
loadingText: null,
errorText: "Disk full",
});
});
});
@@ -1,49 +0,0 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
export const BROWSER_TOOLS_TITLE = "Browser tools";
export const BROWSER_TOOLS_WARNING =
"Allow agents to access and control Paseo browser tabs, including logged-in browser state. Only enable this for agents you trust.";
export interface BrowserToolsCardState {
isVisible: boolean;
isEnabled: boolean;
title: string;
warning: string;
}
export interface BrowserToolsMutationViewState {
isSwitchDisabled: boolean;
loadingText: string | null;
errorText: string | null;
}
export function getBrowserToolsCardState(input: {
isConnected: boolean;
config: MutableDaemonConfig | null;
}): BrowserToolsCardState {
return {
isVisible: input.isConnected,
isEnabled: input.config?.browserTools.enabled === true,
title: BROWSER_TOOLS_TITLE,
warning: BROWSER_TOOLS_WARNING,
};
}
export function createBrowserToolsPatch(enabled: boolean): Partial<MutableDaemonConfig> {
return { browserTools: { enabled } };
}
export function getBrowserToolsMutationViewState(input: {
isPending: boolean;
error: unknown;
}): BrowserToolsMutationViewState {
return {
isSwitchDisabled: input.isPending,
loadingText: input.isPending ? "Updating browser tools…" : null,
errorText: input.error ? toErrorMessage(input.error) : null,
};
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -61,8 +61,7 @@ import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons
import { ICON_SIZE } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import { useProviderIcon } from "@/components/provider-icons";
import { BrowserToolsRow } from "./browser-tools-card";
import { HostPaseoToolsRow } from "./paseo-tools-card";
import { HostAgentToolsRow } from "./agent-tools-row";
import { RestartRecoveryRow } from "./restart-recovery-card";
import { IdleRuntimeCleanupRow } from "./idle-runtime-cleanup-card";
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
@@ -261,8 +260,7 @@ export function HostToolsPage({ serverId }: { serverId: string }) {
</SettingsSection>
<SettingsSection title={t("settings.host.tools.toolsTitle")}>
<SettingsCard testID="host-page-inject-mcp-card">
<HostPaseoToolsRow serverId={serverId} />
<BrowserToolsRow serverId={serverId} />
<HostAgentToolsRow serverId={serverId} />
</SettingsCard>
</SettingsSection>
</>
@@ -1,54 +0,0 @@
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
/** The host's "give agents Paseo tools" row, bound to the host's config, for composing inside a SettingsCard. */
export function HostPaseoToolsRow({ serverId }: { serverId: string }) {
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const handleValueChange = useCallback(
(next: boolean) => {
void patchConfig({ mcp: { injectIntoAgents: next } });
},
[patchConfig],
);
if (!isConnected) return null;
return (
<PaseoToolsRow
value={config?.mcp.injectIntoAgents !== false}
onValueChange={handleValueChange}
/>
);
}
/** The Paseo tools row on its own, for a caller that decides what the switch is bound to. */
export function PaseoToolsRow({
value,
onValueChange,
disabled,
}: {
value: boolean;
onValueChange: (next: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
return (
<SettingsRow
label={t("settings.host.orchestration.enableTools.title")}
hint={t("settings.host.orchestration.enableTools.hint")}
>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
/>
</SettingsRow>
);
}
@@ -0,0 +1,62 @@
// @vitest-environment jsdom
import { render } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { RetainedPanelActivity } from "@/components/retained-panel";
import {
createPostRestoreRevealHolds,
type PostRestoreRevealHolds,
PostRestoreRevealHoldsProvider,
usePostRestoreRevealHold,
} from "./post-restore-reveal-holds";
function Chrome({ pending }: { pending: boolean }) {
usePostRestoreRevealHold(pending);
return null;
}
function Workspace(props: {
holds: PostRestoreRevealHolds | null;
pending: boolean;
onScreen: boolean;
mounted?: boolean;
}) {
return (
<PostRestoreRevealHoldsProvider holds={props.holds}>
<RetainedPanelActivity active={props.onScreen}>
{props.mounted === false ? null : <Chrome pending={props.pending} />}
</RetainedPanelActivity>
</PostRestoreRevealHoldsProvider>
);
}
describe("post-restore reveal holds", () => {
it("holds the reveal while on-screen chrome is pending and releases when it settles", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
expect(holds.isHeld()).toBe(true);
view.rerender(<Workspace holds={holds} pending={false} onScreen />);
expect(holds.isHeld()).toBe(false);
});
it("does not hold for chrome in a hidden pane", () => {
const holds = createPostRestoreRevealHolds();
render(<Workspace holds={holds} pending onScreen={false} />);
expect(holds.isHeld()).toBe(false);
});
it("releases when pending chrome unmounts", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
view.rerender(<Workspace holds={holds} pending onScreen mounted={false} />);
expect(holds.isHeld()).toBe(false);
});
it("releases when the handoff ends and the provider stops offering holds", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
view.rerender(<Workspace holds={null} pending onScreen />);
expect(holds.isHeld()).toBe(false);
});
});
@@ -0,0 +1,77 @@
import {
createContext,
type ReactNode,
useContext,
useLayoutEffect,
useSyncExternalStore,
} from "react";
import { useRetainedPanelActive } from "@/components/retained-panel";
/**
* Workspace chrome mounted behind the `Restoring...` gate that has nothing to show until a layout
* pass answers it. The gate stays up while any on-screen chrome holds it.
*/
export interface PostRestoreRevealHolds {
hold: () => () => void;
subscribe: (listener: () => void) => () => void;
isHeld: () => boolean;
}
export function createPostRestoreRevealHolds(): PostRestoreRevealHolds {
let count = 0;
const listeners = new Set<() => void>();
const notify = () => {
for (const listener of listeners) listener();
};
return {
hold: () => {
count += 1;
notify();
let released = false;
return () => {
if (released) return;
released = true;
count -= 1;
notify();
};
},
subscribe: (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
isHeld: () => count > 0,
};
}
const PostRestoreRevealHoldsContext = createContext<PostRestoreRevealHolds | null>(null);
/** `holds` is null outside a post-restore handoff, so chrome mounting normally never holds. */
export function PostRestoreRevealHoldsProvider({
holds,
children,
}: {
holds: PostRestoreRevealHolds | null;
children: ReactNode;
}) {
return <PostRestoreRevealHoldsContext value={holds}>{children}</PostRestoreRevealHoldsContext>;
}
/**
* Holds the post-restore reveal while `pending`. A hidden pane or a closed explorer never lays
* out, so only chrome that is on screen holds.
*/
export function usePostRestoreRevealHold(pending: boolean): void {
const holds = useContext(PostRestoreRevealHoldsContext);
const isOnScreen = useRetainedPanelActive();
const isHolding = pending && isOnScreen;
useLayoutEffect(() => {
if (!isHolding || !holds) return;
return holds.hold();
}, [holds, isHolding]);
}
export function usePostRestoreRevealHeld(holds: PostRestoreRevealHolds): boolean {
return useSyncExternalStore(holds.subscribe, holds.isHeld, holds.isHeld);
}
@@ -4,7 +4,6 @@ import { Globe, SquareTerminal } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import type { WorkspaceScriptLinkKind } from "@/utils/workspace-script-links";
import { scriptStatus, scriptToneColorMapping } from "./script-status";
const ThemedGlobe = withUnistyles(Globe);
@@ -39,23 +38,6 @@ export function ExitCodeBadge({ code }: { code: number }): ReactElement {
);
}
/** The label of a URL route, as the user picks between them. */
export function routeLabelKey(
kind: WorkspaceScriptLinkKind,
):
| "workspace.scripts.routes.public"
| "workspace.scripts.routes.paseo"
| "workspace.scripts.routes.direct" {
switch (kind) {
case "public":
return "workspace.scripts.routes.public";
case "paseo":
return "workspace.scripts.routes.paseo";
case "direct":
return "workspace.scripts.routes.direct";
}
}
const styles = StyleSheet.create((theme) => ({
scriptIcon: {
flexShrink: 0,
@@ -0,0 +1,164 @@
import { useCallback, useEffect, useMemo, type ReactElement } from "react";
import { Text, View } from "react-native";
import { RotateCw } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { TunnelProviderInfo } from "@getpaseo/protocol/tunnels";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import type { Theme } from "@/styles/theme";
import { DropdownMenuHint, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { SettingsInfoTip } from "@/components/settings/headings/settings-info-tip";
import type { WorkspaceScriptActions } from "./use-workspace-script-actions";
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedRotateCw = withUnistyles(RotateCw);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const LOADING_ICON = <ThemedLoadingSpinner size={14} uniProps={mutedColorMapping} />;
const RETRY_ICON = <ThemedRotateCw size={14} uniProps={mutedColorMapping} />;
function providerDetail(provider: TunnelProviderInfo): string | null {
const { availability } = provider;
if (availability.status === "available") {
return provider.description ?? availability.detail ?? null;
}
return availability.fixHint
? `${availability.reason}\n${availability.fixHint}`
: availability.reason;
}
/**
* One provider: its name, and for one that cannot run, a short status. Everything longer — what
* the provider does, why it is unavailable, how to fix it — sits behind the info tip, so the
* flyout stays a narrow list of names.
*/
function TunnelProviderOption({
script,
provider,
isOpening,
onOpen,
}: {
script: WorkspaceScript;
provider: TunnelProviderInfo;
isOpening: boolean;
onOpen: (script: WorkspaceScript, providerId: string) => void;
}): ReactElement {
const { t } = useTranslation();
const available = provider.availability.status === "available";
const detail = providerDetail(provider);
const testID = `workspace-scripts-tunnel-${script.scriptName}-provider-${provider.id}`;
const handleSelect = useCallback(() => {
onOpen(script, provider.id);
}, [onOpen, provider.id, script]);
const trailing = useMemo(() => {
if (available && !detail) return null;
return (
<View style={styles.trailing}>
{available ? null : (
<Text style={styles.status} numberOfLines={1}>
{t("workspace.scripts.tunnel.unavailable")}
</Text>
)}
{detail ? (
<SettingsInfoTip title={provider.label} info={detail} testID={`${testID}-info`} />
) : null}
</View>
);
}, [available, detail, provider.label, t, testID]);
return (
<DropdownMenuItem
disabled={!available || isOpening}
trailing={trailing}
closeOnSelect={false}
onSelect={handleSelect}
testID={testID}
>
{provider.label}
</DropdownMenuItem>
);
}
/**
* Shared tunnel provider picker page rendered inside both the desktop Scripts popover flyout
* and the compact Workspace actions bottom sheet.
*/
export function TunnelProvidersPage({
script,
actions,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
}): ReactElement {
const { t } = useTranslation();
const { loadTunnelProviders, openTunnel } = actions;
useEffect(() => {
loadTunnelProviders();
}, [loadTunnelProviders]);
const isOpening = actions.isOpeningTunnel(script.scriptName);
if (
actions.tunnelProvidersStatus === "loading" ||
(actions.tunnelProvidersStatus === "idle" && actions.tunnelProviders.length === 0)
) {
return (
<DropdownMenuItem
disabled
leading={LOADING_ICON}
testID={`workspace-scripts-tunnel-${script.scriptName}-loading`}
>
{t("workspace.scripts.tunnel.loadingProviders")}
</DropdownMenuItem>
);
}
if (actions.tunnelProvidersStatus === "error") {
return (
<DropdownMenuItem
leading={RETRY_ICON}
description={actions.tunnelProvidersError ?? undefined}
closeOnSelect={false}
onSelect={loadTunnelProviders}
testID={`workspace-scripts-tunnel-${script.scriptName}-retry`}
>
{t("workspace.scripts.tunnel.retry")}
</DropdownMenuItem>
);
}
if (actions.tunnelProviders.length === 0) {
return <DropdownMenuHint>{t("workspace.scripts.tunnel.noProviders")}</DropdownMenuHint>;
}
return (
<>
{actions.tunnelProviders.map((provider) => (
<TunnelProviderOption
key={provider.id}
script={script}
provider={provider}
isOpening={isOpening}
onOpen={openTunnel}
/>
))}
</>
);
}
const styles = StyleSheet.create((theme) => ({
trailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
},
status: {
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
}));
@@ -1,25 +1,21 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import * as Clipboard from "expo-clipboard";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import type { TunnelProviderInfo } from "@getpaseo/protocol/tunnels";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { useFetchQuery } from "@/data/query";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import { useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useToast } from "@/contexts/toast-api-context";
import {
resolveWorkspaceScriptLink,
type WorkspaceScriptLinkKind,
type WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import { useWorkspaceServiceRoutePreferencesStore } from "@/workspace-service-routes/store";
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
export interface WorkspaceScriptLinks {
/** The URL this host's route preference picks, or null when the script serves none. */
selected: WorkspaceScriptLinkTarget | null;
targets: WorkspaceScriptLinkTarget[];
}
export type TunnelProvidersLoadStatus = "idle" | "loading" | "ready" | "error";
export interface WorkspaceScriptActions {
serverId?: string;
@@ -28,23 +24,42 @@ export interface WorkspaceScriptActions {
/** Stops the script, then starts it again once the daemon reports it stopped. */
restart: (scriptName: string) => void;
copyUrl: (target: WorkspaceScriptLinkTarget) => void;
selectRoute: (kind: WorkspaceScriptLinkKind) => void;
resolveLinks: (script: WorkspaceScript) => WorkspaceScriptLinks;
resolveLocalLink: (script: WorkspaceScript) => WorkspaceScriptLinkTarget | null;
isStartPending: boolean;
isStopPending: boolean;
supportsTunnels: boolean;
tunnelProviders: readonly TunnelProviderInfo[];
tunnelProvidersStatus: TunnelProvidersLoadStatus;
tunnelProvidersError: string | null;
loadTunnelProviders: () => void;
openTunnel: (script: WorkspaceScript, providerId: string) => void;
closeTunnel: (script: WorkspaceScript) => void;
isOpeningTunnel: (scriptName: string) => boolean;
isClosingTunnel: (scriptName: string) => boolean;
getTunnelError: (scriptName: string) => string | null;
getTunnelProviderLabel: (providerId: string) => string;
}
export interface UseWorkspaceScriptActionsInput {
client: Pick<DaemonClient, "startWorkspaceScript" | "killTerminal"> | null;
client: Pick<
DaemonClient,
| "startWorkspaceScript"
| "killTerminal"
| "listTunnelProviders"
| "openWorkspaceScriptTunnel"
| "closeWorkspaceScriptTunnel"
> | null;
serverId: string;
workspaceId: string;
scripts: WorkspaceDescriptor["scripts"];
onScriptTerminalStarted?: (terminalId: string) => void;
}
const TUNNEL_PROVIDERS_STALE_MS = 15_000;
/**
* Run, stop, restart and URL handling for a workspace's scripts, shared by every surface that
* lists them.
* Run, stop, restart, local URL, and on-demand tunnel handling for a workspace's scripts,
* shared by every surface that lists them.
*
* A restart outlives the press that asked for it — the second half waits for the daemon to
* report the script stopped — so mount this once with the workspace screen and pass its actions to
@@ -60,13 +75,49 @@ export function useWorkspaceScriptActions({
const { t } = useTranslation();
const toast = useToast();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const preferredRouteKind = useWorkspaceServiceRoutePreferencesStore(
(state) => state.byServerId[serverId] ?? null,
);
const setPreferredRoute = useWorkspaceServiceRoutePreferencesStore(
(state) => state.setPreferredRoute,
// COMPAT(workspaceScriptTunnels): added in v0.19.0, remove gate after 2027-06-01.
const supportsTunnels = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.workspaceScriptTunnels === true,
);
const pendingRestartRef = useRef<Set<string>>(new Set());
const [tunnelProvidersRequested, setTunnelProvidersRequested] = useState(false);
const [openingTunnels, setOpeningTunnels] = useState<ReadonlySet<string>>(() => new Set());
const [closingTunnels, setClosingTunnels] = useState<ReadonlySet<string>>(() => new Set());
const [tunnelErrors, setTunnelErrors] = useState<Record<string, string>>({});
const tunnelProvidersQuery = useFetchQuery({
queryKey: ["tunnel-providers", serverId],
dataShape: "list",
queryFn: async () => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const response = await client.listTunnelProviders();
return response.providers;
},
enabled: supportsTunnels && client !== null && tunnelProvidersRequested,
staleTimeMs: TUNNEL_PROVIDERS_STALE_MS,
});
const tunnelProvidersRequestedRef = useRef(false);
const tunnelProvidersFetchingRef = useRef(false);
tunnelProvidersFetchingRef.current = tunnelProvidersQuery.isFetching;
const tunnelProvidersNeedsRefreshRef = useRef(false);
tunnelProvidersNeedsRefreshRef.current =
tunnelProvidersQuery.isStale || tunnelProvidersQuery.isError;
const refetchTunnelProviders = tunnelProvidersQuery.refetch;
const loadTunnelProviders = useCallback(() => {
if (!supportsTunnels || !client) return;
if (!tunnelProvidersRequestedRef.current) {
tunnelProvidersRequestedRef.current = true;
setTunnelProvidersRequested(true);
return;
}
if (!tunnelProvidersFetchingRef.current && tunnelProvidersNeedsRefreshRef.current) {
void refetchTunnelProviders();
}
}, [client, refetchTunnelProviders, supportsTunnels]);
const startScriptMutation = useMutation({
mutationFn: async (scriptName: string) => {
@@ -125,6 +176,89 @@ export function useWorkspaceScriptActions({
});
const stopScript = stopScriptMutation.mutate;
const openTunnelMutation = useMutation({
mutationFn: async ({ script, providerId }: { script: WorkspaceScript; providerId: string }) => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const result = await client.openWorkspaceScriptTunnel({
workspaceId,
scriptName: script.scriptName,
providerId,
});
if (result.error) {
throw new Error(result.error);
}
},
onMutate: ({ script }) => {
setOpeningTunnels((prev) => new Set(prev).add(script.scriptName));
setTunnelErrors((prev) => {
if (!(script.scriptName in prev)) return prev;
const next = { ...prev };
delete next[script.scriptName];
return next;
});
},
onError: (error, { script }) => {
const message =
error instanceof Error
? error.message
: t("workspace.scripts.tunnel.openFailed", { scriptName: script.scriptName });
setTunnelErrors((prev) => ({ ...prev, [script.scriptName]: message }));
toast.show(message, { variant: "error" });
},
onSettled: (_data, _error, { script }) => {
setOpeningTunnels((prev) => {
if (!prev.has(script.scriptName)) return prev;
const next = new Set(prev);
next.delete(script.scriptName);
return next;
});
},
});
const mutateOpenTunnel = openTunnelMutation.mutate;
const closeTunnelMutation = useMutation({
mutationFn: async (script: WorkspaceScript) => {
if (!client) {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
const result = await client.closeWorkspaceScriptTunnel({
workspaceId,
scriptName: script.scriptName,
});
if (result.error) {
throw new Error(result.error);
}
},
onMutate: (script) => {
setClosingTunnels((prev) => new Set(prev).add(script.scriptName));
setTunnelErrors((prev) => {
if (!(script.scriptName in prev)) return prev;
const next = { ...prev };
delete next[script.scriptName];
return next;
});
},
onError: (error, script) => {
const message =
error instanceof Error
? error.message
: t("workspace.scripts.tunnel.stopFailed", { scriptName: script.scriptName });
setTunnelErrors((prev) => ({ ...prev, [script.scriptName]: message }));
toast.show(message, { variant: "error" });
},
onSettled: (_data, _error, script) => {
setClosingTunnels((prev) => {
if (!prev.has(script.scriptName)) return prev;
const next = new Set(prev);
next.delete(script.scriptName);
return next;
});
},
});
const mutateCloseTunnel = closeTunnelMutation.mutate;
// Restart = kill the script terminal, then start again once the daemon
// reports the script as stopped (it tears the runtime entry down on exit).
useEffect(() => {
@@ -137,6 +271,24 @@ export function useWorkspaceScriptActions({
}
}, [scripts, startScript]);
// Clear inline tunnel errors once a script stops or its tunnel recovers.
useEffect(() => {
setTunnelErrors((prev) => {
const keys = Object.keys(prev);
if (keys.length === 0) return prev;
let changed = false;
const next = { ...prev };
for (const scriptName of keys) {
const script = scripts.find((entry) => entry.scriptName === scriptName);
if (!script || script.lifecycle !== "running" || script.tunnel?.state === "ready") {
delete next[scriptName];
changed = true;
}
}
return changed ? next : prev;
});
}, [scripts]);
const restart = useCallback(
(scriptName: string) => {
pendingRestartRef.current.add(scriptName);
@@ -153,19 +305,57 @@ export function useWorkspaceScriptActions({
[toast],
);
const selectRoute = useCallback(
(kind: WorkspaceScriptLinkKind) => setPreferredRoute(serverId, kind),
[serverId, setPreferredRoute],
const resolveLocalLink = useCallback(
(script: WorkspaceScript): WorkspaceScriptLinkTarget | null =>
resolveWorkspaceScriptLink({ script, activeConnection }),
[activeConnection],
);
const resolveLinks = useCallback(
(script: WorkspaceScript): WorkspaceScriptLinks => {
const link = resolveWorkspaceScriptLink({ script, activeConnection });
const selected =
link.targets.find((target) => target.kind === preferredRouteKind) ?? link.primary;
return { selected, targets: link.targets };
const openTunnel = useCallback(
(script: WorkspaceScript, providerId: string) => {
mutateOpenTunnel({ script, providerId });
},
[activeConnection, preferredRouteKind],
[mutateOpenTunnel],
);
const closeTunnel = useCallback(
(script: WorkspaceScript) => {
mutateCloseTunnel(script);
},
[mutateCloseTunnel],
);
const isOpeningTunnel = useCallback(
(scriptName: string) => openingTunnels.has(scriptName),
[openingTunnels],
);
const isClosingTunnel = useCallback(
(scriptName: string) => closingTunnels.has(scriptName),
[closingTunnels],
);
const getTunnelError = useCallback(
(scriptName: string) => tunnelErrors[scriptName] ?? null,
[tunnelErrors],
);
const tunnelProviders = tunnelProvidersQuery.data ?? EMPTY_PROVIDERS;
const tunnelProvidersStatus = resolveTunnelProvidersStatus({
requested: tunnelProvidersRequested,
isPending: tunnelProvidersQuery.isPending,
isError: tunnelProvidersQuery.isError,
});
const tunnelProvidersError = resolveTunnelProvidersError({
isError: tunnelProvidersQuery.isError,
error: tunnelProvidersQuery.error,
fallback: t("workspace.scripts.tunnel.providersLoadFailed"),
});
const getTunnelProviderLabel = useCallback(
(providerId: string) =>
tunnelProviders.find((provider) => provider.id === providerId)?.label ?? providerId,
[tunnelProviders],
);
return useMemo(
@@ -175,10 +365,20 @@ export function useWorkspaceScriptActions({
stop: stopScript,
restart,
copyUrl,
selectRoute,
resolveLinks,
resolveLocalLink,
isStartPending: startScriptMutation.isPending,
isStopPending: stopScriptMutation.isPending,
supportsTunnels,
tunnelProviders,
tunnelProvidersStatus,
tunnelProvidersError,
loadTunnelProviders,
openTunnel,
closeTunnel,
isOpeningTunnel,
isClosingTunnel,
getTunnelError,
getTunnelProviderLabel,
}),
[
serverId,
@@ -186,10 +386,50 @@ export function useWorkspaceScriptActions({
stopScript,
restart,
copyUrl,
selectRoute,
resolveLinks,
resolveLocalLink,
startScriptMutation.isPending,
stopScriptMutation.isPending,
supportsTunnels,
tunnelProviders,
tunnelProvidersStatus,
tunnelProvidersError,
loadTunnelProviders,
openTunnel,
closeTunnel,
isOpeningTunnel,
isClosingTunnel,
getTunnelError,
getTunnelProviderLabel,
],
);
}
function resolveTunnelProvidersStatus({
requested,
isPending,
isError,
}: {
requested: boolean;
isPending: boolean;
isError: boolean;
}): TunnelProvidersLoadStatus {
if (!requested) return "idle";
if (isPending) return "loading";
if (isError) return "error";
return "ready";
}
function resolveTunnelProvidersError({
isError,
error,
fallback,
}: {
isError: boolean;
error: unknown;
fallback: string;
}): string | null {
if (!isError) return null;
return error instanceof Error ? error.message : fallback;
}
const EMPTY_PROVIDERS: readonly TunnelProviderInfo[] = [];
@@ -0,0 +1,210 @@
import { i18n } from "@/i18n/i18next";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { View } from "react-native";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import type { TunnelProviderInfo } from "@getpaseo/protocol/tunnels";
import type { WorkspaceScriptActions } from "./use-workspace-script-actions";
import { WorkspaceScriptsButton } from "./workspace-scripts-button";
// Initializes translations, so rows render their English labels.
void i18n;
// App sources compile against the classic JSX runtime, which expects React on the global.
beforeEach(() => vi.stubGlobal("React", React));
/**
* The tunnel is an address of its service, so its row sits on the host rail with
* `localhost:<port>`: same text edge, same action column, same pitch. A real browser, because
* the claim is about where things land on screen.
*/
const PORT = 57483;
const LOCAL_LABEL = `localhost:${PORT}`;
const TUNNEL_HOST = "cool-breeze-demo.trycloudflare.com";
const AT_HEADER_RIGHT = { position: "absolute", top: 8, right: 8 } as const;
/** Past the menu's first placement. */
const PLACED_MS = 400;
const PROVIDERS: TunnelProviderInfo[] = [
{
id: "cloudflare-tunnel",
pluginId: "cloudflared-tunnel",
label: "Cloudflare Tunnel",
description: "Expose local HTTP targets with Cloudflare quick tunnels.",
availability: { status: "available" },
},
{
id: "tailscale-funnel",
pluginId: "tailscale-funnel",
label: "Tailscale Funnel",
availability: {
status: "unavailable",
reason: "Tailscale is not connected (state: NeedsLogin).",
fixHint: "Run `tailscale up` and sign in to your tailnet.",
},
},
];
function noop() {}
function service(tunnel: WorkspaceScriptPayload["tunnel"]): WorkspaceScriptPayload {
return {
scriptName: "web",
type: "service",
hostname: "web",
port: PORT,
localProxyUrl: null,
publicProxyUrl: null,
proxyUrl: null,
tunnel,
lifecycle: "running",
health: "healthy",
exitCode: null,
terminalId: null,
} as WorkspaceScriptPayload;
}
const ACTIONS: WorkspaceScriptActions = {
start: noop,
stop: noop,
restart: noop,
copyUrl: noop,
resolveLocalLink: () => ({ url: `http://localhost:${PORT}`, label: LOCAL_LABEL }),
isStartPending: false,
isStopPending: false,
supportsTunnels: true,
tunnelProviders: PROVIDERS,
tunnelProvidersStatus: "ready",
tunnelProvidersError: null,
loadTunnelProviders: noop,
openTunnel: noop,
closeTunnel: noop,
isOpeningTunnel: () => false,
isClosingTunnel: () => false,
getTunnelError: () => null,
getTunnelProviderLabel: (id) => PROVIDERS.find((provider) => provider.id === id)?.label ?? id,
};
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function wait(ms: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function openScriptsMenu(script: WorkspaceScriptPayload): Promise<void> {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<View style={AT_HEADER_RIGHT}>
<WorkspaceScriptsButton actions={ACTIONS} scripts={[script]} />
</View>,
),
);
act(() => element("workspace-scripts-button").click());
await wait(PLACED_MS);
}
function element(testID: string): HTMLElement {
const found = document.querySelector(`[data-testid="${testID}"]`);
if (!(found instanceof HTMLElement)) throw new Error(`${testID} did not render`);
return found;
}
/** The innermost element showing exactly this text. */
function text(label: string): DOMRect {
const found = Array.from(document.querySelectorAll<HTMLElement>("div, span")).find(
(node) => node.textContent === label && node.children.length === 0,
);
if (!found) throw new Error(`"${label}" did not render`);
return found.getBoundingClientRect();
}
/** Icons are stubbed to nothing here, so a row action is measured by its button box. */
function actionColumn(testID: string): DOMRect {
return element(testID).getBoundingClientRect();
}
/** The chevron's box, the last thing in the Tunnel row. */
function chevronColumn(testID: string): DOMRect {
const chevron = element(testID).lastElementChild;
if (!chevron) throw new Error(`${testID} has no chevron`);
return chevron.getBoundingClientRect();
}
function centerX(rect: DOMRect): number {
return rect.left + rect.width / 2;
}
describe("Scripts menu tunnel rows", () => {
beforeEach(async () => {
await page.viewport(1280, 800);
});
it("puts Tunnel › on the host rail under localhost", async () => {
await openScriptsMenu(service(null));
const local = text(LOCAL_LABEL);
const tunnel = text("Tunnel");
expect(tunnel.left).toBeCloseTo(local.left, 0);
expect(tunnel.top).toBeGreaterThan(local.bottom);
expect(centerX(chevronColumn("workspace-scripts-tunnel-web"))).toBeCloseTo(
centerX(actionColumn("workspace-scripts-copy-web")),
0,
);
expect(element("workspace-scripts-tunnel-web").getBoundingClientRect().height).toBeCloseTo(
element("workspace-scripts-copy-web").parentElement!.getBoundingClientRect().height,
0,
);
});
it("opens the provider picker beside the menu, not over it", async () => {
await openScriptsMenu(service(null));
act(() => element("workspace-scripts-tunnel-web").click());
await wait(PLACED_MS);
const menu = element("workspace-scripts-menu").getBoundingClientRect();
const picker = element("workspace-scripts-menu-workspace-scripts-tunnel/web");
expect(picker.getBoundingClientRect().right).toBeLessThanOrEqual(menu.left + 12);
expect(picker.textContent).toContain("Cloudflare Tunnel");
expect(picker.textContent).not.toContain("quick tunnels");
expect(picker.textContent).not.toContain("NeedsLogin");
});
it("shows a ready tunnel as one host row with its actions on the right rail", async () => {
await openScriptsMenu(
service({
exposureId: "service:workspace-1:web",
providerId: "cloudflare-tunnel",
state: "ready",
url: `https://${TUNNEL_HOST}`,
stability: "ephemeral",
detail: null,
error: null,
}),
);
const local = text(LOCAL_LABEL);
const host = text(TUNNEL_HOST);
expect(host.left).toBeCloseTo(local.left, 0);
expect(centerX(actionColumn("workspace-scripts-tunnel-stop-web"))).toBeCloseTo(
centerX(actionColumn("workspace-scripts-copy-web")),
0,
);
expect(element("workspace-scripts-tunnel-active-web").textContent).not.toContain(
"Temporary URL",
);
});
});
@@ -3,14 +3,16 @@
*/
import { i18n as testI18n } from "@/i18n/i18next";
import React, { type ReactElement } from "react";
import { act, fireEvent } from "@testing-library/react";
import { act, fireEvent, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import type { TunnelProviderInfo } from "@getpaseo/protocol/tunnels";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRoot } from "react-dom/client";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { useWorkspaceScriptActions } from "./use-workspace-script-actions";
import { WorkspaceScriptsButton } from "./workspace-scripts-button";
import { useWorkspaceScriptsMenuPages } from "./workspace-scripts-menu-pages";
void testI18n;
@@ -18,23 +20,29 @@ const {
theme,
startWorkspaceScriptMock,
killTerminalMock,
listTunnelProvidersMock,
openWorkspaceScriptTunnelMock,
closeWorkspaceScriptTunnelMock,
setStringAsyncMock,
copiedToastMock,
routePreferenceByServerIdMock,
routePreferenceListenersMock,
setPreferredRouteMock,
openExternalUrlMock,
openedSubPagesMock,
sessionStateMock,
} = vi.hoisted(() => {
const hoistedTheme = {
spacing: { 1: 4, 1.5: 6, 2: 8, 3: 12 },
borderWidth: { 1: 1 },
borderRadius: { md: 6, lg: 8 },
fontSize: { xs: 11, sm: 13 },
fontSize: { xs: 11, sm: 12, base: 13 },
fontWeight: { normal: "400", medium: "500" },
colors: {
foreground: "#fff",
foregroundMuted: "#aaa",
popoverForeground: "#fff",
surface2: "#222",
borderAccent: "#444",
statusDanger: "#ff453a",
statusSuccess: "#30d158",
palette: {
blue: { 500: "#0a84ff" },
green: { 500: "#30d158" },
@@ -43,13 +51,6 @@ const {
},
};
const routePreferenceByServerId: Record<string, "public" | "paseo" | "direct"> = {};
const routePreferenceListeners = new Set<() => void>();
const setPreferredRoute = vi.fn((serverId: string, kind: "public" | "paseo" | "direct") => {
routePreferenceByServerId[serverId] = kind;
for (const listener of routePreferenceListeners) listener();
});
return {
theme: hoistedTheme,
startWorkspaceScriptMock: vi.fn(async () => ({
@@ -64,11 +65,33 @@ const {
success: true,
requestId: "request-1",
})),
listTunnelProvidersMock: vi.fn(
async (): Promise<{ requestId: string; providers: TunnelProviderInfo[] }> => ({
requestId: "req-providers",
providers: [],
}),
),
openWorkspaceScriptTunnelMock: vi.fn(
async (): Promise<{ requestId: string; workspaceId: string; error: string | null }> => ({
requestId: "req-open",
workspaceId: "workspace-1",
error: null,
}),
),
closeWorkspaceScriptTunnelMock: vi.fn(
async (): Promise<{ requestId: string; workspaceId: string; error: string | null }> => ({
requestId: "req-close",
workspaceId: "workspace-1",
error: null,
}),
),
setStringAsyncMock: vi.fn(async () => true),
copiedToastMock: vi.fn(),
routePreferenceByServerIdMock: routePreferenceByServerId,
routePreferenceListenersMock: routePreferenceListeners,
setPreferredRouteMock: setPreferredRoute,
openExternalUrlMock: vi.fn(),
openedSubPagesMock: vi.fn((_id: string) => {}),
sessionStateMock: {
supportsTunnels: false,
},
};
});
@@ -102,24 +125,34 @@ vi.mock("@/runtime/host-runtime", () => ({
useHostRuntimeSnapshot: () => ({ activeConnection: null }),
}));
vi.mock("@/workspace-service-routes/store", async () => {
const ReactModule = await vi.importActual<typeof import("react")>("react");
const state = {
byServerId: routePreferenceByServerIdMock,
setPreferredRoute: setPreferredRouteMock,
};
return {
useWorkspaceServiceRoutePreferencesStore: <T,>(selector: (value: typeof state) => T) =>
ReactModule.useSyncExternalStore(
(listener) => {
routePreferenceListenersMock.add(listener);
return () => routePreferenceListenersMock.delete(listener);
vi.mock("@/stores/session-store", () => ({
useSessionStore: <T,>(
selector: (state: {
sessions: Record<
string,
{
serverInfo?: {
features?: { tunnelProviders?: boolean; workspaceScriptTunnels?: boolean };
};
workspaces?: Map<string, unknown>;
}
>;
}) => T,
) =>
selector({
sessions: {
"test-server": {
serverInfo: {
features: {
tunnelProviders: true,
workspaceScriptTunnels: sessionStateMock.supportsTunnels,
},
},
workspaces: new Map(),
},
() => selector(state),
() => selector(state),
),
};
});
},
}),
}));
vi.mock("@/contexts/toast-context", () => ({
useToast: () => ({ show: vi.fn(), error: vi.fn(), copied: copiedToastMock }),
@@ -130,30 +163,82 @@ vi.mock("expo-clipboard", () => ({
}));
vi.mock("@/utils/open-external-url", () => ({
openExternalUrl: vi.fn(),
openExternalUrl: openExternalUrlMock,
}));
vi.mock("@/components/ui/loading-spinner", () => ({
LoadingSpinner: ({ size, color }: { size?: number; color?: string }) =>
React.createElement("span", {
"data-icon": "LoadingSpinner",
"data-size": size,
"data-color": color,
}),
}));
vi.mock("@/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuContent: ({ children, testID }: { children: React.ReactNode; testID?: string }) => (
<div data-testid={testID}>{children}</div>
DropdownMenuContent: ({
children,
pages,
testID,
}: {
children: React.ReactNode;
pages?: Array<{ id: string; title: string; content: React.ReactNode }>;
testID?: string;
}) => (
<div data-testid={testID}>
{children}
{pages?.map((page) => (
<div key={page.id} data-testid={`menu-page-${page.id}`}>
{page.content}
</div>
))}
</div>
),
DropdownMenuSeparator: () => <div role="separator" />,
DropdownMenuHint: ({ children }: { children: React.ReactNode }) => (
<div data-testid="dropdown-menu-hint">{children}</div>
),
DropdownMenuSubTrigger: ({
children,
id,
value,
testID,
}: {
children: React.ReactNode;
id: string;
value?: string;
testID?: string;
}) => (
<button type="button" data-testid={testID} data-page-id={id}>
{children}
{value ? <span>{value}</span> : null}
</button>
),
DropdownMenuItem: ({
children,
description,
disabled,
onSelect,
trailing,
testID,
}: {
children: React.ReactNode;
description?: string;
disabled?: boolean;
onSelect?: () => void;
trailing?: React.ReactNode;
testID?: string;
}) => (
<button type="button" data-testid={testID} onClick={onSelect}>
{children}
{description}
</button>
<div>
<button type="button" data-testid={testID} disabled={disabled} onClick={onSelect}>
{children}
{description ? <span>{description}</span> : null}
</button>
{trailing ? (
<div data-testid={testID ? `${testID}-trailing` : undefined}>{trailing}</div>
) : null}
</div>
),
DropdownMenuTrigger: ({
children,
@@ -171,6 +256,12 @@ vi.mock("@/components/ui/dropdown-menu", () => ({
</button>
),
useDropdownMenuClose: () => () => {},
useDropdownMenuSubTrigger: ({ id }: { id: string }) => ({
anchorRef: { current: null },
anchorProps: {},
isOpen: false,
open: () => openedSubPagesMock(id),
}),
}));
vi.mock("@/components/ui/tooltip", () => ({
@@ -194,8 +285,11 @@ vi.mock("lucide-react-native", () => {
Copy: createIcon("Copy"),
Eye: createIcon("Eye"),
ExternalLink: createIcon("ExternalLink"),
ChevronRight: createIcon("ChevronRight"),
Globe: createIcon("Globe"),
Info: createIcon("Info"),
Play: createIcon("Play"),
Radio: createIcon("Radio"),
RotateCw: createIcon("RotateCw"),
Square: createIcon("Square"),
SquareTerminal: createIcon("SquareTerminal"),
@@ -215,9 +309,10 @@ function script(
type: input.type ?? "script",
hostname: input.hostname ?? input.scriptName,
port: input.port ?? null,
localProxyUrl: input.localProxyUrl,
publicProxyUrl: input.publicProxyUrl,
localProxyUrl: input.localProxyUrl ?? null,
publicProxyUrl: input.publicProxyUrl ?? null,
proxyUrl: input.proxyUrl ?? null,
tunnel: input.tunnel ?? null,
lifecycle: input.lifecycle ?? "stopped",
health: input.health ?? null,
exitCode: input.exitCode ?? null,
@@ -229,19 +324,26 @@ const LIVE_TERMINAL_IDS: string[] = ["terminal-script-1"];
interface RenderScriptsOptions {
hideLabels?: boolean;
includeSheetPages?: boolean;
}
const testToast = { show: () => () => {}, error: () => {}, copied: copiedToastMock };
const scriptClient = {
startWorkspaceScript: startWorkspaceScriptMock,
killTerminal: killTerminalMock,
listTunnelProviders: listTunnelProvidersMock,
openWorkspaceScriptTunnel: openWorkspaceScriptTunnelMock,
closeWorkspaceScriptTunnel: closeWorkspaceScriptTunnelMock,
};
function ScriptsOwner({
scripts,
hideLabels,
includeSheetPages,
}: {
scripts: WorkspaceScriptPayload[];
hideLabels?: boolean;
includeSheetPages?: boolean;
}) {
const actions = useWorkspaceScriptActions({
client: scriptClient,
@@ -249,13 +351,32 @@ function ScriptsOwner({
workspaceId: "workspace-1",
scripts,
});
const sheet = useWorkspaceScriptsMenuPages({
actions,
scripts,
liveTerminalIds: LIVE_TERMINAL_IDS,
onViewTerminal: () => {},
onOpenUrlInBrowserTab: () => {},
});
return (
<WorkspaceScriptsButton
actions={actions}
scripts={scripts}
liveTerminalIds={LIVE_TERMINAL_IDS}
hideLabels={hideLabels}
/>
<>
<WorkspaceScriptsButton
actions={actions}
scripts={scripts}
liveTerminalIds={LIVE_TERMINAL_IDS}
hideLabels={hideLabels}
/>
{includeSheetPages ? (
<div data-testid="sheet-pages">
{sheet.pages.map((page) => (
<div key={page.id} data-testid={`sheet-page-${page.id}`}>
{page.content}
</div>
))}
</div>
) : null}
</>
);
}
@@ -280,7 +401,11 @@ function renderScripts(
return (
<QueryClientProvider client={queryClient}>
<ToastApiProvider api={testToast}>
<ScriptsOwner scripts={nextScripts} hideLabels={options.hideLabels} />
<ScriptsOwner
scripts={nextScripts}
hideLabels={options.hideLabels}
includeSheetPages={options.includeSheetPages}
/>
</ToastApiProvider>
</QueryClientProvider>
);
@@ -336,14 +461,27 @@ describe("WorkspaceScriptsButton", () => {
},
);
document.body.innerHTML = "";
sessionStateMock.supportsTunnels = false;
openedSubPagesMock.mockClear();
startWorkspaceScriptMock.mockClear();
killTerminalMock.mockClear();
listTunnelProvidersMock.mockReset();
listTunnelProvidersMock.mockResolvedValue({ requestId: "req-providers", providers: [] });
openWorkspaceScriptTunnelMock.mockReset();
openWorkspaceScriptTunnelMock.mockResolvedValue({
requestId: "req-open",
workspaceId: "workspace-1",
error: null,
});
closeWorkspaceScriptTunnelMock.mockReset();
closeWorkspaceScriptTunnelMock.mockResolvedValue({
requestId: "req-close",
workspaceId: "workspace-1",
error: null,
});
setStringAsyncMock.mockClear();
copiedToastMock.mockClear();
setPreferredRouteMock.mockClear();
for (const serverId of Object.keys(routePreferenceByServerIdMock)) {
delete routePreferenceByServerIdMock[serverId];
}
openExternalUrlMock.mockClear();
});
afterEach(() => {
@@ -405,7 +543,6 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "web",
type: "service",
hostname: "web.paseo.localhost",
lifecycle: "running",
health: "healthy",
port: 3000,
@@ -413,7 +550,6 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "api",
type: "service",
hostname: "api.paseo.localhost",
lifecycle: "running",
health: "unhealthy",
port: 4000,
@@ -421,7 +557,6 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "worker",
type: "service",
hostname: "worker.paseo.localhost",
lifecycle: "running",
health: null,
port: 5000,
@@ -429,7 +564,6 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "old-service",
type: "service",
hostname: "old-service.paseo.localhost",
lifecycle: "stopped",
exitCode: 1,
}),
@@ -454,57 +588,368 @@ describe("WorkspaceScriptsButton", () => {
expect(trigger?.querySelector('[data-icon="ChevronDown"]')).not.toBeNull();
});
it("persists the selected route for the host", () => {
const scripts = [
script({
scriptName: "dev",
type: "service",
hostname: "dev--proj--repo.localhost",
lifecycle: "running",
port: 57483,
proxyUrl: "http://dev--proj--repo.localhost:6767",
terminalId: "terminal-script-1",
}),
];
current = renderScripts(scripts);
const row = requireRow("dev");
expect(row.textContent).toContain("dev--proj--repo.localhost:6767");
const routeButton = row.querySelector('[data-testid="workspace-scripts-route-dev"]');
expect(routeButton).not.toBeNull();
fireEvent.click(
row.querySelector('[data-testid="workspace-scripts-route-dev-direct"]') as HTMLElement,
);
expect(setPreferredRouteMock).toHaveBeenCalledWith("test-server", "direct");
expect(row.textContent).toContain("localhost:57483");
const copyButton = row.querySelector('[data-testid="workspace-scripts-copy-dev"]');
expect(copyButton).not.toBeNull();
fireEvent.click(copyButton as HTMLElement);
expect(setStringAsyncMock).toHaveBeenCalledWith("http://localhost:57483");
expect(copiedToastMock).toHaveBeenCalledWith("localhost:57483");
current.unmount();
current = renderScripts(scripts);
expect(requireRow("dev").textContent).toContain("localhost:57483");
});
it("defaults to a configured reverse proxy URL", () => {
it("shows localhost:<port> directly and copies it without a route selector", () => {
current = renderScripts([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
localProxyUrl: "http://dev--proj--repo.localhost:6767",
publicProxyUrl: "https://dev--proj--repo.services.example.com",
proxyUrl: "https://dev--proj--repo.services.example.com",
terminalId: "terminal-script-1",
}),
]);
expect(requireRow("dev").textContent).toContain("dev--proj--repo.services.example.com");
const row = requireRow("dev");
expect(row.textContent).toContain("localhost:57483");
expect(row.querySelector('[data-testid="workspace-scripts-route-dev"]')).toBeNull();
const copyButton = row.querySelector('[data-testid="workspace-scripts-copy-dev"]');
expect(copyButton).not.toBeNull();
fireEvent.click(copyButton as HTMLElement);
expect(setStringAsyncMock).toHaveBeenCalledWith("http://localhost:57483");
expect(copiedToastMock).toHaveBeenCalledWith("localhost:57483");
});
it("hides Tunnel controls on a daemon with tunnel providers but no script tunnels", () => {
sessionStateMock.supportsTunnels = false;
current = renderScripts([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
}),
]);
expect(document.querySelector('[data-testid="workspace-scripts-tunnel-dev"]')).toBeNull();
expect(listTunnelProvidersMock).not.toHaveBeenCalled();
});
it("lists available and unavailable tunnel providers and opens an exposure on click", async () => {
sessionStateMock.supportsTunnels = true;
listTunnelProvidersMock.mockResolvedValue({
requestId: "req-providers",
providers: [
{
id: "cloudflare-tunnel",
pluginId: "cloudflare-tunnel",
label: "Cloudflare Tunnel",
description: "Quick public HTTPS URL via cloudflared",
availability: {
status: "available",
},
},
{
id: "tailscale-funnel",
pluginId: "tailscale-funnel",
label: "Tailscale Funnel",
description: "Stable tailnet HTTPS URL",
availability: {
status: "unavailable",
reason: "Tailscale is not logged in",
fixHint: "Run tailscale up to connect",
},
},
],
});
current = renderScripts([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
}),
]);
const tunnelTrigger = document.querySelector(
'[data-testid="workspace-scripts-tunnel-dev"]',
) as HTMLElement;
// The tunnel is an address of the service: no leading mark of its own, a chevron to its picker.
expect(tunnelTrigger.textContent).toBe("Tunnel");
expect(tunnelTrigger.querySelector('[data-icon="Radio"]')).toBeNull();
expect(tunnelTrigger.querySelector('[data-icon="ChevronRight"]')).not.toBeNull();
fireEvent.click(tunnelTrigger);
expect(openedSubPagesMock).toHaveBeenCalledWith("workspace-scripts-tunnel/dev");
let cloudflareOption: HTMLButtonElement | null = null;
await waitFor(() => {
cloudflareOption = document.querySelector(
'[data-testid="workspace-scripts-tunnel-dev-provider-cloudflare-tunnel"]',
) as HTMLButtonElement | null;
expect(cloudflareOption).not.toBeNull();
});
const tailscaleOption = document.querySelector(
'[data-testid="workspace-scripts-tunnel-dev-provider-tailscale-funnel"]',
) as HTMLButtonElement | null;
expect(cloudflareOption).not.toBeNull();
expect(cloudflareOption!.disabled).toBe(false);
expect(tailscaleOption).not.toBeNull();
expect(tailscaleOption?.disabled).toBe(true);
// Rows carry the provider name only; status and details sit beside it, details behind the tip.
expect(cloudflareOption!.textContent).toBe("Cloudflare Tunnel");
expect(tailscaleOption?.textContent).toBe("Tailscale Funnel");
const cloudflareTrailing = document.querySelector(
'[data-testid="workspace-scripts-tunnel-dev-provider-cloudflare-tunnel-trailing"]',
);
expect(cloudflareTrailing?.textContent).not.toContain("Unavailable");
expect(cloudflareTrailing?.textContent).toContain("Quick public HTTPS URL via cloudflared");
const tailscaleTrailing = document.querySelector(
'[data-testid="workspace-scripts-tunnel-dev-provider-tailscale-funnel-trailing"]',
);
expect(tailscaleTrailing?.textContent).toContain("Unavailable");
expect(
tailscaleTrailing?.querySelector(
'[data-testid="workspace-scripts-tunnel-dev-provider-tailscale-funnel-info"]',
),
).not.toBeNull();
expect(tailscaleTrailing?.textContent).toContain("Tailscale is not logged in");
expect(tailscaleTrailing?.textContent).toContain("Run tailscale up to connect");
fireEvent.click(cloudflareOption!);
await waitFor(() => {
expect(openWorkspaceScriptTunnelMock).toHaveBeenCalledWith({
workspaceId: "workspace-1",
scriptName: "dev",
providerId: "cloudflare-tunnel",
});
});
});
it("renders connecting, ready, and error tunnel states with Open, Copy, and Stop actions", async () => {
sessionStateMock.supportsTunnels = true;
listTunnelProvidersMock.mockResolvedValue({
requestId: "req-providers",
providers: [
{
id: "cloudflare-tunnel",
pluginId: "cloudflare-tunnel",
label: "Cloudflare Tunnel",
availability: { status: "available" },
},
],
});
current = renderScripts([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
tunnel: {
exposureId: "service:workspace-1:dev",
providerId: "cloudflare-tunnel",
state: "connecting",
url: null,
stability: null,
detail: null,
error: null,
},
}),
]);
let activeBlock = document.querySelector('[data-testid="workspace-scripts-tunnel-active-dev"]');
expect(activeBlock?.textContent).toContain("Connecting...");
expect(
activeBlock?.querySelector('[data-testid="workspace-scripts-tunnel-stop-dev"]'),
).not.toBeNull();
await current.rerender([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
tunnel: {
exposureId: "service:workspace-1:dev",
providerId: "cloudflare-tunnel",
state: "ready",
url: "https://bright-sky.trycloudflare.com",
stability: "ephemeral",
detail: null,
error: null,
},
}),
]);
activeBlock = document.querySelector('[data-testid="workspace-scripts-tunnel-active-dev"]');
expect(activeBlock?.textContent).toContain("bright-sky.trycloudflare.com");
// One host row: the provider and the temporary note live in the host's tooltip.
expect(activeBlock?.textContent).toContain("https://bright-sky.trycloudflare.com");
expect(activeBlock?.textContent).toContain("· Temporary URL");
const openButton = activeBlock?.querySelector(
'[data-testid="workspace-scripts-tunnel-open-dev"]',
) as HTMLElement;
const copyButton = activeBlock?.querySelector(
'[data-testid="workspace-scripts-tunnel-copy-dev"]',
) as HTMLElement;
const stopButton = activeBlock?.querySelector(
'[data-testid="workspace-scripts-tunnel-stop-dev"]',
) as HTMLElement;
fireEvent.click(openButton);
expect(openExternalUrlMock).toHaveBeenCalledWith("https://bright-sky.trycloudflare.com");
fireEvent.click(copyButton);
expect(setStringAsyncMock).toHaveBeenCalledWith("https://bright-sky.trycloudflare.com");
expect(copiedToastMock).toHaveBeenCalledWith("bright-sky.trycloudflare.com");
fireEvent.click(stopButton);
await waitFor(() => {
expect(closeWorkspaceScriptTunnelMock).toHaveBeenCalledWith({
workspaceId: "workspace-1",
scriptName: "dev",
});
});
await current.rerender([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
tunnel: {
exposureId: "service:workspace-1:dev",
providerId: "cloudflare-tunnel",
state: "error",
url: null,
stability: null,
detail: null,
error: "cloudflared exited unexpectedly",
},
}),
]);
activeBlock = document.querySelector('[data-testid="workspace-scripts-tunnel-active-dev"]');
expect(activeBlock?.textContent).toContain("cloudflared exited unexpectedly");
});
it("shows an inline error if opening a tunnel fails", async () => {
sessionStateMock.supportsTunnels = true;
listTunnelProvidersMock.mockResolvedValue({
requestId: "req-providers",
providers: [
{
id: "cloudflare-tunnel",
pluginId: "cloudflare-tunnel",
label: "Cloudflare Tunnel",
availability: { status: "available" },
},
],
});
openWorkspaceScriptTunnelMock.mockRejectedValueOnce(new Error("cloudflared binary missing"));
current = renderScripts([
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
}),
]);
let cloudflareOption: HTMLElement | null = null;
await waitFor(() => {
cloudflareOption = document.querySelector(
'[data-testid="workspace-scripts-tunnel-dev-provider-cloudflare-tunnel"]',
) as HTMLElement | null;
expect(cloudflareOption).not.toBeNull();
});
fireEvent.click(cloudflareOption!);
await waitFor(() => {
const errorNode = document.querySelector(
'[data-testid="workspace-scripts-tunnel-error-dev"]',
);
expect(errorNode?.textContent).toContain("cloudflared binary missing");
});
});
it("exposes tunnel actions in compact sheet script pages", async () => {
sessionStateMock.supportsTunnels = true;
current = renderScripts(
[
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
tunnel: {
exposureId: "service:workspace-1:dev",
providerId: "tailscale-funnel",
state: "ready",
url: "https://dev.tailnet.ts.net",
stability: "stable",
detail: null,
error: null,
},
}),
],
{ includeSheetPages: true },
);
const scriptPage = document.querySelector('[data-testid="sheet-page-workspace-scripts/dev"]');
expect(
scriptPage?.querySelector('[data-testid="workspace-script-dev-tunnel-open"]')?.textContent,
).toBe("Open tunnel URLdev.tailnet.ts.net");
expect(
scriptPage?.querySelector('[data-testid="workspace-script-dev-tunnel-copy"]')?.textContent,
).toBe("Copy tunnel URL");
expect(scriptPage?.textContent).toContain("Stop tunnel");
const stopSheetButton = scriptPage?.querySelector(
'[data-testid="workspace-script-dev-tunnel-stop"]',
) as HTMLElement;
fireEvent.click(stopSheetButton);
await waitFor(() => {
expect(closeWorkspaceScriptTunnelMock).toHaveBeenCalledWith({
workspaceId: "workspace-1",
scriptName: "dev",
});
});
});
it("tells compact sheet users that a ready tunnel URL is temporary", () => {
sessionStateMock.supportsTunnels = true;
current = renderScripts(
[
script({
scriptName: "dev",
type: "service",
lifecycle: "running",
port: 57483,
terminalId: "terminal-script-1",
tunnel: {
exposureId: "service:workspace-1:dev",
providerId: "cloudflare-tunnel",
state: "ready",
url: "https://cool-breeze.trycloudflare.com",
stability: "ephemeral",
detail: null,
error: null,
},
}),
],
{ includeSheetPages: true },
);
const scriptPage = document.querySelector('[data-testid="sheet-page-workspace-scripts/dev"]');
expect(
scriptPage?.querySelector('[data-testid="workspace-script-dev-tunnel-open"]')?.textContent,
).toBe("Open tunnel URLcool-breeze.trycloudflare.com · Temporary URL");
expect(
scriptPage?.querySelector('[data-testid="workspace-script-dev-tunnel-copy"]')?.textContent,
).toBe("Copy tunnel URL");
});
it("stops a running script through its terminal", async () => {
@@ -569,7 +1014,6 @@ describe("WorkspaceScriptsButton", () => {
type: "service",
lifecycle: "running",
port: 3000,
proxyUrl: "http://dev--project.localhost:6767",
terminalId: "terminal-script-1",
}),
]);
@@ -586,9 +1030,6 @@ describe("WorkspaceScriptsButton", () => {
expect(
document.querySelector('[data-testid="workspace-scripts-copy-dev-tooltip"]')?.textContent,
).toBe("Copy URL");
expect(
document.querySelector('[data-testid="workspace-scripts-route-dev-tooltip"]')?.textContent,
).toBe("Choose URL");
});
it("restarts a script once its stopped lifecycle arrives", async () => {
@@ -3,7 +3,9 @@ import type { GestureResponderEvent } from "react-native";
import { Pressable, Text, View } from "react-native";
import {
ChevronDown,
ChevronRight,
Copy,
ExternalLink,
Eye,
Play,
RotateCw,
@@ -16,25 +18,26 @@ import type { WorkspaceDescriptor } from "@/stores/session-store";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
type MenuPageDefinition,
useDropdownMenuClose,
useDropdownMenuSubTrigger,
} from "@/components/ui/dropdown-menu";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { MENU_ITEM_HEIGHT } from "@/components/ui/menu/menu-geometry";
import { openExternalUrl } from "@/utils/open-external-url";
import { openServiceUrl } from "@/utils/open-service-url";
import type {
WorkspaceScriptLinkKind,
WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import { stripUrlProtocol, type WorkspaceScriptLinkTarget } from "@/utils/workspace-script-links";
import type { Theme } from "@/styles/theme";
import { HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { extraMutedIconColorMapping } from "@/components/ui/icon-color";
import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks";
import { ExitCodeBadge, ScriptIcon } from "./script-marks";
import { scriptToneColorMapping } from "./script-status";
import { TunnelProvidersPage } from "./tunnel-picker-page";
import type { WorkspaceScriptActions } from "./use-workspace-script-actions";
type RowActionIcon = "copy" | "open" | "restart" | "start" | "stop" | "terminal";
type RowActionIcon = "copy" | "external" | "open" | "restart" | "start" | "stop" | "terminal";
interface WorkspaceScriptsButtonProps {
actions: WorkspaceScriptActions;
@@ -49,9 +52,12 @@ const ThemedPlay = withUnistyles(Play);
const ThemedSquareTerminal = withUnistyles(SquareTerminal);
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedEye = withUnistyles(Eye);
const ThemedExternalLink = withUnistyles(ExternalLink);
const ThemedChevronRight = withUnistyles(ChevronRight);
const ThemedCopy = withUnistyles(Copy);
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedSquare = withUnistyles(Square);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundColorMapping = (theme: Theme) => ({
color: theme.colors.foreground,
@@ -61,6 +67,10 @@ const mutedColorMapping = (theme: Theme) => ({
});
const playFillTransparent = { fill: "transparent" };
function tunnelPageId(scriptName: string): string {
return `workspace-scripts-tunnel/${scriptName}`;
}
interface ScriptRowActionButtonProps {
accessibilityLabel: string;
disabled?: boolean;
@@ -81,6 +91,8 @@ function RowActionIconElement({
switch (icon) {
case "copy":
return <ThemedCopy size={11} uniProps={colorMapping} />;
case "external":
return <ThemedExternalLink size={11} uniProps={colorMapping} />;
case "open":
return <ThemedEye size={12} uniProps={colorMapping} />;
case "restart":
@@ -137,154 +149,31 @@ function ScriptRowActionButton({
);
}
interface ServiceLinkRowProps {
selectedTarget: WorkspaceScriptLinkTarget;
targets: WorkspaceScriptLinkTarget[];
scriptName: string;
onSelectKind: (kind: WorkspaceScriptLinkKind) => void;
onCopy: (target: WorkspaceScriptLinkTarget) => void;
}
function ServiceRouteOption({
scriptName,
selectedKind,
function ServiceLocalLinkRow({
target,
onSelect,
}: {
scriptName: string;
selectedKind: WorkspaceScriptLinkKind;
target: WorkspaceScriptLinkTarget;
onSelect: (kind: WorkspaceScriptLinkKind) => void;
}): ReactElement {
const { t } = useTranslation();
const handleSelect = useCallback(() => onSelect(target.kind), [onSelect, target.kind]);
return (
<DropdownMenuItem
testID={`workspace-scripts-route-${scriptName}-${target.kind}`}
selected={target.kind === selectedKind}
showSelectedCheck
description={target.label}
onSelect={handleSelect}
>
{t(routeLabelKey(target.kind))}
</DropdownMenuItem>
);
}
function ServiceRouteTriggerContent({
hovered,
label,
}: {
hovered: boolean;
label: string;
}): ReactElement {
return (
<>
<View style={styles.routeSelectorButton}>
<ThemedChevronDown
size={14}
uniProps={hovered ? foregroundColorMapping : mutedColorMapping}
/>
</View>
<Text
style={hovered ? [styles.hostLabel, styles.hostLabelActive] : styles.hostLabel}
numberOfLines={1}
>
{label}
</Text>
</>
);
}
function ServiceRouteSelector({
scriptName,
selectedTarget,
targets,
onSelect,
}: {
scriptName: string;
selectedTarget: WorkspaceScriptLinkTarget;
targets: WorkspaceScriptLinkTarget[];
onSelect: (kind: WorkspaceScriptLinkKind) => void;
}): ReactElement {
const { t } = useTranslation();
const accessibilityLabel = t("workspace.scripts.accessibility.chooseUrl", { scriptName });
return (
<DropdownMenu>
<Tooltip delayDuration={250} enabledOnDesktop enabledOnMobile={false}>
<TooltipTrigger asChild triggerRefProp="ref">
<View collapsable={false} style={styles.routeSelectorFrame}>
<DropdownMenuTrigger
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID={`workspace-scripts-route-${scriptName}`}
hitSlop={6}
style={styles.routeSelectorTrigger}
>
{({ hovered }) => (
<ServiceRouteTriggerContent hovered={hovered} label={selectedTarget.label} />
)}
</DropdownMenuTrigger>
</View>
</TooltipTrigger>
<TooltipContent
testID={`workspace-scripts-route-${scriptName}-tooltip`}
side="top"
align="center"
offset={8}
>
<Text style={styles.tooltipText}>{t("workspace.scripts.actions.chooseUrl")}</Text>
</TooltipContent>
</Tooltip>
<DropdownMenuContent side="bottom" align="end" minWidth={220} maxWidth={280}>
{targets.map((target) => (
<ServiceRouteOption
key={target.kind}
scriptName={scriptName}
selectedKind={selectedTarget.kind}
target={target}
onSelect={onSelect}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
function ServiceLinkRow({
selectedTarget,
targets,
scriptName,
onSelectKind,
onCopy,
}: ServiceLinkRowProps): ReactElement {
}: {
target: WorkspaceScriptLinkTarget;
scriptName: string;
onCopy: (target: WorkspaceScriptLinkTarget) => void;
}): ReactElement {
const { t } = useTranslation();
const closeMenu = useDropdownMenuClose();
const { label } = selectedTarget;
const handleCopy = useCallback(() => {
closeMenu();
onCopy(selectedTarget);
}, [selectedTarget, onCopy, closeMenu]);
onCopy(target);
}, [target, onCopy, closeMenu]);
return (
<View style={styles.hostRow}>
{targets.length > 1 ? (
<ServiceRouteSelector
scriptName={scriptName}
selectedTarget={selectedTarget}
targets={targets}
onSelect={onSelectKind}
/>
) : (
<View style={styles.routeDisplay}>
<View style={styles.routeSelectorButton} />
<Text style={styles.hostLabel} numberOfLines={1}>
{label}
</Text>
</View>
)}
<View style={styles.routeDisplay}>
<View style={styles.leadingSlot} />
<Text style={styles.hostLabel} numberOfLines={1}>
{target.label}
</Text>
</View>
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.copyUrl", { scriptName })}
testID={`workspace-scripts-copy-${scriptName}`}
@@ -296,8 +185,276 @@ function ServiceLinkRow({
);
}
/**
* Text on a host sub-row whose full story does not fit on one line: the whole URL, the provider,
* an error. The row keeps one short line; the rest is a hover or a press away.
*/
function HostRowText({
label,
detail,
tone = "muted",
testID,
}: {
label: string;
detail: readonly string[];
tone?: "muted" | "active" | "danger";
testID?: string;
}): ReactElement {
const textStyle = useMemo(
() => [
styles.hostLabel,
tone === "active" ? styles.hostLabelActive : null,
tone === "danger" ? styles.hostLabelDanger : null,
],
[tone],
);
// Touch has no hover, so a press opens the same detail.
return (
<Tooltip delayDuration={250} enabledOnDesktop enabledOnMobile>
<TooltipTrigger asChild>
<Text style={textStyle} numberOfLines={1} testID={testID}>
{label}
</Text>
</TooltipTrigger>
<TooltipContent side="top" align="start" offset={8}>
{detail.map((line) => (
<Text key={line} style={styles.tooltipText}>
{line}
</Text>
))}
</TooltipContent>
</Tooltip>
);
}
/**
* "Tunnel ›" under a service with no tunnel. It is an address the service could have, so it
* sits on the host rail like `localhost:<port>` rather than on the service rail. The engine owns
* the anchor and hover intent; the anchor spans the surface so the provider flyout clears it.
*/
function TunnelTriggerRow({ scriptName }: { scriptName: string }): ReactElement {
const { t } = useTranslation();
const { anchorRef, anchorProps, isOpen, open } = useDropdownMenuSubTrigger({
id: tunnelPageId(scriptName),
});
const labelStyle = useMemo(
() => (isOpen ? [styles.hostLabel, styles.hostLabelActive] : styles.hostLabel),
[isOpen],
);
const accessibilityState = useMemo(() => ({ expanded: isOpen }), [isOpen]);
return (
<View ref={anchorRef} collapsable={false} {...anchorProps}>
<Pressable
accessibilityRole="button"
accessibilityLabel={t("workspace.scripts.accessibility.tunnel", { scriptName })}
accessibilityState={accessibilityState}
testID={`workspace-scripts-tunnel-${scriptName}`}
onPress={open}
style={styles.hostRow}
>
<View style={styles.routeDisplay}>
<View style={styles.leadingSlot} />
<Text style={labelStyle} numberOfLines={1}>
{t("workspace.scripts.tunnel.title")}
</Text>
</View>
<View style={styles.iconActionButton}>
<ThemedChevronRight
size={11}
uniProps={isOpen ? foregroundColorMapping : mutedColorMapping}
/>
</View>
</Pressable>
</View>
);
}
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
type WorkspaceScriptTunnel = NonNullable<WorkspaceScript["tunnel"]>;
/** The host rows a running service shows for its tunnel, one per tunnel state. */
function ServiceTunnelRows({
script,
actions,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
}): ReactElement {
const { tunnel } = script;
if (!tunnel) {
return actions.isOpeningTunnel(script.scriptName) ? (
<TunnelStatusRow script={script} actions={actions} tunnel={null} />
) : (
<TunnelTriggerRows
scriptName={script.scriptName}
openError={actions.getTunnelError(script.scriptName)}
/>
);
}
if (tunnel.state === "ready" && tunnel.url) {
return <TunnelReadyRow script={script} actions={actions} tunnel={tunnel} url={tunnel.url} />;
}
return <TunnelStatusRow script={script} actions={actions} tunnel={tunnel} />;
}
function TunnelTriggerRows({
scriptName,
openError,
}: {
scriptName: string;
openError: string | null;
}): ReactElement {
return (
<>
<TunnelTriggerRow scriptName={scriptName} />
{openError ? (
<View style={styles.hostRow}>
<View style={styles.routeDisplay}>
<View style={styles.leadingSlot} />
<HostRowText
label={openError}
detail={[openError]}
tone="danger"
testID={`workspace-scripts-tunnel-error-${scriptName}`}
/>
</View>
</View>
) : null}
</>
);
}
function TunnelStopButton({
script,
actions,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
}): ReactElement {
const { t } = useTranslation();
const { closeTunnel } = actions;
const { scriptName } = script;
const handleStop = useCallback(() => {
closeTunnel(script);
}, [closeTunnel, script]);
return (
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.stopTunnel", { scriptName })}
testID={`workspace-scripts-tunnel-stop-${scriptName}`}
disabled={actions.isClosingTunnel(scriptName)}
icon="stop"
onPress={handleStop}
tooltipLabel={t("workspace.scripts.tunnel.stop")}
/>
);
}
/** The tunnel's host on the host rail, with the full URL and provider behind its tooltip. */
function TunnelReadyRow({
script,
actions,
tunnel,
url,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
tunnel: WorkspaceScriptTunnel;
url: string;
}): ReactElement {
const { t } = useTranslation();
const closeMenu = useDropdownMenuClose();
const { scriptName } = script;
const { copyUrl } = actions;
const host = stripUrlProtocol(url);
const providerLabel = actions.getTunnelProviderLabel(tunnel.providerId);
const detail = useMemo(
() => [
url,
tunnel.stability === "ephemeral"
? `${providerLabel} · ${t("workspace.scripts.tunnel.ephemeralNote")}`
: providerLabel,
],
[providerLabel, t, tunnel.stability, url],
);
const handleOpen = useCallback(() => {
closeMenu();
void openExternalUrl(url);
}, [closeMenu, url]);
const handleCopy = useCallback(() => {
closeMenu();
copyUrl({ url, label: host });
}, [closeMenu, copyUrl, host, url]);
return (
<View style={styles.hostRow} testID={`workspace-scripts-tunnel-active-${scriptName}`}>
<View style={styles.routeDisplay}>
<View style={styles.leadingSlot} />
<HostRowText label={host} detail={detail} tone="active" />
</View>
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.openTunnelUrl", { scriptName })}
testID={`workspace-scripts-tunnel-open-${scriptName}`}
icon="external"
onPress={handleOpen}
tooltipLabel={t("workspace.scripts.tunnel.openUrl")}
/>
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.copyTunnelUrl", { scriptName })}
testID={`workspace-scripts-tunnel-copy-${scriptName}`}
icon="copy"
onPress={handleCopy}
tooltipLabel={t("workspace.scripts.tunnel.copyUrl")}
/>
<TunnelStopButton script={script} actions={actions} />
</View>
);
}
/**
* A tunnel on its way up or down: connecting, reconnecting, or failed. One short line on the
* host rail, the provider and full error behind its tooltip. `tunnel` is null while the daemon
* has not answered the open request yet, when there is nothing to stop.
*/
function TunnelStatusRow({
script,
actions,
tunnel,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
tunnel: WorkspaceScriptTunnel | null;
}): ReactElement {
const { t } = useTranslation();
const providerLabel = tunnel ? actions.getTunnelProviderLabel(tunnel.providerId) : null;
const failed = tunnel?.state === "error";
const label = failed
? (tunnel.error ?? t("workspace.scripts.tunnel.errorFallback"))
: t(
tunnel?.state === "reconnecting"
? "workspace.scripts.tunnel.reconnecting"
: "workspace.scripts.tunnel.connecting",
);
const detail = useMemo(
() => (providerLabel ? [providerLabel, label] : [label]),
[label, providerLabel],
);
return (
<View style={styles.hostRow} testID={`workspace-scripts-tunnel-active-${script.scriptName}`}>
<View style={styles.routeDisplay}>
<View style={styles.leadingSlot} />
<HostRowText label={label} detail={detail} tone={failed ? "danger" : "muted"} />
{failed ? null : <ThemedLoadingSpinner size={10} uniProps={mutedColorMapping} />}
</View>
{tunnel ? <TunnelStopButton script={script} actions={actions} /> : null}
</View>
);
}
interface ScriptRowProps {
script: WorkspaceDescriptor["scripts"][number];
script: WorkspaceScript;
liveTerminalIdSet: Set<string>;
actions: WorkspaceScriptActions;
onViewTerminal?: (terminalId: string) => void;
@@ -314,21 +471,23 @@ function ScriptRow({
const { t } = useTranslation();
const isRunning = script.lifecycle === "running";
const exitCode = script.exitCode ?? null;
const { selected: selectedLink, targets: linkTargets } = actions.resolveLinks(script);
const localLink = actions.resolveLocalLink(script);
const liveTerminalId =
script.terminalId && liveTerminalIdSet.has(script.terminalId) ? script.terminalId : null;
const showExitBadge = !isRunning && exitCode !== null;
const showTunnelSection =
actions.supportsTunnels && script.type === "service" && isRunning && script.port !== null;
const { start, stop, restart } = actions;
const closeMenu = useDropdownMenuClose();
const handleOpenService = useCallback(() => {
if (!selectedLink) return;
if (!localLink) return;
closeMenu();
void openServiceUrl(selectedLink.url, {
void openServiceUrl(localLink.url, {
openInApp: onOpenUrlInBrowserTab,
serverId: actions.serverId,
});
}, [actions.serverId, selectedLink, closeMenu, onOpenUrlInBrowserTab]);
}, [actions.serverId, localLink, closeMenu, onOpenUrlInBrowserTab]);
const handleView = useCallback(() => {
if (liveTerminalId) onViewTerminal?.(liveTerminalId);
@@ -364,7 +523,7 @@ function ScriptRow({
/>
) : null;
const openServiceAction = selectedLink ? (
const openServiceAction = localLink ? (
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.openService", {
scriptName: script.scriptName,
@@ -430,15 +589,16 @@ function ScriptRow({
) : null}
{lifecycleAction}
</View>
{selectedLink ? (
{localLink || showTunnelSection ? (
<View style={styles.hostList}>
<ServiceLinkRow
selectedTarget={selectedLink}
targets={linkTargets}
scriptName={script.scriptName}
onSelectKind={actions.selectRoute}
onCopy={actions.copyUrl}
/>
{localLink ? (
<ServiceLocalLinkRow
target={localLink}
scriptName={script.scriptName}
onCopy={actions.copyUrl}
/>
) : null}
{showTunnelSection ? <ServiceTunnelRows script={script} actions={actions} /> : null}
</View>
) : null}
</View>
@@ -464,6 +624,33 @@ export function WorkspaceScriptsButton({
[],
);
const handleOpenChange = useCallback(
(open: boolean) => {
if (open && actions.supportsTunnels) {
actions.loadTunnelProviders();
}
},
[actions],
);
const tunnelPages = useMemo<MenuPageDefinition[]>(() => {
if (!actions.supportsTunnels) return [];
return scripts
.filter(
(script) =>
script.type === "service" &&
script.lifecycle === "running" &&
script.port !== null &&
!script.tunnel &&
!actions.isOpeningTunnel(script.scriptName),
)
.map((script) => ({
id: tunnelPageId(script.scriptName),
title: t("workspace.scripts.tunnel.title"),
content: <TunnelProvidersPage script={script} actions={actions} />,
}));
}, [actions, scripts, t]);
if (scripts.length === 0) {
return null;
}
@@ -475,7 +662,7 @@ export function WorkspaceScriptsButton({
return (
<View style={styles.row}>
<View style={styles.splitButton}>
<DropdownMenu>
<DropdownMenu onOpenChange={handleOpenChange}>
<DropdownMenuTrigger
testID="workspace-scripts-button"
style={triggerStyle}
@@ -492,8 +679,9 @@ export function WorkspaceScriptsButton({
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
minWidth={200}
maxWidth={280}
minWidth={220}
maxWidth={300}
pages={tunnelPages}
testID="workspace-scripts-menu"
>
{scripts.map((script) => (
@@ -577,14 +765,16 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
minWidth: 0,
},
// Host sub-rows sit under their service: the localhost address, then its tunnel. Each row
// carries its own horizontal inset so a row can also be a flyout anchor spanning the surface.
hostList: {
marginTop: 2,
paddingHorizontal: theme.spacing[3],
},
hostRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
paddingVertical: 2,
minHeight: 18,
},
@@ -596,6 +786,13 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[2],
},
leadingSlot: {
width: 14,
height: 14,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
hostLabel: {
flexShrink: 1,
fontSize: theme.fontSize.sm,
@@ -605,26 +802,12 @@ const styles = StyleSheet.create((theme) => ({
hostLabelActive: {
color: theme.colors.foreground,
},
hostLabelDanger: {
color: theme.colors.statusDanger,
},
iconActionButton: {
padding: 2,
},
routeSelectorButton: {
width: 14,
height: 14,
alignItems: "center",
justifyContent: "center",
},
routeSelectorFrame: {
flex: 1,
minWidth: 0,
},
routeSelectorTrigger: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minWidth: 0,
},
tooltipText: {
fontSize: theme.fontSize.base,
color: theme.colors.popoverForeground,
@@ -1,33 +1,46 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { View } from "react-native";
import { Copy, Eye, Play, RotateCw, Square, SquareTerminal } from "lucide-react-native";
import {
Copy,
ExternalLink,
Eye,
Play,
Radio,
RotateCw,
Square,
SquareTerminal,
} from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import {
DropdownMenuHint,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSubTrigger,
type MenuPageDefinition,
} from "@/components/ui/dropdown-menu";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import type { Theme } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
import { openServiceUrl } from "@/utils/open-service-url";
import type {
WorkspaceScriptLinkKind,
WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks";
import { stripUrlProtocol } from "@/utils/workspace-script-links";
import { ExitCodeBadge, ScriptIcon } from "./script-marks";
import { scriptToneColorMapping, summarizeScripts, type ScriptsSummary } from "./script-status";
import { TunnelProvidersPage } from "./tunnel-picker-page";
import type { WorkspaceScriptActions } from "./use-workspace-script-actions";
type WorkspaceScript = WorkspaceDescriptor["scripts"][number];
const ThemedPlay = withUnistyles(Play);
const ThemedEye = withUnistyles(Eye);
const ThemedExternalLink = withUnistyles(ExternalLink);
const ThemedRadio = withUnistyles(Radio);
const ThemedSquareTerminal = withUnistyles(SquareTerminal);
const ThemedCopy = withUnistyles(Copy);
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedSquare = withUnistyles(Square);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const playFillTransparent = { fill: "transparent" };
@@ -36,6 +49,8 @@ const ROW_ICON_SIZE = 16;
const TRAILING_ICON_SIZE = 14;
const OPEN_SERVICE_ICON = <ThemedEye size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const OPEN_TUNNEL_ICON = <ThemedExternalLink size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const TUNNEL_ICON = <ThemedRadio size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />;
const VIEW_TERMINAL_ICON = (
<ThemedSquareTerminal size={ROW_ICON_SIZE} uniProps={mutedColorMapping} />
);
@@ -45,6 +60,7 @@ const STOP_ICON = <ThemedSquare size={ROW_ICON_SIZE} uniProps={mutedColorMapping
const RUN_ICON = (
<ThemedPlay size={ROW_ICON_SIZE} uniProps={mutedColorMapping} {...playFillTransparent} />
);
const CONNECTING_ICON = <ThemedLoadingSpinner size={14} uniProps={mutedColorMapping} />;
const SCRIPTS_PAGE_ID = "workspace-scripts";
@@ -52,6 +68,10 @@ function scriptPageId(scriptName: string): string {
return `${SCRIPTS_PAGE_ID}/${scriptName}`;
}
function scriptTunnelPageId(scriptName: string): string {
return `${SCRIPTS_PAGE_ID}/${scriptName}/tunnel`;
}
export interface UseWorkspaceScriptsMenuPagesInput {
actions: WorkspaceScriptActions;
scripts: WorkspaceDescriptor["scripts"];
@@ -70,7 +90,7 @@ export interface WorkspaceScriptsMenuPages {
/**
* Workspace scripts as pages of a sheet menu: a Scripts row on the root, a page listing every
* script, and one page per script.
* script, one page per script, and a tunnel provider picker page for running services.
*
* Every script gets a page whether or not it runs, so stopping one from its own page flips that
* page to its stopped state instead of pulling it out from under the user.
@@ -95,6 +115,23 @@ export function useWorkspaceScriptsMenuPages({
const pages = useMemo<MenuPageDefinition[]>(() => {
if (scripts.length === 0) return [];
const liveTerminalIdSet = new Set(liveTerminalIds);
const tunnelPages: MenuPageDefinition[] = actions.supportsTunnels
? scripts
.filter(
(script) =>
script.type === "service" &&
script.lifecycle === "running" &&
script.port !== null &&
!script.tunnel &&
!actions.isOpeningTunnel(script.scriptName),
)
.map((script) => ({
id: scriptTunnelPageId(script.scriptName),
title: t("workspace.scripts.tunnel.title"),
content: <TunnelProvidersPage script={script} actions={actions} />,
}))
: [];
return [
{
id: SCRIPTS_PAGE_ID,
@@ -118,6 +155,7 @@ export function useWorkspaceScriptsMenuPages({
/>
),
})),
...tunnelPages,
];
}, [actions, liveTerminalIds, onOpenUrlInBrowserTab, onViewTerminal, scripts, t]);
@@ -243,9 +281,131 @@ function ScriptPage(props: ScriptPageProps): ReactElement {
);
}
function RunningScriptTunnelItems({
script,
actions,
}: {
script: WorkspaceScript;
actions: WorkspaceScriptActions;
}): ReactElement {
const { t } = useTranslation();
const { scriptName, tunnel } = script;
const isOpening = actions.isOpeningTunnel(scriptName);
const isClosing = actions.isClosingTunnel(scriptName);
const inlineError = actions.getTunnelError(scriptName);
const { copyUrl, closeTunnel } = actions;
const readyUrl = tunnel?.state === "ready" ? tunnel.url : null;
const readyLabel = readyUrl ? stripUrlProtocol(readyUrl) : null;
const handleOpenTunnel = useCallback(() => {
if (readyUrl) void openExternalUrl(readyUrl);
}, [readyUrl]);
const handleCopyTunnel = useCallback(() => {
if (readyUrl && readyLabel) copyUrl({ url: readyUrl, label: readyLabel });
}, [copyUrl, readyLabel, readyUrl]);
const handleStopTunnel = useCallback(() => {
closeTunnel(script);
}, [closeTunnel, script]);
if (!tunnel && !isOpening) {
return (
<>
<DropdownMenuSubTrigger
id={scriptTunnelPageId(scriptName)}
leading={TUNNEL_ICON}
testID={`workspace-script-${scriptName}-tunnel`}
>
{t("workspace.scripts.tunnel.title")}
</DropdownMenuSubTrigger>
{inlineError ? <DropdownMenuHint>{inlineError}</DropdownMenuHint> : null}
</>
);
}
if (tunnel?.state === "ready" && readyUrl && readyLabel) {
const openDescription =
tunnel.stability === "ephemeral"
? `${readyLabel} · ${t("workspace.scripts.tunnel.ephemeralNote")}`
: readyLabel;
return (
<>
<DropdownMenuItem
leading={OPEN_TUNNEL_ICON}
description={openDescription}
onSelect={handleOpenTunnel}
testID={`workspace-script-${scriptName}-tunnel-open`}
>
{t("workspace.scripts.tunnel.openUrl")}
</DropdownMenuItem>
<DropdownMenuItem
leading={COPY_URL_ICON}
onSelect={handleCopyTunnel}
testID={`workspace-script-${scriptName}-tunnel-copy`}
>
{t("workspace.scripts.tunnel.copyUrl")}
</DropdownMenuItem>
<DropdownMenuItem
leading={STOP_ICON}
disabled={isClosing}
closeOnSelect={false}
onSelect={handleStopTunnel}
testID={`workspace-script-${scriptName}-tunnel-stop`}
>
{t("workspace.scripts.tunnel.stop")}
</DropdownMenuItem>
</>
);
}
if (tunnel?.state === "error") {
return (
<>
<DropdownMenuHint>
{tunnel.error ?? t("workspace.scripts.tunnel.errorFallback")}
</DropdownMenuHint>
<DropdownMenuItem
leading={STOP_ICON}
disabled={isClosing}
closeOnSelect={false}
onSelect={handleStopTunnel}
testID={`workspace-script-${scriptName}-tunnel-stop`}
>
{t("workspace.scripts.tunnel.stop")}
</DropdownMenuItem>
</>
);
}
const statusText =
tunnel?.state === "reconnecting"
? t("workspace.scripts.tunnel.reconnecting")
: t("workspace.scripts.tunnel.connecting");
const providerLabel = tunnel ? actions.getTunnelProviderLabel(tunnel.providerId) : undefined;
return (
<>
<DropdownMenuItem disabled leading={CONNECTING_ICON} description={providerLabel}>
{statusText}
</DropdownMenuItem>
{tunnel ? (
<DropdownMenuItem
leading={STOP_ICON}
disabled={isClosing}
closeOnSelect={false}
onSelect={handleStopTunnel}
testID={`workspace-script-${scriptName}-tunnel-stop`}
>
{t("workspace.scripts.tunnel.stop")}
</DropdownMenuItem>
) : null}
</>
);
}
/**
* Rows that open something — the service, the terminal, the clipboard toast — close the sheet.
* Stop and the URL choice stay: the page is where their result shows.
* Stop and tunnel controls stay: the page is where their result shows.
*/
function RunningScriptPage({
script,
@@ -256,28 +416,30 @@ function RunningScriptPage({
}: ScriptPageProps): ReactElement {
const { t } = useTranslation();
const { scriptName } = script;
const { selected, targets } = actions.resolveLinks(script);
const { stop, restart, copyUrl, selectRoute } = actions;
const localLink = actions.resolveLocalLink(script);
const { stop, restart, copyUrl } = actions;
const showTunnelSection =
actions.supportsTunnels && script.type === "service" && script.port !== null;
const handleOpenService = useCallback(() => {
if (!selected) return;
void openServiceUrl(selected.url, {
if (!localLink) return;
void openServiceUrl(localLink.url, {
openInApp: onOpenUrlInBrowserTab,
serverId: actions.serverId,
});
}, [actions.serverId, selected, onOpenUrlInBrowserTab]);
}, [actions.serverId, localLink, onOpenUrlInBrowserTab]);
const handleViewTerminal = useCallback(() => {
if (liveTerminalId) onViewTerminal(liveTerminalId);
}, [liveTerminalId, onViewTerminal]);
const handleCopyUrl = useCallback(() => {
if (selected) copyUrl(selected);
}, [selected, copyUrl]);
if (localLink) copyUrl(localLink);
}, [localLink, copyUrl]);
const handleRestart = useCallback(() => restart(scriptName), [restart, scriptName]);
const handleStop = useCallback(() => stop(scriptName), [stop, scriptName]);
return (
<>
{selected ? (
{localLink ? (
<DropdownMenuItem
leading={OPEN_SERVICE_ICON}
onSelect={handleOpenService}
@@ -295,16 +457,23 @@ function RunningScriptPage({
{t("workspace.scripts.actions.view")}
</DropdownMenuItem>
) : null}
{selected ? (
{localLink ? (
<DropdownMenuItem
leading={COPY_URL_ICON}
description={selected.label}
description={localLink.label}
onSelect={handleCopyUrl}
testID={`workspace-script-${scriptName}-copy`}
>
{t("workspace.scripts.actions.copyUrl")}
</DropdownMenuItem>
) : null}
{showTunnelSection ? (
<>
<DropdownMenuSeparator />
<RunningScriptTunnelItems script={script} actions={actions} />
<DropdownMenuSeparator />
</>
) : null}
<DropdownMenuItem
leading={RESTART_ICON}
disabled={actions.isStopPending}
@@ -322,52 +491,10 @@ function RunningScriptPage({
>
{t("workspace.scripts.actions.stop")}
</DropdownMenuItem>
{selected && targets.length > 1 ? (
<>
<DropdownMenuSeparator />
{targets.map((target) => (
<ServiceRouteOption
key={target.kind}
scriptName={scriptName}
target={target}
selected={target.kind === selected.kind}
onSelect={selectRoute}
/>
))}
</>
) : null}
</>
);
}
/** A pick-one URL route. Choosing one keeps the page open so the check moves under the thumb. */
function ServiceRouteOption({
scriptName,
target,
selected,
onSelect,
}: {
scriptName: string;
target: WorkspaceScriptLinkTarget;
selected: boolean;
onSelect: (kind: WorkspaceScriptLinkKind) => void;
}): ReactElement {
const { t } = useTranslation();
const handleSelect = useCallback(() => onSelect(target.kind), [onSelect, target.kind]);
return (
<DropdownMenuItem
selected={selected}
showSelectedCheck
description={target.label}
closeOnSelect={false}
onSelect={handleSelect}
testID={`workspace-script-${scriptName}-route-${target.kind}`}
>
{t(routeLabelKey(target.kind))}
</DropdownMenuItem>
);
}
function StoppedScriptPage({
script,
actions,
@@ -1,4 +1,9 @@
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import {
createPostRestoreRevealHolds,
type PostRestoreRevealHolds,
usePostRestoreRevealHeld,
} from "@/screens/workspace/post-restore-reveal-holds";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import type { WorkspaceRouteState } from "@/screens/workspace/workspace-route-state";
@@ -101,6 +106,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
visibleAgentsTimelineSynced: boolean;
visibleAgentsVisibilityStatus: ViewedTimelineStatus;
visibleAgentsLoadingOlder: boolean;
isRevealHeld: boolean;
routeState: WorkspaceRouteState;
}): {
displayedRouteState: WorkspaceRouteState;
@@ -119,6 +125,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
visibleAgentsTimelineSynced,
visibleAgentsVisibilityStatus,
visibleAgentsLoadingOlder,
isRevealHeld,
routeState,
} = input;
const isRestoringNow =
@@ -138,6 +145,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
const isHandoffReadyToMount = hasReconciledTabs && areVisibleAgentsReadyToMount;
const isHandoffReadyToRelease =
isHandoffReadyToMount &&
!isRevealHeld &&
(visibleAgentsVisibilityStatus === "error" || !visibleAgentsLoadingOlder);
return {
displayedRouteState: isWaitingForHandoffReveal ? handoff.archivedState : routeState,
@@ -168,6 +176,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
paneFocusSuspended: boolean;
}): {
displayedRouteState: WorkspaceRouteState;
revealHolds: PostRestoreRevealHolds;
isHoldingHandoff: boolean;
isPaneRouteFocused: boolean;
effectivePaneFocusSuspended: boolean;
@@ -191,6 +200,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
const scopeKey = `${serverId}:${workspaceId}`;
const [handoff, setHandoff] = useState<PostRestoreHandoffState | null>(null);
const [mountedHandoff, setMountedHandoff] = useState<PostRestoreHandoffState | null>(null);
const [revealHolds] = useState(createPostRestoreRevealHolds);
const isRevealHeld = usePostRestoreRevealHeld(revealHolds);
const reconciledHandoff = nextPostRestoreHandoff({ current: handoff, scopeKey, routeState });
if (reconciledHandoff !== handoff) {
@@ -271,6 +282,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
visibleAgentsTimelineSynced,
visibleAgentsVisibilityStatus,
visibleAgentsLoadingOlder,
isRevealHeld,
routeState,
});
@@ -286,8 +298,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
useEffect(() => {
if (!isWaitingForHandoffReveal) return;
if (isHandoffReadyToRelease) {
// Wait 3 rAFs after hidden workspace chrome mounts so tab label `onLayout` and stream row
// ResizeObservers commit (and any underfilled history fetch starts) before lifting overlay.
// Chrome that waits on its own layout (tab label measurement) holds the reveal explicitly.
// The frames let stream row ResizeObservers commit and any underfilled history fetch start.
return scheduleAnimationFrames(POST_RESTORE_LAYOUT_SETTLE_FRAMES, () => {
setHandoff(null);
});
@@ -300,6 +312,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
return {
displayedRouteState,
revealHolds,
isHoldingHandoff: isMountedBehindOverlay,
isPaneRouteFocused: isRouteFocused && !isMountedBehindOverlay,
effectivePaneFocusSuspended: paneFocusSuspended || isMountedBehindOverlay,
@@ -96,6 +96,7 @@ import {
useHorizontalScrollBoundary,
} from "@/components/ui/horizontal-scroll-boundary";
import { useSessionStore } from "@/stores/session-store";
import { usePostRestoreRevealHold } from "@/screens/workspace/post-restore-reveal-holds";
const DROPDOWN_WIDTH = 220;
const DEFAULT_INLINE_ADD_BUTTON_RESERVED_WIDTH = 36;
@@ -1062,6 +1063,7 @@ export function WorkspaceDesktopTabsRow(props: WorkspaceDesktopTabsRowProps) {
}),
[presentations, props.tabs],
);
usePostRestoreRevealHold(resolvedTabs.length < props.tabs.length);
return (
<>
@@ -1245,6 +1247,7 @@ function ResolvedWorkspaceDesktopTabsRow({
useLayoutEffect(() => {
publishMeasuredTrack();
}, [publishMeasuredTrack]);
usePostRestoreRevealHold(tabs.length > 0 && trackSnapshot?.signature !== tabLabelSignature);
const handleTabLabelLayout = useCallback(
(key: string, label: string, event: LayoutChangeEvent) => {
@@ -264,6 +264,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingTabs.displayedRouteState).toBe(restoringState);
@@ -283,6 +284,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "checking",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingTimeline.displayedRouteState).toBe(restoringState);
@@ -301,6 +303,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "checking",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingCatchUp.displayedRouteState).toBe(restoringState);
@@ -319,6 +322,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: true,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingOlderFill.isHandoffReadyToMount).toBe(true);
@@ -336,6 +340,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(revealed.displayedRouteState).toBe(restoringState);
@@ -355,6 +360,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(cleared.displayedRouteState).toEqual({ kind: "ready" });
@@ -372,11 +378,38 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "error",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(errored.isHandoffReadyToRelease).toBe(true);
});
it("keeps Restoring up while on-screen workspace chrome holds the reveal", () => {
const handoff = nextPostRestoreHandoff({ current: null, scopeKey, routeState: restoringState });
const settled = {
handoff,
scopeKey,
hasActiveWorkspace: true,
hasHydratedWorkspaceLayoutStore: true,
hasHydratedAgents: true,
hasReconciledAutoOpenAgentTabs: true,
visibleAgentCount: 1,
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready" as const,
visibleAgentsLoadingOlder: false,
routeState: { kind: "ready" as const },
};
// A tab row mounted behind the gate has not measured its tabs yet.
const held = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: true });
expect(held.displayedRouteState).toBe(restoringState);
expect(held.isHandoffReadyToMount).toBe(true);
expect(held.isHandoffReadyToRelease).toBe(false);
const released = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: false });
expect(released.isHandoffReadyToRelease).toBe(true);
});
it("marks handoff ready to release immediately when the workspace only has non-auto-open agents", () => {
const captured = nextPostRestoreHandoff({
current: null,
@@ -394,6 +427,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(resolved.isHandoffReadyToRelease).toBe(true);
@@ -164,6 +164,10 @@ import {
canSyncVisibleAgents,
usePostRestoreWorkspaceRouteState,
} from "@/screens/workspace/use-post-restore-handoff";
import {
type PostRestoreRevealHolds,
PostRestoreRevealHoldsProvider,
} from "@/screens/workspace/post-restore-reveal-holds";
import {
renderWorkspaceRouteGate,
WorkspaceLoading,
@@ -1432,6 +1436,7 @@ function WorkspaceScreenContent({
const {
displayedRouteState: displayedWorkspaceRouteState,
revealHolds,
isHoldingHandoff,
isPaneRouteFocused,
effectivePaneFocusSuspended,
@@ -3506,6 +3511,7 @@ function WorkspaceScreenContent({
return (
<PostRestoreOverlayShell
isHoldingHandoff={isHoldingHandoff}
revealHolds={revealHolds}
overlay={gatedWorkspaceScreen}
workspaceKey={persistenceKey}
sheetPaneHost={sheetPaneHost}
@@ -3529,12 +3535,14 @@ function WorkspaceScreenContent({
/** Keeps mounted workspace chrome hidden beneath the restoring gate during layout settle. */
function PostRestoreOverlayShell({
isHoldingHandoff,
revealHolds,
overlay,
workspaceKey,
sheetPaneHost,
children,
}: {
isHoldingHandoff: boolean;
revealHolds: PostRestoreRevealHolds;
overlay: ReactNode;
workspaceKey: string | null;
sheetPaneHost: Parameters<typeof WorkspaceContentProviders>[0]["sheetPaneHost"];
@@ -3552,13 +3560,15 @@ function PostRestoreOverlayShell({
accessibilityElementsHidden={isHoldingHandoff}
importantForAccessibility={isHoldingHandoff ? "no-hide-descendants" : "auto"}
>
<WorkspaceContentProviders
key={workspaceKey}
workspaceKey={workspaceKey}
sheetPaneHost={sheetPaneHost}
>
{children}
</WorkspaceContentProviders>
<PostRestoreRevealHoldsProvider holds={isHoldingHandoff ? revealHolds : null}>
<WorkspaceContentProviders
key={workspaceKey}
workspaceKey={workspaceKey}
sheetPaneHost={sheetPaneHost}
>
{children}
</WorkspaceContentProviders>
</PostRestoreRevealHoldsProvider>
</View>
) : null}
{overlay ? <View style={styles.postRestoreOverlay}>{overlay}</View> : null}
@@ -218,14 +218,24 @@ async function slowClick(element: HTMLElement) {
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
describe("sidebar workspace row presses", () => {
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
it("navigates on Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode, and toggles with Cmd/Ctrl+click once active", async () => {
mountHost(["a", "b", "c", "d"].map(makeEntry));
await userEvent.click(row("a"));
expect(navigatedKeys).toEqual(["srv:a"]);
expect(useSidebarSelectionStore.getState().active).toBe(false);
// Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click) must not enter select mode from idle.
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(useSidebarSelectionStore.getState().active).toBe(false);
expect(navigatedKeys).toEqual(["srv:a", "srv:c"]);
await userEvent.click(row("d"), { modifiers: [MOD_KEY, "Shift"] });
expect(useSidebarSelectionStore.getState().active).toBe(false);
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
// Once select mode is entered (e.g. via Shift+click), Cmd/Ctrl+click and plain clicks toggle.
await userEvent.click(row("c"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["c"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
@@ -238,31 +248,38 @@ describe("sidebar workspace row presses", () => {
// Plain clicks keep toggling while select mode is on.
await userEvent.click(row("a"));
expect(selectedIds()).toEqual(["a", "b", "d"]);
expect(navigatedKeys).toEqual(["srv:a"]);
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
});
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b"].map(makeEntry));
it("selects on the first Shift+click or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b", "c"].map(makeEntry));
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
markGestureCanceled("a");
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
await userEvent.click(row("a"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["a"]);
markGestureCanceled("b");
await userEvent.click(row("b"));
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a", "b"]);
markGestureCanceled("c");
await userEvent.click(row("c"));
expect(selectedIds()).toEqual(["a", "b", "c"]);
});
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
it("opens a row on a slow click and still selects it on the next Shift+click and Cmd/Ctrl+click", async () => {
mountHost(["a", "b"].map(makeEntry));
await act(() => slowClick(row("a")));
expect(navigatedKeys).toEqual(["srv:a"]);
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
await userEvent.click(row("a"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["a"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a", "b"]);
});
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
@@ -12,10 +12,12 @@ interface WorkspaceSelectionPressInput {
}
/**
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
* mouse users can keep tapping without a modifier.
* Routes a sidebar workspace row press between navigation and select mode:
* - Outside select mode, Shift+click (without Cmd/Ctrl) enters select mode on the clicked row
* alone; plain clicks and Cmd/Ctrl+clicks navigate normally so shortcut rollover and Cmd-held
* badge peeks never trigger bulk selection.
* - Inside select mode, Shift+click selects a Finder-style range from the anchor, and plain clicks
* or Cmd/Ctrl+clicks toggle one row without navigating.
*
* Selecting presses never consult the row's long-press flag. They never arm the long-press
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
@@ -30,7 +32,7 @@ export function useWorkspaceSelectionPress({
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const store = useSidebarSelectionStore.getState();
if (!store.active && !modifiers.shift && !modifiers.mod) {
if (!store.active && (!modifiers.shift || modifiers.mod)) {
onNavigate();
return;
}
@@ -43,12 +45,14 @@ export function useWorkspaceSelectionPress({
const handlePressIn = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
if (modifiers.shift || modifiers.mod) {
const isSelectionMode = useSidebarSelectionStore.getState().active;
const entersSelection = !isSelectionMode && modifiers.shift && !modifiers.mod;
if (entersSelection || (isSelectionMode && (modifiers.shift || modifiers.mod))) {
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
event.preventDefault?.();
return;
}
if (!useSidebarSelectionStore.getState().active) {
if (!isSelectionMode) {
onPressIn?.(event);
}
},
@@ -20,6 +20,10 @@ describe("buildAbsoluteExplorerPath", () => {
).toBe("/workspaces/paseo");
});
it.each(["/", "C:\\", "C:/"])("keeps the filesystem root %s absolute", (root) => {
expect(buildAbsoluteExplorerPath({ workspaceRoot: root, entryPath: "." })).toBe(root);
});
it("trims trailing separators from workspace root before joining", () => {
expect(
buildAbsoluteExplorerPath({
+13 -18
View File
@@ -9,28 +9,23 @@ export function buildAbsoluteExplorerPath({
workspaceRoot,
entryPath,
}: BuildAbsoluteExplorerPathInput): string {
const normalizedWorkspaceRoot = workspaceRoot.trim().replace(/[\\/]+$/, "");
const normalizedEntryPath = entryPath.trim();
if (!normalizedWorkspaceRoot) {
return normalizedEntryPath;
const root = workspaceRoot.trim();
const entry = entryPath.trim();
if (!root || isAbsolutePath(entry)) {
return entry;
}
if (!normalizedEntryPath || normalizedEntryPath === ".") {
return normalizedWorkspaceRoot;
const prefix = root.replace(/[\\/]+$/, "");
// Retain one separator on a filesystem root, including a Windows drive root.
const directory =
isAbsolutePath(root) && !isAbsolutePath(prefix) ? root.slice(0, prefix.length + 1) : prefix;
const segments = entry.split(/[\\/]+/).filter(Boolean);
if (segments.length === 0 || entry === ".") {
return directory;
}
if (isAbsolutePath(normalizedEntryPath)) {
return normalizedEntryPath;
}
const separator = normalizedWorkspaceRoot.includes("\\") ? "\\" : "/";
const segments = normalizedEntryPath.split(/[\\/]+/).filter(Boolean);
if (segments.length === 0) {
return normalizedWorkspaceRoot;
}
return `${normalizedWorkspaceRoot}${separator}${segments.join(separator)}`;
const separator = directory.includes("\\") ? "\\" : "/";
return [prefix, ...segments].join(separator);
}
export function parentExplorerPath(entryPath: string): string {
@@ -1,16 +1,17 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import type { ActiveConnection } from "@/runtime/host-runtime";
import { resolveWorkspaceScriptLink } from "./workspace-script-links";
import { resolveWorkspaceScriptLink, stripUrlProtocol } from "./workspace-script-links";
const runningService: WorkspaceScriptPayload = {
scriptName: "web",
type: "service",
hostname: "web--feature--paseo.localhost",
hostname: "web",
port: 3000,
localProxyUrl: "http://web--feature--paseo.localhost:6767",
localProxyUrl: null,
publicProxyUrl: null,
proxyUrl: "http://web--feature--paseo.localhost:6767",
proxyUrl: null,
tunnel: null,
lifecycle: "running",
health: "healthy",
exitCode: null,
@@ -25,56 +26,30 @@ function resolveLink(
}
describe("resolveWorkspaceScriptLink", () => {
it("defaults to the memorable Paseo URL locally and keeps direct as a fallback", () => {
it("resolves running services to localhost:<port> for local, socket, and relay connections", () => {
expect(
resolveLink({ type: "directTcp", endpoint: "localhost:6767", display: "localhost:6767" }),
).toEqual({
primary: {
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
targets: [
{
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
{ kind: "direct", label: "localhost:3000", url: "http://localhost:3000" },
],
label: "localhost:3000",
url: "http://localhost:3000",
});
});
it("defaults to an explicitly configured reverse proxy", () => {
const publicUrl = "https://web--feature--paseo.services.example.com";
expect(
resolveLink(
{ type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" },
{ ...runningService, publicProxyUrl: publicUrl, proxyUrl: publicUrl },
),
resolveLink({ type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" }),
).toEqual({
primary: {
kind: "public",
label: "web--feature--paseo.services.example.com",
url: publicUrl,
},
targets: [
{
kind: "public",
label: "web--feature--paseo.services.example.com",
url: publicUrl,
},
{
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
{ kind: "direct", label: "localhost:3000", url: "http://localhost:3000" },
],
label: "localhost:3000",
url: "http://localhost:3000",
});
expect(
resolveLink({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
).toEqual({
label: "localhost:3000",
url: "http://localhost:3000",
});
});
it("uses the daemon host and service port over a direct network connection", () => {
it("uses the daemon host and service port over a direct non-loopback TCP connection", () => {
expect(
resolveLink({
type: "directTcp",
@@ -82,123 +57,43 @@ describe("resolveWorkspaceScriptLink", () => {
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({
primary: {
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
targets: [
{
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
{
kind: "direct",
label: "mac-mini.tail123.ts.net:3000",
url: "http://mac-mini.tail123.ts.net:3000",
},
],
});
});
it("offers the reverse proxy and direct route over a direct network connection", () => {
const publicUrl = "https://web--feature--paseo.services.example.com";
expect(
resolveLink(
{ type: "directTcp", endpoint: "mac-mini.tail123.ts.net:6767", display: "remote" },
{ ...runningService, publicProxyUrl: publicUrl, proxyUrl: publicUrl },
).targets,
).toEqual([
{ kind: "public", label: "web--feature--paseo.services.example.com", url: publicUrl },
{
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
{
kind: "direct",
label: "mac-mini.tail123.ts.net:3000",
url: "http://mac-mini.tail123.ts.net:3000",
},
]);
});
it("keeps service routes available independently of a relay connection", () => {
const relay: ActiveConnection = {
type: "relay",
endpoint: "relay.paseo.sh:443",
display: "relay",
};
expect(resolveLink(relay)).toEqual({
primary: {
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
targets: [
{
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
{ kind: "direct", label: "localhost:3000", url: "http://localhost:3000" },
],
label: "mac-mini.tail123.ts.net:3000",
url: "http://mac-mini.tail123.ts.net:3000",
});
const publicUrl = "https://web--feature--paseo.services.example.com";
expect(
resolveLink(relay, { ...runningService, publicProxyUrl: publicUrl, proxyUrl: publicUrl }),
resolveLink({
type: "directTcp",
endpoint: "[fd7a:115c:a1e0::1]:6767",
display: "[fd7a:115c:a1e0::1]:6767",
}),
).toEqual({
primary: {
kind: "public",
label: "web--feature--paseo.services.example.com",
url: publicUrl,
},
targets: [
{
kind: "public",
label: "web--feature--paseo.services.example.com",
url: publicUrl,
},
{
kind: "paseo",
label: "web--feature--paseo.localhost:6767",
url: "http://web--feature--paseo.localhost:6767",
},
{ kind: "direct", label: "localhost:3000", url: "http://localhost:3000" },
],
label: "[fd7a:115c:a1e0::1]:3000",
url: "http://[fd7a:115c:a1e0::1]:3000",
});
});
it("classifies proxyUrl from older daemons", () => {
const { localProxyUrl: _local, publicProxyUrl: _public, ...legacyLocal } = runningService;
expect(resolveLink(null, legacyLocal).targets.map((target) => target.kind)).toEqual([
"paseo",
"direct",
]);
const publicUrl = "https://web--feature--paseo.services.example.com";
it("ignores legacy *.localhost proxy URLs and returns localhost:<port>", () => {
expect(
resolveLink(
{ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" },
{ ...legacyLocal, proxyUrl: publicUrl },
).primary,
resolveLink(null, {
...runningService,
localProxyUrl: "http://web--feature--paseo.localhost:6767",
proxyUrl: "http://web--feature--paseo.localhost:6767",
}),
).toEqual({
kind: "public",
label: "web--feature--paseo.services.example.com",
url: publicUrl,
label: "localhost:3000",
url: "http://localhost:3000",
});
});
it("has no routes for stopped services or plain scripts", () => {
expect(resolveLink(null, { ...runningService, lifecycle: "stopped" })).toEqual({
primary: null,
targets: [],
});
expect(resolveLink(null, { ...runningService, type: "script" })).toEqual({
primary: null,
targets: [],
});
it("returns null for stopped services, plain scripts, or services without a port", () => {
expect(resolveLink(null, { ...runningService, lifecycle: "stopped" })).toBeNull();
expect(resolveLink(null, { ...runningService, type: "script" })).toBeNull();
expect(resolveLink(null, { ...runningService, port: null })).toBeNull();
});
it("strips http and https protocols for display labels", () => {
expect(stripUrlProtocol("http://localhost:3000")).toBe("localhost:3000");
expect(stripUrlProtocol("https://demo.trycloudflare.com")).toBe("demo.trycloudflare.com");
});
});
@@ -2,19 +2,11 @@ import { parseHostPort } from "@getpaseo/protocol/daemon-endpoints";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import type { ActiveConnection } from "@/runtime/host-runtime";
export type WorkspaceScriptLinkKind = "public" | "paseo" | "direct";
export interface WorkspaceScriptLinkTarget {
kind: WorkspaceScriptLinkKind;
label: string;
url: string;
}
export interface ResolvedWorkspaceScriptLink {
primary: WorkspaceScriptLinkTarget | null;
targets: WorkspaceScriptLinkTarget[];
}
function isLoopbackHost(host: string): boolean {
const normalizedHost = host.trim().toLowerCase();
return (
@@ -22,21 +14,11 @@ function isLoopbackHost(host: string): boolean {
);
}
function isLocalOnlyUrl(url: string | null | undefined): boolean {
if (!url) return true;
try {
const hostname = new URL(url).hostname.toLowerCase();
return isLoopbackHost(hostname) || hostname.endsWith(".localhost");
} catch {
return true;
}
}
function stripUrlProtocol(url: string): string {
export function stripUrlProtocol(url: string): string {
return url.replace(/^https?:\/\//, "");
}
function buildDirectServiceUrl(
function buildLocalServiceUrl(
activeConnection: ActiveConnection | null,
port: number | null,
): string | null {
@@ -58,35 +40,16 @@ function buildDirectServiceUrl(
}
}
function addTarget(
targets: WorkspaceScriptLinkTarget[],
kind: WorkspaceScriptLinkKind,
url: string | null | undefined,
): void {
if (!url || targets.some((target) => target.url === url)) return;
targets.push({ kind, label: stripUrlProtocol(url), url });
}
export function resolveWorkspaceScriptLink(input: {
script: WorkspaceScriptPayload;
activeConnection: ActiveConnection | null;
}): ResolvedWorkspaceScriptLink {
}): WorkspaceScriptLinkTarget | null {
const { script, activeConnection } = input;
if (script.type !== "service" || script.lifecycle !== "running") {
return { primary: null, targets: [] };
return null;
}
// COMPAT(workspaceScriptSplitUrls): added in v0.2.0, remove after 2027-01-21.
// Old daemons only send proxyUrl, so classify it by reachability.
const localProxyUrl =
script.localProxyUrl ?? (isLocalOnlyUrl(script.proxyUrl) ? script.proxyUrl : null);
const publicProxyUrl =
script.publicProxyUrl ?? (!isLocalOnlyUrl(script.proxyUrl) ? script.proxyUrl : null);
const targets: WorkspaceScriptLinkTarget[] = [];
addTarget(targets, "public", publicProxyUrl);
addTarget(targets, "paseo", localProxyUrl);
addTarget(targets, "direct", buildDirectServiceUrl(activeConnection, script.port));
return { primary: targets[0] ?? null, targets };
const url = buildLocalServiceUrl(activeConnection, script.port);
if (!url) return null;
return { label: stripUrlProtocol(url), url };
}
@@ -1,48 +0,0 @@
import { describe, expect, it } from "vitest";
import type { StateStorage } from "zustand/middleware";
import { createWorkspaceServiceRoutePreferencesStore } from "./store";
function createMemoryStorage(initial?: Record<string, string>): StateStorage & {
values: Map<string, string>;
} {
const values = new Map(Object.entries(initial ?? {}));
return {
values,
getItem: async (name) => values.get(name) ?? null,
setItem: async (name, value) => {
values.set(name, value);
},
removeItem: async (name) => {
values.delete(name);
},
};
}
describe("workspace service route preferences", () => {
it("persists each host's preferred route", async () => {
const storage = createMemoryStorage();
const first = createWorkspaceServiceRoutePreferencesStore(storage);
await first.persist.rehydrate();
first.getState().setPreferredRoute("desktop", "direct");
first.getState().setPreferredRoute("devbox", "public");
const restored = createWorkspaceServiceRoutePreferencesStore(storage);
await restored.persist.rehydrate();
expect(restored.getState().byServerId).toEqual({ desktop: "direct", devbox: "public" });
});
it("clears the complete persisted value when one route kind is invalid", async () => {
const storage = createMemoryStorage({
"workspace-service-route-preferences": JSON.stringify({
state: { byServerId: { desktop: "direct", broken: "unknown" } },
version: 1,
}),
});
const store = createWorkspaceServiceRoutePreferencesStore(storage);
await store.persist.rehydrate();
expect(store.getState().byServerId).toEqual({});
expect(storage.values.has("workspace-service-route-preferences")).toBe(false);
});
});
@@ -1,49 +0,0 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { create } from "zustand";
import { persist, type StateStorage } from "zustand/middleware";
import { z } from "zod";
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
import type { WorkspaceScriptLinkKind } from "@/utils/workspace-script-links";
interface WorkspaceServiceRoutePreferencesState {
byServerId: Record<string, WorkspaceScriptLinkKind>;
setPreferredRoute: (serverId: string, kind: WorkspaceScriptLinkKind) => void;
}
const WorkspaceScriptLinkKindSchema = z.enum(["public", "paseo", "direct"]);
const WorkspaceServiceRoutePreferencesSchema = z.strictObject({
byServerId: z.record(z.string(), WorkspaceScriptLinkKindSchema),
});
export function createWorkspaceServiceRoutePreferencesStore(storage: StateStorage) {
return create<WorkspaceServiceRoutePreferencesState>()(
persist<
WorkspaceServiceRoutePreferencesState,
[],
[],
z.infer<typeof WorkspaceServiceRoutePreferencesSchema>
>(
(set) => ({
byServerId: {},
setPreferredRoute: (serverId, kind) =>
set((state) => ({ byServerId: { ...state.byServerId, [serverId]: kind } })),
}),
{
name: "workspace-service-route-preferences",
version: 1,
storage: createValidatedPersistStorage(storage, WorkspaceServiceRoutePreferencesSchema),
partialize: (state) => ({ byServerId: state.byServerId }),
merge: (persistedState, currentState) => {
const result = WorkspaceServiceRoutePreferencesSchema.safeParse(persistedState);
return {
...currentState,
byServerId: result.success ? result.data.byServerId : {},
};
},
},
),
);
}
export const useWorkspaceServiceRoutePreferencesStore =
createWorkspaceServiceRoutePreferencesStore(AsyncStorage);
@@ -144,6 +144,15 @@ describe("workspace file actions", () => {
expect(host.openedInDefaultApp).toEqual(["~/Downloads/report.csv"]);
});
it("reveals an entry in a workspace rooted at the filesystem root", async () => {
const host = new FakeHost();
host.workspaceRoot = "/";
await createWorkspaceFileCommands(host).revealInFileManager("usr/bin");
expect(host.revealedInFileManager).toEqual(["/usr/bin"]);
});
it("reports a failed desktop action", async () => {
const host = new FakeHost();
host.fileManager = {
@@ -1,4 +1,4 @@
import { useCallback, useRef } from "react";
import { useCallback, useRef, useSyncExternalStore } from "react";
import { useTranslation } from "react-i18next";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useToast } from "@/contexts/toast-context";
@@ -14,7 +14,9 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
isWorkspaceArchiveAttemptPending,
runWorkspaceArchiveAttempt,
subscribeWorkspaceArchiveAttempts,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -41,6 +43,8 @@ export interface ArchiveWorkspaceInput {
export interface WorkspaceArchiveController {
archive: () => void;
/** True from the press until the archive starts or you cancel it, wherever it was pressed. */
isConfirming: boolean;
}
export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArchiveController {
@@ -122,6 +126,16 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
return confirmed ? { force: risk.isDirty === true } : null;
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
const readIsConfirming = useCallback(
() => isWorkspaceArchiveAttemptPending({ serverId, workspaceId }),
[serverId, workspaceId],
);
const isConfirming = useSyncExternalStore(
subscribeWorkspaceArchiveAttempts,
readIsConfirming,
readIsConfirming,
);
const archive = useCallback(() => {
void runWorkspaceArchiveAttempt({
workspace: { serverId, workspaceId },
@@ -132,5 +146,6 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
return {
archive,
isConfirming,
};
}
@@ -16,6 +16,9 @@ import {
archiveWorkspaceOptimistically,
archiveWorkspacesOptimistically,
beginOptimisticWorkspaceArchive,
isWorkspaceArchiveAttemptPending,
runWorkspaceArchiveAttempt,
subscribeWorkspaceArchiveAttempts,
undoWorkspaceArchiveOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -111,6 +114,84 @@ afterEach(() => {
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
});
describe("runWorkspaceArchiveAttempt", () => {
it("shows the archive as pending while it waits for the host's answer", async () => {
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace()]);
const hostAnswer = deferred<{ force: boolean } | null>();
const archiveRequests: Array<{ force: boolean } | undefined> = [];
const attempt = runWorkspaceArchiveAttempt({
workspace: target(),
confirm: () => hostAnswer.promise,
archive: async (options) => {
archiveRequests.push(options);
},
});
expect(isWorkspaceArchiveAttemptPending(target())).toBe(true);
expect(archiveRequests).toEqual([]);
hostAnswer.resolve({ force: true });
await attempt;
expect(archiveRequests).toEqual([{ force: true }]);
expect(isWorkspaceArchiveAttemptPending(target())).toBe(false);
});
it("stops showing the archive as pending when you cancel the warning", async () => {
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace()]);
const archiveRequests: Array<{ force: boolean } | undefined> = [];
await runWorkspaceArchiveAttempt({
workspace: target(),
confirm: async () => null,
archive: async (options) => {
archiveRequests.push(options);
},
});
expect(archiveRequests).toEqual([]);
expect(isWorkspaceArchiveAttemptPending(target())).toBe(false);
});
it("tells subscribers when the pending state starts and ends", async () => {
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace()]);
const hostAnswer = deferred<{ force: boolean } | null>();
const seen: boolean[] = [];
const unsubscribe = subscribeWorkspaceArchiveAttempts(() => {
seen.push(isWorkspaceArchiveAttemptPending(target()));
});
const attempt = runWorkspaceArchiveAttempt({
workspace: target(),
confirm: () => hostAnswer.promise,
archive: async () => {},
});
hostAnswer.resolve({ force: true });
await attempt;
unsubscribe();
expect(seen).toEqual([true, false]);
});
it("keeps other workspaces idle while one archive is pending", async () => {
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace()]);
const hostAnswer = deferred<{ force: boolean } | null>();
const attempt = runWorkspaceArchiveAttempt({
workspace: target(),
confirm: () => hostAnswer.promise,
archive: async () => {},
});
expect(isWorkspaceArchiveAttemptPending(target({ workspaceId: "workspace-2" }))).toBe(false);
expect(isWorkspaceArchiveAttemptPending(target({ serverId: SECOND_SERVER_ID }))).toBe(false);
hostAnswer.resolve(null);
await attempt;
});
});
describe("archiveWorkspaceOptimistically", () => {
it("hides the workspace and marks the archive pending while the daemon call runs", async () => {
const archived = workspace();
@@ -22,6 +22,31 @@ export interface WorkspaceArchiveTarget {
}
const pendingArchiveAttempts = new Set<string>();
const archiveAttemptListeners = new Set<() => void>();
function archiveAttemptKey(workspace: WorkspaceArchiveTarget): string {
return JSON.stringify([workspace.serverId, workspace.workspaceId]);
}
function notifyArchiveAttemptListeners(): void {
for (const listener of archiveAttemptListeners) listener();
}
/**
* True while an archive of the workspace waits for its confirmation: the host's answer about
* uncommitted work, then the warning. The row stays listed until then, so it shows this as pending.
*/
export function isWorkspaceArchiveAttemptPending(workspace: WorkspaceArchiveTarget): boolean {
return pendingArchiveAttempts.has(archiveAttemptKey(workspace));
}
/** Calls `listener` whenever any workspace's archive attempt starts or settles. */
export function subscribeWorkspaceArchiveAttempts(listener: () => void): () => void {
archiveAttemptListeners.add(listener);
return () => {
archiveAttemptListeners.delete(listener);
};
}
/** Checks and starts one archive at a time for a workspace. */
export async function runWorkspaceArchiveAttempt(input: {
@@ -29,11 +54,11 @@ export async function runWorkspaceArchiveAttempt(input: {
confirm?: () => Promise<{ force: boolean } | null>;
archive: (options?: { force: boolean }) => Promise<void>;
}): Promise<void> {
const { serverId, workspaceId } = input.workspace;
const key = JSON.stringify([serverId, workspaceId]);
const key = archiveAttemptKey(input.workspace);
if (pendingArchiveAttempts.has(key)) return;
pendingArchiveAttempts.add(key);
notifyArchiveAttemptListeners();
try {
const confirmed = input.confirm ? await input.confirm() : undefined;
if (confirmed === null) return;
@@ -43,6 +68,7 @@ export async function runWorkspaceArchiveAttempt(input: {
return input.archive(confirmed);
} finally {
pendingArchiveAttempts.delete(key);
notifyArchiveAttemptListeners();
}
}
@@ -0,0 +1,95 @@
import { describe, expect, test } from "vitest";
import { workspaceScriptSchema, type WorkspaceScriptRow } from "./schema.js";
function renderRow(script: WorkspaceScriptRow): Record<string, string | number> {
const result: Record<string, string | number> = {};
for (const column of workspaceScriptSchema.columns) {
result[column.header] =
typeof column.field === "function"
? String(column.field(script))
: String(script[column.field] ?? "-");
}
return result;
}
describe("workspaceScriptSchema", () => {
test("reports local URL and active tunnel URL for running services without legacy proxy URLs", () => {
const row = renderRow({
scriptName: "web",
type: "service",
hostname: "web",
port: 3000,
localProxyUrl: null,
publicProxyUrl: "https://demo.trycloudflare.com",
proxyUrl: "https://demo.trycloudflare.com",
tunnel: {
exposureId: "service:wks_1:web",
providerId: "cloudflared",
state: "ready",
url: "https://demo.trycloudflare.com",
stability: "ephemeral",
detail: null,
error: null,
},
lifecycle: "running",
health: "healthy",
exitCode: null,
terminalId: "term-1",
});
expect(row).toEqual({
NAME: "web",
TYPE: "service",
LIFECYCLE: "running",
HEALTH: "healthy",
PORT: "3000",
"LOCAL URL": "http://localhost:3000",
TUNNEL: "https://demo.trycloudflare.com",
TERMINAL: "term-1",
});
});
test("shows tunnel state while connecting and dashes for stopped services", () => {
const connecting = renderRow({
scriptName: "api",
type: "service",
hostname: "api",
port: 4000,
localProxyUrl: null,
publicProxyUrl: null,
proxyUrl: null,
tunnel: {
exposureId: "service:wks_1:api",
providerId: "cloudflared",
state: "connecting",
url: null,
stability: null,
detail: null,
error: null,
},
lifecycle: "running",
health: null,
exitCode: null,
terminalId: "term-2",
});
expect(connecting["LOCAL URL"]).toBe("http://localhost:4000");
expect(connecting.TUNNEL).toBe("connecting");
const stopped = renderRow({
scriptName: "api",
type: "service",
hostname: "api",
port: 4000,
localProxyUrl: null,
publicProxyUrl: null,
proxyUrl: null,
tunnel: null,
lifecycle: "stopped",
health: null,
exitCode: 0,
terminalId: null,
});
expect(stopped["LOCAL URL"]).toBe("-");
expect(stopped.TUNNEL).toBe("-");
});
});
+19 -1
View File
@@ -3,6 +3,23 @@ import type { OutputSchema } from "../../output/index.js";
export type WorkspaceScriptRow = WorkspaceScriptPayload;
function formatLocalUrl(script: WorkspaceScriptRow): string {
if (script.type !== "service" || script.lifecycle !== "running" || script.port === null) {
return "-";
}
return `http://localhost:${script.port}`;
}
function formatTunnel(script: WorkspaceScriptRow): string {
if (script.tunnel) {
return script.tunnel.url ?? script.tunnel.state;
}
if (script.publicProxyUrl) {
return script.publicProxyUrl;
}
return "-";
}
export const workspaceScriptSchema: OutputSchema<WorkspaceScriptRow> = {
idField: "scriptName",
columns: [
@@ -11,7 +28,8 @@ export const workspaceScriptSchema: OutputSchema<WorkspaceScriptRow> = {
{ header: "LIFECYCLE", field: "lifecycle", width: 10 },
{ header: "HEALTH", field: (script) => script.health ?? "-", width: 10 },
{ header: "PORT", field: (script) => script.port ?? "-", width: 7 },
{ header: "PROXY URL", field: (script) => script.proxyUrl ?? "-", width: 42 },
{ header: "LOCAL URL", field: formatLocalUrl, width: 24 },
{ header: "TUNNEL", field: formatTunnel, width: 42 },
{ header: "TERMINAL", field: (script) => script.terminalId ?? "-", width: 12 },
],
};
+65
View File
@@ -3408,6 +3408,47 @@ export class DaemonClientCore {
});
}
private requireWorkspaceScriptTunnels(): void {
if (!this.isConnected) {
throw this.unavailableError();
}
// COMPAT(workspaceScriptTunnels): added in v0.19.0, remove gate after 2027-06-01.
if (this.getLastServerInfoMessage()?.features?.workspaceScriptTunnels !== true) {
throw Object.assign(new Error("Update the daemon to open tunnels for workspace services"), {
code: "unsupported_capability",
});
}
}
async openWorkspaceScriptTunnel(
input: { workspaceId: string; scriptName: string; providerId: string },
requestId?: string,
): Promise<
Extract<SessionOutboundMessage, { type: "workspace.script.tunnel.open.response" }>["payload"]
> {
this.requireWorkspaceScriptTunnels();
return this.sendCorrelatedSessionRequest({
requestId,
timeout: 35_000,
message: { type: "workspace.script.tunnel.open.request", ...input },
responseType: "workspace.script.tunnel.open.response",
});
}
async closeWorkspaceScriptTunnel(
input: { workspaceId: string; scriptName: string },
requestId?: string,
): Promise<
Extract<SessionOutboundMessage, { type: "workspace.script.tunnel.close.response" }>["payload"]
> {
this.requireWorkspaceScriptTunnels();
return this.sendCorrelatedSessionRequest({
requestId,
message: { type: "workspace.script.tunnel.close.request", ...input },
responseType: "workspace.script.tunnel.close.response",
});
}
async archiveWorkspace(
workspaceId: string,
requestId?: string,
@@ -6223,6 +6264,30 @@ export class DaemonClientCore {
});
}
private requireTunnelProviders(): void {
if (!this.isConnected) {
throw this.unavailableError();
}
// COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01.
if (this.getLastServerInfoMessage()?.features?.tunnelProviders !== true) {
throw Object.assign(new Error("Update the daemon to use tunnel providers"), {
code: "unsupported_capability",
});
}
}
async listTunnelProviders(
requestId?: string,
): Promise<
Extract<SessionOutboundMessage, { type: "tunnel.providers.list.response" }>["payload"]
> {
this.requireTunnelProviders();
return this.sendNamespacedCorrelatedSessionRequest<"tunnel.providers.list.response">({
requestId,
message: { type: "tunnel.providers.list.request" },
});
}
async requestProjectIcon(
cwd: string,
requestId?: string,
@@ -0,0 +1,245 @@
import { describe, expect, test } from "vitest";
import { DaemonClient, type DaemonTransport } from "./daemon-client.js";
function createFakeTransport(features: Record<string, boolean | undefined>): {
transport: DaemonTransport;
sent: unknown[];
} {
const sent: unknown[] = [];
const openHandlers = new Set<() => void>();
const messageHandlers = new Set<(data: unknown, isBinary: boolean) => void | Promise<void>>();
const closeHandlers = new Set<(event?: unknown) => void>();
const errorHandlers = new Set<(event?: unknown) => void>();
const emitMessage = (text: string) => {
queueMicrotask(() => {
for (const handler of messageHandlers) {
void handler(text, false);
}
});
};
const transport: DaemonTransport = {
onOpen(handler) {
openHandlers.add(handler);
queueMicrotask(() => handler());
return () => openHandlers.delete(handler);
},
onMessage(handler) {
messageHandlers.add(handler);
return () => messageHandlers.delete(handler);
},
onClose(handler) {
closeHandlers.add(handler);
return () => closeHandlers.delete(handler);
},
onError(handler) {
errorHandlers.add(handler);
return () => errorHandlers.delete(handler);
},
send(data) {
if (typeof data !== "string") return;
const parsed = JSON.parse(data) as {
type: string;
message?: Record<string, unknown>;
};
sent.push(parsed);
if (parsed.type === "hello") {
emitMessage(
JSON.stringify({
type: "session",
message: {
type: "status",
payload: {
status: "server_info",
serverId: "srv_test",
version: "0.18.2",
features,
},
},
}),
);
return;
}
if (parsed.type !== "session" || !parsed.message) return;
const requestId = parsed.message.requestId;
if (typeof requestId !== "string") return;
if (parsed.message.type === "tunnel.providers.list.request") {
emitMessage(
JSON.stringify({
type: "session",
message: {
type: "tunnel.providers.list.response",
payload: {
requestId,
providers: [
{
id: "cloudflared",
pluginId: "cloudflared-tunnel",
label: "Cloudflare Tunnel",
availability: { status: "available", detail: "quick tunnel" },
},
],
},
},
}),
);
return;
}
if (
parsed.message.type === "workspace.script.tunnel.open.request" ||
parsed.message.type === "workspace.script.tunnel.close.request"
) {
const opening = parsed.message.type === "workspace.script.tunnel.open.request";
emitMessage(
JSON.stringify({
type: "session",
message: {
type: opening
? "workspace.script.tunnel.open.response"
: "workspace.script.tunnel.close.response",
payload: {
requestId,
workspaceId: parsed.message.workspaceId,
scriptName: parsed.message.scriptName,
script: {
scriptName: parsed.message.scriptName,
type: "service",
hostname: "web",
port: 3000,
tunnel: opening
? {
exposureId: "service:wks_1:web",
providerId: parsed.message.providerId,
state: "ready",
url: "https://demo.trycloudflare.com",
stability: "ephemeral",
detail: null,
error: null,
}
: null,
lifecycle: "running",
health: "healthy",
},
error: null,
},
},
}),
);
}
},
close() {
for (const handler of closeHandlers) {
handler({ code: 1000, reason: "closed" });
}
},
};
return { transport, sent };
}
function sentMessageTypes(sent: unknown[]): string[] {
return sent.map((entry) =>
String((entry as { message?: { type?: string } }).message?.type ?? ""),
);
}
describe("DaemonClient tunnel RPCs", () => {
test("fails closed with unsupported_capability when daemon does not advertise tunnelProviders", async () => {
const { transport, sent } = createFakeTransport({});
const client = new DaemonClient({
url: "ws://127.0.0.1:6767/ws",
clientId: "test-client",
transportFactory: () => transport,
});
await client.connect();
await expect(client.listTunnelProviders()).rejects.toMatchObject({
code: "unsupported_capability",
});
expect(sentMessageTypes(sent).some((type) => type.startsWith("tunnel."))).toBe(false);
await client.close();
});
test("refuses script tunnels on a daemon that has tunnel providers but not script tunnels", async () => {
const { transport, sent } = createFakeTransport({ tunnelProviders: true });
const client = new DaemonClient({
url: "ws://127.0.0.1:6767/ws",
clientId: "test-client",
transportFactory: () => transport,
});
await client.connect();
await expect(
client.openWorkspaceScriptTunnel({
workspaceId: "wks_1",
scriptName: "web",
providerId: "cloudflared",
}),
).rejects.toMatchObject({ code: "unsupported_capability" });
await expect(
client.closeWorkspaceScriptTunnel({ workspaceId: "wks_1", scriptName: "web" }),
).rejects.toMatchObject({ code: "unsupported_capability" });
expect(sentMessageTypes(sent).some((type) => type.startsWith("workspace.script.tunnel."))).toBe(
false,
);
await client.close();
});
test("lists tunnel providers, then opens and closes a script tunnel", async () => {
const { transport } = createFakeTransport({
tunnelProviders: true,
workspaceScriptTunnels: true,
});
const client = new DaemonClient({
url: "ws://127.0.0.1:6767/ws",
clientId: "test-client",
transportFactory: () => transport,
});
await client.connect();
const providers = await client.listTunnelProviders("req-list");
expect(providers).toEqual({
requestId: "req-list",
providers: [
{
id: "cloudflared",
pluginId: "cloudflared-tunnel",
label: "Cloudflare Tunnel",
availability: { status: "available", detail: "quick tunnel" },
},
],
});
const opened = await client.openWorkspaceScriptTunnel(
{ workspaceId: "wks_1", scriptName: "web", providerId: "cloudflared" },
"req-open",
);
expect(opened).toMatchObject({
requestId: "req-open",
error: null,
script: {
scriptName: "web",
tunnel: {
providerId: "cloudflared",
state: "ready",
url: "https://demo.trycloudflare.com",
},
},
});
const closed = await client.closeWorkspaceScriptTunnel(
{ workspaceId: "wks_1", scriptName: "web" },
"req-close",
);
expect(closed).toMatchObject({ requestId: "req-close", error: null, script: { tunnel: null } });
await client.close();
});
});
@@ -32,6 +32,7 @@ import type {
AcpRequest,
AcpToolCallSnapshot,
AcpTransformer,
AcpTurnEndContext,
AcpVendorUpdate,
RunAcpProviderOptions,
} from "../acp.js";
@@ -567,7 +568,7 @@ type PendingPermission = PendingToolPermission | PendingElicitation;
type DeferredTurnOutcome =
| { type: "complete"; terminalizeTools: boolean }
| { type: "cancel" }
| { type: "fail"; error: { message: string } };
| { type: "fail"; error: ProviderError };
interface DeferredTurnState {
timer: ReturnType<typeof setTimeout> | null;
@@ -587,6 +588,7 @@ interface ActivePrompt {
crossedEndTurn: boolean;
replyState: DeferredReplyState;
deferred: DeferredTurnState | null;
lastAssistantMessage?: string;
}
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
@@ -1021,21 +1023,15 @@ class AcpRuntime {
await this.drainNotifications();
activePrompt.wirePromptsInFlight -= 1;
if (activePrompt.retired) return undefined;
if (response.usage) {
this.lastUsage = {
...this.lastUsage,
inputTokens: response.usage.inputTokens,
outputTokens: response.usage.outputTokens,
cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
};
this.emit({
type: "session.usage",
sessionId: this.options.boundarySessionId,
turnId,
usage: this.lastUsage,
});
}
if (response.usage) this.recordTurnUsage(turnId, response.usage);
const state = response.stopReason === "cancelled" ? "canceled" : "completed";
if (state === "completed") {
const turnFailure = this.evaluateTurnEnd(activePrompt, response.stopReason);
if (turnFailure) {
this.finishPromptTurn(turnId, "failed", turnFailure.error);
return undefined;
}
}
if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
await this.settleDeferredPrompt(activePrompt);
return undefined;
@@ -1780,6 +1776,9 @@ class AcpRuntime {
const id = this.resolveChunkId(update.sessionUpdate, update.messageId);
const text = `${this.messages.get(id) ?? ""}${update.content.text}`;
this.messages.set(id, text);
this.recordLastAssistantMessage(
update.sessionUpdate === "agent_message_chunk" ? text : undefined,
);
this.emit({
type: "timeline.item",
sessionId: this.options.boundarySessionId,
@@ -1797,10 +1796,14 @@ class AcpRuntime {
}
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear();
this.recordLastAssistantMessage(undefined);
this.reduceToolCall(update, wireSeq);
return;
}
if (update.sessionUpdate === "plan") this.fallbackChunkIds.clear();
if (update.sessionUpdate === "plan") {
this.fallbackChunkIds.clear();
this.recordLastAssistantMessage(undefined);
}
this.reduceStateUpdate(update, wireSeq);
}
@@ -2122,7 +2125,7 @@ class AcpRuntime {
private finishPromptTurn(
turnId: string,
state: "completed" | "failed" | "canceled",
error?: { message: string },
error?: ProviderError,
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
): void {
this.fallbackChunkIds.clear();
@@ -2202,33 +2205,15 @@ class AcpRuntime {
}
this.fallbackChunkIds.clear();
active.lastPromptResponseWireSeq = null;
active.lastAssistantMessage = undefined;
if (active.replyState === "settled_with_open_tools") active.replyState = "idle";
const response = await this.call(
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
);
await this.drainNotifications();
if (this.closing || this.activeRetirement || active.deferred !== deferred) return;
if (response.usage) {
this.lastUsage = {
...this.lastUsage,
inputTokens: response.usage.inputTokens,
outputTokens: response.usage.outputTokens,
cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
};
this.emit({
type: "session.usage",
sessionId: this.options.boundarySessionId,
turnId: active.turnId,
usage: this.lastUsage,
});
}
if (response.stopReason === "cancelled") {
this.finishDeferredTurn(active, { type: "cancel" });
return;
}
if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
}
if (response.usage) this.recordTurnUsage(active.turnId, response.usage);
this.settleSteerResponse(active, input.prompt.clientMessageId, response.stopReason);
} catch (error) {
await this.drainNotifications();
if (this.closing || this.activeRetirement || active.deferred !== deferred) return;
@@ -2238,16 +2223,7 @@ class AcpRuntime {
error: { message: describeError(error) },
});
} else {
this.emit({
type: "session.notice",
sessionId: this.options.boundarySessionId,
notice: {
id: `acp:steer-error:${input.prompt.clientMessageId}`,
severity: "error",
title: "Follow-up prompt failed",
description: describeError(error),
},
});
this.emitSteerFailure(input.prompt.clientMessageId, describeError(error));
}
} finally {
if (active.lastPromptResponseWireSeq === null) {
@@ -2397,9 +2373,91 @@ class AcpRuntime {
) {
return;
}
const turnFailure = this.evaluateTurnEnd(active, "end_turn");
if (turnFailure) {
this.finishDeferredTurn(active, { type: "fail", error: turnFailure.error });
return;
}
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
}
private recordTurnUsage(
turnId: string,
usage: { inputTokens?: number; outputTokens?: number; cachedReadTokens?: number | null },
): void {
this.lastUsage = {
...this.lastUsage,
inputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
cachedInputTokens: usage.cachedReadTokens ?? undefined,
};
this.emit({
type: "session.usage",
sessionId: this.options.boundarySessionId,
turnId,
usage: this.lastUsage,
});
}
private recordLastAssistantMessage(message: string | undefined): void {
if (this.replayWindow !== null || !this.activePrompt) return;
this.activePrompt.lastAssistantMessage = message;
}
private emitSteerFailure(clientMessageId: string, description: string): void {
this.emit({
type: "session.notice",
sessionId: this.options.boundarySessionId,
notice: {
id: `acp:steer-error:${clientMessageId}`,
severity: "error",
title: "Follow-up prompt failed",
description,
},
});
}
private settleSteerResponse(
active: ActivePrompt,
clientMessageId: string,
stopReason: string,
): void {
if (stopReason === "cancelled") {
this.finishDeferredTurn(active, { type: "cancel" });
return;
}
const turnFailure = this.evaluateTurnEnd(active, stopReason);
if (turnFailure) {
// Steers Paseo already accepted are still queued behind this one. Report this reply and
// let the last one settle the turn.
if (active.wirePromptsInFlight > 1) {
this.emitSteerFailure(clientMessageId, turnFailure.error.message);
} else {
this.finishDeferredTurn(active, { type: "fail", error: turnFailure.error });
}
return;
}
if (stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
}
}
private evaluateTurnEnd(
active: ActivePrompt,
stopReason: string,
): { state: "failed"; error: ProviderError } | null {
const context: AcpTurnEndContext = {
sessionId: this.options.boundarySessionId,
stopReason,
lastAssistantMessage: active.lastAssistantMessage,
};
for (const transformer of this.transformers) {
const outcome = transformer.turnEnd?.(context);
if (outcome?.state === "failed") return outcome;
}
return null;
}
private waitForInitialCommands(): Promise<void> {
if (this.receivedInitialCommands) return Promise.resolve();
const timeoutMs = this.options.options.acpOptions?.initialCommandsTimeoutMs ?? 1_000;
+291 -1
View File
@@ -19,7 +19,12 @@ import type {
import { afterEach, describe, expect, it, vi } from "vitest";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
import { runAcpProvider, type AcpStreamMessage } from "./acp.js";
import {
runAcpProvider,
type AcpStreamMessage,
type AcpTransformer,
type AcpTurnEndContext,
} from "./acp.js";
const temporaryDirectories: string[] = [];
@@ -8720,3 +8725,288 @@ describe("runAcpProvider interrupt settlement and hung-cancel retirement (#3256)
}
});
});
describe("turnEnd transformer hook", () => {
it("fails an end_turn prompt when turnEnd reports a failure and clears prior text across tool calls", async () => {
const contexts: AcpTurnEndContext[] = [];
const harness = connectorHarness({
handleRequest(instance, request) {
if (request.method !== "session/prompt") return false;
const params = request.params as { sessionId: string; prompt: Array<{ text?: string }> };
const promptText = params.prompt.map((part) => part.text ?? "").join("");
if (promptText === "fail-turn") {
instance.notify("session/update", {
sessionId: params.sessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "fatal: stream aborted" },
},
});
instance.respond(request, { stopReason: "end_turn" });
return true;
}
if (promptText === "tool-after-message") {
instance.notify("session/update", {
sessionId: params.sessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "fatal: stream aborted" },
},
});
instance.notify("session/update", {
sessionId: params.sessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "t1",
title: "Check status",
status: "completed",
},
});
instance.respond(request, { stopReason: "end_turn" });
return true;
}
return false;
},
});
const registration = runAcpProvider({
id: "turn-end-acp",
label: "TurnEnd ACP",
connector: harness.connector,
transformers: [
{
turnEnd(context) {
contexts.push(context);
if (context.lastAssistantMessage === "fatal: stream aborted") {
return { state: "failed", error: { message: "stream aborted" } };
}
return null;
},
},
],
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "m-fail",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "fail-turn" }] },
},
});
expect(
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:m-fail" &&
event.state !== "started",
),
).toEqual({
type: "session.turn",
sessionId: "session-1",
turnId: "acp:m-fail",
state: "failed",
error: { message: "stream aborted" },
});
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "m-tool",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "tool-after-message" }] },
},
});
expect(
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:m-tool" &&
event.state !== "started",
),
).toEqual({
type: "session.turn",
sessionId: "session-1",
turnId: "acp:m-tool",
state: "completed",
});
expect(contexts).toStrictEqual([
{
sessionId: "session-1",
stopReason: "end_turn",
lastAssistantMessage: "fatal: stream aborted",
},
{ sessionId: "session-1", stopReason: "end_turn", lastAssistantMessage: undefined },
]);
} finally {
await connection.close();
}
});
const executorFailure = {
message: "Executor failed",
code: "executor",
diagnostic: "native trace",
};
const failOnExecutorMessage: AcpTransformer = {
turnEnd: ({ lastAssistantMessage }) =>
lastAssistantMessage === executorFailure.message
? { state: "failed", error: executorFailure }
: null,
};
const promptInput = (
clientMessageId: string,
delivery: "auto" | "steer",
text: string,
): ProviderInput => ({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId,
delivery,
input: { type: "message", content: [{ type: "text", text }] },
},
});
const isTerminalTurn = (event: ProviderEvent) =>
event.type === "session.turn" && event.state !== "started";
it("drops the last assistant message when a tool call update follows it", async () => {
const { connector } = connectorHarness({
handleRequest(instance, request) {
if (request.method !== "session/prompt") return false;
const notify = (update: unknown) =>
instance.notify("session/update", { sessionId: "connector-session", update });
notify({ sessionUpdate: "tool_call", toolCallId: "t1", title: "Build" });
notify(textChunk(executorFailure.message));
notify({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "completed" });
instance.respond(request, { stopReason: "end_turn" });
return true;
},
});
const connection = await runAcpProvider({
id: "tool-update-acp",
label: "Tool Update ACP",
connector,
transformers: [failOnExecutorMessage],
}).connect({ versions: [1], capabilities: ["prompt.message"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send(promptInput("tool-update", "auto", "go"));
expect(await waitForEvent(events, isTerminalTurn)).toMatchObject({ state: "completed" });
} finally {
await connection.close();
}
});
it.each([
{
secondReply: "Second steer reached the agent",
expected: { state: "completed" },
},
{
secondReply: executorFailure.message,
expected: { state: "failed", error: executorFailure },
},
])(
"delivers a queued steer after a failed steer and settles on its reply: $expected.state",
async ({ secondReply, expected }) => {
const firstSteer = Promise.withResolvers<() => void>();
const { connector } = connectorHarness({
handleRequest(instance, request) {
if (request.method !== "session/prompt") return false;
const params = request.params as { prompt: Array<{ text?: string }> };
const text = params.prompt[0]?.text;
const notify = (update: unknown) =>
instance.notify("session/update", { sessionId: "connector-session", update });
if (text === "start") {
notify({
sessionUpdate: "tool_call",
toolCallId: "background",
title: "Long background job",
status: "in_progress",
});
instance.respond(request, {
stopReason: "end_turn",
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
});
} else if (text === "first steer") {
firstSteer.resolve(() => {
notify(textChunk(executorFailure.message));
instance.respond(request, { stopReason: "end_turn" });
});
} else {
notify({
sessionUpdate: "tool_call_update",
toolCallId: "background",
status: "completed",
});
notify(textChunk(secondReply));
instance.respond(request, { stopReason: "end_turn" });
}
return true;
},
});
const connection = await runAcpProvider({
id: "queued-steer",
label: "Queued Steer",
connector,
acpOptions: { deferTurnOnRunningTools: { settleDelayMs: 10, quietLimitMs: 100 } },
transformers: [failOnExecutorMessage],
}).connect({ versions: [1], capabilities: ["prompt.message", "prompt.steer"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send(promptInput("queued-turn", "auto", "start"));
await waitForEvent(events, (event) => event.type === "session.usage");
await connection.send(promptInput("steer-1", "steer", "first steer"));
const finishFirstSteer = await firstSteer.promise;
await connection.send(promptInput("steer-2", "steer", "second steer"));
await waitForEvent(
events,
(event) => event.type === "session.prompt_result" && event.clientMessageId === "steer-2",
);
finishFirstSteer();
expect(await waitForEvent(events, isTerminalTurn)).toMatchObject(expected);
expect(events.filter((event) => event.type === "session.notice")).toEqual([
{
type: "session.notice",
sessionId: "session-1",
notice: {
id: "acp:steer-error:steer-1",
severity: "error",
title: "Follow-up prompt failed",
description: executorFailure.message,
},
},
]);
expect(events).toContainEqual(
expect.objectContaining({
type: "timeline.item",
item: expect.objectContaining({ type: "assistant_message", text: secondReply }),
}),
);
} finally {
await connection.close();
}
},
);
});
+19
View File
@@ -6,6 +6,7 @@ import type {
ProviderCatalogRefreshMode,
ProviderCommand,
ProviderConfigState,
ProviderError,
ProviderMode,
ProviderNotice,
ProviderPersistence,
@@ -93,6 +94,16 @@ export interface AcpContext {
sessionId: string;
}
export interface AcpTurnEndContext extends AcpContext {
/** The ACP `stopReason` of the reply. */
stopReason: string;
/**
* Text of the assistant message that ended the reply. Absent when a tool call, tool call update,
* thought or plan came after the last message, or when the reply had no message.
*/
lastAssistantMessage?: string;
}
export interface AcpConfigAccess {
read(): Promise<Readonly<Record<string, JsonValue>>>;
set(id: string, value: JsonValue): Promise<void>;
@@ -172,6 +183,14 @@ export interface AcpTransformer {
previous?: AcpToolCallSnapshot;
},
): AcpToolCallSnapshot;
/**
* Inspects an agent reply that resolved without being canceled, before Paseo accepts it.
* Return `{ state: "failed", error }` to report it as a failure. It can run more than once
* in a turn, so keep it free of side effects.
*/
turnEnd?(
context: AcpTurnEndContext,
): { state: "failed"; error: ProviderError } | null | undefined;
}
function buildDefaultAcpCatalogCacheKey(options: ProviderCatalogOptions): string {
+87
View File
@@ -29,6 +29,7 @@ import {
TunnelExposureOpenResponseSchema,
TunnelExposureCloseRequestSchema,
TunnelExposureCloseResponseSchema,
WorkspaceScriptTunnelSchema,
} from "./tunnels.js";
export * from "./tunnels.js";
import {
@@ -239,6 +240,40 @@ const MutableBrowserToolsConfigSchema = z
enabled: z.boolean().default(false),
})
.passthrough();
export {
BUILTIN_TOOL_GROUPS,
DEFAULT_DAEMON_TOOL_GROUPS,
type BuiltInToolGroup,
} from "./tool-groups.js";
export const MutableDaemonToolGroupsSchema = z
.object({
orchestration: z.boolean().optional(),
schedules: z.boolean().optional(),
changeRequests: z.boolean().optional(),
browser: z.boolean().optional(),
})
.passthrough();
export const MutableDaemonToolsConfigSchema = z
.object({
enabled: z.boolean(),
groups: MutableDaemonToolGroupsSchema.optional(),
})
.passthrough();
export const MutableDaemonToolsConfigPatchSchema = z
.object({
enabled: z.boolean().optional(),
groups: MutableDaemonToolGroupsSchema.optional(),
})
.passthrough();
export type MutableDaemonToolGroups = z.infer<typeof MutableDaemonToolGroupsSchema>;
export type MutableDaemonToolsConfig = z.infer<typeof MutableDaemonToolsConfigSchema>;
export type MutableDaemonToolsConfigPatch = z.infer<typeof MutableDaemonToolsConfigPatchSchema>;
const MutableRelayConfigSchema = z
.object({
enabled: z.boolean(),
@@ -252,12 +287,15 @@ export const MutableDaemonConfigSchema = z
.object({
// COMPAT(relayConfig): added in v0.2.6, remove after 2027-01-31 when old daemons are unsupported.
relay: MutableRelayConfigSchema.optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients read mcp.injectIntoAgents.
mcp: z
.object({
enabled: z.boolean().optional(),
injectIntoAgents: z.boolean(),
})
.passthrough(),
// COMPAT(daemonToolsConfig): added in v0.18.2, optional while older daemons omit it.
tools: MutableDaemonToolsConfigSchema.optional(),
hostnames: z.union([z.literal(true), z.array(z.string())]).optional(),
cors: z
.object({
@@ -276,6 +314,7 @@ export const MutableDaemonConfigSchema = z
catalogRefreshTimeoutMs: z.number().int().positive().optional(),
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
usage: z.object({ enabled: z.boolean() }).optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients read browserTools.enabled.
browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }),
providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}),
metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }),
@@ -302,8 +341,12 @@ export const MutableDaemonConfigSchema = z
export const MutableDaemonConfigPatchSchema = z
.object({
relay: MutableRelayConfigSchema.partial().optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients patch mcp.injectIntoAgents.
mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(),
// COMPAT(daemonToolsConfig): added in v0.18.2, optional while older clients omit it.
tools: MutableDaemonToolsConfigPatchSchema.optional(),
usage: z.object({ enabled: z.boolean() }).optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients patch browserTools.enabled.
browserTools: MutableBrowserToolsConfigSchema.partial().optional(),
providers: z
.record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough())
@@ -3486,6 +3529,21 @@ export const WorkspaceScriptStopRequestSchema = z.object({
requestId: z.string(),
});
export const WorkspaceScriptTunnelOpenRequestSchema = z.object({
type: z.literal("workspace.script.tunnel.open.request"),
workspaceId: z.string(),
scriptName: z.string(),
providerId: z.string().min(1).max(256),
requestId: z.string(),
});
export const WorkspaceScriptTunnelCloseRequestSchema = z.object({
type: z.literal("workspace.script.tunnel.close.request"),
workspaceId: z.string(),
scriptName: z.string(),
requestId: z.string(),
});
export const SubscribeTerminalRequestSchema = z.object({
type: z.literal("subscribe_terminal_request"),
terminalId: z.string(),
@@ -3903,6 +3961,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceScriptListRequestSchema,
WorkspaceScriptStartRequestSchema,
WorkspaceScriptStopRequestSchema,
WorkspaceScriptTunnelOpenRequestSchema,
WorkspaceScriptTunnelCloseRequestSchema,
SubscribeTerminalRequestSchema,
UnsubscribeTerminalRequestSchema,
TerminalInputSchema,
@@ -4127,6 +4187,8 @@ export const ServerInfoStatusPayloadSchema = z
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
usageSetting: z.boolean().optional(),
usageSources: z.boolean().optional(),
// COMPAT(daemonToolsConfig): added in v0.18.2, remove gate after 2027-06-01.
daemonToolsConfig: z.boolean().optional(),
// COMPAT(providerInstallation): added in v0.17.0, remove gate after 2027-05-13.
providerInstallation: z.boolean().optional(),
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
@@ -4206,6 +4268,10 @@ export const ServerInfoStatusPayloadSchema = z
pluginNotifications: z.boolean().optional(),
// COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01.
tunnelProviders: z.boolean().optional(),
// COMPAT(workspaceScriptTunnels): added in v0.19.0, remove gate after 2027-06-01.
// Daemons with tunnelProviders but not this flag neither report a script's tunnel
// nor close it when the service stops.
workspaceScriptTunnels: z.boolean().optional(),
// COMPAT(usageReportUpdates): added in v0.18.2, remove gate after 2027-05-27.
// Older hosts reject the `status.usage_report_changed` subscription, so subscribe only here.
usageReportUpdates: z.boolean().optional(),
@@ -4574,9 +4640,12 @@ export const WorkspaceScriptPayloadSchema = z.object({
type: z.enum(["script", "service"]).optional().default("service"),
hostname: z.string(),
port: z.number().int().positive().nullable(),
// COMPAT(serviceProxyRemoved): added in v0.19.0, remove after 2027-06-01.
// Retained on the wire so older clients parse new daemon script payloads cleanly.
localProxyUrl: z.string().nullable().optional(),
publicProxyUrl: z.string().nullable().optional(),
proxyUrl: z.string().nullable().optional().default(null),
tunnel: WorkspaceScriptTunnelSchema.nullable().optional(),
lifecycle: WorkspaceScriptLifecycleSchema,
health: WorkspaceScriptHealthSchema.nullable(),
exitCode: z.number().nullable().optional().default(null),
@@ -5246,6 +5315,16 @@ export const WorkspaceScriptStopResponseMessageSchema = z.object({
payload: WorkspaceScriptOperationPayloadSchema,
});
export const WorkspaceScriptTunnelOpenResponseMessageSchema = z.object({
type: z.literal("workspace.script.tunnel.open.response"),
payload: WorkspaceScriptOperationPayloadSchema,
});
export const WorkspaceScriptTunnelCloseResponseMessageSchema = z.object({
type: z.literal("workspace.script.tunnel.close.response"),
payload: WorkspaceScriptOperationPayloadSchema,
});
// COMPAT(desktopEditorBridge): added in v0.1.88, remove after 2026-12-03 once old clients no longer parse daemon editor RPC responses.
export const LegacyListAvailableEditorsResponseMessageSchema = z.object({
type: z.literal("list_available_editors_response"),
@@ -8053,6 +8132,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceScriptListResponseMessageSchema,
WorkspaceScriptStartResponseMessageSchema,
WorkspaceScriptStopResponseMessageSchema,
WorkspaceScriptTunnelOpenResponseMessageSchema,
WorkspaceScriptTunnelCloseResponseMessageSchema,
LegacyListAvailableEditorsResponseMessageSchema,
LegacyOpenInEditorResponseMessageSchema,
ArchiveWorkspaceResponseMessageSchema,
@@ -8287,6 +8368,12 @@ export type StartWorkspaceScriptResponseMessage = z.infer<
export type WorkspaceScriptListRequest = z.infer<typeof WorkspaceScriptListRequestSchema>;
export type WorkspaceScriptStartRequest = z.infer<typeof WorkspaceScriptStartRequestSchema>;
export type WorkspaceScriptStopRequest = z.infer<typeof WorkspaceScriptStopRequestSchema>;
export type WorkspaceScriptTunnelOpenRequest = z.infer<
typeof WorkspaceScriptTunnelOpenRequestSchema
>;
export type WorkspaceScriptTunnelCloseRequest = z.infer<
typeof WorkspaceScriptTunnelCloseRequestSchema
>;
export type WorkspaceScriptListResponseMessage = z.infer<
typeof WorkspaceScriptListResponseMessageSchema
>;

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