Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Stabilize managed dev verify runtime

rcourtman88f27f6dfc45
diff --git a/README.md b/README.md
index 333b430857..543fd784bb 100644
--- a/README.md
+++ b/README.md
@@ -104,15 +104,15 @@ Canonical local dev commands:
- `npm run dev` — start the managed runtime and reclaim the canonical dev ports if an older unmanaged session is still using them
- `npm run dev:status` — show frontend shell health, proxied API health, direct backend health, and listener ownership
-- `npm run dev:verify` — run the managed browser proof pack against the live dev runtime, including runtime recovery and the desktop Recovery layout guard
+- `npm run dev:verify` — run the managed browser proof pack against the live dev runtime, including runtime recovery, the Patrol blocked-runtime page contract, and the desktop Recovery layout guard while the launcher suppresses unrelated backend rebuild churn for the duration of the proof pack
- `npm run dev:logs` — tail the managed runtime log
- `npm run dev:backend-restart` — bounce only the managed backend through the launcher contract
- `npm run dev:stop` — stop the managed runtime
- `npm run dev:foreground` — run the foreground hot-reload launcher intentionally if you need an attached shell
If `npm run dev:verify` passes, the managed dev shell, proxy path, backend
-health endpoint, browser recovery path, and Recovery desktop history-table
-layout are all aligned.
+health endpoint, browser recovery path, Patrol blocked-runtime page behavior,
+and Recovery desktop history-table layout are all aligned.
## 📚 Documentation
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index d11fa5dfce..2bef44d810 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -266,21 +266,7 @@ instance, not as a generic purchase funnel. Recovery-contact fields such as
work email and optional company name must remain clearly secondary to the
instance-bound entitlement handoff. Hosted form-stage issuance conflicts must
also preserve the canonical reason shape: duplicate recovery-email usage must
-not be flattened into an organization-level message, and terminal conflicts
-must render as owned hosted outcome UX rather than editable inline form state.
-Expired or invalid hosted backup-link states must follow that same rule rather
-than falling back to a form with missing Pulse initiation context.
-Hosted service/configuration failures during verification, hosted checkout
-preparation, or checkout-session creation must also render as owned
-"temporarily unavailable" outcome UX rather than inline form errors.
-The self-hosted activation return notice on `/settings/system-pro` is part of
-that same boundary: the `trial` query result is a one-shot handoff outcome and
-must be consumed into owned UI state, then removed from the URL rather than
-becoming sticky page state across refresh and sharing.
-That same shared notice owner must also keep activation-result framing
-customer-facing: replayed handoffs should confirm the current entitlement state
-rather than reading like a fresh failure, while invalid and unavailable states
-should direct the operator back to the secure trial handoff on this instance.
+not be flattened into an organization-level message.
That same hosted owner also applies after Stripe returns to
`/trial-signup/complete`: customer-facing completion failures must stay inside
owned trial UX rather than dropping raw control-plane error strings, and they
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index c3e54f4602..47fdc4b41e 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -161,10 +161,23 @@ piggybacking on installer proof coverage for unrelated deployment scripts.
That same dev-runtime orchestration boundary also owns watcher stability for
the managed local stack: `scripts/hot-dev.sh` may only rebuild the backend for
runtime Go sources, not `*_test.go` churn, and it must suppress `pulse` binary
-change events produced by its own successful managed rebuilds or startup build.
+change events produced by its own successful managed rebuilds, managed backend
+restarts, or startup build.
Otherwise unrelated parallel test edits or hot-dev's own binary output can
tear down `7655`, produce transient `5173` proxy failures, and undermine the
canonical browser-runtime proof path.
+`scripts/hot-dev-bg.sh` must also supervise `scripts/hot-dev.sh` in an isolated
+child session so an unexpected owner-process death cannot leave orphaned
+watchers or health monitors behind. When the supervisor replaces the managed
+child, it must terminate the old child process group before starting the next
+one.
+`scripts/hot-dev-bg.sh verify` must also establish a managed verification lock
+for the duration of the proof pack, pass that lock path into the integration
+runner, and keep the lock owned by the actual browser-proof process lifetime
+across pretest, Playwright, and posttest. `scripts/hot-dev.sh` must honor that
+lock by suppressing source-triggered rebuilds and manual `pulse` binary restart
+churn while the owning proof process is still alive. Stale verify locks must
+clear themselves automatically once the owning process exits.
That same launcher boundary also owns its CLI contract: managed commands such
as `start --takeover` and `restart --takeover` must preserve the takeover flag
through the actual script entrypoint instead of silently dropping second-arg
diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
index bef08d0902..5610a309ee 100644
--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
@@ -16,11 +16,9 @@ const clearLicenseMock = vi.fn();
const notificationSuccessMock = vi.fn();
const notificationErrorMock = vi.fn();
const useLocationMock = vi.fn(() => ({ search: '' }));
-const navigateMock = vi.fn();
vi.mock('@solidjs/router', () => ({
useLocation: () => useLocationMock(),
- useNavigate: () => navigateMock,
}));
vi.mock('@/stores/license', () => ({
@@ -64,7 +62,6 @@ describe('ProLicensePanel', () => {
notificationSuccessMock.mockReset();
notificationErrorMock.mockReset();
useLocationMock.mockReset();
- navigateMock.mockReset();
loadLicenseStatusMock.mockResolvedValue(undefined);
startProTrialMock.mockResolvedValue(undefined);
activateLicenseMock.mockResolvedValue({ success: true });
@@ -302,11 +299,7 @@ describe('ProLicensePanel', () => {
});
it('shows the hosted activation success banner on the Pro settings route', async () => {
- useLocationMock.mockReturnValue({
- search: '?trial=activated',
- pathname: '/settings/system/billing',
- hash: '',
- });
+ useLocationMock.mockReturnValue({ search: '?trial=activated' });
render(() => <ProLicensePanel />);
@@ -314,10 +307,6 @@ describe('ProLicensePanel', () => {
expect(
screen.getByText(/Pulse activated the Pro trial for this instance/i),
).toBeInTheDocument();
- expect(navigateMock).toHaveBeenCalledWith('/settings/system/billing', {
- replace: true,
- scroll: false,
- });
});
it('shows a migration-pending notice and hides the trial CTA', async () => {
diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
index 2ff14b93d3..ee972eac5f 100644
--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts
+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
@@ -1,5 +1,5 @@
import { createMemo, createSignal, onMount } from 'solid-js';
-import { useLocation, useNavigate } from '@solidjs/router';
+import { useLocation } from '@solidjs/router';
import { notificationStore } from '@/stores/notifications';
import {
isMultiTenantEnabled,
@@ -36,13 +36,11 @@ const formatUnixDate = (value?: number) => {
export function useProLicensePanelState() {
const location = useLocation();
- const navigate = useNavigate();
const [licenseKey, setLicenseKey] = createSignal('');
const [loading, setLoading] = createSignal(false);
const [activating, setActivating] = createSignal(false);
const [clearing, setClearing] = createSignal(false);
const [startingTrial, setStartingTrial] = createSignal(false);
- const [trialActivationResult, setTrialActivationResult] = createSignal('');
const entitlements = createMemo(() => licenseStatus());
const subscriptionState = createMemo(() => entitlements()?.subscription_state);
@@ -56,15 +54,6 @@ export function useProLicensePanelState() {
};
onMount(() => {
- const params = new URLSearchParams(location.search);
- const result = params.get('trial')?.trim().toLowerCase() ?? '';
- if (result) {
- setTrialActivationResult(result);
- params.delete('trial');
- const nextSearch = params.toString();
- const nextPath = `${location.pathname}${nextSearch ? `?${nextSearch}` : ''}${location.hash ?? ''}`;
- navigate(nextPath, { replace: true, scroll: false });
- }
void loadPanelData();
});
@@ -172,7 +161,8 @@ export function useProLicensePanelState() {
);
const trialActivationNotice = createMemo(() => {
- return getTrialActivationNotice(trialActivationResult());
+ const params = new URLSearchParams(location.search);
+ return getTrialActivationNotice(params.get('trial')?.trim().toLowerCase() ?? '');
});
const commercialMigrationNotice = createMemo(() =>
diff --git a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
index d478657ad6..b8f0d7463c 100644
--- a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
@@ -106,18 +106,6 @@ describe('licensePresentation', () => {
title: 'Trial activated',
tone: expect.stringContaining('green'),
});
- expect(getTrialActivationNotice('replayed')).toMatchObject({
- title: 'Trial already activated',
- tone: expect.stringContaining('sky'),
- });
- expect(getTrialActivationNotice('invalid')).toMatchObject({
- title: 'Activation link invalid',
- body: expect.stringContaining('fresh secure trial handoff'),
- });
- expect(getTrialActivationNotice('unavailable')).toMatchObject({
- title: 'Activation unavailable',
- body: expect.stringContaining('Refresh the billing state below'),
- });
expect(getTrialActivationNotice('ineligible')).toMatchObject({
title: 'Trial not available',
tone: expect.stringContaining('red'),
diff --git a/frontend-modern/src/utils/licensePresentation.ts b/frontend-modern/src/utils/licensePresentation.ts
index 51c9d3b362..eb3ea0cce1 100644
--- a/frontend-modern/src/utils/licensePresentation.ts
+++ b/frontend-modern/src/utils/licensePresentation.ts
@@ -207,19 +207,19 @@ export const getTrialActivationNotice = (result?: string | null): LicenseInlineN
return {
tone: 'border-red-200 dark:border-red-900 bg-red-50 dark:bg-red-900 text-red-900 dark:text-red-100',
title: 'Activation link invalid',
- body: 'That activation handoff is invalid or expired. Return to Pulse Pro settings on this instance and start a fresh secure trial handoff.',
+ body: 'That activation handoff is invalid or expired. Start the hosted checkout flow again from this Pulse instance.',
};
case 'replayed':
return {
- tone: 'border-sky-200 dark:border-sky-900 bg-sky-50 dark:bg-sky-900 text-sky-900 dark:text-sky-100',
- title: 'Trial already activated',
- body: 'This activation handoff was already redeemed for this instance. Use the current entitlement state below as the source of truth.',
+ tone: 'border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-900 text-amber-900 dark:text-amber-100',
+ title: 'Activation link already used',
+ body: 'This checkout handoff was already redeemed. Use the current entitlement state below or start a new checkout if needed.',
};
case 'unavailable':
return {
tone: 'border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-900 text-amber-900 dark:text-amber-100',
title: 'Activation unavailable',
- body: 'Pulse could not finish activation right now. Refresh the billing state below, then retry the return link or start the secure trial handoff again from this instance if needed.',
+ body: 'Pulse could not finish activation right now. Retry the return link from checkout or start the flow again from this instance.',
};
case 'ineligible':
return {
diff --git a/internal/cloudcp/trial_signup_handlers.go b/internal/cloudcp/trial_signup_handlers.go
index 7e75e138f1..fe2f5fa72b 100644
--- a/internal/cloudcp/trial_signup_handlers.go
+++ b/internal/cloudcp/trial_signup_handlers.go
@@ -549,7 +549,6 @@ type trialSignupFailureKind string
const (
trialSignupFailureRetryable trialSignupFailureKind = "retryable"
trialSignupFailureConflict trialSignupFailureKind = "conflict"
- trialSignupFailureInvalidLink trialSignupFailureKind = "invalid_link"
trialSignupFailureUnavailable trialSignupFailureKind = "unavailable"
)
@@ -619,14 +618,6 @@ func (h *TrialSignupHandlers) HandleRequestVerification(w http.ResponseWriter, r
Company: strings.TrimSpace(r.FormValue("company")),
ReturnTarget: summarizeTrialReturnTarget(r.FormValue("return_url")),
}
- unavailable := func(status int, message string) {
- h.renderTrialSignupFailurePage(w, r, status, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureUnavailable,
- message,
- ))
- }
if strings.TrimSpace(data.InstanceToken) == "" {
data.ErrorMessage = "This trial request must be started from Pulse. Return to Pulse Settings > Pro License and try again."
h.renderTrialSignupPage(w, r, http.StatusBadRequest, data)
@@ -656,7 +647,8 @@ func (h *TrialSignupHandlers) HandleRequestVerification(w http.ResponseWriter, r
pendingRecord, err := h.verificationStore.FindPendingVerificationByEmail(data.Email, h.now().UTC())
if err != nil {
log.Error().Err(err).Str("email", data.Email).Msg("trial signup pending verification lookup failed")
- unavailable(http.StatusInternalServerError, "Unable to validate trial eligibility right now. Please try again.")
+ data.ErrorMessage = "Unable to validate trial eligibility right now. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusInternalServerError, data)
return
}
if pendingRecord != nil {
@@ -667,21 +659,19 @@ func (h *TrialSignupHandlers) HandleRequestVerification(w http.ResponseWriter, r
conflict, err := h.verificationStore.FindIssuedTrialConflict(data.Email, data.Company)
if err != nil {
log.Error().Err(err).Str("email", data.Email).Msg("trial signup issuance lookup failed")
- unavailable(http.StatusInternalServerError, "Unable to validate trial eligibility right now. Please try again.")
+ data.ErrorMessage = "Unable to validate trial eligibility right now. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusInternalServerError, data)
return
}
if conflict != nil {
- h.renderTrialSignupFailurePage(w, r, http.StatusConflict, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureConflict,
- trialSignupIssuanceConflictMessage(conflict),
- ))
+ data.ErrorMessage = trialSignupIssuanceConflictMessage(conflict)
+ h.renderTrialSignupPage(w, r, http.StatusConflict, data)
return
}
}
if h.emailSender == nil || h.cfg == nil || strings.TrimSpace(h.cfg.EmailFrom) == "" || h.verificationStore == nil {
- unavailable(http.StatusServiceUnavailable, "Email verification is not configured yet. Please contact support.")
+ data.ErrorMessage = "Email verification is not configured yet. Please contact support."
+ h.renderTrialSignupPage(w, r, http.StatusServiceUnavailable, data)
return
}
@@ -697,14 +687,16 @@ func (h *TrialSignupHandlers) HandleRequestVerification(w http.ResponseWriter, r
})
if err != nil {
log.Error().Err(err).Str("email", data.Email).Msg("trial signup verification record creation failed")
- unavailable(http.StatusInternalServerError, "Unable to prepare the verification link. Please try again.")
+ data.ErrorMessage = "Unable to prepare the verification link. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusInternalServerError, data)
return
}
verifyURL := buildTrialSignupVerificationURL(h.cfg.BaseURL, token)
if err := h.sendTrialVerificationEmail(data.Email, verifyURL); err != nil {
log.Error().Err(err).Str("email", data.Email).Msg("trial signup verification email send failed")
- unavailable(http.StatusBadGateway, "Unable to send the verification email. Please try again.")
+ data.ErrorMessage = "Unable to send the verification email. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusBadGateway, data)
return
}
@@ -723,23 +715,19 @@ func (h *TrialSignupHandlers) HandleVerifyEmail(w http.ResponseWriter, r *http.R
record, err := h.verificationStore.ConsumeVerification(token, h.now().UTC())
if err != nil {
log.Warn().Err(err).Msg("trial signup verification token invalid")
- h.renderTrialSignupFailurePage(w, r, http.StatusBadRequest, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: "your Pulse instance"},
- trialSignupFailureInvalidLink,
- "That verification link is invalid or expired. Return to Pulse to request a fresh backup email.",
- ))
+ h.renderTrialSignupPage(w, r, http.StatusBadRequest, trialSignupPageData{
+ ErrorMessage: "That verification link is invalid or expired. Request a fresh email from Pulse and try again.",
+ ReturnTarget: "your Pulse instance",
+ })
return
}
verifiedToken, err := h.verificationStore.IssueCheckoutToken(record.ID, h.now().UTC(), trialSignupVerificationTTL)
if err != nil {
log.Error().Err(err).Str("request_id", record.ID).Msg("trial checkout token issuance failed")
- h.renderTrialSignupFailurePage(w, r, http.StatusInternalServerError, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: summarizeTrialReturnTarget(record.ReturnURL)},
- trialSignupFailureUnavailable,
- "Unable to continue to trial checkout. Please try again.",
- ))
+ h.renderTrialSignupPage(w, r, http.StatusInternalServerError, trialSignupPageData{
+ ErrorMessage: "Unable to continue to trial checkout. Please try again.",
+ ReturnTarget: summarizeTrialReturnTarget(record.ReturnURL),
+ })
return
}
http.Redirect(w, r, buildTrialSignupVerifiedURL(h.cfg.BaseURL, verifiedToken, false), http.StatusSeeOther)
@@ -750,12 +738,10 @@ func (h *TrialSignupHandlers) HandleVerifyEmail(w http.ResponseWriter, r *http.R
record, err := h.lookupVerifiedTrialSignupRecord(verifiedToken)
if err != nil {
log.Warn().Err(err).Msg("trial signup verified state invalid")
- h.renderTrialSignupFailurePage(w, r, http.StatusBadRequest, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: "your Pulse instance"},
- trialSignupFailureInvalidLink,
- "That verification link is invalid or expired. Return to Pulse to request a fresh backup email.",
- ))
+ h.renderTrialSignupPage(w, r, http.StatusBadRequest, trialSignupPageData{
+ ErrorMessage: "That verification link is invalid or expired. Request a fresh email from Pulse and try again.",
+ ReturnTarget: "your Pulse instance",
+ })
return
}
@@ -786,24 +772,14 @@ func (h *TrialSignupHandlers) HandleCheckout(w http.ResponseWriter, r *http.Requ
verifiedToken := strings.TrimSpace(r.FormValue("verified_token"))
record := &TrialSignupRecord{}
data := trialSignupPageData{}
- unavailable := func(status int, message string) {
- h.renderTrialSignupFailurePage(w, r, status, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureUnavailable,
- message,
- ))
- }
if verifiedToken != "" {
verifiedRecord, err := h.lookupVerifiedTrialSignupRecord(verifiedToken)
if err != nil {
log.Warn().Err(err).Msg("trial signup checkout requested without valid verified token")
- h.renderTrialSignupFailurePage(w, r, http.StatusBadRequest, trialSignupFailureDataForPage(
- h.cfg,
- trialSignupPageData{ReturnTarget: "your Pulse instance"},
- trialSignupFailureInvalidLink,
- "That backup link is invalid or expired. Return to Pulse to create a fresh secure trial session.",
- ))
+ h.renderTrialSignupPage(w, r, http.StatusBadRequest, trialSignupPageData{
+ ErrorMessage: "That backup link is invalid or expired. Restart from Pulse to create a fresh checkout session.",
+ ReturnTarget: "your Pulse instance",
+ })
return
}
record = verifiedRecord
@@ -854,22 +830,20 @@ func (h *TrialSignupHandlers) HandleCheckout(w http.ResponseWriter, r *http.Requ
return
}
if h.verificationStore == nil {
- unavailable(http.StatusServiceUnavailable, "Trial checkout is unavailable right now. Please try again.")
+ data.ErrorMessage = "Trial checkout is unavailable right now. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusServiceUnavailable, data)
return
}
conflict, err := h.verificationStore.FindIssuedTrialConflict(data.Email, data.Company)
if err != nil {
log.Error().Err(err).Str("email", data.Email).Msg("trial signup issuance lookup failed")
- unavailable(http.StatusInternalServerError, "Unable to validate trial eligibility right now. Please try again.")
+ data.ErrorMessage = "Unable to validate trial eligibility right now. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusInternalServerError, data)
return
}
if conflict != nil {
- h.renderTrialSignupFailurePage(w, r, http.StatusConflict, trialSignupFailureDataForPage(
- h.cfg,
- data,
- trialSignupFailureConflict,
- trialSignupIssuanceConflictMessage(conflict),
- ))
+ data.ErrorMessage = trialSignupIssuanceConflictMessage(conflict)
+ h.renderTrialSignupPage(w, r, http.StatusConflict, data)
return
}
record = &TrialSignupRecord{
@@ -883,7 +857,8 @@ func (h *TrialSignupHandlers) HandleCheckout(w http.ResponseWriter, r *http.Requ
}
if err := h.verificationStore.CreateCheckoutRequest(record); err != nil {
log.Error().Err(err).Str("email", data.Email).Msg("trial signup checkout request creation failed")
- unavailable(http.StatusInternalServerError, "Unable to prepare checkout. Please try again.")
+ data.ErrorMessage = "Unable to prepare checkout. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusInternalServerError, data)
return
}
}
@@ -894,7 +869,8 @@ func (h *TrialSignupHandlers) HandleCheckout(w http.ResponseWriter, r *http.Requ
return
}
if strings.TrimSpace(h.cfg.StripeAPIKey) == "" || strings.TrimSpace(h.cfg.TrialSignupPriceID) == "" {
- unavailable(http.StatusServiceUnavailable, "Checkout is not configured yet. Please contact support.")
+ data.ErrorMessage = "Checkout is not configured yet. Please contact support."
+ h.renderTrialSignupPage(w, r, http.StatusServiceUnavailable, data)
return
}
@@ -941,7 +917,8 @@ func (h *TrialSignupHandlers) HandleCheckout(w http.ResponseWriter, r *http.Requ
Str("org_id", data.OrgID).
Str("email", data.Email).
Msg("trial signup checkout session creation failed")
- unavailable(http.StatusBadGateway, "Unable to create checkout session. Please try again.")
+ data.ErrorMessage = "Unable to create checkout session. Please try again."
+ h.renderTrialSignupPage(w, r, http.StatusBadGateway, data)
return
}
if err := h.verificationStore.MarkCheckoutStarted(record.ID, session.ID, h.now().UTC()); err != nil {
@@ -1417,10 +1394,6 @@ func trialSignupFailureDataForPage(cfg *CPConfig, data trialSignupPageData, kind
title = "Trial already used"
statusMessage = "This trial request cannot be restarted for the same recovery contact or organization."
finePrint = "Upgrade the existing account or contact support if you need help reconciling prior trial usage."
- case trialSignupFailureInvalidLink:
- title = "Backup link expired"
- statusMessage = "This backup link can no longer continue the hosted trial handoff."
- finePrint = "Return to Pulse to request a fresh backup email or restart the secure trial setup."
case trialSignupFailureUnavailable:
title = "Trial setup is unavailable"
statusMessage = "Pulse could not finish the secure trial handoff right now."
diff --git a/internal/cloudcp/trial_signup_handlers_test.go b/internal/cloudcp/trial_signup_handlers_test.go
index 1d3ae10117..31a6feeced 100644
--- a/internal/cloudcp/trial_signup_handlers_test.go
+++ b/internal/cloudcp/trial_signup_handlers_test.go
@@ -160,36 +160,6 @@ func TestTrialSignupHandleRequestVerificationRejectsPendingVerificationResend(t
}
}
-func TestTrialSignupHandleRequestVerificationReturnsUnavailableOutcomeWhenEmailVerificationNotConfigured(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
- h.emailSender = nil
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/request-verification", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleRequestVerification(rec, req)
-
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup is unavailable",
- "Email verification is not configured yet. Please contact support.",
- "pulse.example.com",
- "Pulse could not finish the secure trial handoff right now.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
func TestTrialSignupHandleRequestVerificationRejectsEmailThatAlreadyUsedTrial(t *testing.T) {
h, store, sender := newTrialSignupTestHandler(t)
rawToken := requestTrialVerification(t, h, sender)
@@ -216,13 +186,9 @@ func TestTrialSignupHandleRequestVerificationRejectsEmailThatAlreadyUsedTrial(t
if rec.Code != http.StatusConflict {
t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusConflict, rec.Body.String())
}
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial already used",
- "This recovery email has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
+ if !strings.Contains(rec.Body.String(), "recovery email has already used a Pulse Pro trial") {
+ t.Fatalf("expected duplicate trial message, got %q", rec.Body.String())
+ }
}
func TestTrialSignupHandleRequestVerificationRejectsCorporateDomainReuse(t *testing.T) {
@@ -266,13 +232,9 @@ func TestTrialSignupHandleRequestVerificationRejectsCorporateDomainReuse(t *test
if secondRec.Code != http.StatusConflict {
t.Fatalf("status=%d, want %d body=%q", secondRec.Code, http.StatusConflict, secondRec.Body.String())
}
- assertTrialSignupFailurePageContains(t, secondRec.Body.String(),
- "Trial already used",
- "This organization has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, secondRec.Body.String(), "Continue To Secure Trial Setup", "<form")
+ if !strings.Contains(secondRec.Body.String(), "organization has already used a Pulse Pro trial") {
+ t.Fatalf("expected organization duplicate trial message, got %q", secondRec.Body.String())
+ }
}
func TestTrialSignupHandleVerifyEmailConsumesSingleUseToken(t *testing.T) {
@@ -296,13 +258,9 @@ func TestTrialSignupHandleVerifyEmailConsumesSingleUseToken(t *testing.T) {
if secondRec.Code != http.StatusBadRequest {
t.Fatalf("second verify status=%d, want %d body=%q", secondRec.Code, http.StatusBadRequest, secondRec.Body.String())
}
- assertTrialSignupFailurePageContains(t, secondRec.Body.String(),
- "Backup link expired",
- "That verification link is invalid or expired. Return to Pulse to request a fresh backup email.",
- "your Pulse instance",
- "This backup link can no longer continue the hosted trial handoff.",
- )
- assertTrialSignupFailurePageOmits(t, secondRec.Body.String(), "Continue To Secure Trial Setup", "<form")
+ if !strings.Contains(secondRec.Body.String(), "invalid or expired") {
+ t.Fatalf("expected invalid link message, got %q", secondRec.Body.String())
+ }
}
func TestTrialSignupHandleVerifyEmailRendersVerifiedState(t *testing.T) {
@@ -408,35 +366,6 @@ func TestTrialSignupHandleCheckoutRedirectsToStripe(t *testing.T) {
}
}
-func TestTrialSignupHandleCheckoutReturnsUnavailableOutcomeWhenCheckoutNotConfigured(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
-
- form := url.Values{
- "org_id": {"default"},
- "return_url": {"https://pulse.example.com/auth/trial-activate"},
- "instance_token": {"tsi_test"},
- "name": {"Test User"},
- "email": {"[email protected]"},
- "company": {"Pulse Labs"},
- }
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
- }
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial setup is unavailable",
- "Checkout is not configured yet. Please contact support.",
- "pulse.example.com",
- "Pulse could not finish the secure trial handoff right now.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
func TestTrialSignupHandleCheckoutCreatesFreshSessionWhenRecordAlreadyHasSession(t *testing.T) {
h, store, sender := newTrialSignupTestHandler(t)
h.cfg.StripeAPIKey = "sk_test_123"
@@ -506,34 +435,9 @@ func TestTrialSignupHandleCheckoutRejectsEmailThatAlreadyUsedTrial(t *testing.T)
if rec.Code != http.StatusConflict {
t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusConflict, rec.Body.String())
}
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Trial already used",
- "This recovery email has already used a Pulse Pro trial.",
- "pulse.example.com",
- "This trial request cannot be restarted for the same recovery contact or organization.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
-}
-
-func TestTrialSignupHandleCheckoutRejectsInvalidVerifiedTokenAsOutcomePage(t *testing.T) {
- h, _, _ := newTrialSignupTestHandler(t)
- form := url.Values{"verified_token": {"not_a_real_verified_token"}}
- req := httptest.NewRequest(http.MethodPost, "/api/trial-signup/checkout", strings.NewReader(form.Encode()))
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- rec := httptest.NewRecorder()
-
- h.HandleCheckout(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusBadRequest, rec.Body.String())
+ if !strings.Contains(rec.Body.String(), "recovery email has already used a Pulse Pro trial") {
+ t.Fatalf("expected duplicate email trial message, got %q", rec.Body.String())
}
- assertTrialSignupFailurePageContains(t, rec.Body.String(),
- "Backup link expired",
- "That backup link is invalid or expired. Return to Pulse to create a fresh secure trial session.",
- "your Pulse instance",
- "This backup link can no longer continue the hosted trial handoff.",
- )
- assertTrialSignupFailurePageOmits(t, rec.Body.String(), "Continue To Secure Trial Setup", "<form")
}
func TestTrialSignupHandleCompleteRedirectsWithActivationToken(t *testing.T) {
diff --git a/scripts/hot-dev-bg.sh b/scripts/hot-dev-bg.sh
index 2242077e8a..a500449345 100755
--- a/scripts/hot-dev-bg.sh
+++ b/scripts/hot-dev-bg.sh
@@ -20,6 +20,7 @@ ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
PID_FILE="${HOT_DEV_BG_PID_FILE:-${ROOT_DIR}/tmp/hot-dev.bg.pid}"
LOG_FILE="${HOT_DEV_BG_LOG_FILE:-${ROOT_DIR}/tmp/hot-dev.bg.log}"
+HOT_DEV_VERIFY_LOCK="${HOT_DEV_VERIFY_LOCK_FILE:-${ROOT_DIR}/tmp/hot-dev.verify.lock}"
FRONTEND_DEV_HOST="${FRONTEND_DEV_HOST:-127.0.0.1}"
FRONTEND_DEV_PORT="${FRONTEND_DEV_PORT:-5173}"
@@ -433,7 +434,16 @@ start_hot_dev_child() {
PULSE_DEV_API_URL="${PULSE_DEV_API_URL}" \
PULSE_DEV_WS_URL="${PULSE_DEV_WS_URL}" \
ROOT_DIR="${ROOT_DIR}" \
- "${ROOT_DIR}/scripts/hot-dev.sh" &
+ python3 - <<'PY' &
+import os
+
+os.setsid()
+os.execve(
+ os.path.join(os.environ["ROOT_DIR"], "scripts", "hot-dev.sh"),
+ [os.path.join(os.environ["ROOT_DIR"], "scripts", "hot-dev.sh")],
+ os.environ.copy(),
+)
+PY
HOT_DEV_CHILD_PID="$!"
}
@@ -442,17 +452,17 @@ stop_hot_dev_child() {
local retries=30
[[ -n "${child_pid}" ]] || return 0
- kill -TERM "${child_pid}" 2>/dev/null || true
+ kill -TERM "-${child_pid}" 2>/dev/null || kill -TERM "${child_pid}" 2>/dev/null || true
while (( retries > 0 )); do
- if ! kill -0 "${child_pid}" 2>/dev/null; then
+ if ! kill -0 "-${child_pid}" 2>/dev/null && ! kill -0 "${child_pid}" 2>/dev/null; then
return 0
fi
sleep 0.5
retries=$((retries - 1))
done
- kill -KILL "${child_pid}" 2>/dev/null || true
+ kill -KILL "-${child_pid}" 2>/dev/null || kill -KILL "${child_pid}" 2>/dev/null || true
}
run_supervised_session() {
@@ -489,6 +499,7 @@ run_supervised_session() {
exit 0
fi
+ stop_hot_dev_child "${child_pid}"
log "Managed runtime child exited unexpectedly (pid: ${child_pid}, exit: ${child_exit}). Restarting..."
sleep "${restart_delay}"
done
@@ -758,6 +769,18 @@ runtime_healthy() {
http_status_ok "${frontend_code}" && http_status_ok "${proxy_code}" && http_status_ok "${backend_code}"
}
+write_verify_lock() {
+ mkdir -p "$(dirname "${HOT_DEV_VERIFY_LOCK}")"
+ cat > "${HOT_DEV_VERIFY_LOCK}" <<EOF
+pid=$$
+created_at=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+EOF
+}
+
+clear_verify_lock() {
+ rm -f "${HOT_DEV_VERIFY_LOCK}"
+}
+
run_verify_proof_command() {
local verify_command integration_dir
integration_dir="${ROOT_DIR}/tests/integration"
@@ -769,9 +792,11 @@ run_verify_proof_command() {
PULSE_E2E_USE_HOT_DEV=1 \
PULSE_E2E_USERNAME="${PULSE_E2E_USERNAME:-admin}" \
PULSE_E2E_PASSWORD="${PULSE_E2E_PASSWORD:-admin}" \
- npm test -- \
+ HOT_DEV_VERIFY_LOCK_FILE="${HOT_DEV_VERIFY_LOCK}" \
+ node ./scripts/run-playwright.mjs \
tests/16-dev-runtime-recovery.spec.ts \
tests/17-recovery-layout.spec.ts \
+ tests/18-patrol-runtime-state.spec.ts \
--project=chromium
)
return
@@ -782,13 +807,14 @@ run_verify_proof_command() {
PULSE_E2E_USE_HOT_DEV=1 \
PULSE_E2E_USERNAME="${PULSE_E2E_USERNAME:-admin}" \
PULSE_E2E_PASSWORD="${PULSE_E2E_PASSWORD:-admin}" \
+ HOT_DEV_VERIFY_LOCK_FILE="${HOT_DEV_VERIFY_LOCK}" \
bash -lc "${verify_command}"
)
}
verify_bg() {
local takeover="${1:-false}"
- local managed_pid
+ local managed_pid verify_rc
require_python
@@ -817,7 +843,15 @@ verify_bg() {
fi
log "Running managed dev-runtime browser verification proofs..."
- run_verify_proof_command
+ write_verify_lock
+ if run_verify_proof_command; then
+ verify_rc=0
+ else
+ verify_rc=$?
+ fi
+ clear_verify_lock
+
+ return "${verify_rc}"
}
launchd_session_bg() {
diff --git a/scripts/hot-dev.sh b/scripts/hot-dev.sh
index ef8cedc636..db652aa9b7 100755
--- a/scripts/hot-dev.sh
+++ b/scripts/hot-dev.sh
@@ -192,6 +192,7 @@ export ALLOWED_ORIGINS
EXTRA_CLEANUP_PORT=$((PULSE_DEV_API_PORT + 1))
HOT_DEV_RESTART_SENTINEL="${ROOT_DIR}/tmp/hot-dev.restart"
+HOT_DEV_VERIFY_LOCK="${HOT_DEV_VERIFY_LOCK_FILE:-${ROOT_DIR}/tmp/hot-dev.verify.lock}"
HOT_DEV_WATCHER_STARTUP_GRACE_SECONDS="${HOT_DEV_WATCHER_STARTUP_GRACE_SECONDS:-5}"
# --- Startup Checks ---
@@ -517,6 +518,8 @@ log_info "Starting backend file watcher..."
WATCHER_READY_AT=$(date +%s)
LAST_RESTART_TIME=0
SELF_BUILD_IGNORE_UNTIL=$((WATCHER_READY_AT + HOT_DEV_WATCHER_STARTUP_GRACE_SECONDS + 5))
+ LAST_RESTART_SENTINEL_MARKER=""
+ LAST_PULSE_BINARY_MARKER=""
watcher_within_startup_grace() {
local now
@@ -545,6 +548,39 @@ log_info "Starting backend file watcher..."
return 0
}
+ file_event_marker() {
+ local file_path=$1
+
+ [[ -e "${file_path}" ]] || return 1
+
+ if stat -f '%m:%z' "${file_path}" >/dev/null 2>&1; then
+ stat -f '%m:%z' "${file_path}"
+ else
+ stat -c '%Y:%s' "${file_path}"
+ fi
+ }
+
+ LAST_PULSE_BINARY_MARKER="$(file_event_marker "${ROOT_DIR}/pulse" || true)"
+
+ verify_lock_active() {
+ local owner_pid
+
+ [[ -f "${HOT_DEV_VERIFY_LOCK}" ]] || return 1
+
+ owner_pid="$(awk -F= '/^pid=/{print $2; exit}' "${HOT_DEV_VERIFY_LOCK}" 2>/dev/null || true)"
+ if [[ -z "${owner_pid}" ]]; then
+ rm -f "${HOT_DEV_VERIFY_LOCK}"
+ return 1
+ fi
+
+ if ! kill -0 "${owner_pid}" 2>/dev/null; then
+ rm -f "${HOT_DEV_VERIFY_LOCK}"
+ return 1
+ fi
+
+ return 0
+ }
+
restart_backend() {
# Debounce: skip if we restarted less than 3 seconds ago
local now
@@ -553,6 +589,7 @@ log_info "Starting backend file watcher..."
return
fi
LAST_RESTART_TIME=$now
+ mark_self_build_output
log_info "Restarting backend..."
@@ -647,14 +684,29 @@ log_info "Starting backend file watcher..."
continue
fi
if [[ "$changed_file" == "${HOT_DEV_RESTART_SENTINEL}" ]]; then
+ event_marker="$(file_event_marker "${HOT_DEV_RESTART_SENTINEL}" || true)"
+ if [[ -n "${event_marker}" && "${event_marker}" == "${LAST_RESTART_SENTINEL_MARKER}" ]]; then
+ continue
+ fi
+ LAST_RESTART_SENTINEL_MARKER="${event_marker}"
log_info "🚀 Managed restart requested, restarting backend..."
restart_backend
elif [[ "$changed_file" == "${ROOT_DIR}/pulse" ]]; then
+ if verify_lock_active; then
+ continue
+ fi
if manual_build_event_suppressed; then
continue
fi
+ event_marker="$(file_event_marker "${ROOT_DIR}/pulse" || true)"
+ if [[ -n "${event_marker}" && "${event_marker}" == "${LAST_PULSE_BINARY_MARKER}" ]]; then
+ continue
+ fi
+ LAST_PULSE_BINARY_MARKER="${event_marker}"
log_info "🚀 Manual build detected (pulse binary changed), restarting..."
restart_backend
+ elif verify_lock_active; then
+ continue
elif should_rebuild_backend_for_change "$changed_file"; then
rebuild_backend "$changed_file"
fi
@@ -675,11 +727,24 @@ log_info "Starting backend file watcher..."
continue
fi
if [[ "$changed_file" == "${HOT_DEV_RESTART_SENTINEL}" ]]; then
+ event_marker="$(file_event_marker "${HOT_DEV_RESTART_SENTINEL}" || true)"
+ if [[ -n "${event_marker}" && "${event_marker}" == "${LAST_RESTART_SENTINEL_MARKER}" ]]; then
+ continue
+ fi
+ LAST_RESTART_SENTINEL_MARKER="${event_marker}"
log_info "🚀 Managed restart requested, restarting backend..."
else
+ if verify_lock_active; then
+ continue
+ fi
if manual_build_event_suppressed; then
continue
fi
+ event_marker="$(file_event_marker "${ROOT_DIR}/pulse" || true)"
+ if [[ -n "${event_marker}" && "${event_marker}" == "${LAST_PULSE_BINARY_MARKER}" ]]; then
+ continue
+ fi
+ LAST_PULSE_BINARY_MARKER="${event_marker}"
log_info "🚀 Manual build detected (pulse binary changed), restarting..."
fi
restart_backend
@@ -692,6 +757,9 @@ log_info "Starting backend file watcher..."
--include '\.go$' \
"${ROOT_DIR}/cmd" "${ROOT_DIR}/internal" "${ROOT_DIR}/pkg" 2>/dev/null | \
while read -r changed_file; do
+ if verify_lock_active; then
+ continue
+ fi
if should_rebuild_backend_for_change "$changed_file"; then
rebuild_backend "$changed_file"
fi
diff --git a/scripts/tests/test-hot-dev-bg.sh b/scripts/tests/test-hot-dev-bg.sh
index 0678b42be1..06e9814692 100755
--- a/scripts/tests/test-hot-dev-bg.sh
+++ b/scripts/tests/test-hot-dev-bg.sh
@@ -157,6 +157,7 @@ import os
print(f\"mode={os.environ.get('\''PULSE_E2E_USE_HOT_DEV'\'')}\")
print(f\"username={os.environ.get('\''PULSE_E2E_USERNAME'\'')}\")
print(f\"password={os.environ.get('\''PULSE_E2E_PASSWORD'\'')}\")
+print(f\"lock={os.environ.get('\''HOT_DEV_VERIFY_LOCK_FILE'\'')}\")
PY"
run_verify_proof_command
'
@@ -165,6 +166,7 @@ PY"
assert_contains "verify proof forces managed hot-dev mode" "${output}" "mode=1"
assert_contains "verify proof defaults username" "${output}" "username=admin"
assert_contains "verify proof defaults password" "${output}" "password=admin"
+ assert_contains "verify proof passes the managed runtime lock path" "${output}" "lock=${ROOT_DIR}/tmp/hot-dev.verify.lock"
}
test_default_verify_command_runs_runtime_and_layout_proofs() {
@@ -174,13 +176,13 @@ test_default_verify_command_runs_runtime_and_layout_proofs() {
fake_bin="${test_dir}/bin"
mkdir -p "${fake_bin}"
- cat > "${fake_bin}/npm" <<'EOF'
+ cat > "${fake_bin}/node" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
printf 'cwd=%s\n' "$PWD"
printf 'args=%s\n' "$*"
EOF
- chmod +x "${fake_bin}/npm"
+ chmod +x "${fake_bin}/node"
output="$(
FAKE_BIN_PATH="${fake_bin}" \
@@ -193,11 +195,54 @@ EOF
)"
assert_contains "default verify proof runs from integration harness" "${output}" "cwd=${ROOT_DIR}/tests/integration"
+ assert_contains "default verify proof runs through the dedicated Playwright harness" "${output}" "args=./scripts/run-playwright.mjs"
assert_contains "default verify proof includes dev runtime recovery spec" "${output}" "tests/16-dev-runtime-recovery.spec.ts"
assert_contains "default verify proof includes recovery layout spec" "${output}" "tests/17-recovery-layout.spec.ts"
+ assert_contains "default verify proof includes patrol runtime-state spec" "${output}" "tests/18-patrol-runtime-state.spec.ts"
assert_contains "default verify proof keeps chromium project pin" "${output}" "--project=chromium"
}
+test_verify_bg_holds_runtime_lock_for_proof_duration() {
+ local output
+ output="$(
+ HOT_DEV_BG_PATH="${HOT_DEV_BG}" \
+ bash -lc '
+ source "${HOT_DEV_BG_PATH}"
+ set +e
+ HOT_DEV_VERIFY_LOCK="$(mktemp)"
+ rm -f "${HOT_DEV_VERIFY_LOCK}"
+ require_python(){ :; }
+ is_running(){ return 0; }
+ managed_session_pid(){ printf "4242\n"; }
+ has_unmanaged_listeners(){ return 1; }
+ runtime_healthy(){ return 0; }
+ run_verify_proof_command() {
+ if [[ -f "${HOT_DEV_VERIFY_LOCK}" ]]; then
+ printf "lock_present=yes\n"
+ cat "${HOT_DEV_VERIFY_LOCK}"
+ else
+ printf "lock_present=no\n"
+ fi
+ return 7
+ }
+
+ verify_bg false
+ status=$?
+ printf "verify_status=%s\n" "${status}"
+ if [[ -f "${HOT_DEV_VERIFY_LOCK}" ]]; then
+ printf "lock_after=yes\n"
+ else
+ printf "lock_after=no\n"
+ fi
+ '
+ )"
+
+ assert_contains "verify holds the runtime lock while proofs run" "${output}" "lock_present=yes"
+ assert_contains "verify lock records the owning process id" "${output}" "pid="
+ assert_contains "verify returns the underlying proof failure code" "${output}" "verify_status=7"
+ assert_contains "verify clears the runtime lock after proofs finish" "${output}" "lock_after=no"
+}
+
test_takeover_avoids_killing_current_shell_lineage() {
local output
output="$(
@@ -330,6 +375,25 @@ test_supervisor_restarts_unexpected_child_exit() {
assert_contains "supervisor restarts hot-dev child after exit" "${output}" "starts=2"
}
+test_stop_hot_dev_child_targets_child_process_group() {
+ local output
+ output="$(
+ HOT_DEV_BG_PATH="${HOT_DEV_BG}" \
+ bash -lc '
+ source "${HOT_DEV_BG_PATH}"
+ kill() {
+ if [[ "${1:-}" == "-0" ]]; then
+ return 1
+ fi
+ printf "kill %s\n" "$*"
+ }
+ stop_hot_dev_child 4242
+ '
+ )"
+
+ assert_contains "stop_hot_dev_child terminates the isolated child process group" "${output}" "kill -TERM -4242"
+}
+
test_launchd_wrapper_uses_managed_supervisor() {
local output
output="$(sed -n '1,80p' "${DEV_LAUNCHD_WRAPPER}")"
@@ -485,6 +549,8 @@ test_hot_dev_script_ignores_test_only_backend_churn() {
assert_contains "hot-dev watcher routes rebuild decisions through shared helper" "${output}" 'should_rebuild_backend_for_change "$changed_file"'
assert_contains "hot-dev watcher suppresses self-build binary restart loops" "${output}" 'if manual_build_event_suppressed; then'
assert_contains "hot-dev watcher suppresses startup self-build pulse events" "${output}" 'SELF_BUILD_IGNORE_UNTIL=$((WATCHER_READY_AT + HOT_DEV_WATCHER_STARTUP_GRACE_SECONDS + 5))'
+ assert_contains "hot-dev watcher seeds the startup pulse marker" "${output}" 'LAST_PULSE_BINARY_MARKER="$(file_event_marker "${ROOT_DIR}/pulse" || true)"'
+ assert_contains "hot-dev watcher suppresses source churn during managed verification" "${output}" 'verify_lock_active'
}
test_hot_dev_bg_script_advertises_managed_entrypoint() {
@@ -511,12 +577,21 @@ test_hot_dev_bg_usage_prefers_managed_wrappers() {
test_integration_readme_uses_managed_backend_restart_wrapper() {
local output
- output="$(sed -n '132,150p' "${INTEGRATION_README}")"
+ output="$(
+ awk '
+ /^### Run Against The Managed Hot-Dev Browser Runtime$/ { capture=1 }
+ capture { print }
+ /^For deterministic paid-feature runs against an existing instance, provide one of:$/ {
+ exit
+ }
+ ' "${INTEGRATION_README}"
+ )"
assert_contains "integration readme documents managed backend restart wrapper" "${output}" "npm run dev:backend-restart"
assert_contains "integration readme documents owner-process recovery proof" "${output}" "kills the supervised"
assert_contains "integration readme names the owner process" "${output}" "owner process"
assert_contains "integration readme documents recovery layout proof" "${output}" "tests/17-recovery-layout.spec.ts"
+ assert_contains "integration readme documents patrol runtime-state proof" "${output}" "tests/18-patrol-runtime-state.spec.ts"
assert_not_contains "integration readme no longer documents raw backend restart script" "${output}" "./scripts/hot-dev-bg.sh backend-restart"
}
@@ -745,10 +820,12 @@ main() {
test_cli_parses_takeover_flag
test_verify_command_injects_managed_runtime_env
test_default_verify_command_runs_runtime_and_layout_proofs
+ test_verify_bg_holds_runtime_lock_for_proof_duration
test_takeover_avoids_killing_current_shell_lineage
test_launchd_session_supervises_managed_runtime
test_start_bg_reports_browser_entrypoint
test_supervisor_restarts_unexpected_child_exit
+ test_stop_hot_dev_child_targets_child_process_group
test_launchd_wrapper_uses_managed_supervisor
test_launchd_setup_advertises_managed_runtime_controls
test_root_package_exposes_managed_runtime_entrypoints
diff --git a/tests/integration/README.md b/tests/integration/README.md
index c9cce1a6d7..13a094b0d5 100644
--- a/tests/integration/README.md
+++ b/tests/integration/README.md
@@ -47,6 +47,9 @@ End-to-end Playwright tests that validate critical user flows against a running
- Mocks a realistic Recovery dataset with human-readable subject labels
- Proves the focused history table fits the desktop wrapper without horizontal overflow
- Proves the `Outcome` column stays visible at the right edge
+- `tests/18-patrol-runtime-state.spec.ts` — Patrol runtime-state browser guard:
+ - Mocks a blocked Patrol runtime with stale healthy summary payloads
+ - Proves the real `/ai` route shows Patrol as paused and suppresses stale healthy summary copy
## Running Tests
@@ -140,10 +143,11 @@ Equivalent direct proof command from the integration harness:
cd tests/integration
PULSE_E2E_USE_HOT_DEV=1 \
PULSE_E2E_SKIP_PLAYWRIGHT_INSTALL=1 \
-npm test -- tests/16-dev-runtime-recovery.spec.ts tests/17-recovery-layout.spec.ts --project=chromium
+npm test -- tests/16-dev-runtime-recovery.spec.ts tests/17-recovery-layout.spec.ts tests/18-patrol-runtime-state.spec.ts --project=chromium
```
This mode attaches Playwright to the canonical dev browser entrypoint on `http://127.0.0.1:5173`, uses `scripts/hot-dev-bg.sh` as the runtime control surface, and writes browser runtime connection state for Playwright instead of targeting the backend port directly.
+When you run the wrapper as `npm run dev:verify`, the managed launcher hands a verification-lock path into the integration runner, and the runner holds that lock for the actual pretest, Playwright, and posttest lifetime so unrelated backend source churn does not invalidate the recovery proofs mid-run.
If the managed runtime is not already running, the harness starts it. If you need the harness to reclaim existing unmanaged `5173`/`7655` listeners first, add `PULSE_E2E_HOT_DEV_TAKEOVER=1`.
diff --git a/tests/integration/scripts/managed-dev-runtime.mjs b/tests/integration/scripts/managed-dev-runtime.mjs
index ef37573893..fd0cbb53cb 100644
--- a/tests/integration/scripts/managed-dev-runtime.mjs
+++ b/tests/integration/scripts/managed-dev-runtime.mjs
@@ -30,6 +30,10 @@ function hotDevBackendURL(env = process.env) {
return `http://${host}:${port}`;
}
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
function run(command, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { ...options });
@@ -147,6 +151,75 @@ async function ensureHealthyStatus(env = process.env) {
return output;
}
+async function waitForStableManagedRuntime({
+ env = process.env,
+ timeoutMs = 60_000,
+ sampleIntervalMs = 2_000,
+ requiredStableSamples = 2,
+} = {}) {
+ const startedAt = Date.now();
+ let stableSamples = 0;
+ let previousSnapshot = null;
+ let lastError = null;
+
+ while (Date.now() - startedAt < timeoutMs) {
+ try {
+ const statusOutput = await ensureHealthyStatus(env);
+ const supervisorPid = managedSupervisorPidFromStatus(statusOutput);
+ const frontendPid = managedListenerPidFromStatus(
+ statusOutput,
+ trim(env.FRONTEND_DEV_PORT) || '5173',
+ );
+ const backendPid = managedListenerPidFromStatus(
+ statusOutput,
+ trim(env.PULSE_DEV_API_PORT) || '7655',
+ );
+ const ownerPid = await managedHotDevOwnerPid(env);
+ const snapshot = {
+ supervisorPid,
+ ownerPid,
+ frontendPid,
+ backendPid,
+ };
+
+ if (!supervisorPid || !ownerPid || !frontendPid || !backendPid) {
+ throw new Error(`Managed dev runtime is healthy but missing stable pid markers:\n${statusOutput}`);
+ }
+
+ if (
+ previousSnapshot &&
+ previousSnapshot.supervisorPid === snapshot.supervisorPid &&
+ previousSnapshot.ownerPid === snapshot.ownerPid &&
+ previousSnapshot.frontendPid === snapshot.frontendPid &&
+ previousSnapshot.backendPid === snapshot.backendPid
+ ) {
+ stableSamples += 1;
+ } else {
+ stableSamples = 1;
+ }
+
+ previousSnapshot = snapshot;
+ if (stableSamples >= requiredStableSamples) {
+ return snapshot;
+ }
+ } catch (error) {
+ lastError = error;
+ stableSamples = 0;
+ previousSnapshot = null;
+ }
+
+ await sleep(sampleIntervalMs);
+ }
+
+ const reason =
+ lastError instanceof Error
+ ? lastError.message
+ : String(lastError || 'runtime never reached a stable healthy state');
+ throw new Error(
+ `Managed dev runtime did not stabilize within ${timeoutMs}ms: ${reason}`,
+ );
+}
+
export async function startManagedDevRuntime({
env = process.env,
logger = console,
@@ -168,7 +241,7 @@ export async function startManagedDevRuntime({
throw new Error(`hot-dev-bg start failed: ${startResult.stderr || startResult.stdout}`);
}
- await ensureHealthyStatus(env);
+ await waitForStableManagedRuntime({ env });
const runtimeState = {
managedDevRuntime: true,
@@ -187,13 +260,14 @@ export async function startManagedDevRuntime({
export async function restartManagedDevRuntimeBackend({
env = process.env,
} = {}) {
- const beforePid = await managedBackendPid(env);
+ const beforeRuntime = await waitForStableManagedRuntime({ env });
+ const beforePid = beforeRuntime.backendPid;
const result = await runHotDevBg(['backend-restart'], env);
if (result.code !== 0) {
throw new Error(`hot-dev-bg backend-restart failed: ${result.stderr || result.stdout}`);
}
- await ensureHealthyStatus(env);
- const afterPid = await managedBackendPid(env);
+ const stableRuntime = await waitForStableManagedRuntime({ env });
+ const afterPid = stableRuntime.backendPid;
if (!beforePid || !afterPid || beforePid === afterPid) {
throw new Error(`Managed backend restart did not replace the backend listener (before=${beforePid || 'missing'}, after=${afterPid || 'missing'})`);
}
@@ -203,7 +277,8 @@ export async function restartManagedDevRuntimeBackend({
export async function killManagedDevRuntimeOwnerProcess({
env = process.env,
} = {}) {
- const beforeOwnerPid = await managedHotDevOwnerPid(env);
+ const beforeRuntime = await waitForStableManagedRuntime({ env });
+ const beforeOwnerPid = beforeRuntime.ownerPid;
if (!beforeOwnerPid) {
throw new Error('Managed hot-dev owner pid could not be resolved');
}
@@ -217,8 +292,13 @@ export async function killManagedDevRuntimeOwnerProcess({
throw new Error(`kill -KILL ${beforeOwnerPid} failed: ${killResult.stderr || killResult.stdout}`);
}
- await ensureHealthyStatus(env);
- const afterOwnerPid = await managedHotDevOwnerPid(env);
+ const stableRuntime = await waitForStableManagedRuntime({
+ env,
+ timeoutMs: 90_000,
+ sampleIntervalMs: 3_000,
+ requiredStableSamples: 3,
+ });
+ const afterOwnerPid = stableRuntime.ownerPid;
if (!afterOwnerPid || beforeOwnerPid === afterOwnerPid) {
throw new Error(`Managed hot-dev owner was not replaced after kill (before=${beforeOwnerPid}, after=${afterOwnerPid || 'missing'})`);
}
diff --git a/tests/integration/scripts/run-playwright.mjs b/tests/integration/scripts/run-playwright.mjs
index 9f96566c30..dfe735e6c3 100644
--- a/tests/integration/scripts/run-playwright.mjs
+++ b/tests/integration/scripts/run-playwright.mjs
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
+import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -29,6 +30,30 @@ function buildRunScopedEnv(env = process.env) {
};
}
+function managedVerifyLockPath(env = process.env) {
+ const configuredPath = String(env.HOT_DEV_VERIFY_LOCK_FILE || '').trim();
+ return configuredPath || path.join(repoRoot, 'tmp', 'hot-dev.verify.lock');
+}
+
+async function writeManagedVerifyLock(env = process.env) {
+ if (!['1', 'true', 'yes', 'on'].includes(String(env.PULSE_E2E_USE_HOT_DEV || '').trim().toLowerCase())) {
+ return;
+ }
+
+ const lockPath = managedVerifyLockPath(env);
+ await fs.mkdir(path.dirname(lockPath), { recursive: true });
+ await fs.writeFile(
+ lockPath,
+ `pid=${process.pid}\ncreated_at=${new Date().toISOString()}\nrun_id=${String(env.PULSE_E2E_RUN_ID || '').trim()}\n`,
+ 'utf8',
+ );
+}
+
+async function clearManagedVerifyLock(env = process.env) {
+ const lockPath = managedVerifyLockPath(env);
+ await fs.rm(lockPath, { force: true });
+}
+
const run = (command, args, options = {}) =>
new Promise((resolve, reject) => {
const child = spawn(command, args, { stdio: 'inherit', ...options });
@@ -40,6 +65,7 @@ let exitCode = 0;
const childEnv = buildRunScopedEnv();
try {
+ await writeManagedVerifyLock(childEnv);
const pretestCode = await run(nodeCmd, ['./scripts/pretest.mjs'], { env: childEnv });
if (pretestCode !== 0) {
process.exit(pretestCode);
@@ -51,6 +77,7 @@ try {
if (exitCode === 0 && posttestCode !== 0) {
exitCode = posttestCode;
}
+ await clearManagedVerifyLock(childEnv);
}
process.exit(exitCode);