diff --git a/.env.example b/.env.example index 43055f20..153cb9d3 100644 --- a/.env.example +++ b/.env.example @@ -109,6 +109,15 @@ PASSKEY_RP_ID=localhost PASSKEY_RP_NAME=OpenCode Manager PASSKEY_ORIGIN=http://localhost:5003 +# ============================================ +# Preview Gateway +# ============================================ +# Public HTTPS origin of the preview gateway (port 5004). Required when the +# Manager is served over HTTPS, for example through a Cloudflare Tunnel. +# Use a separate hostname on the same domain as the Manager, and never add it +# to AUTH_TRUSTED_ORIGINS. +# PREVIEW_PUBLIC_URL=https://preview.example.com + # ============================================ # Push Notifications (VAPID) # Enables push notifications for the PWA (background alerts for agent diff --git a/backend/src/services/preview/ports.ts b/backend/src/services/preview/ports.ts index 2ddfb45c..b0027af0 100644 --- a/backend/src/services/preview/ports.ts +++ b/backend/src/services/preview/ports.ts @@ -24,6 +24,13 @@ export interface PortDiscoveryDeps { readdir: (path: string) => Promise readlink: (path: string) => Promise runLsof: () => Promise + runLsofCwd: (pids: number[]) => Promise +} + +interface LsofFieldRecord { + pid: number | null + command: string | null + name: string } const PROC_NET_FILES: ReadonlyArray = [ @@ -142,28 +149,43 @@ function parseLsofName(value: string): { address: string; port: number } | null return { address, port } } -export function parseLsofListen(output: string): LsofListener[] { - const listeners: LsofListener[] = [] +function* iterateLsofFields(output: string): Generator { let pid: number | null = null let command: string | null = null for (const rawLine of output.split('\n')) { - const field = rawLine.trim() - if (!field) continue - const type = field[0] - const value = field.slice(1) + const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine + if (!line) continue + const type = line[0] + const value = line.slice(1) if (type === 'p') { const parsed = Number.parseInt(value, 10) pid = Number.isNaN(parsed) ? null : parsed } else if (type === 'c') { command = value } else if (type === 'n') { - const parsed = parseLsofName(value) - if (parsed) listeners.push({ ...parsed, pid, command }) + yield { pid, command, name: value } } } +} + +export function parseLsofListen(output: string): LsofListener[] { + const listeners: LsofListener[] = [] + for (const record of iterateLsofFields(output)) { + const parsed = parseLsofName(record.name) + if (parsed) listeners.push({ ...parsed, pid: record.pid, command: record.command }) + } return listeners } +export function parseLsofCwds(output: string): Map { + const cwds = new Map() + for (const record of iterateLsofFields(output)) { + if (record.pid === null || record.name === '') continue + cwds.set(record.pid, record.name) + } + return cwds +} + function toHost(address: string): '127.0.0.1' | '::1' { return address === '::1' ? '::1' : '127.0.0.1' } @@ -284,15 +306,23 @@ async function listMacPorts(deps: PortDiscoveryDeps): Promise isAllowedAddress(listener.address)) - .map((listener) => ({ - port: listener.port, - host: toHost(listener.address), - pid: listener.pid, - command: listener.command, - cwd: null, - })) + const listeners = parseLsofListen(output).filter((listener) => isAllowedAddress(listener.address)) + const pids = [...new Set(listeners.map((listener) => listener.pid).filter((pid): pid is number => pid !== null))] + let cwds = new Map() + if (pids.length > 0) { + try { + cwds = parseLsofCwds(await deps.runLsofCwd(pids)) + } catch { + cwds = new Map() + } + } + return listeners.map((listener) => ({ + port: listener.port, + host: toHost(listener.address), + pid: listener.pid, + command: listener.command, + cwd: listener.pid === null ? null : (cwds.get(listener.pid) ?? null), + })) } export async function listListeningPorts(deps: PortDiscoveryDeps = defaultPortDeps): Promise { @@ -308,15 +338,25 @@ export async function listListeningPorts(deps: PortDiscoveryDeps = defaultPortDe .sort((left, right) => left.port - right.port) } +function unwrapCommandResult(result: string | { exitCode: number; stdout: string; stderr: string }): string { + return typeof result === 'string' ? result : result.stdout +} + const defaultPortDeps: PortDiscoveryDeps = { platform: process.platform, readFile: (path, encoding) => readFile(path, encoding), readdir: (path) => readdir(path), readlink: (path) => readlink(path), - runLsof: async () => { - const result = await executeCommand(['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn'], { - ignoreExitCode: true, - }) - return typeof result === 'string' ? result : (result as { stdout: string }).stdout - }, + runLsof: async () => + unwrapCommandResult( + await executeCommand(['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn'], { + ignoreExitCode: true, + }), + ), + runLsofCwd: async (pids) => + unwrapCommandResult( + await executeCommand(['lsof', '-a', '-d', 'cwd', '-p', pids.join(','), '-F', 'pn'], { + ignoreExitCode: true, + }), + ), } diff --git a/backend/test/services/preview/ports.test.ts b/backend/test/services/preview/ports.test.ts index d95166a5..dd19abfb 100644 --- a/backend/test/services/preview/ports.test.ts +++ b/backend/test/services/preview/ports.test.ts @@ -3,6 +3,7 @@ import { ENV } from '@opencode-manager/shared/config/env' import { isReservedPreviewPort, listListeningPorts, + parseLsofCwds, parseLsofListen, parseProcNetTcp, type PortDiscoveryDeps, @@ -54,6 +55,7 @@ function createDeps(fs: FakeFileSystem, overrides: Partial = return value }, runLsof: async () => '', + runLsofCwd: async () => '', ...overrides, } } @@ -97,6 +99,26 @@ describe('parseLsofListen', () => { }) }) +describe('parseLsofCwds', () => { + it('maps pid to working directory, keeping spaces and ignoring fd lines', () => { + const output = [ + 'p777', + 'fcwd', + 'n/Users/dev/my project', + 'p888', + 'fcwd', + 'n/Users/dev/api', + ].join('\n') + + expect(parseLsofCwds(output)).toEqual( + new Map([ + [777, '/Users/dev/my project'], + [888, '/Users/dev/api'], + ]), + ) + }) +}) + describe('isReservedPreviewPort', () => { it('reserves the manager, opencode and preview ports', () => { expect(isReservedPreviewPort(ENV.SERVER.PORT)).toBe(true) @@ -207,12 +229,38 @@ describe('listListeningPorts', () => { ]) }) - it('uses lsof on macOS with a null cwd', async () => { + it('maps cwd per pid from a second lsof call and passes each pid once', async () => { + const cwdCalls: number[][] = [] + const deps = createDeps( + { files: {}, links: {}, dirs: {} }, + { + platform: 'darwin', + runLsof: async () => + ['p777', 'cnode', 'n127.0.0.1:5173', 'p888', 'cbun', 'n127.0.0.1:3000', 'n127.0.0.1:5174'].join('\n'), + runLsofCwd: async (pids) => { + cwdCalls.push(pids) + return ['p777', 'fcwd', 'n/Users/dev/app', 'p888', 'fcwd', 'n/Users/dev/api'].join('\n') + }, + }, + ) + + expect(await listListeningPorts(deps)).toEqual([ + { port: 3000, host: '127.0.0.1', pid: 888, command: 'bun', cwd: '/Users/dev/api' }, + { port: 5173, host: '127.0.0.1', pid: 777, command: 'node', cwd: '/Users/dev/app' }, + { port: 5174, host: '127.0.0.1', pid: 888, command: 'bun', cwd: '/Users/dev/api' }, + ]) + expect(cwdCalls).toEqual([[777, 888]]) + }) + + it('keeps cwd null when the cwd lsof call rejects but still lists the ports', async () => { const deps = createDeps( { files: {}, links: {}, dirs: {} }, { platform: 'darwin', runLsof: async () => ['p777', 'cnode', 'n127.0.0.1:5173'].join('\n'), + runLsofCwd: async () => { + throw new Error('lsof failed') + }, }, ) diff --git a/docker-compose.yml b/docker-compose.yml index c28413c3..ac250c79 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -44,6 +44,7 @@ services: - PASSKEY_RP_ID=${PASSKEY_RP_ID:-localhost} - PASSKEY_RP_NAME=${PASSKEY_RP_NAME:-OpenCode Manager} - PASSKEY_ORIGIN=${PASSKEY_ORIGIN:-http://localhost:5003} + - PREVIEW_PUBLIC_URL=${PREVIEW_PUBLIC_URL:-} - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY:-} - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY:-} - VAPID_SUBJECT=${VAPID_SUBJECT:-} diff --git a/docs/configuration/authentication.md b/docs/configuration/authentication.md index 927b617d..4d8e9d2b 100644 --- a/docs/configuration/authentication.md +++ b/docs/configuration/authentication.md @@ -121,6 +121,10 @@ AUTH_TRUSTED_ORIGINS=https://yourdomain.com AUTH_SECURE_COOKIES=true ``` +### Cloudflare Tunnel + +To reach a Manager on your local network through a Cloudflare Tunnel, including the Preview panel, follow [Cloudflare Tunnel](cloudflare-tunnel.md). + ## Passkeys Passwordless authentication using WebAuthn. diff --git a/docs/configuration/cloudflare-tunnel.md b/docs/configuration/cloudflare-tunnel.md new file mode 100644 index 00000000..962b5120 --- /dev/null +++ b/docs/configuration/cloudflare-tunnel.md @@ -0,0 +1,170 @@ +# Cloudflare Tunnel + +Reach an OpenCode Manager running on your local network from anywhere over HTTPS, without opening ports on your router. This guide covers the Manager itself and the [Preview](../features/preview.md) panel, which needs a hostname of its own. + +## What You Need + +- A domain managed by Cloudflare, for example `example.com`. +- A Cloudflare Tunnel with `cloudflared` running on a machine that can reach the Manager. See Cloudflare's [Create a tunnel](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/) guide. +- Two hostnames on that domain: + +| Hostname | Serves | Manager port | +|----------|--------|--------------| +| `oc.example.com` | The Manager | 5003 | +| `preview.example.com` | The [preview gateway](../features/preview.md#gateway) | 5004 | + +The examples below use these names; replace them with your own. + +!!! info "Why Preview needs its own hostname" + Preview shows pages from dev servers you run, which is untrusted content. It is served from a separate origin so it can never act as the Manager. Both hostnames must be on the **same domain**: the preview login cookie is `SameSite=Lax`, which the browser only sends to a frame on the same site as the page around it. + +!!! warning "Quick tunnels are not supported" + `trycloudflare.com` quick tunnels get a random hostname each time they start, so `PREVIEW_PUBLIC_URL` would change on every restart. Use a named tunnel on your own domain. + +## 1. Publish Both Hostnames + +In your tunnel, add a **published application route** for each hostname. The service URL depends on where `cloudflared` runs. + +=== "cloudflared in Docker Compose" + + Run `cloudflared` next to the Manager in the same `docker-compose.yml`, so it reaches the Manager over the Compose network: + + ```yaml + services: + app: + # the existing OpenCode Manager service + + cloudflared: + image: cloudflare/cloudflared:latest + command: tunnel --no-autoupdate run + environment: + - TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN} + restart: unless-stopped + ``` + + Put the tunnel token from the Cloudflare dashboard in `.env` as `CLOUDFLARE_TUNNEL_TOKEN`, then add these routes: + + | Hostname | Service | + |----------|---------| + | `oc.example.com` | `http://app:5003` | + | `preview.example.com` | `http://app:5004` | + +=== "cloudflared on another machine" + + Point the routes at the Manager's LAN address: + + | Hostname | Service | + |----------|---------| + | `oc.example.com` | `http://192.168.1.10:5003` | + | `preview.example.com` | `http://192.168.1.10:5004` | + + With Docker, ports 5003 and 5004 must be published, as they are in the default `docker-compose.yml`. + +=== "Locally managed tunnel" + + For a tunnel configured with a `config.yml` file: + + ```yaml + tunnel: + credentials-file: /etc/cloudflared/.json + + ingress: + - hostname: oc.example.com + service: http://192.168.1.10:5003 + - hostname: preview.example.com + service: http://192.168.1.10:5004 + - service: http_status:404 + ``` + +## 2. Configure the Manager + +Add to `.env`: + +```bash +AUTH_TRUSTED_ORIGINS=https://oc.example.com +AUTH_SECURE_COOKIES=true + +PASSKEY_RP_ID=oc.example.com +PASSKEY_ORIGIN=https://oc.example.com + +PREVIEW_PUBLIC_URL=https://preview.example.com +``` + +Then restart the Manager. With Docker: `docker compose up -d`. + +| Variable | Why | +|----------|-----| +| `AUTH_TRUSTED_ORIGINS` | Lets the browser sign in from the tunnel hostname. | +| `AUTH_SECURE_COOKIES` | The tunnel serves HTTPS, so session cookies are marked secure. | +| `PASSKEY_RP_ID`, `PASSKEY_ORIGIN` | Passkeys are bound to the hostname. Passkeys added under another hostname (such as `localhost`) do not work here; add a new one from **Settings > Account**. | +| `PREVIEW_PUBLIC_URL` | Without it, the Preview panel loads `https://oc.example.com:5004`, which the tunnel does not serve, and the preview stays blank. | + +!!! danger "Never add the preview hostname to `AUTH_TRUSTED_ORIGINS`" + The Manager rejects state-changing requests from other origins on the same site unless they are trusted. Trusting the preview hostname would let any page you preview act as you in the Manager. See [Isolation level](../features/preview.md#isolation-level). + +## 3. Turn Off Caching for the Preview Hostname + +**This step is required.** Cloudflare caches JavaScript, CSS, images and fonts by default, and keeps responses that have no cache headers for up to two hours ([Cloudflare default cache behavior](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/)). The cache cannot tell dev servers or users apart. Every dev server shares the one preview hostname, and the gateway picks the target from your login cookie. Without this rule: + +- Changes to your files do not appear for up to two hours. +- Two projects that serve the same path, such as `/main.js`, can receive each other's files. +- Cloudflare serves a cached file without going through the preview login, so anyone with its URL can download it. + +Create a cache rule in the Cloudflare dashboard: + +1. Go to **Caching > Cache Rules** and select **Create rule**. +2. Name it, for example `OpenCode Manager preview: bypass cache`. +3. Under **When incoming requests match**, choose **Custom filter expression**: **Hostname** **equals** `preview.example.com`. +4. Under **Cache eligibility**, select **Bypass cache**. +5. Select **Deploy**. + +The Manager hostname does not need this rule. + +## 4. Check WebSockets + +The Terminal and Preview live reload (HMR) use WebSockets. On your domain's **Network** page in the Cloudflare dashboard, make sure **WebSockets** is **On**. + +## 5. Cloudflare Access (Optional) + +If you protect `oc.example.com` with [Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/), choose one of these for the preview hostname: + +- **Add it to the same Access application.** In an application with several domains, Access issues the login cookie for the other domains after you sign in once, so the Preview frame never shows a login page ([multi-domain applications](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/#multi-domain-applications)). +- **Leave it out of Access.** The preview gateway has its own login: it only opens a preview from a single-use token issued by a signed-in Manager, and answers every other request with `401`. + +Do not put the preview hostname in a **separate** Access application. The Preview frame would be sent to the Access login page, which cannot be shown inside a frame, and the preview stays blank. + +## Using the LAN Address as Well + +`PREVIEW_PUBLIC_URL` applies however you open the Manager: + +- **Through the tunnel** (`https://oc.example.com`): Preview works in the panel. +- **Through a LAN address** (`http://192.168.1.10:5003`): the panel still loads the preview from `https://preview.example.com`. That is a different site, so the browser blocks the preview cookie inside the frame. Use **Open in new tab** in the Preview toolbar, or use the tunnel hostname. + +With `AUTH_SECURE_COOKIES=true` you also cannot sign in over plain HTTP, because browsers do not store secure cookies for `http://` addresses. Sign in through the tunnel hostname. + +## Check the Setup + +1. Open `https://oc.example.com` and sign in. +2. Start a dev server from the [Terminal](../features/terminal.md) or [Actions](../features/project-actions.md). +3. Open **Preview** and select its port. The page appears in the panel. +4. Edit a file the dev server serves. The change appears after live reload or a refresh. +5. Optional: open `https://preview.example.com` in a private window. It shows **Preview session expired. Reopen it from OpenCode Manager.** (or the Access login page, if the hostname is behind Access), which confirms that the preview cannot be opened without signing in. + +## Troubleshooting + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Preview stays blank or cannot connect | `PREVIEW_PUBLIC_URL` is not set, so the panel uses port 5004 on the Manager hostname | Set `PREVIEW_PUBLIC_URL` and restart the Manager | +| **Preview session is invalid or expired.** inside the panel | The browser blocked the preview cookie: the hostnames are on different domains, or the Manager was opened by its LAN address | Put both hostnames on the same domain and open the Manager through the tunnel, or use **Open in new tab** | +| **Preview must run on a different origin than OpenCode Manager.** | `PREVIEW_PUBLIC_URL` points at the Manager's own hostname | Use a separate hostname for the preview | +| Old file contents, or another project's files | Cloudflare cached the files | Add the [cache rule](#3-turn-off-caching-for-the-preview-hostname), then purge the cache under **Caching > Configuration** | +| Live reload does not work, or the Terminal does not connect | WebSockets are off | Turn on [WebSockets](#4-check-websockets) | +| Access login page or a blank frame in the Preview panel | The preview hostname is in a separate Access application | Follow [Cloudflare Access](#5-cloudflare-access-optional) | +| Sign-in fails on the tunnel hostname | `AUTH_TRUSTED_ORIGINS` does not include `https://oc.example.com` | Add it and restart the Manager | + +## Related + +- [Preview](../features/preview.md) — how the preview gateway works. +- [Authentication](authentication.md) — trusted origins, secure cookies and passkeys. +- [Docker](docker.md) — ports and environment variables. +- [Environment Variables](environment.md#preview-gateway) — `PREVIEW_PORT` and `PREVIEW_PUBLIC_URL`. diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index 6318fbff..3a64e85a 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -76,6 +76,7 @@ services: - PASSKEY_RP_ID=${PASSKEY_RP_ID:-localhost} - PASSKEY_RP_NAME=${PASSKEY_RP_NAME:-OpenCode Manager} - PASSKEY_ORIGIN=${PASSKEY_ORIGIN:-http://localhost:5003} + - PREVIEW_PUBLIC_URL=${PREVIEW_PUBLIC_URL:-} - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY:-} - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY:-} - VAPID_SUBJECT=${VAPID_SUBJECT:-} @@ -120,6 +121,9 @@ GITHUB_CLIENT_SECRET=your-client-secret PASSKEY_RP_ID=localhost PASSKEY_ORIGIN=http://localhost:5003 +# Optional - preview gateway behind HTTPS (see Cloudflare Tunnel) +PREVIEW_PUBLIC_URL=https://preview.example.com + # Optional - push notifications VAPID_PUBLIC_KEY=BMx-1234567890abcdefghijklmnopqrstuv... VAPID_PRIVATE_KEY=abcd1234567890abcdef... diff --git a/docs/features/preview.md b/docs/features/preview.md index 63be9eac..80cf217c 100644 --- a/docs/features/preview.md +++ b/docs/features/preview.md @@ -6,11 +6,13 @@ The Preview panel lists the loopback ports that are currently listening, then pr ## Port List -Open **Preview** from the desktop sidebar tool list or the **More** drawer, including in the Assistant workspace. The panel lists every listening loopback port on the host, with its port number and process command. On Linux hosts (including the Docker image) it also shows each process's working directory, and ports inside the selected repository or workspace directory are badged **this repo** and sorted first. On macOS the working directory is not available, so no port is badged. Other platforms list no ports. +Open **Preview** from the desktop sidebar tool list or the **More** drawer, including in the Assistant workspace. The port menu at the start of the toolbar lists every listening loopback port on the host as `:PORT command`, with the process's working directory underneath. Type in the menu to filter by port, command or directory. Working directories are read on Linux hosts (including the Docker image) and macOS; ports whose process runs inside the selected repository or workspace directory are grouped under **This repo** at the top, and the rest under **Other ports**. Other platforms list no ports. + +Until a port is selected, the panel body lists the dev servers of this repo so one click opens the preview, and counts the other listening ports. When nothing is listening, it points to the Terminal and Actions to start a dev server. The list excludes reserved ports — the Manager port (`PORT`, default 5003), the OpenCode server port (default 5551) and the preview gateway port itself — and only includes ports at or above 1024. Any other listening loopback port can be previewed; there is no per-port allow-list. This grants nothing an authenticated user does not already have, because the [Terminal](terminal.md) can reach the same ports. -While the port list is shown it refreshes every 2 seconds. It stops refreshing while a preview is open. +Until a preview is open, the port list refreshes every 2 seconds. While a preview is open it refreshes only when you open the port menu. Selecting a port creates a preview session and renders the target in an iframe on the gateway origin. The iframe keeps that origin (`allow-same-origin`) so dev servers can use cookies and storage; isolation from the Manager comes from the separate origin, not from an opaque sandbox. Selecting a different port starts a new session for it. @@ -44,16 +46,17 @@ A browser can hold one preview target per gateway origin at a time: the `ocm_pre A preview can be opened from more than one place: -- **Port list** — select a port in the panel. +- **Port menu** — pick a port in the toolbar, or a dev server listed in the panel body. - **Terminal links** — clicking a local dev URL (`http://localhost:PORT`, `127.0.0.1`, `0.0.0.0`, or `[::1]`) printed in a terminal opens the Preview panel at that port and path instead of a new browser tab. External links still open in a new tab. - **Project actions** — an action's resolved URL opens in the Preview panel when **Auto-open URL** is enabled. ## Toolbar +- **Port** — the port menu described in [Port List](#port-list). Press Escape to close the menu without closing the panel. - **Path** — enter a path and press **Go** (or Enter) to start a session for that path. - **Reload** — remounts the iframe. - **Open in new tab** — creates a fresh session and opens its start URL in a new tab with `noopener`. Start tokens are single-use, so this always mints a new one. -- **Viewport** — switch between Mobile (390 px), Tablet (820 px), and Full width. +- **Viewport** — switch between Mobile (390 px), Tablet (820 px), and Full width. Hidden on small screens, where the panel is already phone-width. ## Behind HTTPS or a Reverse Proxy @@ -62,7 +65,12 @@ By default the panel builds the gateway origin as `${location.protocol}//${locat - **Mixed content** — an `https://` page cannot embed an `http://` preview. - **Third-party cookies** — the `ocm_preview` cookie is blocked in a cross-site iframe. -Set `PREVIEW_PUBLIC_URL` to a same-site HTTPS origin that proxies the preview gateway, for example `https://preview.example.com`. Do not add it to `AUTH_TRUSTED_ORIGINS` (see [Isolation level](#isolation-level)). The panel then builds preview URLs from that origin instead. As a fallback, **Open in new tab** opens the preview as a top-level page, where the session cookie is first-party. +Set `PREVIEW_PUBLIC_URL` to a same-site HTTPS origin that proxies the preview gateway, for example `https://preview.example.com`. Do not add it to `AUTH_TRUSTED_ORIGINS` (see [Isolation level](#isolation-level)). The panel then builds preview URLs from that origin instead, however the Manager itself was opened. As a fallback, **Open in new tab** opens the preview as a top-level page, where the session cookie is first-party. + +!!! warning "Turn off caching for the preview origin" + The gateway passes the dev server's cache headers through unchanged, and every port shares the one preview origin. A CDN or caching proxy in front of the gateway can therefore serve stale files, mix files between projects, and serve cached files without the preview login. Bypass caching for the preview hostname. + +For a complete setup through a Cloudflare Tunnel, including the cache rule and Cloudflare Access, see [Cloudflare Tunnel](../configuration/cloudflare-tunnel.md). ## Related diff --git a/docs/features/project-actions.md b/docs/features/project-actions.md index 82afa1ef..65a258b7 100644 --- a/docs/features/project-actions.md +++ b/docs/features/project-actions.md @@ -81,7 +81,7 @@ Project actions are not available in the Assistant workspace. ## Moving Actions and Setup Commands -The Project Actions dialog moves items between personal settings and the repository file: +The Project Actions dialog moves items between personal settings and the repository file from each row's **⋯** menu: - **Move to repository** writes the item into `.ocm/project.json` and removes it from personal settings. Because the user authored it, the file is trusted automatically. - **Move to my settings** removes the item from `.ocm/project.json` (deleting the file if it becomes empty) and stores it in personal settings. @@ -93,10 +93,10 @@ Moves are transactional: if the file write or the settings update fails, the fil Commands in `.ocm/project.json` run on your machine, so the Manager does not run them until you trust the file: - Trust covers everything in the file that can run or open: each action's `id`, `name`, `command`, `url` and `autoOpenUrl` (including actions hidden because a personal action has the same `id`), plus every setup command. Changing any of these resets trust; changing an icon does not. -- Both trust prompts — **Trust these commands** in the dialog and **Trust and run** in the header menu — list every action and setup command that trusting covers, not only the one you clicked. +- Both trust prompts — **Review** in the dialog and **Trust and run** in the header menu — list every action and setup command that trusting covers, not only the one you clicked. - Trusting requires echoing the exact hash of the content shown, so a file cannot be swapped between review and trust. - Untrusted repository commands never run — not from the header menu, and not as worktree setup commands. -- The dialog shows the untrusted commands and a **Trust these commands** button. Attempting to run an untrusted action prompts for trust first. +- The dialog shows a banner above its tabs while the file is untrusted. **Review** lists the untrusted commands, and **Trust these commands** confirms. Attempting to run an untrusted action prompts for trust first. - Moving an item into the file auto-trusts it, because the user authored it. ## Worktree Setup Commands @@ -105,7 +105,7 @@ Setup commands run once after a new working directory is created — Manager wor - `$ROOT_PROJECT_PATH` is available in the environment and points at the repository's main checkout. - Personal setup commands always run. Repository setup commands are skipped while the file is untrusted; the skipped result is reported. -- Setup commands are configured in the **Worktree setup** section of the Project Actions dialog. +- Setup commands are configured in the **Worktree setup** tab of the Project Actions dialog. Edits are saved together with **Save setup**, which is enabled once there are unsaved changes. ## Related diff --git a/docs/features/terminal.md b/docs/features/terminal.md index bab71f1d..262bc126 100644 --- a/docs/features/terminal.md +++ b/docs/features/terminal.md @@ -9,7 +9,7 @@ Open the terminal from either surface: - **Desktop sidebar** — click **Terminal** in the tool list for a repository or session. - **More drawer** — on mobile or from the overflow menu, open **More** and select **Terminal**. -The terminal panel opens as a dialog. If no terminal exists for the selected directory yet, the panel starts one automatically. +The terminal panel opens as a dialog. If nothing is running in the selected directory, opening the panel starts a shell automatically; exited terminals do not count. Opening a specific terminal — such as a project action or worktree setup — shows that terminal instead and starts nothing extra. Terminals are scoped to the selected repository or OpenCode workspace directory. A terminal opened from a repo runs in that repo's path; a terminal opened from a session runs in the session's working directory. Switching directories shows that directory's terminals. diff --git a/frontend/src/components/preview/PreviewPanel.test.tsx b/frontend/src/components/preview/PreviewPanel.test.tsx index b506a895..f938905d 100644 --- a/frontend/src/components/preview/PreviewPanel.test.tsx +++ b/frontend/src/components/preview/PreviewPanel.test.tsx @@ -19,6 +19,7 @@ const portsData = { } let portsState: PreviewPortsResult['data'] = portsData +const refetchPorts = vi.fn() const DEFAULT_ENTRY = '/repos/1?dialog=preview&previewPort=5173' @@ -57,7 +58,7 @@ describe('PreviewPanel', () => { ({ data: portsState, isLoading: false, - refetch: vi.fn(), + refetch: refetchPorts, }) as unknown as PreviewPortsResult, ) vi.mocked(createPreviewSession).mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null }) @@ -109,20 +110,84 @@ describe('PreviewPanel', () => { expect(screen.getByText(/Preview is unavailable/)).toBeInTheDocument() }) - it('badges ports marked as inside the directory', () => { + it('lists the dev servers of this repo when no port is selected', () => { + portsState = { + enabled: true, + ports: [ + { port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/repo', inDirectory: true }, + { port: 9000, host: '127.0.0.1', pid: 11, command: 'Discord', cwd: '/', inDirectory: false }, + { port: 9001, host: '127.0.0.1', pid: 12, command: 'figma_agent', cwd: null, inDirectory: false }, + ], + } renderPanel('/repos/1?dialog=preview') - expect(screen.getByText('this repo')).toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Dev servers in this repo' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /:5173 vite/ })).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /:9000/ })).not.toBeInTheDocument() + expect(screen.getByText(/2 other ports are listening elsewhere/)).toBeInTheDocument() }) - it('does not badge ports marked as outside the directory', () => { + it('points to the port menu when no listening port belongs to this repo', () => { portsState = { enabled: true, ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/elsewhere', inDirectory: false }], } renderPanel('/repos/1?dialog=preview') - expect(screen.queryByText('this repo')).not.toBeInTheDocument() + expect(screen.queryByRole('heading', { name: 'Dev servers in this repo' })).not.toBeInTheDocument() + expect(screen.getByText(/1 port is listening\. Choose one from the port menu above\./)).toBeInTheDocument() + }) + + it('explains how to start a dev server when no port is listening', () => { + portsState = { enabled: true, ports: [] } + renderPanel('/repos/1?dialog=preview') + + expect(screen.getByText('No dev server is listening')).toBeInTheDocument() + }) + + it('groups repo ports first in the port menu and starts a session for the picked port', async () => { + const user = userEvent.setup() + portsState = { + enabled: true, + ports: [ + { port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/repo', inDirectory: true }, + { port: 9000, host: '127.0.0.1', pid: 11, command: 'python3.12', cwd: '/srv/apps/demo/site', inDirectory: false }, + ], + } + renderPanel('/repos/1?dialog=preview') + + await user.click(screen.getByRole('combobox', { name: 'Preview port' })) + + const groups = screen.getAllByText(/^(This repo|Other ports)$/).map((element) => element.textContent) + expect(groups).toEqual(['This repo', 'Other ports']) + expect(screen.getByText('/.../apps/demo/site')).toBeInTheDocument() + + await user.type(screen.getByRole('combobox', { name: 'Preview port' }), 'python') + expect(screen.queryByText('This repo')).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: /:9000 python3\.12/ })) + + expect(await screen.findByTitle('Preview')).toBeInTheDocument() + expect(createPreviewSession).toHaveBeenCalledWith(9000) + expect(screen.getByRole('combobox', { name: 'Preview port' })).toHaveValue(':9000 python3.12') + }) + + it('keeps the port menu closed when the dialog opens', () => { + renderPanel('/repos/1?dialog=preview') + + expect(screen.getByRole('combobox', { name: 'Preview port' })).not.toHaveFocus() + expect(screen.getAllByRole('button', { name: /:5173/ })).toHaveLength(1) + expect(refetchPorts).not.toHaveBeenCalled() + }) + + it('refreshes the port list when the port menu opens', async () => { + const user = userEvent.setup() + renderPanel() + await screen.findByTitle('Preview') + refetchPorts.mockClear() + + await user.click(screen.getByRole('combobox', { name: 'Preview port' })) + + expect(refetchPorts).toHaveBeenCalledTimes(1) }) it('polls the port list while no preview session is active', () => { diff --git a/frontend/src/components/preview/PreviewPanel.tsx b/frontend/src/components/preview/PreviewPanel.tsx index f6166c81..7658f996 100644 --- a/frontend/src/components/preview/PreviewPanel.tsx +++ b/frontend/src/components/preview/PreviewPanel.tsx @@ -1,14 +1,16 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' -import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types' +import type { CreatePreviewSessionResponse, PreviewPort } from '@opencode-manager/shared/types' import { ExternalLink, Globe, Loader2, Monitor, RefreshCw, Smartphone, Tablet, X } from 'lucide-react' import { createPreviewSession, usePreviewPorts } from '@/api/preview' import { Button } from '@/components/ui/button' +import { Combobox, type ComboboxOption } from '@/components/ui/combobox' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' import { useMobile } from '@/hooks/useMobile' import { useUrlParams } from '@/hooks/useUrlParams' import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors' import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager, parsePort } from '@/lib/preview-url' -import { cn } from '@/lib/utils' +import { cn, shortenPath } from '@/lib/utils' interface PreviewPanelProps { isOpen: boolean @@ -32,6 +34,24 @@ const VIEWPORT_PRESETS: Array<{ preset: ViewportPreset; label: string; icon: typ const PORT_WAIT_TIMEOUT_MS = 60_000 +function formatPortLabel(entry: PreviewPort): string { + return entry.command ? `:${entry.port} ${entry.command}` : `:${entry.port}` +} + +function toPortOptions(ports: PreviewPort[]): ComboboxOption[] { + const hasRepoPorts = ports.some((entry) => entry.inDirectory) + return ports.map((entry) => ({ + value: String(entry.port), + label: formatPortLabel(entry), + description: entry.cwd ? shortenPath(entry.cwd) : undefined, + group: hasRepoPorts ? (entry.inDirectory ? 'This repo' : 'Other ports') : undefined, + })) +} + +function describeListeningPorts(count: number, qualifier = ''): string { + return count === 1 ? `1 ${qualifier}port is listening` : `${count} ${qualifier}ports are listening` +} + interface ActiveSession { targetPort: number path: string @@ -58,6 +78,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) const sessionPortRef = useRef(null) const activePathRef = useRef(null) const requestIdRef = useRef(0) + const contentRef = useRef(null) const activeSession = session && session.targetPort === requestedPort ? session : null @@ -66,6 +87,8 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) refetchInterval: isOpen && !activeSession ? 2000 : false, }) const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data]) + const portOptions = useMemo(() => toPortOptions(ports), [ports]) + const repoPorts = useMemo(() => ports.filter((entry) => entry.inDirectory), [ports]) const enabled = portsQuery.data?.enabled ?? true const portListed = requestedPort !== undefined && ports.some((entry) => entry.port === requestedPort) @@ -134,6 +157,11 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) }, 'replace') }, [updateParams]) + const handlePortChange = useCallback((value: string) => { + const port = parsePort(value) + if (port) selectPort(port) + }, [selectPort]) + const reload = useCallback(() => { if (!requestedPort) return void startSession(requestedPort, requestedPath) @@ -187,12 +215,64 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) ) + const renderPortChooser = () => { + if (ports.length === 0) { + return renderMessage( +
+

