High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the five CLI auto-named output files still collide within one second (PIN-158)
Luigi Agosti7bd57a775cd0
diff --git a/internal/cli/actions/actions_capture.go b/internal/cli/actions/actions_capture.goindex fa3780e4..9550b537 100644--- a/internal/cli/actions/actions_capture.go+++ b/internal/cli/actions/actions_capture.go@@ -6,7 +6,6 @@ import ("fmt""net/http""net/url"- "os""strings""time"@@ -87,7 +86,8 @@ func Capture(client *http.Client, base, token string, cmd *cobra.Command) {writeImage := !jsonOutput || outFileExplicitvar img []byteif writeImage {- if outFile == "" {+ autoNamed := outFile == ""+ if autoNamed {outFile = fmt.Sprintf("capture-%s%s", time.Now().Format("20060102-150405"), ext)}decoded, err := base64.StdEncoding.DecodeString(resp.Image.Base64)@@ -96,10 +96,12 @@ func Capture(client *http.Client, base, token string, cmd *cobra.Command) {return}img = decoded- if err := os.WriteFile(outFile, img, 0600); err != nil {+ saved, err := writeOutputFile(outFile, autoNamed, img)+ if err != nil {output.Error("capture", fmt.Sprintf("write image: %v", err), output.ExitRuntime)return}+ outFile = saved}if jsonOutput {diff --git a/internal/cli/actions/actions_pdf.go b/internal/cli/actions/actions_pdf.goindex 4de47f6c..e3251bf2 100644--- a/internal/cli/actions/actions_pdf.go+++ b/internal/cli/actions/actions_pdf.go@@ -4,7 +4,6 @@ import ("fmt""net/http""net/url"- "os""time""github.com/pinchtab/pinchtab/internal/cli"@@ -72,7 +71,8 @@ func PDF(client *http.Client, base, token string, cmd *cobra.Command) {params.Set("path", v)}- if outFile == "" {+ autoNamed := outFile == ""+ if autoNamed {outFile = fmt.Sprintf("page-%s.pdf", time.Now().Format("20060102-150405"))}@@ -85,8 +85,9 @@ func PDF(client *http.Client, base, token string, cmd *cobra.Command) {if data == nil {return}- if err := os.WriteFile(outFile, data, 0600); err != nil {+ saved, err := writeOutputFile(outFile, autoNamed, data)+ if err != nil {cli.Fatal("Write failed: %v", err)}- fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", saved, len(data))))}diff --git a/internal/cli/actions/actions_record.go b/internal/cli/actions/actions_record.goindex cd7776fa..a4e3ca99 100644--- a/internal/cli/actions/actions_record.go+++ b/internal/cli/actions/actions_record.go@@ -13,6 +13,7 @@ import ("github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/fileout""github.com/pinchtab/pinchtab/internal/readiness""github.com/spf13/cobra")@@ -56,7 +57,8 @@ func RecordStart(client *http.Client, base, token string, cmd *cobra.Command, arfunc RecordStop(client *http.Client, base, token string) {outFile := readRecordingState()- if outFile == "" {+ autoNamed := outFile == ""+ if autoNamed {outFile = fmt.Sprintf("recording-%s.gif", time.Now().Format("20060102-150405"))}@@ -118,7 +120,22 @@ func RecordStop(client *http.Client, base, token string) {}}+ // The bytes are already on disk under the server's own name, so this site reserves+ // rather than writes: the exclusive create claims the name, and the rename replaces+ // our own placeholder atomically. Reserved here rather than where the name is built+ // so a run that never gets this far leaves nothing behind, and released below if the+ // rename fails — an abandoned reservation is an empty file wearing an output's name.+ if autoNamed {+ reserved, err := fileout.ReservePath(outFile)+ if err != nil {+ cli.Fatal("Failed to reserve %s: %v", outFile, err)+ }+ outFile = reserved+ }if err := os.Rename(serverPath, outFile); err != nil {+ if autoNamed {+ _ = os.Remove(outFile)+ }cli.Fatal("Failed to move %s → %s: %v", serverPath, outFile, err)}fmt.Println(cli.StyleStdout(cli.SuccessStyle,diff --git a/internal/cli/actions/actions_screenshot.go b/internal/cli/actions/actions_screenshot.goindex bbe04d7c..7da29d4b 100644--- a/internal/cli/actions/actions_screenshot.go+++ b/internal/cli/actions/actions_screenshot.go@@ -6,7 +6,6 @@ import ("fmt""net/http""net/url"- "os""time""github.com/pinchtab/pinchtab/internal/cli"@@ -88,13 +87,15 @@ func Screenshot(client *http.Client, base, token string, cmd *cobra.Command) {if err != nil {cli.Fatal("Decode image: %v", err)}- if outFile == "" {+ autoNamed := outFile == ""+ if autoNamed {outFile = fmt.Sprintf("screenshot-%s%s", time.Now().Format("20060102-150405"), ext)}- if err := os.WriteFile(outFile, img, 0600); err != nil {+ saved, err := writeOutputFile(outFile, autoNamed, img)+ if err != nil {cli.Fatal("Write failed: %v", err)}- fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(img))))+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", saved, len(img))))// Print a human-readable legend so the operator can correlate visual// labels with refs at a glance. The bracketed number must match what// the overlay draws (the numeric portion of the ref) — using i+1@@ -115,15 +116,17 @@ func Screenshot(client *http.Client, base, token string, cmd *cobra.Command) {}params.Set("raw", "true")- if outFile == "" {+ autoNamed := outFile == ""+ if autoNamed {outFile = fmt.Sprintf("screenshot-%s%s", time.Now().Format("20060102-150405"), ext)}data := apiclient.DoGetRaw(client, base, token, "/screenshot", params)if data == nil {return}- if err := os.WriteFile(outFile, data, 0600); err != nil {+ saved, err := writeOutputFile(outFile, autoNamed, data)+ if err != nil {cli.Fatal("Write failed: %v", err)}- fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", saved, len(data))))}diff --git a/internal/cli/actions/output_file.go b/internal/cli/actions/output_file.gonew file mode 100644index 00000000..3638463a--- /dev/null+++ b/internal/cli/actions/output_file.go@@ -0,0 +1,24 @@+package actions++import (+ "os"++ "github.com/pinchtab/pinchtab/internal/fileout"+)++// writeOutputFile writes buf to path and returns the path actually used.+//+// An auto-named path is reserved with an exclusive create, so a second run in the same+// second gets capture-<ts>-1.jpg rather than destroying the first file. The returned+// path is what the caller must print: it may carry a suffix the caller did not build,+// and printing the built name instead trades a silent overwrite for a confidently+// reported filename that does not exist.+//+// An explicit path is written as the user typed it, overwrite included — that is their+// instruction, not a collision.+func writeOutputFile(path string, autoNamed bool, buf []byte) (string, error) {+ if autoNamed {+ return fileout.WriteUniquePath(path, buf)+ }+ return path, os.WriteFile(path, buf, 0600)+}diff --git a/internal/cli/actions/output_file_test.go b/internal/cli/actions/output_file_test.gonew file mode 100644index 00000000..89ef4001--- /dev/null+++ b/internal/cli/actions/output_file_test.go@@ -0,0 +1,397 @@+package actions++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++// Every auto-named CLI output builds its name from a second-resolution timestamp, so+// two runs in one second used to land on one path and the first file was destroyed —+// silently, while the command printed that path as if it held the new bytes. Driven+// through the real commands rather than the helper, because the defect was as much in+// what each site PRINTS as in what it writes.+func TestTwoRunsInOneSecondKeepBothFilesAndPrintTheNameEachUsed(t *testing.T) {+ for _, tc := range []struct {+ name string+ prefix string+ ext string+ run func(t *testing.T) string+ }{+ {+ name: "capture",+ prefix: "capture-",+ ext: ".jpg",+ run: func(t *testing.T) string {+ m := newMockServer()+ defer m.close()+ m.response = `{"status":"ok","image":{"format":"jpeg","base64":"aW1n"}}`+ cmd := captureCmd()+ return captureStdout(t, func() { Capture(m.server.Client(), m.base(), "", cmd) })+ },+ },+ {+ name: "pdf",+ prefix: "page-",+ ext: ".pdf",+ run: func(t *testing.T) string {+ m := newMockServer()+ defer m.close()+ m.response = "%PDF-1.4 fake"+ cmd := pdfCmd()+ return captureStdout(t, func() { PDF(m.server.Client(), m.base(), "", cmd) })+ },+ },+ {+ name: "screenshot",+ prefix: "screenshot-",+ ext: ".jpg",+ run: func(t *testing.T) string {+ m := newMockServer()+ defer m.close()+ m.response = "rawimagebytes"+ cmd := screenshotCmd()+ return captureStdout(t, func() { Screenshot(m.server.Client(), m.base(), "", cmd) })+ },+ },+ {+ name: "screenshot --annotate",+ prefix: "screenshot-",+ ext: ".jpg",+ run: func(t *testing.T) string {+ m := newMockServer()+ defer m.close()+ m.response = `{"format":"jpeg","base64":"aW1n","annotations":[]}`+ cmd := screenshotCmd()+ _ = cmd.Flags().Set("annotate", "true")+ return captureStdout(t, func() { Screenshot(m.server.Client(), m.base(), "", cmd) })+ },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ dir := chdirTemp(t)++ firstOut := tc.run(t)+ secondOut := tc.run(t)++ written := autoNamedFiles(t, dir, tc.prefix, tc.ext)+ if len(written) != 2 {+ t.Fatalf("two runs left %v; the second overwrote the first", written)+ }+ for _, name := range written {+ if info, err := os.Stat(filepath.Join(dir, name)); err != nil || info.Size() == 0 {+ t.Errorf("%s is missing or empty: %v", name, err)+ }+ }++ // Each run must print the path it actually used, so the two printed names are+ // distinct and both are on disk. Printing the name each run BUILT would have+ // them print one identical name — the file the second run did not write.+ printed := []string{+ printedName(t, firstOut, tc.prefix, tc.ext),+ printedName(t, secondOut, tc.prefix, tc.ext),+ }+ if printed[0] == printed[1] {+ t.Fatalf("both runs printed %s, but two different files were written (%v)", printed[0], written)+ }+ onDisk := map[string]bool{written[0]: true, written[1]: true}+ var suffixed int+ for i, name := range printed {+ if !onDisk[name] {+ t.Errorf("run %d printed %s, which is not one of the files written (%v)", i, name, written)+ }+ if strings.HasSuffix(strings.TrimSuffix(name, tc.ext), "-1") {+ suffixed+++ }+ }+ if suffixed != 1 {+ t.Errorf("printed names %v carry %d collision suffixes, want exactly one", printed, suffixed)+ }+ })+ }+}++// The boundary the parent card pinned: a path the user typed is written as they typed+// it. Overwriting there is their instruction, not a collision to resolve — and a+// suffixed name would break a script that goes on to read the path it passed.+func TestAnExplicitOutputPathStillOverwrites(t *testing.T) {+ dir := chdirTemp(t)+ target := filepath.Join(dir, "chosen.jpg")+ if err := os.WriteFile(target, []byte("stale bytes from an earlier run"), 0600); err != nil {+ t.Fatal(err)+ }++ m := newMockServer()+ defer m.close()+ m.response = `{"status":"ok","image":{"format":"jpeg","base64":"aW1n"}}`+ cmd := captureCmd()+ _ = cmd.Flags().Set("output", target)++ captureStdout(t, func() { Capture(m.server.Client(), m.base(), "", cmd) })++ got, err := os.ReadFile(target) // #nosec G304 -- path built by this test.+ if err != nil {+ t.Fatal(err)+ }+ if string(got) != "img" {+ t.Errorf("explicit path holds %q, want the new bytes", got)+ }+ if extra := autoNamedFiles(t, dir, "chosen", ".jpg"); len(extra) != 1 {+ t.Errorf("explicit path produced %v; it must not gain a suffix", extra)+ }+}++// The census: every auto-naming site in this package must reach the exclusive create.+// A survivor is either a caller-supplied path or named here as deliberate, so a sixth+// site cannot land silently the way these five did.+func TestNoCLIActionAutoNamesAFileItThenOverwrites(t *testing.T) {+ entries, err := os.ReadDir(".")+ if err != nil {+ t.Fatal(err)+ }++ // file -> the call that reserves the name it builds.+ accounted := map[string]string{+ "actions_capture.go": "writeOutputFile with autoNamed",+ "actions_pdf.go": "writeOutputFile with autoNamed",+ "actions_screenshot.go": "writeOutputFile with autoNamed",+ "actions_record.go": "fileout.ReservePath before the rename",+ }++ var scanned, withTimestamp int+ for _, entry := range entries {+ name := entry.Name()+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ continue+ }+ body, err := os.ReadFile(name) // #nosec G304 -- files listed from this package's own directory.+ if err != nil {+ t.Fatal(err)+ }+ scanned+++ if !strings.Contains(string(body), "150405") {+ continue+ }+ withTimestamp+++ if accounted[name] == "" {+ t.Errorf("%s builds a name from a second-resolution timestamp and is not accounted for; route it through writeOutputFile or fileout, or record why it cannot collide", name)+ }+ }++ if scanned < len(accounted) {+ t.Fatalf("scanned %d files in this package; this census would pass vacuously", scanned)+ }+ if withTimestamp != len(accounted) {+ t.Errorf("found %d auto-naming files but %d are accounted for; a stale entry hides a site that no longer reserves", withTimestamp, len(accounted))+ }+ for name := range accounted {+ if _, err := os.Stat(name); err != nil {+ t.Errorf("accounted file %s no longer exists; the census is guarding nothing", name)+ }+ }+}++// printedName pulls the output filename out of whatever sentence a site wraps it in —+// each of the four phrases it differently, and the assertion is about the name.+func printedName(t *testing.T, out, prefix, ext string) string {+ t.Helper()+ for _, field := range strings.Fields(out) {+ // record prints an absolute path, the other four a bare name; the assertion is+ // about which file was named, so compare the basename either way.+ if name := filepath.Base(field); strings.HasPrefix(name, prefix) && strings.HasSuffix(name, ext) {+ return name+ }+ }+ t.Fatalf("output %q names no %s*%s file", strings.TrimSpace(out), prefix, ext)+ return ""+}++func chdirTemp(t *testing.T) string {+ t.Helper()+ dir := t.TempDir()+ t.Chdir(dir)+ // t.TempDir can hand back a symlinked path (/var vs /private/var on darwin), which+ // would make the printed path and the listed name disagree for reasons unrelated to+ // the guard.+ resolved, err := filepath.EvalSymlinks(dir)+ if err != nil {+ t.Fatal(err)+ }+ return resolved+}++func autoNamedFiles(t *testing.T, dir, prefix, ext string) []string {+ t.Helper()+ entries, err := os.ReadDir(dir)+ if err != nil {+ t.Fatal(err)+ }+ var names []string+ for _, entry := range entries {+ if strings.HasPrefix(entry.Name(), prefix) && strings.HasSuffix(entry.Name(), ext) {+ names = append(names, entry.Name())+ }+ }+ return names+}++func captureCmd() *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("output", "", "")+ cmd.Flags().Bool("json", false, "")+ cmd.Flags().String("format", "", "")+ cmd.Flags().String("quality", "", "")+ cmd.Flags().String("selector", "", "")+ cmd.Flags().String("filter", "", "")+ cmd.Flags().String("depth", "", "")+ cmd.Flags().String("wait", "", "")+ cmd.Flags().Bool("beyond-viewport", false, "")+ cmd.Flags().String("scale", "", "")+ cmd.Flags().Bool("require-pair", false, "")+ cmd.Flags().Bool("with-bounds", true, "")+ cmd.Flags().String("tab", "", "")+ return cmd+}++func pdfCmd() *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("output", "", "")+ cmd.Flags().String("tab", "", "")+ cmd.Flags().Bool("landscape", false, "")+ cmd.Flags().String("scale", "", "")+ cmd.Flags().String("paper-width", "", "")+ cmd.Flags().String("paper-height", "", "")+ cmd.Flags().String("margin-top", "", "")+ cmd.Flags().String("margin-bottom", "", "")+ cmd.Flags().String("margin-left", "", "")+ cmd.Flags().String("margin-right", "", "")+ cmd.Flags().String("page-ranges", "", "")+ cmd.Flags().Bool("prefer-css-page-size", false, "")+ cmd.Flags().Bool("display-header-footer", false, "")+ cmd.Flags().String("header-template", "", "")+ cmd.Flags().String("footer-template", "", "")+ cmd.Flags().Bool("generate-tagged-pdf", false, "")+ cmd.Flags().Bool("generate-document-outline", false, "")+ cmd.Flags().Bool("file-output", false, "")+ cmd.Flags().String("path", "", "")+ return cmd+}++func screenshotCmd() *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("output", "", "")+ cmd.Flags().Bool("annotate", false, "")+ cmd.Flags().String("format", "", "")+ cmd.Flags().String("quality", "", "")+ cmd.Flags().String("selector", "", "")+ cmd.Flags().String("scale", "", "")+ cmd.Flags().Bool("beyond-viewport", false, "")+ cmd.Flags().String("tab", "", "")+ return cmd+}++// The record site cannot use the writer form: the bytes are already on disk under the+// server's name, so it reserves and renames. Two stops in one second must therefore+// still keep both recordings and print the name each one took.+func TestTwoRecordStopsInOneSecondKeepBothRecordings(t *testing.T) {+ dir := chdirTemp(t)+ t.Setenv("XDG_STATE_HOME", filepath.Join(dir, "state"))++ stop := func(encoded string) string {+ serverPath := filepath.Join(dir, encoded)+ if err := os.WriteFile(serverPath, []byte("encoded "+encoded), 0600); err != nil {+ t.Fatal(err)+ }+ m := newMockServer()+ defer m.close()+ m.setResponse("POST", "/record/stop", 200, `{"status":"ok","path":"`+serverPath+`","frames":3}`)+ m.setResponse("GET", "/record/status", 200, `{"state":"finished"}`)+ return captureStdout(t, func() { RecordStop(m.server.Client(), m.base(), "") })+ }++ firstOut := stop("srv-a.gif")+ secondOut := stop("srv-b.gif")++ written := autoNamedFiles(t, dir, "recording-", ".gif")+ if len(written) != 2 {+ t.Fatalf("two stops left %v; the second rename destroyed the first recording", written)+ }+ for _, name := range written {+ assertNonEmpty(t, filepath.Join(dir, name))+ }++ first := printedName(t, firstOut, "recording-", ".gif")+ second := printedName(t, secondOut, "recording-", ".gif")+ if first == second {+ t.Fatalf("both stops reported %s, but two files were written (%v)", first, written)+ }+ if !strings.HasSuffix(strings.TrimSuffix(second, ".gif"), "-1") {+ t.Errorf("second stop reported %s, want the collision suffix it actually used", second)+ }+}++// A reservation is a side effect: the name is claimed before the rename, so a rename+// that fails must release it rather than leave an empty file wearing an output's name —+// zero bytes under recording-<ts>.gif reads as a recording that was made.+//+// Driven in a child process because the failure path is cli.Fatal, which calls os.Exit.+func TestAFailedRenameReleasesTheReservation(t *testing.T) {+ if dir := os.Getenv(recordFatalChildEnv); dir != "" {+ runFailedRenameChild(dir)+ return+ }++ dir := t.TempDir()+ child := exec.Command(os.Args[0], "-test.run=TestAFailedRenameReleasesTheReservation", "-test.timeout=60s") // #nosec G204 -- re-executes this test binary.+ child.Env = append(os.Environ(), recordFatalChildEnv+"="+dir)+ raw, err := child.CombinedOutput()++ var exitErr *exec.ExitError+ if !errors.As(err, &exitErr) {+ t.Fatalf("child exited with %v, want the failed rename's os.Exit(1); output:\n%s", err, raw)+ }+ if left := autoNamedFiles(t, dir, "recording-", ".gif"); len(left) != 0 {+ t.Errorf("the failed stop left %v behind; an abandoned reservation is an empty file wearing an output's name", left)+ }+}++const recordFatalChildEnv = "PINCHTAB_TEST_RECORD_FATAL_DIR"++func runFailedRenameChild(dir string) {+ if err := os.Chdir(dir); err != nil {+ panic(err)+ }+ if err := os.Setenv("XDG_STATE_HOME", filepath.Join(dir, "state")); err != nil {+ panic(err)+ }++ missing := filepath.Join(dir, "never-encoded.gif")+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/record/stop" {+ _, _ = w.Write([]byte(`{"status":"ok","path":"` + missing + `","frames":3}`))+ return+ }+ _, _ = w.Write([]byte(`{"state":"finished"}`))+ }))+ defer srv.Close()++ RecordStop(srv.Client(), srv.URL, "")+}++func assertNonEmpty(t *testing.T, path string) {+ t.Helper()+ info, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ if info.Size() == 0 {+ t.Errorf("%s is empty", path)+ }+}diff --git a/internal/fileout/fileout.go b/internal/fileout/fileout.gonew file mode 100644index 00000000..0cff19c4--- /dev/null+++ b/internal/fileout/fileout.go@@ -0,0 +1,110 @@+// Package fileout owns the no-overwrite rule for auto-named output files.+//+// Every auto-naming writer in this repo builds a name from a SECOND-resolution+// timestamp, so two outputs in the same second land on one path and the first is+// destroyed while the caller still reports that path and its byte count. Widening+// the timestamp only shrinks the window — two concurrent writers can share a+// millisecond — so the guarantee has to come from the create call itself.+//+// It lives here rather than in internal/handlers because the rule has two consumers+// that cannot import each other: the HTTP handlers and internal/cli/actions. A leaf+// depending only on the standard library is what both can reach. None of the existing+// shared packages owns filesystem output, and putting file creation in a sanitiser or+// an id generator would trade one small package for a responsibility violation.+//+// The boundary is generated default names only. A path the user typed is written as+// they typed it, overwrite included — that is their instruction, not a collision.+package fileout++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"+)++// MaxUniqueNameAttempts bounds the suffix search. A directory holding this many files+// named for the same second is a runaway caller, not a collision to resolve.+const MaxUniqueNameAttempts = 512++// CreateUnique reserves a path under dir by CREATING it exclusively, bumping a numeric+// suffix until the create succeeds: base+ext, then base-1+ext, base-2+ext…+// It returns the open handle, so the name cannot be taken between the check and the+// write — which is the whole point, and why this is not a stat-then-write.+//+// The caller owns the base name, including its timestamp format, so this closes the+// collision without renaming anything a user might already be globbing for. The+// returned path is authoritative: it may carry a suffix the caller did not ask for,+// and reporting the name that was built instead trades a silent overwrite for a+// confidently printed filename that does not exist.+func CreateUnique(dir, base, ext string) (*os.File, string, error) {+ for attempt := 0; attempt < MaxUniqueNameAttempts; attempt++ {+ name := base + ext+ if attempt > 0 {+ name = fmt.Sprintf("%s-%d%s", base, attempt, ext)+ }+ path := filepath.Join(dir, name)+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)+ if err == nil {+ return f, path, nil+ }+ if !os.IsExist(err) {+ return nil, "", err+ }+ }+ return nil, "", fmt.Errorf("could not find a free name for %s%s in %s after %d attempts", base, ext, dir, MaxUniqueNameAttempts)+}++// WriteUnique creates a fresh file under dir and writes buf to it, returning the path+// actually used.+func WriteUnique(dir, base, ext string, buf []byte) (string, error) {+ f, path, err := CreateUnique(dir, base, ext)+ if err != nil {+ return "", err+ }+ if _, err := f.Write(buf); err != nil {+ _ = f.Close()+ return "", err+ }+ if err := f.Close(); err != nil {+ return "", err+ }+ return path, nil+}++// WriteUniquePath is WriteUnique for a caller holding a whole path rather than its+// three parts, which is the shape every CLI site has.+func WriteUniquePath(path string, buf []byte) (string, error) {+ dir, base, ext := splitPath(path)+ return WriteUnique(dir, base, ext, buf)+}++// ReservePath claims a path for a caller that will not write the bytes itself — one+// moving an already-written file into place with os.Rename. The placeholder is created+// exclusively and closed, and the rename then replaces it atomically on POSIX, so the+// reservation is what stops a second process taking the name in between.+//+// A reservation is a side effect: every path that then gives up must Remove the+// returned path, or an abandoned run litters an empty file under a name that reads+// like a real output.+func ReservePath(path string) (string, error) {+ dir, base, ext := splitPath(path)+ f, reserved, err := CreateUnique(dir, base, ext)+ if err != nil {+ return "", err+ }+ if err := f.Close(); err != nil {+ _ = os.Remove(reserved)+ return "", err+ }+ return reserved, nil+}++// splitPath cuts a path into the three parts CreateUnique numbers, so the suffix lands+// before the extension (capture-<ts>-1.jpg) rather than after it.+func splitPath(path string) (dir, base, ext string) {+ dir = filepath.Dir(path)+ name := filepath.Base(path)+ ext = filepath.Ext(name)+ return dir, strings.TrimSuffix(name, ext), ext+}diff --git a/internal/fileout/fileout_test.go b/internal/fileout/fileout_test.gonew file mode 100644index 00000000..7d57a1c1--- /dev/null+++ b/internal/fileout/fileout_test.go@@ -0,0 +1,132 @@+package fileout++import (+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+)++// Two writes of the same auto-built name must land on different paths with both files+// intact. The name comes from a second-resolution timestamp, so without the exclusive+// create the second write destroys the first.+func TestWritingTheSameNameTwiceKeepsBothFiles(t *testing.T) {+ dir := t.TempDir()+ first := []byte("first payload, deliberately longer than the second")+ second := []byte("second")++ firstPath, err := WriteUnique(dir, "capture-20260101-120000", ".jpg", first)+ if err != nil {+ t.Fatal(err)+ }+ secondPath, err := WriteUnique(dir, "capture-20260101-120000", ".jpg", second)+ if err != nil {+ t.Fatal(err)+ }++ if firstPath == secondPath {+ t.Fatalf("both writes landed on %s; the first file was destroyed", firstPath)+ }+ if got := filepath.Base(secondPath); got != "capture-20260101-120000-1.jpg" {+ t.Errorf("second path = %s, want the suffix before the extension", got)+ }+ assertContents(t, firstPath, first)+ assertContents(t, secondPath, second)+}++// The suffix goes before the extension so the file is still recognised by its type. A+// naive append would produce capture-<ts>.jpg-1, which no image viewer opens.+func TestTheSuffixLandsBeforeTheExtension(t *testing.T) {+ dir := t.TempDir()+ for i, want := range []string{"page-x.pdf", "page-x-1.pdf", "page-x-2.pdf"} {+ got, err := WriteUniquePath(filepath.Join(dir, "page-x.pdf"), []byte("pdf"))+ if err != nil {+ t.Fatal(err)+ }+ if filepath.Base(got) != want {+ t.Errorf("write %d landed on %s, want %s", i, filepath.Base(got), want)+ }+ }+}++// The handle is returned open on purpose: a stat-then-create leaves a window in which a+// second caller takes the name between the check and the write.+func TestTheReservationHoldsTheNameWhileTheFirstHandleIsStillOpen(t *testing.T) {+ dir := t.TempDir()++ first, firstPath, err := CreateUnique(dir, "rec", ".gif")+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = first.Close() }()++ second, secondPath, err := CreateUnique(dir, "rec", ".gif")+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = second.Close() }()++ if firstPath == secondPath {+ t.Fatalf("both reservations returned %s while the first handle was still open", firstPath)+ }+}++// Exhaustion is a refusal, not a fallback to overwriting: a directory holding this many+// files for one second is a runaway caller.+func TestAFullDirectoryIsRefusedRatherThanOverwritten(t *testing.T) {+ dir := t.TempDir()+ for i := 0; i < MaxUniqueNameAttempts; i++ {+ name := "full.bin"+ if i > 0 {+ name = strings.Replace(name, ".bin", "-"+strconv.Itoa(i)+".bin", 1)+ }+ if err := os.WriteFile(filepath.Join(dir, name), []byte("x"), 0600); err != nil {+ t.Fatal(err)+ }+ }+ if _, _, err := CreateUnique(dir, "full", ".bin"); err == nil {+ t.Fatal("CreateUnique succeeded with every name taken; it must refuse rather than overwrite")+ }+}++// ReservePath exists for a caller that renames an already-written file into place. The+// placeholder must hold the name against a second reserver, and a rename over it must+// still land the real bytes.+func TestReservePathHoldsTheNameAndSurvivesARenameOverIt(t *testing.T) {+ dir := t.TempDir()+ target := filepath.Join(dir, "recording-20260101-120000.gif")++ firstReserved, err := ReservePath(target)+ if err != nil {+ t.Fatal(err)+ }+ secondReserved, err := ReservePath(target)+ if err != nil {+ t.Fatal(err)+ }+ if firstReserved == secondReserved {+ t.Fatalf("both reservations returned %s; the placeholder did not hold the name", firstReserved)+ }++ source := filepath.Join(dir, "server-encoded.gif")+ payload := []byte("the encoded recording")+ if err := os.WriteFile(source, payload, 0600); err != nil {+ t.Fatal(err)+ }+ if err := os.Rename(source, firstReserved); err != nil {+ t.Fatalf("rename over our own reservation failed: %v", err)+ }+ assertContents(t, firstReserved, payload)+}++func assertContents(t *testing.T, path string, want []byte) {+ t.Helper()+ got, err := os.ReadFile(path) // #nosec G304 -- path produced by this test.+ if err != nil {+ t.Fatal(err)+ }+ if string(got) != string(want) {+ t.Errorf("%s holds %q, want %q", path, got, want)+ }+}diff --git a/internal/handlers/binary_export.go b/internal/handlers/binary_export.goindex 79641c0d..062373c1 100644--- a/internal/handlers/binary_export.go+++ b/internal/handlers/binary_export.go@@ -1,12 +1,13 @@package handlersimport (- "fmt""log/slog""net/http""os""path/filepath""time"++ "github.com/pinchtab/pinchtab/internal/fileout")// imageContentType maps an image format to its MIME type (jpeg default).@@ -34,63 +35,16 @@ func writeRawImage(w http.ResponseWriter, buf []byte, contentType, logLabel stri}}-// maxUniqueNameAttempts bounds the suffix search. A directory holding this many-// files named for the same second is a runaway caller, not a collision to resolve.-const maxUniqueNameAttempts = 512--// createUniqueFile reserves a path under dir by CREATING it exclusively, bumping a-// numeric suffix until the create succeeds: base+ext, then base-1+ext, base-2+ext…-// It returns the open handle, so the name cannot be taken between the check and the-// write — which is the whole point, and why this is not a stat-then-write.-//-// Every server-side auto-naming writer goes through here. They all built a name from a-// SECOND-resolution timestamp and then wrote it unconditionally, so two outputs in the-// same second landed on one path: the first file was destroyed while its response still-// reported that path, its byte count and its clip rect. Widening the timestamp only-// shrinks the window — two concurrent requests can share a millisecond — so the-// guarantee has to come from the create call itself.-//-// The caller owns the base name, including its timestamp format, so this closes the-// collision without renaming anything a user might already be globbing for.-//-// SCOPE, recorded so it is not mistaken for complete: every auto-naming writer in this-// package routes through here, but the five CLI sites in internal/cli/actions still build-// a name and write it unconditionally. They are deferred to PIN-158 rather than given a-// copy of this loop — a second owner of the rule is the drift worth avoiding, and sharing-// it means moving this primitive down to a leaf package the CLI can import.+// The no-overwrite rule itself lives in internal/fileout, a leaf both this package and+// internal/cli/actions can import — the CLI sites had the same defect and a second copy+// of the loop is the drift worth avoiding. These two keep the names every call site in+// this package already uses, and delegate.func createUniqueFile(dir, base, ext string) (*os.File, string, error) {- for attempt := 0; attempt < maxUniqueNameAttempts; attempt++ {- name := base + ext- if attempt > 0 {- name = fmt.Sprintf("%s-%d%s", base, attempt, ext)- }- path := filepath.Join(dir, name)- f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)- if err == nil {- return f, path, nil- }- if !os.IsExist(err) {- return nil, "", err- }- }- return nil, "", fmt.Errorf("could not find a free name for %s%s in %s after %d attempts", base, ext, dir, maxUniqueNameAttempts)+ return fileout.CreateUnique(dir, base, ext)}-// writeUniqueFile creates a fresh file under dir and writes buf to it, returning the-// path actually used — which may carry a suffix the caller did not ask for.func writeUniqueFile(dir, base, ext string, buf []byte) (string, error) {- f, path, err := createUniqueFile(dir, base, ext)- if err != nil {- return "", err- }- if _, err := f.Write(buf); err != nil {- _ = f.Close()- return "", err- }- if err := f.Close(); err != nil {- return "", err- }- return path, nil+ return fileout.WriteUnique(dir, base, ext, buf)}// exportTimestamp is the second-resolution stamp every auto-named export shares. It isdiff --git a/internal/handlers/binary_export_test.go b/internal/handlers/binary_export_test.goindex ef60a719..bb162e57 100644--- a/internal/handlers/binary_export_test.go+++ b/internal/handlers/binary_export_test.go@@ -13,6 +13,7 @@ import ("github.com/pinchtab/pinchtab/internal/bridge/observe""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/fileout")// Two saves in immediate succession must land on different paths with both files intact.@@ -123,7 +124,7 @@ func TestCreateUniqueFileRefusesRatherThanOverwriteWhenTheLadderIsExhausted(t *t}}occupy(base + ext)- for i := 1; i < maxUniqueNameAttempts; i++ {+ for i := 1; i < fileout.MaxUniqueNameAttempts; i++ {occupy(fmt.Sprintf("%s-%d%s", base, i, ext))}