Skip to content

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

refactor: tab centric pdf api

Luigi Agostia0d58c4fba58
diff --git a/TODO.md b/TODO.md
index 993c3d81..ddc29f73 100644
--- a/TODO.md
+++ b/TODO.md
@@ -92,7 +92,7 @@ POST /tabs/{id}/fingerprint/rotate Rotate fingerprint
❌ POST /instances/{id}/actions → POST /tabs/{id}/actions
❌ GET /instances/{id}/text → GET /tabs/{id}/text
❌ POST /instances/{id}/evaluate → POST /tabs/{id}/evaluate
-❌ GET /instances/{id}/pdf → GET /tabs/{id}/pdf
+✅ PDF endpoint migrated to `GET/POST /tabs/{id}/pdf`
❌ POST /instances/{id}/tab → POST /tabs/new {instanceId}
❌ GET /instances/{id}/tabs → GET /tabs?instanceId={id}
❌ POST /instances/{id}/tab/lock → POST /tabs/{id}/lock
@@ -139,7 +139,7 @@ POST /tabs/{id}/fingerprint/rotate Rotate fingerprint
- `/tabs/{id}/actions` → Extract from `/instances/{id}/actions`
- `/tabs/{id}/text` → Extract from `/instances/{id}/text`
- `/tabs/{id}/evaluate` → Extract from `/instances/{id}/evaluate`
- - `/tabs/{id}/pdf` → Extract from `/instances/{id}/pdf`
+ - `/tabs/{id}/pdf` (implemented)
- `/tabs/{id}/cookies` (GET/POST) → Extract from `/instances/{id}/cookies`
- `/tabs/{id}/lock` → Extract from `/instances/{id}/tab/lock`
- `/tabs/{id}/unlock` → Extract from `/instances/{id}/tab/unlock`
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 5119addd..327cea61 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -42,7 +42,7 @@ CLI COMMANDS:
pinchtab tabs [new <url>|close <id>] Manage tabs
pinchtab ss [-o file] [-q 80] Screenshot
pinchtab eval <expression> Run JavaScript
- pinchtab pdf [-o file] [options] Export page as PDF (see PDF FLAGS)
+ pinchtab pdf --tab <id> [-o file] [options] Export tab as PDF (see PDF FLAGS)
pinchtab instances List running instances
pinchtab profiles List available profiles
pinchtab health Check server status
@@ -737,6 +737,7 @@ func cliPDF(client *http.Client, base, token string, args []string) {
params := url.Values{}
params.Set("raw", "true")
outFile := ""
+ tabID := ""
for i := 0; i < len(args); i++ {
switch args[i] {
case "-o", "--output":
@@ -754,7 +755,7 @@ func cliPDF(client *http.Client, base, token string, args []string) {
case "--tab":
if i+1 < len(args) {
i++
- params.Set("tabId", args[i])
+ tabID = args[i]
}
// Paper dimensions
case "--paper-width":
@@ -831,8 +832,11 @@ func cliPDF(client *http.Client, base, token string, args []string) {
if outFile == "" {
outFile = fmt.Sprintf("page-%s.pdf", time.Now().Format("20060102-150405"))
}
+ if tabID == "" {
+ fatal("tab id required for pdf export: use --tab <tabId> or 'pinchtab tab pdf <tabId>'")
+ }
- data := doGetRaw(client, base, token, "/pdf", params)
+ data := doGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
if data == nil {
return
}
@@ -878,7 +882,7 @@ func cliQuick(client *http.Client, base, token string, args []string) {
fmt.Println(" pinchtab click <ref> # Click an element (use refs from above)")
fmt.Println(" pinchtab type <ref> <text> # Type into input field")
fmt.Println(" pinchtab screenshot # Take a screenshot")
- fmt.Println(" pinchtab pdf -o output.pdf # Save as PDF")
+ fmt.Println(" pinchtab pdf --tab <id> -o output.pdf # Save tab as PDF")
}
// --- health ---
@@ -1205,7 +1209,7 @@ func suggestNextAction(cmd string, result map[string]any) {
fmt.Fprintf(os.Stderr, " pinchtab snap # See page structure\n")
fmt.Fprintf(os.Stderr, " pinchtab screenshot # Capture visual\n")
fmt.Fprintf(os.Stderr, " pinchtab click <ref> # Click an element\n")
- fmt.Fprintf(os.Stderr, " pinchtab pdf -o output.pdf # Save as PDF\n")
+ fmt.Fprintf(os.Stderr, " pinchtab pdf --tab <id> -o output.pdf # Save tab as PDF\n")
case "snap", "snapshot":
refs := extractRefs(result)
diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.go
index d6923191..133824bf 100644
--- a/cmd/pinchtab/cmd_cli_test.go
+++ b/cmd/pinchtab/cmd_cli_test.go
@@ -432,9 +432,9 @@ func TestCLIPDF(t *testing.T) {
client := m.server.Client()
outFile := t.TempDir() + "/test.pdf"
- cliPDF(client, m.base(), "", []string{"-o", outFile, "--landscape", "--scale", "0.8"})
- if m.lastPath != "/pdf" {
- t.Errorf("expected /pdf, got %s", m.lastPath)
+ cliPDF(client, m.base(), "", []string{"-o", outFile, "--tab", "tab-abc", "--landscape", "--scale", "0.8"})
+ if m.lastPath != "/tabs/tab-abc/pdf" {
+ t.Errorf("expected /tabs/tab-abc/pdf, got %s", m.lastPath)
}
if !strings.Contains(m.lastQuery, "landscape=true") {
t.Errorf("expected landscape=true, got %s", m.lastQuery)
@@ -479,6 +479,9 @@ func TestCLIPDFAllOptions(t *testing.T) {
}
cliPDF(client, m.base(), "", args)
+ if m.lastPath != "/tabs/tab-123/pdf" {
+ t.Errorf("expected /tabs/tab-123/pdf, got %s", m.lastPath)
+ }
// Check all parameters were set correctly
expectedParams := []string{
@@ -495,7 +498,6 @@ func TestCLIPDFAllOptions(t *testing.T) {
"displayHeaderFooter=true",
"generateTaggedPDF=true",
"generateDocumentOutline=true",
- "tabId=tab-123",
"raw=true",
}
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 82ac52f1..69974772 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -68,6 +68,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
proxyEndpoints := []string{
"GET /snapshot", "GET /screenshot", "GET /text",
+ "GET /tabs/{tabId}/pdf", "POST /tabs/{tabId}/pdf",
"POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /cookies", "POST /cookies",
diff --git a/docs/get-started.md b/docs/get-started.md
index 4bc336ec..57708fff 100644
--- a/docs/get-started.md
+++ b/docs/get-started.md
@@ -113,8 +113,8 @@ INST=$(pinchtab instance launch | jq -r '.id')
sleep 2
# Navigate
-curl -X POST http://localhost:9867/instances/$INST/navigate \
- -d '{"url":"https://example.com"}'
+TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/navigate \
+ -d '{"url":"https://example.com"}' | jq -r '.tabId')
# Read the page as text
curl http://localhost:9867/instances/$INST/text
@@ -137,7 +137,7 @@ curl "http://localhost:9867/instances/$INST/screenshot?tabId=$TAB_ID" -o page.pn
```bash
# Save PDF
-curl "http://localhost:9867/instances/$INST/pdf?landscape=true" -o output.pdf
+curl "http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf?landscape=true" -o output.pdf
```
### Interact with the Page
@@ -208,8 +208,8 @@ INST=$(pinchtab instance launch | jq -r '.id')
sleep 2
# 2. Navigate to a page
-curl -X POST http://localhost:9867/instances/$INST/navigate \
- -d '{"url":"https://example.com"}'
+TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/navigate \
+ -d '{"url":"https://example.com"}' | jq -r '.tabId')
# 3. Get page structure (see buttons, links, inputs)
curl http://localhost:9867/instances/$INST/snapshot
@@ -223,7 +223,7 @@ curl http://localhost:9867/instances/$INST/snapshot
# 6. Capture result
curl http://localhost:9867/instances/$INST/screenshot -o page.png
-curl http://localhost:9867/instances/$INST/pdf -o report.pdf
+curl "http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf" -o report.pdf
# 7. Stop instance (clean up)
curl -X POST http://localhost:9867/instances/$INST/stop
@@ -525,12 +525,10 @@ curl -X POST http://localhost:9867/instances/$INST/navigate \
INST=$(pinchtab instance launch | jq -r '.id')
sleep 2
-# Navigate to report
-curl -X POST http://localhost:9867/instances/$INST/navigate \
- -d '{"url":"https://reports.example.com/monthly"}'
-
+TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/navigate \
+ -d '{"url":"https://reports.example.com/monthly"}' | jq -r '.tabId')
# Export PDF
-curl "http://localhost:9867/instances/$INST/pdf?landscape=true" -o report.pdf
+curl "http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf?landscape=true" -o report.pdf
```
### Scenario 5: Multi-Tab Workflow
@@ -788,7 +786,7 @@ curl http://localhost:9867/instances/$INST/screenshot # Higher tokens
| Click element | `curl -X POST http://localhost:9867/instances/$INST/action -d '{"kind":"click","ref":"e5"}'` |
| Type text | `curl -X POST http://localhost:9867/instances/$INST/action -d '{"kind":"type","ref":"e3","text":"hello"}'` |
| Screenshot | `curl http://localhost:9867/instances/$INST/screenshot -o page.png` |
-| PDF export | `curl http://localhost:9867/instances/$INST/pdf -o out.pdf` |
+| PDF export | `curl http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf -o out.pdf` |
| List instances | `curl http://localhost:9867/instances` |
| List tabs | `curl http://localhost:9867/instances/$INST/tabs` |
| New tab | `curl -X POST http://localhost:9867/tabs/open -d '{"instanceId":"$INST","url":"..."}'` |
diff --git a/docs/references/api-reference.json b/docs/references/api-reference.json
index 6d63d550..aaa77c54 100644
--- a/docs/references/api-reference.json
+++ b/docs/references/api-reference.json
@@ -138,15 +138,6 @@
"parameters": "tabId (string, query, required), format (string, optional, default: \"webm\")",
"payload": "N/A (GET request)"
},
- {
- "method": "GET",
- "path": "/pdf",
- "handler": "HandlePDF",
- "description": "Export as PDF",
- "cli": true,
- "curl": true,
- "examples": {}
- },
{
"method": "GET",
"path": "/screencast",
@@ -600,6 +591,19 @@
"payload": "N/A (GET)",
"defaults": "returns binary PDF data"
},
+ {
+ "method": "POST",
+ "path": "/tabs/{id}/pdf",
+ "handler": "proxyToTab",
+ "description": "Export tab as PDF (JSON body options)",
+ "tldr": "Export as PDF",
+ "cli": false,
+ "curl": true,
+ "curlExample": "curl -X POST 'http://localhost:9867/tabs/tab_abc/pdf?raw=true' -H 'Content-Type: application/json' -d '{\"landscape\":true,\"scale\":1.0}' > output.pdf",
+ "parameters": "same options as GET, but provided in JSON body",
+ "payload": "{\"landscape\":true,\"scale\":1.0,\"displayHeaderFooter\":true}",
+ "defaults": "returns binary PDF data (or JSON when output=file)"
+ },
{
"method": "GET",
"path": "/tabs/{id}/cookies",
diff --git a/docs/references/cli-design.md b/docs/references/cli-design.md
index 751c41a4..fabd2724 100644
--- a/docs/references/cli-design.md
+++ b/docs/references/cli-design.md
@@ -168,7 +168,7 @@ EOF
| `/tab` | POST | `pinchtab tab create https://example.com` |
| `/tabs` | GET | `pinchtab tabs` |
| `/evaluate` | POST | `pinchtab eval "document.title"` |
-| `/pdf` | GET | `pinchtab pdf -o out.pdf --landscape` |
+| `/tabs/{id}/pdf` | GET | `pinchtab pdf --tab <tabId> -o out.pdf --landscape` |
| `/text` | GET | `pinchtab text` |
| `/text` | GET | `pinchtab text --raw` |
| `/cookies` | GET | `pinchtab cookies` |
@@ -184,7 +184,7 @@ EOF
| `/instances/{id}/tab` | POST | `pinchtab --instance <id> tab create https://example.com` |
| `/instances/{id}/tabs` | GET | `pinchtab --instance <id> tabs` |
| `/instances/{id}/evaluate` | POST | `pinchtab --instance <id> eval 'code'` |
-| `/instances/{id}/pdf` | GET | `pinchtab --instance <id> pdf -o out.pdf` |
+| `/instances/{id}/tabs/{tabId}/pdf` | GET | `pinchtab --instance <id> pdf --tab <tabId> -o out.pdf` |
## Real-World Examples
diff --git a/docs/references/configuration.md b/docs/references/configuration.md
index 2d163e01..eb90e09d 100644
--- a/docs/references/configuration.md
+++ b/docs/references/configuration.md
@@ -158,22 +158,22 @@ Example:
## Chrome Profile Directory Structure
-Profiles are stored in `~/.pinchtab/profiles/{name}/`:
+Profiles are stored in `~/.pinchtab/profiles/{id}/`:
```text
~/.pinchtab/profiles/
-├── work/
+├── prof_9f86d081/
│ ├── Default/
│ │ ├── Preferences
│ │ ├── Cookies
│ │ ├── History
│ │ └── ... (other Chrome data)
│ └── ...
-├── personal/
+├── prof_dc34vewr/
│ ├── Default/
│ │ └── ... (Chrome data)
│ └── ...
-└── default/
+└── prof_34ff6ks9/
└── ... (default profile)
```
diff --git a/docs/references/endpoints.md b/docs/references/endpoints.md
index 371a0b06..04a246f4 100644
--- a/docs/references/endpoints.md
+++ b/docs/references/endpoints.md
@@ -54,7 +54,7 @@ HTTP Client
| **Page Inspection** | `GET /instances/{id}/snapshot` `GET /instances/{id}/text` | Get accessibility tree, extract text |
| **User Actions** | `POST /instances/{id}/action` | Click, type, fill, press, hover, focus, scroll, select |
| **JavaScript** | `POST /instances/{id}/evaluate` | Execute JavaScript in the page |
-| **Visual** | `GET /instances/{id}/screenshot` `GET /instances/{id}/pdf` | Take screenshot, export PDF |
+| **Visual** | `GET /instances/{id}/screenshot` `GET /instances/{id}/tabs/{tabId}/pdf` | Take screenshot, export PDF |
| **Profiles** | `GET /profiles` `POST /profiles` | List and create browser profiles |
| **Aggregate** | `GET /tabs` | Get all tabs across all instances |
@@ -604,11 +604,10 @@ curl "http://localhost:9867/instances/work-9868/screenshot?tabId=tab-1&quality=8
**Endpoint:**
```
-GET /instances/{id}/pdf
+GET /instances/{id}/tabs/{tabId}/pdf
```
**Query Parameters:**
-- `tabId` (optional) — Target tab
- `landscape` (optional) — `true` for landscape
- `paperWidth`, `paperHeight` (optional) — Paper dimensions in inches
- `marginTop`, `marginBottom`, `marginLeft`, `marginRight` (optional) — Margins in inches
@@ -627,7 +626,7 @@ GET /instances/{id}/pdf
**Example (curl):**
```bash
-curl "http://localhost:9867/instances/work-9868/pdf?tabId=tab-1&landscape=true" \
+curl "http://localhost:9867/instances/work-9868/tabs/tab-1/pdf?landscape=true" \
-o output.pdf
```
diff --git a/docs/showcase.md b/docs/showcase.md
index 9d30e693..05b401d0 100644
--- a/docs/showcase.md
+++ b/docs/showcase.md
@@ -518,7 +518,7 @@ echo "Instance: $INST, Tab: $TAB"
**Step 2: Generate PDF (use tabId)**
```bash
-curl "http://localhost:9867/instances/$INST/pdf?tabId=$TAB&landscape=true" \
+curl "http://localhost:9867/instances/$INST/tabs/$TAB/pdf?landscape=true" \
-o report.pdf
```
@@ -546,7 +546,7 @@ echo "Tab: $TAB"
# Step 4: Generate PDF with options using tabId
echo "Generating PDF..."
-curl -s "http://localhost:9867/instances/$INST/pdf?tabId=$TAB&landscape=true&displayHeaderFooter=true" \
+curl -s "http://localhost:9867/instances/$INST/tabs/$TAB/pdf?landscape=true&displayHeaderFooter=true" \
-o report.pdf
echo "PDF saved: report.pdf"
@@ -662,7 +662,7 @@ curl -X POST http://localhost:9867/instances/$INST2/stop
| Extract text | `GET /instances/{id}/text` | Returns readable text |
| Run JavaScript | `POST /instances/{id}/evaluate` | Returns JSON result |
| Screenshot | `GET /instances/{id}/screenshot` | Returns PNG image |
-| PDF export | `GET /instances/{id}/pdf` | Returns PDF file |
+| PDF export | `GET /instances/{id}/tabs/{tabId}/pdf` | Returns PDF file |
| List tabs | `GET /instances/{id}/tabs` | All tabs in instance |
| New tab | `POST /tabs/open` | Open URL in new tab |
| Stop instance | `POST /instances/{id}/stop` | Cleanup, free resources |
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index b524743c..4f02a55b 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -6,7 +6,6 @@ import (
"log/slog"
"math/rand"
"os"
- "time"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/assets"
@@ -126,7 +125,9 @@ func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelF
opts = append(opts, chromedp.Flag("TZ", cfg.Timezone))
}
- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ // Allocator/browser context must be long-lived for the entire bridge instance.
+ // A short timeout here causes all later tab creation to fail once the deadline expires.
+ ctx, cancel := context.WithCancel(context.Background())
return ctx, cancel, opts
}
diff --git a/internal/dashboard/dashboard/profiles.js b/internal/dashboard/dashboard/profiles.js
index 1ffceca7..d4c6c379 100644
--- a/internal/dashboard/dashboard/profiles.js
+++ b/internal/dashboard/dashboard/profiles.js
@@ -175,20 +175,25 @@ async function doCreateProfile() {
try {
const body = { name, useWhen };
+ let res;
if (source) {
- body.source = source;
- await fetch('/profiles/import', {
+ body.sourcePath = source;
+ res = await fetch('/profiles/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} else {
- await fetch('/profiles/create', {
+ res = await fetch('/profiles/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
}
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error || res.statusText || 'create failed');
+ }
loadProfiles();
} catch (e) { await appAlert('Failed: ' + e.message, 'Error'); }
}
diff --git a/internal/handlers/handler_pdf_test.go b/internal/handlers/handler_pdf_test.go
index d8876db0..e4e1e9ba 100644
--- a/internal/handlers/handler_pdf_test.go
+++ b/internal/handlers/handler_pdf_test.go
@@ -8,21 +8,22 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
-func TestHandlePDF_NoTab(t *testing.T) {
+func TestHandleTabPDF_MissingTabID(t *testing.T) {
h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/pdf", nil)
+ req := httptest.NewRequest("GET", "/tabs//pdf", nil)
w := httptest.NewRecorder()
- h.HandlePDF(w, req)
- if w.Code != http.StatusNotFound {
- t.Errorf("expected 404, got %d", w.Code)
+ h.HandleTabPDF(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400, got %d", w.Code)
}
}
-func TestHandlePDF_NoTab_WithTabId(t *testing.T) {
+func TestHandleTabPDF_NoTab_WithTabID(t *testing.T) {
h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/pdf?tabId=nonexistent", nil)
+ req := httptest.NewRequest("GET", "/tabs/nonexistent/pdf", nil)
+ req.SetPathValue("id", "nonexistent")
w := httptest.NewRecorder()
- h.HandlePDF(w, req)
+ h.HandleTabPDF(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", w.Code)
}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 62e44cb3..6984746f 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -41,7 +41,8 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /tabs", h.HandleTabs)
mux.HandleFunc("GET /snapshot", h.HandleSnapshot)
mux.HandleFunc("GET /screenshot", h.HandleScreenshot)
- mux.HandleFunc("GET /pdf", h.HandlePDF)
+ mux.HandleFunc("GET /tabs/{id}/pdf", h.HandleTabPDF)
+ mux.HandleFunc("POST /tabs/{id}/pdf", h.HandleTabPDF)
mux.HandleFunc("GET /text", h.HandleText)
mux.HandleFunc("POST /navigate", h.HandleNavigate)
mux.HandleFunc("POST /action", h.HandleAction)
diff --git a/internal/handlers/media.go b/internal/handlers/media.go
index 93048d4e..363e1c1e 100644
--- a/internal/handlers/media.go
+++ b/internal/handlers/media.go
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"encoding/base64"
+ "encoding/json"
"fmt"
"log/slog"
"net/http"
@@ -18,6 +19,27 @@ import (
"github.com/pinchtab/pinchtab/internal/web"
)
+var pdfQueryParams = map[string]struct{}{
+ "landscape": {},
+ "preferCSSPageSize": {},
+ "displayHeaderFooter": {},
+ "generateTaggedPDF": {},
+ "generateDocumentOutline": {},
+ "scale": {},
+ "paperWidth": {},
+ "paperHeight": {},
+ "marginTop": {},
+ "marginBottom": {},
+ "marginLeft": {},
+ "marginRight": {},
+ "pageRanges": {},
+ "headerTemplate": {},
+ "footerTemplate": {},
+ "output": {},
+ "path": {},
+ "raw": {},
+}
+
func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
@@ -270,6 +292,49 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
})
}
+func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ q := r.URL.Query()
+ if r.Method == http.MethodPost {
+ var body map[string]any
+ if r.ContentLength > 0 {
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&body); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+ for key, value := range body {
+ if _, ok := pdfQueryParams[key]; !ok {
+ continue
+ }
+ switch v := value.(type) {
+ case string:
+ q.Set(key, v)
+ case bool:
+ q.Set(key, strconv.FormatBool(v))
+ case float64:
+ q.Set(key, strconv.FormatFloat(v, 'f', -1, 64))
+ default:
+ web.Error(w, 400, fmt.Errorf("invalid %s type", key))
+ return
+ }
+ }
+ }
+ }
+ q.Set("tabId", tabID)
+
+ req := r.Clone(r.Context())
+ u := *r.URL
+ u.RawQuery = q.Encode()
+ req.URL = &u
+
+ h.HandlePDF(w, req)
+}
+
func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index 261ae134..7ccd46cd 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -47,7 +47,8 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("POST /instances/{id}/action", o.proxyToInstance)
mux.HandleFunc("POST /instances/{id}/actions", o.proxyToInstance)
mux.HandleFunc("GET /instances/{id}/screenshot", o.proxyToInstance)
- mux.HandleFunc("GET /instances/{id}/pdf", o.proxyToInstance)
+ mux.HandleFunc("GET /instances/{id}/tabs/{tabId}/pdf", o.proxyToInstance)
+ mux.HandleFunc("POST /instances/{id}/tabs/{tabId}/pdf", o.proxyToInstance)
mux.HandleFunc("GET /instances/{id}/text", o.proxyToInstance)
mux.HandleFunc("POST /instances/{id}/evaluate", o.proxyToInstance)
mux.HandleFunc("GET /instances/{id}/tabs", o.proxyToInstance)
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index b96c84c4..071ff305 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -161,6 +161,11 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*bridge.Instanc
o.mu.Unlock()
profilePath := filepath.Join(o.baseDir, name)
+ if o.profiles != nil {
+ if resolvedPath, err := o.profiles.ProfilePath(name); err == nil {
+ profilePath = resolvedPath
+ }
+ }
if err := os.MkdirAll(filepath.Join(profilePath, "Default"), 0755); err != nil {
return nil, fmt.Errorf("create profile dir: %w", err)
}
diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.go
index c50e1252..dd2d2d80 100644
--- a/internal/profiles/handlers.go
+++ b/internal/profiles/handlers.go
@@ -4,8 +4,6 @@ import (
"encoding/json"
"fmt"
"net/http"
- "os"
- "path/filepath"
"strconv"
"github.com/pinchtab/pinchtab/internal/web"
@@ -42,12 +40,16 @@ func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {
for _, p := range profiles {
if !p.Temporary {
// Convert to map for JSON response
+ sizeMB := float64(p.DiskUsage) / (1024 * 1024)
filtered = append(filtered, map[string]any{
"id": p.ID,
"name": p.Name,
+ "path": p.Path,
+ "pathExists": p.PathExists,
"created": p.Created,
"lastUsed": p.LastUsed,
"diskUsage": p.DiskUsage,
+ "sizeMB": sizeMB,
"running": p.Running,
"source": p.Source,
"chromeProfileName": p.ChromeProfileName,
@@ -163,11 +165,7 @@ func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Reques
func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
- // Try to find profile by ID first
- pm.mu.RLock()
- entries, err := os.ReadDir(pm.baseDir)
- pm.mu.RUnlock()
-
+ profiles, err := pm.List()
if err != nil {
web.Error(w, 500, err)
return
@@ -175,38 +173,28 @@ func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request)
var foundProfile map[string]any
- for _, entry := range entries {
- if !entry.IsDir() {
+ for _, p := range profiles {
+ // Match by ID or name (backward-compatible)
+ if p.ID != id && p.Name != id {
continue
}
-
- meta := readProfileMeta(filepath.Join(pm.baseDir, entry.Name()))
- if meta.ID == "" {
- meta.ID = profileID(entry.Name())
- }
-
- // If ID matches, or if id looks like a name (for backward compat)
- if meta.ID == id || entry.Name() == id {
- info, err := pm.profileInfo(entry.Name())
- if err != nil {
- continue
- }
-
- foundProfile = map[string]any{
- "id": info.ID,
- "name": info.Name,
- "created": info.CreatedAt,
- "diskUsage": info.SizeMB * 1024 * 1024,
- "source": info.Source,
- "chromeProfileName": info.ChromeProfileName,
- "accountEmail": info.AccountEmail,
- "accountName": info.AccountName,
- "hasAccount": info.HasAccount,
- "useWhen": info.UseWhen,
- "description": info.Description,
- }
- break
+ foundProfile = map[string]any{
+ "id": p.ID,
+ "name": p.Name,
+ "path": p.Path,
+ "pathExists": p.PathExists,
+ "created": p.Created,
+ "diskUsage": p.DiskUsage,
+ "sizeMB": float64(p.DiskUsage) / (1024 * 1024),
+ "source": p.Source,
+ "chromeProfileName": p.ChromeProfileName,
+ "accountEmail": p.AccountEmail,
+ "accountName": p.AccountName,
+ "hasAccount": p.HasAccount,
+ "useWhen": p.UseWhen,
+ "description": p.Description,
}
+ break
}
if foundProfile == nil {
diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.go
index e80d0479..2f54f6ec 100644
--- a/internal/profiles/profiles.go
+++ b/internal/profiles/profiles.go
@@ -46,6 +46,7 @@ type ProfileManager struct {
type ProfileMeta struct {
ID string `json:"id,omitempty"`
+ Name string `json:"name,omitempty"`
UseWhen string `json:"useWhen,omitempty"`
Description string `json:"description,omitempty"`
}
@@ -73,13 +74,48 @@ func NewProfileManager(baseDir string) *ProfileManager {
}
}
-func (pm *ProfileManager) Exists(name string) bool {
+func (pm *ProfileManager) findProfileDirByName(name string) (string, error) {
+ direct := filepath.Join(pm.baseDir, name)
+ if info, err := os.Stat(direct); err == nil && info.IsDir() {
+ return direct, nil
+ }
+
+ entries, err := os.ReadDir(pm.baseDir)
+ if err != nil {
+ return "", err
+ }
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ dir := filepath.Join(pm.baseDir, entry.Name())
+ if entry.Name() == profileID(name) {
+ return dir, nil
+ }
+ meta := readProfileMeta(dir)
+ if meta.Name == name {
+ return dir, nil
+ }
+ }
+ return "", fmt.Errorf("profile %q not found", name)
+}
+
+func (pm *ProfileManager) profileDir(name string) (string, error) {
if err := validateProfileName(name); err != nil {
- return false
+ return "", err
}
- dir := filepath.Join(pm.baseDir, name)
- info, err := os.Stat(dir)
- return err == nil && info.IsDir()
+ pm.mu.RLock()
+ defer pm.mu.RUnlock()
+ return pm.findProfileDirByName(name)
+}
+
+func (pm *ProfileManager) Exists(name string) bool {
+ _, err := pm.profileDir(name)
+ return err == nil
+}
+
+func (pm *ProfileManager) ProfilePath(name string) (string, error) {
+ return pm.profileDir(name)
}
func (pm *ProfileManager) List() ([]bridge.ProfileInfo, error) {
@@ -107,7 +143,7 @@ func (pm *ProfileManager) List() ([]bridge.ProfileInfo, error) {
}
// Mark as temporary if it's an auto-generated instance profile
- isTemporary := strings.HasPrefix(entry.Name(), "instance-")
+ isTemporary := strings.HasPrefix(info.Name, "instance-")
// Check if path exists
pathExists := true
@@ -136,11 +172,11 @@ func (pm *ProfileManager) List() ([]bridge.ProfileInfo, error) {
return profiles, nil
}
-func (pm *ProfileManager) profileInfo(name string) (ProfileDetailedInfo, error) {
- if err := validateProfileName(name); err != nil {
+func (pm *ProfileManager) profileInfo(dirName string) (ProfileDetailedInfo, error) {
+ if err := validateProfileName(dirName); err != nil {
return ProfileDetailedInfo{}, err
}
- dir := filepath.Join(pm.baseDir, name)
+ dir := filepath.Join(pm.baseDir, dirName)
fi, err := os.Stat(dir)
if err != nil {
return ProfileDetailedInfo{}, err
@@ -154,15 +190,27 @@ func (pm *ProfileManager) profileInfo(name string) (ProfileDetailedInfo, error)
chromeProfileName, accountEmail, accountName, hasAccount := readChromeProfileIdentity(dir)
meta := readProfileMeta(dir)
+ profileName := meta.Name
+ if profileName == "" {
+ profileName = dirName
+ }
+ changed := false
if meta.ID == "" {
- meta.ID = profileID(name)
+ meta.ID = profileID(profileName)
+ changed = true
+ }
+ if meta.Name == "" {
+ meta.Name = profileName
+ changed = true
+ }
+ if changed {
_ = writeProfileMeta(dir, meta)
}
return ProfileDetailedInfo{
ID: meta.ID,
- Name: name,
+ Name: profileName,
Path: dir,
CreatedAt: fi.ModTime(),
SizeMB: size,
@@ -183,7 +231,10 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
- dest := filepath.Join(pm.baseDir, name)
+ if _, err := pm.findProfileDirByName(name); err == nil {
+ return fmt.Errorf("profile %q already exists", name)
+ }
+ dest := filepath.Join(pm.baseDir, profileID(name))
if _, err := os.Stat(dest); err == nil {
return fmt.Errorf("profile %q already exists", name)
}
@@ -211,7 +262,10 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {
if err := os.WriteFile(filepath.Join(dest, ".pinchtab-imported"), []byte(sourcePath), 0600); err != nil {
slog.Warn("failed to write import marker", "err", err)
}
- return nil
+ return writeProfileMeta(dest, ProfileMeta{
+ ID: profileID(name),
+ Name: name,
+ })
}
func (pm *ProfileManager) ImportWithMeta(name, sourcePath string, meta ProfileMeta) error {
@@ -221,7 +275,10 @@ func (pm *ProfileManager) ImportWithMeta(name, sourcePath string, meta ProfileMe
if meta.ID == "" {
meta.ID = profileID(name)
}
- dest := filepath.Join(pm.baseDir, name)
+ if meta.Name == "" {
+ meta.Name = name
+ }
+ dest := filepath.Join(pm.baseDir, profileID(name))
return writeProfileMeta(dest, meta)
}
@@ -232,11 +289,20 @@ func (pm *ProfileManager) Create(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
- dest := filepath.Join(pm.baseDir, name)
+ if _, err := pm.findProfileDirByName(name); err == nil {
+ return fmt.Errorf("profile %q already exists", name)
+ }
+ dest := filepath.Join(pm.baseDir, profileID(name))
if _, err := os.Stat(dest); err == nil {
return fmt.Errorf("profile %q already exists", name)
}
- return os.MkdirAll(filepath.Join(dest, "Default"), 0755)
+ if err := os.MkdirAll(filepath.Join(dest, "Default"), 0755); err != nil {
+ return err
+ }
+ return writeProfileMeta(dest, ProfileMeta{
+ ID: profileID(name),
+ Name: name,
+ })
}
func (pm *ProfileManager) CreateWithMeta(name string, meta ProfileMeta) error {
@@ -246,7 +312,10 @@ func (pm *ProfileManager) CreateWithMeta(name string, meta ProfileMeta) error {
if meta.ID == "" {
meta.ID = profileID(name)
}
- dest := filepath.Join(pm.baseDir, name)
+ if meta.Name == "" {
+ meta.Name = name
+ }
+ dest := filepath.Join(pm.baseDir, profileID(name))
return writeProfileMeta(dest, meta)
}
@@ -257,9 +326,9 @@ func (pm *ProfileManager) Reset(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
- dir := filepath.Join(pm.baseDir, name)
- if _, err := os.Stat(dir); os.IsNotExist(err) {
- return fmt.Errorf("profile %q not found", name)
+ dir, err := pm.findProfileDirByName(name)
+ if err != nil {
+ return err
}
nukeDirs := []string{
@@ -303,9 +372,9 @@ func (pm *ProfileManager) Delete(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
- dir := filepath.Join(pm.baseDir, name)
- if _, err := os.Stat(dir); os.IsNotExist(err) {
- return fmt.Errorf("profile %q not found", name)
+ dir, err := pm.findProfileDirByName(name)
+ if err != nil {
+ return err
}
return os.RemoveAll(dir)
}
@@ -341,12 +410,19 @@ func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error
pm.mu.Lock()
defer pm.mu.Unlock()
- dir := filepath.Join(pm.baseDir, name)
- if _, err := os.Stat(dir); os.IsNotExist(err) {
- return fmt.Errorf("profile %q not found", name)
+ if err := validateProfileName(name); err != nil {
+ return err
+ }
+
+ dir, err := pm.findProfileDirByName(name)
+ if err != nil {
+ return err
}
existing := readProfileMeta(dir)
+ if existing.Name == "" {
+ existing.Name = name
+ }
if useWhen, ok := meta["useWhen"]; ok {
existing.UseWhen = useWhen
@@ -370,8 +446,18 @@ func (pm *ProfileManager) FindByID(id string) (string, error) {
if !entry.IsDir() {
continue
}
- meta := readProfileMeta(filepath.Join(pm.baseDir, entry.Name()))
+ dir := filepath.Join(pm.baseDir, entry.Name())
+ meta := readProfileMeta(dir)
if meta.ID == id {
+ if meta.Name != "" {
+ return meta.Name, nil
+ }
+ return entry.Name(), nil
+ }
+ if entry.Name() == id && meta.Name != "" {
+ return meta.Name, nil
+ }
+ if meta.ID == "" && profileID(entry.Name()) == id {
return entry.Name(), nil
}
}
diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.go
index 55136794..18337c81 100644
--- a/internal/profiles/profiles_test.go
+++ b/internal/profiles/profiles_test.go
@@ -23,7 +23,7 @@ func TestProfileManagerCreateAndList(t *testing.T) {
}
// Verify profile directory exists on disk
- profileDir := filepath.Join(dir, "test-profile")
+ profileDir := filepath.Join(dir, profileID("test-profile"))
if _, err := os.Stat(profileDir); err != nil {
t.Fatalf("profile directory not created: %s", profileDir)
}
@@ -104,7 +104,7 @@ func TestProfileManagerListReadsAccountFromPreferences(t *testing.T) {
t.Fatal(err)
}
- prefsPath := filepath.Join(dir, "acc-pref", "Default", "Preferences")
+ prefsPath := filepath.Join(dir, profileID("acc-pref"), "Default", "Preferences")
prefs := `{"account_info":[{"email":"[email protected]","full_name":"Alice"}]}`
if err := os.WriteFile(prefsPath, []byte(prefs), 0644); err != nil {
t.Fatal(err)
@@ -135,7 +135,7 @@ func TestProfileManagerListReadsLocalStateIdentity(t *testing.T) {
t.Fatal(err)
}
- localStatePath := filepath.Join(dir, "acc-local", "Local State")
+ localStatePath := filepath.Join(dir, profileID("acc-local"), "Local State")
localState := `{"profile":{"info_cache":{"Default":{"name":"Work","user_name":"[email protected]","gaia_name":"Bob","gaia_id":"123"}}}}`
if err := os.WriteFile(localStatePath, []byte(localState), 0644); err != nil {
t.Fatal(err)
@@ -167,11 +167,11 @@ func TestProfileManagerReset(t *testing.T) {
pm := NewProfileManager(dir)
_ = pm.Create("reset-me")
- sessDir := filepath.Join(dir, "reset-me", "Default", "Sessions")
+ sessDir := filepath.Join(dir, profileID("reset-me"), "Default", "Sessions")
_ = os.MkdirAll(sessDir, 0755)
_ = os.WriteFile(filepath.Join(sessDir, "session1"), []byte("data"), 0644)
- cacheDir := filepath.Join(dir, "reset-me", "Default", "Cache")
+ cacheDir := filepath.Join(dir, profileID("reset-me"), "Default", "Cache")
_ = os.MkdirAll(cacheDir, 0755)
if err := pm.Reset("reset-me"); err != nil {
@@ -185,7 +185,7 @@ func TestProfileManagerReset(t *testing.T) {
t.Error("Cache dir should be removed after reset")
}
- if _, err := os.Stat(filepath.Join(dir, "reset-me")); err != nil {
+ if _, err := os.Stat(filepath.Join(dir, profileID("reset-me"))); err != nil {
t.Error("Profile dir should still exist after reset")
}
}
@@ -260,10 +260,19 @@ func TestProfileHandlerList(t *testing.T) {
if len(profiles) != 2 {
t.Errorf("expected 2 profiles, got %d", len(profiles))
}
+ for _, p := range profiles {
+ if p.Path == "" {
+ t.Fatalf("expected path to be present for profile %q", p.Name)
+ }
+ if !p.PathExists {
+ t.Fatalf("expected pathExists=true for profile %q", p.Name)
+ }
+ }
}
func TestProfileHandlerCreate(t *testing.T) {
- pm := NewProfileManager(t.TempDir())
+ baseDir := t.TempDir()
+ pm := NewProfileManager(baseDir)
mux := http.NewServeMux()
pm.RegisterHandlers(mux)
@@ -275,6 +284,15 @@ func TestProfileHandlerCreate(t *testing.T) {
if w.Code != 200 {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
+
+ idDir := filepath.Join(baseDir, profileID("new-profile"))
+ if _, err := os.Stat(idDir); err != nil {
+ t.Fatalf("expected id-based directory to exist: %s", idDir)
+ }
+ nameDir := filepath.Join(baseDir, "new-profile")
+ if _, err := os.Stat(nameDir); !os.IsNotExist(err) {
+ t.Fatalf("expected name-based directory not to exist: %s", nameDir)
+ }
}
func TestProfileHandlerReset(t *testing.T) {
@@ -321,7 +339,7 @@ func TestProfileMetaReadWrite(t *testing.T) {
}
// Read back the metadata
- readMeta := readProfileMeta(filepath.Join(dir, "work-profile"))
+ readMeta := readProfileMeta(filepath.Join(dir, profileID("work-profile")))
if readMeta.UseWhen != "I need to access work email" {
t.Errorf("expected useWhen 'I need to access work email', got %q", readMeta.UseWhen)
}
diff --git a/skill/pinchtab/SKILL.md b/skill/pinchtab/SKILL.md
index 370d2c4b..9c223138 100644
--- a/skill/pinchtab/SKILL.md
+++ b/skill/pinchtab/SKILL.md
@@ -121,7 +121,7 @@ pinchtab text # readable text (~1K tokens)
pinchtab text | jq .text # pipe to jq
pinchtab ss -o page.jpg # screenshot
pinchtab eval "document.title" # run JavaScript
-pinchtab pdf -o page.pdf # export PDF
+pinchtab pdf --tab TAB_ID -o page.pdf # export PDF
```
For the full HTTP API (curl examples, download, upload, cookies, stealth, batch actions, PDF export with full parameter control), see [references/api.md](references/api.md).
@@ -136,7 +136,7 @@ For the full HTTP API (curl examples, download, upload, cookies, stealth, batch
| `/snapshot?format=compact` | ~56-64% less | One-line-per-node, best efficiency |
| `/snapshot` | ~10,500 | Full page understanding |
| `/screenshot` | ~2K (vision) | Visual verification |
-| `/pdf` | 0 (binary) | Export page as PDF (no token cost) |
+| `/tabs/{id}/pdf` | 0 (binary) | Export page as PDF (no token cost) |
**Strategy**: Start with `?filter=interactive&format=compact`. Use `?diff=true` on subsequent snapshots. Use `/text` when you only need readable content. Full `/snapshot` only when needed.
diff --git a/skill/pinchtab/references/api.md b/skill/pinchtab/references/api.md
index 9b83ef37..f33dfa54 100644
--- a/skill/pinchtab/references/api.md
+++ b/skill/pinchtab/references/api.md
@@ -138,33 +138,33 @@ Returns `{url, title, text}`. Cheapest option (~1K tokens for most pages).
## PDF export
```bash
-# CLI: pinchtab pdf [-o file.pdf] [--landscape] [--scale 0.8]
+# CLI: pinchtab pdf --tab TAB_ID [-o file.pdf] [--landscape] [--scale 0.8]
# Returns base64 JSON
-curl /pdf
+curl "/tabs/TAB_ID/pdf"
# Raw PDF bytes
-curl "/pdf?raw=true" -o page.pdf
+curl "/tabs/TAB_ID/pdf?raw=true" -o page.pdf
# Save to disk
-curl "/pdf?output=file&path=/tmp/page.pdf"
+curl "/tabs/TAB_ID/pdf?output=file&path=/tmp/page.pdf"
# Landscape with custom scale
-curl "/pdf?landscape=true&scale=0.8&raw=true" -o page.pdf
+curl "/tabs/TAB_ID/pdf?landscape=true&scale=0.8&raw=true" -o page.pdf
# Custom paper size (Letter: 8.5x11, A4: 8.27x11.69)
-curl "/pdf?paperWidth=8.5&paperHeight=11&marginTop=0.5&marginLeft=0.5&raw=true" -o custom.pdf
+curl "/tabs/TAB_ID/pdf?paperWidth=8.5&paperHeight=11&marginTop=0.5&marginLeft=0.5&raw=true" -o custom.pdf
# Export specific pages
-curl "/pdf?pageRanges=1-5&raw=true" -o pages.pdf
+curl "/tabs/TAB_ID/pdf?pageRanges=1-5&raw=true" -o pages.pdf
# With header/footer
-curl "/pdf?displayHeaderFooter=true&headerTemplate=%3Cspan%20class=title%3E%3C/span%3E&raw=true" -o header.pdf
+curl "/tabs/TAB_ID/pdf?displayHeaderFooter=true&headerTemplate=%3Cspan%20class=title%3E%3C/span%3E&raw=true" -o header.pdf
# Accessible PDF with document outline
-curl "/pdf?generateTaggedPDF=true&generateDocumentOutline=true&raw=true" -o accessible.pdf
+curl "/tabs/TAB_ID/pdf?generateTaggedPDF=true&generateDocumentOutline=true&raw=true" -o accessible.pdf
# Honor CSS page size
-curl "/pdf?preferCSSPageSize=true&raw=true" -o css-sized.pdf
+curl "/tabs/TAB_ID/pdf?preferCSSPageSize=true&raw=true" -o css-sized.pdf
```
**Query Parameters:**
diff --git a/tests/integration/pdf_test.go b/tests/integration/pdf_test.go
index cb5e6474..c7e4f421 100644
--- a/tests/integration/pdf_test.go
+++ b/tests/integration/pdf_test.go
@@ -4,14 +4,27 @@ package integration
import (
"encoding/base64"
+ "fmt"
"os"
"testing"
)
+func tabPDFPath(t *testing.T, query string) string {
+ t.Helper()
+ if currentTabID == "" {
+ t.Fatal("missing current tab id; call navigate() first")
+ }
+ path := fmt.Sprintf("/tabs/%s/pdf", currentTabID)
+ if query != "" {
+ path += "?" + query
+ }
+ return path
+}
+
// PD1: PDF base64
func TestPDF_Base64(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf")
+ code, body := httpGet(t, tabPDFPath(t, ""))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -32,7 +45,7 @@ func TestPDF_Base64(t *testing.T) {
// PD2: PDF raw bytes
func TestPDF_Raw(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -44,7 +57,7 @@ func TestPDF_Raw(t *testing.T) {
// PD3: PDF save to file (uses default state dir)
func TestPDF_SaveFile(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?output=file")
+ code, body := httpGet(t, tabPDFPath(t, "output=file"))
if code != 200 {
t.Fatalf("expected 200, got %d (body: %s)", code, body)
}
@@ -67,7 +80,7 @@ func TestPDF_SaveFile(t *testing.T) {
// PD5: PDF landscape
func TestPDF_Landscape(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?landscape=true&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "landscape=true&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -79,7 +92,7 @@ func TestPDF_Landscape(t *testing.T) {
// PD6: PDF scale
func TestPDF_Scale(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?scale=0.5&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "scale=0.5&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -91,7 +104,7 @@ func TestPDF_Scale(t *testing.T) {
// PD7: PDF with custom paper size
func TestPDF_CustomPaperSize(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?paperWidth=7&paperHeight=9&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "paperWidth=7&paperHeight=9&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -103,7 +116,7 @@ func TestPDF_CustomPaperSize(t *testing.T) {
// PD8: PDF with custom margins
func TestPDF_CustomMargins(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?marginTop=0.75&marginLeft=0.75&marginRight=0.75&marginBottom=0.75&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "marginTop=0.75&marginLeft=0.75&marginRight=0.75&marginBottom=0.75&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -115,7 +128,7 @@ func TestPDF_CustomMargins(t *testing.T) {
// PD9: PDF with page ranges
func TestPDF_PageRanges(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?pageRanges=1&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "pageRanges=1&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -127,7 +140,7 @@ func TestPDF_PageRanges(t *testing.T) {
// PD10: PDF with header/footer
func TestPDF_HeaderFooter(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?displayHeaderFooter=true&headerTemplate=%3Cspan%20class=url%3E%3C/span%3E&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "displayHeaderFooter=true&headerTemplate=%3Cspan%20class=url%3E%3C/span%3E&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -139,7 +152,7 @@ func TestPDF_HeaderFooter(t *testing.T) {
// PD11: PDF with accessibility and outline
func TestPDF_AccessiblePDF(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?generateTaggedPDF=true&generateDocumentOutline=true&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "generateTaggedPDF=true&generateDocumentOutline=true&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
@@ -151,7 +164,7 @@ func TestPDF_AccessiblePDF(t *testing.T) {
// PD12: PDF with preferCSSPageSize
func TestPDF_PreferCSSPageSize(t *testing.T) {
navigate(t, "https://example.com")
- code, body := httpGet(t, "/pdf?preferCSSPageSize=true&raw=true")
+ code, body := httpGet(t, tabPDFPath(t, "preferCSSPageSize=true&raw=true"))
if code != 200 {
t.Fatalf("expected 200, got %d", code)
}
diff --git a/tests/manual/core.md b/tests/manual/core.md
index f70be018..cc837b5e 100644
--- a/tests/manual/core.md
+++ b/tests/manual/core.md
@@ -147,14 +147,14 @@ Navigate to the test page first: `POST /navigate {"url":"file://<repo>/tests/ass
| # | Scenario | Steps | Expected |
|---|----------|-------|----------|
-| PD1 | PDF base64 | Navigate to page, `GET /pdf` | JSON with `format: "pdf"` and `base64` field |
-| PD2 | PDF raw bytes | `GET /pdf?raw=true` | Content-Type `application/pdf`, valid PDF bytes |
-| PD3 | PDF save to file | `GET /pdf?output=file` | JSON with `path` and `size` |
-| PD4 | PDF custom path | `GET /pdf?output=file&path=/tmp/test.pdf` | File written to `/tmp/test.pdf` |
-| PD5 | PDF landscape | `GET /pdf?landscape=true&raw=true` | Valid PDF in landscape |
-| PD6 | PDF scale | `GET /pdf?scale=0.5&raw=true` | Valid PDF with scaled content |
-| PD7 | PDF no tab | `GET /pdf` with no tabs | 404 error |
-| PD8 | PDF specific tab | `GET /pdf?tabId=TAB_ID` | PDF of specified tab |
+| PD1 | PDF base64 | Navigate to page, capture `TAB_ID`, `GET /tabs/TAB_ID/pdf` | JSON with `format: "pdf"` and `base64` field |
+| PD2 | PDF raw bytes | `GET /tabs/TAB_ID/pdf?raw=true` | Content-Type `application/pdf`, valid PDF bytes |
+| PD3 | PDF save to file | `GET /tabs/TAB_ID/pdf?output=file` | JSON with `path` and `size` |
+| PD4 | PDF custom path | `GET /tabs/TAB_ID/pdf?output=file&path=/tmp/test.pdf` | File written to `/tmp/test.pdf` |
+| PD5 | PDF landscape | `GET /tabs/TAB_ID/pdf?landscape=true&raw=true` | Valid PDF in landscape |
+| PD6 | PDF scale | `GET /tabs/TAB_ID/pdf?scale=0.5&raw=true` | Valid PDF with scaled content |
+| PD7 | PDF no tab | `GET /tabs/nonexistent/pdf` | 404 error |
+| PD8 | PDF specific tab | `GET /tabs/TAB_ID/pdf` | PDF of specified tab |
### 1.12 Stealth
@@ -205,7 +205,7 @@ Navigate to the test page first: `POST /navigate {"url":"file://<repo>/tests/ass
| CL8 | Text raw | `pinchtab text --raw` | Raw innerText |
| CL9 | Screenshot | `pinchtab ss -o /tmp/test.jpg` | File saved, size reported |
| CL10 | Evaluate | `pinchtab eval "document.title"` | Returns page title |
-| CL11 | PDF | `pinchtab pdf -o /tmp/test.pdf` | PDF file saved |
+| CL11 | PDF | `pinchtab pdf --tab <TAB_ID> -o /tmp/test.pdf` | PDF file saved |
| CL12 | Tabs list | `pinchtab tabs` | JSON array of tabs |
| CL13 | Tab new | `pinchtab tabs new https://example.com` | New tab opened |
| CL14 | Health | `pinchtab health` | JSON with status ok |