No dev server is listening

+

Start one in the Terminal or from Actions. It appears here automatically.

+
, + ) + } + if (repoPorts.length === 0) { + return renderMessage( +
+

Select a port to preview

+

{describeListeningPorts(ports.length)}. Choose one from the port menu above.

+
, + ) + } + const otherPortCount = ports.length - repoPorts.length + return ( +
+
+

Dev servers in this repo

+
    + {repoPorts.map((entry) => ( +
  • + +
  • + ))} +
+ {otherPortCount > 0 && ( +

+ {describeListeningPorts(otherPortCount, 'other ')} elsewhere. Choose one from the port menu above. +

+ )} +
+
+ ) + } + const body = () => { if (!enabled) { return renderMessage('Preview is unavailable') } if (!requestedPort) { - return renderMessage('Select a port to preview') + return renderPortChooser() } if (!portListed) { if (waitExpired) { @@ -236,10 +316,15 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) return ( { if (!open) onClose() }}> { + event.preventDefault() + contentRef.current?.focus() + }} className={cn( - 'p-0 flex flex-col bg-card border-border gap-0', + 'p-0 flex flex-col bg-card border-border gap-0 focus:outline-none', isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0', )} > @@ -261,80 +346,68 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) )} -
- setPathDraft(event.target.value)} - onKeyDown={(event) => { if (event.key === 'Enter') handleGo() }} - className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-sm" - placeholder="/" +
+ { void portsQuery.refetch() }} + className="sm:w-72 sm:flex-shrink-0" /> - - - -
- {VIEWPORT_PRESETS.map(({ preset, label, icon: Icon }) => ( - - ))} +
+ setPathDraft(event.target.value)} + onKeyDown={(event) => { if (event.key === 'Enter') handleGo() }} + className="h-9 min-w-0 flex-1 bg-transparent px-3 py-1" + placeholder="/" + /> + + + +
+ {VIEWPORT_PRESETS.map(({ preset, label, icon: Icon }) => ( + + ))} +
- {enabled && ports.length > 0 && ( -
- {ports.map((entry) => ( - - ))} -
- )} -
{body()}
diff --git a/frontend/src/components/repo/RepoActionsDialog.test.tsx b/frontend/src/components/repo/RepoActionsDialog.test.tsx index ef4b3a80..de40dd43 100644 --- a/frontend/src/components/repo/RepoActionsDialog.test.tsx +++ b/frontend/src/components/repo/RepoActionsDialog.test.tsx @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { render, screen, waitFor } from '@testing-library/react' -import userEvent from '@testing-library/user-event' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent, { type UserEvent } from '@testing-library/user-event' import { FetchError } from '@opencode-manager/shared' import { RepoActionsDialog } from './RepoActionsDialog' import type { ProjectConfigResponse } from '@opencode-manager/shared/types' @@ -54,6 +54,25 @@ function renderDialog() { ) } +async function openSetupTab(user: UserEvent) { + await user.click(screen.getByRole('tab', { name: /worktree setup/i })) +} + +async function openRowMenu(user: UserEvent, label: string) { + await user.click(screen.getByRole('button', { name: label })) + return screen.findByRole('menu') +} + +async function closeRowMenu(user: UserEvent) { + await user.keyboard('{Escape}') + await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument()) +} + +async function openTrustReview(user: UserEvent) { + await user.click(screen.getByRole('button', { name: /^review$/i })) + return screen.findByRole('dialog', { name: /trust repository commands/i }) +} + describe('RepoActionsDialog', () => { beforeEach(() => { vi.clearAllMocks() @@ -104,7 +123,7 @@ describe('RepoActionsDialog', () => { } }) - it('offers no edit button for repo items but allows moving them to personal settings', () => { + it('offers no edit button for repo items but allows moving them to personal settings', async () => { mockConfig( baseConfig({ actions: [ @@ -113,12 +132,38 @@ describe('RepoActionsDialog', () => { ], }), ) + const user = userEvent.setup() renderDialog() expect(screen.getAllByRole('button', { name: /edit/i })).toHaveLength(1) expect(screen.getByText('In repo')).toBeInTheDocument() - expect(screen.getByRole('button', { name: /move to my settings/i })).toBeInTheDocument() - expect(screen.getByRole('button', { name: /move to repository/i })).toBeInTheDocument() + + const repoMenu = await openRowMenu(user, 'Actions for Repo action') + expect(within(repoMenu).getByRole('menuitem', { name: /move to my settings/i })).toBeInTheDocument() + expect(within(repoMenu).queryByRole('menuitem', { name: /delete/i })).not.toBeInTheDocument() + await closeRowMenu(user) + + const personalMenu = await openRowMenu(user, 'Actions for Personal action') + expect(within(personalMenu).getByRole('menuitem', { name: /move to repository/i })).toBeInTheDocument() + expect(within(personalMenu).getByRole('menuitem', { name: /delete/i })).toBeInTheDocument() + }) + + it('moves a repo action to personal settings from its row menu', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' }, + ], + }), + ) + const user = userEvent.setup() + renderDialog() + + const menu = await openRowMenu(user, 'Actions for Repo action') + await user.click(within(menu).getByRole('menuitem', { name: /move to my settings/i })) + + await waitFor(() => expect(mocks.moveMutate).toHaveBeenCalledTimes(1)) + expect(mocks.moveMutate.mock.calls[0][0]).toEqual({ kind: 'action', id: 'repo-1', to: 'personal', directory: '/repo' }) }) it('shows the trust banner for an untrusted repo file and sends the displayed hash', async () => { @@ -146,12 +191,13 @@ describe('RepoActionsDialog', () => { renderDialog() expect(screen.getByText(/not trusted/i)).toBeInTheDocument() - await user.click(screen.getByRole('button', { name: /trust these commands/i })) + const review = await openTrustReview(user) + await user.click(within(review).getByRole('button', { name: /trust these commands/i })) expect(mocks.trustMutate.mock.calls[0][0]).toEqual({ hash: HASH, directory: '/repo' }) }) - it('lists every executable action and setup command, including shadowed actions', () => { + it('lists every executable action and setup command, including shadowed actions', async () => { mockConfig( baseConfig({ actions: [ @@ -172,15 +218,17 @@ describe('RepoActionsDialog', () => { }, }), ) + const user = userEvent.setup() renderDialog() - expect(screen.getAllByText('Actions').length).toBeGreaterThan(1) - expect(screen.getByText('Repo action')).toBeInTheDocument() - expect(screen.getByText('echo repo')).toBeInTheDocument() - expect(screen.getByText('https://example.com')).toBeInTheDocument() - expect(screen.getByText('Opens URL automatically')).toBeInTheDocument() - expect(screen.getByText('Worktree setup commands')).toBeInTheDocument() - expect(screen.getByText('pnpm install')).toBeInTheDocument() + const review = await openTrustReview(user) + expect(within(review).getByText('Actions')).toBeInTheDocument() + expect(within(review).getByText('Repo action')).toBeInTheDocument() + expect(within(review).getByText('echo repo')).toBeInTheDocument() + expect(within(review).getByText('https://example.com')).toBeInTheDocument() + expect(within(review).getByText('Opens URL automatically')).toBeInTheDocument() + expect(within(review).getByText('Worktree setup commands')).toBeInTheDocument() + expect(within(review).getByText('pnpm install')).toBeInTheDocument() }) it('does not offer trust when the repo file has no executable commands', () => { @@ -192,7 +240,7 @@ describe('RepoActionsDialog', () => { renderDialog() expect(screen.queryByText(/not trusted/i)).not.toBeInTheDocument() - expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: /^review$/i })).not.toBeInTheDocument() }) it('uses the shared action icon map', () => { @@ -223,7 +271,8 @@ describe('RepoActionsDialog', () => { ) renderDialog() - expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument() + expect(screen.queryByText(/not trusted/i)).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: /^review$/i })).not.toBeInTheDocument() }) it('renders repository config parse errors', () => { @@ -254,8 +303,11 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() renderDialog() - await user.click(screen.getByRole('button', { name: /move to repository/i })) + await openSetupTab(user) + const menu = await openRowMenu(user, 'Actions for setup command 1') + await user.click(within(menu).getByRole('menuitem', { name: /move to repository/i })) + await waitFor(() => expect(mocks.moveMutate).toHaveBeenCalledTimes(1)) expect(mocks.moveMutate.mock.calls[0][0]).toEqual({ kind: 'setup', command: 'pnpm install', @@ -273,14 +325,47 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() renderDialog() - expect(screen.getByRole('button', { name: /move to repository/i })).toBeEnabled() + await openSetupTab(user) + let menu = await openRowMenu(user, 'Actions for setup command 1') + expect(within(menu).getByRole('menuitem', { name: /move to repository/i })).not.toHaveAttribute('aria-disabled') + await closeRowMenu(user) await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') + await user.tab() - expect(screen.getByRole('button', { name: /move to repository/i })).toBeDisabled() + menu = await openRowMenu(user, 'Actions for setup command 1') + expect(within(menu).getByRole('menuitem', { name: /move to repository/i })).toHaveAttribute('aria-disabled', 'true') + await closeRowMenu(user) expect(mocks.moveMutate).not.toHaveBeenCalled() }) + it('enables saving setup only after an edit and pins the save button outside the scrolling list', async () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const user = userEvent.setup() + renderDialog() + + await openSetupTab(user) + const save = screen.getByRole('button', { name: /save setup/i }) + expect(save).toBeDisabled() + expect(screen.queryByText('Unsaved changes')).not.toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: /add command/i })) + expect(screen.getByLabelText('Setup command 2')).toHaveFocus() + expect(save).toBeDisabled() + + await user.type(screen.getByLabelText('Setup command 2'), 'pnpm build') + expect(save).toBeEnabled() + expect(screen.getByText('Unsaved changes')).toBeInTheDocument() + expect(save.closest('.overflow-y-auto')).toBeNull() + + await user.click(save) + expect(mocks.updateSetupMutate.mock.calls[0][0]).toEqual(['pnpm install', 'pnpm build']) + }) + it('reports a failed action save and keeps the draft', async () => { mockConfig( baseConfig({ @@ -321,6 +406,7 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() renderDialog() + await openSetupTab(user) const input = screen.getByLabelText('Setup command 1') await user.clear(input) await user.type(input, 'pnpm ci') @@ -359,7 +445,8 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() renderDialog() - await user.click(screen.getByRole('button', { name: /trust these commands/i })) + const review = await openTrustReview(user) + await user.click(within(review).getByRole('button', { name: /trust these commands/i })) expect(mocks.showToastError).toHaveBeenCalledWith('Trust rejected') }) @@ -380,9 +467,10 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() renderDialog() - await user.click(screen.getByRole('button', { name: /move to repository/i })) + const menu = await openRowMenu(user, 'Actions for Personal action') + await user.click(within(menu).getByRole('menuitem', { name: /move to repository/i })) - expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected') + await waitFor(() => expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected')) }) it('preserves unsaved setup edits when unrelated config data refetches', async () => { @@ -397,6 +485,7 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() const view = renderDialog() + await openSetupTab(user) await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') mockConfig( @@ -414,13 +503,15 @@ describe('RepoActionsDialog', () => { expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install --frozen-lockfile') }) - it('reflects persisted setup commands after a setup operation', () => { + it('reflects persisted setup commands after a setup operation', async () => { mockConfig( baseConfig({ worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], }), ) + const user = userEvent.setup() const view = renderDialog() + await openSetupTab(user) mockConfig( baseConfig({ @@ -441,10 +532,12 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() const view = renderDialog() + await openSetupTab(user) await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') view.rerender() view.rerender() + await openSetupTab(user) expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install') }) @@ -458,6 +551,7 @@ describe('RepoActionsDialog', () => { const user = userEvent.setup() const view = renderDialog() + await openSetupTab(user) await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') mockConfig( diff --git a/frontend/src/components/repo/RepoActionsDialog.tsx b/frontend/src/components/repo/RepoActionsDialog.tsx index 4cbcebef..18b78f62 100644 --- a/frontend/src/components/repo/RepoActionsDialog.tsx +++ b/frontend/src/components/repo/RepoActionsDialog.tsx @@ -1,13 +1,16 @@ import { useEffect, useMemo, useRef, useState } from 'react' -import { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert, Trash2 } from 'lucide-react' +import { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert } from 'lucide-react' import { arrayMove } from '@dnd-kit/sortable' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' +import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Switch } from '@/components/ui/switch' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { SettingsList, SettingsListRow, SettingsListRowActionsMenu } from '@/components/ui/settings-list' +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { useMoveProjectItem, useProjectConfig, @@ -21,6 +24,7 @@ import { randomId } from '@/lib/utils' import type { ProjectAction, ProjectActionIcon, + ProjectConfigResponse, ProjectItemSource, } from '@opencode-manager/shared/types' import { ACTION_ICON_OPTIONS, actionIcon } from './projectActionIcons' @@ -85,16 +89,41 @@ interface ActionFormProps { function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormProps) { const canSave = draft.name.trim().length > 0 && draft.command.trim().length > 0 + const formRef = useRef(null) + + useEffect(() => { + formRef.current?.scrollIntoView({ block: 'nearest' }) + }, []) return ( -
-
- - onChange({ ...draft, name: event.target.value })} - /> +
+
+
+ + onChange({ ...draft, name: event.target.value })} + /> +
+
+ + +
@@ -104,24 +133,6 @@ function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormP onChange={(event) => onChange({ ...draft, command: event.target.value })} />
-
- - -
+ +interface TrustReview { + hash: string + directory: string | undefined + executable: RepoFileExecutable +} + +const COMPACT_ROW_CLASS = 'flex-row items-center gap-3 py-2.5' + +function ActionTitle({ action }: { action: ProjectAction }) { + const Icon = actionIcon(action.icon) + return ( + <> + + {action.name} + + ) +} + +function ActionUrl({ url }: { url: string | undefined }) { + if (!url) return null + return

{url}

+} + +function TabCount({ count }: { count: number }) { + return {count} +} + interface RepoActionsDialogProps { repoId: number directory: string | undefined @@ -167,8 +207,11 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep const [draft, setDraft] = useState(null) const [setupCommands, setSetupCommands] = useState([]) + const [focusSetupIndex, setFocusSetupIndex] = useState(null) + const [trustReview, setTrustReview] = useState(null) const config = configQuery.data + const repoFile = config?.repoFile const personalActions = useMemo( () => (config?.actions ?? []).filter((action) => action.source === 'personal'), @@ -192,12 +235,14 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep useEffect(() => { if (!open || !config) { setupSyncKey.current = null + setTrustReview(null) return } const syncKey = `${directory ?? ''}\u0000${personalSetupBaseline}` if (setupSyncKey.current === syncKey) return setupSyncKey.current = syncKey setSetupCommands(personalSetup) + setFocusSetupIndex(null) }, [open, config, directory, personalSetup, personalSetupBaseline]) const setupDirty = useMemo( @@ -206,6 +251,7 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep setupCommands.some((command, index) => command !== personalSetup[index]), [setupCommands, personalSetup], ) + const setupValid = setupCommands.every((command) => command.trim().length > 0) const handleSaveAction = (nextDraft: ActionDraft) => { const payload = draftToPayload(nextDraft) @@ -231,11 +277,26 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep }) } + const addSetupCommand = () => { + setFocusSetupIndex(setupCommands.length) + setSetupCommands((current) => [...current, '']) + } + + const needsTrust = Boolean(repoFile?.exists && !repoFile.trusted && repoFile.hash && repoFile.executable) + + const openTrustReview = () => { + if (!repoFile?.hash || !repoFile.executable) return + setTrustReview({ hash: repoFile.hash, directory, executable: repoFile.executable }) + } + const handleTrust = () => { - if (!config?.repoFile.hash) return + if (!trustReview) return trustConfig.mutate( - { hash: config.repoFile.hash, directory }, - { onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')) }, + { hash: trustReview.hash, directory: trustReview.directory }, + { + onSuccess: () => setTrustReview(null), + onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')), + }, ) } @@ -254,285 +315,290 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep } const isAddingAction = draft !== null && !personalActions.some((action) => action.id === draft.id) + const hasRepoFileStatus = Boolean(repoFile?.error) || (repoFile?.warnings.length ?? 0) > 0 || needsTrust + + const renderActionForm = (current: ActionDraft) => ( + setDraft(null)} + /> + ) return ( - - - - Project Actions - Commands and setup steps for this location. - + <> + + + + Project Actions + Commands and setup steps for this location. + -
{configQuery.isLoading ? (
) : !config ? ( -

+

{configQuery.error instanceof Error ? configQuery.error.message : 'No configuration available.'}

) : ( <> -
-
-

Actions

- -
- - {personalActions.length === 0 && repoActions.length === 0 && ( -

No actions configured.

- )} - - {personalActions.map((action) => { - const Icon = actionIcon(action.icon) - const isEditing = draft?.id === action.id - return ( -
- {isEditing && draft ? ( - setDraft(null)} - /> - ) : ( - <> -
- - {action.name} -
-

{action.command}

- {action.url && ( -

{action.url}

- )} -
- - - -
- - )} -
- ) - })} - - {repoActions.map((action) => { - const Icon = actionIcon(action.icon) - return ( -
-
- - {action.name} - In repo + {hasRepoFileStatus && ( +
+ {config.repoFile.error && ( +

+ {config.repoFile.error} +

+ )} + {config.repoFile.warnings.map((warning) => ( +

+ {warning} +

+ ))} + {needsTrust && ( +
+ +
+

Repository commands are not trusted

+

They won't run until you review and trust them.

-

{action.command}

- {action.url && ( -

{action.url}

- )} -
- ) - })} + )} +
+ )} - {isAddingAction && draft && ( -
- setDraft(null)} - /> -
- )} -
- -
-
-

Worktree setup

-

- Commands run after a new worktree is created. Use{' '} - $ROOT_PROJECT_PATH to reference the main checkout. -

+ +
+ + + Actions + + + + Worktree setup + + +
- {setupCommands.length === 0 && repoSetup.length === 0 && ( -

No setup commands.

- )} - - {setupCommands.map((command, index) => ( -
-
- - setSetupCommands((current) => - current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)), - ) - } - /> - - - -
-
- -
-
- ))} - - {repoSetup.map((item) => ( -
-
- {item.command} - In repo -
+ +
+

Start these from the actions menu in the header.

- ))} +
+ + {personalActions.map((action) => + draft?.id === action.id ? ( + renderActionForm(draft) + ) : ( + } + description={{action.command}} + belowDescription={} + onClick={() => setDraft(actionToDraft(action))} + trailing={ + + } + actions={[ + { + label: 'Move to repository', + onClick: () => moveAction(action, 'repo'), + disabled: moveItem.isPending, + }, + { + label: 'Delete', + destructive: true, + separatorBefore: true, + onClick: () => handleDeleteAction(action.id), + disabled: updateActions.isPending, + }, + ]} + actionsLabel={`Actions for ${action.name}`} + /> + ), + )} + {isAddingAction && draft && renderActionForm(draft)} + {repoActions.map((action) => ( + } + badges={In repo} + description={{action.command}} + belowDescription={} + actions={[ + { + label: 'Move to my settings', + onClick: () => moveAction(action, 'personal'), + disabled: moveItem.isPending, + }, + ]} + actionsLabel={`Actions for ${action.name}`} + /> + ))} + +
+
-
- - -
-
- -
- {config.repoFile.error && ( -

- {config.repoFile.error} -

- )} - {config.repoFile.warnings.map((warning) => ( -

- {warning} -

- ))} - {config.repoFile.exists && - !config.repoFile.trusted && - config.repoFile.hash && - config.repoFile.executable && ( -
-
- - Repository commands are not trusted -
-

- This repository defines commands that run on your machine. Review and trust them to enable. -

- - -
- )} -
+ +
+

