mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af36a85a8f | ||
|
|
c3c86b9d18 | ||
|
|
5140065373 | ||
|
|
0f3ed9118b | ||
|
|
66b57ed3b3 | ||
|
|
b9bd2a2b05 | ||
|
|
748972b982 | ||
|
|
1f6b2493f0 | ||
|
|
2575621974 | ||
|
|
c51431fc98 | ||
|
|
7454db9b0d | ||
|
|
c00398cd10 | ||
|
|
6e1dbe31af | ||
|
|
0437922aff |
@@ -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 |
|
||||
|
||||
+8
-10
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 |
|
||||
@@ -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,
|
||||
}) => {
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
|
||||
@@ -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} />;
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -289,7 +289,8 @@ function useWorkspaceScreenArchiveController({
|
||||
|
||||
return {
|
||||
...controller,
|
||||
isArchiving: workspaceDescriptor?.archivingAt != null || isHidingWorkspace,
|
||||
isArchiving:
|
||||
workspaceDescriptor?.archivingAt != null || isHidingWorkspace || controller.isConfirming,
|
||||
canArchive: canArchiveWorkspace(workspaceDescriptor, archiveRisk),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -857,7 +857,6 @@ export const ar: TranslationResources = {
|
||||
scripts: {
|
||||
title: "البرامج النصية",
|
||||
actions: {
|
||||
chooseUrl: "اختيار الرابط",
|
||||
copyUrl: "نسخ الرابط",
|
||||
openService: "عرض الخدمة",
|
||||
restart: "إعادة التشغيل",
|
||||
@@ -873,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}}",
|
||||
|
||||
@@ -854,7 +854,6 @@ export const en = {
|
||||
scripts: {
|
||||
title: "Scripts",
|
||||
actions: {
|
||||
chooseUrl: "Choose URL",
|
||||
copyUrl: "Copy URL",
|
||||
openService: "View service",
|
||||
restart: "Restart",
|
||||
@@ -870,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}}",
|
||||
|
||||
@@ -865,7 +865,6 @@ export const es: TranslationResources = {
|
||||
scripts: {
|
||||
title: "Scripts",
|
||||
actions: {
|
||||
chooseUrl: "Elegir URL",
|
||||
copyUrl: "Copiar URL",
|
||||
openService: "Ver servicio",
|
||||
restart: "Reiniciar",
|
||||
@@ -881,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}}",
|
||||
|
||||
@@ -866,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",
|
||||
@@ -882,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}}",
|
||||
|
||||
@@ -861,7 +861,6 @@ export const ja: TranslationResources = {
|
||||
scripts: {
|
||||
title: "スクリプト",
|
||||
actions: {
|
||||
chooseUrl: "URLを選択",
|
||||
copyUrl: "URLをコピー",
|
||||
openService: "サービスを表示",
|
||||
restart: "再起動",
|
||||
@@ -877,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}}",
|
||||
|
||||
@@ -857,7 +857,6 @@ export const ko: TranslationResources = {
|
||||
scripts: {
|
||||
title: "스크립트",
|
||||
actions: {
|
||||
chooseUrl: "URL를 선택하세요",
|
||||
copyUrl: "URL 복사",
|
||||
openService: "서비스 보기",
|
||||
restart: "다시 시작",
|
||||
@@ -873,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}}",
|
||||
|
||||
@@ -861,7 +861,6 @@ export const ptBR: TranslationResources = {
|
||||
scripts: {
|
||||
title: "Scripts",
|
||||
actions: {
|
||||
chooseUrl: "Escolher URL",
|
||||
copyUrl: "Copiar URL",
|
||||
openService: "Ver serviço",
|
||||
restart: "Reiniciar",
|
||||
@@ -877,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}}",
|
||||
|
||||
@@ -866,7 +866,6 @@ export const ru: TranslationResources = {
|
||||
scripts: {
|
||||
title: "Скрипты",
|
||||
actions: {
|
||||
chooseUrl: "Выбрать URL",
|
||||
copyUrl: "Скопировать URL",
|
||||
openService: "Открыть сервис",
|
||||
restart: "Перезапустить",
|
||||
@@ -882,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}}",
|
||||
|
||||
@@ -853,7 +853,6 @@ export const zhCN: TranslationResources = {
|
||||
scripts: {
|
||||
title: "Scripts",
|
||||
actions: {
|
||||
chooseUrl: "选择 URL",
|
||||
copyUrl: "复制 URL",
|
||||
openService: "查看服务",
|
||||
restart: "重启",
|
||||
@@ -869,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}}",
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
+25
-8
@@ -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({
|
||||
|
||||
@@ -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("-");
|
||||
});
|
||||
});
|
||||
@@ -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 },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
TunnelExposureOpenResponseSchema,
|
||||
TunnelExposureCloseRequestSchema,
|
||||
TunnelExposureCloseResponseSchema,
|
||||
WorkspaceScriptTunnelSchema,
|
||||
} from "./tunnels.js";
|
||||
export * from "./tunnels.js";
|
||||
import {
|
||||
@@ -3528,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(),
|
||||
@@ -3945,6 +3961,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WorkspaceScriptListRequestSchema,
|
||||
WorkspaceScriptStartRequestSchema,
|
||||
WorkspaceScriptStopRequestSchema,
|
||||
WorkspaceScriptTunnelOpenRequestSchema,
|
||||
WorkspaceScriptTunnelCloseRequestSchema,
|
||||
SubscribeTerminalRequestSchema,
|
||||
UnsubscribeTerminalRequestSchema,
|
||||
TerminalInputSchema,
|
||||
@@ -4250,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(),
|
||||
@@ -4618,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),
|
||||
@@ -5290,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"),
|
||||
@@ -8097,6 +8132,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WorkspaceScriptListResponseMessageSchema,
|
||||
WorkspaceScriptStartResponseMessageSchema,
|
||||
WorkspaceScriptStopResponseMessageSchema,
|
||||
WorkspaceScriptTunnelOpenResponseMessageSchema,
|
||||
WorkspaceScriptTunnelCloseResponseMessageSchema,
|
||||
LegacyListAvailableEditorsResponseMessageSchema,
|
||||
LegacyOpenInEditorResponseMessageSchema,
|
||||
ArchiveWorkspaceResponseMessageSchema,
|
||||
@@ -8331,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
|
||||
>;
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ServerInfoStatusPayloadSchema,
|
||||
SessionInboundMessageSchema,
|
||||
SessionOutboundMessageSchema,
|
||||
WorkspaceScriptPayloadSchema,
|
||||
} from "./messages.js";
|
||||
|
||||
describe("tunnel protocol schemas", () => {
|
||||
@@ -105,4 +106,57 @@ describe("tunnel protocol schemas", () => {
|
||||
ServerInfoStatusPayloadSchema.parse({ ...base, features: {} }).features?.tunnelProviders,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses WorkspaceScriptPayload with optional tunnel state and remains wire-compatible", () => {
|
||||
const legacy = WorkspaceScriptPayloadSchema.parse({
|
||||
scriptName: "web",
|
||||
hostname: "web",
|
||||
port: 3000,
|
||||
lifecycle: "running",
|
||||
health: "healthy",
|
||||
});
|
||||
expect(legacy.tunnel).toBeUndefined();
|
||||
|
||||
const withTunnel = WorkspaceScriptPayloadSchema.parse({
|
||||
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(withTunnel.tunnel).toEqual({
|
||||
exposureId: "service:wks_1:web",
|
||||
providerId: "cloudflared",
|
||||
state: "ready",
|
||||
url: "https://demo.trycloudflare.com",
|
||||
stability: "ephemeral",
|
||||
detail: null,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const withNullTunnel = WorkspaceScriptPayloadSchema.parse({
|
||||
scriptName: "web",
|
||||
hostname: "web",
|
||||
port: 3000,
|
||||
tunnel: null,
|
||||
lifecycle: "running",
|
||||
health: null,
|
||||
});
|
||||
expect(withNullTunnel.tunnel).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,12 +52,23 @@ export const TunnelExposureSchema = z.object({
|
||||
updatedAt: z.string(),
|
||||
});
|
||||
|
||||
export const WorkspaceScriptTunnelSchema = z.object({
|
||||
exposureId: z.string(),
|
||||
providerId: z.string(),
|
||||
state: TunnelExposureStateSchema,
|
||||
url: z.string().nullable(),
|
||||
stability: TunnelStabilitySchema.nullable(),
|
||||
detail: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
});
|
||||
|
||||
export type TunnelStabilityWire = z.infer<typeof TunnelStabilitySchema>;
|
||||
export type TunnelExposureState = z.infer<typeof TunnelExposureStateSchema>;
|
||||
export type TunnelProviderAvailability = z.infer<typeof TunnelProviderAvailabilitySchema>;
|
||||
export type TunnelProviderInfo = z.infer<typeof TunnelProviderInfoSchema>;
|
||||
export type TunnelExposureTarget = z.infer<typeof TunnelExposureTargetSchema>;
|
||||
export type TunnelExposure = z.infer<typeof TunnelExposureSchema>;
|
||||
export type WorkspaceScriptTunnel = z.infer<typeof WorkspaceScriptTunnelSchema>;
|
||||
|
||||
export const TunnelProvidersListRequestSchema = z.object({
|
||||
type: z.literal("tunnel.providers.list.request"),
|
||||
|
||||
@@ -16,26 +16,28 @@ import type {
|
||||
AgentSession,
|
||||
AgentSessionConfig,
|
||||
} from "./agent-sdk-types.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestAgentClient, createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createDaemonTestContext } from "../test-utils/daemon-test-context.js";
|
||||
|
||||
test("loads archived records for history and active records with the interactive default", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "agent-loading-purpose-"));
|
||||
const logger = createTestLogger();
|
||||
const storage = new AgentStorage(path.join(root, "agents"), logger);
|
||||
const baseClient = createTestAgentClients().codex;
|
||||
if (!baseClient) {
|
||||
throw new Error("expected Codex test client");
|
||||
}
|
||||
const baseClient = createTestAgentClient("pi");
|
||||
|
||||
const resumeOptions: Array<AgentResumeSessionOptions | undefined> = [];
|
||||
const launchContexts: AgentLaunchContext[] = [];
|
||||
const resolvedWorkspaceIds: string[] = [];
|
||||
const client: AgentClient = {
|
||||
provider: baseClient.provider,
|
||||
capabilities: baseClient.capabilities,
|
||||
createSession: async (
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> => await baseClient.createSession(config, launchContext),
|
||||
): Promise<AgentSession> => {
|
||||
launchContexts.push(launchContext ?? {});
|
||||
return await baseClient.createSession(config, launchContext);
|
||||
},
|
||||
resumeSession: async (
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
@@ -43,14 +45,19 @@ test("loads archived records for history and active records with the interactive
|
||||
options?: AgentResumeSessionOptions,
|
||||
): Promise<AgentSession> => {
|
||||
resumeOptions.push(options);
|
||||
launchContexts.push(launchContext ?? {});
|
||||
return await baseClient.resumeSession(handle, overrides, launchContext);
|
||||
},
|
||||
fetchCatalog: async (options) => await baseClient.fetchCatalog(options),
|
||||
isAvailable: async () => await baseClient.isAvailable(),
|
||||
};
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
clients: { pi: client },
|
||||
registry: storage,
|
||||
resolveWorkspaceProjectResourceApproval: async (workspaceId) => {
|
||||
resolvedWorkspaceIds.push(workspaceId);
|
||||
return workspaceId === "workspace-active";
|
||||
},
|
||||
logger,
|
||||
});
|
||||
|
||||
@@ -58,12 +65,12 @@ test("loads archived records for history and active records with the interactive
|
||||
const activeId = "00000000-0000-4000-8000-000000000302";
|
||||
|
||||
try {
|
||||
const archived = await manager.createAgent({ provider: "codex", cwd: root }, archivedId, {
|
||||
const archived = await manager.createAgent({ provider: "pi", cwd: root }, archivedId, {
|
||||
workspaceId: "workspace-archived",
|
||||
});
|
||||
await manager.archiveAgent(archived.id);
|
||||
|
||||
const active = await manager.createAgent({ provider: "codex", cwd: root }, activeId, {
|
||||
const active = await manager.createAgent({ provider: "pi", cwd: root }, activeId, {
|
||||
workspaceId: "workspace-active",
|
||||
});
|
||||
await manager.closeAgent(active.id);
|
||||
@@ -72,6 +79,9 @@ test("loads archived records for history and active records with the interactive
|
||||
await ensureAgentLoaded(active.id, { agentManager: manager, agentStorage: storage, logger });
|
||||
|
||||
expect(resumeOptions).toEqual([{ purpose: "history" }, { purpose: "interactive" }]);
|
||||
expect(resolvedWorkspaceIds).toEqual(["workspace-active"]);
|
||||
expect(launchContexts[2]?.approveProjectResources).toBeUndefined();
|
||||
expect(launchContexts[3]?.approveProjectResources).toBe(true);
|
||||
} finally {
|
||||
await Promise.all([
|
||||
manager.closeAgent(archivedId).catch(() => undefined),
|
||||
|
||||
@@ -140,7 +140,11 @@ export async function ensureAgentLoaded(
|
||||
handle,
|
||||
buildConfigOverrides(record),
|
||||
agentId,
|
||||
{ ...extractTimestamps(record), attention: extractAttention(record) },
|
||||
{
|
||||
...extractTimestamps(record),
|
||||
attention: extractAttention(record),
|
||||
approveProjectResources: !record.archivedAt,
|
||||
},
|
||||
deps.purpose ? { purpose: deps.purpose } : undefined,
|
||||
);
|
||||
deps.logger.info({ agentId, provider: record.provider }, "Agent resumed from persistence");
|
||||
|
||||
@@ -67,7 +67,7 @@ import type {
|
||||
ResolveAgentDefaultModeInput,
|
||||
} from "./agent-sdk-types.js";
|
||||
import type { PaseoToolCatalog } from "./tools/types.js";
|
||||
import type { ProviderDefinition } from "./provider-registry.js";
|
||||
import { buildProviderRegistry, type ProviderDefinition } from "./provider-registry.js";
|
||||
import { mergeProviderOptions } from "./provider-options.js";
|
||||
|
||||
import { OpenCodeV2AgentClient } from "./providers/opencode/v2/agent.js";
|
||||
@@ -4280,6 +4280,186 @@ test("createAgent and resume give the agent its workspace id", async () => {
|
||||
expect(client.resumeLaunchContext?.env).toEqual(expectedEnv);
|
||||
});
|
||||
|
||||
test("gates project-resource approval by trusted workspaceId across session boundaries", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-project-trust-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
|
||||
class ProjectTrustSession extends TestAgentSession {
|
||||
override describePersistence(): AgentPersistenceHandle {
|
||||
return { provider: "pi", sessionId: this.id };
|
||||
}
|
||||
}
|
||||
|
||||
class ProjectTrustCaptureClient extends TestAgentClient {
|
||||
constructor() {
|
||||
super("pi");
|
||||
}
|
||||
|
||||
readonly launchContexts: AgentLaunchContext[] = [];
|
||||
|
||||
override async createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> {
|
||||
this.launchContexts.push(launchContext ?? {});
|
||||
return new ProjectTrustSession(config);
|
||||
}
|
||||
|
||||
override async resumeSession(
|
||||
handle: AgentPersistenceHandle,
|
||||
config?: Partial<AgentSessionConfig>,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> {
|
||||
this.launchContexts.push(launchContext ?? {});
|
||||
return new ProjectTrustSession({
|
||||
provider: this.provider,
|
||||
cwd: config?.cwd ?? (handle.metadata?.cwd as string) ?? process.cwd(),
|
||||
});
|
||||
}
|
||||
|
||||
override async importSession(
|
||||
input: ImportProviderSessionInput,
|
||||
context: ImportProviderSessionContext,
|
||||
) {
|
||||
this.launchContexts.push(context.launchContext ?? {});
|
||||
return {
|
||||
session: new ProjectTrustSession(context.config),
|
||||
config: context.storedConfig,
|
||||
persistence: {
|
||||
provider: this.provider,
|
||||
sessionId: input.providerHandleId,
|
||||
nativeHandle: input.providerHandleId,
|
||||
},
|
||||
timeline: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const client = new ProjectTrustCaptureClient();
|
||||
const manager = new AgentManager({
|
||||
clients: { pi: client },
|
||||
registry: storage,
|
||||
resolveWorkspaceProjectResourceApproval: async (workspaceId) => workspaceId === "trusted",
|
||||
logger,
|
||||
});
|
||||
|
||||
const trusted = await manager.createAgent({ provider: "pi", cwd: workdir }, undefined, {
|
||||
workspaceId: "trusted",
|
||||
approveProjectResources: true,
|
||||
});
|
||||
const untrusted = await manager.createAgent({ provider: "pi", cwd: workdir }, undefined, {
|
||||
workspaceId: "untrusted",
|
||||
approveProjectResources: true,
|
||||
});
|
||||
|
||||
expect(client.launchContexts[0]?.approveProjectResources).toBe(true);
|
||||
expect(client.launchContexts[1]?.approveProjectResources).toBeUndefined();
|
||||
expect(trusted.config).not.toHaveProperty("approveProjectResources");
|
||||
|
||||
const resumed = await manager.resumeAgentFromPersistence(
|
||||
trusted.persistence!,
|
||||
undefined,
|
||||
undefined,
|
||||
{ workspaceId: "trusted", approveProjectResources: true },
|
||||
);
|
||||
expect(client.launchContexts[2]?.approveProjectResources).toBe(true);
|
||||
|
||||
const reloaded = await manager.reloadAgentSession(untrusted.id);
|
||||
expect(client.launchContexts[3]?.approveProjectResources).toBeUndefined();
|
||||
|
||||
const imported = await manager.importProviderSession({
|
||||
provider: "pi",
|
||||
providerHandleId: "imported-untrusted",
|
||||
cwd: workdir,
|
||||
workspaceId: "untrusted",
|
||||
});
|
||||
expect(client.launchContexts[4]?.approveProjectResources).toBeUndefined();
|
||||
|
||||
const firstSessionId = "00000000-0000-4000-8000-000000000495";
|
||||
const record = (await storage.get(trusted.id))!;
|
||||
await storage.upsert({ ...record, id: firstSessionId, persistence: null });
|
||||
const firstSession = await manager.createAgentFromRecord(firstSessionId);
|
||||
expect(client.launchContexts[5]?.approveProjectResources).toBe(true);
|
||||
await firstSession.session.close();
|
||||
|
||||
await trusted.session.close();
|
||||
await untrusted.session.close();
|
||||
await resumed.session.close();
|
||||
await reloaded.session.close();
|
||||
await imported.session.close();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("starts a configured Pi provider with project resources in a trusted workspace", async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), "derived-pi-project-trust-"));
|
||||
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
|
||||
const cli = join(cwd, "pi-cli.cjs");
|
||||
writeFileSync(
|
||||
cli,
|
||||
`const { createInterface } = require("node:readline");
|
||||
const state = {
|
||||
sessionId: "test-session",
|
||||
thinkingLevel: "off",
|
||||
isStreaming: false,
|
||||
isCompacting: false,
|
||||
messageCount: 0,
|
||||
pendingMessageCount: 0,
|
||||
};
|
||||
const commands = process.argv.includes("--approve")
|
||||
? [{ name: "skill:project", source: "skill" }]
|
||||
: [];
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, type } = JSON.parse(line);
|
||||
const data = type === "get_state" ? state : { commands };
|
||||
console.log(JSON.stringify({ id, type: "response", command: type, success: true, data }));
|
||||
});`,
|
||||
);
|
||||
const providers = buildProviderRegistry(logger, {
|
||||
providerOverrides: {
|
||||
"project-pi": { extends: "pi", label: "Project Pi", command: [process.execPath, cli] },
|
||||
},
|
||||
});
|
||||
const manager = new AgentManager({
|
||||
clients: { "project-pi": providers["project-pi"]!.createClient(logger) },
|
||||
resolveWorkspaceProjectResourceApproval: async (id) => id === "trusted",
|
||||
logger,
|
||||
});
|
||||
const agent = await manager.createAgent({ provider: "project-pi", cwd }, undefined, {
|
||||
workspaceId: "trusted",
|
||||
approveProjectResources: true,
|
||||
});
|
||||
try {
|
||||
await expect(agent.session.listCommands!()).resolves.toContainEqual(
|
||||
expect.objectContaining({ name: "skill:project" }),
|
||||
);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
}
|
||||
});
|
||||
|
||||
test("propagates workspace-trust resolution failures instead of launching unapproved", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-project-trust-error-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
|
||||
const manager = new AgentManager({
|
||||
clients: { pi: new TestAgentClient("pi") },
|
||||
registry: storage,
|
||||
resolveWorkspaceProjectResourceApproval: async () => {
|
||||
throw new Error("workspace registry unavailable");
|
||||
},
|
||||
logger,
|
||||
});
|
||||
|
||||
await expect(
|
||||
manager.createAgent({ provider: "pi", cwd: workdir }, undefined, {
|
||||
workspaceId: "some-workspace",
|
||||
approveProjectResources: true,
|
||||
}),
|
||||
).rejects.toThrow("workspace registry unavailable");
|
||||
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("createAgent passes persistSession to provider create options", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
|
||||
@@ -312,6 +312,8 @@ interface ResumeAgentOptions {
|
||||
owner?: AgentOwner;
|
||||
background?: boolean;
|
||||
attention?: AttentionState;
|
||||
internal?: boolean;
|
||||
approveProjectResources?: boolean;
|
||||
}
|
||||
|
||||
interface PluginToolCall {
|
||||
@@ -516,6 +518,8 @@ type ProviderEnabledMap = Partial<Record<AgentProvider, ProviderEnabledFlag>>;
|
||||
type ProviderClientMap = Partial<Record<AgentProvider, AgentClient>>;
|
||||
|
||||
export interface CreateAgentOptions {
|
||||
/** Runtime-only intent from an interactive user-session boundary. */
|
||||
approveProjectResources?: boolean;
|
||||
labels?: Record<string, string>;
|
||||
metadata?: AgentMetadata;
|
||||
initialPrompt?: string;
|
||||
@@ -547,6 +551,8 @@ export interface AgentManagerOptions {
|
||||
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
|
||||
hasActiveVoiceTools?: (agentId: string) => boolean;
|
||||
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
|
||||
/** Resolve project-resource trust by opaque workspace ID. Missing/error is untrusted. */
|
||||
resolveWorkspaceProjectResourceApproval?: (workspaceId: string, cwd: string) => Promise<boolean>;
|
||||
appendSystemPrompt?: string;
|
||||
agentStreamCoalesceWindowMs?: number;
|
||||
rescueTimeouts?: AgentManagerRescueTimeouts;
|
||||
@@ -1095,6 +1101,7 @@ function toResumeOptionsFromStored(storedRecord: StoredAgentRecord) {
|
||||
owner: storedRecord.owner,
|
||||
background: storedRecord.background,
|
||||
attention: extractAttention(storedRecord),
|
||||
approveProjectResources: !storedRecord.archivedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1251,6 +1258,9 @@ export class AgentManager {
|
||||
private logger: Logger;
|
||||
private readonly rescueTimeouts: Required<AgentManagerRescueTimeouts>;
|
||||
private readonly beforeSteerUnavailableFallback?: AgentManagerOptions["beforeSteerUnavailableFallback"];
|
||||
private readonly resolveWorkspaceProjectResourceApproval:
|
||||
| AgentManagerOptions["resolveWorkspaceProjectResourceApproval"]
|
||||
| undefined;
|
||||
private acceptingAgentRegistrations = true;
|
||||
|
||||
constructor(options: AgentManagerOptions) {
|
||||
@@ -1266,6 +1276,7 @@ export class AgentManager {
|
||||
this.mcpAuthToken = options?.mcpAuthToken ?? null;
|
||||
this.configurePaseoTools(options);
|
||||
this.resolvePaseoToolPolicy = options.resolvePaseoToolPolicy ?? (() => undefined);
|
||||
this.resolveWorkspaceProjectResourceApproval = options.resolveWorkspaceProjectResourceApproval;
|
||||
this.appendSystemPrompt = options.appendSystemPrompt ?? "";
|
||||
this.logger = options.logger.child({ module: "agent", component: "agent-manager" });
|
||||
this.rescueTimeouts = {
|
||||
@@ -2040,6 +2051,7 @@ export class AgentManager {
|
||||
config,
|
||||
resolvedAgentId,
|
||||
{
|
||||
approveProjectResources: !record.archivedAt,
|
||||
labels: record.labels,
|
||||
metadata: record.metadata,
|
||||
workspaceId: record.workspaceId,
|
||||
@@ -2119,6 +2131,8 @@ export class AgentManager {
|
||||
background: options.background,
|
||||
labels: options.labels ?? {},
|
||||
metadata: options.metadata ?? {},
|
||||
approveProjectResources: options.approveProjectResources === true,
|
||||
internal: storedConfig.internal === true,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
@@ -2158,17 +2172,7 @@ export class AgentManager {
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
agentId?: string,
|
||||
options?: {
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
lastUserMessageAt?: Date | null;
|
||||
labels?: Record<string, string>;
|
||||
metadata?: AgentMetadata;
|
||||
workspaceId?: string;
|
||||
owner?: AgentOwner;
|
||||
background?: boolean;
|
||||
attention?: AttentionState;
|
||||
},
|
||||
options?: ResumeAgentOptions,
|
||||
resumeOptions?: AgentResumeSessionOptions,
|
||||
): Promise<ManagedAgent> {
|
||||
const resolvedAgentId = validateAgentId(
|
||||
@@ -2204,17 +2208,7 @@ export class AgentManager {
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
agentId?: string,
|
||||
options?: {
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
lastUserMessageAt?: Date | null;
|
||||
labels?: Record<string, string>;
|
||||
metadata?: AgentMetadata;
|
||||
workspaceId?: string;
|
||||
owner?: AgentOwner;
|
||||
background?: boolean;
|
||||
attention?: AttentionState;
|
||||
},
|
||||
options?: ResumeAgentOptions,
|
||||
resumeOptions?: AgentResumeSessionOptions,
|
||||
): Promise<ManagedAgent> {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
@@ -2264,6 +2258,8 @@ export class AgentManager {
|
||||
title: record?.title ?? mergedConfig.title ?? null,
|
||||
background: options?.background,
|
||||
...agentEntityData(record ?? options),
|
||||
approveProjectResources: options?.approveProjectResources === true,
|
||||
internal: (record ?? options)?.internal,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
@@ -2352,6 +2348,7 @@ export class AgentManager {
|
||||
purpose: "interactive",
|
||||
workspaceId: input.workspaceId,
|
||||
labels: input.labels ?? {},
|
||||
approveProjectResources: true,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
@@ -2638,6 +2635,7 @@ export class AgentManager {
|
||||
toResumeConfigFromStored(storedRecord),
|
||||
agentId,
|
||||
{
|
||||
approveProjectResources: !storedRecord.archivedAt,
|
||||
labels: storedRecord.labels,
|
||||
metadata: storedRecord.metadata,
|
||||
workspaceId: storedRecord.workspaceId,
|
||||
@@ -2834,6 +2832,8 @@ export class AgentManager {
|
||||
background: source.background,
|
||||
labels: source.labels,
|
||||
metadata: source.metadata,
|
||||
approveProjectResources: true,
|
||||
internal: source.internal,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
@@ -3050,6 +3050,8 @@ export class AgentManager {
|
||||
background: existing.background,
|
||||
labels: existing.labels,
|
||||
metadata: existing.metadata,
|
||||
approveProjectResources: !existing.internal,
|
||||
internal: existing.internal === true,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveReloadLaunchConfig(
|
||||
@@ -8068,6 +8070,8 @@ export class AgentManager {
|
||||
background?: boolean;
|
||||
labels?: Record<string, string>;
|
||||
metadata?: AgentMetadata;
|
||||
approveProjectResources?: boolean;
|
||||
internal?: boolean;
|
||||
},
|
||||
): Promise<AgentLaunchContext> {
|
||||
let appendSystemPrompt: string[] | undefined;
|
||||
@@ -8112,9 +8116,31 @@ export class AgentManager {
|
||||
},
|
||||
};
|
||||
await this.attachLaunchPaseoTools(context, agentId, client, paseoToolPolicy);
|
||||
await this.attachProjectResourceApproval(context, cwd, opening);
|
||||
return context;
|
||||
}
|
||||
|
||||
private async attachProjectResourceApproval(
|
||||
context: AgentLaunchContext,
|
||||
cwd: string,
|
||||
opening?: {
|
||||
purpose: PluginSessionOpenRequest["purpose"];
|
||||
workspaceId?: string | null;
|
||||
approveProjectResources?: boolean;
|
||||
internal?: boolean;
|
||||
},
|
||||
): Promise<void> {
|
||||
if (
|
||||
opening?.purpose === "interactive" &&
|
||||
opening.approveProjectResources === true &&
|
||||
opening.internal !== true &&
|
||||
opening.workspaceId &&
|
||||
(await this.resolveWorkspaceProjectResourceApproval?.(opening.workspaceId, cwd))
|
||||
) {
|
||||
context.approveProjectResources = true;
|
||||
}
|
||||
}
|
||||
|
||||
private async attachLaunchPaseoTools(
|
||||
context: AgentLaunchContext,
|
||||
agentId: string,
|
||||
|
||||
@@ -768,6 +768,11 @@ export interface AgentLaunchContext {
|
||||
env?: Record<string, string>;
|
||||
/** Spawn the harness as `[...wrap, command, ...args]`. Selected by a plugin hook; never persisted. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
/**
|
||||
* Runtime-only permission for project-controlled Pi resources. This must be
|
||||
* derived from the owning workspace, never persisted in AgentSessionConfig.
|
||||
*/
|
||||
approveProjectResources?: boolean;
|
||||
/**
|
||||
* Runtime-only internal Paseo tools. This must never be persisted into
|
||||
* AgentSessionConfig; providers may adapt it to their native tool surface.
|
||||
|
||||
@@ -270,6 +270,7 @@ async function resolveSessionCreateAgent(
|
||||
return {
|
||||
config: sessionConfig,
|
||||
createOptions: {
|
||||
approveProjectResources: true,
|
||||
labels: input.labels,
|
||||
metadata: input.metadata,
|
||||
initialPrompt: trimmedPrompt,
|
||||
|
||||
@@ -883,7 +883,6 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
emit: () => {},
|
||||
sessionLogger: createTestLogger(),
|
||||
terminalManager: null,
|
||||
serviceProxy: null,
|
||||
scriptRuntimeStore: null,
|
||||
getDaemonTcpPort: null,
|
||||
getDaemonTcpHost: null,
|
||||
|
||||
@@ -12,8 +12,8 @@ afterEach(() => {
|
||||
describe("agent provider runtime", () => {
|
||||
test("owns bridge injection, catalog forwarding, and idempotent shutdown", async () => {
|
||||
vi.spyOn(OpenCodeBridge.prototype, "start").mockResolvedValue();
|
||||
const setManifestCatalog = vi
|
||||
.spyOn(OpenCodeBridge.prototype, "setManifestCatalog")
|
||||
const setManifestCatalogFactory = vi
|
||||
.spyOn(OpenCodeBridge.prototype, "setManifestCatalogFactory")
|
||||
.mockImplementation(() => undefined);
|
||||
const close = vi.spyOn(OpenCodeBridge.prototype, "close").mockResolvedValue();
|
||||
const runtime = await createAgentProviderRuntime({
|
||||
@@ -21,17 +21,17 @@ describe("agent provider runtime", () => {
|
||||
logger: createTestLogger(),
|
||||
snapshotManager: {},
|
||||
});
|
||||
const catalog = emptyCatalog();
|
||||
const factory = () => emptyCatalog();
|
||||
|
||||
expect(
|
||||
runtime.snapshotManager.getAgentManagerProviderState().clients.opencode?.capabilities
|
||||
.supportsNativePaseoTools,
|
||||
).toBe(true);
|
||||
runtime.setPaseoToolCatalog(catalog);
|
||||
runtime.setPaseoToolCatalogFactory(factory);
|
||||
await Promise.all([runtime.shutdown(), runtime.shutdown()]);
|
||||
|
||||
expect(setManifestCatalog).toHaveBeenCalledOnce();
|
||||
expect(setManifestCatalog).toHaveBeenCalledWith(catalog);
|
||||
expect(setManifestCatalogFactory).toHaveBeenCalledOnce();
|
||||
expect(setManifestCatalogFactory).toHaveBeenCalledWith(factory);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { PaseoToolCatalog } from "./tools/types.js";
|
||||
|
||||
export interface AgentProviderRuntime {
|
||||
snapshotManager: ProviderSnapshotManager;
|
||||
setPaseoToolCatalog(catalog: Pick<PaseoToolCatalog, "tools"> | null): void;
|
||||
setPaseoToolCatalogFactory(factory: (() => Pick<PaseoToolCatalog, "tools">) | null): void;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ export async function createAgentProviderRuntime(
|
||||
let shutdownPromise: Promise<void> | null = null;
|
||||
return {
|
||||
snapshotManager,
|
||||
setPaseoToolCatalog: (catalog) => bridge.setManifestCatalog(catalog),
|
||||
setPaseoToolCatalogFactory: (factory) => bridge.setManifestCatalogFactory(factory),
|
||||
shutdown: () => {
|
||||
shutdownPromise ??= shutdownProviderRuntime(snapshotManager, bridge);
|
||||
return shutdownPromise;
|
||||
|
||||
@@ -67,7 +67,7 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
break;
|
||||
case "session/set_config_option":
|
||||
appendFileSync(process.argv[3], JSON.stringify(request) + "\n");
|
||||
configOptions = configOptions.map(option => option.id === request.params.configId
|
||||
configOptions = scenario.modeWriteConfigOptions ?? configOptions.map(option => option.id === request.params.configId
|
||||
? {...option, currentValue: request.params.value} : option);
|
||||
reply({configOptions});
|
||||
break;
|
||||
@@ -101,6 +101,7 @@ async function fixture(
|
||||
updates?: SessionUpdate[];
|
||||
rejectedMode?: string;
|
||||
startupMode?: string;
|
||||
modeWriteConfigOptions?: SessionConfigOption[];
|
||||
copilot?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
@@ -120,6 +121,7 @@ async function fixture(
|
||||
{ sessionUpdate: "config_option_update", configOptions: editOptions() },
|
||||
],
|
||||
rejectedMode: options.rejectedMode,
|
||||
modeWriteConfigOptions: options.modeWriteConfigOptions,
|
||||
}),
|
||||
);
|
||||
const command: [string, ...string[]] = [process.execPath, script, scenario, calls];
|
||||
@@ -204,6 +206,32 @@ describe("ACP mode and config-value namespaces over stdio", () => {
|
||||
expect(await peer.calls()).toEqual([modeCall("dont_ask")]);
|
||||
});
|
||||
|
||||
test("publishes a thinking level changed by the live mode response", async () => {
|
||||
const effort = (currentValue: string): SessionConfigOption => ({
|
||||
type: "select",
|
||||
id: "effort",
|
||||
category: "thought_level",
|
||||
name: "Effort",
|
||||
currentValue,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
});
|
||||
const peer = await fixture({
|
||||
state: { configOptions: [...editOptions(), effort("low")] },
|
||||
updates: [],
|
||||
modeWriteConfigOptions: [...editOptions("session"), effort("high")],
|
||||
});
|
||||
const levels: Array<string | null> = [];
|
||||
peer.session.subscribe((event) => {
|
||||
if (event.type === "thinking_option_changed") levels.push(event.thinkingOptionId);
|
||||
});
|
||||
await peer.session.setMode("session");
|
||||
expect((await peer.session.getRuntimeInfo()).thinkingOptionId).toBe("high");
|
||||
expect(levels).toEqual(["high"]);
|
||||
});
|
||||
|
||||
test("selects a config-only mode through its owning config option", async () => {
|
||||
const peer = await fixture({ state: { configOptions: editOptions() } });
|
||||
await peer.session.setMode("session");
|
||||
|
||||
@@ -2516,6 +2516,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
this.currentMode = providerResult.currentModeId ?? modeId;
|
||||
if (providerResult.configOptions) {
|
||||
this.configOptions = this.transformConfigOptions(providerResult.configOptions);
|
||||
this.syncThinkingAfterModeChange();
|
||||
}
|
||||
this.availableModes = this.modesFromConfig().modes;
|
||||
this.pushEvent({
|
||||
@@ -2597,6 +2598,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
requestedValue: modeId,
|
||||
label: "mode",
|
||||
});
|
||||
this.syncThinkingAfterModeChange();
|
||||
this.reportFeatureChanges(before);
|
||||
this.availableModes = this.modesFromConfig().modes;
|
||||
this.pushEvent({
|
||||
@@ -2607,6 +2609,17 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
});
|
||||
}
|
||||
|
||||
private syncThinkingAfterModeChange(): void {
|
||||
const level = deriveCurrentConfigValue(this.configOptions, "thought_level");
|
||||
if (level === null || level === this.thinkingOptionId) return;
|
||||
this.thinkingOptionId = level;
|
||||
this.pushEvent({
|
||||
type: "thinking_option_changed",
|
||||
provider: this.provider,
|
||||
thinkingOptionId: level,
|
||||
});
|
||||
}
|
||||
|
||||
private createProviderModeWriterContext(
|
||||
requestedModeId: string,
|
||||
selection: ACPModeSelection,
|
||||
@@ -3660,8 +3673,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
|
||||
private async applyConfiguredThinkingOption(): Promise<void> {
|
||||
if (this.initialHandle) {
|
||||
// Restoring the saved mode or model can move the level, and those writes do not record it.
|
||||
// Live switches keep their own behavior (#10336).
|
||||
// Restoring the saved model or mode can also change the current thinking level.
|
||||
this.thinkingOptionId =
|
||||
deriveCurrentConfigValue(this.configOptions, "thought_level") ?? this.thinkingOptionId;
|
||||
}
|
||||
|
||||
@@ -213,49 +213,6 @@ function createFakeCodexAppServerProcess(spawn: () => ChildProcessWithoutNullStr
|
||||
};
|
||||
}
|
||||
|
||||
test.each(["create", "resume"] as const)(
|
||||
"keeps Paseo caller identity in the Codex shell policy on %s",
|
||||
async (operation) => {
|
||||
const appServer = createFakeCodexAppServer();
|
||||
const processPort = createFakeCodexAppServerProcess(() => appServer.child);
|
||||
let spawnArgs: string[] | undefined;
|
||||
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
|
||||
appServerProcess: {
|
||||
...processPort,
|
||||
spawn: ({ args }) => {
|
||||
spawnArgs = args;
|
||||
return appServer.child;
|
||||
},
|
||||
},
|
||||
});
|
||||
const internals = castInternals<{
|
||||
goalsEnabledPromise: Promise<boolean> | null;
|
||||
autoReviewEnabledPromise: Promise<boolean> | null;
|
||||
}>(provider);
|
||||
internals.goalsEnabledPromise = Promise.resolve(false);
|
||||
internals.autoReviewEnabledPromise = Promise.resolve(false);
|
||||
const agentId = "00000000-0000-4000-8000-000000000301";
|
||||
const launchContext = { agentId, env: { PASEO_AGENT_ID: agentId } };
|
||||
const session =
|
||||
operation === "create"
|
||||
? await provider.createSession(createConfig(), launchContext)
|
||||
: await provider.resumeSession(
|
||||
{ sessionId: "saved-thread" },
|
||||
createConfig(),
|
||||
launchContext,
|
||||
);
|
||||
try {
|
||||
expect(spawnArgs).toEqual([
|
||||
"app-server",
|
||||
"-c",
|
||||
`shell_environment_policy.set.PASEO_AGENT_ID="${agentId}"`,
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
async function startPublicSteeringSession(
|
||||
appServer: FakeCodexAppServer,
|
||||
resolveSlashCommandInvocation?: (prompt: AgentPromptInput) => Promise<{
|
||||
|
||||
@@ -8390,13 +8390,6 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
const processPort = this.deps.appServerProcess ?? defaultCodexAppServerProcess;
|
||||
const launchPrefix = await processPort.resolvePrefix({ runtimeSettings: this.runtimeSettings });
|
||||
const args = [...launchPrefix.args, "app-server"];
|
||||
if (options.agentId) {
|
||||
// Codex shell inheritance can filter the caller ID out of tool subprocesses.
|
||||
args.push(
|
||||
"-c",
|
||||
`shell_environment_policy.set.PASEO_AGENT_ID=${JSON.stringify(options.agentId)}`,
|
||||
);
|
||||
}
|
||||
if (options.goalsEnabled) {
|
||||
args.push("--enable", "goals");
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ test("real OpenCode server advertises agent-scoped notification descriptions", a
|
||||
logger,
|
||||
};
|
||||
const bridge = new OpenCodeBridge({ paseoHome: root, logger });
|
||||
bridge.setManifestCatalog(createPaseoAgentToolManifest(dependencies));
|
||||
bridge.setManifestCatalogFactory(() => createPaseoAgentToolManifest(dependencies));
|
||||
const manager = new OpenCodeServerManager({
|
||||
logger,
|
||||
resolveHomeDir: () => root,
|
||||
@@ -138,7 +138,7 @@ test("real OpenCode server shares one process while shell.env stays session-scop
|
||||
await bridge.start();
|
||||
const firstTools = createCallerCatalog("real-agent-one");
|
||||
const secondTools = createCallerCatalog("real-agent-two");
|
||||
bridge.setManifestCatalog(firstTools);
|
||||
bridge.setManifestCatalogFactory(() => firstTools);
|
||||
const manager = new OpenCodeServerManager({
|
||||
logger,
|
||||
resolveHomeDir: () => root,
|
||||
@@ -270,7 +270,7 @@ test("real OpenCode server asks before running a Paseo tool with an ask rule", a
|
||||
const bridge = new OpenCodeBridge({ paseoHome: root, logger });
|
||||
await bridge.start();
|
||||
const catalog = createCallerCatalog("ask-rule-agent");
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
const realSettings = getRealProviderRuntimeSettings("opencode");
|
||||
const runtimeSettings = {
|
||||
...realSettings,
|
||||
@@ -356,7 +356,7 @@ test("v2 native tool bridge preserves caller identity", async () => {
|
||||
const logger = createTestLogger();
|
||||
const bridge = new OpenCodeBridge({ paseoHome: root, logger });
|
||||
const catalog = createCallerCatalog("paseo-v2-caller");
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
await bridge.start();
|
||||
const client = new OpenCodeV2AgentClient({ logger, bridge });
|
||||
let session: Awaited<ReturnType<typeof client.createSession>> | undefined;
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ async function startFixture(mode: Mode, options: { userHub?: boolean } = {}): Pr
|
||||
paseoHome: path.join(root, "paseo"),
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
bridge.setManifestCatalog({ tools: new Map() });
|
||||
bridge.setManifestCatalogFactory(() => ({ tools: new Map() }));
|
||||
await bridge.start();
|
||||
const userHub = options.userHub
|
||||
? // Its `marker` requires an input that the agents' `marker` does not have.
|
||||
|
||||
@@ -10,11 +10,7 @@ import { ProviderSnapshotManager } from "../../provider-snapshot-manager.js";
|
||||
import { OpenCodeBridge } from "./bridge.js";
|
||||
import { ScheduleService } from "../../../schedule/service.js";
|
||||
import { createWorkspaceScriptsService } from "../../../session/workspace-scripts/workspace-scripts-service.js";
|
||||
import {
|
||||
FileBackedProjectRegistry,
|
||||
FileBackedWorkspaceRegistry,
|
||||
} from "../../../workspace-registry.js";
|
||||
import { createServiceProxySubsystem } from "../../../service-proxy.js";
|
||||
import { FileBackedWorkspaceRegistry } from "../../../workspace-registry.js";
|
||||
import { WorkspaceScriptRuntimeStore } from "../../../workspace-script-runtime-store.js";
|
||||
import { createTerminalManager } from "../../../../terminal/terminal-manager.js";
|
||||
import { createTestAgentMessages } from "../../../test-utils/agent-messages.js";
|
||||
@@ -40,22 +36,18 @@ test("bridge preserves tool failure messages and classifies invalid requests as
|
||||
runner: async () => ({ agentId: null, output: "done" }),
|
||||
});
|
||||
const workspaceScripts = createWorkspaceScriptsService({
|
||||
serviceProxy: createServiceProxySubsystem({ logger }),
|
||||
scriptRuntimeStore: new WorkspaceScriptRuntimeStore(),
|
||||
terminalManager: createTerminalManager(),
|
||||
workspaceRegistry: new FileBackedWorkspaceRegistry(
|
||||
path.join(paseoHome, "workspaces.json"),
|
||||
logger,
|
||||
),
|
||||
projectRegistry: new FileBackedProjectRegistry(path.join(paseoHome, "projects.json"), logger),
|
||||
workspaceRuntimeStore: {
|
||||
get: () => {
|
||||
throw new Error("Unexpected git lookup");
|
||||
},
|
||||
},
|
||||
getDaemonTcpPort: null,
|
||||
getDaemonTcpHost: null,
|
||||
serviceProxyPublicBaseUrl: null,
|
||||
resolveScriptHealth: null,
|
||||
getGlobalServicePorts: async () => undefined,
|
||||
logger,
|
||||
@@ -77,7 +69,7 @@ test("bridge preserves tool failure messages and classifies invalid requests as
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger });
|
||||
try {
|
||||
await bridge.start();
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
bridge.bindSession({ sessionId: "diagnosis", env: {}, tools: catalog });
|
||||
const config = JSON.parse(bridge.decorateServerEnv({}).OPENCODE_CONFIG_CONTENT);
|
||||
const { baseUrl, token } = config.plugin[0][1];
|
||||
|
||||
@@ -82,7 +82,7 @@ describe("OpenCodeBridge", () => {
|
||||
temporaryDirectories.push(paseoHome);
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
const catalog = createCatalog();
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
await bridge.start();
|
||||
const unbind = bridge.bindSession({ sessionId: "bound", env: {}, tools: catalog });
|
||||
bridge.bindSession({ sessionId: "disabled", env: {} });
|
||||
@@ -148,7 +148,7 @@ describe("OpenCodeBridge", () => {
|
||||
return { content: [{ type: "text", text: "Plugin action complete" }] };
|
||||
},
|
||||
};
|
||||
bridge.setManifestCatalog(builtin);
|
||||
bridge.setManifestCatalogFactory(() => builtin);
|
||||
await bridge.start();
|
||||
bridge.bindSession({ sessionId: "author/one", env: {}, tools: author });
|
||||
bridge.bindSession({ sessionId: "other", env: {}, tools: builtin });
|
||||
@@ -250,7 +250,7 @@ describe("OpenCodeBridge", () => {
|
||||
};
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger });
|
||||
await bridge.start();
|
||||
bridge.setManifestCatalog(createPaseoAgentToolManifest(dependencies));
|
||||
bridge.setManifestCatalogFactory(() => createPaseoAgentToolManifest(dependencies));
|
||||
try {
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "codex", cwd: paseoHome },
|
||||
@@ -414,6 +414,41 @@ describe("OpenCodeBridge", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("builds the unbound tool manifest when OpenCode first requests it", async () => {
|
||||
const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-bridge-"));
|
||||
temporaryDirectories.push(paseoHome);
|
||||
const builds: string[] = [];
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
await bridge.start();
|
||||
try {
|
||||
bridge.setManifestCatalogFactory(() => {
|
||||
builds.push("first");
|
||||
return createCatalog();
|
||||
});
|
||||
bridge.setManifestCatalogFactory(() => {
|
||||
builds.push("second");
|
||||
return createCatalog();
|
||||
});
|
||||
expect(builds).toEqual([]);
|
||||
|
||||
const plugin = readPluginOptions(bridge.decorateServerEnv({}));
|
||||
const headers = { Authorization: `Bearer ${plugin.token}` };
|
||||
const readToolNames = async () => {
|
||||
const response = await fetch(`${plugin.baseUrl}/_internal/opencode/tools`, { headers });
|
||||
const manifest = (await response.json()) as { tools: Array<{ name: string }> };
|
||||
return manifest.tools.map((tool) => tool.name);
|
||||
};
|
||||
expect(await readToolNames()).toEqual(["echo_context"]);
|
||||
expect(await readToolNames()).toEqual(["echo_context"]);
|
||||
expect(builds).toEqual(["second"]);
|
||||
|
||||
bridge.setManifestCatalogFactory(null);
|
||||
expect(await readToolNames()).toEqual([]);
|
||||
} finally {
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("serves authenticated session context and caller-scoped tools", async () => {
|
||||
const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-bridge-"));
|
||||
temporaryDirectories.push(paseoHome);
|
||||
@@ -426,7 +461,7 @@ describe("OpenCodeBridge", () => {
|
||||
};
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
await bridge.start();
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
const release = bridge.bindSession({
|
||||
sessionId: "ses_one",
|
||||
env: {
|
||||
@@ -554,7 +589,7 @@ describe("OpenCodeBridge", () => {
|
||||
temporaryDirectories.push(paseoHome);
|
||||
const catalog = createCatalog();
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
await bridge.start();
|
||||
const release = bridge.bindSession({ sessionId: "parent", env: {}, tools: catalog });
|
||||
const releaseDisabled = bridge.bindSession({ sessionId: "disabled", env: {} });
|
||||
@@ -635,7 +670,7 @@ describe("OpenCodeBridge", () => {
|
||||
logger,
|
||||
});
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger });
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
await bridge.start();
|
||||
const release = bridge.bindSession({ sessionId: "caller", env: {}, tools: catalog });
|
||||
try {
|
||||
@@ -719,7 +754,7 @@ describe("OpenCodeBridge", () => {
|
||||
await tools.get(name)!.handler(input, context ?? {}),
|
||||
};
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
bridge.setManifestCatalog(catalog);
|
||||
bridge.setManifestCatalogFactory(() => catalog);
|
||||
await bridge.start();
|
||||
const release = bridge.bindSession({ sessionId: "session", env: {}, tools: catalog });
|
||||
try {
|
||||
|
||||
@@ -85,6 +85,7 @@ export class OpenCodeBridge {
|
||||
private baseUrl: string | null = null;
|
||||
private pluginUrl: string | null = null;
|
||||
private v2PluginUrl: string | null = null;
|
||||
private manifestCatalogFactory: (() => Pick<PaseoToolCatalog, "tools">) | null = null;
|
||||
private manifestCatalog: Pick<PaseoToolCatalog, "tools"> | null = null;
|
||||
|
||||
constructor(options: OpenCodeBridgeOptions) {
|
||||
@@ -115,8 +116,11 @@ export class OpenCodeBridge {
|
||||
this.baseUrl = `http://127.0.0.1:${address.port}`;
|
||||
}
|
||||
|
||||
setManifestCatalog(catalog: Pick<PaseoToolCatalog, "tools"> | null): void {
|
||||
this.manifestCatalog = catalog;
|
||||
// Building the catalog is synchronous schema work. Config changes only replace the
|
||||
// factory; the catalog is built when OpenCode asks for the unbound manifest.
|
||||
setManifestCatalogFactory(factory: (() => Pick<PaseoToolCatalog, "tools">) | null): void {
|
||||
this.manifestCatalogFactory = factory;
|
||||
this.manifestCatalog = null;
|
||||
}
|
||||
|
||||
bindSession(input: BindOpenCodeSessionInput): () => void {
|
||||
@@ -263,15 +267,24 @@ export class OpenCodeBridge {
|
||||
};
|
||||
}
|
||||
|
||||
private serializeManifest(sessionId: string | null): Array<Record<string, unknown>> {
|
||||
let catalog: Pick<PaseoToolCatalog, "tools"> | null | undefined = this.manifestCatalog;
|
||||
if (sessionId !== null) {
|
||||
const binding = this.sessions.get(sessionId);
|
||||
if (!binding) {
|
||||
throw new OpenCodeBridgeClientError(404, "OpenCode session is not bound to a Paseo agent");
|
||||
}
|
||||
catalog = binding.tools;
|
||||
private readManifestCatalog(): Pick<PaseoToolCatalog, "tools"> | null {
|
||||
if (!this.manifestCatalog && this.manifestCatalogFactory) {
|
||||
this.manifestCatalog = this.manifestCatalogFactory();
|
||||
}
|
||||
return this.manifestCatalog;
|
||||
}
|
||||
|
||||
private readSessionCatalog(sessionId: string): Pick<PaseoToolCatalog, "tools"> | undefined {
|
||||
const binding = this.sessions.get(sessionId);
|
||||
if (!binding) {
|
||||
throw new OpenCodeBridgeClientError(404, "OpenCode session is not bound to a Paseo agent");
|
||||
}
|
||||
return binding.tools;
|
||||
}
|
||||
|
||||
private serializeManifest(sessionId: string | null): Array<Record<string, unknown>> {
|
||||
const catalog =
|
||||
sessionId === null ? this.readManifestCatalog() : this.readSessionCatalog(sessionId);
|
||||
if (!catalog) return [];
|
||||
return [...catalog.tools.values()].map((tool) => {
|
||||
const definition: Record<string, unknown> = {
|
||||
|
||||
@@ -44,7 +44,7 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions"
|
||||
const tool = { name: "echo", description: "echo", inputSchema: { value: z.string() } };
|
||||
const tools = new Map([[tool.name, tool]]);
|
||||
// Session-only tools must survive plugin reload without a global definition.
|
||||
bridge.setManifestCatalog({ tools: new Map() });
|
||||
bridge.setManifestCatalogFactory(() => ({ tools: new Map() }));
|
||||
await bridge.start();
|
||||
const unbind = bridge.bindSession({
|
||||
sessionId: "paseo",
|
||||
@@ -165,7 +165,7 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions"
|
||||
logger: createTestLogger(),
|
||||
port: Number(new URL(plugin.options.baseUrl).port),
|
||||
});
|
||||
restarted.setManifestCatalog({ tools });
|
||||
restarted.setManifestCatalogFactory(() => ({ tools }));
|
||||
await restarted.start();
|
||||
const releaseRestarted = restarted.bindSession({ sessionId: "paseo", env: {} });
|
||||
try {
|
||||
@@ -193,7 +193,7 @@ test("a shared plugin rebinds a session after the previous bridge stops listenin
|
||||
await new Promise<void>((resolve) => previous.listen(0, "127.0.0.1", resolve));
|
||||
const previousPort = (previous.address() as AddressInfo).port;
|
||||
const current = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
|
||||
current.setManifestCatalog({ tools: new Map() });
|
||||
current.setManifestCatalogFactory(() => ({ tools: new Map() }));
|
||||
let rpc: Record<string, (input: Binding) => Promise<unknown>> = {};
|
||||
let dispose: (() => Promise<void>) | undefined;
|
||||
let releaseCurrent: (() => void) | undefined;
|
||||
@@ -392,7 +392,7 @@ test("binding another session at the same location preserves the first session's
|
||||
test("a shared plugin gives each session its own MCP tools behind OpenCode's permission check", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-mcp-"));
|
||||
const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
|
||||
bridge.setManifestCatalog({ tools: new Map() });
|
||||
bridge.setManifestCatalogFactory(() => ({ tools: new Map() }));
|
||||
await bridge.start();
|
||||
const adopted: string[] = [];
|
||||
const sessionMcp = (marker: string) => ({
|
||||
|
||||
@@ -204,7 +204,9 @@ async function createSession(
|
||||
events: SessionEvents;
|
||||
}> {
|
||||
const client = createClient(pi, usagePollScheduler);
|
||||
const session = (await client.createSession(createConfig())) as PiRpcAgentSession;
|
||||
const session = (await client.createSession(createConfig(), {
|
||||
approveProjectResources: true,
|
||||
})) as PiRpcAgentSession;
|
||||
const events = new SessionEvents(session);
|
||||
return { pi, session, events };
|
||||
}
|
||||
@@ -225,15 +227,42 @@ test("forwards launch-context env to the Pi process launch", async () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("approves project-local Pi resources for trusted interactive sessions", async () => {
|
||||
const pi = new FakePi();
|
||||
const client = createClient(pi);
|
||||
const session = await client.createSession(createConfig(), {
|
||||
approveProjectResources: true,
|
||||
});
|
||||
|
||||
expect(pi.recordedLaunches[0]?.argv).toContain("--approve");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("does not approve project-local Pi resources for untrusted interactive sessions", async () => {
|
||||
const pi = new FakePi();
|
||||
const client = createClient(pi);
|
||||
const session = await client.createSession(createConfig(), {
|
||||
approveProjectResources: false,
|
||||
});
|
||||
|
||||
expect(pi.recordedLaunches[0]?.argv).not.toContain("--approve");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("starts internal Pi agents without persisting a native session", async () => {
|
||||
const pi = new FakePi();
|
||||
const client = createClient(pi);
|
||||
const session = await client.createSession(createConfig({ internal: true }));
|
||||
const session = await client.createSession(createConfig({ internal: true }), {
|
||||
approveProjectResources: true,
|
||||
});
|
||||
|
||||
expect(pi.recordedLaunches[0]).toMatchObject({
|
||||
noSession: true,
|
||||
argv: expect.arrayContaining(["--no-session"]),
|
||||
});
|
||||
expect(pi.recordedLaunches[0]?.argv).not.toContain("--approve");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
@@ -1331,12 +1360,16 @@ describe("PiRpcAgentSession", () => {
|
||||
test("uses the Pi entry attached to a submitted prompt after resuming old history", async () => {
|
||||
const pi = new FakePi();
|
||||
const client = createClient(pi);
|
||||
const session = (await client.resumeSession({
|
||||
provider: "pi",
|
||||
sessionId: "pi-session-1",
|
||||
nativeHandle: "/tmp/native-pi-session",
|
||||
metadata: { cwd: "/workspace/project" },
|
||||
})) as PiRpcAgentSession;
|
||||
const session = (await client.resumeSession(
|
||||
{
|
||||
provider: "pi",
|
||||
sessionId: "pi-session-1",
|
||||
nativeHandle: "/tmp/native-pi-session",
|
||||
metadata: { cwd: "/workspace/project" },
|
||||
},
|
||||
undefined,
|
||||
{ approveProjectResources: true },
|
||||
)) as PiRpcAgentSession;
|
||||
const events = new SessionEvents(session);
|
||||
const fakeSession = pi.latestSession();
|
||||
fakeSession.treeUserEntries = [{ id: "entry-old", parentId: null, text: "old prompt" }];
|
||||
@@ -1432,6 +1465,87 @@ describe("PiRpcAgentSession", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps the turn open when an extension sends context before Pi answers the prompt", async () => {
|
||||
const { pi, session, events } = await createSession();
|
||||
const fakeSession = pi.latestSession();
|
||||
|
||||
// Pi answers `prompt` after before_agent_start, where extensions inject hidden context.
|
||||
fakeSession.holdNextPrompt();
|
||||
const { turnId } = await session.startTurn("hello", { clientMessageId: "client-hello" });
|
||||
fakeSession.emit({
|
||||
type: "message_end",
|
||||
message: {
|
||||
role: "custom",
|
||||
customType: "project-context",
|
||||
content: [{ type: "text", text: "Hidden context" }],
|
||||
display: false,
|
||||
},
|
||||
});
|
||||
// Pi writes its answer and agent_start back to back.
|
||||
const answered = fakeSession.answerHeldPrompt();
|
||||
fakeSession.emit({ type: "agent_start" });
|
||||
fakeSession.emit({ type: "turn_start" });
|
||||
await answered;
|
||||
fakeSession.finishSubmittedUserMessage({ id: "entry-hello", parentId: null, text: "hello" });
|
||||
|
||||
expect(events.turnCompletedEvents()).toHaveLength(0);
|
||||
expect(events.timelineItems()).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: "hello",
|
||||
messageId: "entry-hello",
|
||||
clientMessageId: "client-hello",
|
||||
},
|
||||
]);
|
||||
|
||||
fakeSession.finishTurn();
|
||||
expect(await events.nextTurnCompletion()).toMatchObject({ type: "turn_completed", turnId });
|
||||
expect(events.turnCompletedEvents()).toHaveLength(1);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("keeps the turn open when Pi has answered the prompt and is still starting the run", async () => {
|
||||
const { pi, session, events } = await createSession();
|
||||
const fakeSession = pi.latestSession();
|
||||
|
||||
fakeSession.holdNextPrompt();
|
||||
const { turnId } = await session.startTurn("hello");
|
||||
fakeSession.emit({
|
||||
type: "message_end",
|
||||
message: {
|
||||
role: "custom",
|
||||
content: [{ type: "text", text: "Hidden context" }],
|
||||
display: false,
|
||||
},
|
||||
});
|
||||
fakeSession.state = { ...fakeSession.state, isStreaming: true };
|
||||
await fakeSession.answerHeldPrompt();
|
||||
await flushTurnScheduling();
|
||||
expect(events.turnCompletedEvents()).toHaveLength(0);
|
||||
|
||||
fakeSession.emit({ type: "agent_start" });
|
||||
fakeSession.finishTurn();
|
||||
expect(await events.nextTurnCompletion()).toMatchObject({ type: "turn_completed", turnId });
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("completes a prompt an extension handled with a custom message once Pi answers it", async () => {
|
||||
const { pi, session, events } = await createSession();
|
||||
const fakeSession = pi.latestSession();
|
||||
|
||||
fakeSession.holdNextPrompt();
|
||||
const { turnId } = await session.startTurn("show status");
|
||||
fakeSession.emit({
|
||||
type: "message_end",
|
||||
message: { role: "custom", content: [{ type: "text", text: "Extension output" }] },
|
||||
});
|
||||
expect(events.turnCompletedEvents()).toHaveLength(0);
|
||||
|
||||
await fakeSession.answerHeldPrompt();
|
||||
expect(await events.nextTurnCompletion()).toMatchObject({ type: "turn_completed", turnId });
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("settles an autonomous turn triggered by a Pi extension custom message", async () => {
|
||||
const { pi, events } = await createSession();
|
||||
const fakeSession = pi.latestSession();
|
||||
@@ -1896,7 +2010,7 @@ describe("PiRpcAgentSession", () => {
|
||||
},
|
||||
},
|
||||
{},
|
||||
{ env: { RESUME_PROBE: "expected" } },
|
||||
{ env: { RESUME_PROBE: "expected" }, approveProjectResources: true },
|
||||
);
|
||||
|
||||
expect(session.usageSession?.()).toMatchObject({
|
||||
@@ -1917,6 +2031,7 @@ describe("PiRpcAgentSession", () => {
|
||||
"pi",
|
||||
"--mode",
|
||||
"rpc",
|
||||
"--approve",
|
||||
"--thinking",
|
||||
"high",
|
||||
"--session",
|
||||
@@ -2162,6 +2277,24 @@ describe("PiRpcAgentSession", () => {
|
||||
await expect(session.getRuntimeInfo()).resolves.toMatchObject({ thinkingOptionId: "high" });
|
||||
});
|
||||
|
||||
test("does not approve persisted Pi sessions when the workspace is untrusted", async () => {
|
||||
const pi = new FakePi();
|
||||
const client = createClient(pi);
|
||||
|
||||
await client.resumeSession(
|
||||
{
|
||||
provider: "pi",
|
||||
sessionId: "pi-session-untrusted",
|
||||
nativeHandle: "/tmp/native-pi-untrusted",
|
||||
metadata: { cwd: "/workspace/untrusted" },
|
||||
},
|
||||
undefined,
|
||||
{ approveProjectResources: false },
|
||||
);
|
||||
|
||||
expect(pi.recordedLaunches[0]?.argv).not.toContain("--approve");
|
||||
});
|
||||
|
||||
test("reports the persisted Pi entry attached to the submitted message", async () => {
|
||||
const pi = new FakePi();
|
||||
const client = createClient(pi);
|
||||
@@ -2254,6 +2387,7 @@ describe("PiRpcAgentSession", () => {
|
||||
daemonAppendSystemPrompt: "Daemon prompt",
|
||||
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
|
||||
}),
|
||||
{ approveProjectResources: true },
|
||||
);
|
||||
|
||||
const actualLaunch = pi.recordedLaunches[0]!;
|
||||
@@ -2265,6 +2399,7 @@ describe("PiRpcAgentSession", () => {
|
||||
"pi",
|
||||
"--mode",
|
||||
"rpc",
|
||||
"--approve",
|
||||
"--extension",
|
||||
actualLaunch.extensionPaths[0],
|
||||
]);
|
||||
@@ -2298,6 +2433,7 @@ describe("PiRpcAgentSession", () => {
|
||||
daemonAppendSystemPrompt: "Daemon prompt",
|
||||
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
|
||||
},
|
||||
{ approveProjectResources: true },
|
||||
);
|
||||
|
||||
expect(pi.recordedLaunches).toHaveLength(1);
|
||||
@@ -2311,6 +2447,7 @@ describe("PiRpcAgentSession", () => {
|
||||
"pi",
|
||||
"--mode",
|
||||
"rpc",
|
||||
"--approve",
|
||||
"--thinking",
|
||||
"high",
|
||||
"--session",
|
||||
@@ -3343,7 +3480,11 @@ describe("PiRpcAgentClient", () => {
|
||||
|
||||
const imported = await client.importSession(
|
||||
{ providerHandleId: sessionFile, cwd },
|
||||
{ config: createConfig({ cwd }), storedConfig: createConfig({ cwd }) },
|
||||
{
|
||||
config: createConfig({ cwd }),
|
||||
storedConfig: createConfig({ cwd }),
|
||||
launchContext: { approveProjectResources: true },
|
||||
},
|
||||
);
|
||||
|
||||
const actualLaunch = pi.recordedLaunches[0]!;
|
||||
@@ -3352,6 +3493,7 @@ describe("PiRpcAgentClient", () => {
|
||||
"pi",
|
||||
"--mode",
|
||||
"rpc",
|
||||
"--approve",
|
||||
"--thinking",
|
||||
"high",
|
||||
"--session",
|
||||
@@ -3402,6 +3544,7 @@ describe("PiRpcAgentClient", () => {
|
||||
modes: [],
|
||||
});
|
||||
expect(pi.recordedLaunches[0]).toMatchObject({ cwd: "/workspace/with-extension" });
|
||||
expect(pi.recordedLaunches[0]?.argv).not.toContain("--approve");
|
||||
});
|
||||
|
||||
test("marks the model Pi resolves from its own settings as the catalog default", async () => {
|
||||
@@ -4092,6 +4235,7 @@ describe("PiRpcAgentClient", () => {
|
||||
);
|
||||
|
||||
expect(pi.recordedLaunches).toHaveLength(2);
|
||||
expect(pi.recordedLaunches[0]?.argv).not.toContain("--approve");
|
||||
const actualLaunch = pi.recordedLaunches[1]!;
|
||||
expect(actualLaunch.extensionPaths).toHaveLength(1);
|
||||
expect(actualLaunch.argv).toEqual([
|
||||
|
||||
@@ -123,6 +123,7 @@ import {
|
||||
} from "./tool-call-mapper.js";
|
||||
|
||||
const PI_PROVIDER = "pi";
|
||||
const PI_PROJECT_TRUST_ARGS = ["--approve"];
|
||||
const DEFAULT_PI_THINKING_LEVEL: PiThinkingLevel = "medium";
|
||||
const PI_BINARY_COMMAND = process.env.PI_COMMAND ?? process.env.PI_ACP_PI_COMMAND ?? "pi";
|
||||
const PASEO_PI_TREE_EXTENSION_COMMAND = "paseo_tree";
|
||||
@@ -493,6 +494,15 @@ function buildResumeConfig(
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePiProjectTrustArgs(
|
||||
launchContext: AgentLaunchContext | undefined,
|
||||
config: AgentSessionConfig,
|
||||
): string[] | undefined {
|
||||
return launchContext?.approveProjectResources && config.internal !== true
|
||||
? PI_PROJECT_TRUST_ARGS
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function buildResumeStartInput(input: {
|
||||
resumeConfig: PiResumeConfig;
|
||||
processCwd: string;
|
||||
@@ -509,6 +519,7 @@ function buildResumeStartInput(input: {
|
||||
thinkingOptionId: normalizePiThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined,
|
||||
mcpConfigPath: input.mcpConfigFile?.path,
|
||||
extensionPaths: input.paseoExtension ? [input.paseoExtension.path] : undefined,
|
||||
extraArgs: resolvePiProjectTrustArgs(input.launchContext, input.resumeConfig.config),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1208,6 +1219,9 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
private activeNoTurnPromptText: string | null = null;
|
||||
private readonly pendingNoTurnOutputs: Array<{ turnId: string; message: string }> = [];
|
||||
private activePromptRequestId: string | null = null;
|
||||
// Pi answers `prompt` only after extension preflight (input handlers, the compaction check and
|
||||
// before_agent_start), so events can arrive for a turn whose prompt is still unanswered.
|
||||
private promptPreflight: { turnId: string; sawCustomMessage: boolean } | null = null;
|
||||
private readonly pendingPromptResults = new Map<string, boolean>();
|
||||
private readonly pendingSteerSubmissions: PiPendingSteerSubmission[] = [];
|
||||
currentLeafOverrideId: string | null | undefined;
|
||||
@@ -1357,7 +1371,11 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const ack = await this.runtimeSession.prompt(payload.text, payload.images);
|
||||
const preflight = { turnId, sawCustomMessage: false };
|
||||
this.promptPreflight = preflight;
|
||||
const ack = await this.runtimeSession.prompt(payload.text, payload.images).finally(() => {
|
||||
if (this.promptPreflight === preflight) this.promptPreflight = null;
|
||||
});
|
||||
this.activePromptRequestId = ack.requestId ?? null;
|
||||
const correlatedResult = ack.requestId
|
||||
? this.pendingPromptResults.get(ack.requestId)
|
||||
@@ -1370,10 +1388,12 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
await this.completeNoTurnPrompt(turnId);
|
||||
return;
|
||||
}
|
||||
// Pi can acknowledge a prompt as handled even when the extension starts a run.
|
||||
// A custom message or a handled acknowledgment can precede a run started by the extension.
|
||||
if (
|
||||
agentInvoked === undefined &&
|
||||
(ack.handledByExtension || this.parseSlashCommandInput(payload.text) !== null)
|
||||
(preflight.sawCustomMessage ||
|
||||
ack.handledByExtension ||
|
||||
this.parseSlashCommandInput(payload.text) !== null)
|
||||
) {
|
||||
await this.completePromptIfHandledWithoutTurn(turnId);
|
||||
}
|
||||
@@ -2638,7 +2658,12 @@ export class PiRpcAgentSession implements AgentSession {
|
||||
),
|
||||
});
|
||||
}
|
||||
if (!this.activeTurnStarted) {
|
||||
// An extension can send context from preflight, before Pi answers the prompt. Whether a run
|
||||
// follows is known once Pi answers; startTurn checks then.
|
||||
const preflight = this.promptPreflight;
|
||||
if (preflight && preflight.turnId === turnId) {
|
||||
preflight.sawCustomMessage = true;
|
||||
} else if (!this.activeTurnStarted) {
|
||||
this.completeTurn(turnId, []);
|
||||
}
|
||||
return;
|
||||
@@ -2799,6 +2824,7 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
wrap,
|
||||
mcpConfigPath: mcpConfigFile?.path,
|
||||
extensionPaths: paseoExtension ? [paseoExtension.path] : undefined,
|
||||
extraArgs: resolvePiProjectTrustArgs(launchContext, config),
|
||||
});
|
||||
} catch (error) {
|
||||
mcpConfigFile?.cleanup();
|
||||
|
||||
@@ -393,6 +393,27 @@ describe("PiCliRuntime", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("prompt waits beyond the control-plane timeout while Pi runs extension preflight", async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = createPiChild();
|
||||
const pendingPrompt = capturePendingCommand(child, "prompt");
|
||||
const session = await createRuntime(child).startSession({ cwd: "/workspace/project" });
|
||||
|
||||
try {
|
||||
const promptPromise = session.prompt("hello");
|
||||
void promptPromise.catch(() => {});
|
||||
const promptCommand = await pendingPrompt;
|
||||
// An extension asks the user a question before the run starts; they answer two minutes later.
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
writePiResponse(child, promptCommand, {});
|
||||
|
||||
await expect(promptPromise).resolves.toMatchObject({ requestId: promptCommand.id });
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("compact waits beyond the default control-plane timeout for a late response", async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = createPiChild();
|
||||
|
||||
@@ -126,15 +126,19 @@ class PiCliRuntimeSession implements PiRuntimeSession {
|
||||
message: string,
|
||||
images?: Array<{ type: "image"; data: string; mimeType: string }>,
|
||||
): Promise<PiPromptAck> {
|
||||
const { id: requestId, promise } = this.options.process.startRequest({
|
||||
type: "prompt",
|
||||
message,
|
||||
...(images?.length ? { images } : {}),
|
||||
// Pi can be busy with a run it started itself (an extension message, a background
|
||||
// result) before it reports agent_start. It rejects a bare prompt then; followUp queues
|
||||
// the prompt into that run. Pi ignores the option when it is idle.
|
||||
streamingBehavior: "followUp",
|
||||
});
|
||||
// Pi answers after extension preflight, which can wait for user input or compaction.
|
||||
const { id: requestId, promise } = this.options.process.startRequest(
|
||||
{
|
||||
type: "prompt",
|
||||
message,
|
||||
...(images?.length ? { images } : {}),
|
||||
// Pi can be busy with a run it started itself (an extension message, a background
|
||||
// result) before it reports agent_start. It rejects a bare prompt then; followUp queues
|
||||
// the prompt into that run. Pi ignores the option when it is idle.
|
||||
streamingBehavior: "followUp",
|
||||
},
|
||||
JSONL_RPC_NO_TIMEOUT,
|
||||
);
|
||||
const data = await promise;
|
||||
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
|
||||
const { agentInvoked, disposition } = data as Record<string, unknown>;
|
||||
|
||||
@@ -53,6 +53,12 @@ interface FakePiUserEntry {
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface HeldPrompt {
|
||||
promise: Promise<void>;
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
export class FakePi implements PiRuntime {
|
||||
readonly recordedLaunches: PiRuntimeLaunch[] = [];
|
||||
private readonly sessions: FakePiSession[] = [];
|
||||
@@ -183,9 +189,8 @@ export class FakePiSession implements PiRuntimeSession {
|
||||
|
||||
private readonly subscribers = new Set<(event: PiRuntimeEvent) => void>();
|
||||
private readonly subagentMessageResults = new Map<string, FakePiSubagentMessagesResult[]>();
|
||||
private nextHeldPrompt: { promise: Promise<void>; reject: (error: Error) => void } | null = null;
|
||||
private activeHeldPrompt: { promise: Promise<void>; reject: (error: Error) => void } | null =
|
||||
null;
|
||||
private nextHeldPrompt: HeldPrompt | null = null;
|
||||
private activeHeldPrompt: HeldPrompt | null = null;
|
||||
|
||||
constructor(
|
||||
launch: PiRuntimeLaunch,
|
||||
@@ -238,11 +243,23 @@ export class FakePiSession implements PiRuntimeSession {
|
||||
if (this.nextHeldPrompt || this.activeHeldPrompt) {
|
||||
throw new Error("FakePi already has a held prompt");
|
||||
}
|
||||
let resolve!: () => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<void>((_resolve, rejectPromise) => {
|
||||
const promise = new Promise<void>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
this.nextHeldPrompt = { promise, reject };
|
||||
this.nextHeldPrompt = { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/** Pi answers a prompt only after extension preflight; this ends that wait. */
|
||||
async answerHeldPrompt(): Promise<void> {
|
||||
const heldPrompt = this.activeHeldPrompt ?? this.nextHeldPrompt;
|
||||
if (!heldPrompt) {
|
||||
throw new Error("FakePi has no held prompt");
|
||||
}
|
||||
heldPrompt.resolve();
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
async failHeldPrompt(error: Error): Promise<void> {
|
||||
|
||||
@@ -2601,7 +2601,7 @@ function createToolCatalog(
|
||||
{
|
||||
title: "List workspace scripts",
|
||||
description:
|
||||
"List configured workspace scripts and their lifecycle, service port, proxy URL, health, and terminal ID.",
|
||||
"List configured workspace scripts and their lifecycle, service port, active tunnel, health, and terminal ID.",
|
||||
inputSchema: {
|
||||
workspaceId: z.string().describe("Workspace ID whose configured scripts to list."),
|
||||
},
|
||||
|
||||
@@ -246,6 +246,8 @@ const INBOUND_PERMISSION = {
|
||||
"workspace.script.list.request": "workspace.read",
|
||||
"workspace.script.start.request": "workspace.write",
|
||||
"workspace.script.stop.request": "workspace.write",
|
||||
"workspace.script.tunnel.open.request": "tunnel.manage",
|
||||
"workspace.script.tunnel.close.request": "tunnel.manage",
|
||||
"workspace.title.set.request": ["workspace.manage", "hub.execute"],
|
||||
workspace_setup_status_request: "workspace.read",
|
||||
"workspace.setup.subscribe.request": "workspace.read",
|
||||
@@ -516,6 +518,8 @@ const OUTBOUND_PERMISSION = {
|
||||
"workspace.script.list.response": "workspace.read",
|
||||
"workspace.script.start.response": "workspace.write",
|
||||
"workspace.script.stop.response": "workspace.write",
|
||||
"workspace.script.tunnel.open.response": "tunnel.manage",
|
||||
"workspace.script.tunnel.close.response": "tunnel.manage",
|
||||
"workspace.title.set.response": ["workspace.manage", "hub.execute"],
|
||||
workspace_setup_progress: "workspace.read",
|
||||
workspace_setup_status_response: "workspace.read",
|
||||
|
||||
@@ -25,13 +25,13 @@ import {
|
||||
import { AgentStorage, type StoredAgentRecord } from "./agent/agent-storage.js";
|
||||
import { ensureAgentLoaded, loadAgentHistory } from "./agent/agent-loading.js";
|
||||
import { AgentManagerShuttingDownError } from "./agent/agent-manager.js";
|
||||
import { hashDaemonPassword } from "./auth.js";
|
||||
import { generateLocalPairingOffer } from "./pairing-offer.js";
|
||||
import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js";
|
||||
import { createTestAgentClients } from "./test-utils/fake-agent-client.js";
|
||||
import { DaemonClient } from "./test-utils/daemon-client.js";
|
||||
import { isPlatform } from "../test-utils/platform.js";
|
||||
import { findFreePort } from "./service-proxy.js";
|
||||
import { buildServiceTunnelExposureId } from "./tunnels/index.js";
|
||||
import { findFreePort } from "./workspace-service-port-allocator.js";
|
||||
import {
|
||||
configureGitProcessPolicy,
|
||||
snapshotGitCommandRuntimeMetrics,
|
||||
@@ -528,7 +528,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
lazyTerminalWorker: true,
|
||||
});
|
||||
let client: DaemonClient | null = null;
|
||||
let proxyUpstream: http.Server | null = null;
|
||||
|
||||
try {
|
||||
await daemon.start();
|
||||
@@ -540,23 +539,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
proxyUpstream = http.createServer((req, res) => {
|
||||
res.end(String(req.headers["x-forwarded-proto"] ?? "missing"));
|
||||
});
|
||||
await new Promise<void>((resolve) => proxyUpstream?.listen(0, "127.0.0.1", resolve));
|
||||
const proxyAddress = proxyUpstream.address();
|
||||
if (!proxyAddress || typeof proxyAddress === "string") {
|
||||
throw new Error("Expected proxy upstream TCP address");
|
||||
}
|
||||
const proxyRoute = daemon.serviceProxy.registerWorkspaceService({
|
||||
workspaceId: "workspace-config-reload",
|
||||
projectSlug: "reload",
|
||||
branchName: "main",
|
||||
scriptName: "proxy",
|
||||
port: proxyAddress.port,
|
||||
});
|
||||
const proxyHost = `${proxyRoute.hostname}:${target.port}`;
|
||||
|
||||
expect(
|
||||
(await httpGetWithHost(target.port, "before.example.test", "/api/health")).status,
|
||||
).toBe(200);
|
||||
@@ -575,10 +557,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
// Any answer from the agent MCP handler proves the route is live; the handler
|
||||
// rejects a body-less POST as an unsupported media type.
|
||||
expect(beforeMcp.status).toBe(415);
|
||||
const beforeProxyReload = await httpGetWithHost(target.port, proxyHost, "/", {
|
||||
"x-forwarded-proto": "https",
|
||||
});
|
||||
expect(await beforeProxyReload.text()).toBe("http");
|
||||
|
||||
const reloadedPersisted = {
|
||||
...initialPersisted,
|
||||
@@ -630,10 +608,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
expect(afterCors.headers.get("access-control-allow-origin")).toBe(
|
||||
"https://after.example.test",
|
||||
);
|
||||
const afterProxyReload = await httpGetWithHost(target.port, proxyHost, "/", {
|
||||
"x-forwarded-proto": "https",
|
||||
});
|
||||
expect(await afterProxyReload.text()).toBe("https");
|
||||
await expect(
|
||||
probeWebSocketConnection(`ws://127.0.0.1:${target.port}/ws`, {
|
||||
host: "after.example.test",
|
||||
@@ -670,9 +644,6 @@ describe("paseo daemon bootstrap", () => {
|
||||
configureGitProcessPolicy(DEFAULT_GIT_PROCESS_POLICY);
|
||||
await client?.close().catch(() => undefined);
|
||||
await daemon.stop().catch(() => undefined);
|
||||
if (proxyUpstream) {
|
||||
await new Promise<void>((resolve) => proxyUpstream?.close(() => resolve()));
|
||||
}
|
||||
await Promise.all([
|
||||
rm(paseoHomeRoot, { recursive: true, force: true }),
|
||||
rm(staticDir, { recursive: true, force: true }),
|
||||
@@ -707,66 +678,235 @@ describe("paseo daemon bootstrap", () => {
|
||||
});
|
||||
}
|
||||
|
||||
test("proxies registered service hosts before daemon auth while daemon APIs stay protected", async () => {
|
||||
const upstream = http.createServer((_req, res) => {
|
||||
res.writeHead(200, { "content-type": "text/plain" });
|
||||
res.end("service-ok");
|
||||
});
|
||||
await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
|
||||
const address = upstream.address();
|
||||
if (!address || typeof address === "string") {
|
||||
throw new Error("Expected upstream TCP address");
|
||||
}
|
||||
test("logs a startup deprecation warning when daemon.serviceProxy is configured and boots cleanly", async () => {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-service-proxy-deprecated-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-"));
|
||||
await mkdir(paseoHome, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(paseoHome, "config.json"),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
daemon: {
|
||||
listen: "127.0.0.1:0",
|
||||
relay: { enabled: false },
|
||||
serviceProxy: {
|
||||
enabled: true,
|
||||
listen: "127.0.0.1:9999",
|
||||
publicBaseUrl: "https://services.example.com",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
const daemonHandle = await createTestPaseoDaemon({
|
||||
auth: { password: hashDaemonPassword("secret") },
|
||||
const logLines: string[] = [];
|
||||
const logger = pino(
|
||||
{ level: "warn" },
|
||||
{
|
||||
write: (line: string) => {
|
||||
logLines.push(line);
|
||||
},
|
||||
},
|
||||
);
|
||||
const config = loadConfig(paseoHome, { env: {} });
|
||||
config.staticDir = staticDir;
|
||||
config.agentClients = createTestAgentClients();
|
||||
config.agentStoragePath = path.join(paseoHome, "agents");
|
||||
config.speech = {
|
||||
providers: {
|
||||
dictationStt: { provider: "local", explicit: true, enabled: false },
|
||||
voiceTurnDetection: { provider: "local", explicit: true, enabled: false },
|
||||
voiceStt: { provider: "local", explicit: true, enabled: false },
|
||||
voiceTts: { provider: "local", explicit: true, enabled: false },
|
||||
},
|
||||
};
|
||||
const daemon = await createPaseoDaemon(config, logger, {
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
});
|
||||
try {
|
||||
daemonHandle.daemon.serviceProxy.registerWorkspaceService({
|
||||
workspaceId: "workspace-service-auth",
|
||||
projectSlug: "repo",
|
||||
branchName: "main",
|
||||
scriptName: "web",
|
||||
port: address.port,
|
||||
});
|
||||
|
||||
const serviceResponse = await httpGetWithHost(
|
||||
daemonHandle.port,
|
||||
`web--repo.localhost:${daemonHandle.port}`,
|
||||
"/",
|
||||
);
|
||||
expect(serviceResponse.status).toBe(200);
|
||||
expect(await serviceResponse.text()).toBe("service-ok");
|
||||
|
||||
const daemonResponse = await httpGetWithHost(
|
||||
daemonHandle.port,
|
||||
`daemon.localhost:${daemonHandle.port}`,
|
||||
"/api/status",
|
||||
);
|
||||
expect(daemonResponse.status).toBe(401);
|
||||
await daemon.start();
|
||||
const target = daemon.getListenTarget();
|
||||
if (!target || target.type !== "tcp") throw new Error("Expected TCP listener");
|
||||
const health = await fetch(`http://127.0.0.1:${target.port}/api/health`);
|
||||
expect(health.status).toBe(200);
|
||||
expect(
|
||||
logLines.some((line) =>
|
||||
line.includes("`daemon.serviceProxy` was removed in favor of tunnel providers"),
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
await daemonHandle.close();
|
||||
await new Promise<void>((resolve) => upstream.close(() => resolve()));
|
||||
await daemon.stop().catch(() => undefined);
|
||||
await rm(paseoHomeRoot, { recursive: true, force: true });
|
||||
await rm(staticDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("configured public service namespace misses never reach daemon APIs", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon({
|
||||
serviceProxy: {
|
||||
publicBaseUrl: "https://services.example.com",
|
||||
standaloneListen: null,
|
||||
test("pushes live script_status_update on workspace service tunnel transitions and closes tunnels on archive", async () => {
|
||||
const workspaceDir = await mkdtemp(path.join(os.tmpdir(), "paseo-service-tunnel-ws-"));
|
||||
await writeFile(
|
||||
path.join(workspaceDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
scripts: {
|
||||
web: { type: "service", command: "npm run dev", port: 4123 },
|
||||
},
|
||||
}),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
const daemonHandle = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemonHandle.port}/ws`,
|
||||
appVersion: "0.18.2",
|
||||
});
|
||||
|
||||
type TunnelEventFn = (event: {
|
||||
type: "connecting" | "ready" | "reconnecting" | "error" | "closed";
|
||||
url?: string;
|
||||
stability?: "ephemeral" | "stable";
|
||||
detail?: string;
|
||||
reason?: string;
|
||||
message?: string;
|
||||
recoverable?: boolean;
|
||||
}) => void;
|
||||
let emitTunnelEvent: TunnelEventFn | null = null;
|
||||
const closedExposureIds: string[] = [];
|
||||
const openedTargets: Array<{ host: string; port: number }> = [];
|
||||
// An IPv6-only service: the daemon must target ::1, not a fixed 127.0.0.1.
|
||||
const service = createNetServer((socket) => socket.destroy());
|
||||
const servicePort = await new Promise<number>((resolve, reject) => {
|
||||
service.once("error", reject);
|
||||
service.listen(0, "::1", () => {
|
||||
const address = service.address();
|
||||
if (address === null || typeof address === "string") {
|
||||
reject(new Error("Service has no TCP address"));
|
||||
return;
|
||||
}
|
||||
resolve(address.port);
|
||||
});
|
||||
});
|
||||
|
||||
daemonHandle.daemon.tunnelManager.registerProvider({
|
||||
id: "cloudflared",
|
||||
pluginId: "cloudflared-tunnel",
|
||||
label: "Cloudflare Tunnel",
|
||||
status: async () => ({ status: "available", detail: "quick tunnel" }),
|
||||
open(exposureId, target, callbacks) {
|
||||
openedTargets.push({ host: target.host, port: target.port });
|
||||
emitTunnelEvent = (event) =>
|
||||
callbacks.onEvent(event as Parameters<typeof callbacks.onEvent>[0]);
|
||||
return {
|
||||
async close() {
|
||||
closedExposureIds.push(exposureId);
|
||||
callbacks.onClosed();
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const scriptUpdates: Array<{
|
||||
workspaceId: string;
|
||||
scripts: Array<{
|
||||
scriptName: string;
|
||||
tunnel?: { state: string; url: string | null; error: string | null } | null;
|
||||
proxyUrl?: string | null;
|
||||
}>;
|
||||
}> = [];
|
||||
let unsubscribeScripts: (() => void) | null = null;
|
||||
|
||||
try {
|
||||
const response = await httpGetWithHost(
|
||||
daemonHandle.port,
|
||||
`missing.services.example.com:${daemonHandle.port}`,
|
||||
"/api/status",
|
||||
);
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.text()).toBe("404 Not Found");
|
||||
await client.connect();
|
||||
const subscription = client.observeEvents(["script_status_update"]);
|
||||
unsubscribeScripts = subscription.subscribe({
|
||||
snapshot: () => {},
|
||||
update: (message) => {
|
||||
if (message.type === "script_status_update") {
|
||||
scriptUpdates.push(message.payload);
|
||||
}
|
||||
},
|
||||
});
|
||||
await subscription.ready;
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "directory", path: workspaceDir },
|
||||
});
|
||||
const workspaceId = created.workspace?.id;
|
||||
if (!workspaceId) throw new Error("Expected workspace id");
|
||||
|
||||
daemonHandle.daemon.scriptRuntimeStore.set({
|
||||
workspaceId,
|
||||
scriptName: "web",
|
||||
type: "service",
|
||||
lifecycle: "running",
|
||||
terminalId: "term-web",
|
||||
exitCode: null,
|
||||
port: servicePort,
|
||||
});
|
||||
|
||||
const exposureId = buildServiceTunnelExposureId(workspaceId, "web");
|
||||
const opening = client.openWorkspaceScriptTunnel({
|
||||
workspaceId,
|
||||
scriptName: "web",
|
||||
providerId: "cloudflared",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(scriptUpdates.at(-1)?.scripts[0]?.tunnel).toMatchObject({
|
||||
state: "connecting",
|
||||
url: null,
|
||||
});
|
||||
});
|
||||
|
||||
emitTunnelEvent?.({
|
||||
type: "ready",
|
||||
url: "https://live-demo.trycloudflare.com",
|
||||
stability: "ephemeral",
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(scriptUpdates.at(-1)?.scripts[0]).toMatchObject({
|
||||
proxyUrl: "https://live-demo.trycloudflare.com",
|
||||
tunnel: {
|
||||
state: "ready",
|
||||
url: "https://live-demo.trycloudflare.com",
|
||||
},
|
||||
});
|
||||
});
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
error: null,
|
||||
script: { tunnel: { exposureId, state: "ready" } },
|
||||
});
|
||||
expect(openedTargets).toEqual([{ host: "::1", port: servicePort }]);
|
||||
|
||||
emitTunnelEvent?.({ type: "reconnecting", reason: "network switch" });
|
||||
await vi.waitFor(() => {
|
||||
expect(scriptUpdates.at(-1)?.scripts[0]).toMatchObject({
|
||||
proxyUrl: null,
|
||||
tunnel: {
|
||||
state: "reconnecting",
|
||||
url: "https://live-demo.trycloudflare.com",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
emitTunnelEvent?.({ type: "error", message: "edge timeout", recoverable: true });
|
||||
await vi.waitFor(() => {
|
||||
expect(scriptUpdates.at(-1)?.scripts[0]?.tunnel).toMatchObject({
|
||||
state: "error",
|
||||
error: "edge timeout",
|
||||
});
|
||||
});
|
||||
|
||||
await client.archiveWorkspace(workspaceId);
|
||||
await vi.waitFor(() => {
|
||||
expect(closedExposureIds).toContain(exposureId);
|
||||
expect(daemonHandle.daemon.tunnelManager.getExposure(exposureId)).toBeNull();
|
||||
});
|
||||
} finally {
|
||||
unsubscribeScripts?.();
|
||||
await client.close().catch(() => undefined);
|
||||
await daemonHandle.close();
|
||||
await new Promise<void>((resolve) => service.close(() => resolve()));
|
||||
await rm(workspaceDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -826,72 +966,7 @@ describe("paseo daemon bootstrap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("rolls back daemon listener when standalone service proxy startup fails", async () => {
|
||||
const occupiedServer = http.createServer((_req, res) => {
|
||||
res.end("occupied");
|
||||
});
|
||||
await new Promise<void>((resolve) => occupiedServer.listen(0, "127.0.0.1", resolve));
|
||||
const address = occupiedServer.address();
|
||||
if (!address || typeof address === "string") {
|
||||
throw new Error("Expected occupied TCP address");
|
||||
}
|
||||
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-standalone-rollback-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-"));
|
||||
await mkdir(paseoHome, { recursive: true });
|
||||
const config: PaseoDaemonConfig = {
|
||||
listen: "127.0.0.1:0",
|
||||
paseoHome,
|
||||
corsAllowedOrigins: [],
|
||||
hostnames: true,
|
||||
mcpEnabled: false,
|
||||
staticDir,
|
||||
mcpDebug: false,
|
||||
agentClients: createTestAgentClients(),
|
||||
agentStoragePath: path.join(paseoHome, "agents"),
|
||||
relayEnabled: false,
|
||||
appBaseUrl: "https://app.paseo.sh",
|
||||
openai: undefined,
|
||||
speech: undefined,
|
||||
serviceProxy: {
|
||||
standaloneListen: `127.0.0.1:${address.port}`,
|
||||
},
|
||||
};
|
||||
const daemon = await createPaseoDaemon(config, pino({ level: "silent" }), {
|
||||
builtinPlugins: new BuiltinPluginLoader(undefined, []),
|
||||
lazyTerminalWorker: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(daemon.start()).rejects.toThrow();
|
||||
await expect(fetch(`http://127.0.0.1:${daemon.port}/api/health`)).rejects.toThrow();
|
||||
} finally {
|
||||
await daemon.stop().catch(() => undefined);
|
||||
await new Promise<void>((resolve) => occupiedServer.close(() => resolve()));
|
||||
await rm(paseoHomeRoot, { recursive: true, force: true });
|
||||
await rm(staticDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("local service namespace misses never reach daemon APIs", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon({
|
||||
auth: { password: hashDaemonPassword("secret") },
|
||||
});
|
||||
try {
|
||||
const response = await httpGetWithHost(
|
||||
daemonHandle.port,
|
||||
`missing--repo.localhost:${daemonHandle.port}`,
|
||||
"/api/status",
|
||||
);
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.text()).toBe("404 Not Found");
|
||||
} finally {
|
||||
await daemonHandle.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("daemon websocket still upgrades when service proxy upgrade handler is mounted", async () => {
|
||||
test("daemon websocket upgrades cleanly on /ws", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon();
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${daemonHandle.port}/ws`);
|
||||
try {
|
||||
@@ -1019,58 +1094,12 @@ describe("paseo daemon bootstrap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("standalone listener exposes services only", async () => {
|
||||
const standalonePort = await findFreePort();
|
||||
const upstream = http.createServer((_req, res) => {
|
||||
res.end("service-ok");
|
||||
});
|
||||
await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
|
||||
const upstreamAddress = upstream.address();
|
||||
if (!upstreamAddress || typeof upstreamAddress === "string") {
|
||||
throw new Error("Expected upstream TCP address");
|
||||
}
|
||||
|
||||
const daemonHandle = await createTestPaseoDaemon({
|
||||
serviceProxy: { standaloneListen: `127.0.0.1:${standalonePort}` },
|
||||
});
|
||||
try {
|
||||
daemonHandle.daemon.serviceProxy.registerWorkspaceService({
|
||||
workspaceId: "workspace-standalone",
|
||||
projectSlug: "repo",
|
||||
branchName: "main",
|
||||
scriptName: "web",
|
||||
port: upstreamAddress.port,
|
||||
});
|
||||
|
||||
const serviceResponse = await httpGetWithHost(
|
||||
standalonePort,
|
||||
`web--repo.localhost:${standalonePort}`,
|
||||
"/",
|
||||
);
|
||||
expect(serviceResponse.status).toBe(200);
|
||||
expect(await serviceResponse.text()).toBe("service-ok");
|
||||
|
||||
for (const requestPath of ["/api/health", "/ws", "/mcp/agents", "/index.html", "/files/x"]) {
|
||||
const response = await httpGetWithHost(
|
||||
standalonePort,
|
||||
`daemon.localhost:${standalonePort}`,
|
||||
requestPath,
|
||||
);
|
||||
expect(response.status).toBe(404);
|
||||
}
|
||||
} finally {
|
||||
await daemonHandle.close();
|
||||
await new Promise<void>((resolve) => upstream.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
test("rolls back standalone listener without starting plugins when main listen fails", async () => {
|
||||
test("does not start plugins when main listen fails", async () => {
|
||||
const mainPort = await findFreePort();
|
||||
const occupiedMain = http.createServer((_req, res) => {
|
||||
res.end("occupied-main");
|
||||
});
|
||||
await new Promise<void>((resolve) => occupiedMain.listen(mainPort, "127.0.0.1", resolve));
|
||||
const standalonePort = await findFreePort();
|
||||
|
||||
const paseoHomeRoot = await mkdtemp(path.join(os.tmpdir(), "paseo-main-rollback-"));
|
||||
const paseoHome = path.join(paseoHomeRoot, ".paseo");
|
||||
@@ -1110,7 +1139,6 @@ export default function contribute(plugin: unknown) {
|
||||
appBaseUrl: "https://app.paseo.sh",
|
||||
openai: undefined,
|
||||
speech: undefined,
|
||||
serviceProxy: { standaloneListen: `127.0.0.1:${standalonePort}` },
|
||||
pluginsEnabled: !isPlatform("win32"),
|
||||
plugins: isPlatform("win32")
|
||||
? {}
|
||||
@@ -1123,7 +1151,6 @@ export default function contribute(plugin: unknown) {
|
||||
|
||||
try {
|
||||
await expect(daemon.start()).rejects.toThrow();
|
||||
await expect(fetch(`http://127.0.0.1:${standalonePort}/api/health`)).rejects.toThrow();
|
||||
if (!isPlatform("win32")) {
|
||||
await expect(readFile(pluginPidPath, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { unarchiveWorkspaceAgents } from "./workspace-archive-service.js";
|
||||
import { createRestartRecovery } from "./agent/restart-recovery/index.js";
|
||||
import { sendPromptToAgent, unarchiveAgentState } from "./agent/agent-prompt.js";
|
||||
@@ -27,7 +28,6 @@ import { createMcpHandler } from "@modelcontextprotocol/server";
|
||||
import { toNodeHandler } from "@modelcontextprotocol/node";
|
||||
import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
import { createBranchChangeRouteHandler } from "./script-route-branch-handler.js";
|
||||
|
||||
import {
|
||||
createDaemonListeners,
|
||||
@@ -185,7 +185,6 @@ import type {
|
||||
ProviderOverride,
|
||||
} from "./agent/provider-launch-config.js";
|
||||
import { type PersistedConfig } from "./persisted-config.js";
|
||||
import { createServiceProxySubsystem, type ServiceProxySubsystem } from "./service-proxy.js";
|
||||
import { releaseWorkspaceServicePortPlan } from "./workspace-service-port-registry.js";
|
||||
import { ScriptHealthMonitor } from "./script-health-monitor.js";
|
||||
import { createScriptStatusEmitter } from "./script-status-projection.js";
|
||||
@@ -234,7 +233,11 @@ import {
|
||||
} from "./hub/relationship-remote.js";
|
||||
import { DaemonExecutions } from "./hub/daemon-executions.js";
|
||||
import { PluginService } from "./plugins/index.js";
|
||||
import { TunnelManager } from "./tunnels/index.js";
|
||||
import {
|
||||
closeWorkspaceServiceTunnels,
|
||||
parseServiceTunnelExposureId,
|
||||
TunnelManager,
|
||||
} from "./tunnels/index.js";
|
||||
import { BuiltinPluginLoader } from "./plugins/builtin/index.js";
|
||||
import { ManagedPluginSources } from "./plugins/managed-source.js";
|
||||
|
||||
@@ -393,10 +396,7 @@ export interface PaseoDaemonConfig {
|
||||
relayPublicEndpoint?: string;
|
||||
relayUseTls?: boolean;
|
||||
relayPublicUseTls?: boolean;
|
||||
serviceProxy?: {
|
||||
publicBaseUrl: string | null;
|
||||
standaloneListen: string | null;
|
||||
};
|
||||
deprecatedConfigWarnings?: string[];
|
||||
webUi?: {
|
||||
enabled: boolean;
|
||||
distDir: string | null;
|
||||
@@ -443,7 +443,6 @@ export interface PaseoDaemon {
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
terminalManager: TerminalManager;
|
||||
serviceProxy: ServiceProxySubsystem;
|
||||
tunnelManager: TunnelManager;
|
||||
scriptRuntimeStore: WorkspaceScriptRuntimeStore;
|
||||
browserToolsBroker: BrowserToolsBroker;
|
||||
@@ -604,6 +603,9 @@ export async function createPaseoDaemon(
|
||||
const hostMachineKindReady = primeHostMachineKind();
|
||||
configureGitProcessPolicy(config.git ?? resolveGitProcessPolicy({ env: process.env }));
|
||||
const logger = rootLogger.child({ module: "bootstrap" });
|
||||
for (const warning of config.deprecatedConfigWarnings ?? []) {
|
||||
logger.warn(warning);
|
||||
}
|
||||
const obsoleteTimelineDirectory = path.join(config.paseoHome, "agent-timelines");
|
||||
await rm(obsoleteTimelineDirectory, { recursive: true, force: true }).catch((error) => {
|
||||
logger.warn(
|
||||
@@ -763,13 +765,6 @@ async function assemblePaseoDaemon({
|
||||
);
|
||||
applyTerminalAgentHookSetting({ store: daemonConfigStore, logger });
|
||||
|
||||
const serviceProxyPublicBaseUrl = config.serviceProxy?.publicBaseUrl
|
||||
? config.serviceProxy.publicBaseUrl
|
||||
: null;
|
||||
const serviceProxy = createServiceProxySubsystem({
|
||||
logger,
|
||||
publicBaseUrl: serviceProxyPublicBaseUrl,
|
||||
});
|
||||
const scriptRuntimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const workspaceSetupRuntime = new WorkspaceSetupRuntime();
|
||||
const workspaceArchiveOperations = new WorkspaceArchiveOperations();
|
||||
@@ -782,35 +777,31 @@ async function assemblePaseoDaemon({
|
||||
appBaseUrl = typeof value === "string" ? value : "https://app.paseo.sh";
|
||||
});
|
||||
let wsServer: VoiceAssistantWebSocketServer | null = null;
|
||||
let serviceProxyListenTarget: ListenTarget | null = null;
|
||||
const scriptHealthMonitor = new ScriptHealthMonitor({
|
||||
serviceProxy,
|
||||
onChange: createScriptStatusEmitter({
|
||||
sessions: () =>
|
||||
wsServer?.listSessions().map((session) => ({
|
||||
emit: (message) => session.emitServerMessage(message),
|
||||
})) ?? [],
|
||||
serviceProxy,
|
||||
runtimeStore: scriptRuntimeStore,
|
||||
daemonPort: () => (boundListenTarget?.type === "tcp" ? boundListenTarget.port : null),
|
||||
resolveWorkspaceDirectory: async (workspaceId) =>
|
||||
(await workspaceRegistry?.get(workspaceId))?.cwd ?? null,
|
||||
logger,
|
||||
serviceProxyPublicBaseUrl,
|
||||
}),
|
||||
});
|
||||
const handleBranchChange = createBranchChangeRouteHandler({
|
||||
serviceProxy,
|
||||
onRoutesChanged: (workspaceId) => {
|
||||
scriptHealthMonitor.invalidateWorkspace(workspaceId);
|
||||
},
|
||||
let scriptHealthMonitor!: ScriptHealthMonitor;
|
||||
const emitScriptStatus = createScriptStatusEmitter({
|
||||
sessions: () =>
|
||||
wsServer?.listSessions().map((session) => ({
|
||||
emit: (message) => session.emitServerMessage(message),
|
||||
})) ?? [],
|
||||
runtimeStore: scriptRuntimeStore,
|
||||
tunnelManager,
|
||||
resolveWorkspaceDirectory: async (workspaceId) =>
|
||||
(await workspaceRegistry?.get(workspaceId))?.cwd ?? null,
|
||||
resolveHealth: (workspaceId, scriptName) =>
|
||||
scriptHealthMonitor.getHealthForScript(workspaceId, scriptName),
|
||||
logger,
|
||||
});
|
||||
|
||||
// Service proxy classifies service hosts before daemon auth/route fallthrough.
|
||||
// Registered service hosts proxy directly; known service namespaces without a
|
||||
// route return 404 and never reach daemon APIs.
|
||||
app.use(serviceProxy.middleware());
|
||||
scriptHealthMonitor = new ScriptHealthMonitor({
|
||||
runtimeStore: scriptRuntimeStore,
|
||||
onChange: emitScriptStatus,
|
||||
});
|
||||
const unsubscribeServiceTunnelStatus = tunnelManager.subscribe((event) => {
|
||||
if (event.type !== "exposure.changed") return;
|
||||
const parsed = parseServiceTunnelExposureId(event.exposure.id);
|
||||
if (parsed) {
|
||||
void emitScriptStatus(parsed.workspaceId);
|
||||
}
|
||||
});
|
||||
|
||||
// Host allowlist / DNS rebinding protection (vite-like semantics).
|
||||
// Validate the accepted connection so extra TCP listeners also enforce the allowlist.
|
||||
@@ -866,10 +857,9 @@ async function assemblePaseoDaemon({
|
||||
// Local, harmless, and token-gated; deliberately skips daemon auth.
|
||||
app.post("/api/terminal-activity", express.json(), handleTerminalActivityRequest);
|
||||
|
||||
// Serve the bundled browser web UI when enabled. Mounted after service-proxy
|
||||
// classification and host/CORS handling, but before daemon bearer auth, so
|
||||
// static app files load without the daemon password while API/WebSocket calls
|
||||
// remain protected.
|
||||
// Serve the bundled browser web UI when enabled. Mounted after host/CORS
|
||||
// handling, but before daemon bearer auth, so static app files load without
|
||||
// the daemon password while API/WebSocket calls remain protected.
|
||||
mountWebUi(app, config, logger);
|
||||
|
||||
let localCredential: string | null = null;
|
||||
@@ -971,16 +961,6 @@ async function assemblePaseoDaemon({
|
||||
});
|
||||
daemonConfigStore.attachListeners(listeners);
|
||||
|
||||
// Script proxy WebSocket upgrade handler — must be registered before the
|
||||
// VoiceAssistantWebSocketServer attaches its own "upgrade" listener so that
|
||||
// script-bound upgrades are forwarded first. The handler is a no-op for
|
||||
// requests that don't match a registered script route.
|
||||
httpServer.on("upgrade", serviceProxy.upgradeHandler({ passthroughUnknown: true }));
|
||||
|
||||
if (config.serviceProxy?.standaloneListen) {
|
||||
serviceProxyListenTarget = parseListenString(config.serviceProxy.standaloneListen);
|
||||
}
|
||||
|
||||
const agentStorage = new AgentStorage(config.agentStoragePath, logger);
|
||||
const projectRegistry = new FileBackedProjectRegistry(
|
||||
path.join(config.paseoHome, "projects", "projects.json"),
|
||||
@@ -1083,6 +1063,15 @@ async function assemblePaseoDaemon({
|
||||
hasActiveVoiceTools,
|
||||
resolvePaseoToolPolicy: (provider) =>
|
||||
resolvePaseoToolPolicy(provider, daemonConfigStore.get().providers),
|
||||
resolveWorkspaceProjectResourceApproval: async (workspaceId, cwd) => {
|
||||
const workspace = await workspaceRegistry.get(workspaceId);
|
||||
return (
|
||||
workspace !== null &&
|
||||
workspace.archivedAt === null &&
|
||||
workspace.untrustedSource === undefined &&
|
||||
createRealpathAwarePathMatcher(workspace.cwd)(cwd)
|
||||
);
|
||||
},
|
||||
logger,
|
||||
});
|
||||
const syncPluginProviders = () => {
|
||||
@@ -1138,6 +1127,7 @@ async function assemblePaseoDaemon({
|
||||
await workspaceLabelService.initialize();
|
||||
logger.info({ elapsed: elapsed() }, "Workspace registries bootstrapped");
|
||||
const teardownArchivedWorkspaceRuntime = (workspaceId: string): void => {
|
||||
void closeWorkspaceServiceTunnels(tunnelManager, workspaceId);
|
||||
scriptRuntimeStore.removeForWorkspace(workspaceId);
|
||||
releaseWorkspaceServicePortPlan(workspaceId);
|
||||
};
|
||||
@@ -1332,11 +1322,9 @@ async function assemblePaseoDaemon({
|
||||
emit: emitExternalSessionMessage,
|
||||
sessionLogger: logger,
|
||||
terminalManager,
|
||||
serviceProxy,
|
||||
scriptRuntimeStore,
|
||||
getDaemonTcpPort: () => (boundListenTarget?.type === "tcp" ? boundListenTarget.port : null),
|
||||
getDaemonTcpHost: () => (boundListenTarget?.type === "tcp" ? boundListenTarget.host : null),
|
||||
serviceProxyPublicBaseUrl,
|
||||
onScriptsChanged: null,
|
||||
},
|
||||
input,
|
||||
@@ -1470,6 +1458,8 @@ async function assemblePaseoDaemon({
|
||||
const workspace = await workspaceProvisioning.createWorkspaceForDirectory(
|
||||
input.cwd,
|
||||
resolveFirstAgentPromptTitle(input.firstAgentContext),
|
||||
undefined,
|
||||
{ inheritWorktreeProject: true },
|
||||
);
|
||||
workspaceAutoName.scheduleForDirectory({
|
||||
workspaceId: workspace.workspaceId,
|
||||
@@ -1672,16 +1662,14 @@ async function assemblePaseoDaemon({
|
||||
return workspace;
|
||||
},
|
||||
workspaceScripts: createWorkspaceScriptsService({
|
||||
serviceProxy,
|
||||
scriptRuntimeStore,
|
||||
terminalManager,
|
||||
tunnelManager,
|
||||
workspaceRegistry,
|
||||
projectRegistry,
|
||||
workspaceRuntimeStore,
|
||||
getDaemonTcpPort: () => (boundListenTarget?.type === "tcp" ? boundListenTarget.port : null),
|
||||
getDaemonTcpHost: () => (boundListenTarget?.type === "tcp" ? boundListenTarget.host : null),
|
||||
serviceProxyPublicBaseUrl,
|
||||
resolveScriptHealth: (hostname) => scriptHealthMonitor.getHealthForHostname(hostname),
|
||||
resolveScriptHealth: (workspaceId, scriptName) =>
|
||||
scriptHealthMonitor.getHealthForScript(workspaceId, scriptName),
|
||||
logger,
|
||||
emit: (message) => wsServer?.broadcast(wrapSessionMessage(message)),
|
||||
publishStatusUpdate: (message) => wsServer?.publishScriptStatusUpdate(message),
|
||||
@@ -1714,8 +1702,8 @@ async function assemblePaseoDaemon({
|
||||
const getCurrentToolsConfig = () => resolveDaemonToolsFromMutableConfig(daemonConfigStore.get());
|
||||
let mcpEnabled = config.mcpEnabled ?? true;
|
||||
const setAgentProviderToolsEnabled = (enabled: boolean) => {
|
||||
agentProviderRuntime.setPaseoToolCatalog(
|
||||
enabled ? createPaseoAgentToolManifest(createAgentToolHostDependencies({})) : null,
|
||||
agentProviderRuntime.setPaseoToolCatalogFactory(
|
||||
enabled ? () => createPaseoAgentToolManifest(createAgentToolHostDependencies({})) : null,
|
||||
);
|
||||
};
|
||||
agentManager.setPaseoToolCatalogFactory(createAgentToolCatalog);
|
||||
@@ -1881,20 +1869,6 @@ async function assemblePaseoDaemon({
|
||||
}),
|
||||
]);
|
||||
localCredential = nextLocalCredential;
|
||||
if (serviceProxyListenTarget) {
|
||||
const boundServiceProxyTarget = await serviceProxy.startStandalone({
|
||||
listenTarget: serviceProxyListenTarget,
|
||||
});
|
||||
serviceProxyListenTarget = boundServiceProxyTarget;
|
||||
logger.info(
|
||||
{
|
||||
listen: formatListenTarget(serviceProxyListenTarget),
|
||||
publicBaseUrl: serviceProxyPublicBaseUrl,
|
||||
elapsed: elapsed(),
|
||||
},
|
||||
"Service proxy listening",
|
||||
);
|
||||
}
|
||||
|
||||
// Start main HTTP server
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -2013,12 +1987,12 @@ async function assemblePaseoDaemon({
|
||||
workspaceRegistry,
|
||||
scheduleService,
|
||||
checkoutDiffManager,
|
||||
serviceProxy,
|
||||
scriptRuntimeStore,
|
||||
handleBranchChange,
|
||||
undefined,
|
||||
() => (boundListenTarget?.type === "tcp" ? boundListenTarget.port : null),
|
||||
() => (boundListenTarget?.type === "tcp" ? boundListenTarget.host : null),
|
||||
(hostname) => scriptHealthMonitor.getHealthForHostname(hostname),
|
||||
(workspaceId, scriptName) =>
|
||||
scriptHealthMonitor.getHealthForScript(workspaceId, scriptName),
|
||||
workspaceGitService,
|
||||
github,
|
||||
config.pushNotificationSender,
|
||||
@@ -2045,7 +2019,6 @@ async function assemblePaseoDaemon({
|
||||
daemonConfigStore.get().relay?.requireProtectedSecurity === true,
|
||||
}),
|
||||
},
|
||||
serviceProxyPublicBaseUrl,
|
||||
browserToolsBroker,
|
||||
hubRelationships,
|
||||
workspaceSetupRuntime,
|
||||
@@ -2123,10 +2096,10 @@ async function assemblePaseoDaemon({
|
||||
localCredential = null;
|
||||
await deleteLocalCredential(config.paseoHome);
|
||||
unsubscribePluginProviders();
|
||||
unsubscribeServiceTunnelStatus();
|
||||
await tunnelManager.closeAll().catch(() => undefined);
|
||||
unsubscribeObservedUsage();
|
||||
await pluginRuntime.stopAllPlugins().catch(() => undefined);
|
||||
await serviceProxy.stopStandalone().catch(() => undefined);
|
||||
await agentProviderRuntime.shutdown().catch(() => undefined);
|
||||
await listeners.stop();
|
||||
await loopbackAgentEndpoint?.stop().catch(() => undefined);
|
||||
@@ -2152,6 +2125,7 @@ async function assemblePaseoDaemon({
|
||||
// they serve has been closed, further down.
|
||||
unsubscribePluginProviders();
|
||||
unsubscribeObservedUsage();
|
||||
unsubscribeServiceTunnelStatus();
|
||||
await hubRelationships.stop();
|
||||
workspaceReconciliation.dispose();
|
||||
scriptHealthMonitor.stop();
|
||||
@@ -2222,7 +2196,6 @@ async function assemblePaseoDaemon({
|
||||
await wsServer.close();
|
||||
}
|
||||
forgeResolver.dispose();
|
||||
await serviceProxy.stopStandalone();
|
||||
await loopbackAgentEndpoint?.stop();
|
||||
// Force-drop remaining sockets so httpServer.close() resolves promptly.
|
||||
// We've already closed wsServer (which sent ws-layer close frames) and
|
||||
@@ -2254,7 +2227,6 @@ async function assemblePaseoDaemon({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
terminalManager,
|
||||
serviceProxy,
|
||||
tunnelManager,
|
||||
scriptRuntimeStore,
|
||||
browserToolsBroker,
|
||||
|
||||
@@ -87,7 +87,6 @@ test("daemon resolves human and managed CLI workspace ownership", async () => {
|
||||
});
|
||||
expect(attachedAgent.workspaceId).toBe(firstWorkspaceId);
|
||||
expect(attachedAgent.cwd).toBe(cwd);
|
||||
expect(attachedAgent.labels[PARENT_AGENT_ID_LABEL]).toBeUndefined();
|
||||
expect(await workspaceIds(client)).toEqual(idsBeforeAttach);
|
||||
|
||||
await expect(
|
||||
@@ -120,12 +119,6 @@ test("daemon resolves human and managed CLI workspace ownership", async () => {
|
||||
expect(crossWorkspaceChild.workspaceId).toBe(secondWorkspaceId);
|
||||
expect(crossWorkspaceChild.cwd).toBe(otherCwd);
|
||||
expect(crossWorkspaceChild.labels[PARENT_AGENT_ID_LABEL]).toBe(firstAgent.id);
|
||||
|
||||
const { entries } = await client.fetchAgents();
|
||||
const childIds = entries
|
||||
.filter(({ agent }) => agent.labels[PARENT_AGENT_ID_LABEL] === firstAgent.id)
|
||||
.map(({ agent }) => agent.id);
|
||||
expect(new Set(childIds)).toEqual(new Set([sameWorkspaceChild.id, crossWorkspaceChild.id]));
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
|
||||
@@ -37,6 +37,8 @@ export const DAEMON_SETTING_ENV_KEYS = [
|
||||
"PASEO_RELAY_PUBLIC_ENDPOINT",
|
||||
"PASEO_RELAY_PUBLIC_USE_TLS",
|
||||
"PASEO_RELAY_USE_TLS",
|
||||
// COMPAT(serviceProxyRemoved): added in v0.19.0, remove after 2027-06-01.
|
||||
// Kept here so startup deprecation checks can detect and warn on legacy env vars.
|
||||
"PASEO_SERVICE_PROXY_ENABLED",
|
||||
"PASEO_SERVICE_PROXY_LISTEN",
|
||||
"PASEO_SERVICE_PROXY_PUBLIC_BASE_URL",
|
||||
|
||||
@@ -155,69 +155,49 @@ describe("daemon relay config", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("daemon service proxy config", () => {
|
||||
describe("deprecated daemon serviceProxy config", () => {
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
test("loads public base URL from env before persisted config", async () => {
|
||||
test("parses legacy daemon.serviceProxy without crashing and emits a deprecation warning", async () => {
|
||||
const home = await createPaseoHome({
|
||||
version: 1,
|
||||
daemon: {
|
||||
serviceProxy: {
|
||||
publicBaseUrl: "https://persisted.example.com",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const config = loadConfig(home, {
|
||||
env: { PASEO_SERVICE_PROXY_PUBLIC_BASE_URL: "https://env.example.com/" },
|
||||
});
|
||||
|
||||
expect(config.serviceProxy).toEqual({
|
||||
publicBaseUrl: "https://env.example.com",
|
||||
standaloneListen: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("does not synthesize a standalone service listener from enabled true", async () => {
|
||||
const home = await createPaseoHome({
|
||||
version: 1,
|
||||
daemon: { serviceProxy: { enabled: true } },
|
||||
});
|
||||
|
||||
expect(loadConfig(home, { env: {} }).serviceProxy).toEqual({
|
||||
publicBaseUrl: null,
|
||||
standaloneListen: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("enabled false suppresses optional service proxy layers only", async () => {
|
||||
const home = await createPaseoHome({
|
||||
version: 1,
|
||||
daemon: {
|
||||
serviceProxy: {
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
listen: "127.0.0.1:9999",
|
||||
publicBaseUrl: "https://persisted.example.com",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(loadConfig(home, { env: {} }).serviceProxy).toEqual({
|
||||
publicBaseUrl: null,
|
||||
standaloneListen: null,
|
||||
});
|
||||
const config = loadConfig(home, { env: {} });
|
||||
|
||||
expect(config.deprecatedConfigWarnings).toEqual([
|
||||
"`daemon.serviceProxy` was removed in favor of tunnel providers and is now ignored.",
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects invalid PASEO_SERVICE_PROXY_PUBLIC_BASE_URL values", async () => {
|
||||
test("ignores legacy PASEO_SERVICE_PROXY_* env vars and records a deprecation warning", async () => {
|
||||
const home = await createPaseoHome({ version: 1 });
|
||||
|
||||
expect(() =>
|
||||
loadConfig(home, {
|
||||
env: { PASEO_SERVICE_PROXY_PUBLIC_BASE_URL: "not-a-url" },
|
||||
}),
|
||||
).toThrow("Invalid PASEO_SERVICE_PROXY_PUBLIC_BASE_URL: not-a-url");
|
||||
const config = loadConfig(home, {
|
||||
env: {
|
||||
PASEO_SERVICE_PROXY_ENABLED: "false",
|
||||
PASEO_SERVICE_PROXY_PUBLIC_BASE_URL: "not-even-a-url",
|
||||
},
|
||||
});
|
||||
|
||||
expect(config.deprecatedConfigWarnings).toEqual([
|
||||
"PASEO_SERVICE_PROXY_ENABLED, PASEO_SERVICE_PROXY_PUBLIC_BASE_URL were removed in favor of tunnel providers and are now ignored.",
|
||||
]);
|
||||
});
|
||||
|
||||
test("emits no deprecation warnings when serviceProxy config and env vars are absent", async () => {
|
||||
const home = await createPaseoHome({ version: 1 });
|
||||
|
||||
expect(loadConfig(home, { env: {} }).deprecatedConfigWarnings).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -286,11 +286,6 @@ interface ResolvedRelay {
|
||||
publicUseTls: boolean;
|
||||
}
|
||||
|
||||
interface ResolvedServiceProxy {
|
||||
publicBaseUrl: string | null;
|
||||
standaloneListen: string | null;
|
||||
}
|
||||
|
||||
function resolveTlsFromEnv(
|
||||
envValue: string | undefined,
|
||||
persistedValue: boolean | undefined,
|
||||
@@ -356,39 +351,31 @@ interface ResolvedVoiceLlm {
|
||||
model: string | null;
|
||||
}
|
||||
|
||||
function resolveServiceProxyPublicBaseUrl(value: string | null): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new URL(value).toString().replace(/\/$/, "");
|
||||
} catch {
|
||||
throw new Error(`Invalid PASEO_SERVICE_PROXY_PUBLIC_BASE_URL: ${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveServiceProxyConfig(
|
||||
// COMPAT(serviceProxyRemoved): added in v0.19.0, remove after 2027-06-01.
|
||||
// Warn and ignore legacy serviceProxy config/env instead of failing daemon startup.
|
||||
function collectDeprecatedConfigWarnings(
|
||||
env: NodeJS.ProcessEnv,
|
||||
persisted: ReturnType<typeof loadPersistedConfig>,
|
||||
): ResolvedServiceProxy {
|
||||
const enabledShim =
|
||||
parseBooleanEnv(env.PASEO_SERVICE_PROXY_ENABLED) ?? persisted.daemon?.serviceProxy?.enabled;
|
||||
// COMPAT(serviceProxyEnabled): added 2026-06-02, remove after 2026-12-02.
|
||||
// `enabled=false` used to disable the separate service proxy listener. Localhost
|
||||
// service proxying is now always enabled; this only suppresses optional layers.
|
||||
const optionalLayersEnabled = enabledShim !== false;
|
||||
const publicBaseUrl = optionalLayersEnabled
|
||||
? resolveServiceProxyPublicBaseUrl(
|
||||
env.PASEO_SERVICE_PROXY_PUBLIC_BASE_URL ??
|
||||
persisted.daemon?.serviceProxy?.publicBaseUrl ??
|
||||
null,
|
||||
)
|
||||
: null;
|
||||
const standaloneListen = optionalLayersEnabled
|
||||
? (env.PASEO_SERVICE_PROXY_LISTEN ?? persisted.daemon?.serviceProxy?.listen ?? null)
|
||||
: null;
|
||||
): string[] {
|
||||
const warnings: string[] = [];
|
||||
const hasPersistedServiceProxy = persisted.daemon?.serviceProxy !== undefined;
|
||||
const legacyEnvVars = [
|
||||
"PASEO_SERVICE_PROXY_ENABLED",
|
||||
"PASEO_SERVICE_PROXY_LISTEN",
|
||||
"PASEO_SERVICE_PROXY_PUBLIC_BASE_URL",
|
||||
].filter((key) => env[key] !== undefined);
|
||||
|
||||
return { publicBaseUrl, standaloneListen };
|
||||
if (hasPersistedServiceProxy) {
|
||||
warnings.push(
|
||||
"`daemon.serviceProxy` was removed in favor of tunnel providers and is now ignored.",
|
||||
);
|
||||
}
|
||||
if (legacyEnvVars.length > 0) {
|
||||
warnings.push(
|
||||
`${legacyEnvVars.join(", ")} ${legacyEnvVars.length === 1 ? "was" : "were"} removed in favor of tunnel providers and ${legacyEnvVars.length === 1 ? "is" : "are"} now ignored.`,
|
||||
);
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
|
||||
interface ResolvedWebUi {
|
||||
@@ -680,7 +667,7 @@ export function resolveConfigFromPersisted(
|
||||
relayPublicEndpoint: relay.publicEndpoint,
|
||||
relayUseTls: relay.useTls,
|
||||
relayPublicUseTls: relay.publicUseTls,
|
||||
serviceProxy: resolveServiceProxyConfig(env, persisted),
|
||||
deprecatedConfigWarnings: collectDeprecatedConfigWarnings(env, persisted),
|
||||
webUi: resolveWebUiConfig(paseoHome, env, cli, persisted),
|
||||
auth: resolveAuthConfig(env, persisted),
|
||||
openai,
|
||||
@@ -829,15 +816,6 @@ function resolveServiceAndWebUiOverridePaths(
|
||||
cli: CliConfigOverrides | undefined,
|
||||
): string[] {
|
||||
const paths: string[] = [];
|
||||
const serviceProxyEnabled = parseBooleanEnv(env.PASEO_SERVICE_PROXY_ENABLED);
|
||||
if (serviceProxyEnabled !== undefined) paths.push("daemon.serviceProxy.enabled");
|
||||
if (env.PASEO_SERVICE_PROXY_LISTEN !== undefined || serviceProxyEnabled === false) {
|
||||
paths.push("daemon.serviceProxy.listen");
|
||||
}
|
||||
if (env.PASEO_SERVICE_PROXY_PUBLIC_BASE_URL !== undefined || serviceProxyEnabled === false) {
|
||||
paths.push("daemon.serviceProxy.publicBaseUrl");
|
||||
}
|
||||
|
||||
if (cli?.webUiEnabled !== undefined || parseBooleanEnv(env.PASEO_WEB_UI_ENABLED) !== undefined) {
|
||||
paths.push("features.webUi.enabled");
|
||||
}
|
||||
|
||||
@@ -590,6 +590,73 @@ test("agent.config.apply sets an option that has no control and the next snapsho
|
||||
}
|
||||
});
|
||||
|
||||
test("listing commands after importing archived history does not call the provider", async () => {
|
||||
const clients = createTestAgentClients();
|
||||
const codex = clients.codex as AgentClient;
|
||||
const listed: string[] = [];
|
||||
// Records which session phase lists commands; behavior is the fake client's.
|
||||
function recordListCommands(session: AgentSession, phase: string): AgentSession {
|
||||
const list = session.listCommands?.bind(session);
|
||||
session.listCommands = async () => {
|
||||
listed.push(phase);
|
||||
return (await list?.()) ?? [];
|
||||
};
|
||||
return session;
|
||||
}
|
||||
const recordingCodex: AgentClient = Object.create(codex, {
|
||||
createSession: {
|
||||
value: async (...args: Parameters<AgentClient["createSession"]>) =>
|
||||
recordListCommands(await codex.createSession(...args), "created"),
|
||||
},
|
||||
resumeSession: {
|
||||
value: async (...args: Parameters<AgentClient["resumeSession"]>) =>
|
||||
recordListCommands(await codex.resumeSession(...args), "resumed"),
|
||||
},
|
||||
});
|
||||
const root = mkdtempSync(path.join(tmpdir(), "paseo-archived-commands-"));
|
||||
const cwd = path.join(root, "repo");
|
||||
const staticDir = path.join(root, "static");
|
||||
mkdirSync(cwd);
|
||||
mkdirSync(staticDir);
|
||||
const startDaemon = () =>
|
||||
createTestPaseoDaemon({
|
||||
agentClients: { ...clients, codex: recordingCodex },
|
||||
paseoHomeRoot: root,
|
||||
staticDir,
|
||||
cleanup: false,
|
||||
});
|
||||
const connectClient = (port: number) =>
|
||||
new DaemonClient({ url: `ws://127.0.0.1:${port}/ws`, appVersion: "0.1.82" });
|
||||
let daemon = await startDaemon();
|
||||
let client = connectClient(daemon.port);
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const agent = await client.createAgent({ provider: "codex", cwd, title: "Archived agent" });
|
||||
await client.archiveAgent(agent.id);
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
|
||||
// Simulate an archived record from before timelines were stored in SQLite.
|
||||
rmSync(path.join(daemon.paseoHome, "paseo.db"));
|
||||
daemon = await startDaemon();
|
||||
client = connectClient(daemon.port);
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const timeline = await client.fetchAgentTimeline(agent.id, { limit: 5 });
|
||||
expect(timeline.error).toBeNull();
|
||||
const commands = await client.listCommands(agent.id);
|
||||
|
||||
expect(listed).toEqual([]);
|
||||
expect(commands).toMatchObject({ commands: [], error: `Agent not found: ${agent.id}` });
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("createAgent with background initialPrompt returns a running snapshot before turn completion", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user