Skip to content

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

feat: record start/stop/status for capturing browser activity as video

Marioaf0b961f0b89
diff --git a/cmd/pinchtab/cmd_cli_browser_record.go b/cmd/pinchtab/cmd_cli_browser_record.go
new file mode 100644
index 00000000..60f947a0
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_browser_record.go
@@ -0,0 +1,42 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var recordCmd = &cobra.Command{
+ Use: "record",
+ Short: "Record browser activity to video",
+}
+
+var recordStartCmd = &cobra.Command{
+ Use: "start <file>",
+ Short: "Start recording (.webm, .mp4, .gif)",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.RecordStart(rt.client, rt.base, rt.token, cmd, args)
+ })
+ },
+}
+
+var recordStopCmd = &cobra.Command{
+ Use: "stop",
+ Short: "Stop recording and save",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.RecordStop(rt.client, rt.base, rt.token)
+ })
+ },
+}
+
+var recordStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Check recording status",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.RecordStatus(rt.client, rt.base, rt.token)
+ })
+ },
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 8be704aa..3fa07957 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -82,6 +82,7 @@ func registerBrowserCommands() {
tabResumeCmd,
handoffStatusCmd,
tabHandoffStatusCmd,
+ recordCmd,
)
// These commands carry GroupID="browser" (set by setCommandGroup above).
@@ -93,6 +94,7 @@ func registerBrowserCommands() {
dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)
mouseCmd.AddCommand(mouseMoveCmd, mouseDownCmd, mouseUpCmd, mouseWheelCmd)
networkCmd.AddCommand(networkRouteCmd, networkUnrouteCmd)
+ recordCmd.AddCommand(recordStartCmd, recordStopCmd, recordStatusCmd)
configureBrowserFlags()
@@ -155,6 +157,7 @@ func registerBrowserCommands() {
handoffCmd,
resumeCmd,
handoffStatusCmd,
+ recordCmd,
)
}
@@ -258,6 +261,11 @@ func configureBrowserFlags() {
pdfCmd.Flags().Bool("file-output", false, "Use server-side file output")
pdfCmd.Flags().String("path", "", "Server-side output path")
+ recordStartCmd.Flags().Int("fps", 5, "Frames per second (1-30)")
+ recordStartCmd.Flags().Int("quality", 80, "JPEG capture quality (1-100)")
+ recordStartCmd.Flags().Float64("scale", 1.0, "Resolution scale multiplier")
+ addTabFlag(recordStartCmd)
+
findCmd.Flags().String("threshold", "", "Minimum similarity score (0-1)")
findCmd.Flags().Bool("explain", false, "Show score breakdown")
findCmd.Flags().Bool("ref-only", false, "Output just the element ref")
diff --git a/docs/commands.md b/docs/commands.md
index b99e6e24..6cbfb266 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -223,6 +223,12 @@ pinchtab download <url> # Download through the browser session
pinchtab download <url> -o <path> # Save downloaded file to a path
pinchtab upload <file> # Upload to the default file input
pinchtab upload <file> -s <css> # Upload to a specific file input
+pinchtab record start <file> # Start recording (.webm, .mp4, .gif)
+pinchtab record start <file> --fps 10 # Custom frame rate (default 5)
+pinchtab record start <file> --quality 90 # JPEG capture quality (default 80)
+pinchtab record start <file> --scale 0.5 # Half resolution
+pinchtab record stop # Stop recording and save
+pinchtab record status # Check recording status
```
## Instances, Profiles, And Activity
diff --git a/docs/endpoints.md b/docs/endpoints.md
index ab55ee74..ceac56cb 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -249,6 +249,9 @@ GET /screencast
GET /screencast/tabs
GET /instances/{id}/screencast
GET /instances/{id}/proxy/screencast
+POST /record/start
+POST /record/stop
+GET /record/status
```
Screenshot query parameters:
@@ -282,6 +285,21 @@ PDF query parameters:
- `generateTaggedPDF`
- `generateDocumentOutline`
+Record start body fields (JSON POST `/record/start`):
+
+- `format`: `gif`, `webm`, or `mp4`.
+- `fps`: Frames per second, 1-30 (default 5).
+- `quality`: JPEG capture quality 1-100 (default 80).
+- `scale`: Resolution multiplier (default 1.0).
+- `tabId`: Target a specific tab.
+
+Notes:
+
+- Recording endpoints are gated by `security.allowScreencast`.
+- `.webm` and `.mp4` formats require `ffmpeg` on the server PATH.
+- `.gif` format uses pure Go encoding (always available).
+- Only one recording per bridge instance.
+
## Downloads, Uploads, Cookies, And Clipboard
```text
diff --git a/docs/reference/index.md b/docs/reference/index.md
index 88bb2d9c..173cd360 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -22,6 +22,7 @@ Note: this index is generated and should be checked against the code when comman
- [Navigate](./navigate.md)
- [PDF](./pdf.md)
- [Press](./press.md)
+- [Record](./record.md)
- [Profiles](./profiles.md)
- [Scheduler And Tasks](./scheduler.md)
- [Screenshot](./screenshot.md)
diff --git a/docs/reference/record.md b/docs/reference/record.md
new file mode 100644
index 00000000..3a1cc8b1
--- /dev/null
+++ b/docs/reference/record.md
@@ -0,0 +1,71 @@
+# Record
+
+Record browser activity as a video file. Supports GIF (pure Go), WebM, and MP4 (require ffmpeg).
+
+```bash
+# Start recording (format from file extension)
+curl -X POST http://localhost:9867/record/start \
+ -H "Content-Type: application/json" \
+ -d '{"format":"gif","fps":5,"quality":80}'
+
+# Check status
+curl http://localhost:9867/record/status
+
+# Stop and save
+curl -X POST http://localhost:9867/record/stop > recording.gif
+```
+
+## Start Response
+
+```json
+{
+ "status": "recording",
+ "format": "gif",
+ "fps": 5,
+ "quality": 80,
+ "tabId": "tab1"
+}
+```
+
+## Status Response
+
+```json
+{
+ "active": true,
+ "format": "gif",
+ "durationSeconds": 12.5,
+ "frames": 62,
+ "tabId": "tab1",
+ "fps": 5
+}
+```
+
+## API Body Fields (POST /record/start)
+
+- `format`: `gif`, `webm`, or `mp4`. Determined by file extension in CLI.
+- `fps`: Frames per second, 1-30 (default 5).
+- `quality`: JPEG capture quality 1-100 (default 80).
+- `scale`: Resolution multiplier (default 1.0). Values < 1 reduce output size.
+- `tabId`: Target a specific tab.
+
+## CLI
+
+- `record start <file>`: Start recording. Format from extension (.gif, .webm, .mp4).
+- `record stop`: Stop and save to the path given at start.
+- `record status`: Show active recording info.
+- `--fps <n>`: Frames per second (default 5).
+- `--quality <n>`: JPEG capture quality (default 80).
+- `--scale <f>`: Resolution scale (default 1.0).
+- `--tab <id>`: Target a specific tab.
+
+## Notes
+
+- Gated by `security.allowScreencast`.
+- `.webm` and `.mp4` require `ffmpeg` installed on the server.
+- `.gif` always available (pure Go encoding).
+- One active recording per bridge instance.
+
+## Related Pages
+
+- [Screenshot](./screenshot.md)
+- [PDF](./pdf.md)
diff --git a/internal/cli/actions/actions_record.go b/internal/cli/actions/actions_record.go
new file mode 100644
index 00000000..d59f5315
--- /dev/null
+++ b/internal/cli/actions/actions_record.go
@@ -0,0 +1,125 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+func RecordStart(client *http.Client, base, token string, cmd *cobra.Command, args []string) {
+ outFile := args[0]
+
+ ext := strings.ToLower(filepath.Ext(outFile))
+ var format string
+ switch ext {
+ case ".gif":
+ format = "gif"
+ case ".webm":
+ format = "webm"
+ case ".mp4":
+ format = "mp4"
+ default:
+ cli.Fatal("Unsupported format %q — use .gif, .webm, or .mp4", ext)
+ }
+
+ fps, _ := cmd.Flags().GetInt("fps")
+ quality, _ := cmd.Flags().GetInt("quality")
+ scale, _ := cmd.Flags().GetFloat64("scale")
+ tab, _ := cmd.Flags().GetString("tab")
+
+ body := map[string]any{
+ "format": format,
+ "fps": fps,
+ "quality": quality,
+ "scale": scale,
+ }
+ if tab != "" {
+ body["tabId"] = tab
+ }
+
+ apiclient.DoPost(client, base, token, "/record/start", body)
+
+ writeRecordingState(outFile)
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Recording started → %s (%s, %d fps)", outFile, format, fps)))
+}
+
+func RecordStop(client *http.Client, base, token string) {
+ outFile := readRecordingState()
+ if outFile == "" {
+ outFile = fmt.Sprintf("recording-%s.gif", time.Now().Format("20060102-150405"))
+ }
+
+ data := apiclient.DoPostRaw(client, base, token, "/record/stop", map[string]any{})
+ if data == nil {
+ return
+ }
+
+ if err := os.WriteFile(outFile, data, 0600); err != nil {
+ cli.Fatal("Write failed: %v", err)
+ }
+ clearRecordingState()
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+}
+
+func RecordStatus(client *http.Client, base, token string) {
+ raw := apiclient.DoGetRaw(client, base, token, "/record/status", nil)
+ if raw == nil {
+ return
+ }
+
+ var status struct {
+ Active bool `json:"active"`
+ Format string `json:"format"`
+ Duration float64 `json:"durationSeconds"`
+ Frames int `json:"frames"`
+ TabID string `json:"tabId"`
+ FPS int `json:"fps"`
+ }
+ if err := json.Unmarshal(raw, &status); err != nil {
+ cli.Fatal("Decode failed: %v", err)
+ }
+
+ if !status.Active {
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "No active recording"))
+ return
+ }
+
+ fmt.Printf("Recording: %s @ %d fps | %.1fs | %d frames | tab %s\n",
+ status.Format, status.FPS, status.Duration, status.Frames, status.TabID)
+}
+
+func recordingStateFile() string {
+ if dir := os.Getenv("XDG_STATE_HOME"); dir != "" {
+ return dir + "/pinchtab/current-recording"
+ }
+ if home, err := os.UserHomeDir(); err == nil {
+ return home + "/.local/state/pinchtab/current-recording"
+ }
+ return "/tmp/pinchtab-current-recording"
+}
+
+func writeRecordingState(outFile string) {
+ path := recordingStateFile()
+ _ = os.MkdirAll(filepath.Dir(path), 0755)
+ _ = os.WriteFile(path, []byte(outFile+"\n"), 0644)
+}
+
+func readRecordingState() string {
+ data, err := os.ReadFile(recordingStateFile())
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(data))
+}
+
+func clearRecordingState() {
+ _ = os.Remove(recordingStateFile())
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 23751e04..cd790388 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -42,6 +42,8 @@ type Handlers struct {
// tabId and has no stored scoped current tab. See EmptyPointerPolicy.
emptyPointerPolicy EmptyPointerPolicy
+ recorder *recorder
+
// Optional dependency injection (for unit testing)
evalJS func(ctx context.Context, expression string, out *string) error
autoSolverRunner func(ctx context.Context, tabID string) error
@@ -64,6 +66,7 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,
IDPIGuard: idpi.NewGuard(cfg.IDPI, cfg.AllowedDomains),
CurrentTabs: NewCurrentTabStore(),
credentialStore: newCredentialStore(),
+ recorder: &recorder{},
}
// Wire up the recovery engine with callbacks that delegate back to
@@ -297,6 +300,9 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("POST /find", h.HandleFind)
mux.HandleFunc("GET /screencast", h.HandleScreencast)
mux.HandleFunc("GET /screencast/tabs", h.HandleScreencastAll)
+ mux.HandleFunc("POST /record/start", h.HandleRecordStart)
+ mux.HandleFunc("POST /record/stop", h.HandleRecordStop)
+ mux.HandleFunc("GET /record/status", h.HandleRecordStatus)
mux.HandleFunc("POST /tabs/{id}/evaluate", h.HandleTabEvaluate)
mux.HandleFunc("POST /evaluate", h.HandleEvaluate)
mux.HandleFunc("GET /clipboard/read", h.HandleClipboardRead)
diff --git a/internal/handlers/record.go b/internal/handlers/record.go
new file mode 100644
index 00000000..ce78e757
--- /dev/null
+++ b/internal/handlers/record.go
@@ -0,0 +1,383 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "image"
+ "image/color/palette"
+ "image/draw"
+ "image/gif"
+ "image/jpeg"
+ "log/slog"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+type RecordingStatus struct {
+ Active bool `json:"active"`
+ Format string `json:"format,omitempty"`
+ Duration float64 `json:"durationSeconds,omitempty"`
+ Frames int `json:"frames"`
+ TabID string `json:"tabId,omitempty"`
+ FPS int `json:"fps,omitempty"`
+}
+
+type recorder struct {
+ mu sync.Mutex
+ active bool
+ tabCtx context.Context
+ tabID string
+ format string
+ fps int
+ quality int
+ scale float64
+ tmpDir string
+ frameNum int
+ startTime time.Time
+ stopCh chan struct{}
+ doneCh chan struct{}
+}
+
+func (rec *recorder) start(tabCtx context.Context, tabID, format string, fps, quality int, scale float64) error {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+
+ if rec.active {
+ return fmt.Errorf("recording already in progress")
+ }
+
+ tmpDir, err := os.MkdirTemp("", "pinchtab-recording-*")
+ if err != nil {
+ return fmt.Errorf("create temp dir: %w", err)
+ }
+
+ rec.active = true
+ rec.tabCtx = tabCtx
+ rec.tabID = tabID
+ rec.format = format
+ rec.fps = fps
+ rec.quality = quality
+ rec.scale = scale
+ rec.tmpDir = tmpDir
+ rec.frameNum = 0
+ rec.startTime = time.Now()
+ rec.stopCh = make(chan struct{})
+ rec.doneCh = make(chan struct{})
+
+ go rec.captureLoop()
+ return nil
+}
+
+func (rec *recorder) stop() ([]byte, string, error) {
+ rec.mu.Lock()
+ if !rec.active {
+ rec.mu.Unlock()
+ return nil, "", fmt.Errorf("no active recording")
+ }
+ close(rec.stopCh)
+ rec.mu.Unlock()
+
+ <-rec.doneCh
+
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+
+ defer func() {
+ _ = os.RemoveAll(rec.tmpDir)
+ rec.active = false
+ rec.tmpDir = ""
+ }()
+
+ if rec.frameNum == 0 {
+ return nil, "", fmt.Errorf("no frames captured")
+ }
+
+ data, err := rec.encode()
+ if err != nil {
+ return nil, "", err
+ }
+
+ return data, rec.format, nil
+}
+
+func (rec *recorder) status() RecordingStatus {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+
+ if !rec.active {
+ return RecordingStatus{}
+ }
+ return RecordingStatus{
+ Active: true,
+ Format: rec.format,
+ Duration: time.Since(rec.startTime).Seconds(),
+ Frames: rec.frameNum,
+ TabID: rec.tabID,
+ FPS: rec.fps,
+ }
+}
+
+func (rec *recorder) captureLoop() {
+ defer close(rec.doneCh)
+
+ interval := time.Second / time.Duration(rec.fps)
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-rec.stopCh:
+ return
+ case <-rec.tabCtx.Done():
+ return
+ case <-ticker.C:
+ frame, err := captureScreencastJPEG(rec.tabCtx, rec.quality)
+ if err != nil {
+ slog.Debug("recording frame capture failed", "err", err)
+ continue
+ }
+ rec.mu.Lock()
+ rec.frameNum++
+ path := filepath.Join(rec.tmpDir, fmt.Sprintf("frame_%06d.jpg", rec.frameNum))
+ rec.mu.Unlock()
+ if err := os.WriteFile(path, frame, 0600); err != nil {
+ slog.Debug("recording frame write failed", "err", err)
+ }
+ }
+ }
+}
+
+func (rec *recorder) encode() ([]byte, error) {
+ switch rec.format {
+ case "gif":
+ return rec.encodeGIF()
+ case "webm":
+ return rec.encodeFFmpeg("libvpx", "-crf", "10", "-b:v", "1M")
+ case "mp4":
+ return rec.encodeFFmpeg("libx264", "-pix_fmt", "yuv420p", "-crf", "23")
+ default:
+ return nil, fmt.Errorf("unsupported format: %s", rec.format)
+ }
+}
+
+func (rec *recorder) encodeGIF() ([]byte, error) {
+ files, err := filepath.Glob(filepath.Join(rec.tmpDir, "frame_*.jpg"))
+ if err != nil {
+ return nil, err
+ }
+ sort.Strings(files)
+
+ delay := 100 / rec.fps
+ if delay < 1 {
+ delay = 1
+ }
+
+ g := &gif.GIF{LoopCount: 0}
+
+ for _, f := range files {
+ data, err := os.ReadFile(f)
+ if err != nil {
+ continue
+ }
+ img, err := jpeg.Decode(bytes.NewReader(data))
+ if err != nil {
+ continue
+ }
+
+ if rec.scale != 1.0 && rec.scale > 0 {
+ img = scaleImage(img, rec.scale)
+ }
+
+ bounds := img.Bounds()
+ paletted := image.NewPaletted(bounds, palette.Plan9)
+ draw.FloydSteinberg.Draw(paletted, bounds, img, bounds.Min)
+ g.Image = append(g.Image, paletted)
+ g.Delay = append(g.Delay, delay)
+ }
+
+ if len(g.Image) == 0 {
+ return nil, fmt.Errorf("no frames to encode")
+ }
+
+ var buf bytes.Buffer
+ if err := gif.EncodeAll(&buf, g); err != nil {
+ return nil, fmt.Errorf("gif encode: %w", err)
+ }
+ return buf.Bytes(), nil
+}
+
+func (rec *recorder) encodeFFmpeg(codec string, extraArgs ...string) ([]byte, error) {
+ outFile := filepath.Join(rec.tmpDir, "output."+rec.format)
+
+ args := []string{
+ "-y",
+ "-framerate", strconv.Itoa(rec.fps),
+ "-i", filepath.Join(rec.tmpDir, "frame_%06d.jpg"),
+ }
+
+ if rec.scale != 1.0 && rec.scale > 0 {
+ args = append(args, "-vf",
+ fmt.Sprintf("scale=trunc(iw*%g/2)*2:trunc(ih*%g/2)*2", rec.scale, rec.scale))
+ }
+
+ args = append(args, "-c:v", codec)
+ args = append(args, extraArgs...)
+ args = append(args, outFile)
+
+ cmd := exec.Command("ffmpeg", args...)
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err != nil {
+ return nil, fmt.Errorf("ffmpeg encode: %w\n%s", err, stderr.String())
+ }
+ return os.ReadFile(outFile)
+}
+
+func scaleImage(src image.Image, scale float64) image.Image {
+ bounds := src.Bounds()
+ w := int(float64(bounds.Dx()) * scale)
+ h := int(float64(bounds.Dy()) * scale)
+ if w < 1 {
+ w = 1
+ }
+ if h < 1 {
+ h = 1
+ }
+ dst := image.NewRGBA(image.Rect(0, 0, w, h))
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ srcX := bounds.Min.X + int(float64(x)/scale)
+ srcY := bounds.Min.Y + int(float64(y)/scale)
+ if srcX >= bounds.Max.X {
+ srcX = bounds.Max.X - 1
+ }
+ if srcY >= bounds.Max.Y {
+ srcY = bounds.Max.Y - 1
+ }
+ dst.Set(x, y, src.At(srcX, srcY))
+ }
+ }
+ return dst
+}
+
+func ffmpegAvailable() bool {
+ _, err := exec.LookPath("ffmpeg")
+ return err == nil
+}
+
+// HandleRecordStart starts a recording session for a tab.
+func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {
+ if !h.Config.AllowScreencast {
+ httpx.ErrorCode(w, 403, "recording_disabled",
+ httpx.DisabledEndpointMessage("recording", "security.allowScreencast"), false,
+ map[string]any{"setting": "security.allowScreencast"})
+ return
+ }
+
+ if !h.ensureChromeOrRespond(w) {
+ return
+ }
+
+ var req struct {
+ TabID string `json:"tabId"`
+ Format string `json:"format"`
+ FPS int `json:"fps"`
+ Quality int `json:"quality"`
+ Scale float64 `json:"scale"`
+ }
+ if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
+ }
+
+ if req.Format == "" {
+ req.Format = "gif"
+ }
+ if req.FPS <= 0 {
+ req.FPS = 5
+ }
+ if req.FPS > 30 {
+ req.FPS = 30
+ }
+ if req.Quality <= 0 {
+ req.Quality = 80
+ }
+ if req.Scale <= 0 {
+ req.Scale = 1.0
+ }
+
+ switch req.Format {
+ case "gif":
+ case "webm", "mp4":
+ if !ffmpegAvailable() {
+ httpx.ErrorCode(w, 400, "ffmpeg_required",
+ fmt.Sprintf("recording to .%s requires ffmpeg; install it or use .gif", req.Format),
+ false, nil)
+ return
+ }
+ default:
+ httpx.ErrorCode(w, 400, "invalid_format",
+ "supported formats: gif, webm, mp4", false, nil)
+ return
+ }
+
+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)
+ if err != nil {
+ httpx.Problem(w, http.StatusNotFound, "tab_not_found", "tab not found", false, nil)
+ return
+ }
+
+ if err := h.recorder.start(ctx, resolvedTabID, req.Format, req.FPS, req.Quality, req.Scale); err != nil {
+ httpx.ErrorCode(w, 409, "recording_error", err.Error(), false, nil)
+ return
+ }
+
+ slog.Info("recording started", "tab", resolvedTabID, "format", req.Format, "fps", req.FPS)
+ httpx.JSON(w, 200, map[string]any{
+ "status": "recording",
+ "format": req.Format,
+ "fps": req.FPS,
+ "quality": req.Quality,
+ "tabId": resolvedTabID,
+ })
+}
+
+// HandleRecordStop stops the active recording and returns the encoded file.
+func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {
+ data, format, err := h.recorder.stop()
+ if err != nil {
+ httpx.ErrorCode(w, 400, "recording_error", err.Error(), false, nil)
+ return
+ }
+
+ contentType := "application/octet-stream"
+ switch format {
+ case "gif":
+ contentType = "image/gif"
+ case "webm":
+ contentType = "video/webm"
+ case "mp4":
+ contentType = "video/mp4"
+ }
+
+ slog.Info("recording stopped", "format", format, "size", len(data))
+ w.Header().Set("Content-Type", contentType)
+ w.Header().Set("Content-Length", strconv.Itoa(len(data)))
+ w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=recording.%s", format))
+ w.WriteHeader(200)
+ _, _ = w.Write(data)
+}
+
+// HandleRecordStatus returns the current recording status.
+func (h *Handlers) HandleRecordStatus(w http.ResponseWriter, r *http.Request) {
+ httpx.JSON(w, 200, h.recorder.status())
+}
diff --git a/internal/handlers/record_test.go b/internal/handlers/record_test.go
new file mode 100644
index 00000000..ed30fe0f
--- /dev/null
+++ b/internal/handlers/record_test.go
@@ -0,0 +1,193 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleRecordStart_Disabled(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: false}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ body := `{"format":"gif","fps":5}`
+ req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 403 {
+ t.Errorf("expected 403 when recording disabled, got %d", w.Code)
+ }
+}
+
+func TestHandleRecordStart_InvalidFormat(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: true}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ body := `{"format":"avi","fps":5}`
+ req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 for invalid format, got %d", w.Code)
+ }
+}
+
+func TestHandleRecordStart_TabNotFound(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: true}
+ h := New(&mockBridge{failTab: true}, cfg, nil, nil, nil)
+
+ body := `{"format":"gif","fps":5,"tabId":"missing"}`
+ req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 404 {
+ t.Errorf("expected 404 for missing tab, got %d", w.Code)
+ }
+}
+
+func TestHandleRecordStart_Success(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: true}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ body := `{"format":"gif","fps":5}`
+ req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp["status"] != "recording" {
+ t.Errorf("expected status=recording, got %v", resp["status"])
+ }
+ if resp["format"] != "gif" {
+ t.Errorf("expected format=gif, got %v", resp["format"])
+ }
+ if resp["fps"] != float64(5) {
+ t.Errorf("expected fps=5, got %v", resp["fps"])
+ }
+ if resp["tabId"] == nil || resp["tabId"] == "" {
+ t.Errorf("expected tabId to be set, got %v", resp["tabId"])
+ }
+
+ // Clean up: stop the recording (ignore error since no frames captured)
+ _, _, _ = h.recorder.stop()
+}
+
+func TestHandleRecordStart_AlreadyRecording(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: true}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ // First start: should succeed
+ body := `{"format":"gif","fps":5}`
+ req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("first start: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Second start: should return 409
+ req = httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w = httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 409 {
+ t.Errorf("expected 409 for already recording, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Clean up: stop the recording (ignore error since no frames captured)
+ _, _, _ = h.recorder.stop()
+}
+
+func TestHandleRecordStop_NoRecording(t *testing.T) {
+ cfg := &config.RuntimeConfig{}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/record/stop", nil)
+ w := httptest.NewRecorder()
+ h.HandleRecordStop(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400 when no recording active, got %d", w.Code)
+ }
+}
+
+func TestHandleRecordStatus_Inactive(t *testing.T) {
+ cfg := &config.RuntimeConfig{}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/record/status", nil)
+ w := httptest.NewRecorder()
+ h.HandleRecordStatus(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+
+ var resp RecordingStatus
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Active {
+ t.Errorf("expected active=false, got true")
+ }
+}
+
+func TestHandleRecordStatus_Active(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: true}
+ h := New(&mockBridge{}, cfg, nil, nil, nil)
+
+ // Start a recording first
+ body := `{"format":"gif","fps":5}`
+ req := httptest.NewRequest("POST", "/record/start", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleRecordStart(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("start: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Check status
+ req = httptest.NewRequest("GET", "/record/status", nil)
+ w = httptest.NewRecorder()
+ h.HandleRecordStatus(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("status: expected 200, got %d", w.Code)
+ }
+
+ var resp RecordingStatus
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if !resp.Active {
+ t.Errorf("expected active=true, got false")
+ }
+ if resp.Format != "gif" {
+ t.Errorf("expected format=gif, got %q", resp.Format)
+ }
+ if resp.FPS != 5 {
+ t.Errorf("expected fps=5, got %d", resp.FPS)
+ }
+
+ // Clean up: stop the recording (ignore error since no frames captured)
+ _, _, _ = h.recorder.stop()
+}
+
+func TestFFmpegAvailable(t *testing.T) {
+ // Just verify it doesn't panic; result depends on environment.
+ _ = ffmpegAvailable()
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 405b009d..f7dea8c1 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -157,6 +157,9 @@ var coreEndpoints = []Endpoint{
{"POST", "/upload", "Upload file to file input", CapUpload, true},
{"GET", "/screencast", "Live tab frame stream", CapScreencast, false},
{"GET", "/screencast/tabs", "List tabs available for screencast", CapScreencast, false},
+ {"POST", "/record/start", "Start recording browser activity to video", CapScreencast, false},
+ {"POST", "/record/stop", "Stop recording and return encoded file", CapScreencast, false},
+ {"GET", "/record/status", "Check recording status", CapScreencast, false},
// CapStateExport gates all sensitive state I/O: reading, writing, injection, and deletion.
{"GET", "/storage", "Get storage items (current origin)", CapStateExport, true},
{"GET", "/state/show", "Show state file details", CapStateExport, false},
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.md
index 69e4b8f1..8c53baec 100644
--- a/skills/pinchtab/SKILL.md
+++ b/skills/pinchtab/SKILL.md
@@ -209,6 +209,9 @@ Timeout 10s default, 30s max via `--timeout <ms>`. Prefer `--not-text`/`--state
```bash
pinchtab screenshot [-o path.png] [-q <jpeg-quality>] # format by extension
pinchtab pdf [-o path.pdf] [--landscape]
+pinchtab record start out.gif [--fps 5] [--scale 1.0] # .gif/.webm/.mp4; requires security.allowScreencast
+pinchtab record stop # stop and save to path given at start
+pinchtab record status # check active recording
```
### Advanced (explicit opt-in only)
diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.md
index 827dd91a..4d2fd897 100644
--- a/skills/pinchtab/references/api.md
+++ b/skills/pinchtab/references/api.md
@@ -300,6 +300,25 @@ curl "/screenshot?raw=true&quality=50" -o screenshot.jpg
curl "/screenshot?raw=true&format=png" -o screenshot.png
```
+## Recording
+
+Record browser activity as a video file. Requires `security.allowScreencast: true`.
+
+```bash
+# CLI: pinchtab record start output.gif [--fps 2] [--quality 80] [--scale 1.0]
+# Start recording
+curl -X POST /record/start -H 'Content-Type: application/json' \
+ -d '{"format":"gif","fps":5,"quality":80}'
+
+# Check status
+curl /record/status
+
+# Stop and save (returns raw binary)
+curl -X POST /record/stop -o recording.gif
+```
+
+Formats: `gif` (always available), `webm` and `mp4` (require ffmpeg). One active recording per instance.
+
## Evaluate JavaScript
Use this sparingly. Prefer `text`, `snapshot`, and normal actions first.
diff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.md
index fb44aab0..3d8ee4c5 100644
--- a/skills/pinchtab/references/commands.md
+++ b/skills/pinchtab/references/commands.md
@@ -178,6 +178,25 @@ pinchtab screenshot --quality 80 # JPEG at 80%
> ⚠️ **Quirk:** Use `screenshot` (full word), not `ss` or `shot`.
+### `pinchtab record`
+Record browser activity as a video file.
+
+```bash
+pinchtab record start output.gif # start recording (format from extension)
+pinchtab record start output.gif --fps 2 # lower frame rate
+pinchtab record stop # stop and save to the path given at start
+pinchtab record status # check if recording is active
+```
+
+| Flag | Description |
+|------|-------------|
+| `--fps <n>` | Frames per second (default 5) |
+| `--quality <n>` | JPEG capture quality 1-100 (default 80) |
+| `--scale <f>` | Resolution scale (default 1.0; 0.5 = half size) |
+| `--tab <id>` | Target a specific tab |
+
+Supported formats: `.gif` (always available), `.webm` and `.mp4` (require ffmpeg on the server). Requires `security.allowScreencast: true`.
+
### `pinchtab text`
Extract readable text from the page.
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index faec556d..c546d2c1 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -39,6 +39,7 @@
"security": {
"allowEvaluate": true,
"allowDownload": true,
+ "allowScreencast": true,
"allowCookies": true,
"allowUpload": true,
"allowClipboard": true,
diff --git a/tests/e2e/scenarios/api/recording-smoke.sh b/tests/e2e/scenarios/api/recording-smoke.sh
new file mode 100755
index 00000000..5e7b9a60
--- /dev/null
+++ b/tests/e2e/scenarios/api/recording-smoke.sh
@@ -0,0 +1,85 @@
+#!/bin/bash
+# recording-smoke.sh — Recording smoke tests (API + CLI).
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "record: status shows inactive"
+
+pt_get /record/status
+assert_ok "record status"
+assert_json_eq "$RESULT" ".active" "false" "no active recording"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "record: start → status → stop (API gif)"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate"
+
+pt_post /record/start -d '{"format":"gif","fps":2,"quality":60}'
+assert_ok "record start"
+assert_json_eq "$RESULT" ".status" "recording" "recording started"
+assert_json_eq "$RESULT" ".format" "gif" "format is gif"
+
+sleep 2
+
+pt_get /record/status
+assert_ok "record status"
+assert_json_eq "$RESULT" ".active" "true" "recording active"
+
+OUTFILE="/tmp/e2e-recording-test.gif"
+e2e_curl -s -X POST "${E2E_SERVER}/record/stop" -o "$OUTFILE" \
+ -H "Content-Type: application/json" -d '{}'
+FILESIZE=$(wc -c < "$OUTFILE" 2>/dev/null | tr -d ' ')
+
+if [ -f "$OUTFILE" ] && [ "$FILESIZE" -gt 0 ]; then
+ pass_assert "recording file created ($FILESIZE bytes)"
+else
+ fail_assert "recording file missing or empty"
+fi
+rm -f "$OUTFILE"
+
+pt_get /record/status
+assert_ok "record status after stop"
+assert_json_eq "$RESULT" ".active" "false" "recording inactive after stop"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "record: stop without start returns 400"
+
+pt_post /record/stop -d '{}'
+assert_http_status 400 "stop without active recording"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "record: CLI start → stop roundtrip"
+
+rm -f "${XDG_STATE_HOME:-$HOME/.local/state}/pinchtab/current-recording" 2>/dev/null || true
+rm -f /tmp/pinchtab-current-recording 2>/dev/null || true
+
+CLI_OUTFILE="/tmp/e2e-cli-recording.gif"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate for CLI recording"
+
+e2e_curl -s -X POST "${E2E_SERVER}/record/start" \
+ -H "Content-Type: application/json" \
+ -d '{"format":"gif","fps":2,"quality":60}' > /dev/null
+sleep 2
+e2e_curl -s -X POST "${E2E_SERVER}/record/stop" -o "$CLI_OUTFILE" \
+ -H "Content-Type: application/json" -d '{}'
+FILESIZE=$(wc -c < "$CLI_OUTFILE" 2>/dev/null | tr -d ' ')
+
+if [ -f "$CLI_OUTFILE" ] && [ "$FILESIZE" -gt 0 ]; then
+ pass_assert "CLI recording file created ($FILESIZE bytes)"
+else
+ fail_assert "CLI recording file missing or empty"
+fi
+rm -f "$CLI_OUTFILE"
+
+end_test
diff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.json
index 57f74778..4c55a6bc 100644
--- a/tests/e2e/scenarios/manifest.json
+++ b/tests/e2e/scenarios/manifest.json
@@ -101,6 +101,9 @@
"services": ["pinchtab", "pinchtab-secure", "pinchtab-lite", "fixtures"],
"ready": ["E2E_SERVER", "E2E_SECURE_SERVER", "E2E_LITE_SERVER"],
"tags": ["system", "tasks", "idpi", "lite", "secure"]
+ },
+ "api/recording-smoke.sh": {
+ "tags": ["recording", "video", "smoke"]
}
}
}
diff --git a/tests/tools/runner/internal/e2e/e2e_test.go b/tests/tools/runner/internal/e2e/e2e_test.go
index a8ae5b98..e0e9de25 100644
--- a/tests/tools/runner/internal/e2e/e2e_test.go
+++ b/tests/tools/runner/internal/e2e/e2e_test.go
@@ -633,7 +633,7 @@ func TestDryRunSmokePlan(t *testing.T) {
`Skipping plugin-smoke: filter "" has no matching scenarios`,
"docker compose -f tests/e2e/docker-compose-multi.yml up -d pinchtab pinchtab-secure pinchtab-autoclose pinchtab-medium pinchtab-full fixtures",
"E2E_SUMMARY_TITLE=PinchTab E2E API Smoke Suite",
- "runner-api /bin/bash /e2e/run.sh scenario=auto-switch-smoke.sh scenario=network-route-smoke.sh scenario=tabs-autoclose-smoke.sh",
+ "runner-api /bin/bash /e2e/run.sh scenario=auto-switch-smoke.sh scenario=network-route-smoke.sh scenario=recording-smoke.sh scenario=tabs-autoclose-smoke.sh",
"E2E_SUMMARY_TITLE=PinchTab E2E CLI Smoke Suite",
"runner-cli /bin/bash /e2e/run.sh scenario=system-smoke.sh scenario=tabs-smoke.sh",
"docker compose -f tests/e2e/docker-compose-multi.yml restart pinchtab",