mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(ui): preview port menu, terminal auto-start, and project actions tabs
This commit is contained in:
1 parent
cf9fa61118
commit
62e36eb3b2
31 files changed
+1332
-489
No files matched your search
@@ -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
|
||||
|
||||
@@ -24,6 +24,13 @@ export interface PortDiscoveryDeps {
|
||||
readdir: (path: string) => Promise<string[]>
|
||||
readlink: (path: string) => Promise<string>
|
||||
runLsof: () => Promise<string>
|
||||
runLsofCwd: (pids: number[]) => Promise<string>
|
||||
}
|
||||
|
||||
interface LsofFieldRecord {
|
||||
pid: number | null
|
||||
command: string | null
|
||||
name: string
|
||||
}
|
||||
|
||||
const PROC_NET_FILES: ReadonlyArray<readonly [string, 4 | 6]> = [
|
||||
@@ -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<LsofFieldRecord> {
|
||||
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<number, string> {
|
||||
const cwds = new Map<number, string>()
|
||||
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<PreviewPortEntry[]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
return parseLsofListen(output)
|
||||
.filter((listener) => 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<number, string>()
|
||||
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<PreviewPortEntry[]> {
|
||||
@@ -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,
|
||||
}),
|
||||
),
|
||||
}
|
||||
@@ -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<PortDiscoveryDeps> =
|
||||
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')
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -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:-}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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: <TUNNEL-ID>
|
||||
credentials-file: /etc/cloudflared/<TUNNEL-ID>.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`.
|
||||
@@ -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...
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<number | null>(null)
|
||||
const activePathRef = useRef<string | null>(null)
|
||||
const requestIdRef = useRef(0)
|
||||
const contentRef = useRef<HTMLDivElement>(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)
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderPortChooser = () => {
|
||||
if (ports.length === 0) {
|
||||
return renderMessage(
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-foreground">No dev server is listening</p>
|
||||
<p>Start one in the Terminal or from Actions. It appears here automatically.</p>
|
||||
</div>,
|
||||
)
|
||||
}
|
||||
if (repoPorts.length === 0) {
|
||||
return renderMessage(
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-foreground">Select a port to preview</p>
|
||||
<p>{describeListeningPorts(ports.length)}. Choose one from the port menu above.</p>
|
||||
</div>,
|
||||
)
|
||||
}
|
||||
const otherPortCount = ports.length - repoPorts.length
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center p-6">
|
||||
<div className="w-full max-w-lg space-y-3">
|
||||
<h3 className="text-sm font-medium text-foreground">Dev servers in this repo</h3>
|
||||
<ul className="divide-y divide-border overflow-hidden rounded-md border border-border">
|
||||
{repoPorts.map((entry) => (
|
||||
<li key={entry.port}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectPort(entry.port)}
|
||||
aria-label={formatPortLabel(entry)}
|
||||
className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"
|
||||
>
|
||||
<span className="font-mono font-medium tabular-nums text-foreground">:{entry.port}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground">{entry.command}</span>
|
||||
{entry.cwd && (
|
||||
<span className="max-w-[45%] truncate text-xs text-muted-foreground" title={entry.cwd}>
|
||||
{shortenPath(entry.cwd)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{otherPortCount > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{describeListeningPorts(otherPortCount, 'other ')} elsewhere. Choose one from the port menu above.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
|
||||
<DialogContent
|
||||
ref={contentRef}
|
||||
mobileFullscreen
|
||||
hideCloseButton={isMobile}
|
||||
onOpenAutoFocus={(event) => {
|
||||
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)
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-center gap-2 border-b border-border px-3 py-2 flex-shrink-0">
|
||||
<input
|
||||
aria-label="Preview path"
|
||||
value={pathDraft}
|
||||
onChange={(event) => 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="/"
|
||||
<div className="flex flex-col gap-2 border-b border-border px-3 py-2 flex-shrink-0 sm:flex-row sm:items-center">
|
||||
<Combobox
|
||||
value={requestedPort ? String(requestedPort) : ''}
|
||||
onChange={handlePortChange}
|
||||
options={portOptions}
|
||||
placeholder="Select port"
|
||||
disabled={!enabled}
|
||||
allowCustomValue={false}
|
||||
ariaLabel="Preview port"
|
||||
onOpen={() => { void portsQuery.refetch() }}
|
||||
className="sm:w-72 sm:flex-shrink-0"
|
||||
/>
|
||||
<Button size="sm" variant="outline" onClick={handleGo} disabled={!requestedPort}>
|
||||
Go
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={reload}
|
||||
disabled={!requestedPort}
|
||||
aria-label="Reload preview"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleOpenInNewTab}
|
||||
disabled={!requestedPort}
|
||||
aria-label="Open preview in new tab"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{VIEWPORT_PRESETS.map(({ preset, label, icon: Icon }) => (
|
||||
<Button
|
||||
key={preset}
|
||||
size="sm"
|
||||
variant={viewport === preset ? 'secondary' : 'ghost'}
|
||||
onClick={() => setViewport(preset)}
|
||||
aria-label={label}
|
||||
aria-pressed={viewport === preset}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
</Button>
|
||||
))}
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<Input
|
||||
aria-label="Preview path"
|
||||
value={pathDraft}
|
||||
onChange={(event) => 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="/"
|
||||
/>
|
||||
<Button size="sm" variant="outline" onClick={handleGo} disabled={!requestedPort} className="h-9">
|
||||
Go
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={reload}
|
||||
disabled={!requestedPort}
|
||||
aria-label="Reload preview"
|
||||
className="h-9 w-9 p-0"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleOpenInNewTab}
|
||||
disabled={!requestedPort}
|
||||
aria-label="Open preview in new tab"
|
||||
className="h-9 w-9 p-0"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="ml-auto hidden items-center gap-1 sm:flex">
|
||||
{VIEWPORT_PRESETS.map(({ preset, label, icon: Icon }) => (
|
||||
<Button
|
||||
key={preset}
|
||||
size="sm"
|
||||
variant={viewport === preset ? 'secondary' : 'ghost'}
|
||||
onClick={() => setViewport(preset)}
|
||||
aria-label={label}
|
||||
aria-pressed={viewport === preset}
|
||||
className="h-9 w-9 p-0"
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{enabled && ports.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1 border-b border-border px-3 py-2 flex-shrink-0">
|
||||
{ports.map((entry) => (
|
||||
<button
|
||||
key={entry.port}
|
||||
type="button"
|
||||
onClick={() => selectPort(entry.port)}
|
||||
title={entry.cwd ?? undefined}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors',
|
||||
entry.port === requestedPort
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-border text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<span className="font-medium">:{entry.port}</span>
|
||||
{entry.command && <span className="truncate">{entry.command}</span>}
|
||||
{entry.inDirectory && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px]">this repo</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative flex-1 min-h-0">{body()}</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -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(<RepoActionsDialog repoId={1} directory="/repo" open={false} onOpenChange={vi.fn()} />)
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
|
||||
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(
|
||||
|
||||
@@ -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<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
formRef.current?.scrollIntoView({ block: 'nearest' })
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-name">Name</Label>
|
||||
<Input
|
||||
id="action-name"
|
||||
value={draft.name}
|
||||
onChange={(event) => onChange({ ...draft, name: event.target.value })}
|
||||
/>
|
||||
<div ref={formRef} className="space-y-3 bg-card p-3">
|
||||
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_9rem]">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-name">Name</Label>
|
||||
<Input
|
||||
id="action-name"
|
||||
value={draft.name}
|
||||
onChange={(event) => onChange({ ...draft, name: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-icon">Icon</Label>
|
||||
<Select
|
||||
value={draft.icon}
|
||||
onValueChange={(value) => onChange({ ...draft, icon: value as ProjectActionIcon })}
|
||||
>
|
||||
<SelectTrigger id="action-icon">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACTION_ICON_OPTIONS.map(({ value, label }) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-command">Command</Label>
|
||||
@@ -104,24 +133,6 @@ function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormP
|
||||
onChange={(event) => onChange({ ...draft, command: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-icon">Icon</Label>
|
||||
<Select
|
||||
value={draft.icon}
|
||||
onValueChange={(value) => onChange({ ...draft, icon: value as ProjectActionIcon })}
|
||||
>
|
||||
<SelectTrigger id="action-icon">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACTION_ICON_OPTIONS.map(({ value, label }) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="action-url">URL template</Label>
|
||||
<Input
|
||||
@@ -151,6 +162,35 @@ function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormP
|
||||
)
|
||||
}
|
||||
|
||||
type RepoFileExecutable = NonNullable<ProjectConfigResponse['repoFile']['executable']>
|
||||
|
||||
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 (
|
||||
<>
|
||||
<Icon className="mr-2 inline h-4 w-4 align-[-3px] text-muted-foreground" />
|
||||
{action.name}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ActionUrl({ url }: { url: string | undefined }) {
|
||||
if (!url) return null
|
||||
return <p className="mt-0.5 truncate text-xs text-muted-foreground">{url}</p>
|
||||
}
|
||||
|
||||
function TabCount({ count }: { count: number }) {
|
||||
return <span className="ml-1.5 text-xs tabular-nums text-muted-foreground">{count}</span>
|
||||
}
|
||||
|
||||
interface RepoActionsDialogProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
@@ -167,8 +207,11 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
|
||||
|
||||
const [draft, setDraft] = useState<ActionDraft | null>(null)
|
||||
const [setupCommands, setSetupCommands] = useState<string[]>([])
|
||||
const [focusSetupIndex, setFocusSetupIndex] = useState<number | null>(null)
|
||||
const [trustReview, setTrustReview] = useState<TrustReview | null>(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) => (
|
||||
<ActionForm
|
||||
key={current.id}
|
||||
draft={current}
|
||||
isSaving={updateActions.isPending}
|
||||
onChange={setDraft}
|
||||
onSave={handleSaveAction}
|
||||
onCancel={() => setDraft(null)}
|
||||
/>
|
||||
)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
className="sm:fixed sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:w-[520px] sm:max-w-[520px] sm:h-auto sm:max-h-[85vh] flex flex-col gap-0 pb-safe"
|
||||
>
|
||||
<DialogHeader className="px-4 sm:px-6 pt-4 sm:pt-6 pb-2 sm:pb-3 shrink-0">
|
||||
<DialogTitle>Project Actions</DialogTitle>
|
||||
<DialogDescription>Commands and setup steps for this location.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
className="flex flex-col gap-0 overflow-hidden p-0 pb-safe sm:h-auto sm:max-h-[85vh] sm:max-w-[560px] sm:p-0"
|
||||
>
|
||||
<DialogHeader className="shrink-0 border-b border-border px-4 py-4 sm:px-6">
|
||||
<DialogTitle>Project Actions</DialogTitle>
|
||||
<DialogDescription>Commands and setup steps for this location.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-4 sm:px-6 pb-4 sm:pb-6 space-y-6">
|
||||
{configQuery.isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
||||
</div>
|
||||
) : !config ? (
|
||||
<p className="text-sm text-destructive">
|
||||
<p className="px-4 py-4 text-sm text-destructive sm:px-6">
|
||||
{configQuery.error instanceof Error ? configQuery.error.message : 'No configuration available.'}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<section className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold">Actions</h3>
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => setDraft(emptyActionDraft())}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add action
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{personalActions.length === 0 && repoActions.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No actions configured.</p>
|
||||
)}
|
||||
|
||||
{personalActions.map((action) => {
|
||||
const Icon = actionIcon(action.icon)
|
||||
const isEditing = draft?.id === action.id
|
||||
return (
|
||||
<div key={action.id} className="rounded-lg border border-border bg-card p-3 space-y-2">
|
||||
{isEditing && draft ? (
|
||||
<ActionForm
|
||||
draft={draft}
|
||||
isSaving={updateActions.isPending}
|
||||
onChange={setDraft}
|
||||
onSave={handleSaveAction}
|
||||
onCancel={() => setDraft(null)}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium truncate">{action.name}</span>
|
||||
</div>
|
||||
<p className="font-mono text-xs text-muted-foreground truncate">{action.command}</p>
|
||||
{action.url && (
|
||||
<p className="text-xs text-muted-foreground truncate">{action.url}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setDraft(actionToDraft(action))}
|
||||
>
|
||||
<Pencil className="h-3 w-3 mr-1" />
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveAction(action, 'repo')}
|
||||
disabled={moveItem.isPending}
|
||||
>
|
||||
Move to repository
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleDeleteAction(action.id)}
|
||||
disabled={updateActions.isPending}
|
||||
>
|
||||
<Trash2 className="h-3 w-3 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{repoActions.map((action) => {
|
||||
const Icon = actionIcon(action.icon)
|
||||
return (
|
||||
<div key={action.id} className="rounded-lg border border-border bg-card p-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium truncate">{action.name}</span>
|
||||
<Badge variant="secondary">In repo</Badge>
|
||||
{hasRepoFileStatus && (
|
||||
<div className="shrink-0 space-y-2 px-4 pt-3 sm:px-6">
|
||||
{config.repoFile.error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{config.repoFile.error}
|
||||
</p>
|
||||
)}
|
||||
{config.repoFile.warnings.map((warning) => (
|
||||
<p key={warning} className="text-xs text-warning">
|
||||
{warning}
|
||||
</p>
|
||||
))}
|
||||
{needsTrust && (
|
||||
<div className="flex items-center gap-3 rounded-lg border border-warning/50 bg-warning/10 p-3">
|
||||
<ShieldAlert className="h-4 w-4 shrink-0 text-warning" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">Repository commands are not trusted</p>
|
||||
<p className="text-xs text-muted-foreground">They won't run until you review and trust them.</p>
|
||||
</div>
|
||||
<p className="font-mono text-xs text-muted-foreground truncate">{action.command}</p>
|
||||
{action.url && (
|
||||
<p className="text-xs text-muted-foreground truncate">{action.url}</p>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveAction(action, 'personal')}
|
||||
disabled={moveItem.isPending}
|
||||
>
|
||||
Move to my settings
|
||||
<Button type="button" size="sm" variant="outline" className="shrink-0" onClick={openTrustReview}>
|
||||
Review
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAddingAction && draft && (
|
||||
<div className="rounded-lg border border-border bg-card p-3">
|
||||
<ActionForm
|
||||
draft={draft}
|
||||
isSaving={updateActions.isPending}
|
||||
onChange={setDraft}
|
||||
onSave={handleSaveAction}
|
||||
onCancel={() => setDraft(null)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold">Worktree setup</h3>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Commands run after a new worktree is created. Use{' '}
|
||||
<code className="font-mono">$ROOT_PROJECT_PATH</code> to reference the main checkout.
|
||||
</p>
|
||||
<Tabs defaultValue="actions" className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="shrink-0 px-4 pt-3 sm:px-6">
|
||||
<TabsList className="w-full justify-start">
|
||||
<TabsTrigger value="actions">
|
||||
Actions
|
||||
<TabCount count={personalActions.length + repoActions.length} />
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="setup">
|
||||
Worktree setup
|
||||
<TabCount count={setupCommands.length + repoSetup.length} />
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
{setupCommands.length === 0 && repoSetup.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No setup commands.</p>
|
||||
)}
|
||||
|
||||
{setupCommands.map((command, index) => (
|
||||
<div key={index} className="rounded-lg border border-border bg-card p-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
aria-label={`Setup command ${index + 1}`}
|
||||
value={command}
|
||||
onChange={(event) =>
|
||||
setSetupCommands((current) =>
|
||||
current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label="Move up"
|
||||
disabled={index === 0}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index - 1))}
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label="Move down"
|
||||
disabled={index === setupCommands.length - 1}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index + 1))}
|
||||
>
|
||||
<ArrowDown className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
aria-label="Remove command"
|
||||
onClick={() => setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index))}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveSetup(command, 'repo')}
|
||||
disabled={setupDirty || moveItem.isPending}
|
||||
>
|
||||
Move to repository
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{repoSetup.map((item) => (
|
||||
<div
|
||||
key={item.command}
|
||||
className="flex items-center justify-between gap-2 rounded-lg border border-border bg-card p-3"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="font-mono text-xs truncate">{item.command}</span>
|
||||
<Badge variant="secondary">In repo</Badge>
|
||||
</div>
|
||||
<TabsContent value="actions" className="mt-0 flex min-h-0 flex-1 flex-col px-0">
|
||||
<div className="flex shrink-0 items-center justify-between gap-3 px-4 py-3 sm:px-6">
|
||||
<p className="text-xs text-muted-foreground">Start these from the actions menu in the header.</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => moveSetup(item.command, 'personal')}
|
||||
disabled={moveItem.isPending}
|
||||
className="shrink-0"
|
||||
onClick={() => setDraft(emptyActionDraft())}
|
||||
>
|
||||
Move to my settings
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add action
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 sm:px-6 sm:pb-6">
|
||||
<SettingsList
|
||||
isEmpty={personalActions.length === 0 && repoActions.length === 0 && !isAddingAction}
|
||||
emptyTitle="No actions configured"
|
||||
emptyHint="Add a command you run often, like a dev server or test watcher."
|
||||
maxHeightClassName="max-h-none"
|
||||
>
|
||||
{personalActions.map((action) =>
|
||||
draft?.id === action.id ? (
|
||||
renderActionForm(draft)
|
||||
) : (
|
||||
<SettingsListRow
|
||||
key={action.id}
|
||||
className={COMPACT_ROW_CLASS}
|
||||
title={<ActionTitle action={action} />}
|
||||
description={<span className="font-mono" title={action.command}>{action.command}</span>}
|
||||
belowDescription={<ActionUrl url={action.url} />}
|
||||
onClick={() => setDraft(actionToDraft(action))}
|
||||
trailing={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8"
|
||||
aria-label={`Edit ${action.name}`}
|
||||
onClick={() => setDraft(actionToDraft(action))}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
}
|
||||
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) => (
|
||||
<SettingsListRow
|
||||
key={`repo:${action.id}`}
|
||||
className={COMPACT_ROW_CLASS}
|
||||
title={<ActionTitle action={action} />}
|
||||
badges={<Badge variant="secondary" className="shrink-0">In repo</Badge>}
|
||||
description={<span className="font-mono" title={action.command}>{action.command}</span>}
|
||||
belowDescription={<ActionUrl url={action.url} />}
|
||||
actions={[
|
||||
{
|
||||
label: 'Move to my settings',
|
||||
onClick: () => moveAction(action, 'personal'),
|
||||
disabled: moveItem.isPending,
|
||||
},
|
||||
]}
|
||||
actionsLabel={`Actions for ${action.name}`}
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setSetupCommands((current) => [...current, ''])}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add command
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSaveSetup}
|
||||
disabled={setupCommands.some((command) => !command.trim()) || updateSetup.isPending}
|
||||
>
|
||||
Save setup
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-2">
|
||||
{config.repoFile.error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{config.repoFile.error}
|
||||
</p>
|
||||
)}
|
||||
{config.repoFile.warnings.map((warning) => (
|
||||
<p key={warning} className="text-xs text-warning">
|
||||
{warning}
|
||||
</p>
|
||||
))}
|
||||
{config.repoFile.exists &&
|
||||
!config.repoFile.trusted &&
|
||||
config.repoFile.hash &&
|
||||
config.repoFile.executable && (
|
||||
<div className="rounded-lg border border-warning/50 bg-warning/10 p-3 space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ShieldAlert className="h-4 w-4 text-warning" />
|
||||
Repository commands are not trusted
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This repository defines commands that run on your machine. Review and trust them to enable.
|
||||
</p>
|
||||
<TrustExecutableList executable={config.repoFile.executable} />
|
||||
<Button type="button" size="sm" onClick={handleTrust} disabled={trustConfig.isPending}>
|
||||
Trust these commands
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<TabsContent value="setup" className="mt-0 flex min-h-0 flex-1 flex-col px-0">
|
||||
<div className="flex shrink-0 items-center justify-between gap-3 px-4 py-3 sm:px-6">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Run in order after a new worktree is created.{' '}
|
||||
<code className="font-mono">$ROOT_PROJECT_PATH</code> points to the main checkout.
|
||||
</p>
|
||||
<Button type="button" size="sm" variant="outline" className="shrink-0" onClick={addSetupCommand}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add command
|
||||
</Button>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 sm:px-6">
|
||||
<SettingsList
|
||||
isEmpty={setupCommands.length === 0 && repoSetup.length === 0}
|
||||
emptyTitle="No setup commands"
|
||||
emptyHint="Add commands such as pnpm install to prepare new worktrees."
|
||||
maxHeightClassName="max-h-none"
|
||||
>
|
||||
{setupCommands.map((command, index) => (
|
||||
<div key={index} className="flex items-center gap-1 bg-card px-3 py-2">
|
||||
<Input
|
||||
aria-label={`Setup command ${index + 1}`}
|
||||
autoFocus={index === focusSetupIndex}
|
||||
value={command}
|
||||
className="mr-1 h-9 min-w-0 flex-1 font-mono md:text-xs"
|
||||
onChange={(event) =>
|
||||
setSetupCommands((current) =>
|
||||
current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 shrink-0"
|
||||
aria-label="Move up"
|
||||
disabled={index === 0}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index - 1))}
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 shrink-0"
|
||||
aria-label="Move down"
|
||||
disabled={index === setupCommands.length - 1}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index + 1))}
|
||||
>
|
||||
<ArrowDown className="h-4 w-4" />
|
||||
</Button>
|
||||
<SettingsListRowActionsMenu
|
||||
label={`Actions for setup command ${index + 1}`}
|
||||
actions={[
|
||||
{
|
||||
label: 'Move to repository',
|
||||
onClick: () => moveSetup(command, 'repo'),
|
||||
disabled: setupDirty || moveItem.isPending,
|
||||
},
|
||||
{
|
||||
label: 'Remove',
|
||||
destructive: true,
|
||||
separatorBefore: true,
|
||||
onClick: () =>
|
||||
setSetupCommands((current) => current.filter((_, itemIndex) => itemIndex !== index)),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{repoSetup.map((item) => (
|
||||
<SettingsListRow
|
||||
key={`repo:${item.command}`}
|
||||
className={COMPACT_ROW_CLASS}
|
||||
title={<span title={item.command}>{item.command}</span>}
|
||||
titleClassName="font-mono text-xs font-normal"
|
||||
badges={<Badge variant="secondary" className="shrink-0">In repo</Badge>}
|
||||
actions={[
|
||||
{
|
||||
label: 'Move to my settings',
|
||||
onClick: () => moveSetup(item.command, 'personal'),
|
||||
disabled: moveItem.isPending,
|
||||
},
|
||||
]}
|
||||
actionsLabel={`Actions for ${item.command}`}
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-4 py-3 sm:px-6">
|
||||
<p className="text-xs text-muted-foreground" aria-live="polite">
|
||||
{setupDirty ? 'Unsaved changes' : ''}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSaveSetup}
|
||||
disabled={!setupDirty || !setupValid || updateSetup.isPending}
|
||||
>
|
||||
Save setup
|
||||
</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDestructiveDialog
|
||||
open={open && trustReview !== null}
|
||||
onOpenChange={(next) => { 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 ? <TrustExecutableList executable={trustReview.executable} /> : undefined}
|
||||
confirmLabel="Trust these commands"
|
||||
pendingLabel="Trusting…"
|
||||
isPending={trustConfig.isPending}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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(
|
||||
<MemoryRouter initialEntries={['/repos/1?dialog=terminal']}>
|
||||
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={vi.fn()} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
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<typeof import('@/api/terminals')>('@/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<Response>((resolve) => { resolveList = resolve }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const panel = (isOpen: boolean) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/1?dialog=terminal&terminal=t2']}>
|
||||
<TerminalPanel repoId={1} directory="/repo" isOpen={isOpen} onClose={vi.fn()} />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
@@ -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<TerminalInfo | null>(null)
|
||||
const viewHandlesRef = useRef(new Map<string, TerminalViewHandle>())
|
||||
const autoCreatedDirectoryRef = useRef<string | null>(null)
|
||||
const autoCreateCheckedDirectoryRef = useRef<string | null>(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(
|
||||
|
||||
@@ -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(
|
||||
<div>
|
||||
<Combobox value="builtin" onChange={vi.fn()} options={options} allowCustomValue={false} ariaLabel="Provider" onOpen={onOpen} />
|
||||
<button type="button">Outside</button>
|
||||
</div>,
|
||||
)
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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<HTMLInputElement>(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<HTMLInputElement>) => {
|
||||
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',
|
||||
|
||||
@@ -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(
|
||||
<Dialog open onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogTitle>Test Dialog</DialogTitle>
|
||||
<Combobox value="" onChange={vi.fn()} options={[{ value: "a", label: "Alpha" }]} ariaLabel="Choice" />
|
||||
</DialogContent>
|
||||
</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(
|
||||
<Dialog open>
|
||||
|
||||
@@ -77,7 +77,7 @@ interface DialogContentProps
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
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 && (
|
||||
|
||||
@@ -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 (
|
||||
<span
|
||||
|
||||
@@ -94,6 +94,38 @@ export function SettingsList({
|
||||
)
|
||||
}
|
||||
|
||||
interface SettingsListRowActionsMenuProps {
|
||||
actions: SettingsListRowAction[]
|
||||
label?: string
|
||||
}
|
||||
|
||||
export function SettingsListRowActionsMenu({ actions, label }: SettingsListRowActionsMenuProps) {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 [[data-opencode-settings]_&]:max-sm:h-11 [[data-opencode-settings]_&]:max-sm:w-11" aria-label={label}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{actions.map((action, i) => (
|
||||
<Fragment key={action.label}>
|
||||
{action.separatorBefore && i > 0 && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem
|
||||
disabled={action.disabled}
|
||||
onSelect={() => setTimeout(action.onClick, 0)}
|
||||
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
|
||||
>
|
||||
{action.icon}
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
</Fragment>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function SettingsListRow({
|
||||
title,
|
||||
titleClassName,
|
||||
@@ -136,7 +168,7 @@ export function SettingsListRow({
|
||||
{belowDescription}
|
||||
</div>
|
||||
<div
|
||||
className="flex w-full shrink-0 items-center justify-end gap-1 sm:w-auto sm:justify-start [[data-opencode-settings]_&]:w-auto"
|
||||
className="flex shrink-0 items-center justify-end gap-1 sm:justify-start"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{trailing}
|
||||
@@ -151,28 +183,7 @@ export function SettingsListRow({
|
||||
</Button>
|
||||
)}
|
||||
{overflowActions && overflowActions.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 [[data-opencode-settings]_&]:max-sm:h-11 [[data-opencode-settings]_&]:max-sm:w-11" aria-label={actionsLabel}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{overflowActions.map((action, i) => (
|
||||
<Fragment key={action.label}>
|
||||
{action.separatorBefore && i > 0 && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem
|
||||
disabled={action.disabled}
|
||||
onSelect={() => setTimeout(action.onClick, 0)}
|
||||
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
|
||||
>
|
||||
{action.icon}
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
</Fragment>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<SettingsListRowActionsMenu actions={overflowActions} label={actionsLabel} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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<string, string>,
|
||||
@@ -10,7 +17,7 @@ export function useOpenTerminal(): (
|
||||
|
||||
return useCallback(
|
||||
(terminalId: string, extraParams?: Record<string, string>) => {
|
||||
openDialogParam(updateParams, 'terminal', { terminal: terminalId, ...extraParams })
|
||||
openDialogParam(updateParams, TERMINAL_DIALOG, { terminal: terminalId, ...extraParams })
|
||||
},
|
||||
[updateParams],
|
||||
)
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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')
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user