+ Run in order after a new worktree is created.{' '} + $ROOT_PROJECT_PATH points to the main checkout. +

+ +
+
+ + {setupCommands.map((command, index) => ( +
+ + setSetupCommands((current) => + current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)), + ) + } + /> + + + moveSetup(command, 'repo'), + disabled: setupDirty || moveItem.isPending, + }, + { + label: 'Remove', + destructive: true, + separatorBefore: true, + onClick: () => + setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index)), + }, + ]} + /> +
+ ))} + {repoSetup.map((item) => ( + {item.command}} + titleClassName="font-mono text-xs font-normal" + badges={In repo} + actions={[ + { + label: 'Move to my settings', + onClick: () => moveSetup(item.command, 'personal'), + disabled: moveItem.isPending, + }, + ]} + actionsLabel={`Actions for ${item.command}`} + /> + ))} +
+
+
+

+ {setupDirty ? 'Unsaved changes' : ''} +

+ +
+
+ )} -
-
-
+
+
+ + { if (!next) setTrustReview(null) }} + onConfirm={handleTrust} + onCancel={() => setTrustReview(null)} + title="Trust repository commands" + description="This repository defines commands that run on your machine." + warning={trustReview ? : undefined} + confirmLabel="Trust these commands" + pendingLabel="Trusting…" + isPending={trustConfig.isPending} + /> + ) } diff --git a/frontend/src/components/terminal/TerminalPanel.test.tsx b/frontend/src/components/terminal/TerminalPanel.test.tsx index de031cee..63e2b523 100644 --- a/frontend/src/components/terminal/TerminalPanel.test.tsx +++ b/frontend/src/components/terminal/TerminalPanel.test.tsx @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { fireEvent, render, screen } from '@testing-library/react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { MemoryRouter } from 'react-router-dom' import type { TerminalInfo } from '@opencode-manager/shared/types' import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals' @@ -130,6 +131,84 @@ describe('TerminalPanel', () => { expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object)) }) + it('auto-creates a shell when only exited terminals exist and none is requested', () => { + mockTerminalHooks([exitedTerminal]) + renderPanel() + + expect(createMutate).toHaveBeenCalledTimes(1) + expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object)) + }) + + it('decides on auto-creation once per opening, so a shell exiting later is not replaced', () => { + mockTerminalHooks([runningTerminal]) + const { rerender } = renderPanel() + expect(createMutate).not.toHaveBeenCalled() + + mockTerminalHooks([{ ...runningTerminal, status: 'exited', exitCode: 0 }]) + rerender( + + + , + ) + + expect(createMutate).not.toHaveBeenCalled() + }) + + it('shows a requested exited terminal without auto-creating a shell', async () => { + mockTerminalHooks([exitedTerminal]) + renderPanel('/repos/1?dialog=terminal&terminal=t2') + + const view = await screen.findByTestId('terminal-view') + expect(view).toHaveAttribute('data-active', 'true') + expect(createMutate).not.toHaveBeenCalled() + }) + + it('selects a running terminal over an exited one when none is requested', async () => { + mockTerminalHooks([exitedTerminal, runningTerminal]) + renderPanel() + + const views = await screen.findAllByTestId('terminal-view') + expect(views.find((view) => view.getAttribute('data-pty-id') === 't1')).toHaveAttribute('data-active', 'true') + expect(createMutate).not.toHaveBeenCalled() + }) + + it('opens a requested terminal without auto-creating a shell from a stale cached empty list', async () => { + const actual = await vi.importActual('@/api/terminals') + vi.mocked(useTerminals).mockImplementation(actual.useTerminals) + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + queryClient.setQueryData(['terminals', 1, '/repo'], []) + let resolveList: (response: Response) => void = () => {} + const fetchMock = vi.fn(() => new Promise((resolve) => { resolveList = resolve })) + vi.stubGlobal('fetch', fetchMock) + const panel = (isOpen: boolean) => ( + + + + + + ) + + try { + const { rerender } = render(panel(false)) + rerender(panel(true)) + + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)) + expect(createMutate).not.toHaveBeenCalled() + + resolveList(new Response(JSON.stringify({ terminals: [exitedTerminal] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + })) + + const view = await screen.findByTestId('terminal-view') + expect(view).toHaveAttribute('data-pty-id', 't2') + expect(view).toHaveAttribute('data-active', 'true') + expect(createMutate).not.toHaveBeenCalled() + } finally { + vi.unstubAllGlobals() + } + }) + it('exposes an accessible name for the mobile panel close control', async () => { mockTerminalHooks([runningTerminal]) vi.mocked(useMobile).mockReturnValue(true) diff --git a/frontend/src/components/terminal/TerminalPanel.tsx b/frontend/src/components/terminal/TerminalPanel.tsx index 068ed0b8..aaae0a66 100644 --- a/frontend/src/components/terminal/TerminalPanel.tsx +++ b/frontend/src/components/terminal/TerminalPanel.tsx @@ -28,7 +28,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa const isMobile = useMobile() const { searchParams, updateParams } = useUrlParams() const openPreview = useOpenPreview() - const { data, isLoading, isSuccess, refetch } = useTerminals(repoId, directory, { + const { data, isLoading, isSuccess, isFetching, refetch } = useTerminals(repoId, directory, { enabled: isOpen && !!directory, refetchInterval: isOpen ? 5000 : false, }) @@ -38,7 +38,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa const [ctrlArmed, setCtrlArmed] = useState(false) const [pendingClose, setPendingClose] = useState(null) const viewHandlesRef = useRef(new Map()) - const autoCreatedDirectoryRef = useRef(null) + const autoCreateCheckedDirectoryRef = useRef(null) const terminals = useMemo(() => data ?? [], [data]) @@ -49,23 +49,25 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa }, [updateParams]) const requestedTerminalId = searchParams.get('terminal') - const activeTerminalId = requestedTerminalId && terminals.some((terminal) => terminal.id === requestedTerminalId) - ? requestedTerminalId - : terminals[0]?.id + const requestedTerminal = terminals.find((terminal) => terminal.id === requestedTerminalId) + const runningTerminal = terminals.find((terminal) => terminal.status === 'running') + const activeTerminalId = (requestedTerminal ?? runningTerminal ?? terminals[0])?.id + const needsShell = !requestedTerminal && !runningTerminal useEffect(() => { if (!isOpen || !directory) { - autoCreatedDirectoryRef.current = null + autoCreateCheckedDirectoryRef.current = null return } - if (!isSuccess || terminals.length > 0) return - if (autoCreatedDirectoryRef.current === directory) return - autoCreatedDirectoryRef.current = directory + if (!isSuccess || isFetching) return + if (autoCreateCheckedDirectoryRef.current === directory) return + autoCreateCheckedDirectoryRef.current = directory + if (!needsShell) return createTerminal( { directory }, { onSuccess: (terminal) => selectTerminal(terminal.id) }, ) - }, [isOpen, directory, isSuccess, terminals.length, createTerminal, selectTerminal]) + }, [isOpen, directory, isSuccess, isFetching, needsShell, createTerminal, selectTerminal]) const handleCreate = useCallback(() => { createTerminal( diff --git a/frontend/src/components/ui/combobox.test.tsx b/frontend/src/components/ui/combobox.test.tsx new file mode 100644 index 00000000..5ff5e372 --- /dev/null +++ b/frontend/src/components/ui/combobox.test.tsx @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { Combobox } from './combobox' + +const options = [ + { value: 'builtin', label: 'Built-in Browser' }, + { value: 'external', label: 'External API' }, +] + +function renderCombobox(onOpen = vi.fn()) { + render( +
+ + +
, + ) + return screen.getByRole('combobox', { name: 'Provider' }) +} + +describe('Combobox', () => { + it('restores the selected label, not the raw value, on Escape', async () => { + const user = userEvent.setup() + const input = renderCombobox() + + await user.clear(input) + await user.type(input, 'Ext') + await user.keyboard('{Escape}') + + expect(input).toHaveValue('Built-in Browser') + }) + + it('restores the selected label, not the raw value, on an outside click', async () => { + const user = userEvent.setup() + const input = renderCombobox() + + await user.clear(input) + await user.type(input, 'Ext') + await user.click(screen.getByRole('button', { name: 'Outside' })) + + expect(input).toHaveValue('Built-in Browser') + }) + + it('calls onOpen each time the options open', async () => { + const user = userEvent.setup() + const onOpen = vi.fn() + const input = renderCombobox(onOpen) + + await user.click(input) + await user.keyboard('{Escape}') + await user.click(screen.getByRole('button', { name: 'Outside' })) + await user.click(input) + + expect(onOpen).toHaveBeenCalledTimes(2) + }) +}) diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx index b0b16dd9..54a3fa02 100644 --- a/frontend/src/components/ui/combobox.tsx +++ b/frontend/src/components/ui/combobox.tsx @@ -18,6 +18,12 @@ interface ComboboxProps { className?: string allowCustomValue?: boolean showClear?: boolean + ariaLabel?: string + onOpen?: () => void +} + +function getOptionLabel(options: ComboboxOption[], value: string): string { + return options.find(o => o.value === value)?.label || value } export function Combobox({ @@ -29,12 +35,11 @@ export function Combobox({ className, allowCustomValue = true, showClear = false, + ariaLabel, + onOpen, }: ComboboxProps) { const [isOpen, setIsOpen] = useState(false) - const [inputValue, setInputValue] = useState(() => { - const selectedOption = options.find(o => o.value === value) - return selectedOption?.label || value - }) + const [inputValue, setInputValue] = useState(() => getOptionLabel(options, value)) const [selectedIndex, setSelectedIndex] = useState(0) const [isUserTyping, setIsUserTyping] = useState(false) const inputRef = useRef(null) @@ -43,11 +48,24 @@ export function Combobox({ useEffect(() => { if (!isUserTyping) { - const selectedOption = options.find(o => o.value === value) - setInputValue(selectedOption?.label || value) + setInputValue(getOptionLabel(options, value)) } }, [value, options, isUserTyping]) + const onOpenRef = useRef(onOpen) + useEffect(() => { + onOpenRef.current = onOpen + }, [onOpen]) + + useEffect(() => { + if (isOpen) onOpenRef.current?.() + }, [isOpen]) + + const restoreSelectedLabel = useCallback(() => { + setInputValue(getOptionLabel(options, value)) + setIsUserTyping(false) + }, [options, value]) + const isExactMatch = options.some(o => o.value === value || o.label === inputValue) const filteredOptions = (isExactMatch && !isUserTyping) ? options : options.filter(option => @@ -77,15 +95,15 @@ export function Combobox({ setIsOpen(false) if (allowCustomValue) { onChange(inputValue) - } else if (!options.some(o => o.value === inputValue)) { - setInputValue(value) + } else { + restoreSelectedLabel() } } } document.addEventListener('mousedown', handleClickOutside) return () => document.removeEventListener('mousedown', handleClickOutside) - }, [isOpen, inputValue, value, onChange, options, allowCustomValue]) + }, [isOpen, inputValue, onChange, allowCustomValue, restoreSelectedLabel]) useEffect(() => { if (!isOpen || !listRef.current) return @@ -135,7 +153,7 @@ export function Combobox({ case 'Escape': e.preventDefault() setIsOpen(false) - setInputValue(value) + restoreSelectedLabel() break case 'Tab': setIsOpen(false) @@ -144,7 +162,7 @@ export function Combobox({ } break } - }, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, value, onChange]) + }, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, onChange, restoreSelectedLabel]) const handleInputChange = useCallback((e: React.ChangeEvent) => { const newValue = e.target.value @@ -174,6 +192,10 @@ export function Combobox({ onKeyDown={handleKeyDown} placeholder={placeholder} disabled={disabled} + role="combobox" + aria-label={ariaLabel} + aria-autocomplete="list" + aria-expanded={isOpen} className={cn( 'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-[16px] md:text-sm shadow-sm transition-colors', 'file:border-0 file:bg-transparent file:text-sm file:font-medium', diff --git a/frontend/src/components/ui/dialog.test.tsx b/frontend/src/components/ui/dialog.test.tsx index 5435d0ac..95b8c72e 100644 --- a/frontend/src/components/ui/dialog.test.tsx +++ b/frontend/src/components/ui/dialog.test.tsx @@ -1,7 +1,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { useState } from "react"; import { render, screen, act, fireEvent, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { stubMatchMedia } from "@/test/test-utils"; +import { Combobox } from "./combobox"; import { Dialog, DialogContent, @@ -33,6 +35,29 @@ describe("DialogContent", () => { }) }) + it("closes an open combobox on Escape before closing the dialog", async () => { + const user = userEvent.setup(); + const onOpenChange = vi.fn(); + render( + + + Test Dialog + + + + ); + const combobox = screen.getByRole("combobox", { name: "Choice" }); + + await user.click(combobox); + expect(combobox).toHaveAttribute("aria-expanded", "true"); + await user.keyboard("{Escape}"); + expect(combobox).toHaveAttribute("aria-expanded", "false"); + expect(onOpenChange).not.toHaveBeenCalled(); + + await user.keyboard("{Escape}"); + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + it("applies safe-area padding when fullscreen prop is true", () => { render( diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index b6d34f5e..9e49feca 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -77,7 +77,7 @@ interface DialogContentProps const DialogContent = React.forwardRef< React.ElementRef, DialogContentProps ->(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, ...props }, ref) => { +>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, onEscapeKeyDown, ...props }, ref) => { const isMobileFullscreenMode = fullscreen || mobileFullscreen const isDialogOpen = React.useContext(DialogOpenContext) const returnFocus = React.useContext(DialogReturnFocusContext) @@ -87,6 +87,12 @@ const DialogContent = React.forwardRef< event.preventDefault() returnFocus.focus() } + const handleEscapeKeyDown = (event: KeyboardEvent) => { + onEscapeKeyDown?.(event) + if (event.target instanceof Element && event.target.matches('[role="combobox"][aria-expanded="true"]')) { + event.preventDefault() + } + } const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false) const shouldEnableMobileSwipe = mobileSwipeToClose !== false && isMobile && isDialogOpen const shouldAnimateSwipe = shouldEnableMobileSwipe && isMobileFullscreenMode @@ -150,6 +156,7 @@ const DialogContent = React.forwardRef< style={Object.keys(mergedStyle).length > 0 ? mergedStyle : undefined} {...props} onCloseAutoFocus={handleCloseAutoFocus} + onEscapeKeyDown={handleEscapeKeyDown} > {children} {shouldEnableMobileSwipe && ( diff --git a/frontend/src/components/ui/path-display.tsx b/frontend/src/components/ui/path-display.tsx index d242b34c..93c7eed6 100644 --- a/frontend/src/components/ui/path-display.tsx +++ b/frontend/src/components/ui/path-display.tsx @@ -1,4 +1,5 @@ import { useMemo } from 'react' +import { shortenPath } from '@/lib/utils' interface PathDisplayProps { path: string @@ -7,19 +8,7 @@ interface PathDisplayProps { } export function PathDisplay({ path, maxSegments = 3, className = '' }: PathDisplayProps) { - const displayPath = useMemo(() => { - if (!path || path === '/') return '/' - - const normalizedPath = path.startsWith('/') ? path : '/' + path - const segments = normalizedPath.split('/').filter(Boolean) - - if (segments.length <= maxSegments) { - return '/' + segments.join('/') - } - - const visibleSegments = segments.slice(-maxSegments) - return '/.../' + visibleSegments.join('/') - }, [path, maxSegments]) + const displayPath = useMemo(() => shortenPath(path, maxSegments), [path, maxSegments]) return ( + + + + + {actions.map((action, i) => ( + + {action.separatorBefore && i > 0 && } + setTimeout(action.onClick, 0)} + className={action.destructive ? 'text-destructive focus:text-destructive' : undefined} + > + {action.icon} + {action.label} + + + ))} + + + ) +} + export function SettingsListRow({ title, titleClassName, @@ -136,7 +168,7 @@ export function SettingsListRow({ {belowDescription}
e.stopPropagation()} > {trailing} @@ -151,28 +183,7 @@ export function SettingsListRow({ )} {overflowActions && overflowActions.length > 0 && ( - - - - - - {overflowActions.map((action, i) => ( - - {action.separatorBefore && i > 0 && } - setTimeout(action.onClick, 0)} - className={action.destructive ? 'text-destructive focus:text-destructive' : undefined} - > - {action.icon} - {action.label} - - - ))} - - + )}
diff --git a/frontend/src/hooks/useDialogParam.ts b/frontend/src/hooks/useDialogParam.ts index e0a0d7c8..de40cce0 100644 --- a/frontend/src/hooks/useDialogParam.ts +++ b/frontend/src/hooks/useDialogParam.ts @@ -31,7 +31,12 @@ export function openDialogParam( }, 'push') } -export function useDialogParam(name: string): [boolean, (open: boolean) => void] { +const NO_OWNED_PARAMS: readonly string[] = [] + +export function useDialogParam( + name: string, + ownedParams: readonly string[] = NO_OWNED_PARAMS, +): [boolean, (open: boolean) => void] { const { searchParams, updateParams } = useUrlParams() const isOpen = searchParams.get('dialog') === name @@ -43,12 +48,12 @@ export function useDialogParam(name: string): [boolean, (open: boolean) => void] return } updateParams((p) => { - if (p.get('dialog') === name) { - p.delete('dialog') - } + if (p.get('dialog') !== name) return + p.delete('dialog') + for (const param of ownedParams) p.delete(param) }, 'replace') }, - [updateParams, name], + [updateParams, name, ownedParams], ) return [isOpen, setOpen] diff --git a/frontend/src/hooks/useOpenTerminal.test.tsx b/frontend/src/hooks/useOpenTerminal.test.tsx index d5892625..203acc0a 100644 --- a/frontend/src/hooks/useOpenTerminal.test.tsx +++ b/frontend/src/hooks/useOpenTerminal.test.tsx @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest' import { act } from '@testing-library/react' import { renderHookWithRouterAndLocation } from '@/test/test-utils' -import { useOpenTerminal } from './useOpenTerminal' +import { useOpenTerminal, useTerminalDialogParam } from './useOpenTerminal' describe('useOpenTerminal', () => { it('opens the terminal dialog with the terminal id', () => { @@ -36,3 +36,38 @@ describe('useOpenTerminal', () => { expect(params.has('mobileTab')).toBe(false) }) }) + +describe('useTerminalDialogParam', () => { + it('drops the selected terminal when the dialog closes so a later open is not tied to it', () => { + const { result, capturedSearch } = renderHookWithRouterAndLocation( + () => useTerminalDialogParam(), + ['/repos/1?dialog=terminal&terminal=pty-1&keep=1'], + ) + expect(result.current[0]).toBe(true) + + act(() => { + result.current[1](false) + }) + + const params = new URLSearchParams(capturedSearch.current) + expect(result.current[0]).toBe(false) + expect(params.has('dialog')).toBe(false) + expect(params.has('terminal')).toBe(false) + expect(params.get('keep')).toBe('1') + }) + + it('leaves another dialog and its params alone', () => { + const { result, capturedSearch } = renderHookWithRouterAndLocation( + () => useTerminalDialogParam(), + ['/repos/1?dialog=preview&terminal=pty-1'], + ) + + act(() => { + result.current[1](false) + }) + + const params = new URLSearchParams(capturedSearch.current) + expect(params.get('dialog')).toBe('preview') + expect(params.get('terminal')).toBe('pty-1') + }) +}) diff --git a/frontend/src/hooks/useOpenTerminal.ts b/frontend/src/hooks/useOpenTerminal.ts index 9926ec1b..93e39e20 100644 --- a/frontend/src/hooks/useOpenTerminal.ts +++ b/frontend/src/hooks/useOpenTerminal.ts @@ -1,7 +1,14 @@ import { useCallback } from 'react' -import { openDialogParam } from './useDialogParam' +import { openDialogParam, useDialogParam } from './useDialogParam' import { useUrlParams } from './useUrlParams' +const TERMINAL_DIALOG = 'terminal' +const TERMINAL_DIALOG_PARAMS = ['terminal'] as const + +export function useTerminalDialogParam(): [boolean, (open: boolean) => void] { + return useDialogParam(TERMINAL_DIALOG, TERMINAL_DIALOG_PARAMS) +} + export function useOpenTerminal(): ( terminalId: string, extraParams?: Record, @@ -10,7 +17,7 @@ export function useOpenTerminal(): ( return useCallback( (terminalId: string, extraParams?: Record) => { - openDialogParam(updateParams, 'terminal', { terminal: terminalId, ...extraParams }) + openDialogParam(updateParams, TERMINAL_DIALOG, { terminal: terminalId, ...extraParams }) }, [updateParams], ) diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts index aebbf9a5..e80d96a1 100644 --- a/frontend/src/lib/utils.test.ts +++ b/frontend/src/lib/utils.test.ts @@ -6,8 +6,20 @@ import { randomId, formatShortRelativeTime, getOriginOnlyBranchNames, + shortenPath, } from './utils' +describe('shortenPath', () => { + it('keeps short paths and collapses the leading segments of long ones', () => { + expect(shortenPath('/')).toBe('/') + expect(shortenPath('')).toBe('/') + expect(shortenPath('/a/b/c')).toBe('/a/b/c') + expect(shortenPath('a/b')).toBe('/a/b') + expect(shortenPath('/Users/chris/development/oc-manager/workspace/repos/test')).toBe('/.../workspace/repos/test') + expect(shortenPath('/a/b/c/d/e', 4)).toBe('/.../b/c/d/e') + }) +}) + describe('sanitizeForTTS', () => { it('should handle headers', () => { expect(sanitizeForTTS('# Main Header\n## Sub Header\n### Detail')).toBe('Main Header\nSub Header\nDetail') diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 32820576..a4b34ccd 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -33,6 +33,14 @@ export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } +/** Keeps the last `maxSegments` segments of an absolute path, replacing the rest with `/...`. */ +export function shortenPath(path: string, maxSegments = 3): string { + const segments = path.split('/').filter(Boolean) + if (segments.length === 0) return '/' + if (segments.length <= maxSegments) return `/${segments.join('/')}` + return `/.../${segments.slice(-maxSegments).join('/')}` +} + export function randomId(): string { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { return crypto.randomUUID() diff --git a/frontend/src/pages/AssistantRedirect.tsx b/frontend/src/pages/AssistantRedirect.tsx index 36f3d9e4..69c7e5ce 100644 --- a/frontend/src/pages/AssistantRedirect.tsx +++ b/frontend/src/pages/AssistantRedirect.tsx @@ -3,6 +3,7 @@ import { useQuery } from "@tanstack/react-query" import { getRepo } from "@/api/repos" import { useCreateSession } from "@/hooks/useOpenCode" import { useDialogParam } from "@/hooks/useDialogParam" +import { useTerminalDialogParam } from "@/hooks/useOpenTerminal" import { useSSE } from "@/hooks/useSSE" import { getSessionPath } from "@/lib/navigation" import { Button } from "@/components/ui/button" @@ -25,7 +26,7 @@ export function AssistantRedirect() { const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp') const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills') const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl') - const [terminalOpen, setTerminalOpen] = useDialogParam('terminal') + const [terminalOpen, setTerminalOpen] = useTerminalDialogParam() const [previewOpen, setPreviewOpen] = useDialogParam('preview') const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions') diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index b1dff887..d031a2ab 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -18,7 +18,7 @@ import { useRepoActivity } from "@/hooks/useRepoActivity"; import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings"; import { useSSE } from "@/hooks/useSSE"; import { useDialogParam } from "@/hooks/useDialogParam"; -import { useOpenTerminal } from "@/hooks/useOpenTerminal"; +import { useOpenTerminal, useTerminalDialogParam } from "@/hooks/useOpenTerminal"; import { useWorktreeTab } from "@/hooks/useWorktreeTab"; import { WorktreeTabs } from "@/components/repo/WorktreeTabs"; import { WorkspaceManager } from "@/components/repo/WorkspaceManager"; @@ -40,7 +40,7 @@ export function RepoDetail() { const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp'); const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills'); const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl'); - const [terminalOpen, setTerminalOpen] = useDialogParam('terminal'); + const [terminalOpen, setTerminalOpen] = useTerminalDialogParam(); const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions'); const [previewOpen, setPreviewOpen] = useDialogParam('preview'); const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions'); diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index ca048fbe..7aa3b784 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -59,6 +59,7 @@ import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBan import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar"; import { SessionGoalBar } from "@/components/session/SessionGoalBar"; import { useDialogParam } from "@/hooks/useDialogParam"; +import { useTerminalDialogParam } from "@/hooks/useOpenTerminal"; import { SessionMoreButton } from "@/components/navigation/SessionMoreButton"; import { SideQuestionDialog } from "@/components/session/SideQuestionDialog"; import { SessionMessagePickerDialog } from "@/components/session/SessionMessagePickerDialog"; @@ -123,7 +124,7 @@ export function SessionDetail() { const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp'); const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills'); const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl'); - const [terminalOpen, setTerminalOpen] = useDialogParam('terminal'); + const [terminalOpen, setTerminalOpen] = useTerminalDialogParam(); const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions'); const [previewOpen, setPreviewOpen] = useDialogParam('preview'); const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions'); diff --git a/mkdocs.yml b/mkdocs.yml index bbe41ee5..120f6693 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -55,6 +55,7 @@ nav: - Authentication: configuration/authentication.md - OAuth Providers: configuration/oauth.md - Docker: configuration/docker.md + - Cloudflare Tunnel: configuration/cloudflare-tunnel.md - Development: - Local Setup: development/setup.md - Contributing: development/contributing.md