Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 4abe1e9ca0 fix(app): insert dictation at the composer cursor
Use the live editor selection when a transcript arrives so dictated words go into the paragraph the user is editing.
2026-11-30 13:31:03 +00:00
236 changed files with 6080 additions and 10091 deletions
+1
View File
@@ -45,6 +45,7 @@ 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 |
+4 -7
View File
@@ -249,8 +249,7 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
mcp: { enabled: boolean, injectIntoAgents: boolean },
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -352,14 +351,12 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
+10 -8
View File
@@ -440,13 +440,15 @@ 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` | 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. |
| 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.
`<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.
@@ -503,7 +505,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/*`, and the WebSocket upgrade. 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/*`, the WebSocket upgrade, and service-proxy routes. Static files load without daemon bearer auth; API and WebSocket calls still enforce auth.
The served app auto-bootstraps a connection to the same origin, so opening `http://localhost:6767/` directly usually skips the Add Host step.
-8
View File
@@ -32,11 +32,6 @@ 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
@@ -53,9 +48,6 @@ through rebinds. For numeric injection, use AppleScript physical key codes (for
25 for 9); `keystroke "9"` did not deliver a digit in the QA session.
Simulator exposes a virtual `GCKeyboard` even with Connect Hardware Keyboard off.
Verify the iOS absence case on a physical iPhone.
Xcode 27.2 has Device Hub in place of Simulator. AppleScript keystrokes reach the
device only while its view has Mac focus. Give it focus with a real mouse click
(a `CGEvent`); keystrokes sent elsewhere drive Device Hub's own controls.
Never register Backspace: it would take deletion away from text fields. Changes
to the native module require a native rebuild; an over-the-air JavaScript update
-10
View File
@@ -72,11 +72,6 @@ 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.
@@ -132,11 +127,6 @@ 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.
+6 -38
View File
@@ -22,31 +22,6 @@ 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
@@ -66,9 +41,8 @@ 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 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.
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.
## Native
@@ -83,9 +57,6 @@ 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
@@ -98,8 +69,7 @@ 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 and the ring's cadence, the frames a ring draws beside an
idle chat, reduced motion, and a hidden tab. Run it with
the indicator components, the loader's cadence, 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.
@@ -107,8 +77,6 @@ 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. 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.
`/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.
+141
View File
@@ -0,0 +1,141 @@
# Service Proxy
Paseo proxies HTTP traffic to services running inside your workspaces. Localhost service URLs are always enabled; optional public aliases and a separate service-only listener can be layered on through config.
## How it works
When a `paseo.json` script of `"type": "service"` starts, Paseo assigns it a local port and registers a route in the service proxy. Incoming requests whose `Host` header matches the script's generated hostname are forwarded to that port. HTTP requests, WebSocket upgrades, and service health checks select the reachable IPv4 or IPv6 loopback address. Services can bind to `127.0.0.1` or `::1` without changing their proxy URL.
The generated hostname is built from the script name, branch, and project:
```
<script>--<branch>--<project>.localhost
```
If the branch is `main` or `master`, the branch segment is omitted:
```
<script>--<project>.localhost
```
**Example:** a script named `dev` in the `miniweb` project on branch `feature/auth` would be reachable at:
```
dev--feature-auth--miniweb.localhost
```
Local and public routes use one combined leftmost label (`script--branch--project`). This keeps the hostname compatible with normal single-level wildcard DNS and TLS. If the combined label would exceed DNS's 63-character label limit, Paseo truncates it with a deterministic hash suffix to avoid collisions.
## Managing workspace scripts
Configured `paseo.json` scripts can be managed without addressing their backing terminal directly:
```bash
paseo script ls [--cwd <path> | --workspace <workspace-id>]
paseo script start <name> [--cwd <path> | --workspace <workspace-id>]
paseo script stop <name> [--cwd <path> | --workspace <workspace-id>]
```
The commands return the same script metadata shown by the workspace: lifecycle, service port, proxy URLs, health, exit code, and supervised terminal ID. `stop` terminates the managed terminal rather than only removing the proxy route, so normal script lifecycle cleanup remains authoritative. MCP exposes matching `list_workspace_scripts`, `start_workspace_script`, and `stop_workspace_script` tools; those require an explicit workspace ID.
## Configuration
Add a `serviceProxy` block under `daemon` in `~/.paseo/config.json`:
```json
{
"version": 1,
"daemon": {
"serviceProxy": {
"listen": "0.0.0.0:8080",
"publicBaseUrl": "https://paseoapps.my.domain.com"
}
}
}
```
| Field | Required | Description |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `listen` | No | Starts a separate service-only listener at this address. If omitted, services are still reachable on the daemon listener via localhost hosts. |
| `publicBaseUrl` | No | Adds public service host aliases and public service links. If omitted, links use localhost addresses only. |
`enabled` is accepted for old configs but no longer enables a mode. `enabled: false` suppresses optional `listen`/`publicBaseUrl` layers only; localhost service proxying remains always enabled.
## DNS and reverse proxy setup
For generated URLs to be reachable, you need wildcard DNS pointing to the machine running the Paseo daemon.
**Example:** to expose services at `https://dev--miniweb.paseoapps.my.domain.com` where the daemon host is `10.1.1.1`:
1. Configure a wildcard DNS record:
```
*.paseoapps.my.domain.com → 10.1.1.1
```
2. Set `publicBaseUrl` to `https://paseoapps.my.domain.com` in your config.
3. If you put a reverse proxy (nginx, Caddy, Traefik, etc.) in front of Paseo, point it at either the daemon listener or the optional service-only listener and ensure it forwards the `Host` header unchanged. The proxy uses the `Host` header to route requests to the correct service — rewriting it will break routing.
Public service URLs expose the workspace service itself. Daemon password authentication protects daemon APIs; it does not protect proxied dev services.
If the same reverse proxy serves the daemon web UI over HTTPS, it must also set `X-Forwarded-Proto` so the web UI can auto-connect with `wss://`. The daemon trusts forwarded headers from loopback proxies by default. If your proxy reaches the daemon from another address, configure the proxy ranges explicitly:
```json
{
"version": 1,
"daemon": {
"trustedProxies": ["loopback", "172.16.0.0/12"]
}
}
```
`PASEO_TRUSTED_PROXIES` accepts the same comma-separated values, for example `loopback,172.16.0.0/12`. Use `true` only when the final trusted proxy overwrites client-supplied `X-Forwarded-*` headers.
Nginx example:
```nginx
server {
listen 443 ssl;
server_name *.paseoapps.my.domain.com;
location / {
proxy_pass http://10.1.1.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Nginx's `$host` drops the port. If you terminate on a non-default port, use `$http_host` instead so the port survives — that is what "forwards the `Host` header unchanged" means here.
## Forwarded headers
Paseo sets these when it forwards a request to a workspace service:
| Header | Value |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Forwarded-Host` | The `Host` header verbatim, including the port when the client used one |
| `X-Forwarded-Proto` | The request scheme (`http` on the WebSocket upgrade path) |
| `X-Forwarded-For` | The immediate peer address. Replaces any existing chain, so behind your own reverse proxy this is the proxy's address, not the client's |
| `X-Forwarded-Port` | The port from the `Host` header when it has one, otherwise whatever your proxy already set |
`X-Forwarded-Port` follows the same trust rule as `X-Forwarded-Host`: the authority Paseo observed wins. When the `Host` header carries a port, that port is reported and replaces any inbound `X-Forwarded-Port`, so a client cannot forge one. When `Host` carries no port there is nothing to observe, so a value your reverse proxy set survives untouched — that is the case where nginx's `$host` drops the port and `X-Forwarded-Port` is the only source. Paseo never derives the port from the scheme. Any other `X-Forwarded-*` header your proxy sends is passed through untouched.
Services that build absolute URLs should prefer `Host` or `X-Forwarded-Host`.
### The forwarded authority is not authenticated
Route lookup normalizes the port away before matching a service hostname, so a client can address the daemon with any port in `Host` and still reach the service. That port is what lands in `X-Forwarded-Host` and `X-Forwarded-Port`. Paseo also does not check whether an inbound `X-Forwarded-Port` came from a proxy in `trustedProxies` — when `Host` carries no port, a client-supplied value is passed through.
Treat the forwarded authority as client-influenced input. A service that builds password reset links, absolute redirects, or cached URLs from it should pin its own public origin in configuration rather than deriving one from request headers. This is not specific to `X-Forwarded-Port`: the `Host` header has always carried a client-chosen port.
## Environment variables
The listen address and public base URL can also be set via environment variables, which take precedence over `config.json`:
| Variable | Description |
| ------------------------------------- | ------------------------------------------------------------------------- |
| `PASEO_SERVICE_PROXY_ENABLED` | Compatibility shim; `false` suppresses optional public/listen layers only |
| `PASEO_SERVICE_PROXY_LISTEN` | Starts the optional service-only listener, e.g. `0.0.0.0:8080` |
| `PASEO_SERVICE_PROXY_PUBLIC_BASE_URL` | Adds public service aliases and links |
@@ -2,8 +2,7 @@ import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
import { openSettingsSection } from "../support/helpers/settings";
test("shows Pure black in the appearance picker", async ({ page }, testInfo) => {
await page.goto("/settings");
@@ -97,43 +96,3 @@ test("applies the interface font size to settings text", async ({ page }) => {
await expect(contentSizeInput).toHaveValue("21");
await expect(sectionTitle).toHaveCSS("font-size", "10px");
});
test("applies the content font size to an already-open chat", async ({ page }) => {
const agent = await seedMockAgentWorkspace({ repoPrefix: "chat-font-size-", title: "Font size" });
const prompt = "Existing message for the font size check";
try {
await agent.client.sendAgentMessage(agent.agentId, prompt);
await agent.client.waitForFinish(agent.agentId, 30_000);
await openAgentRoute(page, agent);
const userText = page.getByText(prompt, { exact: true });
const assistantText = page.getByTestId("assistant-message").first().locator("p").first();
const initialSize = await test.step("Read both messages at the default size", async () => {
await expect(userText).toBeVisible();
await expect(assistantText).toBeVisible();
return userText.evaluate((element) => getComputedStyle(element).fontSize);
});
const timeOrigin = await page.evaluate(() => performance.timeOrigin);
await test.step("Increase Content font size and return to the same chat", async () => {
await page.getByTestId("sidebar-settings").filter({ visible: true }).first().click();
await openSettingsSection(page, "appearance");
const size = page.getByRole("textbox", { name: "Content font size", exact: true });
await size.fill("21");
await size.press("Tab");
await expect(size).toHaveValue("21");
await clickSettingsBackToWorkspace(page);
});
await test.step("Read both messages at the new size without reloading", async () => {
expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
await expect(assistantText).not.toHaveCSS("font-size", initialSize);
const updatedSize = await assistantText.evaluate(
(element) => getComputedStyle(element).fontSize,
);
await expect(userText).toHaveCSS("font-size", updatedSize);
});
} finally {
await agent.cleanup();
}
});
@@ -1,11 +1,5 @@
import { expect, test, type Page } from "../support/fixtures";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSessionRowArchived,
@@ -146,47 +140,6 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
}
test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit");
+1 -28
View File
@@ -10,7 +10,6 @@ import {
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser,
openRelayPairingFromSetup,
closeRelayPairing,
@@ -25,7 +24,6 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setHostTools,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
@@ -428,30 +426,6 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
}
});
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
const host = await startSetupHost("tool-groups");
try {
await setHostTools(host, { groups: { schedules: false, browser: true } });
await openAppAsNewUser(page, host);
await expectSetupStep(page, "Welcome to Paseo");
await goToSetupStep(page, "Orchestration");
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
// Setup offers only the main switch; tool groups live in Settings.
await expect(
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
).toHaveCount(0);
await continueSetup(page);
await expectSetupStep(page, "Take your agents with you");
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
} finally {
await host.close();
}
});
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills");
@@ -489,7 +463,6 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
@@ -498,7 +471,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects");
await primary("Continue").click();
// The host has tools off; the setup switch still starts on.
// The setup host starts with Paseo tools off; the switch starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -8,13 +8,11 @@ import {
import {
captureLoaderSteps,
freezeAnimationsAt,
openIdleChatBesideRunningAgent,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordLoaderStepChanges,
recordRingAngles,
runningToolCall,
statusRings,
workingLoader,
@@ -47,10 +45,6 @@ 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.
@@ -115,45 +109,6 @@ 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,28 +52,17 @@ async function exitSelection(page: Page) {
}
/**
* 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.
* 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.
*/
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();
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle.
await third.click({ modifiers: ["Shift"] });
await third.click({ modifiers: [MOD] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
@@ -113,7 +102,7 @@ test.describe("sidebar workspace selection clicks", () => {
seeded = null;
});
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
@@ -122,9 +111,7 @@ test.describe("sidebar workspace selection clicks", () => {
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({
page,
}) => {
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
@@ -99,10 +99,6 @@ 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)
@@ -367,33 +363,10 @@ 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,
}) => {
+2 -36
View File
@@ -4,10 +4,6 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import type {
MutableDaemonToolGroups,
MutableDaemonToolsConfigPatch,
} from "@getpaseo/protocol/messages";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -142,7 +138,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
}
export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Enable tools", exact: true });
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
}
/** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -151,37 +147,7 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
const config = (await client.getDaemonConfig()).config;
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
}
/** The host's saved tool groups, read from the host itself. */
export async function hostToolGroups(host: {
port: number;
}): Promise<MutableDaemonToolGroups | undefined> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.tools?.groups;
} finally {
await client.close();
}
}
/** Saves tool settings on the host, the way Settings does. */
export async function setHostTools(
host: { port: number },
tools: MutableDaemonToolsConfigPatch,
): Promise<void> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
await client.patchDaemonConfig({ tools });
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
@@ -50,76 +50,6 @@ export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspa
}
}
/**
* Opens an idle chat while an agent runs in another workspace: the only thing moving on screen is
* the running workspace's status ring in the sidebar.
*/
export async function openIdleChatBesideRunningAgent(page: Page): Promise<{
cleanup(): Promise<void>;
}> {
const running = await seedMockAgentWorkspace({
repoPrefix: "running-beside-",
title: "Running beside",
initialPrompt: HELD_TOOL_CALL_PROMPT,
});
try {
const idle = await seedMockAgentWorkspace({ repoPrefix: "idle-chat-", title: "Idle chat" });
const cleanup = async () => {
await idle.cleanup();
await running.cleanup();
};
try {
await openAgentRoute(page, { workspaceId: idle.workspaceId, agentId: idle.agentId });
await expectComposerVisible(page);
await expect(statusRings(page).first()).toBeVisible({ timeout: 30_000 });
await expect(workingLoader(page)).toHaveCount(0);
await page.mouse.move(900, 300);
return { cleanup };
} catch (error) {
await cleanup();
throw error;
}
} catch (error) {
await running.cleanup().catch(() => undefined);
throw error;
}
}
/** Every angle the first visible status ring's quarter is seen at over the window, in degrees. */
export async function recordRingAngles(page: Page, windowMs: number): Promise<number[]> {
return statusRings(page)
.first()
.evaluate(
(ring, sampleWindowMs) =>
new Promise<number[]>((resolve, reject) => {
const turning = document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && ring.contains(effect.target));
const quarter = turning?.target;
if (!quarter) {
reject(new Error("The status ring is not turning"));
return;
}
const angles = new Set<number>();
const startedAt = performance.now();
const sample = () => {
const { a, b } = new DOMMatrixReadOnly(getComputedStyle(quarter).transform);
const degrees = (Math.atan2(b, a) * 180) / Math.PI;
angles.add(Math.round(((degrees + 360) % 360) * 100) / 100);
if (performance.now() - startedAt >= sampleWindowMs) {
resolve([...angles].sort((first, second) => first - second));
return;
}
requestAnimationFrame(sample);
};
sample();
}),
windowMs,
);
}
/** The loader's current step, or null while the dots are between two readable states. */
export async function readLoaderStep(page: Page): Promise<number | null> {
const opacities = await loaderDots(page).evaluateAll((dots) =>
+1 -1
View File
@@ -519,7 +519,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
}
function idleAgentReleaseSwitch(page: Page) {
@@ -180,7 +180,9 @@ public final class PaseoHardwareKeyboardWindow: UIWindow {
}
public override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText() {
if isHardwareSubmitEnabled && !isPlainReturnClaimed && !isComposingText()
&& UIDevice.current.userInterfaceIdiom == .pad
{
commands.append(makeSubmitCommand())
}
if !isComposingText() {
@@ -1,79 +0,0 @@
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,12 +7,6 @@ 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.
*
@@ -21,31 +15,20 @@ const STEP_LEAD = 1 / 8;
* on every frame it changes.
*/
export interface IndicatorClock {
/**
* 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>;
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
cycle(periodMs: number): Animated.AnimatedModulo<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
run(): () => void;
}
export function createIndicatorClock(
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
): IndicatorClock {
export function createIndicatorClock(): IndicatorClock {
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
let runners = 0;
let ticking: Animated.CompositeAnimation | null = null;
return {
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));
cycle(periodMs) {
return Animated.modulo(elapsedMs, periodMs);
},
run() {
runners += 1;
+2 -7
View File
@@ -1,4 +1,3 @@
import { AppearanceText } from "@/appearance/text";
import { useDisclosureHold } from "@/agent-stream/disclosure";
import { MessagePreview, MessageSender } from "@/components/user-message";
import { useStableEvent } from "@/hooks/use-stable-event";
@@ -571,13 +570,9 @@ export const UserMessage = memo(function UserMessage({
</View>
) : null}
{hasText ? (
<AppearanceText
selectable
style={userMessageStylesheet.text}
dataSet={MESSAGE_TEXT_DATASET}
>
<Text selectable style={userMessageStylesheet.text} dataSet={MESSAGE_TEXT_DATASET}>
{message}
</AppearanceText>
</Text>
) : null}
</MessagePreview>
</View>
@@ -2,19 +2,12 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native";
import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
import { SettingsRowHeader } from "./row-header";
interface SettingsCollapsibleRowProps {
label: string;
/** A line under the label explaining the group. */
hint?: string;
hintStatus?: SettingsRowHintStatus;
/** A short status shown before the chevron, so the row says something while collapsed. */
summary?: string;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
accessibilityLabel?: string;
defaultExpanded?: boolean;
testID?: string;
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
@@ -28,11 +21,7 @@ interface SettingsCollapsibleRowProps {
*/
export function SettingsCollapsibleRow({
label,
hint,
hintStatus,
summary,
control,
accessibilityLabel,
defaultExpanded = false,
testID,
children,
@@ -50,11 +39,7 @@ export function SettingsCollapsibleRow({
<View testID={testID}>
<SettingsRowHeader
label={label}
hint={hint}
hintStatus={hintStatus}
summary={summary}
control={control}
accessibilityLabel={accessibilityLabel}
onPress={toggle}
expanded={expanded}
accessibilityState={accessibilityState}
@@ -1287,6 +1287,7 @@ 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,
@@ -1305,8 +1306,6 @@ function WorkspaceRowWithMenu({
onArchiveStarted: redirectAfterArchive,
onSetHiding: setIsHidingWorkspace,
});
const isArchiving =
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
const handleArchive = useCallback(() => {
if (isArchiving) {
@@ -720,6 +720,7 @@ function StatusWorkspaceRowWithMenu({
const toast = useToast();
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const rename = useSidebarWorkspaceRename(workspace);
const isArchiving = workspace.archivingAt !== null || isHidingWorkspace;
const redirectAfterArchive = useCallback(() => {
redirectIfArchivingActiveWorkspace({
@@ -741,8 +742,6 @@ function StatusWorkspaceRowWithMenu({
onArchiveStarted: redirectAfterArchive,
onSetHiding: setIsHidingWorkspace,
});
const isArchiving =
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
const handleArchive = useCallback(() => {
if (isArchiving) return;
@@ -31,12 +31,6 @@ 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, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS } 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, STATUS_RING_STEPS).interpolate({
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
inputRange: [0, STATUS_RING_PERIOD_MS],
outputRange: ["0deg", "360deg"],
});
@@ -8,15 +8,12 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS } 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)", easing: `steps(${STATUS_RING_STEPS})` },
{ transform: "rotate(360deg)" },
],
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
durationMs: STATUS_RING_PERIOD_MS,
phase: "shared",
};
+3 -4
View File
@@ -36,9 +36,8 @@ 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. 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`).
* 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.
*/
function flipPlacement(input: {
placement: Placement;
@@ -157,7 +156,7 @@ export function computePosition({
placement: Placement;
alignment: Alignment;
offset: number;
/** Lets a left or right placement open on the other side when its own has no room. */
/** Hover cards can choose either side; submenu direction is owned by the menu. */
flipHorizontal?: boolean;
}): { x: number; y: number; actualPlacement: Placement } {
const actualPlacement = flipPlacement({
@@ -35,10 +35,7 @@ export type {
MenuItemProps as DropdownMenuItemProps,
} from "@/components/ui/menu";
export type { MenuPageDefinition } from "@/components/ui/menu";
export {
MenuSubTrigger as DropdownMenuSubTrigger,
useMenuSubTrigger as useDropdownMenuSubTrigger,
} from "@/components/ui/menu";
export { MenuSubTrigger as DropdownMenuSubTrigger } from "@/components/ui/menu";
export function DropdownMenuContent(props: MenuSurfaceProps): ReactElement | null {
return <MenuSurface {...props} />;
+1 -1
View File
@@ -17,7 +17,7 @@ export {
type MenuPageDefinition,
type MenuSurfaceProps,
} from "./menu-surface";
export { MenuSubTrigger, useMenuSubTrigger, type MenuSubTriggerBinding } from "./menu-sub";
export { MenuSubTrigger } from "./menu-sub";
export {
MenuCheckboxItem,
MenuHint,
@@ -192,61 +192,3 @@ 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,7 +7,6 @@ import {
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactElement,
type RefObject,
@@ -102,7 +101,6 @@ export function useAnchoredPosition({
offset,
scrollable,
maxHeight,
flipHorizontal = false,
}: {
open: boolean;
anchorRect: Rect | null;
@@ -112,18 +110,11 @@ 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;
@@ -145,7 +136,6 @@ export function useAnchoredPosition({
setTriggerRect(null);
setContentSize(null);
setPosition(null);
heldSideRef.current = null;
return undefined;
}
@@ -179,21 +169,18 @@ 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: heldSide ?? side,
placement: 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, flipHorizontal]);
}, [triggerRect, visibleContentSize, side, align, offset]);
const onContentLayout = useCallback(
(event: { nativeEvent: { layout: { width: number; height: number } } }) => {
@@ -227,8 +214,6 @@ 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.
@@ -261,7 +246,6 @@ export function AnchoredSurface({
horizontalPadding = 16,
scrollable = false,
backdrop = true,
flipHorizontal = false,
onPointerEnter,
onPointerLeave,
testID,
@@ -279,7 +263,6 @@ 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,7 +5,6 @@ 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";
@@ -54,56 +53,6 @@ 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 } =
@@ -115,12 +64,11 @@ export function useMenuSubTrigger({
}, [id, registerSubAnchor]);
const isOpen = isSubPageOpen(menu.path, { id, depth });
const tracksHover = menu.presentation === "popover" && !disabled;
const { openSub } = menu;
const isPopover = menu.presentation === "popover";
const open = useCallback(() => {
openSub({ id, depth });
}, [openSub, id, depth]);
const handleSelect = useCallback(() => {
menu.openSub({ id, depth });
}, [menu, id, depth]);
const handlePointerEnter = useCallback(
(event: PointerEvent) => {
@@ -139,13 +87,31 @@ export function useMenuSubTrigger({
[hoverClose, depth],
);
const anchorProps = useMemo(
() =>
tracksHover ? { onPointerEnter: handlePointerEnter, onPointerLeave: handlePointerLeave } : {},
[tracksHover, handlePointerEnter, handlePointerLeave],
const trailing = useMemo(
() => <MenuSubTrailing value={value} indicator={indicator} />,
[value, indicator],
);
return { anchorRef, anchorProps, isOpen, open };
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>
);
}
function MenuSubTrailing({
@@ -351,7 +351,6 @@ function MenuFlyout({
anchorRect={null}
anchorRef={anchorRef}
side="right"
flipHorizontal
align="start"
offset={-SUBMENU_OVERLAP}
minWidth={minWidth}
+7 -19
View File
@@ -1671,16 +1671,7 @@ function ComposerContentImpl({
);
const runPluginClientSlashCommand = useCallback(
(
resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string },
hasAttachments: boolean,
) => {
if (hasAttachments) {
setSendError(
t("composer.errors.removePluginCommandAttachments", { command: resolved.command.name }),
);
return;
}
(resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string }): boolean => {
if (blurOnSubmit) messageInputRef.current?.blur();
clearDraft("sent");
replaceUserInput("");
@@ -1695,8 +1686,9 @@ function ComposerContentImpl({
toastErrorRef.current(error instanceof Error ? error.message : String(error));
},
});
return true;
},
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments],
);
const { pickImages } = useImageAttachmentPicker();
@@ -1996,12 +1988,10 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -2271,12 +2261,10 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
queueMessage(payload.text, outgoingAttachments);
},
[
+5 -1
View File
@@ -1583,7 +1583,11 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
const autoSend = sendAfterTranscriptRef.current;
sendAfterTranscriptRef.current = false;
applyDictationTranscript(text, {
value: valueRef.current,
input: getComposerInputSnapshot(
textInputRef.current,
valueRef.current,
selectionRef.current,
),
defaultSendBehavior,
isAgentRunning,
onQueue,
+27 -1
View File
@@ -172,11 +172,37 @@ describe("dictation keyboard behavior", () => {
});
describe("dictation transcript behavior", () => {
it("inserts dictated words into the paragraph at the cursor", () => {
const value = "Intro: \n\nKeep this as the second paragraph.";
let draft = value;
let selection = { start: 7, end: 7 };
applyDictationTranscript("Spoken words.", {
input: { text: value, selection: { start: 7, end: 7 } },
defaultSendBehavior: "interrupt" as const,
isAgentRunning: false,
onQueue: undefined,
replaceText: (text, caret) => {
draft = text;
selection = caret ?? selection;
},
onSubmit: () => {
throw new Error("Insert must leave the message unsent");
},
attachments: [],
cwd: "/repo",
autoSend: false,
});
expect(draft).toBe("Intro: Spoken words.\n\nKeep this as the second paragraph.");
expect(selection).toEqual({ start: 20, end: 20 });
});
it("publishes an auto-sent transcript to the composer before submitting it", () => {
const actions: string[] = [];
applyDictationTranscript("spoken prompt", {
value: "typed context",
input: { text: "typed context", selection: { start: 13, end: 13 } },
defaultSendBehavior: "interrupt",
isAgentRunning: false,
onQueue: undefined,
+17 -12
View File
@@ -3,6 +3,8 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type { MessagePayload, TextReplacement } from "@/composer/types";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import { insertAtSelection } from "../insert-text";
import type { ComposerInputSnapshot } from "./input";
export type SendBehavior = ActiveTurnBehavior | "queue";
@@ -56,12 +58,12 @@ interface SendActionContext {
}
interface DictationTranscriptContext {
value: string;
input: ComposerInputSnapshot;
defaultSendBehavior: SendBehavior;
isAgentRunning: boolean;
onQueue: ((payload: MessagePayload) => void) | undefined;
onSubmit: (payload: MessagePayload) => void;
replaceText: (text: string) => void;
replaceText: (text: string, selection?: ComposerInputSnapshot["selection"]) => void;
attachments: MessagePayload["attachments"];
cwd: string;
autoSend: boolean;
@@ -69,24 +71,27 @@ interface DictationTranscriptContext {
export function applyDictationTranscript(text: string, ctx: DictationTranscriptContext): void {
if (!text) return;
const shouldPad = ctx.value.length > 0 && !/\s$/.test(ctx.value);
const nextValue = `${ctx.value}${shouldPad ? " " : ""}${text}`;
const selection = resolveRetainedSelection(ctx.input.selection, ctx.input.text.length);
const before = ctx.input.text.slice(0, selection.start);
const after = ctx.input.text.slice(selection.end);
const leadingSpace = /\S$/.test(before) ? " " : "";
const trailingSpace = /^[\p{L}\p{N}]/u.test(after) ? " " : "";
const next = insertAtSelection(
{ text: ctx.input.text, selection },
`${leadingSpace}${text}${trailingSpace}`,
);
if (!ctx.autoSend) {
ctx.replaceText(nextValue);
return;
}
ctx.replaceText(nextValue);
ctx.replaceText(next.text, next.selection);
if (!ctx.autoSend) return;
if (ctx.defaultSendBehavior === "queue" && ctx.isAgentRunning && ctx.onQueue) {
ctx.onQueue({ text: nextValue, attachments: ctx.attachments, cwd: ctx.cwd });
ctx.onQueue({ text: next.text, attachments: ctx.attachments, cwd: ctx.cwd });
ctx.replaceText("");
return;
}
ctx.onSubmit({
text: nextValue,
text: next.text,
attachments: ctx.attachments,
cwd: ctx.cwd,
forceSend: ctx.isAgentRunning || undefined,
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { render, within } from "@testing-library/react";
import { render } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { FileHtmlPreview } from "./html-preview.web";
@@ -15,24 +15,4 @@ describe("FileHtmlPreview on web", () => {
expect(changedFrame).not.toBe(firstFrame);
expect(decodeURIComponent(changedFrame.getAttribute("src") ?? "")).toContain("Changed plan");
});
it("reports oversized desktop previews using the encoded URL length", () => {
window.paseoDesktop = { platform: "linux" };
try {
// Percent encoding puts this document over the limit even though its source is smaller.
const html = `<h1>Slides</h1><!--${" ".repeat(750_000)}-->`;
const view = render(<FileHtmlPreview html={html} testID="preview" />);
const preview = within(view.container);
const status = preview.getByRole("status");
const message = within(status).getByText("panels.file.tooLargeToDisplay");
expect(getComputedStyle(message).color).toBe("rgb(102, 102, 102)");
expect(preview.queryByTestId("preview")).toBeNull();
view.rerender(<FileHtmlPreview html="<h1>Slides</h1>" testID="preview" />);
expect(preview.getByTestId("preview").getAttribute("sandbox")).toBe("allow-scripts");
} finally {
delete window.paseoDesktop;
}
});
});
@@ -1,8 +1,5 @@
import { useMemo } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { isElectronRuntime } from "@/desktop/host";
import { withPreviewCsp } from "./html-preview-csp";
// `allow-scripts` alone: the file gets an opaque origin, so a plan page can run
@@ -19,9 +16,6 @@ import { withPreviewCsp } from "./html-preview-csp";
// over with a directive browsers ignore.
const SANDBOX = "allow-scripts";
// Electron rejects iframe navigations above 2 MiB of encoded URL bytes.
const MAX_DESKTOP_PREVIEW_URL_LENGTH = 2 * 1024 * 1024;
const iframeStyle = {
flex: 1,
minHeight: 0,
@@ -29,20 +23,6 @@ const iframeStyle = {
backgroundColor: "white",
} as const;
const styles = StyleSheet.create((theme) => ({
status: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: theme.spacing[4],
},
statusText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
textAlign: "center",
},
}));
export function FileHtmlPreview({ html, testID }: { html: string; testID?: string }) {
const { t } = useTranslation();
// A document URL lets the browser resolve fragment links within the preview.
@@ -51,13 +31,6 @@ export function FileHtmlPreview({ html, testID }: { html: string; testID?: strin
() => `data:text/html;charset=utf-8,${encodeURIComponent(withPreviewCsp(html))}`,
[html],
);
if (source.length > MAX_DESKTOP_PREVIEW_URL_LENGTH && isElectronRuntime()) {
return (
<View role="status" style={styles.status}>
<Text style={styles.statusText}>{t("panels.file.tooLargeToDisplay")}</Text>
</View>
);
}
return (
// Each document loads in a new frame. The Source view keeps this preview mounted and hidden,
// and it gets a changed document in the same render that shows it again. Chromium can leave a
+1 -2
View File
@@ -289,8 +289,7 @@ function useWorkspaceScreenArchiveController({
return {
...controller,
isArchiving:
workspaceDescriptor?.archivingAt != null || isHidingWorkspace || controller.isConfirming,
isArchiving: workspaceDescriptor?.archivingAt != null || isHidingWorkspace,
canArchive: canArchiveWorkspace(workspaceDescriptor, archiveRisk),
};
}
+1 -1
View File
@@ -385,7 +385,7 @@ describe("translation resources", () => {
expect(en.settings.host.notFound).toBe("Host not found");
expect(en.settings.host.connections.title).toBe("Connections");
expect(en.settings.host.daemon.restart.title).toBe("Restart daemon");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable tools");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable Paseo tools");
expect(en.settings.providers.title).toBe("Providers");
expect(en.settings.providers.models.addModel).toBe("Add model");
expect(en.settings.providers.diagnostic.title).toBe("Diagnostic");
+10 -45
View File
@@ -195,7 +195,6 @@ export const ar: TranslationResources = {
removeReview: "إزالة مرفق المراجعة",
},
errors: {
removePluginCommandAttachments: "أزل المرفقات لتشغيل الأمر /{{command}}.",
failedToSend: "فشل في إرسال الرسالة",
failedToCreateAgent: "فشل في إنشاء الوكيل",
noHostSelected: "لم يتم تحديد مضيف",
@@ -857,6 +856,7 @@ export const ar: TranslationResources = {
scripts: {
title: "البرامج النصية",
actions: {
chooseUrl: "اختيار الرابط",
copyUrl: "نسخ الرابط",
openService: "عرض الخدمة",
restart: "إعادة التشغيل",
@@ -872,28 +872,13 @@ export const ar: TranslationResources = {
stopScript: "إيقاف{{scriptName}}",
restartScript: "إعادة تشغيل{{scriptName}}",
copyUrl: "نسخ عنوان URL لـ{{scriptName}}",
openTunnelUrl: "فتح رابط النفق لـ {{scriptName}}",
copyTunnelUrl: "نسخ رابط النفق لـ {{scriptName}}",
stopTunnel: "إيقاف نفق {{scriptName}}",
tunnel: "نفق {{scriptName}}",
chooseUrl: "اختيار رابط {{scriptName}}",
script: "البرنامج النصي{{scriptName}}",
},
tunnel: {
title: "نفق",
connecting: "جارٍ الاتصال...",
reconnecting: "جارٍ إعادة الاتصال...",
ephemeralNote: "رابط مؤقت",
openUrl: "فتح رابط النفق",
copyUrl: "نسخ رابط النفق",
stop: "إيقاف النفق",
loadingProviders: "جارٍ التحقق من مزوّدي الأنفاق...",
noProviders: "لا يوجد مزوّدو أنفاق متاحون.",
providersLoadFailed: "فشل تحميل مزوّدي الأنفاق.",
retry: "إعادة المحاولة",
openFailed: "فشل فتح النفق لـ {{scriptName}}",
stopFailed: "فشل إيقاف النفق لـ {{scriptName}}",
errorFallback: "فشل النفق.",
unavailable: "غير متاح",
routes: {
public: "الوكيل العكسي",
paseo: "Memorable",
direct: "مباشر",
},
states: {
exitCode: "الخروج من{{code}}",
@@ -3162,35 +3147,15 @@ export const ar: TranslationResources = {
tools: {
instructionsTitle: "التعليمات",
toolsTitle: "أدوات الوكلاء",
pluginNote: "الأدوات التي تضيفها الإضافات تتبع أيضًا خيار تمكين الأدوات",
updateHostForGroups: "حدّث هذا المضيف لضبط مجموعات الأدوات الفردية",
groups: {
orchestration: {
title: "التنسيق",
hint: "إدارة مساحات العمل والوكلاء والطرفيات والسكربتات",
},
schedules: {
title: "الجداول الزمنية",
hint: "إنشاء وإدارة الجداول الزمنية ونبضات المتابعة",
},
changeRequests: {
title: "مراقبة طلبات السحب",
hint: "مراقبة تحديثات طلبات السحب والدمج",
},
browser: {
title: "المتصفح",
hint: "التحكم في علامات تبويب متصفح Paseo بما في ذلك الجلسات المسجّل الدخول إليها. فعّل هذا الخيار فقط للوكلاء الموثوقين.",
},
},
},
orchestration: {
title: "التنسيق",
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
enableTools: {
title: "تمكين الأدوات",
hint: "يسمح لـ Paseo والإضافات بتوفير الأدوات للوكلاء.",
accessibilityLabel: "تمكين الأدوات",
updateFailed: "تعذر تحديث الأدوات.",
title: "تمكين أدوات Paseo",
hint: "سيتمكن الوكلاء من إدارة أشجار العمل والوكلاء والجداول الزمنية",
accessibilityLabel: "حقن أدوات Paseo",
updateFailed: "تعذر تحديث أدوات Paseo.",
},
systemPrompt: {
title: "موجه النظام",
+10 -45
View File
@@ -193,7 +193,6 @@ export const en = {
removeReview: "Remove review attachment",
},
errors: {
removePluginCommandAttachments: "Remove attachments to run /{{command}}.",
failedToSend: "Failed to send message",
failedToCreateAgent: "Failed to create agent",
noHostSelected: "No host selected",
@@ -854,6 +853,7 @@ export const en = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Choose URL",
copyUrl: "Copy URL",
openService: "View service",
restart: "Restart",
@@ -869,28 +869,13 @@ export const en = {
stopScript: "Stop {{scriptName}}",
restartScript: "Restart {{scriptName}}",
copyUrl: "Copy {{scriptName}} URL",
openTunnelUrl: "Open {{scriptName}} tunnel URL",
copyTunnelUrl: "Copy {{scriptName}} tunnel URL",
stopTunnel: "Stop {{scriptName}} tunnel",
tunnel: "{{scriptName}} tunnel",
chooseUrl: "Choose URL for {{scriptName}}",
script: "{{scriptName}} script",
},
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",
routes: {
public: "Reverse proxy",
paseo: "Memorable",
direct: "Direct",
},
states: {
exitCode: "exit {{code}}",
@@ -3262,35 +3247,15 @@ export const en = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Agent tools",
pluginNote: "Tools added by plugins also follow Enable tools",
updateHostForGroups: "Update this host to configure individual tool groups",
groups: {
orchestration: {
title: "Orchestration",
hint: "Manage workspaces, agents, terminals, and scripts",
},
schedules: {
title: "Schedules",
hint: "Create and manage schedules and heartbeats",
},
changeRequests: {
title: "PR watching",
hint: "Watch pull requests and merge requests for updates",
},
browser: {
title: "Browser",
hint: "Control Paseo browser tabs, including logged-in state. Enable only for agents you trust.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connect to this host to manage orchestration",
enableTools: {
title: "Enable tools",
hint: "Let Paseo and plugins give tools to agents.",
accessibilityLabel: "Enable tools",
updateFailed: "Unable to update tools.",
title: "Enable Paseo tools",
hint: "Agents will be able to manage worktrees, agents and schedules",
accessibilityLabel: "Inject Paseo tools",
updateFailed: "Unable to update Paseo tools.",
},
systemPrompt: {
title: "System prompt",
+10 -45
View File
@@ -196,7 +196,6 @@ export const es: TranslationResources = {
removeReview: "Eliminar archivo adjunto de reseña",
},
errors: {
removePluginCommandAttachments: "Quita los archivos adjuntos para ejecutar /{{command}}.",
failedToSend: "No se pudo enviar el mensaje",
failedToCreateAgent: "No se pudo crear el agente",
noHostSelected: "Ningún anfitrión seleccionado",
@@ -865,6 +864,7 @@ export const es: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Elegir URL",
copyUrl: "Copiar URL",
openService: "Ver servicio",
restart: "Reiniciar",
@@ -880,28 +880,13 @@ export const es: TranslationResources = {
stopScript: "Detener{{scriptName}}",
restartScript: "Reiniciar{{scriptName}}",
copyUrl: "Copiar URL de{{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}}",
chooseUrl: "Elegir URL para {{scriptName}}",
script: "Guión{{scriptName}}",
},
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",
routes: {
public: "Proxy inverso",
paseo: "Memorable",
direct: "Directa",
},
states: {
exitCode: "salir de{{code}}",
@@ -3195,35 +3180,15 @@ export const es: TranslationResources = {
tools: {
instructionsTitle: "Instrucciones",
toolsTitle: "Herramientas de agentes",
pluginNote: "Las herramientas de los plugins también siguen Habilitar herramientas",
updateHostForGroups: "Actualiza este host para configurar grupos de herramientas",
groups: {
orchestration: {
title: "Orquestación",
hint: "Gestiona workspaces, agentes, terminales y scripts",
},
schedules: {
title: "Programaciones",
hint: "Crea y gestiona programaciones y heartbeats",
},
changeRequests: {
title: "Seguimiento de PR",
hint: "Supervisa pull requests y merge requests para ver actualizaciones",
},
browser: {
title: "Navegador",
hint: "Controla las pestañas del navegador de Paseo, incluido el estado con sesión iniciada. Actívalo solo para agentes de confianza.",
},
},
},
orchestration: {
title: "Orquestación",
unavailable: "Conéctese a este host para administrar la orquestación",
enableTools: {
title: "Habilitar herramientas",
hint: "Permite que Paseo y los plugins proporcionen herramientas a los agentes.",
accessibilityLabel: "Habilitar herramientas",
updateFailed: "No se pudieron actualizar las herramientas.",
title: "Habilitar herramientasPaseo",
hint: "Los agentes podrán gestionar árboles de trabajo, agentes y horarios.",
accessibilityLabel: "Inyectar herramientasPaseo",
updateFailed: "No se pudieron actualizar las herramientas de Paseo.",
},
systemPrompt: {
title: "Aviso del sistema",
+10 -45
View File
@@ -197,7 +197,6 @@ export const fr: TranslationResources = {
removeReview: "Retirer la revue jointe",
},
errors: {
removePluginCommandAttachments: "Retirez les pièces jointes pour exécuter /{{command}}.",
failedToSend: "Impossible d’envoyer le message",
failedToCreateAgent: "Impossible de créer l’agent",
noHostSelected: "Aucun hôte sélectionné",
@@ -866,6 +865,7 @@ export const fr: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Choisir l’URL",
copyUrl: "Copier l’URL",
openService: "Voir le service",
restart: "Redémarrer",
@@ -881,28 +881,13 @@ export const fr: TranslationResources = {
stopScript: "Arrêter {{scriptName}}",
restartScript: "Redémarrer {{scriptName}}",
copyUrl: "Copier 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}}",
chooseUrl: "Choisir l’URL de {{scriptName}}",
script: "Script {{scriptName}}",
},
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",
routes: {
public: "Proxy inverse",
paseo: "Mémorable",
direct: "Directe",
},
states: {
exitCode: "sortie {{code}}",
@@ -3197,35 +3182,15 @@ export const fr: TranslationResources = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Outils des agents",
pluginNote: "Les outils ajoutés par les plugins suivent aussi Activer les outils",
updateHostForGroups: "Mettez à jour cet hôte pour configurer chaque groupe d'outils",
groups: {
orchestration: {
title: "Orchestration",
hint: "Gérer les workspaces, les agents, les terminaux et les scripts",
},
schedules: {
title: "Planifications",
hint: "Créer et gérer des planifications et des heartbeats",
},
changeRequests: {
title: "Suivi des PR",
hint: "Surveiller les pull requests et merge requests",
},
browser: {
title: "Navigateur",
hint: "Contrôler les onglets du navigateur Paseo, y compris les sessions connectées. Activez uniquement pour des agents de confiance.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
enableTools: {
title: "Activer les outils",
hint: "Autorise Paseo et les plugins à fournir des outils aux agents.",
accessibilityLabel: "Activer les outils",
updateFailed: "Impossible de mettre à jour les outils.",
title: "Activer les outils Paseo",
hint: "Les agents pourront gérer les worktrees, les agents et les planifications",
accessibilityLabel: "Injecter les outils Paseo",
updateFailed: "Impossible de mettre à jour les outils Paseo.",
},
systemPrompt: {
title: "Prompt système",
+10 -45
View File
@@ -196,7 +196,6 @@ export const ja: TranslationResources = {
removeReview: "レビュー添付ファイルを削除",
},
errors: {
removePluginCommandAttachments: "/{{command}} を実行するには添付ファイルを削除してください。",
failedToSend: "メッセージの送信に失敗しました",
failedToCreateAgent: "エージェントの作成に失敗しました",
noHostSelected: "ホストが選択されていません",
@@ -861,6 +860,7 @@ export const ja: TranslationResources = {
scripts: {
title: "スクリプト",
actions: {
chooseUrl: "URLを選択",
copyUrl: "URLをコピー",
openService: "サービスを表示",
restart: "再起動",
@@ -876,28 +876,13 @@ export const ja: TranslationResources = {
stopScript: "{{scriptName}}を停止",
restartScript: "{{scriptName}}を再起動",
copyUrl: "{{scriptName}}のURLをコピー",
openTunnelUrl: "{{scriptName}}のトンネルURLを開く",
copyTunnelUrl: "{{scriptName}}のトンネルURLをコピー",
stopTunnel: "{{scriptName}}のトンネルを停止",
tunnel: "{{scriptName}}のトンネル",
chooseUrl: "{{scriptName}}のURLを選択",
script: "{{scriptName}}スクリプト",
},
tunnel: {
title: "トンネル",
connecting: "接続中...",
reconnecting: "再接続中...",
ephemeralNote: "一時URL",
openUrl: "トンネルURLを開く",
copyUrl: "トンネルURLをコピー",
stop: "トンネルを停止",
loadingProviders: "トンネルプロバイダーを確認中...",
noProviders: "利用可能なトンネルプロバイダーがありません。",
providersLoadFailed: "トンネルプロバイダーの読み込みに失敗しました。",
retry: "再試行",
openFailed: "{{scriptName}}のトンネル開始に失敗しました",
stopFailed: "{{scriptName}}のトンネル停止に失敗しました",
errorFallback: "トンネルエラーが発生しました。",
unavailable: "利用不可",
routes: {
public: "リバースプロキシ",
paseo: "Memorable",
direct: "直接接続",
},
states: {
exitCode: "終了コード: {{code}}",
@@ -3157,35 +3142,15 @@ export const ja: TranslationResources = {
tools: {
instructionsTitle: "指示",
toolsTitle: "エージェントツール",
pluginNote: "プラグインが追加するツールもこのスイッチに従います",
updateHostForGroups: "ツールグループを個別に設定するにはホストを更新してください",
groups: {
orchestration: {
title: "オーケストレーション",
hint: "ワークスペース、エージェント、ターミナル、スクリプトを管理します",
},
schedules: {
title: "スケジュール",
hint: "スケジュールとハートビートを作成・管理します",
},
changeRequests: {
title: "PRの監視",
hint: "プルリクエストやマージリクエストの更新を監視します",
},
browser: {
title: "ブラウザ",
hint: "ログイン状態を含む Paseo のブラウザタブを操作します。信頼できるエージェントにのみ有効にしてください。",
},
},
},
orchestration: {
title: "オーケストレーション",
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
enableTools: {
title: "ツールを有効にする",
hint: "Paseo とプラグインからエージェントへツールを提供します。",
accessibilityLabel: "ツールを有効にする",
updateFailed: "ツールを更新できませんでした。",
title: "Paseoツールを有効にする",
hint: "エージェントがワークツリー、エージェント、スケジュールを管理できるようになります",
accessibilityLabel: "Paseoツールを有効にする",
updateFailed: "Paseoツールを更新できませんでした。",
},
systemPrompt: {
title: "システムプロンプト",
+10 -45
View File
@@ -195,7 +195,6 @@ export const ko: TranslationResources = {
removeReview: "리뷰 첨부 제거",
},
errors: {
removePluginCommandAttachments: "/{{command}} 명령을 실행하려면 첨부 파일을 제거하세요.",
failedToSend: "메시지를 보내지 못했습니다",
failedToCreateAgent: "에이전트를 생성하지 못했습니다",
noHostSelected: "선택된 호스트가 없습니다",
@@ -857,6 +856,7 @@ export const ko: TranslationResources = {
scripts: {
title: "스크립트",
actions: {
chooseUrl: "URL를 선택하세요",
copyUrl: "URL 복사",
openService: "서비스 보기",
restart: "다시 시작",
@@ -872,28 +872,13 @@ export const ko: TranslationResources = {
stopScript: "{{scriptName}} 중지",
restartScript: "{{scriptName}} 다시 시작",
copyUrl: "{{scriptName}} URL 복사",
openTunnelUrl: "{{scriptName}} 터널 URL 열기",
copyTunnelUrl: "{{scriptName}} 터널 URL 복사",
stopTunnel: "{{scriptName}} 터널 중지",
tunnel: "{{scriptName}} 터널",
chooseUrl: "{{scriptName}}의 URL 선택",
script: "{{scriptName}} 스크립트",
},
tunnel: {
title: "터널",
connecting: "연결 중...",
reconnecting: "다시 연결 중...",
ephemeralNote: "임시 URL",
openUrl: "터널 URL 열기",
copyUrl: "터널 URL 복사",
stop: "터널 중지",
loadingProviders: "터널 공급자 확인 중...",
noProviders: "사용 가능한 터널 공급자가 없습니다.",
providersLoadFailed: "터널 공급자를 불러오지 못했습니다.",
retry: "다시 시도",
openFailed: "{{scriptName}}의 터널을 열지 못했습니다",
stopFailed: "{{scriptName}}의 터널을 중지하지 못했습니다",
errorFallback: "터널에 실패했습니다.",
unavailable: "사용할 수 없음",
routes: {
public: "역방향 프록시",
paseo: "간편 주소",
direct: "직접",
},
states: {
exitCode: "종료 {{code}}",
@@ -3141,35 +3126,15 @@ export const ko: TranslationResources = {
tools: {
instructionsTitle: "지침",
toolsTitle: "에이전트 도구",
pluginNote: "플러그인이 추가한 도구도 도구 활성화 스위치를 따릅니다",
updateHostForGroups: "개별 도구 그룹을 설정하려면 이 호스트를 업데이트하세요",
groups: {
orchestration: {
title: "오케스트레이션",
hint: "워크스페이스, 에이전트, 터미널, 스크립트 관리",
},
schedules: {
title: "일정",
hint: "일정 및 하트비트 생성과 관리",
},
changeRequests: {
title: "PR 감시",
hint: "풀 리퀘스트와 머지 리퀘스트 업데이트 감시",
},
browser: {
title: "브라우저",
hint: "로그인된 상태를 포함해 Paseo 브라우저 탭을 제어합니다. 신뢰하는 에이전트에만 활성화하세요.",
},
},
},
orchestration: {
title: "오케스트레이션",
unavailable: "오케스트레이션을 관리하려면 이 호스트에 연결하세요",
enableTools: {
title: "도구 활성화",
hint: "Paseo와 플러그인이 에이전트에 도구를 제공할 수 있게 합니다.",
accessibilityLabel: "도구 활성화",
updateFailed: "도구를 업데이트할 수 없습니다.",
title: "Paseo 도구 활성화",
hint: "에이전트가 워크트리, 에이전트, 일정을 관리할 수 있습니다",
accessibilityLabel: "Paseo 도구 주입",
updateFailed: "Paseo 도구를 업데이트할 수 없습니다.",
},
systemPrompt: {
title: "시스템 프롬프트",
+10 -45
View File
@@ -196,7 +196,6 @@ export const ptBR: TranslationResources = {
removeReview: "Remover anexo de revisão",
},
errors: {
removePluginCommandAttachments: "Remova os anexos para executar /{{command}}.",
failedToSend: "Falha ao enviar mensagem",
failedToCreateAgent: "Falha ao criar agente",
noHostSelected: "Nenhum host selecionado",
@@ -861,6 +860,7 @@ export const ptBR: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "Escolher URL",
copyUrl: "Copiar URL",
openService: "Ver serviço",
restart: "Reiniciar",
@@ -876,28 +876,13 @@ export const ptBR: TranslationResources = {
stopScript: "Parar {{scriptName}}",
restartScript: "Reiniciar {{scriptName}}",
copyUrl: "Copiar URL de {{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}}",
chooseUrl: "Escolher URL para {{scriptName}}",
script: "script {{scriptName}}",
},
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",
routes: {
public: "Proxy reverso",
paseo: "Memorable",
direct: "Direta",
},
states: {
exitCode: "saída {{code}}",
@@ -3176,35 +3161,15 @@ export const ptBR: TranslationResources = {
tools: {
instructionsTitle: "Instruções",
toolsTitle: "Ferramentas de agentes",
pluginNote: "Ferramentas adicionadas por plugins também seguem Ativar ferramentas",
updateHostForGroups: "Atualize este host para configurar grupos de ferramentas",
groups: {
orchestration: {
title: "Orquestração",
hint: "Gerencie workspaces, agentes, terminais e scripts",
},
schedules: {
title: "Agendamentos",
hint: "Crie e gerencie agendamentos e heartbeats",
},
changeRequests: {
title: "Monitoramento de PR",
hint: "Acompanhe atualizações de pull requests e merge requests",
},
browser: {
title: "Navegador",
hint: "Controle abas do navegador do Paseo, incluindo sessões conectadas. Ative apenas para agentes confiáveis.",
},
},
},
orchestration: {
title: "Orquestração",
unavailable: "Conecte-se a este host para gerenciar a orquestração",
enableTools: {
title: "Ativar ferramentas",
hint: "Permite que o Paseo e plugins forneçam ferramentas aos agentes.",
accessibilityLabel: "Ativar ferramentas",
updateFailed: "Não foi possível atualizar as ferramentas.",
title: "Ativar ferramentas do Paseo",
hint: "Agentes poderão gerenciar worktrees, agentes e agendamentos",
accessibilityLabel: "Injetar ferramentas do Paseo",
updateFailed: "Não foi possível atualizar as ferramentas do Paseo.",
},
systemPrompt: {
title: "Prompt do sistema",
+10 -45
View File
@@ -196,7 +196,6 @@ export const ru: TranslationResources = {
removeReview: "Удалить вложение проверки",
},
errors: {
removePluginCommandAttachments: "Чтобы выполнить /{{command}}, удалите вложения.",
failedToSend: "Не удалось отправить сообщение",
failedToCreateAgent: "Не удалось создать агента.",
noHostSelected: "Хост не выбран",
@@ -866,6 +865,7 @@ export const ru: TranslationResources = {
scripts: {
title: "Скрипты",
actions: {
chooseUrl: "Выбрать URL",
copyUrl: "Скопировать URL",
openService: "Открыть сервис",
restart: "Перезапустить",
@@ -881,28 +881,13 @@ export const ru: TranslationResources = {
stopScript: "Остановить скрипт {{scriptName}}",
restartScript: "Перезапустить скрипт {{scriptName}}",
copyUrl: "Скопировать URL скрипта {{scriptName}}",
openTunnelUrl: "Открыть URL туннеля {{scriptName}}",
copyTunnelUrl: "Скопировать URL туннеля {{scriptName}}",
stopTunnel: "Остановить туннель {{scriptName}}",
tunnel: "Туннель {{scriptName}}",
chooseUrl: "Выбрать URL для {{scriptName}}",
script: "Скрипт {{scriptName}}",
},
tunnel: {
title: "Туннель",
connecting: "Подключение...",
reconnecting: "Переподключение...",
ephemeralNote: "Временный URL",
openUrl: "Открыть URL туннеля",
copyUrl: "Скопировать URL туннеля",
stop: "Остановить туннель",
loadingProviders: "Проверка провайдеров туннелей...",
noProviders: "Нет доступных провайдеров туннелей.",
providersLoadFailed: "Не удалось загрузить провайдеров туннелей.",
retry: "Повторить",
openFailed: "Не удалось открыть туннель для {{scriptName}}",
stopFailed: "Не удалось остановить туннель для {{scriptName}}",
errorFallback: "Ошибка туннеля.",
unavailable: "Недоступно",
routes: {
public: "Обратный прокси",
paseo: "Запоминающийся адрес",
direct: "Прямой адрес",
},
states: {
exitCode: "Код выхода: {{code}}",
@@ -3184,35 +3169,15 @@ export const ru: TranslationResources = {
tools: {
instructionsTitle: "Инструкции",
toolsTitle: "Инструменты агентов",
pluginNote: "Инструменты плагинов также зависят от переключателя «Включить инструменты»",
updateHostForGroups: "Обновите этот хост, чтобы настраивать отдельные группы инструментов",
groups: {
orchestration: {
title: "Оркестрация",
hint: "Управление рабочими пространствами, агентами, терминалами и скриптами",
},
schedules: {
title: "Расписания",
hint: "Создание и управление расписаниями и heartbeat",
},
changeRequests: {
title: "Отслеживание PR",
hint: "Отслеживание обновлений pull request и merge request",
},
browser: {
title: "Браузер",
hint: "Управление вкладками браузера Paseo, включая авторизованные сессии. Включайте только для доверенных агентов.",
},
},
},
orchestration: {
title: "Оркестрация",
unavailable: "Подключитесь к этому хосту, чтобы управлять оркестрацией.",
enableTools: {
title: "Включить инструменты",
hint: "Позволяет Paseo и плагинам предоставлять агентам инструменты.",
accessibilityLabel: "Включить инструменты",
updateFailed: "Не удалось обновить инструменты.",
title: "Включить инструменты Paseo",
hint: "Агенты смогут управлять worktree, агентами и расписаниями.",
accessibilityLabel: "Добавить инструменты Paseo",
updateFailed: "Не удалось обновить инструменты Paseo.",
},
systemPrompt: {
title: "Системный промпт",
+10 -45
View File
@@ -195,7 +195,6 @@ export const zhCN: TranslationResources = {
removeReview: "移除 review 附件",
},
errors: {
removePluginCommandAttachments: "请先移除附件,再运行 /{{command}}。",
failedToSend: "发送消息失败",
failedToCreateAgent: "创建 Agent 失败",
noHostSelected: "未选择 Host",
@@ -853,6 +852,7 @@ export const zhCN: TranslationResources = {
scripts: {
title: "Scripts",
actions: {
chooseUrl: "选择 URL",
copyUrl: "复制 URL",
openService: "查看服务",
restart: "重启",
@@ -868,28 +868,13 @@ export const zhCN: TranslationResources = {
stopScript: "停止 {{scriptName}}",
restartScript: "重启 {{scriptName}}",
copyUrl: "复制 {{scriptName}} 的 URL",
openTunnelUrl: "打开 {{scriptName}} 的隧道 URL",
copyTunnelUrl: "复制 {{scriptName}} 的隧道 URL",
stopTunnel: "停止 {{scriptName}} 的隧道",
tunnel: "{{scriptName}} 的隧道",
chooseUrl: "选择 {{scriptName}} 的 URL",
script: "{{scriptName}} script",
},
tunnel: {
title: "隧道",
connecting: "正在连接...",
reconnecting: "正在重新连接...",
ephemeralNote: "临时 URL",
openUrl: "打开隧道 URL",
copyUrl: "复制隧道 URL",
stop: "停止隧道",
loadingProviders: "正在检查隧道提供程序...",
noProviders: "没有可用的隧道提供程序。",
providersLoadFailed: "无法加载隧道提供程序。",
retry: "重试",
openFailed: "无法为 {{scriptName}} 打开隧道",
stopFailed: "无法停止 {{scriptName}} 的隧道",
errorFallback: "隧道连接失败。",
unavailable: "不可用",
routes: {
public: "反向代理",
paseo: "Memorable",
direct: "直接地址",
},
states: {
exitCode: "exit {{code}}",
@@ -3095,35 +3080,15 @@ export const zhCN: TranslationResources = {
tools: {
instructionsTitle: "指令",
toolsTitle: "代理工具",
pluginNote: "插件提供的工具同样受“启用工具”开关控制",
updateHostForGroups: "更新此 Host 以单独配置各个工具组",
groups: {
orchestration: {
title: "编排",
hint: "管理工作区、智能体、终端和脚本",
},
schedules: {
title: "计划任务",
hint: "创建和管理计划任务与心跳",
},
changeRequests: {
title: "PR 监控",
hint: "监控 Pull Request 和 Merge Request 的更新",
},
browser: {
title: "浏览器",
hint: "控制 Paseo 浏览器标签页,包括已登录状态。仅对受信任的智能体启用。",
},
},
},
orchestration: {
title: "编排",
unavailable: "连接到这个 Host 以管理编排",
enableTools: {
title: "启用工具",
hint: "允许 Paseo 和插件为智能体提供工具。",
accessibilityLabel: "启用工具",
updateFailed: "无法更新工具设置。",
title: "启用 Paseo tools",
hint: "Agent 将能够管理 worktree、Agent 和计划",
accessibilityLabel: "注入 Paseo tools",
updateFailed: "无法更新 Paseo 工具。",
},
systemPrompt: {
title: "System prompt",
@@ -93,54 +93,19 @@ export function readPressModifiers(
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
const trustEventFlags = !isTouchPressEvent(event);
return {
shift: resolveModifierFlag(event, "shiftKey", "Shift", trustEventFlags, context.held),
mod: resolveModifierFlag(event, MODIFIER_FLAGS[modKey], modKey, trustEventFlags, context.held),
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
};
}
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 {
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): 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");
if (Reflect.get(event, flag) === true) return true;
const nativeEvent = Reflect.get(event, "nativeEvent");
return (
typeof sourceCapabilities === "object" &&
sourceCapabilities !== null &&
Reflect.get(sourceCapabilities, "firesTouchEvents") === true
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
);
}
@@ -407,45 +407,6 @@ describe("press modifiers", () => {
mod: false,
});
});
it("trusts explicit boolean flags on non-touch pointer events over stale held keys", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
// Simulate a missed key-up (e.g. OS overlay or native menu swallowing release).
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { shiftKey: true, metaKey: true }));
const mouseClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "mouse" },
};
expect(readPressModifiers(mouseClick, { isMac: true, held })).toEqual({
shift: false,
mod: false,
});
// Touch-synthesized clicks on web may report false modifier flags while a hardware key is held.
const touchPointerClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "touch" },
};
expect(readPressModifiers(touchPointerClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
const touchCapabilityClick = {
nativeEvent: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
sourceCapabilities: { firesTouchEvents: true },
},
};
expect(readPressModifiers(touchCapabilityClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
});
});
describe("non-TextInput native focus registration", () => {
@@ -9,11 +9,6 @@ import {
import { useToast } from "@/contexts/toast-context";
import { useCliInstall } from "@/desktop/hooks/use-install-status";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import {
createOnboardingAgentToolsPatch,
isHostAgentToolsEnabled,
} from "@/screens/settings/agent-tools-config";
export type OrchestrationChoice = "tools" | "skills" | "cli";
type Choices = Record<OrchestrationChoice, boolean>;
@@ -44,7 +39,6 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const toast = useToast();
const skills = useAgentSkills(serverId);
const cli = useCliInstall();
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const [chosen, setChosen] = useState<Choices>(ALL_ON);
// With nothing picked there is nothing to install, so skills read as off, as they do in Settings.
@@ -66,7 +60,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
// What the host and this computer have now, or null while it is still being read. A choice is
// skipped only when it is known to match; an unknown state is always written.
const toolsEnabled = config ? isHostAgentToolsEnabled(config) : null;
const toolsOn = config ? config.mcp.injectIntoAgents !== false : null;
const skillsInstalled = skills.status ? areSkillsInstalled(skills.status) : null;
const cliInstalled = cli.status ? cli.status.installed : null;
const { reconcile, uninstall } = skills;
@@ -74,21 +68,16 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const offersSkills = offered.skills;
const offersCli = offered.cli;
const applyTools = useCallback(() => {
const patch = createOnboardingAgentToolsPatch({
enabled: choices.tools,
currentEnabled: toolsEnabled,
supportsToolsConfig,
});
if (!patch) return Promise.resolve(true);
return patchConfig(patch)
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
});
}, [choices.tools, toolsEnabled, patchConfig, supportsToolsConfig, t, toast]);
const setTools = useCallback(
(on: boolean) =>
patchConfig({ mcp: { injectIntoAgents: on } })
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
}),
[patchConfig, t, toast],
);
const setSkillsInstalled = useCallback(
(on: boolean) => (on ? reconcile() : uninstall()),
[reconcile, uninstall],
@@ -98,7 +87,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(true);
try {
const results = await Promise.all([
applyTools(),
choices.tools === toolsOn ? true : setTools(choices.tools),
!offersSkills || choices.skills === skillsInstalled
? true
: setSkillsInstalled(choices.skills),
@@ -109,23 +98,16 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(false);
}
}, [
applyTools,
choices.cli,
choices.skills,
choices,
toolsOn,
setTools,
offersSkills,
skillsInstalled,
setSkillsInstalled,
offersSkills,
offersCli,
cliInstalled,
setCliInstalled,
]);
return {
choices,
setChoice,
offered,
skills,
isApplying,
apply,
};
return { choices, setChoice, offered, skills, isApplying, apply };
}
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { AgentSkillsRow } from "@/agent-skills";
import { SettingsCard } from "@/components/settings";
import { CommandLineRow } from "@/desktop/components/integrations-section";
import { EnableToolsSwitchRow } from "@/screens/settings/agent-tools-row";
import { PaseoToolsRow } from "@/screens/settings/paseo-tools-card";
import type { OrchestrationSetupController } from "../orchestration-setup";
/** Three switches, all on to start; Continue applies them. */
@@ -13,7 +13,7 @@ export function OrchestrationStep({ setup }: { setup: OrchestrationSetupControll
const setCli = useCallback((on: boolean) => setChoice("cli", on), [setChoice]);
return (
<SettingsCard>
<EnableToolsSwitchRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
<PaseoToolsRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
{offered.skills ? (
<AgentSkillsRow
skills={setup.skills}
@@ -33,12 +33,14 @@ describe("plugin client slash commands", () => {
expect(
resolvePluginClientSlashCommand({
text: " /review foo bar ",
hasAttachments: false,
commands: [command],
}),
).toEqual({ command, args: "foo bar" });
expect(
resolvePluginClientSlashCommand({
text: "/another-command foo",
text: "/review foo",
hasAttachments: true,
commands: [command],
}),
).toBeNull();
@@ -47,8 +47,10 @@ export function mergeSlashCommandSources<
export function resolvePluginClientSlashCommand<Command extends SlashCommandDescriptor>(input: {
text: string;
hasAttachments: boolean;
commands: readonly Command[];
}): { command: Command; args: string } | null {
if (input.hasAttachments) return null;
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(input.text.trim());
if (!match) return null;
const command = input.commands.find((candidate) => candidate.name === match[1]);
@@ -73,29 +73,10 @@ class FakeDirectoryClient {
return () => handlers.delete(registered);
}
private readonly rawListeners = new Set<(message: SessionOutboundMessage) => void>();
private readonly replyWaiters = new Map<string, () => void>();
subscribeRawMessages(handler: (message: SessionOutboundMessage) => void): () => void {
this.rawListeners.add(handler);
return () => this.rawListeners.delete(handler);
}
/** Resolves when a reply carrying `requestId` arrives, after every listener saw it. */
awaitReply(requestId: string): Promise<void> {
return new Promise((resolve) => this.replyWaiters.set(requestId, resolve));
}
emit<TType extends SessionOutboundMessage["type"]>(
message: Extract<SessionOutboundMessage, { type: TType }>,
): void {
for (const listener of this.rawListeners) listener(message);
for (const handler of this.handlers.get(message.type) ?? []) handler(message);
if (!("payload" in message)) return;
const requestId = (message.payload as { requestId?: unknown }).requestId;
if (typeof requestId !== "string") return;
this.replyWaiters.get(requestId)?.();
this.replyWaiters.delete(requestId);
}
holdWorkspaceFetch(): (result: WorkspaceFetchResult) => void {
@@ -2436,40 +2417,3 @@ it("coalesces duplicate upserts and removals within a single workspace_update ba
directory.dispose();
}
});
it("applies workspace updates the host sent before a reply by the time the reply resolves", async () => {
const serverId = "workspace-update-before-reply";
const { client, directory } = createDirectory(serverId);
const store = useSessionStore.getState();
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
store.updateSessionServerInfo(serverId, {
serverId,
hostname: null,
version: "test",
features: { workspaceMultiplicity: true, directorySync: true },
});
directory.setDemand({}, true);
await directory.refreshDemand();
try {
const restored = client.awaitReply("restore-1");
client.emit({
type: "workspace_update",
payload: {
kind: "upsert",
workspace: createWorkspaceEntry("ws-restored"),
generation: "gen-restore",
seq: 1,
},
});
client.emit({
type: "workspace.recovery.restore.response",
payload: { requestId: "restore-1", workspaceId: "ws-restored", accepted: true, error: null },
});
await restored;
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has("ws-restored")).toBe(true);
} finally {
directory.dispose();
}
});
@@ -4,7 +4,7 @@ import type {
FetchAgentsEntry,
FetchAgentsOptions,
} from "@getpaseo/client/internal/daemon-client";
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { fetchAgentTimelineOnce } from "@/timeline/fetch-agent-timeline-once";
import {
normalizeProjectDescriptor,
@@ -49,17 +49,6 @@ interface WorkspaceDeltaFlushHandle {
cancel: () => void;
}
function isReply(message: SessionOutboundMessage): boolean {
if (!("payload" in message)) return false;
const payload: unknown = message.payload;
return (
typeof payload === "object" &&
payload !== null &&
"requestId" in payload &&
typeof payload.requestId === "string"
);
}
function scheduleWorkspaceDeltaFlush(callback: () => void): WorkspaceDeltaFlushHandle {
let done = false;
let rafId: number | null = null;
@@ -215,7 +204,6 @@ export class DirectorySync {
delta: WorkspaceDirectoryDelta;
}> = [];
private workspaceDeltaFlush: WorkspaceDeltaFlushHandle | null = null;
private stopObservingReplies: (() => void) | null = null;
constructor(
private readonly serverId: string,
@@ -247,13 +235,10 @@ export class DirectorySync {
this.flushAbortedTransactions();
this.releaseSubscriptions();
this.releaseScriptStatusEvents();
this.stopObservingReplies?.();
this.stopObservingReplies = null;
workspaceLabels.disconnect(this.serverId);
this.connection = connection;
this.abortPendingSessionWaits();
if (!connection.client || connection.status !== "online") return true;
this.stopObservingReplies = this.applyWorkspaceUpdatesBeforeReplies(connection.client);
if (this.scriptStatusDemand.size > 0) this.observeScriptStatusEvents();
// Reattach labels here because route-only demand can satisfy the epoch before full demand requests them.
void this.connectWorkspaceLabels().catch(() => undefined);
@@ -309,8 +294,6 @@ export class DirectorySync {
}
dispose(): void {
this.stopObservingReplies?.();
this.stopObservingReplies = null;
this.cancelPendingWorkspaceDeltas();
this.flushAbortedTransactions();
this.abortPendingSessionWaits();
@@ -374,16 +357,6 @@ export class DirectorySync {
this.applyWorkspaceDeltas([{ source, delta }]);
}
/**
* The host sends a workspace update before the reply to the request that caused it, so a
* caller reading the store after its reply must see the update. Buffered updates end at a reply.
*/
private applyWorkspaceUpdatesBeforeReplies(client: DaemonClient): () => void {
return client.subscribeRawMessages((message) => {
if (isReply(message)) this.flushPendingWorkspaceDeltas();
});
}
private flushPendingWorkspaceDeltas(): void {
if (this.workspaceDeltaFlush) {
this.workspaceDeltaFlush.cancel();
@@ -206,10 +206,6 @@ class FakeDaemonClient {
this.setConnectionState({ status: "connected" });
}
subscribeRawMessages(_handler: (message: SessionOutboundMessage) => void): () => void {
return () => {};
}
subscribeConnectionStatus(listener: (status: ConnectionState) => void): () => void {
this.listeners.add(listener);
listener(this.state);
@@ -873,7 +873,6 @@ 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,
@@ -1,178 +0,0 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
createAgentToolGroupPatch,
createAgentToolsMasterPatch,
createOnboardingAgentToolsPatch,
DEFAULT_AGENT_TOOL_GROUPS,
isHostAgentToolsEnabled,
resolveAgentToolsState,
} from "./agent-tools-config";
function makeConfig(overrides: Partial<MutableDaemonConfig> = {}): MutableDaemonConfig {
return {
relay: { enabled: false },
mcp: { injectIntoAgents: true },
browserTools: { enabled: false },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
...overrides,
};
}
describe("agent tools UI state and legacy daemon compatibility", () => {
it("reads unified daemon.tools state from a modern daemon", () => {
const state = resolveAgentToolsState({
config: makeConfig({
tools: {
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
},
mcp: { injectIntoAgents: true },
browserTools: { enabled: true },
}),
supportsToolsConfig: true,
});
expect(state).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
supportsGroupControls: true,
});
});
it("preserves saved group values when master enabled is false", () => {
const state = resolveAgentToolsState({
config: makeConfig({
tools: {
enabled: false,
groups: {
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
},
},
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
supportsToolsConfig: true,
});
expect(state.enabled).toBe(false);
expect(state.groups).toEqual({
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
});
});
it("falls back cleanly to legacy mcp.injectIntoAgents and browserTools.enabled on older daemons", () => {
const state = resolveAgentToolsState({
config: makeConfig({
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
supportsToolsConfig: false,
});
expect(state).toEqual({
enabled: false,
groups: {
...DEFAULT_AGENT_TOOL_GROUPS,
browser: true,
},
supportsGroupControls: false,
});
});
it("builds tools.* patches for modern daemons and legacy mcp/browserTools patches for older daemons", () => {
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: true })).toEqual({
tools: { enabled: false },
});
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: false })).toEqual({
mcp: { injectIntoAgents: false },
});
expect(
createAgentToolGroupPatch({
group: "schedules",
enabled: false,
supportsToolsConfig: true,
}),
).toEqual({
tools: { groups: { schedules: false } },
});
expect(
createAgentToolGroupPatch({
group: "browser",
enabled: true,
supportsToolsConfig: false,
}),
).toEqual({
browserTools: { enabled: true },
});
expect(
createAgentToolGroupPatch({
group: "orchestration",
enabled: false,
supportsToolsConfig: false,
}),
).toBeNull();
});
it("setup writes only the main switch, and only when it differs from the host", () => {
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: true,
supportsToolsConfig: true,
}),
).toBeNull();
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: false,
supportsToolsConfig: true,
}),
).toEqual({ tools: { enabled: true } });
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: null,
supportsToolsConfig: true,
}),
).toEqual({ tools: { enabled: true } });
expect(
createOnboardingAgentToolsPatch({
enabled: false,
currentEnabled: true,
supportsToolsConfig: false,
}),
).toEqual({ mcp: { injectIntoAgents: false } });
});
it("reports whether host agent tools are enabled", () => {
expect(isHostAgentToolsEnabled(null)).toBe(true);
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: true } }))).toBe(true);
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: false } }))).toBe(false);
expect(isHostAgentToolsEnabled(makeConfig({ mcp: { injectIntoAgents: false } }))).toBe(false);
});
});
@@ -1,85 +0,0 @@
import {
BUILTIN_TOOL_GROUPS,
DEFAULT_DAEMON_TOOL_GROUPS,
type BuiltInToolGroup,
type MutableDaemonConfig,
type MutableDaemonConfigPatch,
} from "@getpaseo/protocol/messages";
export type AgentToolGroupId = BuiltInToolGroup;
export type AgentToolGroupsState = Record<AgentToolGroupId, boolean>;
export const AGENT_TOOL_GROUP_ORDER: readonly AgentToolGroupId[] = BUILTIN_TOOL_GROUPS;
export const DEFAULT_AGENT_TOOL_GROUPS: AgentToolGroupsState = { ...DEFAULT_DAEMON_TOOL_GROUPS };
export interface ResolvedAgentToolsState {
enabled: boolean;
groups: AgentToolGroupsState;
supportsGroupControls: boolean;
}
export function isHostAgentToolsEnabled(config: MutableDaemonConfig | null | undefined): boolean {
if (!config) return true;
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
}
export function resolveAgentToolsState(input: {
config: MutableDaemonConfig | null | undefined;
supportsToolsConfig: boolean;
}): ResolvedAgentToolsState {
const { config, supportsToolsConfig } = input;
const enabled = isHostAgentToolsEnabled(config);
const groups: AgentToolGroupsState = {
orchestration: config?.tools?.groups?.orchestration ?? DEFAULT_AGENT_TOOL_GROUPS.orchestration,
schedules: config?.tools?.groups?.schedules ?? DEFAULT_AGENT_TOOL_GROUPS.schedules,
changeRequests:
config?.tools?.groups?.changeRequests ?? DEFAULT_AGENT_TOOL_GROUPS.changeRequests,
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
browser: config?.tools?.groups?.browser ?? config?.browserTools.enabled === true,
};
return {
enabled,
groups,
supportsGroupControls: supportsToolsConfig,
};
}
export function createAgentToolsMasterPatch(input: {
enabled: boolean;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch {
if (input.supportsToolsConfig) {
return { tools: { enabled: input.enabled } };
}
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
return { mcp: { injectIntoAgents: input.enabled } };
}
export function createAgentToolGroupPatch(input: {
group: AgentToolGroupId;
enabled: boolean;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch | null {
if (input.supportsToolsConfig) {
return { tools: { groups: { [input.group]: input.enabled } } };
}
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
if (input.group === "browser") {
return { browserTools: { enabled: input.enabled } };
}
return null;
}
/**
* Setup only sets the main switch. It never writes tool groups, so the host keeps the groups saved
* in Settings. An unknown host state is always written.
*/
export function createOnboardingAgentToolsPatch(input: {
enabled: boolean;
currentEnabled: boolean | null;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch | null {
if (input.currentEnabled === input.enabled) return null;
return createAgentToolsMasterPatch(input);
}
@@ -1,147 +0,0 @@
import React, { act, useCallback, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { I18nextProvider } from "react-i18next";
import { SettingsCard } from "@/components/settings";
import { i18n } from "@/i18n/i18next";
import {
DEFAULT_AGENT_TOOL_GROUPS,
type AgentToolGroupId,
type AgentToolGroupsState,
} from "./agent-tools-config";
import { AgentToolsRow } from "./agent-tools-row";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function Harness({
initialEnabled = true,
initialGroups = DEFAULT_AGENT_TOOL_GROUPS,
supportsGroupControls = true,
}: {
initialEnabled?: boolean;
initialGroups?: AgentToolGroupsState;
supportsGroupControls?: boolean;
}) {
const [enabled, setEnabled] = useState(initialEnabled);
const [groups, setGroups] = useState<AgentToolGroupsState>(initialGroups);
const handleGroupChange = useCallback((group: AgentToolGroupId, next: boolean) => {
setGroups((current) => ({ ...current, [group]: next }));
}, []);
return (
<I18nextProvider i18n={i18n}>
<SettingsCard>
<AgentToolsRow
enabled={enabled}
groups={groups}
supportsGroupControls={supportsGroupControls}
onEnabledChange={setEnabled}
onGroupChange={handleGroupChange}
/>
</SettingsCard>
</I18nextProvider>
);
}
function mount(props?: React.ComponentProps<typeof Harness>) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(<Harness {...props} />);
});
}
function byTestId(testID: string): HTMLElement | null {
return document.querySelector(`[data-testid="${testID}"]`);
}
function expandButton(): HTMLElement {
const row = byTestId("host-page-tools-row-toggle");
const button = row?.querySelector('[role="button"]');
if (!(button instanceof HTMLElement)) {
throw new Error("Expected expand button in host-page-tools-row-toggle");
}
return button;
}
describe("AgentToolsRow collapsible behavior", () => {
it("starts collapsed, expands to show all four groups, and preserves selections when toggled off and on", () => {
mount({
initialEnabled: true,
initialGroups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
});
const masterSwitch = byTestId("host-page-tools-master-switch");
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
// Expand the row
act(() => {
expandButton().click();
});
expect(byTestId("host-page-tool-group-orchestration")).not.toBeNull();
expect(byTestId("host-page-tool-group-schedules")).not.toBeNull();
expect(byTestId("host-page-tool-group-changeRequests")).not.toBeNull();
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
expect(document.body.textContent).toContain("Tools added by plugins also follow Enable tools");
expect(document.body.textContent).not.toContain("MCP");
const browserSwitch = byTestId("host-page-browser-tools-switch")!;
const schedulesSwitch = byTestId("host-page-tool-group-schedules-switch")!;
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
// Turn master switch off: stays expanded, disables group switches, preserves selections
act(() => {
masterSwitch?.click();
});
expect(masterSwitch?.getAttribute("aria-checked")).toBe("false");
expect(browserSwitch.getAttribute("aria-disabled")).toBe("true");
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-disabled")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
// Turn master switch back on: group switches become interactive again with saved state
act(() => {
masterSwitch?.click();
});
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
});
it("shows only Browser and an update hint on older daemons without daemonToolsConfig", () => {
mount({ supportsGroupControls: false });
act(() => {
expandButton().click();
});
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
expect(byTestId("host-page-tool-group-schedules")).toBeNull();
expect(byTestId("host-page-tool-group-changeRequests")).toBeNull();
expect(document.body.textContent).toContain(
"Update this host to configure individual tool groups",
);
});
});
@@ -1,272 +0,0 @@
import { useMutation } from "@tanstack/react-query";
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { MutableDaemonConfigPatch } from "@getpaseo/protocol/messages";
import { SettingsCollapsibleRow, SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
AGENT_TOOL_GROUP_ORDER,
createAgentToolGroupPatch,
createAgentToolsMasterPatch,
resolveAgentToolsState,
type AgentToolGroupId,
type AgentToolGroupsState,
} from "./agent-tools-config";
const GROUP_TRANSLATION_KEYS: Record<
AgentToolGroupId,
{
title:
| "settings.host.tools.groups.orchestration.title"
| "settings.host.tools.groups.schedules.title"
| "settings.host.tools.groups.changeRequests.title"
| "settings.host.tools.groups.browser.title";
hint:
| "settings.host.tools.groups.orchestration.hint"
| "settings.host.tools.groups.schedules.hint"
| "settings.host.tools.groups.changeRequests.hint"
| "settings.host.tools.groups.browser.hint";
}
> = {
orchestration: {
title: "settings.host.tools.groups.orchestration.title",
hint: "settings.host.tools.groups.orchestration.hint",
},
schedules: {
title: "settings.host.tools.groups.schedules.title",
hint: "settings.host.tools.groups.schedules.hint",
},
changeRequests: {
title: "settings.host.tools.groups.changeRequests.title",
hint: "settings.host.tools.groups.changeRequests.hint",
},
browser: {
title: "settings.host.tools.groups.browser.title",
hint: "settings.host.tools.groups.browser.hint",
},
};
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function resolveHintStatus(
error: string | null | undefined,
isPending: boolean | undefined,
): "error" | "busy" | undefined {
if (error) return "error";
if (isPending) return "busy";
return undefined;
}
/** The host's expandable "Enable tools" row, bound to the host's config, for composing inside a SettingsCard. */
export function HostAgentToolsRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const state = useMemo(
() => resolveAgentToolsState({ config, supportsToolsConfig }),
[config, supportsToolsConfig],
);
const mutation = useMutation({
mutationFn: async (patch: MutableDaemonConfigPatch) => {
const result = await patchConfig(patch);
if (!result) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return result;
},
});
const handleEnabledChange = useCallback(
(enabled: boolean) => {
mutation.mutate(createAgentToolsMasterPatch({ enabled, supportsToolsConfig }));
},
[mutation, supportsToolsConfig],
);
const handleGroupChange = useCallback(
(group: AgentToolGroupId, enabled: boolean) => {
const patch = createAgentToolGroupPatch({ group, enabled, supportsToolsConfig });
if (!patch) return;
mutation.mutate(patch);
},
[mutation, supportsToolsConfig],
);
if (!isConnected) return null;
return (
<AgentToolsRow
enabled={state.enabled}
groups={state.groups}
supportsGroupControls={state.supportsGroupControls}
onEnabledChange={handleEnabledChange}
onGroupChange={handleGroupChange}
isPending={mutation.isPending}
error={mutation.error ? toErrorMessage(mutation.error) : null}
/>
);
}
/** Plain "Enable tools" switch with no group controls, for setup. Groups stay in Settings. */
export function EnableToolsSwitchRow({
value,
onValueChange,
disabled,
}: {
value: boolean;
onValueChange: (enabled: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
return (
<SettingsRow
label={t("settings.host.orchestration.enableTools.title")}
hint={t("settings.host.orchestration.enableTools.hint")}
>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
/>
</SettingsRow>
);
}
/** Expandable "Enable tools" row on its own, for callers that control the state. */
export function AgentToolsRow({
enabled,
groups,
supportsGroupControls,
onEnabledChange,
onGroupChange,
disabled,
isPending,
error,
}: {
enabled: boolean;
groups: AgentToolGroupsState;
supportsGroupControls: boolean;
onEnabledChange: (enabled: boolean) => void;
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
disabled?: boolean;
isPending?: boolean;
error?: string | null;
}) {
const { t } = useTranslation();
const visibleGroups: readonly AgentToolGroupId[] = supportsGroupControls
? AGENT_TOOL_GROUP_ORDER
: ["browser"];
const controlsDisabled = Boolean(disabled || isPending);
const hint = error ?? t("settings.host.orchestration.enableTools.hint");
const hintStatus = resolveHintStatus(error, isPending);
const masterControl = useMemo(
() => (
<Switch
value={enabled}
onValueChange={onEnabledChange}
disabled={controlsDisabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
testID="host-page-tools-master-switch"
/>
),
[controlsDisabled, enabled, onEnabledChange, t],
);
return (
<SettingsCollapsibleRow
label={t("settings.host.orchestration.enableTools.title")}
hint={hint}
hintStatus={hintStatus}
control={masterControl}
testID="host-page-tools-row"
>
{visibleGroups.map((group) => (
<ToolGroupSwitchRow
key={group}
group={group}
value={groups[group]}
disabled={controlsDisabled || !enabled}
dimmed={!enabled}
onGroupChange={onGroupChange}
/>
))}
<View style={styles.noteRow}>
<Text style={settingsStyles.rowHint}>
{supportsGroupControls
? t("settings.host.tools.pluginNote")
: t("settings.host.tools.updateHostForGroups")}
</Text>
</View>
</SettingsCollapsibleRow>
);
}
function ToolGroupSwitchRow({
group,
value,
disabled,
dimmed,
onGroupChange,
}: {
group: AgentToolGroupId;
value: boolean;
disabled: boolean;
dimmed: boolean;
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
}) {
const { t } = useTranslation();
const keys = GROUP_TRANSLATION_KEYS[group];
const label = t(keys.title);
const handleChange = useCallback(
(next: boolean) => {
onGroupChange(group, next);
},
[group, onGroupChange],
);
return (
<View style={dimmed ? styles.disabledGroup : undefined}>
<SettingsRow
label={label}
hint={t(keys.hint)}
testID={
group === "browser" ? "host-page-browser-tools-card" : `host-page-tool-group-${group}`
}
>
<Switch
value={value}
onValueChange={handleChange}
disabled={disabled}
accessibilityLabel={label}
testID={
group === "browser"
? "host-page-browser-tools-switch"
: `host-page-tool-group-${group}-switch`
}
/>
</SettingsRow>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
disabledGroup: {
opacity: theme.opacity[50],
},
noteRow: {
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[2],
},
}));
@@ -0,0 +1,74 @@
import React, { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
createBrowserToolsPatch,
getBrowserToolsCardState,
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
export function BrowserToolsRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const state = getBrowserToolsCardState({ isConnected, config });
const mutation = useMutation({
mutationFn: async (next: boolean) => {
const result = await patchConfig(createBrowserToolsPatch(next));
if (!result) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return result;
},
});
const mutationView = getBrowserToolsMutationViewState({
isPending: mutation.isPending,
error: mutation.error,
});
const handleValueChange = useCallback(
(next: boolean) => {
mutation.mutate(next);
},
[mutation],
);
const hint = useMemo(
() => (
<View>
<Text style={settingsStyles.rowHint}>{state.warning}</Text>
{mutationView.loadingText ? (
<Text style={settingsStyles.rowHint} testID="host-page-browser-tools-loading">
{mutationView.loadingText}
</Text>
) : null}
</View>
),
[mutationView.loadingText, state.warning],
);
if (!state.isVisible) return null;
return (
<SettingsRow
label={state.title}
hint={hint}
error={mutationView.errorText ?? undefined}
testID="host-page-browser-tools-card"
>
<Switch
value={state.isEnabled}
onValueChange={handleValueChange}
disabled={mutationView.isSwitchDisabled}
accessibilityLabel="Enable browser tools"
testID="host-page-browser-tools-switch"
/>
</SettingsRow>
);
}
@@ -0,0 +1,71 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
BROWSER_TOOLS_WARNING,
createBrowserToolsPatch,
getBrowserToolsCardState,
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
function makeConfig(browserToolsEnabled = false): MutableDaemonConfig {
return {
relay: { enabled: false },
mcp: { injectIntoAgents: false },
browserTools: { enabled: browserToolsEnabled },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
};
}
describe("browser tools opt-in config", () => {
it("shows the card with the logged-in browser state warning when connected", () => {
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(false) })).toEqual({
isVisible: true,
isEnabled: false,
title: "Browser tools",
warning: BROWSER_TOOLS_WARNING,
});
});
it("reads enabled state from daemon config", () => {
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(true) })).toMatchObject(
{
isEnabled: true,
},
);
});
it("hides the card when the host is disconnected", () => {
expect(
getBrowserToolsCardState({ isConnected: false, config: makeConfig(true) }),
).toMatchObject({
isVisible: false,
});
});
it("writes daemon.browserTools.enabled when toggled", () => {
expect(createBrowserToolsPatch(true)).toEqual({ browserTools: { enabled: true } });
expect(createBrowserToolsPatch(false)).toEqual({ browserTools: { enabled: false } });
});
it("shows loading and disables the toggle while browser tool settings save", () => {
expect(getBrowserToolsMutationViewState({ isPending: true, error: null })).toEqual({
isSwitchDisabled: true,
loadingText: "Updating browser tools…",
errorText: null,
});
});
it("shows the save error when browser tool settings fail", () => {
expect(
getBrowserToolsMutationViewState({ isPending: false, error: new Error("Disk full") }),
).toEqual({
isSwitchDisabled: false,
loadingText: null,
errorText: "Disk full",
});
});
});
@@ -0,0 +1,49 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
export const BROWSER_TOOLS_TITLE = "Browser tools";
export const BROWSER_TOOLS_WARNING =
"Allow agents to access and control Paseo browser tabs, including logged-in browser state. Only enable this for agents you trust.";
export interface BrowserToolsCardState {
isVisible: boolean;
isEnabled: boolean;
title: string;
warning: string;
}
export interface BrowserToolsMutationViewState {
isSwitchDisabled: boolean;
loadingText: string | null;
errorText: string | null;
}
export function getBrowserToolsCardState(input: {
isConnected: boolean;
config: MutableDaemonConfig | null;
}): BrowserToolsCardState {
return {
isVisible: input.isConnected,
isEnabled: input.config?.browserTools.enabled === true,
title: BROWSER_TOOLS_TITLE,
warning: BROWSER_TOOLS_WARNING,
};
}
export function createBrowserToolsPatch(enabled: boolean): Partial<MutableDaemonConfig> {
return { browserTools: { enabled } };
}
export function getBrowserToolsMutationViewState(input: {
isPending: boolean;
error: unknown;
}): BrowserToolsMutationViewState {
return {
isSwitchDisabled: input.isPending,
loadingText: input.isPending ? "Updating browser tools…" : null,
errorText: input.error ? toErrorMessage(input.error) : null,
};
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -61,7 +61,8 @@ import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons
import { ICON_SIZE } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import { useProviderIcon } from "@/components/provider-icons";
import { HostAgentToolsRow } from "./agent-tools-row";
import { BrowserToolsRow } from "./browser-tools-card";
import { HostPaseoToolsRow } from "./paseo-tools-card";
import { RestartRecoveryRow } from "./restart-recovery-card";
import { IdleRuntimeCleanupRow } from "./idle-runtime-cleanup-card";
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
@@ -260,7 +261,8 @@ export function HostToolsPage({ serverId }: { serverId: string }) {
</SettingsSection>
<SettingsSection title={t("settings.host.tools.toolsTitle")}>
<SettingsCard testID="host-page-inject-mcp-card">
<HostAgentToolsRow serverId={serverId} />
<HostPaseoToolsRow serverId={serverId} />
<BrowserToolsRow serverId={serverId} />
</SettingsCard>
</SettingsSection>
</>
@@ -0,0 +1,54 @@
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
/** The host's "give agents Paseo tools" row, bound to the host's config, for composing inside a SettingsCard. */
export function HostPaseoToolsRow({ serverId }: { serverId: string }) {
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const handleValueChange = useCallback(
(next: boolean) => {
void patchConfig({ mcp: { injectIntoAgents: next } });
},
[patchConfig],
);
if (!isConnected) return null;
return (
<PaseoToolsRow
value={config?.mcp.injectIntoAgents !== false}
onValueChange={handleValueChange}
/>
);
}
/** The Paseo tools row on its own, for a caller that decides what the switch is bound to. */
export function PaseoToolsRow({
value,
onValueChange,
disabled,
}: {
value: boolean;
onValueChange: (next: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
return (
<SettingsRow
label={t("settings.host.orchestration.enableTools.title")}
hint={t("settings.host.orchestration.enableTools.hint")}
>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
/>
</SettingsRow>
);
}
@@ -1,62 +0,0 @@
// @vitest-environment jsdom
import { render } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { RetainedPanelActivity } from "@/components/retained-panel";
import {
createPostRestoreRevealHolds,
type PostRestoreRevealHolds,
PostRestoreRevealHoldsProvider,
usePostRestoreRevealHold,
} from "./post-restore-reveal-holds";
function Chrome({ pending }: { pending: boolean }) {
usePostRestoreRevealHold(pending);
return null;
}
function Workspace(props: {
holds: PostRestoreRevealHolds | null;
pending: boolean;
onScreen: boolean;
mounted?: boolean;
}) {
return (
<PostRestoreRevealHoldsProvider holds={props.holds}>
<RetainedPanelActivity active={props.onScreen}>
{props.mounted === false ? null : <Chrome pending={props.pending} />}
</RetainedPanelActivity>
</PostRestoreRevealHoldsProvider>
);
}
describe("post-restore reveal holds", () => {
it("holds the reveal while on-screen chrome is pending and releases when it settles", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
expect(holds.isHeld()).toBe(true);
view.rerender(<Workspace holds={holds} pending={false} onScreen />);
expect(holds.isHeld()).toBe(false);
});
it("does not hold for chrome in a hidden pane", () => {
const holds = createPostRestoreRevealHolds();
render(<Workspace holds={holds} pending onScreen={false} />);
expect(holds.isHeld()).toBe(false);
});
it("releases when pending chrome unmounts", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
view.rerender(<Workspace holds={holds} pending onScreen mounted={false} />);
expect(holds.isHeld()).toBe(false);
});
it("releases when the handoff ends and the provider stops offering holds", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
view.rerender(<Workspace holds={null} pending onScreen />);
expect(holds.isHeld()).toBe(false);
});
});
@@ -1,77 +0,0 @@
import {
createContext,
type ReactNode,
useContext,
useLayoutEffect,
useSyncExternalStore,
} from "react";
import { useRetainedPanelActive } from "@/components/retained-panel";
/**
* Workspace chrome mounted behind the `Restoring...` gate that has nothing to show until a layout
* pass answers it. The gate stays up while any on-screen chrome holds it.
*/
export interface PostRestoreRevealHolds {
hold: () => () => void;
subscribe: (listener: () => void) => () => void;
isHeld: () => boolean;
}
export function createPostRestoreRevealHolds(): PostRestoreRevealHolds {
let count = 0;
const listeners = new Set<() => void>();
const notify = () => {
for (const listener of listeners) listener();
};
return {
hold: () => {
count += 1;
notify();
let released = false;
return () => {
if (released) return;
released = true;
count -= 1;
notify();
};
},
subscribe: (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
isHeld: () => count > 0,
};
}
const PostRestoreRevealHoldsContext = createContext<PostRestoreRevealHolds | null>(null);
/** `holds` is null outside a post-restore handoff, so chrome mounting normally never holds. */
export function PostRestoreRevealHoldsProvider({
holds,
children,
}: {
holds: PostRestoreRevealHolds | null;
children: ReactNode;
}) {
return <PostRestoreRevealHoldsContext value={holds}>{children}</PostRestoreRevealHoldsContext>;
}
/**
* Holds the post-restore reveal while `pending`. A hidden pane or a closed explorer never lays
* out, so only chrome that is on screen holds.
*/
export function usePostRestoreRevealHold(pending: boolean): void {
const holds = useContext(PostRestoreRevealHoldsContext);
const isOnScreen = useRetainedPanelActive();
const isHolding = pending && isOnScreen;
useLayoutEffect(() => {
if (!isHolding || !holds) return;
return holds.hold();
}, [holds, isHolding]);
}
export function usePostRestoreRevealHeld(holds: PostRestoreRevealHolds): boolean {
return useSyncExternalStore(holds.subscribe, holds.isHeld, holds.isHeld);
}
@@ -4,6 +4,7 @@ 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);
@@ -38,6 +39,23 @@ 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,
@@ -1,164 +0,0 @@
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,21 +1,25 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef } from "react";
import * as Clipboard from "expo-clipboard";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type { TunnelProviderInfo } from "@getpaseo/protocol/tunnels";
import type { WorkspaceDescriptor } from "@/stores/session-store";
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 type TunnelProvidersLoadStatus = "idle" | "loading" | "ready" | "error";
export interface WorkspaceScriptLinks {
/** The URL this host's route preference picks, or null when the script serves none. */
selected: WorkspaceScriptLinkTarget | null;
targets: WorkspaceScriptLinkTarget[];
}
export interface WorkspaceScriptActions {
serverId?: string;
@@ -24,42 +28,23 @@ export interface WorkspaceScriptActions {
/** Stops the script, then starts it again once the daemon reports it stopped. */
restart: (scriptName: string) => void;
copyUrl: (target: WorkspaceScriptLinkTarget) => void;
resolveLocalLink: (script: WorkspaceScript) => WorkspaceScriptLinkTarget | null;
selectRoute: (kind: WorkspaceScriptLinkKind) => void;
resolveLinks: (script: WorkspaceScript) => WorkspaceScriptLinks;
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"
| "listTunnelProviders"
| "openWorkspaceScriptTunnel"
| "closeWorkspaceScriptTunnel"
> | null;
client: Pick<DaemonClient, "startWorkspaceScript" | "killTerminal"> | null;
serverId: string;
workspaceId: string;
scripts: WorkspaceDescriptor["scripts"];
onScriptTerminalStarted?: (terminalId: string) => void;
}
const TUNNEL_PROVIDERS_STALE_MS = 15_000;
/**
* Run, stop, restart, local URL, and on-demand tunnel handling for a workspace's scripts,
* shared by every surface that lists them.
* Run, stop, restart and URL 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
@@ -75,49 +60,13 @@ export function useWorkspaceScriptActions({
const { t } = useTranslation();
const toast = useToast();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
// 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 preferredRouteKind = useWorkspaceServiceRoutePreferencesStore(
(state) => state.byServerId[serverId] ?? null,
);
const setPreferredRoute = useWorkspaceServiceRoutePreferencesStore(
(state) => state.setPreferredRoute,
);
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) => {
@@ -176,89 +125,6 @@ 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(() => {
@@ -271,24 +137,6 @@ 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);
@@ -305,57 +153,19 @@ export function useWorkspaceScriptActions({
[toast],
);
const resolveLocalLink = useCallback(
(script: WorkspaceScript): WorkspaceScriptLinkTarget | null =>
resolveWorkspaceScriptLink({ script, activeConnection }),
[activeConnection],
const selectRoute = useCallback(
(kind: WorkspaceScriptLinkKind) => setPreferredRoute(serverId, kind),
[serverId, setPreferredRoute],
);
const openTunnel = useCallback(
(script: WorkspaceScript, providerId: string) => {
mutateOpenTunnel({ script, providerId });
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 };
},
[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],
[activeConnection, preferredRouteKind],
);
return useMemo(
@@ -365,20 +175,10 @@ export function useWorkspaceScriptActions({
stop: stopScript,
restart,
copyUrl,
resolveLocalLink,
selectRoute,
resolveLinks,
isStartPending: startScriptMutation.isPending,
isStopPending: stopScriptMutation.isPending,
supportsTunnels,
tunnelProviders,
tunnelProvidersStatus,
tunnelProvidersError,
loadTunnelProviders,
openTunnel,
closeTunnel,
isOpeningTunnel,
isClosingTunnel,
getTunnelError,
getTunnelProviderLabel,
}),
[
serverId,
@@ -386,50 +186,10 @@ export function useWorkspaceScriptActions({
stopScript,
restart,
copyUrl,
resolveLocalLink,
selectRoute,
resolveLinks,
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[] = [];
@@ -1,210 +0,0 @@
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,16 +3,14 @@
*/
import { i18n as testI18n } from "@/i18n/i18next";
import React, { type ReactElement } from "react";
import { act, fireEvent, waitFor } from "@testing-library/react";
import { act, fireEvent } 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;
@@ -20,29 +18,23 @@ const {
theme,
startWorkspaceScriptMock,
killTerminalMock,
listTunnelProvidersMock,
openWorkspaceScriptTunnelMock,
closeWorkspaceScriptTunnelMock,
setStringAsyncMock,
copiedToastMock,
openExternalUrlMock,
openedSubPagesMock,
sessionStateMock,
routePreferenceByServerIdMock,
routePreferenceListenersMock,
setPreferredRouteMock,
} = 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: 12, base: 13 },
fontSize: { xs: 11, sm: 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" },
@@ -51,6 +43,13 @@ 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 () => ({
@@ -65,33 +64,11 @@ 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(),
openExternalUrlMock: vi.fn(),
openedSubPagesMock: vi.fn((_id: string) => {}),
sessionStateMock: {
supportsTunnels: false,
},
routePreferenceByServerIdMock: routePreferenceByServerId,
routePreferenceListenersMock: routePreferenceListeners,
setPreferredRouteMock: setPreferredRoute,
};
});
@@ -125,34 +102,24 @@ vi.mock("@/runtime/host-runtime", () => ({
useHostRuntimeSnapshot: () => ({ activeConnection: null }),
}));
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(),
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);
},
},
}),
}));
() => selector(state),
() => selector(state),
),
};
});
vi.mock("@/contexts/toast-context", () => ({
useToast: () => ({ show: vi.fn(), error: vi.fn(), copied: copiedToastMock }),
@@ -163,82 +130,30 @@ vi.mock("expo-clipboard", () => ({
}));
vi.mock("@/utils/open-external-url", () => ({
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,
}),
openExternalUrl: vi.fn(),
}));
vi.mock("@/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{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>
DropdownMenuContent: ({ children, testID }: { children: React.ReactNode; testID?: string }) => (
<div data-testid={testID}>{children}</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;
}) => (
<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>
<button type="button" data-testid={testID} onClick={onSelect}>
{children}
{description}
</button>
),
DropdownMenuTrigger: ({
children,
@@ -256,12 +171,6 @@ 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", () => ({
@@ -285,11 +194,8 @@ 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"),
@@ -309,10 +215,9 @@ function script(
type: input.type ?? "script",
hostname: input.hostname ?? input.scriptName,
port: input.port ?? null,
localProxyUrl: input.localProxyUrl ?? null,
publicProxyUrl: input.publicProxyUrl ?? null,
localProxyUrl: input.localProxyUrl,
publicProxyUrl: input.publicProxyUrl,
proxyUrl: input.proxyUrl ?? null,
tunnel: input.tunnel ?? null,
lifecycle: input.lifecycle ?? "stopped",
health: input.health ?? null,
exitCode: input.exitCode ?? null,
@@ -324,26 +229,19 @@ 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,
@@ -351,32 +249,13 @@ 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}
/>
{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}
</>
<WorkspaceScriptsButton
actions={actions}
scripts={scripts}
liveTerminalIds={LIVE_TERMINAL_IDS}
hideLabels={hideLabels}
/>
);
}
@@ -401,11 +280,7 @@ function renderScripts(
return (
<QueryClientProvider client={queryClient}>
<ToastApiProvider api={testToast}>
<ScriptsOwner
scripts={nextScripts}
hideLabels={options.hideLabels}
includeSheetPages={options.includeSheetPages}
/>
<ScriptsOwner scripts={nextScripts} hideLabels={options.hideLabels} />
</ToastApiProvider>
</QueryClientProvider>
);
@@ -461,27 +336,14 @@ 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();
openExternalUrlMock.mockClear();
setPreferredRouteMock.mockClear();
for (const serverId of Object.keys(routePreferenceByServerIdMock)) {
delete routePreferenceByServerIdMock[serverId];
}
});
afterEach(() => {
@@ -543,6 +405,7 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "web",
type: "service",
hostname: "web.paseo.localhost",
lifecycle: "running",
health: "healthy",
port: 3000,
@@ -550,6 +413,7 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "api",
type: "service",
hostname: "api.paseo.localhost",
lifecycle: "running",
health: "unhealthy",
port: 4000,
@@ -557,6 +421,7 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "worker",
type: "service",
hostname: "worker.paseo.localhost",
lifecycle: "running",
health: null,
port: 5000,
@@ -564,6 +429,7 @@ describe("WorkspaceScriptsButton", () => {
script({
scriptName: "old-service",
type: "service",
hostname: "old-service.paseo.localhost",
lifecycle: "stopped",
exitCode: 1,
}),
@@ -588,368 +454,57 @@ describe("WorkspaceScriptsButton", () => {
expect(trigger?.querySelector('[data-icon="ChevronDown"]')).not.toBeNull();
});
it("shows localhost:<port> directly and copies it without a route selector", () => {
current = renderScripts([
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");
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");
current.unmount();
current = renderScripts(scripts);
expect(requireRow("dev").textContent).toContain("localhost:57483");
});
it("hides Tunnel controls on a daemon with tunnel providers but no script tunnels", () => {
sessionStateMock.supportsTunnels = false;
it("defaults to a configured reverse proxy URL", () => {
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(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");
expect(requireRow("dev").textContent).toContain("dev--proj--repo.services.example.com");
});
it("stops a running script through its terminal", async () => {
@@ -1014,6 +569,7 @@ describe("WorkspaceScriptsButton", () => {
type: "service",
lifecycle: "running",
port: 3000,
proxyUrl: "http://dev--project.localhost:6767",
terminalId: "terminal-script-1",
}),
]);
@@ -1030,6 +586,9 @@ 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,9 +3,7 @@ import type { GestureResponderEvent } from "react-native";
import { Pressable, Text, View } from "react-native";
import {
ChevronDown,
ChevronRight,
Copy,
ExternalLink,
Eye,
Play,
RotateCw,
@@ -18,26 +16,25 @@ 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 { stripUrlProtocol, type WorkspaceScriptLinkTarget } from "@/utils/workspace-script-links";
import type {
WorkspaceScriptLinkKind,
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, ScriptIcon } from "./script-marks";
import { ExitCodeBadge, routeLabelKey, 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" | "external" | "open" | "restart" | "start" | "stop" | "terminal";
type RowActionIcon = "copy" | "open" | "restart" | "start" | "stop" | "terminal";
interface WorkspaceScriptsButtonProps {
actions: WorkspaceScriptActions;
@@ -52,12 +49,9 @@ 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,
@@ -67,10 +61,6 @@ const mutedColorMapping = (theme: Theme) => ({
});
const playFillTransparent = { fill: "transparent" };
function tunnelPageId(scriptName: string): string {
return `workspace-scripts-tunnel/${scriptName}`;
}
interface ScriptRowActionButtonProps {
accessibilityLabel: string;
disabled?: boolean;
@@ -91,8 +81,6 @@ 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":
@@ -149,31 +137,154 @@ function ScriptRowActionButton({
);
}
function ServiceLocalLinkRow({
target,
scriptName,
onCopy,
}: {
target: WorkspaceScriptLinkTarget;
interface ServiceLinkRowProps {
selectedTarget: WorkspaceScriptLinkTarget;
targets: WorkspaceScriptLinkTarget[];
scriptName: string;
onSelectKind: (kind: WorkspaceScriptLinkKind) => void;
onCopy: (target: WorkspaceScriptLinkTarget) => void;
}
function ServiceRouteOption({
scriptName,
selectedKind,
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 {
const { t } = useTranslation();
const closeMenu = useDropdownMenuClose();
const { label } = selectedTarget;
const handleCopy = useCallback(() => {
closeMenu();
onCopy(target);
}, [target, onCopy, closeMenu]);
onCopy(selectedTarget);
}, [selectedTarget, onCopy, closeMenu]);
return (
<View style={styles.hostRow}>
<View style={styles.routeDisplay}>
<View style={styles.leadingSlot} />
<Text style={styles.hostLabel} numberOfLines={1}>
{target.label}
</Text>
</View>
{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>
)}
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.copyUrl", { scriptName })}
testID={`workspace-scripts-copy-${scriptName}`}
@@ -185,276 +296,8 @@ function ServiceLocalLinkRow({
);
}
/**
* 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: WorkspaceScript;
script: WorkspaceDescriptor["scripts"][number];
liveTerminalIdSet: Set<string>;
actions: WorkspaceScriptActions;
onViewTerminal?: (terminalId: string) => void;
@@ -471,23 +314,21 @@ function ScriptRow({
const { t } = useTranslation();
const isRunning = script.lifecycle === "running";
const exitCode = script.exitCode ?? null;
const localLink = actions.resolveLocalLink(script);
const { selected: selectedLink, targets: linkTargets } = actions.resolveLinks(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 (!localLink) return;
if (!selectedLink) return;
closeMenu();
void openServiceUrl(localLink.url, {
void openServiceUrl(selectedLink.url, {
openInApp: onOpenUrlInBrowserTab,
serverId: actions.serverId,
});
}, [actions.serverId, localLink, closeMenu, onOpenUrlInBrowserTab]);
}, [actions.serverId, selectedLink, closeMenu, onOpenUrlInBrowserTab]);
const handleView = useCallback(() => {
if (liveTerminalId) onViewTerminal?.(liveTerminalId);
@@ -523,7 +364,7 @@ function ScriptRow({
/>
) : null;
const openServiceAction = localLink ? (
const openServiceAction = selectedLink ? (
<ScriptRowActionButton
accessibilityLabel={t("workspace.scripts.accessibility.openService", {
scriptName: script.scriptName,
@@ -589,16 +430,15 @@ function ScriptRow({
) : null}
{lifecycleAction}
</View>
{localLink || showTunnelSection ? (
{selectedLink ? (
<View style={styles.hostList}>
{localLink ? (
<ServiceLocalLinkRow
target={localLink}
scriptName={script.scriptName}
onCopy={actions.copyUrl}
/>
) : null}
{showTunnelSection ? <ServiceTunnelRows script={script} actions={actions} /> : null}
<ServiceLinkRow
selectedTarget={selectedLink}
targets={linkTargets}
scriptName={script.scriptName}
onSelectKind={actions.selectRoute}
onCopy={actions.copyUrl}
/>
</View>
) : null}
</View>
@@ -624,33 +464,6 @@ 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;
}
@@ -662,7 +475,7 @@ export function WorkspaceScriptsButton({
return (
<View style={styles.row}>
<View style={styles.splitButton}>
<DropdownMenu onOpenChange={handleOpenChange}>
<DropdownMenu>
<DropdownMenuTrigger
testID="workspace-scripts-button"
style={triggerStyle}
@@ -679,9 +492,8 @@ export function WorkspaceScriptsButton({
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
minWidth={220}
maxWidth={300}
pages={tunnelPages}
minWidth={200}
maxWidth={280}
testID="workspace-scripts-menu"
>
{scripts.map((script) => (
@@ -765,16 +577,14 @@ 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,
},
@@ -786,13 +596,6 @@ 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,
@@ -802,12 +605,26 @@ 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,46 +1,33 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { View } from "react-native";
import {
Copy,
ExternalLink,
Eye,
Play,
Radio,
RotateCw,
Square,
SquareTerminal,
} from "lucide-react-native";
import { Copy, Eye, Play, 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 { stripUrlProtocol } from "@/utils/workspace-script-links";
import { ExitCodeBadge, ScriptIcon } from "./script-marks";
import type {
WorkspaceScriptLinkKind,
WorkspaceScriptLinkTarget,
} from "@/utils/workspace-script-links";
import { ExitCodeBadge, routeLabelKey, 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" };
@@ -49,8 +36,6 @@ 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} />
);
@@ -60,7 +45,6 @@ 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";
@@ -68,10 +52,6 @@ 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"];
@@ -90,7 +70,7 @@ export interface WorkspaceScriptsMenuPages {
/**
* Workspace scripts as pages of a sheet menu: a Scripts row on the root, a page listing every
* script, one page per script, and a tunnel provider picker page for running services.
* script, and one page per script.
*
* 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.
@@ -115,23 +95,6 @@ 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,
@@ -155,7 +118,6 @@ export function useWorkspaceScriptsMenuPages({
/>
),
})),
...tunnelPages,
];
}, [actions, liveTerminalIds, onOpenUrlInBrowserTab, onViewTerminal, scripts, t]);
@@ -281,131 +243,9 @@ 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 tunnel controls stay: the page is where their result shows.
* Stop and the URL choice stay: the page is where their result shows.
*/
function RunningScriptPage({
script,
@@ -416,30 +256,28 @@ function RunningScriptPage({
}: ScriptPageProps): ReactElement {
const { t } = useTranslation();
const { scriptName } = script;
const localLink = actions.resolveLocalLink(script);
const { stop, restart, copyUrl } = actions;
const showTunnelSection =
actions.supportsTunnels && script.type === "service" && script.port !== null;
const { selected, targets } = actions.resolveLinks(script);
const { stop, restart, copyUrl, selectRoute } = actions;
const handleOpenService = useCallback(() => {
if (!localLink) return;
void openServiceUrl(localLink.url, {
if (!selected) return;
void openServiceUrl(selected.url, {
openInApp: onOpenUrlInBrowserTab,
serverId: actions.serverId,
});
}, [actions.serverId, localLink, onOpenUrlInBrowserTab]);
}, [actions.serverId, selected, onOpenUrlInBrowserTab]);
const handleViewTerminal = useCallback(() => {
if (liveTerminalId) onViewTerminal(liveTerminalId);
}, [liveTerminalId, onViewTerminal]);
const handleCopyUrl = useCallback(() => {
if (localLink) copyUrl(localLink);
}, [localLink, copyUrl]);
if (selected) copyUrl(selected);
}, [selected, copyUrl]);
const handleRestart = useCallback(() => restart(scriptName), [restart, scriptName]);
const handleStop = useCallback(() => stop(scriptName), [stop, scriptName]);
return (
<>
{localLink ? (
{selected ? (
<DropdownMenuItem
leading={OPEN_SERVICE_ICON}
onSelect={handleOpenService}
@@ -457,23 +295,16 @@ function RunningScriptPage({
{t("workspace.scripts.actions.view")}
</DropdownMenuItem>
) : null}
{localLink ? (
{selected ? (
<DropdownMenuItem
leading={COPY_URL_ICON}
description={localLink.label}
description={selected.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}
@@ -491,10 +322,52 @@ function RunningScriptPage({
>
{t("workspace.scripts.actions.stop")}
</DropdownMenuItem>
{selected && targets.length > 1 ? (
<>
<DropdownMenuSeparator />
{targets.map((target) => (
<ServiceRouteOption
key={target.kind}
scriptName={scriptName}
target={target}
selected={target.kind === selected.kind}
onSelect={selectRoute}
/>
))}
</>
) : null}
</>
);
}
/** A pick-one URL route. Choosing one keeps the page open so the check moves under the thumb. */
function ServiceRouteOption({
scriptName,
target,
selected,
onSelect,
}: {
scriptName: string;
target: WorkspaceScriptLinkTarget;
selected: boolean;
onSelect: (kind: WorkspaceScriptLinkKind) => void;
}): ReactElement {
const { t } = useTranslation();
const handleSelect = useCallback(() => onSelect(target.kind), [onSelect, target.kind]);
return (
<DropdownMenuItem
selected={selected}
showSelectedCheck
description={target.label}
closeOnSelect={false}
onSelect={handleSelect}
testID={`workspace-script-${scriptName}-route-${target.kind}`}
>
{t(routeLabelKey(target.kind))}
</DropdownMenuItem>
);
}
function StoppedScriptPage({
script,
actions,
@@ -1,9 +1,4 @@
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import {
createPostRestoreRevealHolds,
type PostRestoreRevealHolds,
usePostRestoreRevealHeld,
} from "@/screens/workspace/post-restore-reveal-holds";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import type { WorkspaceRouteState } from "@/screens/workspace/workspace-route-state";
@@ -106,7 +101,6 @@ export function resolvePostRestoreDisplayedRouteState(input: {
visibleAgentsTimelineSynced: boolean;
visibleAgentsVisibilityStatus: ViewedTimelineStatus;
visibleAgentsLoadingOlder: boolean;
isRevealHeld: boolean;
routeState: WorkspaceRouteState;
}): {
displayedRouteState: WorkspaceRouteState;
@@ -125,7 +119,6 @@ export function resolvePostRestoreDisplayedRouteState(input: {
visibleAgentsTimelineSynced,
visibleAgentsVisibilityStatus,
visibleAgentsLoadingOlder,
isRevealHeld,
routeState,
} = input;
const isRestoringNow =
@@ -145,7 +138,6 @@ export function resolvePostRestoreDisplayedRouteState(input: {
const isHandoffReadyToMount = hasReconciledTabs && areVisibleAgentsReadyToMount;
const isHandoffReadyToRelease =
isHandoffReadyToMount &&
!isRevealHeld &&
(visibleAgentsVisibilityStatus === "error" || !visibleAgentsLoadingOlder);
return {
displayedRouteState: isWaitingForHandoffReveal ? handoff.archivedState : routeState,
@@ -176,7 +168,6 @@ export function usePostRestoreWorkspaceRouteState(input: {
paneFocusSuspended: boolean;
}): {
displayedRouteState: WorkspaceRouteState;
revealHolds: PostRestoreRevealHolds;
isHoldingHandoff: boolean;
isPaneRouteFocused: boolean;
effectivePaneFocusSuspended: boolean;
@@ -200,8 +191,6 @@ export function usePostRestoreWorkspaceRouteState(input: {
const scopeKey = `${serverId}:${workspaceId}`;
const [handoff, setHandoff] = useState<PostRestoreHandoffState | null>(null);
const [mountedHandoff, setMountedHandoff] = useState<PostRestoreHandoffState | null>(null);
const [revealHolds] = useState(createPostRestoreRevealHolds);
const isRevealHeld = usePostRestoreRevealHeld(revealHolds);
const reconciledHandoff = nextPostRestoreHandoff({ current: handoff, scopeKey, routeState });
if (reconciledHandoff !== handoff) {
@@ -282,7 +271,6 @@ export function usePostRestoreWorkspaceRouteState(input: {
visibleAgentsTimelineSynced,
visibleAgentsVisibilityStatus,
visibleAgentsLoadingOlder,
isRevealHeld,
routeState,
});
@@ -298,8 +286,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
useEffect(() => {
if (!isWaitingForHandoffReveal) return;
if (isHandoffReadyToRelease) {
// Chrome that waits on its own layout (tab label measurement) holds the reveal explicitly.
// The frames let stream row ResizeObservers commit and any underfilled history fetch start.
// Wait 3 rAFs after hidden workspace chrome mounts so tab label `onLayout` and stream row
// ResizeObservers commit (and any underfilled history fetch starts) before lifting overlay.
return scheduleAnimationFrames(POST_RESTORE_LAYOUT_SETTLE_FRAMES, () => {
setHandoff(null);
});
@@ -312,7 +300,6 @@ export function usePostRestoreWorkspaceRouteState(input: {
return {
displayedRouteState,
revealHolds,
isHoldingHandoff: isMountedBehindOverlay,
isPaneRouteFocused: isRouteFocused && !isMountedBehindOverlay,
effectivePaneFocusSuspended: paneFocusSuspended || isMountedBehindOverlay,
@@ -96,7 +96,6 @@ import {
useHorizontalScrollBoundary,
} from "@/components/ui/horizontal-scroll-boundary";
import { useSessionStore } from "@/stores/session-store";
import { usePostRestoreRevealHold } from "@/screens/workspace/post-restore-reveal-holds";
const DROPDOWN_WIDTH = 220;
const DEFAULT_INLINE_ADD_BUTTON_RESERVED_WIDTH = 36;
@@ -1063,7 +1062,6 @@ export function WorkspaceDesktopTabsRow(props: WorkspaceDesktopTabsRowProps) {
}),
[presentations, props.tabs],
);
usePostRestoreRevealHold(resolvedTabs.length < props.tabs.length);
return (
<>
@@ -1247,7 +1245,6 @@ function ResolvedWorkspaceDesktopTabsRow({
useLayoutEffect(() => {
publishMeasuredTrack();
}, [publishMeasuredTrack]);
usePostRestoreRevealHold(tabs.length > 0 && trackSnapshot?.signature !== tabLabelSignature);
const handleTabLabelLayout = useCallback(
(key: string, label: string, event: LayoutChangeEvent) => {
@@ -264,7 +264,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingTabs.displayedRouteState).toBe(restoringState);
@@ -284,7 +283,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "checking",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingTimeline.displayedRouteState).toBe(restoringState);
@@ -303,7 +301,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "checking",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingCatchUp.displayedRouteState).toBe(restoringState);
@@ -322,7 +319,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: true,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingOlderFill.isHandoffReadyToMount).toBe(true);
@@ -340,7 +336,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(revealed.displayedRouteState).toBe(restoringState);
@@ -360,7 +355,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(cleared.displayedRouteState).toEqual({ kind: "ready" });
@@ -378,38 +372,11 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "error",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(errored.isHandoffReadyToRelease).toBe(true);
});
it("keeps Restoring up while on-screen workspace chrome holds the reveal", () => {
const handoff = nextPostRestoreHandoff({ current: null, scopeKey, routeState: restoringState });
const settled = {
handoff,
scopeKey,
hasActiveWorkspace: true,
hasHydratedWorkspaceLayoutStore: true,
hasHydratedAgents: true,
hasReconciledAutoOpenAgentTabs: true,
visibleAgentCount: 1,
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready" as const,
visibleAgentsLoadingOlder: false,
routeState: { kind: "ready" as const },
};
// A tab row mounted behind the gate has not measured its tabs yet.
const held = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: true });
expect(held.displayedRouteState).toBe(restoringState);
expect(held.isHandoffReadyToMount).toBe(true);
expect(held.isHandoffReadyToRelease).toBe(false);
const released = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: false });
expect(released.isHandoffReadyToRelease).toBe(true);
});
it("marks handoff ready to release immediately when the workspace only has non-auto-open agents", () => {
const captured = nextPostRestoreHandoff({
current: null,
@@ -427,7 +394,6 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(resolved.isHandoffReadyToRelease).toBe(true);
@@ -164,10 +164,6 @@ import {
canSyncVisibleAgents,
usePostRestoreWorkspaceRouteState,
} from "@/screens/workspace/use-post-restore-handoff";
import {
type PostRestoreRevealHolds,
PostRestoreRevealHoldsProvider,
} from "@/screens/workspace/post-restore-reveal-holds";
import {
renderWorkspaceRouteGate,
WorkspaceLoading,
@@ -1436,7 +1432,6 @@ function WorkspaceScreenContent({
const {
displayedRouteState: displayedWorkspaceRouteState,
revealHolds,
isHoldingHandoff,
isPaneRouteFocused,
effectivePaneFocusSuspended,
@@ -3511,7 +3506,6 @@ function WorkspaceScreenContent({
return (
<PostRestoreOverlayShell
isHoldingHandoff={isHoldingHandoff}
revealHolds={revealHolds}
overlay={gatedWorkspaceScreen}
workspaceKey={persistenceKey}
sheetPaneHost={sheetPaneHost}
@@ -3535,14 +3529,12 @@ function WorkspaceScreenContent({
/** Keeps mounted workspace chrome hidden beneath the restoring gate during layout settle. */
function PostRestoreOverlayShell({
isHoldingHandoff,
revealHolds,
overlay,
workspaceKey,
sheetPaneHost,
children,
}: {
isHoldingHandoff: boolean;
revealHolds: PostRestoreRevealHolds;
overlay: ReactNode;
workspaceKey: string | null;
sheetPaneHost: Parameters<typeof WorkspaceContentProviders>[0]["sheetPaneHost"];
@@ -3560,15 +3552,13 @@ function PostRestoreOverlayShell({
accessibilityElementsHidden={isHoldingHandoff}
importantForAccessibility={isHoldingHandoff ? "no-hide-descendants" : "auto"}
>
<PostRestoreRevealHoldsProvider holds={isHoldingHandoff ? revealHolds : null}>
<WorkspaceContentProviders
key={workspaceKey}
workspaceKey={workspaceKey}
sheetPaneHost={sheetPaneHost}
>
{children}
</WorkspaceContentProviders>
</PostRestoreRevealHoldsProvider>
<WorkspaceContentProviders
key={workspaceKey}
workspaceKey={workspaceKey}
sheetPaneHost={sheetPaneHost}
>
{children}
</WorkspaceContentProviders>
</View>
) : null}
{overlay ? <View style={styles.postRestoreOverlay}>{overlay}</View> : null}
@@ -100,14 +100,12 @@ export async function archiveSelectedWorkspaces(input: {
}
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
const dirtyWorktrees = new Set<SidebarWorkspaceEntry>();
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
if (worktrees.length > 0) {
try {
const risks = await Promise.all(
worktrees.map(async ({ entry, client }) => {
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
if (risk.isDirty) dirtyWorktrees.add(entry);
return {
workspaceName: entry.name,
diffStat: entry.diffStat,
@@ -164,7 +162,6 @@ export async function archiveSelectedWorkspaces(input: {
return {
client,
workspace,
force: dirtyWorktrees.has(entry) || undefined,
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
};
}),
@@ -178,11 +175,7 @@ export async function archiveSelectedWorkspaces(input: {
...legacy.map(async ({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
try {
await deps.archiveWithoutUndo({
client,
workspace,
force: dirtyWorktrees.has(entry) || undefined,
});
await deps.archiveWithoutUndo({ client, workspace });
deps.purgeWorkspaceState(workspace);
} catch (error) {
failures.push({ error });
@@ -218,24 +218,14 @@ async function slowClick(element: HTMLElement) {
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
describe("sidebar workspace row presses", () => {
it("navigates on Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode, and toggles with Cmd/Ctrl+click once active", async () => {
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", 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] });
@@ -248,38 +238,31 @@ 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", "srv:c", "srv:d"]);
expect(navigatedKeys).toEqual(["srv:a"]);
});
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));
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));
// 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: ["Shift"] });
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a"]);
markGestureCanceled("b");
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
await userEvent.click(row("b"));
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 Shift+click and Cmd/Ctrl+click", async () => {
it("opens a row on a slow click and still selects it on the next 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: ["Shift"] });
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
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,12 +12,10 @@ interface WorkspaceSelectionPressInput {
}
/**
* 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.
* 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.
*
* 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
@@ -32,7 +30,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;
}
@@ -45,14 +43,12 @@ export function useWorkspaceSelectionPress({
const handlePressIn = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const isSelectionMode = useSidebarSelectionStore.getState().active;
const entersSelection = !isSelectionMode && modifiers.shift && !modifiers.mod;
if (entersSelection || (isSelectionMode && (modifiers.shift || modifiers.mod))) {
if (modifiers.shift || modifiers.mod) {
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
event.preventDefault?.();
return;
}
if (!isSelectionMode) {
if (!useSidebarSelectionStore.getState().active) {
onPressIn?.(event);
}
},
@@ -1349,33 +1349,6 @@ test("membership retry cannot run while disconnected", async () => {
expect(restored.agentIds).toEqual(["agent-a"]);
});
test("reopening a cached chat while its previous subscription is pending rechecks freshness", async () => {
const world = new TimelineWorld(undefined, true);
const agentId = "agent-a";
world.cursors.set(agentId, { epoch: "cached", endSeq: 9 });
world.show("workspace", [agentId]);
world.sync.setConnected(true);
try {
const previous = await world.nextMembership();
world.show("workspace", []);
world.sync.replaceOpenTabAgentIds([]);
world.show("workspace", [agentId]);
previous.succeed({ [agentId]: "current" });
const reopened = await world.nextMembership();
expect(reopened.agentIds).toEqual([agentId]);
expect(reopened.cursors).toEqual({ [agentId]: { epoch: "cached", seq: 9 } });
reopened.succeed({ [agentId]: "current" });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus(agentId)).toBe("ready"));
expect(world.appliedCurrent).toEqual([agentId]);
world.expectNoPendingFetch();
} finally {
world.sync.dispose();
}
});
test("returning to an open hidden agent stays live after inactivity", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
@@ -778,7 +778,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
let connected = false;
let observation: {
handle: ReturnType<ViewedTimelineSyncPorts["observe"]>;
generation: number;
agentIds: string[];
} | null = null;
let disposed = false;
let desired: string[] = [];
@@ -1049,12 +1049,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
}
};
// A request from an earlier generation can have the same IDs after a tab
// closes and reopens. Its answer will be ignored, so it cannot satisfy this one.
const membershipIsCovered = (generation: number, requested: string[]) =>
const membershipIsSettled = (requested: string[]) =>
!membershipNeedsRetry &&
!freshnessCheckOwed &&
(observation ? observation.generation === generation : requested.length === 0);
sameAgentIds(requested, observation?.agentIds ?? acknowledged);
// A chat with no fetch running and a cursor to compare; the daemon can answer without a fetch.
const collectFreshnessCursors = (requested: string[]) => {
@@ -1106,13 +1104,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
if (disposed || !connected) return;
const generation = membershipGeneration;
const requested = desired;
if (membershipIsCovered(generation, requested)) return;
if (membershipIsSettled(requested)) return;
const canCheck = ports.canCheckFreshness();
if (canCheck) {
// The cursor sent to the daemon must include whatever the cache restores.
await Promise.all(requested.map((agentId) => cacheLoads.get(agentId)));
if (isReconcileSuperseded(generation)) return;
if (membershipIsCovered(generation, requested)) return;
if (membershipIsSettled(requested)) return;
}
membershipNeedsRetry = false;
freshnessCheckOwed = false;
@@ -1124,7 +1122,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
try {
const previous = observation;
const handle = ports.observe(requested, cursors);
observation = { handle, generation };
observation = { handle, agentIds: requested };
// A subscription routes events only once the daemon accepts it, so the old one delivers until then.
const answer = await handle.ready.finally(() => {
void previous?.handle.release().catch(ports.reportError);
@@ -20,10 +20,6 @@ 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({
+18 -13
View File
@@ -9,23 +9,28 @@ export function buildAbsoluteExplorerPath({
workspaceRoot,
entryPath,
}: BuildAbsoluteExplorerPathInput): string {
const root = workspaceRoot.trim();
const entry = entryPath.trim();
if (!root || isAbsolutePath(entry)) {
return entry;
const normalizedWorkspaceRoot = workspaceRoot.trim().replace(/[\\/]+$/, "");
const normalizedEntryPath = entryPath.trim();
if (!normalizedWorkspaceRoot) {
return normalizedEntryPath;
}
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 (!normalizedEntryPath || normalizedEntryPath === ".") {
return normalizedWorkspaceRoot;
}
const separator = directory.includes("\\") ? "\\" : "/";
return [prefix, ...segments].join(separator);
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)}`;
}
export function parentExplorerPath(entryPath: string): string {
@@ -1,17 +1,16 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages";
import type { ActiveConnection } from "@/runtime/host-runtime";
import { resolveWorkspaceScriptLink, stripUrlProtocol } from "./workspace-script-links";
import { resolveWorkspaceScriptLink } from "./workspace-script-links";
const runningService: WorkspaceScriptPayload = {
scriptName: "web",
type: "service",
hostname: "web",
hostname: "web--feature--paseo.localhost",
port: 3000,
localProxyUrl: null,
localProxyUrl: "http://web--feature--paseo.localhost:6767",
publicProxyUrl: null,
proxyUrl: null,
tunnel: null,
proxyUrl: "http://web--feature--paseo.localhost:6767",
lifecycle: "running",
health: "healthy",
exitCode: null,
@@ -26,30 +25,56 @@ function resolveLink(
}
describe("resolveWorkspaceScriptLink", () => {
it("resolves running services to localhost:<port> for local, socket, and relay connections", () => {
it("defaults to the memorable Paseo URL locally and keeps direct as a fallback", () => {
expect(
resolveLink({ type: "directTcp", endpoint: "localhost:6767", display: "localhost:6767" }),
).toEqual({
label: "localhost:3000",
url: "http://localhost:3000",
});
expect(
resolveLink({ type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" }),
).toEqual({
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",
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" },
],
});
});
it("uses the daemon host and service port over a direct non-loopback TCP connection", () => {
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 },
),
).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" },
],
});
});
it("uses the daemon host and service port over a direct network connection", () => {
expect(
resolveLink({
type: "directTcp",
@@ -57,43 +82,123 @@ describe("resolveWorkspaceScriptLink", () => {
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({
label: "mac-mini.tail123.ts.net:3000",
url: "http://mac-mini.tail123.ts.net:3000",
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: "[fd7a:115c:a1e0::1]:6767",
display: "[fd7a:115c:a1e0::1]:6767",
}),
).toEqual({
label: "[fd7a:115c:a1e0::1]:3000",
url: "http://[fd7a:115c:a1e0::1]:3000",
});
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("ignores legacy *.localhost proxy URLs and returns localhost:<port>", () => {
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" },
],
});
const publicUrl = "https://web--feature--paseo.services.example.com";
expect(
resolveLink(null, {
...runningService,
localProxyUrl: "http://web--feature--paseo.localhost:6767",
proxyUrl: "http://web--feature--paseo.localhost:6767",
}),
resolveLink(relay, { ...runningService, publicProxyUrl: publicUrl, proxyUrl: publicUrl }),
).toEqual({
label: "localhost:3000",
url: "http://localhost:3000",
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" },
],
});
});
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("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";
expect(
resolveLink(
{ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" },
{ ...legacyLocal, proxyUrl: publicUrl },
).primary,
).toEqual({
kind: "public",
label: "web--feature--paseo.services.example.com",
url: publicUrl,
});
});
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");
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: [],
});
});
});
@@ -2,11 +2,19 @@ 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 (
@@ -14,11 +22,21 @@ function isLoopbackHost(host: string): boolean {
);
}
export function stripUrlProtocol(url: string): string {
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 {
return url.replace(/^https?:\/\//, "");
}
function buildLocalServiceUrl(
function buildDirectServiceUrl(
activeConnection: ActiveConnection | null,
port: number | null,
): string | null {
@@ -40,16 +58,35 @@ function buildLocalServiceUrl(
}
}
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;
}): WorkspaceScriptLinkTarget | null {
}): ResolvedWorkspaceScriptLink {
const { script, activeConnection } = input;
if (script.type !== "service" || script.lifecycle !== "running") {
return null;
return { primary: null, targets: [] };
}
const url = buildLocalServiceUrl(activeConnection, script.port);
if (!url) return null;
return { label: stripUrlProtocol(url), url };
// 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 };
}
@@ -0,0 +1,48 @@
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);
});
});
@@ -0,0 +1,49 @@
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);
@@ -6,21 +6,20 @@ import {
isWorkspaceListed,
undoWorkspaceArchiveOptimistically,
type WorkspaceArchiveTarget,
type WorkspaceArchiveClient,
} from "@/workspace/workspace-archive";
import { WorkspaceArchivedToast } from "./workspace-archived-toast";
/** How long the archived toast, and with it the chance to undo, stays up. */
export const WORKSPACE_ARCHIVE_UNDO_WINDOW_MS = 6000;
export interface UndoableWorkspaceArchiveClient extends WorkspaceArchiveClient {
export interface UndoableWorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
export interface UndoableWorkspaceArchiveEntryInput {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
onArchiveCommitted: () => void;
}
@@ -230,7 +229,6 @@ export async function archiveWorkspacesWithUndo(input: {
export async function archiveWorkspaceWithUndo(input: {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
toast: ToastApi;
onArchiveCommitted: () => void;
}): Promise<void> {
@@ -239,7 +237,6 @@ export async function archiveWorkspaceWithUndo(input: {
{
client: input.client,
workspace: input.workspace,
force: input.force,
onArchiveCommitted: input.onArchiveCommitted,
},
],
@@ -144,15 +144,6 @@ 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, useSyncExternalStore } from "react";
import { useCallback, useRef } from "react";
import { useTranslation } from "react-i18next";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useToast } from "@/contexts/toast-context";
@@ -14,9 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
import {
archiveWorkspaceOptimistically,
isWorkspaceArchiveAttemptPending,
runWorkspaceArchiveAttempt,
subscribeWorkspaceArchiveAttempts,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -43,8 +41,6 @@ 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 {
@@ -66,47 +62,44 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
const onArchiveStartedRef = useRef(onArchiveStarted);
onArchiveStartedRef.current = onArchiveStarted;
const archiveWorkspaceRecord = useCallback(
async (options?: { force: boolean }) => {
const client = getHostRuntimeStore().getClient(serverId);
if (!client) {
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return;
}
const workspace = { serverId, workspaceId };
onSetHiding?.(true);
try {
onArchiveStartedRef.current(workspace);
if (supportsWorkspaceArchiveUndo(serverId)) {
await archiveWorkspaceWithUndo({
client,
workspace,
force: options?.force,
toast,
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
});
} else {
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
await archiveWorkspaceOptimistically({ client, workspace, force: options?.force });
purgeArchivedWorkspaceState(workspace);
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
);
} finally {
onSetHiding?.(false);
}
},
[onSetHiding, serverId, t, toast, workspaceId],
);
// Ask the host what the archive would lose. The sidebar may not have loaded Git status.
const confirmWorktreeArchive = useCallback(async (): Promise<{ force: boolean } | null> => {
const archiveWorkspaceRecord = useCallback(async () => {
const client = getHostRuntimeStore().getClient(serverId);
if (!client) {
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return null;
return;
}
const workspace = { serverId, workspaceId };
onSetHiding?.(true);
try {
onArchiveStartedRef.current(workspace);
if (supportsWorkspaceArchiveUndo(serverId)) {
await archiveWorkspaceWithUndo({
client,
workspace,
toast,
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
});
} else {
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
await archiveWorkspaceOptimistically({ client, workspace });
purgeArchivedWorkspaceState(workspace);
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
);
} finally {
onSetHiding?.(false);
}
}, [onSetHiding, serverId, t, toast, workspaceId]);
// The host removes a worktree it archives, uncommitted work included. Ask it what that would
// lose: the sidebar row's git status is empty until the row receives it.
const confirmWorktreeArchive = useCallback(async (): Promise<boolean> => {
const client = getHostRuntimeStore().getClient(serverId);
if (!client) {
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return false;
}
const risk = await readWorktreeArchiveRisk(client, workspaceDirectory).catch(
(error: unknown) => {
@@ -117,25 +110,14 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
},
);
if (!risk) {
return null;
return false;
}
const confirmed = await confirmRiskyWorktreeArchive(
return await confirmRiskyWorktreeArchive(
{ workspaceName: name, diffStat, ...risk },
warningLabels,
);
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 },
@@ -146,6 +128,5 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
return {
archive,
isConfirming,
};
}
@@ -16,9 +16,6 @@ import {
archiveWorkspaceOptimistically,
archiveWorkspacesOptimistically,
beginOptimisticWorkspaceArchive,
isWorkspaceArchiveAttemptPending,
runWorkspaceArchiveAttempt,
subscribeWorkspaceArchiveAttempts,
undoWorkspaceArchiveOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -114,84 +111,6 @@ 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,62 +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: {
workspace: WorkspaceArchiveTarget;
confirm?: () => Promise<{ force: boolean } | null>;
archive: (options?: { force: boolean }) => Promise<void>;
confirm?: () => Promise<boolean>;
archive: () => Promise<void>;
}): Promise<void> {
const key = archiveAttemptKey(input.workspace);
const { serverId, workspaceId } = input.workspace;
const key = JSON.stringify([serverId, workspaceId]);
if (pendingArchiveAttempts.has(key)) return;
pendingArchiveAttempts.add(key);
notifyArchiveAttemptListeners();
try {
const confirmed = input.confirm ? await input.confirm() : undefined;
if (confirmed === null) return;
if (input.confirm && !(await input.confirm())) return;
if (!isWorkspaceListed(input.workspace)) return;
// Archive hides the row synchronously. Undo can restore it and start a new
// archive while the previous daemon request is still settling.
return input.archive(confirmed);
return input.archive();
} finally {
pendingArchiveAttempts.delete(key);
notifyArchiveAttemptListeners();
}
}
export interface WorkspaceArchiveClient {
archiveWorkspace: (
workspaceId: string,
requestId?: string,
options?: { force?: boolean },
) => Promise<{ error: string | null; canceled?: boolean }>;
interface WorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
}
interface WorkspaceArchiveUndoClient {
@@ -189,11 +158,8 @@ function invalidateAgentHistory(serverId: string): void {
async function archiveWorkspaceOrThrow(input: {
client: WorkspaceArchiveClient;
workspaceId: string;
force?: boolean;
}): Promise<WorkspaceArchiveOutcome> {
const payload = input.force
? await input.client.archiveWorkspace(input.workspaceId, undefined, { force: true })
: await input.client.archiveWorkspace(input.workspaceId);
const payload = await input.client.archiveWorkspace(input.workspaceId);
if (payload.canceled) {
return "canceled";
}
@@ -210,7 +176,6 @@ async function archiveWorkspaceOrThrow(input: {
export function beginOptimisticWorkspaceArchive(input: {
client: WorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
}): OptimisticWorkspaceArchive {
const snapshot = hideWorkspaceOptimistically(input.workspace);
const done = (async () => {
@@ -218,7 +183,6 @@ export function beginOptimisticWorkspaceArchive(input: {
const outcome = await archiveWorkspaceOrThrow({
client: input.client,
workspaceId: input.workspace.workspaceId,
force: input.force,
});
if (outcome === "canceled") {
restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot });
@@ -237,7 +201,6 @@ export function beginOptimisticWorkspaceArchive(input: {
export async function archiveWorkspaceOptimistically(input: {
client: WorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
}): Promise<WorkspaceArchiveOutcome> {
return beginOptimisticWorkspaceArchive(input).done;
}
@@ -1,95 +0,0 @@
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("-");
});
});
+1 -19
View File
@@ -3,23 +3,6 @@ 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: [
@@ -28,8 +11,7 @@ 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: "LOCAL URL", field: formatLocalUrl, width: 24 },
{ header: "TUNNEL", field: formatTunnel, width: 42 },
{ header: "PROXY URL", field: (script) => script.proxyUrl ?? "-", width: 42 },
{ header: "TERMINAL", field: (script) => script.terminalId ?? "-", width: 12 },
],
};

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