Skip to content

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

fix: non-blocking record stop, GPU crash recovery, and e2e test alignment

Mario1d200ef4619d
diff --git a/cmd/pinchtab/cmd_cli_browser_record.go b/cmd/pinchtab/cmd_cli_browser_record.go
index 7d353ebc..60f947a0 100644
--- a/cmd/pinchtab/cmd_cli_browser_record.go
+++ b/cmd/pinchtab/cmd_cli_browser_record.go
@@ -1,9 +1,6 @@
package main
import (
- "net/http"
- "time"
-
browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
"github.com/spf13/cobra"
)
@@ -29,12 +26,7 @@ var recordStopCmd = &cobra.Command{
Short: "Stop recording and save",
Run: func(cmd *cobra.Command, args []string) {
runCLI(func(rt cliRuntime) {
- // Encoding can take minutes; use a dedicated long-timeout client.
- longClient := &http.Client{
- Timeout: 3 * time.Minute,
- Transport: rt.client.Transport,
- }
- browseractions.RecordStop(longClient, rt.base, rt.token)
+ browseractions.RecordStop(rt.client, rt.base, rt.token)
})
},
}
diff --git a/internal/bridge/bridge_lifecycle.go b/internal/bridge/bridge_lifecycle.go
index dc89c670..c4894984 100644
--- a/internal/bridge/bridge_lifecycle.go
+++ b/internal/bridge/bridge_lifecycle.go
@@ -103,14 +103,14 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
if b.BrowserCtx.Err() == nil {
return nil
}
- // Chrome died — reset state for re-initialization
- slog.Warn("chrome context cancelled, re-initializing")
+ slog.Warn("chrome context cancelled, re-initializing without in-process-gpu")
b.initialized = false
b.BrowserCtx = nil
b.BrowserCancel = nil
b.AllocCtx = nil
b.AllocCancel = nil
b.TabManager = nil
+ cfg.DisableInProcessGPU = true
}
if b.BrowserCtx != nil {
diff --git a/internal/bridge/crash.go b/internal/bridge/crash.go
index 23a3ed5c..1f70844a 100644
--- a/internal/bridge/crash.go
+++ b/internal/bridge/crash.go
@@ -125,22 +125,26 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {
}
})
- // Monitor browser context cancellation
+ // Monitor browser context cancellation. A canceled context during
+ // draining is expected (deliberate shutdown); otherwise it indicates
+ // an unexpected failure such as an in-process GPU crash.
go func() {
<-b.BrowserCtx.Done()
err := b.BrowserCtx.Err()
- if err == nil || err == context.Canceled {
- slog.Info("browser context ended", "reason", "context canceled")
+ if b.draining {
+ slog.Info("browser context ended during drain", "reason", err)
return
}
+ reason := "unexpected context cancellation"
+ if err != nil && err != context.Canceled {
+ reason = err.Error()
+ }
event := CrashEvent{
Time: time.Now(),
- Reason: err.Error(),
+ Reason: reason,
}
recordCrashEvent(event)
- slog.Warn("🔥 BROWSER CONTEXT ENDED",
- "error", err,
- )
+ slog.Warn("🔥 BROWSER CONTEXT ENDED UNEXPECTEDLY", "error", err)
if handler != nil {
handler(event)
}
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
index 68b0d0ba..d6e6329f 100644
--- a/internal/bridge/runtime/init.go
+++ b/internal/bridge/runtime/init.go
@@ -181,9 +181,11 @@ func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hoo
// Collapse the GPU process into the browser process. Saves one
// OS process and ~50-150MB per Chrome instance, and avoids the
// GPU-process sandbox negotiation in our --no-sandbox containers.
- // Trade-off: a GPU code crash takes the browser with it, but the
- // always-on strategy restarts instances anyway.
- opts = append(opts, chromedp.Flag("in-process-gpu", true))
+ // Trade-off: a GPU code crash takes the browser with it. Disabled
+ // automatically after a crash so the failure doesn't repeat.
+ if !cfg.DisableInProcessGPU {
+ opts = append(opts, chromedp.Flag("in-process-gpu", true))
+ }
} else {
opts = append(opts, chromedp.Flag("headless", false))
}
diff --git a/internal/cli/actions/actions_record.go b/internal/cli/actions/actions_record.go
index dc4fc705..21985923 100644
--- a/internal/cli/actions/actions_record.go
+++ b/internal/cli/actions/actions_record.go
@@ -57,16 +57,33 @@ func RecordStop(client *http.Client, base, token string) {
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 {
+ abs, err := filepath.Abs(outFile)
+ if err == nil {
+ outFile = abs
+ }
+
+ raw := apiclient.DoPostRaw(client, base, token, "/record/stop", map[string]any{
+ "outputPath": outFile,
+ })
+ clearRecordingState()
+
+ if raw == nil {
return
}
- if err := os.WriteFile(outFile, data, 0600); err != nil {
- cli.Fatal("Write failed: %v", err)
+ var result struct {
+ Status string `json:"status"`
+ Path string `json:"path"`
+ Frames int `json:"frames"`
+ Hint string `json:"hint"`
}
- clearRecordingState()
- fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+ if err := json.Unmarshal(raw, &result); err != nil {
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Encoding → %s", outFile)))
+ return
+ }
+
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle,
+ fmt.Sprintf("Encoding %d frames → %s (use `record status` to check progress)", result.Frames, result.Path)))
}
func RecordStatus(client *http.Client, base, token string) {
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 04082c46..f1dd475b 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -46,22 +46,23 @@ type RuntimeConfig struct {
TrustLoopbackProxy bool // when true, navigation responses with a loopback RemoteIPAddress (e.g. system HTTP/SOCKS proxy on 127.0.0.1) are not blocked; default false
// Browser/instance settings
- Headless bool
- HeadlessSet bool // true when explicitly set via config or flag
- NoRestore bool
- ProfileDir string
- ProfilesBaseDir string
- DefaultProfile string
- ChromeVersion string
- Timezone string
- BlockImages bool
- BlockMedia bool
- BlockAds bool
- MaxTabs int
- MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU
- ChromeBinary string
- ChromeDebugPort int
- ChromeExtraFlags string
+ Headless bool
+ HeadlessSet bool // true when explicitly set via config or flag
+ DisableInProcessGPU bool // runtime-only: set after a GPU crash to avoid repeating the failure
+ NoRestore bool
+ ProfileDir string
+ ProfilesBaseDir string
+ DefaultProfile string
+ ChromeVersion string
+ Timezone string
+ BlockImages bool
+ BlockMedia bool
+ BlockAds bool
+ MaxTabs int
+ MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU
+ ChromeBinary string
+ ChromeDebugPort int
+ ChromeExtraFlags string
// CDPAttachURL: when set, the bridge skips launching its own Chrome and
// connects to an already-running Chrome whose browser-level CDP
// WebSocket URL is provided here (e.g.
diff --git a/internal/handlers/record.go b/internal/handlers/record.go
index 715d7d14..68b11095 100644
--- a/internal/handlers/record.go
+++ b/internal/handlers/record.go
@@ -84,6 +84,8 @@ type RecordingStatus struct {
Frames int `json:"frames"`
TabID string `json:"tabId,omitempty"`
FPS int `json:"fps,omitempty"`
+ OutputPath string `json:"outputPath,omitempty"`
+ Error string `json:"error,omitempty"`
}
type recorder struct {
@@ -103,13 +105,16 @@ type recorder struct {
startTime time.Time
stopCh chan struct{}
doneCh chan struct{}
+ outputPath string // final destination set by stop(); encoding writes here
+ encodeErr error // set by background encode goroutine
}
func (rec *recorder) start(tabCtx context.Context, tabID, owner, format string, fps, quality int, scale float64) error {
rec.mu.Lock()
defer rec.mu.Unlock()
- if rec.state == stateAborted {
+ if rec.state == stateAborted || rec.state == stateFinished {
+ rec.cleanup()
rec.state = stateIdle
rec.stopReason = ""
}
@@ -144,23 +149,31 @@ func (rec *recorder) start(tabCtx context.Context, tabID, owner, format string,
return nil
}
-func (rec *recorder) stop(callerOwner string) ([]byte, string, error) {
+func (rec *recorder) stop(callerOwner, outputPath string) (RecordStopResult, error) {
rec.mu.Lock()
if rec.state == stateIdle || rec.state == stateAborted {
rec.mu.Unlock()
- return nil, "", fmt.Errorf("no active recording")
+ return RecordStopResult{}, fmt.Errorf("no active recording")
}
- if rec.state == stateStopping || rec.state == stateEncoding || rec.state == stateFinished {
- doneCh := rec.doneCh
+ if rec.state == stateEncoding {
+ r := RecordStopResult{
+ OutputPath: rec.outputPath,
+ Format: rec.format,
+ Frames: rec.frameNum,
+ }
+ rec.mu.Unlock()
+ return r, fmt.Errorf("already encoding to %s — use record status to check progress", rec.outputPath)
+ }
+ if rec.state == stateStopping || rec.state == stateFinished {
rec.mu.Unlock()
- <-doneCh
- return nil, "", fmt.Errorf("no active recording")
+ return RecordStopResult{}, fmt.Errorf("no active recording")
}
if rec.owner != "" && callerOwner != rec.owner {
rec.mu.Unlock()
- return nil, "", fmt.Errorf("recording owned by another session")
+ return RecordStopResult{}, fmt.Errorf("recording owned by another session")
}
rec.state = stateStopping
+ rec.outputPath = outputPath
close(rec.stopCh)
doneCh := rec.doneCh
format := rec.format
@@ -172,29 +185,70 @@ func (rec *recorder) stop(callerOwner string) ([]byte, string, error) {
<-doneCh
+ result := RecordStopResult{
+ OutputPath: outputPath,
+ Format: format,
+ Frames: frameNum,
+ }
+
+ if frameNum == 0 {
+ rec.mu.Lock()
+ rec.state = stateFinished
+ rec.cleanup()
+ rec.state = stateIdle
+ rec.mu.Unlock()
+ return result, fmt.Errorf("no frames captured")
+ }
+
rec.mu.Lock()
rec.state = stateEncoding
rec.mu.Unlock()
- var data []byte
- var encErr error
- if frameNum > 0 {
- data, encErr = encode(tmpDir, format, fps, scale)
- } else {
- encErr = fmt.Errorf("no frames captured")
- }
+ go func() {
+ tmpOut := outputPath + ".encoding.tmp"
+ encErr := encodeToFile(tmpDir, tmpOut, format, fps, scale)
+ if encErr == nil {
+ encErr = os.Rename(tmpOut, outputPath)
+ if encErr != nil {
+ _ = os.Remove(tmpOut)
+ }
+ } else {
+ _ = os.Remove(tmpOut)
+ }
- rec.mu.Lock()
- defer rec.mu.Unlock()
- rec.state = stateFinished
- rec.cleanup()
- rec.state = stateIdle
- rec.stopReason = ""
+ rec.mu.Lock()
+ rec.encodeErr = encErr
+ rec.state = stateFinished
+ if rec.tabCancel != nil {
+ rec.tabCancel()
+ rec.tabCancel = nil
+ }
+ if rec.tmpDir != "" {
+ _ = os.RemoveAll(rec.tmpDir)
+ rec.tmpDir = ""
+ }
+ rec.mu.Unlock()
- if encErr != nil {
- return nil, "", encErr
- }
- return data, format, nil
+ if encErr != nil {
+ slog.Error("recording encode failed", "path", outputPath, "err", encErr)
+ } else {
+ info, _ := os.Stat(outputPath)
+ size := int64(0)
+ if info != nil {
+ size = info.Size()
+ }
+ slog.Info("recording saved", "path", outputPath, "bytes", size)
+ }
+ }()
+
+ return result, nil
+}
+
+// RecordStopResult is returned immediately by stop(); encoding continues in the background.
+type RecordStopResult struct {
+ OutputPath string
+ Format string
+ Frames int
}
// cleanup releases resources but does not change state — callers set the
@@ -209,6 +263,8 @@ func (rec *recorder) cleanup() {
}
rec.tmpDir = ""
rec.owner = ""
+ rec.outputPath = ""
+ rec.encodeErr = nil
}
func (rec *recorder) status() RecordingStatus {
@@ -218,6 +274,18 @@ func (rec *recorder) status() RecordingStatus {
if rec.state == stateIdle {
return RecordingStatus{State: stateIdle.String()}
}
+ if rec.state == stateFinished {
+ s := RecordingStatus{
+ State: stateFinished.String(),
+ Format: rec.format,
+ Frames: rec.frameNum,
+ OutputPath: rec.outputPath,
+ }
+ if rec.encodeErr != nil {
+ s.Error = rec.encodeErr.Error()
+ }
+ return s
+ }
return RecordingStatus{
Active: rec.state != stateAborted,
State: rec.state.String(),
@@ -227,6 +295,7 @@ func (rec *recorder) status() RecordingStatus {
Frames: rec.frameNum,
TabID: rec.tabID,
FPS: rec.fps,
+ OutputPath: rec.outputPath,
}
}
@@ -333,26 +402,26 @@ func (rec *recorder) scheduleLimitCleanup() {
}()
}
-func encode(tmpDir, format string, fps int, scale float64) ([]byte, error) {
+func encodeToFile(tmpDir, outputPath, format string, fps int, scale float64) error {
ctx, cancel := context.WithTimeout(context.Background(), encodeTimeout)
defer cancel()
switch format {
case "gif":
- return encodeGIF(tmpDir, fps, scale)
+ return encodeGIFToFile(tmpDir, outputPath, fps, scale)
case "webm":
- return encodeFFmpeg(ctx, tmpDir, format, fps, scale, "libvpx", "-crf", "10", "-b:v", "1M")
+ return encodeFFmpegToFile(ctx, tmpDir, outputPath, format, fps, scale, "libvpx", "-crf", "10", "-b:v", "1M")
case "mp4":
- return encodeFFmpeg(ctx, tmpDir, format, fps, scale, "libx264", "-pix_fmt", "yuv420p", "-crf", "23")
+ return encodeFFmpegToFile(ctx, tmpDir, outputPath, format, fps, scale, "libx264", "-pix_fmt", "yuv420p", "-crf", "23")
default:
- return nil, fmt.Errorf("unsupported format: %s", format)
+ return fmt.Errorf("unsupported format: %s", format)
}
}
-func encodeGIF(tmpDir string, fps int, scale float64) ([]byte, error) {
+func encodeGIFToFile(tmpDir, outputPath string, fps int, scale float64) error {
files, err := filepath.Glob(filepath.Join(tmpDir, "frame_*.jpg"))
if err != nil {
- return nil, err
+ return err
}
sort.Strings(files)
@@ -365,10 +434,9 @@ func encodeGIF(tmpDir string, fps int, scale float64) ([]byte, error) {
delay = 1
}
- outPath := filepath.Join(tmpDir, "output.gif")
- outFile, err := os.Create(outPath)
+ outFile, err := os.Create(outputPath)
if err != nil {
- return nil, fmt.Errorf("create gif output: %w", err)
+ return fmt.Errorf("create gif output: %w", err)
}
defer func() { _ = outFile.Close() }()
@@ -411,21 +479,17 @@ func encodeGIF(tmpDir string, fps int, scale float64) ([]byte, error) {
}
if len(g.Image) == 0 {
- return nil, fmt.Errorf("no frames to encode")
+ return fmt.Errorf("no frames to encode")
}
lw := &limitedWriter{w: outFile, max: int64(maxOutputBytes)}
if err := gif.EncodeAll(lw, g); err != nil {
- return nil, fmt.Errorf("gif encode: %w", err)
+ return fmt.Errorf("gif encode: %w", err)
}
- _ = outFile.Close()
-
- return readFileCapped(outPath, maxOutputBytes)
+ return outFile.Close()
}
-func encodeFFmpeg(ctx context.Context, tmpDir, format string, fps int, scale float64, codec string, extraArgs ...string) ([]byte, error) {
- outFile := filepath.Join(tmpDir, "output."+format)
-
+func encodeFFmpegToFile(ctx context.Context, tmpDir, outputPath, format string, fps int, scale float64, codec string, extraArgs ...string) error {
args := []string{
"-y",
"-framerate", strconv.Itoa(fps),
@@ -440,27 +504,15 @@ func encodeFFmpeg(ctx context.Context, tmpDir, format string, fps int, scale flo
args = append(args, "-c:v", codec)
args = append(args, extraArgs...)
args = append(args, "-fs", strconv.Itoa(maxOutputBytes))
- args = append(args, outFile)
+ args = append(args, outputPath)
cmd := exec.CommandContext(ctx, "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 fmt.Errorf("ffmpeg encode: %w\n%s", err, stderr.String())
}
-
- return readFileCapped(outFile, maxOutputBytes)
-}
-
-func readFileCapped(path string, maxBytes int) ([]byte, error) {
- info, err := os.Stat(path)
- if err != nil {
- return nil, err
- }
- if info.Size() > int64(maxBytes) {
- return nil, fmt.Errorf("encoded output too large (%d bytes, max %d)", info.Size(), maxBytes)
- }
- return os.ReadFile(path)
+ return nil
}
func scaleImage(src image.Image, scale float64) image.Image {
@@ -584,38 +636,36 @@ func (h *Handlers) HandleRecordStart(w http.ResponseWriter, r *http.Request) {
})
}
-// HandleRecordStop stops the active recording and returns the encoded binary
-// file directly (not JSON). The Content-Type is set to the appropriate media
-// type (image/gif, video/webm, video/mp4). This endpoint is fundamentally
-// different from most other API endpoints which return JSON.
+// HandleRecordStop stops the active recording. Encoding runs in the background;
+// this endpoint returns immediately with a JSON status so callers are not
+// blocked. Use /record/status to check encoding progress.
func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {
- // Encoding can exceed the default WriteTimeout; extend the deadline.
- rc := http.NewResponseController(w)
- _ = rc.SetWriteDeadline(time.Now().Add(encodeTimeout + 30*time.Second))
+ var req struct {
+ OutputPath string `json:"outputPath"`
+ }
+ _ = httpx.DecodeJSONBody(w, r, 0, &req)
+
+ if req.OutputPath == "" {
+ httpx.ErrorCode(w, 400, "missing_output_path", "outputPath is required — the encoded file will be written there", false, nil)
+ return
+ }
owner := authenticatedOwner(r)
- data, format, err := h.recorder.stop(owner)
+ result, err := h.recorder.stop(owner, req.OutputPath)
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)
+ slog.Info("recording stopped, encoding in background",
+ "format", result.Format, "frames", result.Frames, "path", result.OutputPath)
+ httpx.JSON(w, 200, map[string]any{
+ "status": "encoding",
+ "path": result.OutputPath,
+ "format": result.Format,
+ "frames": result.Frames,
+ "hint": fmt.Sprintf("Encoding %d frames to %s. Use `record status` to check progress — the file will appear at the path once encoding completes.", result.Frames, result.OutputPath),
+ })
}
// HandleRecordStatus returns the current recording status.
diff --git a/internal/handlers/record_test.go b/internal/handlers/record_test.go
index 5acebbdf..0532b2b2 100644
--- a/internal/handlers/record_test.go
+++ b/internal/handlers/record_test.go
@@ -101,7 +101,7 @@ func TestRecorderStart_AlreadyRecording(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
- _, _, _ = rec.stop("")
+ _, _ = rec.stop("", "")
}
func TestHandleRecordStop_NoRecording(t *testing.T) {
@@ -167,7 +167,7 @@ func TestRecorderStatus_Active(t *testing.T) {
t.Errorf("expected tabId=tab1, got %q", status.TabID)
}
- _, _, _ = rec.stop("")
+ _, _ = rec.stop("", "")
}
func TestHandleRecordStart_ClampsInputs(t *testing.T) {
@@ -204,12 +204,12 @@ func TestRecorderStop_OwnerMismatch(t *testing.T) {
t.Fatal(err)
}
- _, _, err := rec.stop("agent-2")
+ _, err := rec.stop("agent-2", "")
if err == nil || err.Error() != "recording owned by another session" {
t.Errorf("expected owner mismatch error, got %v", err)
}
- _, _, _ = rec.stop("agent-1")
+ _, _ = rec.stop("agent-1", "")
}
func TestRecorderStop_OwnerMatch(t *testing.T) {
@@ -222,7 +222,7 @@ func TestRecorderStop_OwnerMatch(t *testing.T) {
}
// Gets past owner check; fails with "no frames captured" which is expected
- _, _, err := rec.stop("agent-1")
+ _, err := rec.stop("agent-1", "")
if err == nil || err.Error() != "no frames captured" {
t.Errorf("expected 'no frames captured' error, got %v", err)
}
@@ -237,7 +237,7 @@ func TestRecorderStop_NoOwnerCanStopAnonymous(t *testing.T) {
t.Fatal(err)
}
- _, _, err := rec.stop("any-agent")
+ _, err := rec.stop("any-agent", "")
if err == nil || err.Error() != "no frames captured" {
t.Errorf("expected 'no frames captured', got %v", err)
}
@@ -301,7 +301,7 @@ func TestRecorderStatus_IdleAfterStop(t *testing.T) {
t.Fatalf("start: %v", err)
}
- _, _, _ = rec.stop("")
+ _, _ = rec.stop("", "")
status := rec.status()
if status.Active {
diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.go
index bfd5b01d..febdd844 100644
--- a/internal/mcp/handlers_record.go
+++ b/internal/mcp/handlers_record.go
@@ -6,7 +6,6 @@ import (
"io"
"os"
"path/filepath"
- "time"
"github.com/mark3labs/mcp-go/mcp"
)
@@ -15,10 +14,6 @@ import (
// unbounded disk writes (matches the server-side maxOutputBytes).
const maxRecordFileBytes = 256 << 20 // 256 MiB
-// recordStopTimeout matches the server-side encodeTimeout (2m) plus the
-// write-deadline extension (30s), with headroom for network transfer.
-const recordStopTimeout = 3 * time.Minute
-
func handleRecordStart(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
file, err := r.RequireString("file")
@@ -66,8 +61,6 @@ func handleRecordStart(c *Client) func(context.Context, mcp.CallToolRequest) (*m
}
func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- long := c.withTimeout(recordStopTimeout)
-
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
file := optString(r, "file")
if file == "" {
@@ -76,42 +69,25 @@ func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
dest, pathErr := safeRecordPath(file)
if pathErr != nil {
- // Path is invalid, but a recording may be active server-side.
- // Stop it so we don't leave it dangling.
- stopBody, stopCode, stopErr := long.PostStream(ctx, "/record/stop", map[string]any{})
- if stopErr == nil {
- _ = stopBody.Close()
- }
+ _, _, stopErr := c.Post(ctx, "/record/stop", map[string]any{})
msg := fmt.Sprintf("invalid output path: %v", pathErr)
if stopErr != nil {
msg += fmt.Sprintf(" (also failed to stop recording: %v)", stopErr)
- } else if stopCode >= 400 {
- msg += fmt.Sprintf(" (recording stop returned HTTP %d)", stopCode)
}
return mcp.NewToolResultError(msg), nil
}
- body, code, err := long.PostStream(ctx, "/record/stop", map[string]any{})
+ body, code, err := c.Post(ctx, "/record/stop", map[string]any{
+ "outputPath": dest,
+ })
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
- defer func() { _ = body.Close() }()
-
if code >= 400 {
- errBody, _ := io.ReadAll(io.LimitReader(body, 10<<20))
- return resultFromBytes(errBody, code)
+ return resultFromBytes(body, code)
}
- n, err := streamToFile(dest, body)
- if err != nil {
- return mcp.NewToolResultError(fmt.Sprintf("write file: %v", err)), nil
- }
-
- return jsonResult(map[string]any{
- "status": "saved",
- "file": dest,
- "bytes": n,
- })
+ return resultFromBytes(body, code)
}
}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 67b2a8a0..ffbd63ec 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -45,7 +45,6 @@ type Orchestrator struct {
runner HostRunner
mu sync.RWMutex
client *http.Client
- longClient *http.Client // for routes that can take minutes (e.g. record/stop encoding)
childAuthToken string
allowEvaluate bool
internalToken string
@@ -171,7 +170,6 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator
// - Short timeout (<5s) would break first-request scenarios
// See: internal/orchestrator/health.go (monitor), internal/bridge/init.go (InitChrome)
client: &http.Client{Timeout: 60 * time.Second},
- longClient: &http.Client{Timeout: 3 * time.Minute},
childAuthToken: "",
allowEvaluate: false,
internalToken: generateInternalToken(),
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 09e092a3..98a56d29 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -114,20 +114,10 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
o.proxyToURL(w, r, targetURL)
}
-// proxyClientForPath returns the HTTP client to use for the given request path.
-// Encoding-heavy routes like /record/stop get a longer timeout.
-func (o *Orchestrator) proxyClientForPath(path string) *http.Client {
- if strings.HasSuffix(path, "/record/stop") {
- return o.longClient
- }
- return o.client
-}
-
// proxyToURL proxies an HTTP request to the given target URL.
func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetURL *url.URL) {
- client := o.proxyClientForPath(r.URL.Path)
iproxy.Forward(w, r, targetURL, iproxy.Options{
- Client: client,
+ Client: o.client,
AllowedURL: func(u *url.URL) bool {
return o.proxyTargetInstance(u) != nil
},
diff --git a/tests/e2e/scenarios/api/recording-smoke.sh b/tests/e2e/scenarios/api/recording-smoke.sh
index 7f480872..834cca44 100755
--- a/tests/e2e/scenarios/api/recording-smoke.sh
+++ b/tests/e2e/scenarios/api/recording-smoke.sh
@@ -30,21 +30,31 @@ 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)"
+pt_post /record/stop -d '{"outputPath":"/tmp/e2e-recording-test.gif"}'
+assert_ok "record stop"
+assert_json_eq "$RESULT" ".status" "encoding" "stop returns encoding status"
+
+# Poll /record/status until encoding completes (state transitions to "finished")
+ENCODE_OK=false
+for i in $(seq 1 60); do
+ pt_get /record/status >/dev/null 2>&1
+ STATE=$(echo "$RESULT" | jq -r '.state // empty')
+ if [ "$STATE" = "finished" ]; then
+ ENCODE_OK=true
+ break
+ fi
+ if [ "$STATE" = "idle" ]; then
+ ENCODE_OK=true
+ break
+ fi
+ sleep 1
+done
+
+if [ "$ENCODE_OK" = "true" ]; then
+ pass_assert "encoding completed (state=$STATE)"
else
- fail_assert "recording file missing or empty"
+ fail_assert "encoding did not complete within timeout (state=$STATE)"
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
@@ -65,10 +75,12 @@ assert_ok "navigate for double stop"
pt_post /record/start -d '{"format":"gif","fps":2,"quality":60}'
assert_ok "start for double stop"
-e2e_curl -s -X POST "${E2E_SERVER}/record/stop" -o /dev/null \
- -H "Content-Type: application/json" -d '{}'
+sleep 2
-pt_post /record/stop -d '{}'
+pt_post /record/stop -d '{"outputPath":"/tmp/e2e-recording-double-stop.gif"}'
+assert_ok "first stop"
+
+pt_post /record/stop -d '{"outputPath":"/tmp/e2e-recording-double-stop2.gif"}'
assert_http_status 400 "second stop returns error"
end_test