Skip to content

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

feat: always-on the default startup strategy with configurable restart policy

Luigi Agosti44c31fd3ce9c
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 95183d27..03ac855c 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -24,6 +24,7 @@ import (
"github.com/pinchtab/pinchtab/internal/web"
// Register strategies via init().
+ _ "github.com/pinchtab/pinchtab/internal/strategy/alwayson"
_ "github.com/pinchtab/pinchtab/internal/strategy/autorestart"
_ "github.com/pinchtab/pinchtab/internal/strategy/explicit"
_ "github.com/pinchtab/pinchtab/internal/strategy/simple"
@@ -90,6 +91,9 @@ func runDashboard(cfg *config.RuntimeConfig) {
if err != nil {
slog.Warn("unknown strategy, falling back to default", "strategy", cfg.Strategy, "err", err)
} else {
+ if runtimeAware, ok := strat.(strategy.RuntimeConfigAware); ok {
+ runtimeAware.SetRuntimeConfig(cfg)
+ }
// Inject orchestrator dependency.
if setter, ok := strat.(strategy.OrchestratorAware); ok {
setter.SetOrchestrator(orch)
@@ -165,7 +169,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
if activeStrategy != nil {
if err := activeStrategy.Start(context.Background()); err != nil {
slog.Error("strategy start failed", "strategy", activeStrategy.Name(), "err", err)
- } else {
+ } else if launchAware, ok := activeStrategy.(strategy.LaunchAware); ok && launchAware.HandlesLaunch() {
strategyHandlesLaunch = true
}
}
@@ -207,7 +211,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
slog.Info("auto-launched instance", "profile", profileToLaunch, "id", inst.ID, "port", inst.Port, "headless", headlessDefault)
}()
} else if !strategyHandlesLaunch {
- slog.Info("dashboard auto-launch disabled", "hint", "set PINCHTAB_AUTO_LAUNCH=1 or PINCHTAB_STRATEGY=simple-autorestart to enable")
+ slog.Info("dashboard auto-launch disabled", "hint", "set PINCHTAB_AUTO_LAUNCH=1 or PINCHTAB_STRATEGY=always-on to enable")
}
shutdownOnce := &sync.Once{}
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index 357cb551..bf9849fb 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -716,7 +716,7 @@ export default function SettingsPage() {
{activeSection === "orchestration" && (
<SectionCard
title="Orchestration"
- description="Port range and allocation policy can be applied immediately for future launches. Strategy changes require a dashboard restart because routes are registered at startup."
+ description="Port range and allocation policy can be applied immediately for future launches. Strategy and restart-policy changes require a dashboard restart because strategy routes and lifecycle state are registered at startup."
>
<SettingRow
label="Strategy"
@@ -732,6 +732,7 @@ export default function SettingsPage() {
}
className={selectClass}
>
+ <option value="always-on">Always on</option>
<option value="simple">Simple</option>
<option value="explicit">Explicit</option>
<option value="simple-autorestart">
@@ -790,6 +791,82 @@ export default function SettingsPage() {
className={fieldClass}
/>
</SettingRow>
+ <SettingRow
+ label="Max restarts"
+ description="Maximum restart attempts for restart-managed strategies. Use -1 for unlimited."
+ >
+ <input
+ type="number"
+ min={-1}
+ value={backendConfig.multiInstance.restart.maxRestarts}
+ onChange={(e) =>
+ updateBackendSection("multiInstance", {
+ restart: {
+ ...backendConfig.multiInstance.restart,
+ maxRestarts: Number(e.target.value),
+ },
+ })
+ }
+ className={fieldClass}
+ />
+ </SettingRow>
+ <SettingRow
+ label="Initial backoff"
+ description="Delay in seconds before the first restart attempt."
+ >
+ <input
+ type="number"
+ min={1}
+ value={backendConfig.multiInstance.restart.initBackoffSec}
+ onChange={(e) =>
+ updateBackendSection("multiInstance", {
+ restart: {
+ ...backendConfig.multiInstance.restart,
+ initBackoffSec: Number(e.target.value),
+ },
+ })
+ }
+ className={fieldClass}
+ />
+ </SettingRow>
+ <SettingRow
+ label="Max backoff"
+ description="Upper bound in seconds for exponential restart backoff."
+ >
+ <input
+ type="number"
+ min={1}
+ value={backendConfig.multiInstance.restart.maxBackoffSec}
+ onChange={(e) =>
+ updateBackendSection("multiInstance", {
+ restart: {
+ ...backendConfig.multiInstance.restart,
+ maxBackoffSec: Number(e.target.value),
+ },
+ })
+ }
+ className={fieldClass}
+ />
+ </SettingRow>
+ <SettingRow
+ label="Stable after"
+ description="Seconds the instance must stay healthy before the restart counter resets."
+ >
+ <input
+ type="number"
+ min={1}
+ value={backendConfig.multiInstance.restart.stableAfterSec}
+ onChange={(e) =>
+ updateBackendSection("multiInstance", {
+ restart: {
+ ...backendConfig.multiInstance.restart,
+ stableAfterSec: Number(e.target.value),
+ },
+ })
+ }
+ className={fieldClass}
+ />
+ </SettingRow>
</SectionCard>
)}
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 6945bbff..2f25456f 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -97,10 +97,18 @@ export interface BackendProfilesConfig {
}
export interface BackendMultiInstanceConfig {
- strategy: "simple" | "explicit" | "simple-autorestart";
+ strategy: "simple" | "explicit" | "simple-autorestart" | "always-on";
allocationPolicy: "fcfs" | "round_robin" | "random";
instancePortStart: number;
instancePortEnd: number;
+ restart: BackendMultiInstanceRestartConfig;
+}
+
+export interface BackendMultiInstanceRestartConfig {
+ maxRestarts: number;
+ initBackoffSec: number;
+ maxBackoffSec: number;
+ stableAfterSec: number;
}
export interface BackendAttachConfig {
@@ -194,10 +202,16 @@ export const defaultBackendConfig: BackendConfig = {
defaultProfile: "default",
},
multiInstance: {
- strategy: "simple",
+ strategy: "always-on",
allocationPolicy: "fcfs",
instancePortStart: 9868,
instancePortEnd: 9968,
+ restart: {
+ maxRestarts: 20,
+ initBackoffSec: 2,
+ maxBackoffSec: 60,
+ stableAfterSec: 300,
+ },
},
timeouts: {
actionSec: 30,
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 697bae2c..9fbfa8fb 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -169,10 +169,16 @@ Current nested config shape:
"defaultProfile": "default"
},
"multiInstance": {
- "strategy": "simple",
+ "strategy": "always-on",
"allocationPolicy": "fcfs",
"instancePortStart": 9868,
- "instancePortEnd": 9968
+ "instancePortEnd": 9968,
+ "restart": {
+ "maxRestarts": 20,
+ "initBackoffSec": 2,
+ "maxBackoffSec": 60,
+ "stableAfterSec": 300
+ }
},
"timeouts": {
"actionSec": 30,
@@ -192,7 +198,7 @@ Current nested config shape:
| `instanceDefaults` | Default behavior for managed instances |
| `security` | Sensitive feature gates, attach policy, and IDPI |
| `profiles` | Profile storage defaults |
-| `multiInstance` | Strategy, allocation, and instance port range |
+| `multiInstance` | Strategy, allocation, instance port range, and restart policy |
| `timeouts` | Runtime timeouts |
## Common Examples
@@ -300,8 +306,10 @@ Use `pinchtab config init` to create a nested config file.
- `instanceDefaults.maxParallelTabs >= 0`
- valid `multiInstance.strategy`
- valid `multiInstance.allocationPolicy`
+- valid `multiInstance.restart.*` values
- valid `security.attach.allowSchemes`
- `multiInstance.instancePortStart <= multiInstance.instancePortEnd`
+- `multiInstance.restart.initBackoffSec <= multiInstance.restart.maxBackoffSec`
- non-negative timeout values
Valid enum values:
@@ -311,7 +319,7 @@ Valid enum values:
| `instanceDefaults.mode` | `headless`, `headed` |
| `instanceDefaults.stealthLevel` | `light`, `medium`, `full` |
| `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` (default) |
-| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart` |
+| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart`, `always-on` (default) |
| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |
| `security.attach.allowSchemes` | `ws`, `wss` |
diff --git a/docs/reference/strategies.md b/docs/reference/strategies.md
index a753cb6f..d041258f 100644
--- a/docs/reference/strategies.md
+++ b/docs/reference/strategies.md
@@ -18,12 +18,11 @@ Valid strategies in the current implementation:
- `simple`
- `explicit`
+- `always-on`
- `simple-autorestart`
### `simple`
-`simple` is the default.
-
Behavior:
- registers the full orchestrator API
@@ -52,6 +51,23 @@ Best fit:
- agents that should name instances deliberately
- deployments where hidden auto-launch would be surprising
+### `always-on`
+
+`always-on` behaves like a managed single-instance service that should stay up for the full lifetime of the PinchTab process.
+
+Behavior:
+
+- launches one managed instance when the strategy starts
+- exposes the same shorthand routes as `simple`
+- watches that managed instance and keeps restarting it after unexpected exits until the configured restart limit is reached
+- exposes `GET /always-on/status` for current managed-instance state
+
+Best fit:
+
+- daemon-style local services
+- agent hosts that expect one default browser to always be present
+- setups where startup availability matters, but you still want a bounded failure policy
+
### `simple-autorestart`
`simple-autorestart` behaves like a managed single-instance service with recovery.
@@ -60,7 +76,7 @@ Behavior:
- launches one managed instance when the strategy starts
- exposes the same shorthand routes as `simple`
-- watches that managed instance and tries to restart it after unexpected exits
+- watches that managed instance and tries to restart it after unexpected exits under the configured restart policy
- exposes `GET /autorestart/status` for restart state
Best fit:
@@ -122,6 +138,25 @@ Best fit:
## Recommended Defaults
+### Always-On Service
+
+```json
+{
+ "multiInstance": {
+ "strategy": "always-on",
+ "allocationPolicy": "fcfs",
+ "restart": {
+ "maxRestarts": 20,
+ "initBackoffSec": 2,
+ "maxBackoffSec": 60,
+ "stableAfterSec": 300
+ }
+ }
+}
+```
+
+Use this when the default managed browser should be started immediately and kept available with a bounded restart policy.
+
### Simple Local Service
```json
@@ -154,7 +189,13 @@ Use this when your client is instance-aware and you want to control lifecycle di
{
"multiInstance": {
"strategy": "simple-autorestart",
- "allocationPolicy": "fcfs"
+ "allocationPolicy": "fcfs",
+ "restart": {
+ "maxRestarts": 3,
+ "initBackoffSec": 2,
+ "maxBackoffSec": 60,
+ "stableAfterSec": 300
+ }
}
}
```
@@ -164,7 +205,8 @@ Use this when one managed browser should stay available and recover after crashe
## Decision Rule
```text
-simple = easiest default, auto-launches on shorthand traffic
+always-on = default, launched at startup, restarted under restart policy
+simple = on-demand shorthand auto-launch
explicit = most control, no shorthand auto-launch
simple-autorestart = one managed browser with crash recovery
@@ -172,4 +214,3 @@ fcfs = deterministic
round_robin = balanced rotation
random = loose distribution
```
-
diff --git a/internal/config/config.go b/internal/config/config.go
index 69cd3736..7a3ef000 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -60,8 +60,12 @@ type RuntimeConfig struct {
WaitNavDelay time.Duration
// Orchestrator settings (dashboard mode only)
- Strategy string // "simple" (default), "explicit", or "simple-autorestart"
- AllocationPolicy string // "fcfs" (default), "round_robin", "random"
+ Strategy string // "always-on" (default), "simple", "explicit", or "simple-autorestart"
+ AllocationPolicy string // "fcfs" (default), "round_robin", "random"
+ RestartMaxRestarts int // Max restart attempts for restart-managed strategies (-1 = unlimited, 0 = strategy default)
+ RestartInitBackoff time.Duration // Initial restart backoff (0 = strategy default)
+ RestartMaxBackoff time.Duration // Maximum restart backoff cap (0 = strategy default)
+ RestartStableAfter time.Duration // Stable runtime window that resets the restart counter (0 = strategy default)
// Attach settings
AttachEnabled bool
@@ -225,10 +229,19 @@ var defaultLocalAllowedDomains = []string{"127.0.0.1", "localhost", "::1"}
// MultiInstanceConfig holds multi-instance orchestration settings.
type MultiInstanceConfig struct {
- Strategy string `json:"strategy,omitempty"`
- AllocationPolicy string `json:"allocationPolicy,omitempty"`
- InstancePortStart *int `json:"instancePortStart,omitempty"`
- InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+ Strategy string `json:"strategy,omitempty"`
+ AllocationPolicy string `json:"allocationPolicy,omitempty"`
+ InstancePortStart *int `json:"instancePortStart,omitempty"`
+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+ Restart MultiInstanceRestartConfig `json:"restart,omitempty"`
+}
+
+// MultiInstanceRestartConfig controls restart-managed strategy recovery behavior.
+type MultiInstanceRestartConfig struct {
+ MaxRestarts *int `json:"maxRestarts,omitempty"`
+ InitBackoffSec *int `json:"initBackoffSec,omitempty"`
+ MaxBackoffSec *int `json:"maxBackoffSec,omitempty"`
+ StableAfterSec *int `json:"stableAfterSec,omitempty"`
}
// AttachConfig holds policy for attaching to externally managed Chrome instances.
@@ -529,8 +542,12 @@ func Load() *RuntimeConfig {
WaitNavDelay: 1 * time.Second,
// Orchestrator defaults
- Strategy: "simple",
- AllocationPolicy: "fcfs",
+ Strategy: "always-on",
+ AllocationPolicy: "fcfs",
+ RestartMaxRestarts: 20,
+ RestartInitBackoff: 2 * time.Second,
+ RestartMaxBackoff: 60 * time.Second,
+ RestartStableAfter: 5 * time.Minute,
// Attach defaults
AttachEnabled: false,
@@ -712,6 +729,18 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.MultiInstance.InstancePortEnd != nil {
cfg.InstancePortEnd = *fc.MultiInstance.InstancePortEnd
}
+ if fc.MultiInstance.Restart.MaxRestarts != nil {
+ cfg.RestartMaxRestarts = *fc.MultiInstance.Restart.MaxRestarts
+ }
+ if fc.MultiInstance.Restart.InitBackoffSec != nil {
+ cfg.RestartInitBackoff = time.Duration(*fc.MultiInstance.Restart.InitBackoffSec) * time.Second
+ }
+ if fc.MultiInstance.Restart.MaxBackoffSec != nil {
+ cfg.RestartMaxBackoff = time.Duration(*fc.MultiInstance.Restart.MaxBackoffSec) * time.Second
+ }
+ if fc.MultiInstance.Restart.StableAfterSec != nil {
+ cfg.RestartStableAfter = time.Duration(*fc.MultiInstance.Restart.StableAfterSec) * time.Second
+ }
// Attach
if fc.Security.Attach.Enabled != nil {
@@ -780,6 +809,10 @@ func ApplyFileConfigToRuntime(cfg *RuntimeConfig, fc *FileConfig) {
func DefaultFileConfig() FileConfig {
start := 9868
end := 9968
+ restartMaxRestarts := 20
+ restartInitBackoffSec := 2
+ restartMaxBackoffSec := 60
+ restartStableAfterSec := 300
maxTabs := 20
allowEvaluate := false
allowMacro := false
@@ -827,10 +860,16 @@ func DefaultFileConfig() FileConfig {
DefaultProfile: "default",
},
MultiInstance: MultiInstanceConfig{
- Strategy: "simple",
+ Strategy: "always-on",
AllocationPolicy: "fcfs",
InstancePortStart: &start,
InstancePortEnd: &end,
+ Restart: MultiInstanceRestartConfig{
+ MaxRestarts: &restartMaxRestarts,
+ InitBackoffSec: &restartInitBackoffSec,
+ MaxBackoffSec: &restartMaxBackoffSec,
+ StableAfterSec: &restartStableAfterSec,
+ },
},
Timeouts: TimeoutsConfig{
ActionSec: 30,
@@ -865,6 +904,10 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
attachEnabled := cfg.AttachEnabled
start := cfg.InstancePortStart
end := cfg.InstancePortEnd
+ restartMaxRestarts := cfg.RestartMaxRestarts
+ restartInitBackoffSec := int(cfg.RestartInitBackoff / time.Second)
+ restartMaxBackoffSec := int(cfg.RestartMaxBackoff / time.Second)
+ restartStableAfterSec := int(cfg.RestartStableAfter / time.Second)
mode := "headless"
if !cfg.Headless {
@@ -922,6 +965,12 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
AllocationPolicy: cfg.AllocationPolicy,
InstancePortStart: &start,
InstancePortEnd: &end,
+ Restart: MultiInstanceRestartConfig{
+ MaxRestarts: &restartMaxRestarts,
+ InitBackoffSec: &restartInitBackoffSec,
+ MaxBackoffSec: &restartMaxBackoffSec,
+ StableAfterSec: &restartStableAfterSec,
+ },
},
Timeouts: TimeoutsConfig{
ActionSec: int(cfg.ActionTimeout / time.Second),
@@ -1086,6 +1135,10 @@ func handleConfigShow(cfg *RuntimeConfig) {
fmt.Println("Multi-Instance:")
fmt.Printf(" Strategy: %s\n", cfg.Strategy)
fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
+ fmt.Printf(" Max Restarts: %d\n", cfg.RestartMaxRestarts)
+ fmt.Printf(" Init Backoff: %v\n", cfg.RestartInitBackoff)
+ fmt.Printf(" Max Backoff: %v\n", cfg.RestartMaxBackoff)
+ fmt.Printf(" Stable After: %v\n", cfg.RestartStableAfter)
fmt.Println()
fmt.Println("Attach:")
fmt.Printf(" Enabled: %v\n", cfg.AttachEnabled)
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index 0811f50a..b589a50a 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -96,12 +96,18 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.AllowEvaluate {
t.Errorf("default AllowEvaluate = %v, want false", cfg.AllowEvaluate)
}
- if cfg.Strategy != "simple" {
- t.Errorf("default Strategy = %v, want simple", cfg.Strategy)
+ if cfg.Strategy != "always-on" {
+ t.Errorf("default Strategy = %v, want always-on", cfg.Strategy)
}
if cfg.AllocationPolicy != "fcfs" {
t.Errorf("default AllocationPolicy = %v, want fcfs", cfg.AllocationPolicy)
}
+ if cfg.RestartMaxRestarts != 20 {
+ t.Errorf("default RestartMaxRestarts = %v, want 20", cfg.RestartMaxRestarts)
+ }
+ if cfg.RestartInitBackoff != 2*time.Second {
+ t.Errorf("default RestartInitBackoff = %v, want 2s", cfg.RestartInitBackoff)
+ }
if cfg.TabEvictionPolicy != "close_lru" {
t.Errorf("default TabEvictionPolicy = %v, want close_lru", cfg.TabEvictionPolicy)
}
@@ -187,8 +193,11 @@ func TestDefaultFileConfig(t *testing.T) {
if fc.InstanceDefaults.Mode != "headless" {
t.Errorf("DefaultFileConfig.InstanceDefaults.Mode = %v, want headless", fc.InstanceDefaults.Mode)
}
- if fc.MultiInstance.Strategy != "simple" {
- t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want simple", fc.MultiInstance.Strategy)
+ if fc.MultiInstance.Strategy != "always-on" {
+ t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want always-on", fc.MultiInstance.Strategy)
+ }
+ if fc.MultiInstance.Restart.MaxRestarts == nil || *fc.MultiInstance.Restart.MaxRestarts != 20 {
+ t.Errorf("DefaultFileConfig.MultiInstance.Restart.MaxRestarts = %v, want 20", formatIntPtr(fc.MultiInstance.Restart.MaxRestarts))
}
if len(fc.Security.Attach.AllowSchemes) != 2 || fc.Security.Attach.AllowSchemes[0] != "ws" || fc.Security.Attach.AllowSchemes[1] != "wss" {
t.Errorf("DefaultFileConfig.Security.Attach.AllowSchemes = %v, want [ws wss]", fc.Security.Attach.AllowSchemes)
@@ -257,7 +266,13 @@ func TestLoadNestedConfig(t *testing.T) {
},
"multiInstance": {
"strategy": "explicit",
- "allocationPolicy": "round_robin"
+ "allocationPolicy": "round_robin",
+ "restart": {
+ "maxRestarts": 7,
+ "initBackoffSec": 4,
+ "maxBackoffSec": 90,
+ "stableAfterSec": 420
+ }
},
"timeouts": {
"actionSec": 60,
@@ -307,6 +322,18 @@ func TestLoadNestedConfig(t *testing.T) {
if cfg.AllocationPolicy != "round_robin" {
t.Errorf("nested AllocationPolicy = %v, want round_robin", cfg.AllocationPolicy)
}
+ if cfg.RestartMaxRestarts != 7 {
+ t.Errorf("nested RestartMaxRestarts = %v, want 7", cfg.RestartMaxRestarts)
+ }
+ if cfg.RestartInitBackoff != 4*time.Second {
+ t.Errorf("nested RestartInitBackoff = %v, want 4s", cfg.RestartInitBackoff)
+ }
+ if cfg.RestartMaxBackoff != 90*time.Second {
+ t.Errorf("nested RestartMaxBackoff = %v, want 90s", cfg.RestartMaxBackoff)
+ }
+ if cfg.RestartStableAfter != 420*time.Second {
+ t.Errorf("nested RestartStableAfter = %v, want 420s", cfg.RestartStableAfter)
+ }
if cfg.AttachEnabled != true {
t.Errorf("nested AttachEnabled = %v, want true", cfg.AttachEnabled)
}
diff --git a/internal/config/editor.go b/internal/config/editor.go
index c507cead..e81442fb 100644
--- a/internal/config/editor.go
+++ b/internal/config/editor.go
@@ -172,6 +172,10 @@ func setProfilesField(p *ProfilesConfig, field, value string) error {
}
func setMultiInstanceField(o *MultiInstanceConfig, field, value string) error {
+ if strings.HasPrefix(field, "restart.") {
+ return setMultiInstanceRestartField(&o.Restart, strings.TrimPrefix(field, "restart."), value)
+ }
+
switch field {
case "strategy":
o.Strategy = value
@@ -195,6 +199,27 @@ func setMultiInstanceField(o *MultiInstanceConfig, field, value string) error {
return nil
}
+func setMultiInstanceRestartField(r *MultiInstanceRestartConfig, field, value string) error {
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("multiInstance.restart.%s must be a number: %w", field, err)
+ }
+
+ switch field {
+ case "maxRestarts":
+ r.MaxRestarts = &n
+ case "initBackoffSec":
+ r.InitBackoffSec = &n
+ case "maxBackoffSec":
+ r.MaxBackoffSec = &n
+ case "stableAfterSec":
+ r.StableAfterSec = &n
+ default:
+ return fmt.Errorf("unknown field multiInstance.restart.%s", field)
+ }
+ return nil
+}
+
func setTimeoutsField(t *TimeoutsConfig, field, value string) error {
n, err := strconv.Atoi(value)
if err != nil {
@@ -361,6 +386,10 @@ func getProfilesField(p *ProfilesConfig, field string) (string, error) {
}
func getMultiInstanceField(o *MultiInstanceConfig, field string) (string, error) {
+ if strings.HasPrefix(field, "restart.") {
+ return getMultiInstanceRestartField(&o.Restart, strings.TrimPrefix(field, "restart."))
+ }
+
switch field {
case "strategy":
return o.Strategy, nil
@@ -375,6 +404,21 @@ func getMultiInstanceField(o *MultiInstanceConfig, field string) (string, error)
}
}
+func getMultiInstanceRestartField(r *MultiInstanceRestartConfig, field string) (string, error) {
+ switch field {
+ case "maxRestarts":
+ return formatIntPtr(r.MaxRestarts), nil
+ case "initBackoffSec":
+ return formatIntPtr(r.InitBackoffSec), nil
+ case "maxBackoffSec":
+ return formatIntPtr(r.MaxBackoffSec), nil
+ case "stableAfterSec":
+ return formatIntPtr(r.StableAfterSec), nil
+ default:
+ return "", fmt.Errorf("unknown field multiInstance.restart.%s", field)
+ }
+}
+
func getAttachField(a *AttachConfig, field string) (string, error) {
switch field {
case "enabled":
diff --git a/internal/config/editor_test.go b/internal/config/editor_test.go
index 60c84093..1339af00 100644
--- a/internal/config/editor_test.go
+++ b/internal/config/editor_test.go
@@ -111,6 +111,12 @@ func TestSetConfigValue_MultiInstanceFields(t *testing.T) {
{"multiInstance.strategy", "explicit", func(fc *FileConfig) bool { return fc.MultiInstance.Strategy == "explicit" }, false},
{"multiInstance.allocationPolicy", "round_robin", func(fc *FileConfig) bool { return fc.MultiInstance.AllocationPolicy == "round_robin" }, false},
{"multiInstance.instancePortStart", "9900", func(fc *FileConfig) bool { return *fc.MultiInstance.InstancePortStart == 9900 }, false},
+ {"multiInstance.restart.maxRestarts", "12", func(fc *FileConfig) bool {
+ return fc.MultiInstance.Restart.MaxRestarts != nil && *fc.MultiInstance.Restart.MaxRestarts == 12
+ }, false},
+ {"multiInstance.restart.initBackoffSec", "3", func(fc *FileConfig) bool {
+ return fc.MultiInstance.Restart.InitBackoffSec != nil && *fc.MultiInstance.Restart.InitBackoffSec == 3
+ }, false},
{"multiInstance.unknown", "value", nil, true},
}
@@ -422,6 +428,10 @@ func TestGetConfigValue_RoundTrip(t *testing.T) {
{"multiInstance.allocationPolicy", "round_robin", "round_robin"},
{"multiInstance.instancePortStart", "9900", "9900"},
{"multiInstance.instancePortEnd", "9950", "9950"},
+ {"multiInstance.restart.maxRestarts", "12", "12"},
+ {"multiInstance.restart.initBackoffSec", "3", "3"},
+ {"multiInstance.restart.maxBackoffSec", "45", "45"},
+ {"multiInstance.restart.stableAfterSec", "600", "600"},
{"security.attach.enabled", "true", "true"},
{"security.idpi.enabled", "true", "true"},
{"security.idpi.allowedDomains", "localhost,example.com", "localhost,example.com"},
diff --git a/internal/config/validate.go b/internal/config/validate.go
index f4541e9b..a43d2a5e 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -39,6 +39,39 @@ func ValidateFileConfig(fc *FileConfig) []error {
})
}
}
+ if fc.MultiInstance.Restart.MaxRestarts != nil {
+ if *fc.MultiInstance.Restart.MaxRestarts != -1 && *fc.MultiInstance.Restart.MaxRestarts < 1 {
+ errs = append(errs, ValidationError{
+ Field: "multiInstance.restart.maxRestarts",
+ Message: fmt.Sprintf("must be >= 1 or -1 for unlimited (got %d)", *fc.MultiInstance.Restart.MaxRestarts),
+ })
+ }
+ }
+ if fc.MultiInstance.Restart.InitBackoffSec != nil && *fc.MultiInstance.Restart.InitBackoffSec < 1 {
+ errs = append(errs, ValidationError{
+ Field: "multiInstance.restart.initBackoffSec",
+ Message: fmt.Sprintf("must be >= 1 (got %d)", *fc.MultiInstance.Restart.InitBackoffSec),
+ })
+ }
+ if fc.MultiInstance.Restart.MaxBackoffSec != nil && *fc.MultiInstance.Restart.MaxBackoffSec < 1 {
+ errs = append(errs, ValidationError{
+ Field: "multiInstance.restart.maxBackoffSec",
+ Message: fmt.Sprintf("must be >= 1 (got %d)", *fc.MultiInstance.Restart.MaxBackoffSec),
+ })
+ }
+ if fc.MultiInstance.Restart.StableAfterSec != nil && *fc.MultiInstance.Restart.StableAfterSec < 1 {
+ errs = append(errs, ValidationError{
+ Field: "multiInstance.restart.stableAfterSec",
+ Message: fmt.Sprintf("must be >= 1 (got %d)", *fc.MultiInstance.Restart.StableAfterSec),
+ })
+ }
+ if fc.MultiInstance.Restart.InitBackoffSec != nil && fc.MultiInstance.Restart.MaxBackoffSec != nil &&
+ *fc.MultiInstance.Restart.InitBackoffSec > *fc.MultiInstance.Restart.MaxBackoffSec {
+ errs = append(errs, ValidationError{
+ Field: "multiInstance.restart.initBackoffSec/maxBackoffSec",
+ Message: fmt.Sprintf("init backoff (%d) must be <= max backoff (%d)", *fc.MultiInstance.Restart.InitBackoffSec, *fc.MultiInstance.Restart.MaxBackoffSec),
+ })
+ }
// Instance defaults validation
if fc.InstanceDefaults.Mode != "" && fc.InstanceDefaults.Mode != "headless" && fc.InstanceDefaults.Mode != "headed" {
@@ -81,7 +114,7 @@ func ValidateFileConfig(fc *FileConfig) []error {
if !isValidStrategy(fc.MultiInstance.Strategy) {
errs = append(errs, ValidationError{
Field: "multiInstance.strategy",
- Message: fmt.Sprintf("invalid value %q (must be simple, explicit, or simple-autorestart)", fc.MultiInstance.Strategy),
+ Message: fmt.Sprintf("invalid value %q (must be simple, explicit, simple-autorestart, or always-on)", fc.MultiInstance.Strategy),
})
}
}
@@ -192,7 +225,7 @@ func isValidEvictionPolicy(policy string) bool {
func isValidStrategy(strategy string) bool {
switch strategy {
- case "simple", "explicit", "simple-autorestart":
+ case "simple", "explicit", "simple-autorestart", "always-on":
return true
default:
return false
@@ -229,7 +262,7 @@ func ValidEvictionPolicies() []string {
// ValidStrategies returns all valid strategy values.
func ValidStrategies() []string {
- return []string{"simple", "explicit", "simple-autorestart"}
+ return []string{"simple", "explicit", "simple-autorestart", "always-on"}
}
// validateIDPIConfig validates the security.idpi sub-section.
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 40cc78f1..0bef0f52 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -21,6 +21,12 @@ func TestValidateFileConfig_Valid(t *testing.T) {
MultiInstance: MultiInstanceConfig{
Strategy: "simple",
AllocationPolicy: "fcfs",
+ Restart: MultiInstanceRestartConfig{
+ MaxRestarts: intPtr(20),
+ InitBackoffSec: intPtr(2),
+ MaxBackoffSec: intPtr(60),
+ StableAfterSec: intPtr(300),
+ },
},
Timeouts: TimeoutsConfig{
ActionSec: 30,
@@ -34,6 +40,65 @@ func TestValidateFileConfig_Valid(t *testing.T) {
}
}
+func TestValidateFileConfig_RestartPolicy(t *testing.T) {
+ tests := []struct {
+ name string
+ restart MultiInstanceRestartConfig
+ wantErr bool
+ }{
+ {
+ name: "bounded",
+ restart: MultiInstanceRestartConfig{
+ MaxRestarts: intPtr(10),
+ InitBackoffSec: intPtr(2),
+ MaxBackoffSec: intPtr(60),
+ StableAfterSec: intPtr(300),
+ },
+ wantErr: false,
+ },
+ {
+ name: "unlimited",
+ restart: MultiInstanceRestartConfig{
+ MaxRestarts: intPtr(-1),
+ InitBackoffSec: intPtr(2),
+ MaxBackoffSec: intPtr(60),
+ StableAfterSec: intPtr(300),
+ },
+ wantErr: false,
+ },
+ {
+ name: "zero max restarts invalid",
+ restart: MultiInstanceRestartConfig{
+ MaxRestarts: intPtr(0),
+ },
+ wantErr: true,
+ },
+ {
+ name: "max backoff lower than init invalid",
+ restart: MultiInstanceRestartConfig{
+ InitBackoffSec: intPtr(10),
+ MaxBackoffSec: intPtr(5),
+ },
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ fc := &FileConfig{
+ MultiInstance: MultiInstanceConfig{Restart: tt.restart},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Fatalf("got error=%v, want %v (errs: %v)", hasErr, tt.wantErr, errs)
+ }
+ })
+ }
+}
+
+func intPtr(v int) *int { return &v }
+
func TestValidateFileConfig_InvalidPort(t *testing.T) {
tests := []struct {
port string
@@ -120,6 +185,7 @@ func TestValidateFileConfig_InvalidStrategy(t *testing.T) {
{"simple", false},
{"explicit", false},
{"simple-autorestart", false},
+ {"always-on", false},
{"", false},
{"auto", true},
{"default", true},
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index 4ec147ff..43a41ca7 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -225,10 +225,23 @@ func (c *ConfigAPI) restartReasonsFor(next config.FileConfig) []string {
if c.boot.MultiInstance.Strategy != next.MultiInstance.Strategy {
reasons = append(reasons, "Routing strategy")
}
+ if !sameIntPtr(c.boot.MultiInstance.Restart.MaxRestarts, next.MultiInstance.Restart.MaxRestarts) ||
+ !sameIntPtr(c.boot.MultiInstance.Restart.InitBackoffSec, next.MultiInstance.Restart.InitBackoffSec) ||
+ !sameIntPtr(c.boot.MultiInstance.Restart.MaxBackoffSec, next.MultiInstance.Restart.MaxBackoffSec) ||
+ !sameIntPtr(c.boot.MultiInstance.Restart.StableAfterSec, next.MultiInstance.Restart.StableAfterSec) {
+ reasons = append(reasons, "Restart policy")
+ }
return reasons
}
+func sameIntPtr(a, b *int) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+ return *a == *b
+}
+
func normalizeFileConfig(fc *config.FileConfig) (config.FileConfig, error) {
base := config.DefaultFileConfig()
if fc == nil {
diff --git a/internal/strategy/alwayson/alwayson.go b/internal/strategy/alwayson/alwayson.go
new file mode 100644
index 00000000..56516ae9
--- /dev/null
+++ b/internal/strategy/alwayson/alwayson.go
@@ -0,0 +1,16 @@
+package alwayson
+
+import (
+ "github.com/pinchtab/pinchtab/internal/strategy"
+ "github.com/pinchtab/pinchtab/internal/strategy/autorestart"
+)
+
+func init() {
+ strategy.MustRegister("always-on", func() strategy.Strategy {
+ return autorestart.New(autorestart.AutorestartConfig{
+ MaxRestarts: 20,
+ StrategyName: "always-on",
+ StatusPath: "/always-on/status",
+ })
+ })
+}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index b1b8be80..a9b5023d 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -17,6 +17,7 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
@@ -24,13 +25,15 @@ import (
)
const (
- defaultMaxRestarts = 3
- defaultInitBackoff = 2 * time.Second
- defaultMaxBackoff = 60 * time.Second
- defaultStableAfter = 5 * time.Minute
- defaultProfileName = "default"
- healthPollInterval = 500 * time.Millisecond
- healthPollTimeout = 30 * time.Second
+ defaultMaxRestarts = 3
+ defaultInitBackoff = 2 * time.Second
+ defaultMaxBackoff = 60 * time.Second
+ defaultStableAfter = 5 * time.Minute
+ defaultProfileName = "default"
+ defaultStrategyName = "simple-autorestart"
+ defaultStatusPath = "/autorestart/status"
+ healthPollInterval = 500 * time.Millisecond
+ healthPollTimeout = 30 * time.Second
)
func init() {
@@ -41,13 +44,15 @@ func init() {
// AutorestartConfig configures the autorestart behavior.
type AutorestartConfig struct {
- MaxRestarts int // Max consecutive restarts before giving up (0 = use default 3)
- InitBackoff time.Duration // Initial backoff between restarts (0 = use default 2s)
- MaxBackoff time.Duration // Maximum backoff cap (0 = use default 60s)
- StableAfter time.Duration // Reset counter after running this long (0 = use default 5m)
- ProfileName string // Profile to launch (empty = "default")
- Headless bool // Chrome headless mode
- HeadlessSet bool // Whether Headless was explicitly set (false = use default true)
+ MaxRestarts int // Max consecutive restarts before giving up (0 = use default 3, <0 = unlimited)
+ InitBackoff time.Duration // Initial backoff between restarts (0 = use default 2s)
+ MaxBackoff time.Duration // Maximum backoff cap (0 = use default 60s)
+ StableAfter time.Duration // Reset counter after running this long (0 = use default 5m)
+ ProfileName string // Profile to launch (empty = "default")
+ Headless bool // Chrome headless mode
+ HeadlessSet bool // Whether Headless was explicitly set (false = use default true)
+ StrategyName string // Exposed strategy identifier (empty = "simple-autorestart")
+ StatusPath string // Status endpoint path (empty = "/autorestart/status")
}
// RestartState tracks the restart state of the managed instance.
@@ -78,7 +83,7 @@ type Strategy struct {
// New creates a new autorestart strategy with the given config.
func New(cfg AutorestartConfig) *Strategy {
- if cfg.MaxRestarts <= 0 {
+ if cfg.MaxRestarts == 0 {
cfg.MaxRestarts = defaultMaxRestarts
}
if cfg.InitBackoff <= 0 {
@@ -96,13 +101,38 @@ func New(cfg AutorestartConfig) *Strategy {
if !cfg.HeadlessSet {
cfg.Headless = true
}
+ if cfg.StrategyName == "" {
+ cfg.StrategyName = defaultStrategyName
+ }
+ if cfg.StatusPath == "" {
+ cfg.StatusPath = defaultStatusPath
+ }
return &Strategy{
config: cfg,
}
}
-func (s *Strategy) Name() string { return "simple-autorestart" }
+func (s *Strategy) Name() string { return s.config.StrategyName }
+func (s *Strategy) HandlesLaunch() bool { return true }
+
+func (s *Strategy) SetRuntimeConfig(cfg *config.RuntimeConfig) {
+ if cfg == nil {
+ return
+ }
+ if cfg.RestartMaxRestarts != 0 {
+ s.config.MaxRestarts = cfg.RestartMaxRestarts
+ }
+ if cfg.RestartInitBackoff > 0 {
+ s.config.InitBackoff = cfg.RestartInitBackoff
+ }
+ if cfg.RestartMaxBackoff > 0 {
+ s.config.MaxBackoff = cfg.RestartMaxBackoff
+ }
+ if cfg.RestartStableAfter > 0 {
+ s.config.StableAfter = cfg.RestartStableAfter
+ }
+}
// SetOrchestrator injects the orchestrator after construction.
func (s *Strategy) SetOrchestrator(o *orchestrator.Orchestrator) {
@@ -164,7 +194,7 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
strategy.RegisterCapabilityRoute(mux, "POST /macro", s.orch.AllowsMacro(), "macro", "security.allowMacro", "macro_disabled", s.proxyToManaged)
mux.HandleFunc("GET /tabs", s.handleTabs)
- mux.HandleFunc("GET /autorestart/status", s.handleStatus)
+ mux.HandleFunc("GET "+s.config.StatusPath, s.handleStatus)
}
// State returns the current restart state for observability.
@@ -173,7 +203,7 @@ func (s *Strategy) State() RestartState {
defer s.mu.Unlock()
status := "running"
- if s.restartCount >= s.config.MaxRestarts {
+ if s.hasRestartLimit() && s.restartCount >= s.config.MaxRestarts {
status = "crashed"
} else if s.restarting {
status = "restarting"
@@ -205,7 +235,7 @@ func (s *Strategy) launchInitial() {
inst, err := s.orch.Launch(s.config.ProfileName, "", s.config.Headless, nil)
if err != nil {
- slog.Error("autorestart: initial launch failed", "profile", s.config.ProfileName, "err", err)
+ slog.Error(s.logPrefix("initial launch failed"), "profile", s.config.ProfileName, "err", err)
return
}
@@ -214,7 +244,7 @@ func (s *Strategy) launchInitial() {
s.lastStart = time.Now()
s.mu.Unlock()
- slog.Info("autorestart: instance launched", "id", inst.ID, "profile", s.config.ProfileName)
+ slog.Info(s.logPrefix("instance launched"), "id", inst.ID, "profile", s.config.ProfileName)
}
// handleEvent processes orchestrator lifecycle events.
@@ -240,7 +270,7 @@ func (s *Strategy) handleEvent(evt orchestrator.InstanceEvent) {
switch evt.Type {
case "instance.stopped":
if deliberate {
- slog.Info("autorestart: instance stopped deliberately", "id", managedID)
+ slog.Info(s.logPrefix("instance stopped deliberately"), "id", managedID)
return
}
// Instance exited unexpectedly — check if we should restart.
@@ -272,8 +302,8 @@ func (s *Strategy) handleCrash(ctx context.Context, crashedID string) {
}
s.mu.Unlock()
- if count > maxRestarts {
- slog.Error("autorestart: max restarts exceeded, giving up",
+ if s.hasRestartLimit() && count > maxRestarts {
+ slog.Error(s.logPrefix("max restarts exceeded, giving up"),
"id", crashedID,
"restartCount", count-1,
"maxRestarts", maxRestarts,
@@ -290,12 +320,15 @@ func (s *Strategy) handleCrash(ctx context.Context, crashedID string) {
return
}
- slog.Warn("autorestart: instance crashed, scheduling restart",
+ args := []any{
"id", crashedID,
"attempt", count,
- "maxRestarts", maxRestarts,
"backoff", backoff,
- )
+ }
+ if s.hasRestartLimit() {
+ args = append(args, "maxRestarts", maxRestarts)
+ }
+ slog.Warn(s.logPrefix("instance crashed, scheduling restart"), args...)
// Emit restarting event.
if s.orch != nil {
@@ -333,13 +366,13 @@ func (s *Strategy) restartInstance() {
// profile slot and allocated port before we attempt a new launch.
if oldID != "" {
if err := s.orch.Stop(oldID); err != nil {
- slog.Debug("autorestart: stop old instance (may already be gone)", "id", oldID, "err", err)
+ slog.Debug(s.logPrefix("stop old instance (may already be gone)"), "id", oldID, "err", err)
}
}
inst, err := s.orch.Launch(s.config.ProfileName, "", s.config.Headless, nil)
if err != nil {
- slog.Error("autorestart: restart failed",
+ slog.Error(s.logPrefix("restart failed"),
"oldId", oldID,
"err", err,
)
@@ -356,7 +389,7 @@ func (s *Strategy) restartInstance() {
s.restarting = false
s.mu.Unlock()
- slog.Info("autorestart: instance restarted",
+ slog.Info(s.logPrefix("instance restarted"),
"oldId", oldID,
"newId", inst.ID,
"attempt", count,
@@ -386,7 +419,7 @@ func (s *Strategy) stabilityLoop() {
case <-ticker.C:
s.mu.Lock()
if s.restartCount > 0 && !s.lastStart.IsZero() && time.Since(s.lastStart) > s.config.StableAfter {
- slog.Info("autorestart: instance stable, resetting restart counter",
+ slog.Info(s.logPrefix("instance stable, resetting restart counter"),
"id", s.instanceID,
"stableFor", time.Since(s.lastStart).Round(time.Second),
)
@@ -430,3 +463,11 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
func (s *Strategy) handleStatus(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, s.State())
}
+
+func (s *Strategy) hasRestartLimit() bool {
+ return s.config.MaxRestarts > 0
+}
+
+func (s *Strategy) logPrefix(message string) string {
+ return s.Name() + ": " + message
+}
diff --git a/internal/strategy/autorestart/autorestart_test.go b/internal/strategy/autorestart/autorestart_test.go
index 1897f2d7..7791c694 100644
--- a/internal/strategy/autorestart/autorestart_test.go
+++ b/internal/strategy/autorestart/autorestart_test.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
)
@@ -77,6 +78,42 @@ func TestStrategy_CustomConfig(t *testing.T) {
}
}
+func TestStrategy_UnlimitedRestarts(t *testing.T) {
+ s := New(AutorestartConfig{MaxRestarts: -1})
+ s.restartCount = 100
+
+ state := s.State()
+ if state.MaxRestarts != -1 {
+ t.Fatalf("expected MaxRestarts=-1, got %d", state.MaxRestarts)
+ }
+ if state.Status == "crashed" {
+ t.Fatal("expected unlimited-restart strategy to avoid crashed state")
+ }
+}
+
+func TestStrategy_SetRuntimeConfig(t *testing.T) {
+ s := New(AutorestartConfig{})
+ s.SetRuntimeConfig(&config.RuntimeConfig{
+ RestartMaxRestarts: 11,
+ RestartInitBackoff: 4 * time.Second,
+ RestartMaxBackoff: 45 * time.Second,
+ RestartStableAfter: 8 * time.Minute,
+ })
+
+ if s.config.MaxRestarts != 11 {
+ t.Fatalf("expected MaxRestarts=11, got %d", s.config.MaxRestarts)
+ }
+ if s.config.InitBackoff != 4*time.Second {
+ t.Fatalf("expected InitBackoff=4s, got %s", s.config.InitBackoff)
+ }
+ if s.config.MaxBackoff != 45*time.Second {
+ t.Fatalf("expected MaxBackoff=45s, got %s", s.config.MaxBackoff)
+ }
+ if s.config.StableAfter != 8*time.Minute {
+ t.Fatalf("expected StableAfter=8m, got %s", s.config.StableAfter)
+ }
+}
+
func TestStrategy_State_InitialStatus(t *testing.T) {
s := New(AutorestartConfig{})
state := s.State()
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index 1ecdc558..3eff09cc 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -26,7 +26,8 @@ type Strategy struct {
orch *orchestrator.Orchestrator
}
-func (s *Strategy) Name() string { return "explicit" }
+func (s *Strategy) Name() string { return "explicit" }
+func (s *Strategy) HandlesLaunch() bool { return false }
// SetOrchestrator injects the orchestrator after construction.
func (s *Strategy) SetOrchestrator(o *orchestrator.Orchestrator) {
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index e84e9e6f..9795ccde 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -33,7 +33,8 @@ type Strategy struct {
orch *orchestrator.Orchestrator
}
-func (s *Strategy) Name() string { return "simple" }
+func (s *Strategy) Name() string { return "simple" }
+func (s *Strategy) HandlesLaunch() bool { return false }
// SetOrchestrator injects the orchestrator after construction.
func (s *Strategy) SetOrchestrator(o *orchestrator.Orchestrator) {
diff --git a/internal/strategy/strategy.go b/internal/strategy/strategy.go
index 3cf24c60..a7bce6b8 100644
--- a/internal/strategy/strategy.go
+++ b/internal/strategy/strategy.go
@@ -8,6 +8,7 @@ import (
"net/http"
"sync"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/orchestrator"
)
@@ -25,6 +26,19 @@ type OrchestratorAware interface {
SetOrchestrator(o *orchestrator.Orchestrator)
}
+// LaunchAware is implemented by strategies that manage instance startup
+// themselves and therefore should suppress the dashboard's separate
+// PINCHTAB_AUTO_LAUNCH fallback.
+type LaunchAware interface {
+ HandlesLaunch() bool
+}
+
+// RuntimeConfigAware is implemented by strategies that need access to
+// runtime configuration at construction time.
+type RuntimeConfigAware interface {
+ SetRuntimeConfig(cfg *config.RuntimeConfig)
+}
+
// Strategy defines a browser allocation approach.
type Strategy interface {
// Name returns the strategy identifier.
diff --git a/internal/strategy/strategy_test.go b/internal/strategy/strategy_test.go
index 5951c5bd..a9928b4a 100644
--- a/internal/strategy/strategy_test.go
+++ b/internal/strategy/strategy_test.go
@@ -6,6 +6,7 @@ import (
"github.com/pinchtab/pinchtab/internal/strategy"
// Register strategies via init()
+ _ "github.com/pinchtab/pinchtab/internal/strategy/alwayson"
_ "github.com/pinchtab/pinchtab/internal/strategy/autorestart"
_ "github.com/pinchtab/pinchtab/internal/strategy/explicit"
_ "github.com/pinchtab/pinchtab/internal/strategy/simple"
@@ -41,6 +42,16 @@ func TestRegistry_SimpleAutorestartRegistered(t *testing.T) {
}
}
+func TestRegistry_AlwaysOnRegistered(t *testing.T) {
+ s, err := strategy.New("always-on")
+ if err != nil {
+ t.Fatalf("always-on strategy not registered: %v", err)
+ }
+ if s.Name() != "always-on" {
+ t.Errorf("expected name 'always-on', got %q", s.Name())
+ }
+}
+
func TestRegistry_UnknownStrategy(t *testing.T) {
_, err := strategy.New("nonexistent")
if err == nil {
@@ -63,10 +74,13 @@ func TestRegistry_Names(t *testing.T) {
if !found["simple-autorestart"] {
t.Error("simple-autorestart not in names")
}
+ if !found["always-on"] {
+ t.Error("always-on not in names")
+ }
}
func TestOrchestratorAware_AllStrategies(t *testing.T) {
- for _, name := range []string{"explicit", "simple", "simple-autorestart"} {
+ for _, name := range []string{"explicit", "simple", "simple-autorestart", "always-on"} {
s, err := strategy.New(name)
if err != nil {
t.Fatalf("strategy %q not registered: %v", name, err)
@@ -76,3 +90,26 @@ func TestOrchestratorAware_AllStrategies(t *testing.T) {
}
}
}
+
+func TestLaunchAware_Strategies(t *testing.T) {
+ tests := map[string]bool{
+ "simple": false,
+ "explicit": false,
+ "simple-autorestart": true,
+ "always-on": true,
+ }
+
+ for name, want := range tests {
+ s, err := strategy.New(name)
+ if err != nil {
+ t.Fatalf("strategy %q not registered: %v", name, err)
+ }
+ launchAware, ok := s.(strategy.LaunchAware)
+ if !ok {
+ t.Fatalf("strategy %q does not implement LaunchAware", name)
+ }
+ if got := launchAware.HandlesLaunch(); got != want {
+ t.Errorf("strategy %q HandlesLaunch=%v, want %v", name, got, want)
+ }
+ }
+}
diff --git a/tests/e2e/config/pinchtab-secure.json b/tests/e2e/config/pinchtab-secure.json
index 20e24bd0..98bd0a08 100644
--- a/tests/e2e/config/pinchtab-secure.json
+++ b/tests/e2e/config/pinchtab-secure.json
@@ -9,6 +9,16 @@
"instanceDefaults": {
"maxTabs": 2
},
+ "multiInstance": {
+ "strategy": "always-on",
+ "allocationPolicy": "fcfs",
+ "restart": {
+ "maxRestarts": 20,
+ "initBackoffSec": 2,
+ "maxBackoffSec": 60,
+ "stableAfterSec": 300
+ }
+ },
"security": {
"allowEvaluate": false,
"allowDownload": false,
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index 22552df3..1635b343 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -9,6 +9,16 @@
"instanceDefaults": {
"maxTabs": 10
},
+ "multiInstance": {
+ "strategy": "always-on",
+ "allocationPolicy": "fcfs",
+ "restart": {
+ "maxRestarts": 20,
+ "initBackoffSec": 2,
+ "maxBackoffSec": 60,
+ "stableAfterSec": 300
+ }
+ },
"security": {
"allowEvaluate": true,
"allowDownload": true,
diff --git a/tests/e2e/scenarios/common.sh b/tests/e2e/scenarios/common.sh
index d49f82fa..22edfb22 100755
--- a/tests/e2e/scenarios/common.sh
+++ b/tests/e2e/scenarios/common.sh
@@ -50,6 +50,32 @@ get_time_ms() {
fi
}
+wait_for_strategy_running() {
+ local base_url="$1"
+ local path="$2"
+ local timeout_sec="${3:-60}"
+ local started_at
+ started_at=$(date +%s)
+
+ while true; do
+ local now
+ now=$(date +%s)
+ if [ $((now - started_at)) -ge "$timeout_sec" ]; then
+ echo -e " ${RED}✗${NC} strategy at ${base_url}${path} did not reach running within ${timeout_sec}s"
+ return 1
+ fi
+
+ local status
+ status=$(curl -sf "${base_url}${path}" 2>/dev/null | jq -r '.status // empty' 2>/dev/null || true)
+ if [ "$status" = "running" ]; then
+ echo -e " ${GREEN}✓${NC} strategy ready at ${base_url}${path}"
+ return 0
+ fi
+
+ sleep 1
+ done
+}
+
# Start a test
start_test() {
CURRENT_TEST="$1"
diff --git a/tests/e2e/scenarios/run-all.sh b/tests/e2e/scenarios/run-all.sh
index 36e32e39..eddee01e 100755
--- a/tests/e2e/scenarios/run-all.sh
+++ b/tests/e2e/scenarios/run-all.sh
@@ -14,6 +14,10 @@ echo "FIXTURES_URL: ${FIXTURES_URL}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
+wait_for_strategy_running "${PINCHTAB_URL}" "/always-on/status"
+wait_for_strategy_running "${PINCHTAB_SECURE_URL}" "/always-on/status"
+echo ""
+
# Find and run all test scripts in order
for script in "${SCRIPT_DIR}"/[0-9][0-9]-*.sh; do
if [ -f "$script" ]; then
diff --git a/tests/integration/main_test.go b/tests/integration/main_test.go
index 6e2a2c5d..17c43dca 100644
--- a/tests/integration/main_test.go
+++ b/tests/integration/main_test.go
@@ -31,9 +31,10 @@ func TestMain(m *testing.M) {
client = testutil.NewClient(server.URL)
- // Launch a test instance for orchestrator-mode tests
- if _, err := testutil.LaunchInstance(server.URL); err != nil {
- fmt.Fprintf(os.Stderr, "failed to launch test instance: %v\n", err)
+ // Wait for the default always-on instance to reach running state before
+ // tests issue shorthand requests like /navigate and /snapshot.
+ if !testutil.WaitForStrategyStatus(server.URL, "/always-on/status", "running", testutil.StrategyTimeout) {
+ fmt.Fprintf(os.Stderr, "always-on strategy did not become ready within %v\n", testutil.StrategyTimeout)
server.Stop()
stopFixtureSite()
os.Exit(1)
diff --git a/tests/testutil/server.go b/tests/testutil/server.go
index cbd813d5..95b706bd 100644
--- a/tests/testutil/server.go
+++ b/tests/testutil/server.go
@@ -23,6 +23,7 @@ const (
HealthTimeoutCI = 60 * time.Second
ShutdownTimeout = 10 * time.Second
InstanceTimeout = 30 * time.Second
+ StrategyTimeout = 60 * time.Second
)
// ServerConfig mirrors key fields from internal/config.RuntimeConfig for test setup.
@@ -49,7 +50,7 @@ type ServerConfig struct {
IDPI appconfig.IDPIConfig
// Orchestrator
- Strategy string // default: "" (uses config default: "simple")
+ Strategy string // default: "" (uses config default: "always-on")
AllocationPolicy string // default: "" (uses config default: "fcfs")
}
@@ -270,6 +271,40 @@ func WaitForHealth(base string, timeout time.Duration) bool {
}
}
+// WaitForStrategyStatus polls a strategy status endpoint until it reports the
+// requested status or the timeout expires.
+func WaitForStrategyStatus(base, path, want string, timeout time.Duration) bool {
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+
+ url := strings.TrimRight(base, "/") + path
+
+ for {
+ select {
+ case <-ctx.Done():
+ return false
+ default:
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
+ if err != nil {
+ continue
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err == nil {
+ var payload struct {
+ Status string `json:"status"`
+ }
+ if resp.StatusCode == 200 && json.NewDecoder(resp.Body).Decode(&payload) == nil && payload.Status == want {
+ _ = resp.Body.Close()
+ return true
+ }
+ _ = resp.Body.Close()
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+}
+
// FindRepoRoot walks up from cwd looking for go.mod.
func FindRepoRoot() string {
dir, _ := os.Getwd()