Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

chore: updating docker

Luigi Agostif9903f033aae
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 6581724f..12ffc8f7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -122,11 +122,8 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
+ packages: read
steps:
- - uses: actions/checkout@v4
- with:
- ref: ${{ github.event.inputs.tag || github.ref }}
-
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
@@ -134,19 +131,23 @@ jobs:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
+ - uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
- name: Extract version
id: version
run: |
TAG="${{ github.event.inputs.tag || github.ref_name }}"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
+ echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
- - uses: docker/build-push-action@v6
- with:
- context: .
- push: true
- platforms: linux/amd64,linux/arm64
- tags: |
- pinchtab/pinchtab:latest
- pinchtab/pinchtab:${{ steps.version.outputs.tag }}
- cache-from: type=gha
- cache-to: type=gha,mode=max
+ - name: Mirror pinned release image to Docker Hub
+ run: |
+ docker buildx imagetools create \
+ --tag pinchtab/pinchtab:latest \
+ --tag pinchtab/pinchtab:${{ steps.version.outputs.tag }} \
+ --tag pinchtab/pinchtab:${{ steps.version.outputs.version }} \
+ ghcr.io/pinchtab/pinchtab:${{ steps.version.outputs.version }}
diff --git a/Dockerfile b/Dockerfile
index eb86e978..525c4809 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -33,23 +33,22 @@ RUN apk add --no-cache \
ttf-freefont \
dumb-init
-# Create non-root user and state directory
-RUN adduser -D -g '' pinchtab && \
+# Create non-root user and persistent config/state directory
+RUN adduser -D -h /data -g '' pinchtab && \
mkdir -p /data && \
chown pinchtab:pinchtab /data
# Copy binary from builder
COPY --from=builder /build/pinchtab /usr/local/bin/pinchtab
+COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
# Switch to non-root user
USER pinchtab
WORKDIR /data
# Environment variables
-ENV PINCHTAB_BIND=0.0.0.0 \
- PINCHTAB_PORT=9867 \
- CHROME_BINARY=/usr/bin/chromium-browser \
- CHROME_FLAGS="--no-sandbox --disable-gpu"
+ENV HOME=/data \
+ XDG_CONFIG_HOME=/data/.config
# Expose port
EXPOSE 9867
@@ -58,4 +57,4 @@ EXPOSE 9867
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
# Run pinchtab
-CMD ["pinchtab"]
\ No newline at end of file
+CMD ["/usr/local/bin/docker-entrypoint.sh", "pinchtab"]
diff --git a/Dockerfile.goreleaser b/Dockerfile.goreleaser
index baa45eb3..e64d11f7 100644
--- a/Dockerfile.goreleaser
+++ b/Dockerfile.goreleaser
@@ -1,4 +1,4 @@
-FROM alpine:latest
+FROM alpine:3.21
LABEL org.opencontainers.image.source="https://github.com/pinchtab/pinchtab"
LABEL org.opencontainers.image.description="Browser control for AI agents"
@@ -17,19 +17,15 @@ RUN adduser -D -g '' pinchtab && \
chown pinchtab:pinchtab /data
COPY pinchtab /usr/local/bin/pinchtab
+COPY --chmod=0755 docker-entrypoint-release.sh /usr/local/bin/docker-entrypoint-release.sh
USER pinchtab
WORKDIR /data
-ENV PINCHTAB_BIND=0.0.0.0 \
- PINCHTAB_PORT=9867 \
- PINCHTAB_HEADLESS=true \
- PINCHTAB_STATE_DIR=/data \
- PINCHTAB_PROFILE_DIR=/data/chrome-profile \
- CHROME_BINARY=/usr/bin/chromium-browser \
- CHROME_FLAGS="--no-sandbox --disable-gpu"
+ENV HOME=/data \
+ XDG_CONFIG_HOME=/data/.config
EXPOSE 9867
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
-CMD ["pinchtab"]
+CMD ["/usr/local/bin/docker-entrypoint-release.sh", "pinchtab"]
diff --git a/README.md b/README.md
index 40e3c3d8..0a67c452 100644
--- a/README.md
+++ b/README.md
@@ -87,7 +87,26 @@ npm install -g pinchtab
**Docker:**
```bash
-docker run -d -p 9867:9867 pinchtab/pinchtab
+docker run -d \
+ --name pinchtab \
+ -p 127.0.0.1:9867:9867 \
+ -v pinchtab-data:/data \
+ --shm-size=2g \
+ pinchtab/pinchtab
+```
+
+The bundled container persists its managed config at `/data/.config/pinchtab/config.json`.
+If you want to supply your own config file instead, mount it and point `PINCHTAB_CONFIG` at it:
+
+```bash
+docker run -d \
+ --name pinchtab \
+ -p 127.0.0.1:9867:9867 \
+ -e PINCHTAB_CONFIG=/config/config.json \
+ -v "$PWD/config.json:/config/config.json:ro" \
+ -v pinchtab-data:/data \
+ --shm-size=2g \
+ pinchtab/pinchtab
```
### Use It
diff --git a/RELEASE.md b/RELEASE.md
index 395c4c57..22b2677f 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -148,7 +148,8 @@ Depends on: `release` job (waits for goreleaser to finish)
### 3. Docker
-Independent job. Pushes to Docker Hub if configured.
+Goreleaser builds the pinned release image from `Dockerfile.goreleaser` and publishes it to GHCR.
+The Docker Hub job then mirrors that exact multi-arch manifest to Docker Hub, so the public release image does not rebuild from the floating development Dockerfile.
## Troubleshooting
diff --git a/docker-compose.yml b/docker-compose.yml
index 5e0abe87..95b60ba8 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -3,22 +3,22 @@ services:
build: .
container_name: pinchtab
ports:
- - "9867:9867"
+ - "127.0.0.1:9867:9867"
volumes:
- pinchtab-data:/data
environment:
- - PINCHTAB_BIND=0.0.0.0
- - PINCHTAB_PORT=9867
- - PINCHTAB_HEADLESS=true
- - PINCHTAB_TOKEN=${PINCHTAB_TOKEN:-}
- - PINCHTAB_STATE_DIR=/data
- - PINCHTAB_PROFILE_DIR=/data/chrome-profile
+ PINCHTAB_TOKEN: ${PINCHTAB_TOKEN:-}
restart: unless-stopped
# Shared memory is critical for Chrome stability
shm_size: "2gb"
- # Required for Chrome to work in container
+ read_only: true
+ tmpfs:
+ - /tmp:size=512m,noexec,nosuid,nodev
+ - /run:size=64m,noexec,nosuid,nodev
security_opt:
- - seccomp:unconfined
+ - no-new-privileges:true
+ cap_drop:
+ - ALL
# Limit resources
mem_limit: 2g
cpus: "2.0"
diff --git a/docker-entrypoint-release.sh b/docker-entrypoint-release.sh
new file mode 100644
index 00000000..bd3a7f0f
--- /dev/null
+++ b/docker-entrypoint-release.sh
@@ -0,0 +1,31 @@
+#!/bin/sh
+set -eu
+
+home_dir="${HOME:-/data}"
+xdg_config_home="${XDG_CONFIG_HOME:-$home_dir/.config}"
+default_config_path="$xdg_config_home/pinchtab/config.json"
+
+mkdir -p "$home_dir" "$xdg_config_home" "$(dirname "$default_config_path")"
+
+if [ -z "${PINCHTAB_CONFIG:-}" ] && [ ! -f "$default_config_path" ]; then
+ /usr/local/bin/pinchtab config init >/dev/null
+ if [ -n "${PINCHTAB_TOKEN:-}" ]; then
+ /usr/local/bin/pinchtab config set server.token "$PINCHTAB_TOKEN" >/dev/null
+ fi
+fi
+
+# Docker port publishing needs a non-loopback bind inside the container, but
+# keep the persisted config on its secure local default unless the user
+# explicitly overrides it.
+if [ -z "${PINCHTAB_CONFIG:-}" ] && [ -z "${PINCHTAB_BIND:-}" ]; then
+ export PINCHTAB_BIND=0.0.0.0
+fi
+
+if [ -z "${PINCHTAB_CONFIG:-}" ] && [ -f "$default_config_path" ]; then
+ current_flags="$(/usr/local/bin/pinchtab config get browser.extraFlags 2>/dev/null || true)"
+ if [ -z "$current_flags" ]; then
+ /usr/local/bin/pinchtab config set browser.extraFlags "--no-sandbox --disable-gpu" >/dev/null
+ fi
+fi
+
+exec "$@"
diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh
new file mode 100644
index 00000000..80c6897c
--- /dev/null
+++ b/docker-entrypoint.sh
@@ -0,0 +1,25 @@
+#!/bin/sh
+set -eu
+
+home_dir="${HOME:-/data}"
+xdg_config_home="${XDG_CONFIG_HOME:-$home_dir/.config}"
+default_config_path="$xdg_config_home/pinchtab/config.json"
+
+mkdir -p "$home_dir" "$xdg_config_home" "$(dirname "$default_config_path")"
+
+# Generate a persisted config on first boot.
+if [ -z "${PINCHTAB_CONFIG:-}" ] && [ ! -f "$default_config_path" ]; then
+ /usr/local/bin/pinchtab config init >/dev/null
+ if [ -n "${PINCHTAB_TOKEN:-}" ]; then
+ /usr/local/bin/pinchtab config set server.token "$PINCHTAB_TOKEN" >/dev/null
+ fi
+fi
+
+# Docker port publishing needs a non-loopback bind inside the container, but
+# keep the persisted config on its secure local default unless the user
+# explicitly overrides it.
+if [ -z "${PINCHTAB_CONFIG:-}" ] && [ -z "${PINCHTAB_BIND:-}" ]; then
+ export PINCHTAB_BIND=0.0.0.0
+fi
+
+exec "$@"
diff --git a/docs/guides/docker.md b/docs/guides/docker.md
index a1feaca3..9e1c54e4 100644
--- a/docs/guides/docker.md
+++ b/docs/guides/docker.md
@@ -1,6 +1,8 @@
# Docker Deployment
-PinchTab can run in Docker with a mounted data volume for config, profiles, and state. The safest way to configure the current implementation is to mount a `config.json` file and point `PINCHTAB_CONFIG` at it.
+PinchTab can run in Docker with a mounted data volume for config, profiles, and state.
+The bundled image now manages its default config under `/data/.config/pinchtab/config.json`.
+If you want full control over the config file path, you can still mount your own file and point `PINCHTAB_CONFIG` at it.
## Quick Start
@@ -10,7 +12,31 @@ Build the image from this repository:
docker build -t pinchtab .
```
-Create a local data directory with config:
+Run the container with a persistent data volume:
+
+```bash
+docker run -d \
+ --name pinchtab \
+ -p 127.0.0.1:9867:9867 \
+ -v pinchtab-data:/data \
+ --shm-size=2g \
+ pinchtab
+```
+
+On first boot, the image creates `/data/.config/pinchtab/config.json` and generates a token if needed. When you use the managed-config path, the container binds to `0.0.0.0` at runtime via `PINCHTAB_BIND`, but the persisted config remains on the normal loopback default unless you override it yourself.
+
+If you inspect the startup security summary from inside Docker, the loopback bind check will still report the effective runtime bind as non-loopback. That is expected: the process is listening on `0.0.0.0` inside the container so Docker port publishing can forward traffic to it.
+
+This does not automatically mean the service is exposed beyond your machine. Host exposure still depends on how you publish the container port. For example:
+
+- `-p 127.0.0.1:9867:9867` keeps the service reachable only from the host machine
+- `-p 9867:9867` exposes it on the host's network interfaces
+
+Treat the Docker runtime bind and the host-published address as separate layers. If you expose PinchTab beyond localhost, keep an auth token set and put it behind TLS or a trusted reverse proxy.
+
+## Supplying Your Own `config.json`
+
+If you want to manage the config file yourself, mount it and point `PINCHTAB_CONFIG` at it:
```text
docker-data/
@@ -37,16 +63,16 @@ Example `docker-data/config.json`:
}
```
-Run the container:
+Run with an explicit config file:
```bash
docker run -d \
--name pinchtab \
- -p 9867:9867 \
+ -p 127.0.0.1:9867:9867 \
+ -e PINCHTAB_CONFIG=/config/config.json \
-v "$PWD/docker-data:/data" \
- -e PINCHTAB_CONFIG=/data/config.json \
+ -v "$PWD/docker-data/config.json:/config/config.json:ro" \
--shm-size=2g \
- --security-opt seccomp=unconfined \
pinchtab
```
@@ -61,7 +87,7 @@ curl http://localhost:9867/instances
If you want data to survive container restarts, persist:
-- the config file
+- the managed config directory or your mounted config file
- the profile directory
- the state directory
@@ -79,15 +105,17 @@ For current runtime overrides, rely on:
Everything else should go in `config.json`.
-In the bundled image, you usually do not need to set `CHROME_BIN` manually unless you are replacing the browser binary.
+In the bundled image, you usually do not need to set `PINCHTAB_BIND`, `PINCHTAB_PORT`, or `CHROME_BIN` manually unless you are overriding the generated config or replacing the browser binary. The managed-config entrypoint supplies `PINCHTAB_BIND=0.0.0.0` at runtime so Docker port publishing works without broadening the persisted config.
## Compose
-The repository includes a `docker-compose.yml`, but the stable configuration pattern is still:
+The repository includes a `docker-compose.yml` that follows the managed-config pattern:
+
+1. mount a persistent `/data` volume
+2. let the entrypoint create and maintain `/data/.config/pinchtab/config.json`
+3. optionally pass `PINCHTAB_TOKEN`
-1. mount a persistent data directory
-2. point `PINCHTAB_CONFIG` at `/data/config.json`
-3. keep behavior settings in that file
+If you prefer a fully user-managed config file, mount it separately and set `PINCHTAB_CONFIG`.
If you expose PinchTab beyond localhost, set an auth token and put it behind TLS or a trusted reverse proxy.
@@ -96,7 +124,6 @@ If you expose PinchTab beyond localhost, set an auth token and put it behind TLS
Chrome in containers usually needs:
- larger shared memory, such as `--shm-size=2g`
-- a relaxed seccomp profile such as `seccomp=unconfined`
- enough RAM for your tab count and workload
For heavier scraping or testing workloads, also consider:
diff --git a/docs/implementations/docker-local-testing.md b/docs/implementations/docker-local-testing.md
new file mode 100644
index 00000000..93330f65
--- /dev/null
+++ b/docs/implementations/docker-local-testing.md
@@ -0,0 +1,130 @@
+# Docker Local Testing
+
+This page is a practical checklist for testing the current Docker setup locally.
+
+It covers two paths:
+
+- the default managed-config flow, where the container owns `/data/.config/pinchtab/config.json`
+- the explicit-config flow, where you mount your own `config.json` and set `PINCHTAB_CONFIG`
+
+## Managed Config Flow
+
+Build and start the local Compose service:
+
+```bash
+docker compose up --build -d
+docker compose logs -f pinchtab
+```
+
+Inspect the effective config path and persisted config:
+
+```bash
+docker exec pinchtab pinchtab config path
+docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
+```
+
+Expected results:
+
+- the config path is `/data/.config/pinchtab/config.json`
+- `server.bind` in the persisted config remains `127.0.0.1`
+- a token is present if one was generated on first boot or passed in
+
+Verify the effective runtime bind separately:
+
+```bash
+docker exec pinchtab sh -lc 'echo "$PINCHTAB_BIND"'
+```
+
+Expected result:
+
+- `PINCHTAB_BIND` is `0.0.0.0` unless you overrode it explicitly
+
+Verify persistence across restart:
+
+```bash
+docker compose down
+docker compose up -d
+docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
+```
+
+## Explicit `PINCHTAB_CONFIG` Flow
+
+Create a local config file, for example `./tmp/config.json`:
+
+```json
+{
+ "server": {
+ "bind": "0.0.0.0",
+ "port": "9867",
+ "token": "local-test-token"
+ },
+ "browser": {
+ "extraFlags": "--no-sandbox --disable-gpu"
+ }
+}
+```
+
+Run the container with that config mounted read-only:
+
+```bash
+docker run --rm -d \
+ --name pinchtab-test \
+ -p 127.0.0.1:9867:9867 \
+ -e PINCHTAB_CONFIG=/config/config.json \
+ -v "$PWD/tmp/config.json:/config/config.json:ro" \
+ -v pinchtab-data:/data \
+ --shm-size=2g \
+ pinchtab/pinchtab
+```
+
+Verify the explicit config path and auth:
+
+```bash
+docker exec pinchtab-test pinchtab config path
+docker exec pinchtab-test sh -lc 'cat /config/config.json'
+curl -H 'Authorization: Bearer local-test-token' http://127.0.0.1:9867/health
+```
+
+Expected results:
+
+- `pinchtab config path` reports `/config/config.json`
+- the mounted file is used as-is
+- the container entrypoint does not rewrite the custom config
+
+## What To Check When Something Fails
+
+Container logs:
+
+```bash
+docker logs pinchtab
+docker logs pinchtab-test
+```
+
+Config path:
+
+```bash
+docker exec pinchtab pinchtab config path
+docker exec pinchtab-test pinchtab config path
+```
+
+Persisted config content:
+
+```bash
+docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
+```
+
+## Current Caveat
+
+The development Docker path may still need explicit Chrome flags on some hosts.
+
+If Chromium fails to launch in the local development image, add:
+
+```json
+{
+ "browser": {
+ "extraFlags": "--no-sandbox --disable-gpu"
+ }
+}
+```
+
+The release image path backfills those flags into the managed config automatically.
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index 0dcbbc9f..55cdc9c3 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log/slog"
"math/rand"
"net"
@@ -193,6 +194,10 @@ func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelF
// times out we fall back to launching Chrome directly via os/exec and connecting
// with a RemoteAllocator (requires debugPort > 0).
func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int) (context.Context, context.CancelFunc, error) {
+ return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, false)
+}
+
+func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int, retriedProfileLock bool) (context.Context, context.CancelFunc, error) {
slog.Debug("creating chrome allocator")
// Create allocator context (inner, wraps parentCtx)
@@ -249,6 +254,17 @@ func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, opts []ch
errMsg := err.Error()
+ if !retriedProfileLock && isChromeProfileLockError(errMsg) {
+ recovered, recoverErr := clearStaleChromeProfileLock(cfg.ProfileDir, errMsg)
+ if recoverErr != nil {
+ slog.Warn("failed to recover chrome profile lock", "profile", cfg.ProfileDir, "err", recoverErr)
+ } else if recovered {
+ slog.Warn("cleared stale chrome profile lock; retrying chrome startup", "profile", cfg.ProfileDir)
+ time.Sleep(250 * time.Millisecond)
+ return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, true)
+ }
+ }
+
// Chrome binary not found — report clearly and stop.
if strings.Contains(errMsg, "executable file not found") ||
strings.Contains(errMsg, "no such file or directory") {
@@ -337,6 +353,8 @@ func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.Runti
// #nosec G204 -- chromeBinary from CHROME_BIN env var, user config, or findChromeBinary() known system paths
cmd := exec.Command(chromeBinary, args...)
+ cmd.Stdout = newPrefixedLogWriter(os.Stdout, "chrome stdout")
+ cmd.Stderr = newPrefixedLogWriter(os.Stderr, "chrome stderr")
if err := cmd.Start(); err != nil {
return nil, nil, fmt.Errorf("failed to start chrome directly: %w", err)
}
@@ -512,3 +530,51 @@ func randomWindowSize() (int, int) {
s := sizes[rand.Intn(len(sizes))]
return s[0], s[1]
}
+
+type prefixedLogWriter struct {
+ dst io.Writer
+ prefix string
+ buf []byte
+}
+
+func newPrefixedLogWriter(dst io.Writer, prefix string) *prefixedLogWriter {
+ return &prefixedLogWriter{
+ dst: dst,
+ prefix: prefix,
+ buf: make([]byte, 0, 1024),
+ }
+}
+
+func (w *prefixedLogWriter) Write(p []byte) (int, error) {
+ w.buf = append(w.buf, p...)
+ for {
+ idx := bytesIndexByte(w.buf, '\n')
+ if idx < 0 {
+ break
+ }
+ line := w.buf[:idx]
+ w.buf = w.buf[idx+1:]
+ if err := w.writeLine(line); err != nil {
+ return 0, err
+ }
+ }
+ return len(p), nil
+}
+
+func (w *prefixedLogWriter) writeLine(line []byte) error {
+ text := string(line)
+ if text == "" {
+ return nil
+ }
+ _, err := fmt.Fprintf(w.dst, "%s: %s\n", w.prefix, text)
+ return err
+}
+
+func bytesIndexByte(b []byte, c byte) int {
+ for i, v := range b {
+ if v == c {
+ return i
+ }
+ }
+ return -1
+}
diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.go
new file mode 100644
index 00000000..6da6085d
--- /dev/null
+++ b/internal/bridge/profile_lock.go
@@ -0,0 +1,149 @@
+package bridge
+
+import (
+ "bytes"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+var chromeProfileProcessLister = findChromeProfileProcesses
+var chromePIDIsRunning = isChromePIDRunning
+
+var chromeSingletonFiles = []string{
+ "SingletonLock",
+ "SingletonSocket",
+ "SingletonCookie",
+}
+
+var chromeProfileLockPIDPattern = regexp.MustCompile(`(?:Chromium|Chrome) process \((\d+)\)`)
+
+type chromeProfileProcess struct {
+ PID string
+ Command string
+}
+
+func isChromeProfileLockError(msg string) bool {
+ if msg == "" {
+ return false
+ }
+ return strings.Contains(msg, "The profile appears to be in use by another Chromium process") ||
+ strings.Contains(msg, "The profile appears to be in use by another Chrome process") ||
+ strings.Contains(msg, "process_singleton")
+}
+
+func clearStaleChromeProfileLock(profileDir, errMsg string) (bool, error) {
+ if strings.TrimSpace(profileDir) == "" {
+ return false, nil
+ }
+
+ if pid, ok := extractChromeProfileLockPID(errMsg); ok {
+ running, err := chromePIDIsRunning(pid)
+ if err != nil {
+ slog.Warn("failed to probe chrome lock pid; falling back to process listing", "profile", profileDir, "pid", pid, "err", err)
+ } else if running {
+ slog.Warn("chrome profile lock appears active; leaving singleton files in place", "profile", profileDir, "pid", pid)
+ return false, nil
+ }
+ }
+
+ processes, err := chromeProfileProcessLister(profileDir)
+ if err != nil {
+ if _, ok := extractChromeProfileLockPID(errMsg); ok {
+ slog.Warn("profile process listing unavailable; proceeding with stale lock cleanup based on lock pid", "profile", profileDir, "err", err)
+ } else {
+ return false, err
+ }
+ }
+ if len(processes) > 0 {
+ pids := make([]string, 0, len(processes))
+ for _, proc := range processes {
+ pids = append(pids, proc.PID)
+ }
+ slog.Warn("chrome profile lock appears active; leaving singleton files in place", "profile", profileDir, "pids", strings.Join(pids, ","))
+ return false, nil
+ }
+
+ removed := false
+ for _, name := range chromeSingletonFiles {
+ path := filepath.Join(profileDir, name)
+ if _, err := os.Lstat(path); err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return false, fmt.Errorf("inspect %s: %w", path, err)
+ }
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ return removed, fmt.Errorf("remove %s: %w", path, err)
+ }
+ removed = true
+ }
+
+ return removed, nil
+}
+
+func extractChromeProfileLockPID(msg string) (int, bool) {
+ if msg == "" {
+ return 0, false
+ }
+ match := chromeProfileLockPIDPattern.FindStringSubmatch(msg)
+ if len(match) != 2 {
+ return 0, false
+ }
+ pid := 0
+ for _, ch := range match[1] {
+ pid = pid*10 + int(ch-'0')
+ }
+ if pid <= 0 {
+ return 0, false
+ }
+ return pid, true
+}
+
+func findChromeProfileProcesses(profileDir string) ([]chromeProfileProcess, error) {
+ if strings.TrimSpace(profileDir) == "" {
+ return nil, nil
+ }
+
+ cmd := exec.Command("ps", "-axo", "pid=,args=")
+ out, err := cmd.Output()
+ if err != nil {
+ return nil, fmt.Errorf("list chrome processes: %w", err)
+ }
+
+ return parseChromeProfileProcesses(out, profileDir), nil
+}
+
+func parseChromeProfileProcesses(out []byte, profileDir string) []chromeProfileProcess {
+ if len(out) == 0 || strings.TrimSpace(profileDir) == "" {
+ return nil
+ }
+
+ needleEquals := "--user-data-dir=" + profileDir
+ needleSpace := "--user-data-dir " + profileDir
+ lines := bytes.Split(out, []byte{'\n'})
+ processes := make([]chromeProfileProcess, 0)
+
+ for _, rawLine := range lines {
+ line := strings.TrimSpace(string(rawLine))
+ if line == "" || (!strings.Contains(line, needleEquals) && !strings.Contains(line, needleSpace)) {
+ continue
+ }
+
+ fields := strings.Fields(line)
+ if len(fields) < 2 {
+ continue
+ }
+
+ processes = append(processes, chromeProfileProcess{
+ PID: fields[0],
+ Command: strings.TrimSpace(strings.TrimPrefix(line, fields[0])),
+ })
+ }
+
+ return processes
+}
diff --git a/internal/bridge/profile_lock_pid_other.go b/internal/bridge/profile_lock_pid_other.go
new file mode 100644
index 00000000..96922891
--- /dev/null
+++ b/internal/bridge/profile_lock_pid_other.go
@@ -0,0 +1,25 @@
+//go:build !windows
+
+package bridge
+
+import (
+ "errors"
+ "syscall"
+)
+
+func isChromePIDRunning(pid int) (bool, error) {
+ if pid <= 0 {
+ return false, nil
+ }
+ err := syscall.Kill(pid, syscall.Signal(0))
+ if err == nil {
+ return true, nil
+ }
+ if errors.Is(err, syscall.ESRCH) {
+ return false, nil
+ }
+ if errors.Is(err, syscall.EPERM) {
+ return true, nil
+ }
+ return false, err
+}
diff --git a/internal/bridge/profile_lock_pid_windows.go b/internal/bridge/profile_lock_pid_windows.go
new file mode 100644
index 00000000..fe4ae15c
--- /dev/null
+++ b/internal/bridge/profile_lock_pid_windows.go
@@ -0,0 +1,8 @@
+//go:build windows
+
+package bridge
+
+func isChromePIDRunning(pid int) (bool, error) {
+ _ = pid
+ return false, nil
+}
diff --git a/internal/bridge/profile_lock_test.go b/internal/bridge/profile_lock_test.go
new file mode 100644
index 00000000..a62df91a
--- /dev/null
+++ b/internal/bridge/profile_lock_test.go
@@ -0,0 +1,152 @@
+package bridge
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+func TestIsChromeProfileLockError(t *testing.T) {
+ t.Parallel()
+
+ msg := "chrome failed to start: [2046:2046:0309/221021.856597:ERROR:chrome/browser/process_singleton_posix.cc:363] The profile appears to be in use by another Chromium process"
+ if !isChromeProfileLockError(msg) {
+ t.Fatal("expected profile lock error to be detected")
+ }
+}
+
+func TestParseChromeProfileProcesses(t *testing.T) {
+ t.Parallel()
+
+ profileDir := "/data/.config/pinchtab/profiles/default"
+ out := []byte(" 36 /usr/bin/chromium-browser --user-data-dir=/data/.config/pinchtab/profiles/default --remote-debugging-port=9222\n 99 /usr/bin/chromium-browser --user-data-dir=/tmp/other\n")
+
+ got := parseChromeProfileProcesses(out, profileDir)
+ want := []chromeProfileProcess{
+ {
+ PID: "36",
+ Command: "/usr/bin/chromium-browser --user-data-dir=/data/.config/pinchtab/profiles/default --remote-debugging-port=9222",
+ },
+ }
+
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("parseChromeProfileProcesses() = %#v, want %#v", got, want)
+ }
+}
+
+func TestExtractChromeProfileLockPID(t *testing.T) {
+ t.Parallel()
+
+ msg := "The profile appears to be in use by another Chromium process (36) on another computer"
+ pid, ok := extractChromeProfileLockPID(msg)
+ if !ok {
+ t.Fatal("expected pid to be parsed from profile lock error")
+ }
+ if pid != 36 {
+ t.Fatalf("extractChromeProfileLockPID() = %d, want 36", pid)
+ }
+}
+
+func TestClearStaleChromeProfileLockRemovesSingletonFiles(t *testing.T) {
+ profileDir := t.TempDir()
+ for _, name := range chromeSingletonFiles {
+ if err := os.WriteFile(filepath.Join(profileDir, name), []byte("x"), 0644); err != nil {
+ t.Fatalf("write %s: %v", name, err)
+ }
+ }
+
+ orig := chromeProfileProcessLister
+ origPID := chromePIDIsRunning
+ chromeProfileProcessLister = func(string) ([]chromeProfileProcess, error) {
+ return nil, nil
+ }
+ chromePIDIsRunning = func(int) (bool, error) {
+ return false, nil
+ }
+ t.Cleanup(func() {
+ chromeProfileProcessLister = orig
+ chromePIDIsRunning = origPID
+ })
+
+ removed, err := clearStaleChromeProfileLock(profileDir, "")
+ if err != nil {
+ t.Fatalf("clearStaleChromeProfileLock() error = %v", err)
+ }
+ if !removed {
+ t.Fatal("expected singleton files to be removed")
+ }
+
+ for _, name := range chromeSingletonFiles {
+ if _, err := os.Lstat(filepath.Join(profileDir, name)); !os.IsNotExist(err) {
+ t.Fatalf("expected %s to be removed, got err=%v", name, err)
+ }
+ }
+}
+
+func TestClearStaleChromeProfileLockLeavesActiveProfileUntouched(t *testing.T) {
+ profileDir := t.TempDir()
+ lockPath := filepath.Join(profileDir, chromeSingletonFiles[0])
+ if err := os.WriteFile(lockPath, []byte("x"), 0644); err != nil {
+ t.Fatalf("write lock file: %v", err)
+ }
+
+ orig := chromeProfileProcessLister
+ origPID := chromePIDIsRunning
+ chromeProfileProcessLister = func(string) ([]chromeProfileProcess, error) {
+ return []chromeProfileProcess{{PID: "36", Command: "/usr/bin/chromium-browser --user-data-dir=" + profileDir}}, nil
+ }
+ chromePIDIsRunning = func(int) (bool, error) {
+ return false, nil
+ }
+ t.Cleanup(func() {
+ chromeProfileProcessLister = orig
+ chromePIDIsRunning = origPID
+ })
+
+ removed, err := clearStaleChromeProfileLock(profileDir, "")
+ if err != nil {
+ t.Fatalf("clearStaleChromeProfileLock() error = %v", err)
+ }
+ if removed {
+ t.Fatal("expected active profile lock to remain in place")
+ }
+ if _, err := os.Lstat(lockPath); err != nil {
+ t.Fatalf("expected lock file to remain, got err=%v", err)
+ }
+}
+
+func TestClearStaleChromeProfileLockFallsBackToPIDProbe(t *testing.T) {
+ profileDir := t.TempDir()
+ lockPath := filepath.Join(profileDir, chromeSingletonFiles[0])
+ if err := os.WriteFile(lockPath, []byte("x"), 0644); err != nil {
+ t.Fatalf("write lock file: %v", err)
+ }
+
+ orig := chromeProfileProcessLister
+ origPID := chromePIDIsRunning
+ chromeProfileProcessLister = func(string) ([]chromeProfileProcess, error) {
+ return nil, os.ErrPermission
+ }
+ chromePIDIsRunning = func(pid int) (bool, error) {
+ if pid != 36 {
+ t.Fatalf("unexpected pid probe: got %d, want 36", pid)
+ }
+ return false, nil
+ }
+ t.Cleanup(func() {
+ chromeProfileProcessLister = orig
+ chromePIDIsRunning = origPID
+ })
+
+ removed, err := clearStaleChromeProfileLock(profileDir, "another Chromium process (36)")
+ if err != nil {
+ t.Fatalf("clearStaleChromeProfileLock() error = %v", err)
+ }
+ if !removed {
+ t.Fatal("expected singleton file to be removed after stale pid probe")
+ }
+ if _, err := os.Lstat(lockPath); !os.IsNotExist(err) {
+ t.Fatalf("expected lock file to be removed, got err=%v", err)
+ }
+}
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index c7a0ce2a..1bd0abd7 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -31,6 +31,7 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("POST /instances/{id}/start", o.handleStartByInstanceID)
mux.HandleFunc("POST /instances/{id}/stop", o.handleStopByInstanceID)
mux.HandleFunc("GET /instances/{id}/logs", o.handleLogsByID)
+ mux.HandleFunc("GET /instances/{id}/logs/stream", o.handleLogsStreamByID)
mux.HandleFunc("GET /instances/{id}/tabs", o.handleInstanceTabs)
mux.HandleFunc("POST /instances/{id}/tabs/open", o.handleInstanceTabOpen)
mux.HandleFunc("POST /instances/{id}/tab", o.proxyToInstance)
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index f83b7f0f..de252f5e 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -143,6 +143,74 @@ func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(logs))
}
+func (o *Orchestrator) handleLogsStreamByID(w http.ResponseWriter, r *http.Request) {
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "streaming not supported", http.StatusInternalServerError)
+ return
+ }
+
+ if err := http.NewResponseController(w).SetWriteDeadline(time.Time{}); err != nil {
+ http.Error(w, "streaming deadline unsupported", http.StatusInternalServerError)
+ return
+ }
+
+ id := r.PathValue("id")
+ initial, err := o.Logs(id)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+ w.Header().Set("X-Accel-Buffering", "no")
+
+ writeLogs := func(logs string) bool {
+ data, err := json.Marshal(map[string]string{"logs": logs})
+ if err != nil {
+ return false
+ }
+ if _, err := fmt.Fprintf(w, "event: log\ndata: %s\n\n", data); err != nil {
+ return false
+ }
+ flusher.Flush()
+ return true
+ }
+
+ if !writeLogs(initial) {
+ return
+ }
+
+ ticker := time.NewTicker(1 * time.Second)
+ defer ticker.Stop()
+
+ last := initial
+ for {
+ select {
+ case <-ticker.C:
+ current, err := o.Logs(id)
+ if err != nil {
+ return
+ }
+ if current != last {
+ last = current
+ if !writeLogs(current) {
+ return
+ }
+ continue
+ }
+ if _, err := fmt.Fprintf(w, ": keepalive\n\n"); err != nil {
+ return
+ }
+ flusher.Flush()
+ case <-r.Context().Done():
+ return
+ }
+ }
+}
+
func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Request) {
var req struct {
ProfileID string `json:"profileId,omitempty"`