:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phrocs): add hotkey to restart all failed processes (#58077)
Arnaud Hillen5d4893726c7c
diff --git a/tools/phrocs/README.md b/tools/phrocs/README.mdindex 0a25d850fc1e..b218221b9333 100644--- a/tools/phrocs/README.md+++ b/tools/phrocs/README.md@@ -60,6 +60,7 @@ You typically run phrocs via `hogli start` rather than directly.| `home` | Jump to top of output || `end` | Jump to bottom of output || `r` | Restart selected process |+| `R` | Restart all failed processes || `s` | Stop selected process || `c` | Enter copy mode || `i` | Show process info in pager |diff --git a/tools/phrocs/internal/tui/app.go b/tools/phrocs/internal/tui/app.goindex 067e7610dc72..2f2861ece8ef 100644--- a/tools/phrocs/internal/tui/app.go+++ b/tools/phrocs/internal/tui/app.go@@ -94,8 +94,8 @@ type Model struct {inputBuffer string// Show-all mode: display registry processes not in the current intent config- showAllRegProcs bool- standbyRegProcs []*process.Process // standby processes from registry (not in intent config)+ showAllRegProcs bool+ standbyRegProcs []*process.Process // standby processes from registry (not in intent config)// Setup mode: full-screen intent selection for dev environment configsetupMode booldiff --git a/tools/phrocs/internal/tui/keymap.go b/tools/phrocs/internal/tui/keymap.goindex 10c5652aa1d9..90c76e058ab3 100644--- a/tools/phrocs/internal/tui/keymap.go+++ b/tools/phrocs/internal/tui/keymap.go@@ -3,37 +3,38 @@ package tuiimport "charm.land/bubbles/v2/key"type keyMap struct {- PrevProc key.Binding- NextProc key.Binding- KeyUp key.Binding- KeyDown key.Binding- ScrollUp key.Binding- ScrollDown key.Binding- GotoTop key.Binding- GotoBottom key.Binding- NextPane key.Binding- PrevPane key.Binding- Start key.Binding- Stop key.Binding- Restart key.Binding- ClearLogs key.Binding- CopyMode key.Binding- InfoMode key.Binding- SearchMode key.Binding- SearchNext key.Binding- SearchPrev key.Binding- CommitFilter key.Binding- ToggleFilter key.Binding- Quit key.Binding- Help key.Binding- Backspace key.Binding- Hedgehog key.Binding- Sort key.Binding- Group key.Binding- LazyDocker key.Binding- ProcViewer key.Binding- SetupMode key.Binding- ShowAll key.Binding+ PrevProc key.Binding+ NextProc key.Binding+ KeyUp key.Binding+ KeyDown key.Binding+ ScrollUp key.Binding+ ScrollDown key.Binding+ GotoTop key.Binding+ GotoBottom key.Binding+ NextPane key.Binding+ PrevPane key.Binding+ Start key.Binding+ Stop key.Binding+ Restart key.Binding+ RestartAllFailed key.Binding+ ClearLogs key.Binding+ CopyMode key.Binding+ InfoMode key.Binding+ SearchMode key.Binding+ SearchNext key.Binding+ SearchPrev key.Binding+ CommitFilter key.Binding+ ToggleFilter key.Binding+ Quit key.Binding+ Help key.Binding+ Backspace key.Binding+ Hedgehog key.Binding+ Sort key.Binding+ Group key.Binding+ LazyDocker key.Binding+ ProcViewer key.Binding+ SetupMode key.Binding+ ShowAll key.Binding}func defaultKeyMap() keyMap {@@ -88,6 +89,17 @@ func defaultKeyMap() keyMap {key.WithKeys("r"),key.WithHelp("r:", "restart"),),+ RestartAllFailed: key.NewBinding(+ // Capital R mirrors the lowercase-vs-uppercase pattern used by+ // many TUIs to distinguish "single" vs "bulk" actions.+ // Restarts every proc currently in StatusCrashed (non-zero exit+ // or killed by a signal). Manually-stopped, clean-exit, never-+ // started, and standby procs are all naturally excluded — they+ // sit in different status states.+ key.WithKeys("R"),+ key.WithHelp("R:", "restart all failed"),+ key.WithDisabled(),+ ),ClearLogs: key.NewBinding(key.WithKeys("l"),key.WithHelp("l:", "clear"),diff --git a/tools/phrocs/internal/tui/keys.go b/tools/phrocs/internal/tui/keys.goindex 6fa63602b2ad..795e7825102c 100644--- a/tools/phrocs/internal/tui/keys.go+++ b/tools/phrocs/internal/tui/keys.go@@ -8,6 +8,8 @@ import ("charm.land/bubbles/v2/key"tea "charm.land/bubbletea/v2"++ "github.com/posthog/posthog/phrocs/internal/process")// procViewerCmd returns an exec.Cmd for the best available process viewer,@@ -291,10 +293,14 @@ func (m Model) handleHedgehogKey(msg tea.KeyPressMsg, cmds []tea.Cmd) (Model, []return m, cmds, true}-// updateProcKeys enables/disables start, stop, and restart bindings// based on the active process state.func (m *Model) updateProcKeys() {+ // RestartAllFailed is global (operates across the whole sidebar) and is+ // gated on at-least-one failed proc so the hotkey is a no-op when+ // there's nothing to do.+ m.keys.RestartAllFailed.SetEnabled(m.hasFailedProc())+p := m.activeProc()if p == nil {m.keys.Start.SetEnabled(false)@@ -317,6 +323,41 @@ func (m *Model) updateProcKeys() {m.keys.ClearLogs.SetEnabled(running)}+// hasFailedProc reports whether any sidebar service is currently in+// StatusCrashed — i.e. whether `R` has anything to do.+func (m *Model) hasFailedProc() bool {+ for _, p := range m.services {+ if p.Status() == process.StatusCrashed {+ return true+ }+ }+ return false+}++// restartAllFailed starts every service currently in StatusCrashed in+// display order. Manually-stopped, clean-exit, never-started, and standby+// procs are all in different status states and naturally skipped, so the+// hotkey only ever touches procs that actually died on their own.+// Returns the number of procs that were kicked off.+func (m *Model) restartAllFailed() int {+ send := m.mgr.Send()+ count := 0+ for _, p := range m.services {+ if p.Status() != process.StatusCrashed {+ continue+ }+ m.dbg("restart failed: proc=%s", p.Name)+ // Fan out so we don't block the TUI event loop while Start allocates+ // a PTY and forks the child. As a side benefit, spawns happen in+ // parallel rather than serially. Capture p locally to avoid the+ // closure-over-loop-variable pitfall on older Go versions.+ proc := p+ go func() { _ = proc.Start(send) }()+ count+++ }+ return count+}+func (m Model) handleNormalKey(msg tea.KeyPressMsg, cmds []tea.Cmd) (tea.Model, tea.Cmd) {// When the active process is waiting for input, buffer keystrokes and send them on Enter.p := m.activeProc()@@ -474,6 +515,11 @@ func (m Model) handleNormalKey(msg tea.KeyPressMsg, cmds []tea.Cmd) (tea.Model,go p.Restart(send)}+ case key.Matches(msg, m.keys.RestartAllFailed):+ if started := m.restartAllFailed(); started > 0 {+ m.dbg("restart failed: kicked off %d procs", started)+ }+case key.Matches(msg, m.keys.Stop):if p := m.activeProc(); p != nil && p.IsRunning() {m.dbg("stop: proc=%s", p.Name)diff --git a/tools/phrocs/internal/tui/restart_failed_test.go b/tools/phrocs/internal/tui/restart_failed_test.gonew file mode 100644index 000000000000..42db84afda1d--- /dev/null+++ b/tools/phrocs/internal/tui/restart_failed_test.go@@ -0,0 +1,223 @@+package tui++import (+ "testing"+ "time"++ tea "charm.land/bubbletea/v2"+ "github.com/posthog/posthog/phrocs/internal/config"+ "github.com/posthog/posthog/phrocs/internal/process"+)++// noopSend is a sender that drops every message. Tests don't drive the Bubble+// Tea event loop, so we just need a non-nil function for Manager.send.+func noopSend(tea.Msg) {}++// wireSend installs a no-op sender on the manager — required because+// process.Start panics on a nil send func, and Manager.send is otherwise only+// populated by the real Program at app startup.+func wireSend(m *Model) {+ m.mgr.SetSend(noopSend)+}++// findProc returns the proc with the given name from the model's services.+func findProc(t *testing.T, m Model, name string) *process.Process {+ t.Helper()+ for _, p := range m.services {+ if p.Name == name {+ return p+ }+ }+ t.Fatalf("proc %q not found in services", name)+ return nil+}++// runUntilStatus starts the proc and blocks until it reaches the target+// status. Useful for driving a proc to a known terminal state via a real+// shell exit code (`true` → Done, `false` → Crashed). Skips on PTY failure.+func runUntilStatus(t *testing.T, p *process.Process, send func(tea.Msg), target process.Status) {+ t.Helper()+ if err := p.Start(send); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }+ deadline := time.After(5 * time.Second)+ for p.Status() != target {+ select {+ case <-deadline:+ t.Fatalf("proc %s never reached %s (last status: %s)", p.Name, target, p.Status())+ case <-time.After(20 * time.Millisecond):+ }+ }+ t.Cleanup(func() { p.Stop() })+}++// modelWithProcs builds a ready model where each proc has a custom shell+// command. Useful for setting up mixed-state scenarios (some `false`, some+// `true`, some `sleep`) in a single test.+func modelWithProcs(t *testing.T, shells map[string]string) Model {+ t.Helper()+ f := false+ procs := make(map[string]config.ProcConfig, len(shells))+ for name, shell := range shells {+ procs[name] = config.ProcConfig{Shell: shell, Autostart: &f}+ }+ cfg := &config.Config{+ Procs: procs,+ MouseScrollSpeed: 3,+ Scrollback: 1000,+ }+ mgr := process.NewManager(cfg)+ m := New(mgr, cfg, "", nil)+ next, _ := m.Update(tea.WindowSizeMsg{Width: 120, Height: 40})+ model := next.(Model)+ wireSend(&model)+ return model+}++// ── hasFailedProc ───────────────────────────────────────────────────────────────++func TestHasFailedProc_falseOnFreshModel(t *testing.T) {+ m := readyModel(t, "backend", "frontend")+ if m.hasFailedProc() {+ t.Error("fresh model with never-started procs should have no failed procs")+ }+}++func TestHasFailedProc_falseAfterCleanExit(t *testing.T) {+ // `true` shell exits 0 → StatusDone, NOT failed. This is the key+ // difference from "all stopped/crashed": a clean one-shot exit must+ // not be auto-restarted.+ m := modelWithProcs(t, map[string]string{"oneshot": "true"})+ runUntilStatus(t, findProc(t, m, "oneshot"), m.mgr.Send(), process.StatusDone)+ if m.hasFailedProc() {+ t.Error("clean exit (StatusDone) should not be considered failed")+ }+}++func TestHasFailedProc_trueAfterCrash(t *testing.T) {+ m := modelWithProcs(t, map[string]string{"flaky": "exit 1"})+ runUntilStatus(t, findProc(t, m, "flaky"), m.mgr.Send(), process.StatusCrashed)+ if !m.hasFailedProc() {+ t.Error("non-zero exit (StatusCrashed) should be considered failed")+ }+}++func TestHasFailedProc_falseAfterManualStop(t *testing.T) {+ // Manually-stopped procs sit at StatusStopped — user said stop, leave+ // them stopped. `R` must not undo a manual stop.+ m := modelWithProcs(t, map[string]string{"sleeper": "sleep 30"})+ p := findProc(t, m, "sleeper")+ if err := p.Start(m.mgr.Send()); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }+ deadline := time.After(2 * time.Second)+ for !p.IsRunning() {+ select {+ case <-deadline:+ t.Fatal("sleeper never started")+ case <-time.After(20 * time.Millisecond):+ }+ }+ p.Stop()++ if m.hasFailedProc() {+ t.Error("manually stopped proc (StatusStopped) should not be considered failed")+ }+}++func TestHasFailedProc_falseWhileRunning(t *testing.T) {+ m := modelWithProcs(t, map[string]string{"sleeper": "sleep 30"})+ p := findProc(t, m, "sleeper")+ if err := p.Start(m.mgr.Send()); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }+ t.Cleanup(func() { p.Stop() })++ deadline := time.After(2 * time.Second)+ for !p.IsRunning() {+ select {+ case <-deadline:+ t.Fatal("sleeper never reached running state")+ case <-time.After(20 * time.Millisecond):+ }+ }++ if m.hasFailedProc() {+ t.Error("running procs should not be considered failed")+ }+}++// ── restartAllFailed ────────────────────────────────────────────────────────────++func TestRestartAllFailed_returnsZeroOnFreshModel(t *testing.T) {+ m := readyModel(t, "backend", "frontend")+ if n := m.restartAllFailed(); n != 0 {+ t.Errorf("restartAllFailed on fresh model: got %d, want 0", n)+ }+}++func TestRestartAllFailed_picksOnlyCrashed(t *testing.T) {+ m := modelWithProcs(t, map[string]string{+ "crash-a": "exit 1",+ "crash-b": "exit 2",+ "clean": "true",+ "sleeper": "sleep 30",+ "untouched": "exit 1",+ })+ send := m.mgr.Send()++ // Drive each proc to its terminal state, except "untouched" which we+ // leave as-is so it stays at the never-started StatusStopped.+ runUntilStatus(t, findProc(t, m, "crash-a"), send, process.StatusCrashed)+ runUntilStatus(t, findProc(t, m, "crash-b"), send, process.StatusCrashed)+ runUntilStatus(t, findProc(t, m, "clean"), send, process.StatusDone)++ sleeper := findProc(t, m, "sleeper")+ if err := sleeper.Start(send); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }+ t.Cleanup(func() { sleeper.Stop() })+ deadline := time.After(2 * time.Second)+ for !sleeper.IsRunning() {+ select {+ case <-deadline:+ t.Fatal("sleeper never started")+ case <-time.After(20 * time.Millisecond):+ }+ }++ if n := m.restartAllFailed(); n != 2 {+ t.Errorf("restartAllFailed: got %d, want 2 (only crash-a and crash-b should count)", n)+ }++ // Belt and braces: the non-crashed procs must not have been touched.+ if findProc(t, m, "clean").Status() != process.StatusDone {+ t.Error("clean proc was touched")+ }+ if findProc(t, m, "untouched").Status() != process.StatusStopped {+ t.Error("never-started proc was touched")+ }+ if !sleeper.IsRunning() {+ t.Error("running sleeper was disturbed")+ }+}++// ── updateProcKeys: RestartAllFailed binding gating ──────────────────────────────++func TestUpdateProcKeys_RestartAllFailedDisabledWhenNothingFailed(t *testing.T) {+ m := readyModel(t, "backend", "frontend")+ m.updateProcKeys()+ if m.keys.RestartAllFailed.Enabled() {+ t.Error("RestartAllFailed should be disabled when no proc has crashed")+ }+}++func TestUpdateProcKeys_RestartAllFailedEnabledOnceOneCrashes(t *testing.T) {+ m := modelWithProcs(t, map[string]string{"flaky": "exit 1"})+ runUntilStatus(t, findProc(t, m, "flaky"), m.mgr.Send(), process.StatusCrashed)++ m.updateProcKeys()+ if !m.keys.RestartAllFailed.Enabled() {+ t.Error("RestartAllFailed should be enabled when at least one proc has crashed")+ }+}