@molecule/app-ide-panel-logic 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +368 -3
- package/dist/command-metadata.d.ts +225 -4
- package/dist/command-metadata.d.ts.map +1 -1
- package/dist/command-metadata.js +163 -2
- package/dist/command-metadata.js.map +1 -1
- package/dist/components/chat-models-utilities.d.ts +16 -0
- package/dist/components/chat-models-utilities.d.ts.map +1 -1
- package/dist/components/chat-models-utilities.js +25 -0
- package/dist/components/chat-models-utilities.js.map +1 -1
- package/dist/components/chat-settings-utilities.d.ts +65 -4
- package/dist/components/chat-settings-utilities.d.ts.map +1 -1
- package/dist/components/chat-settings-utilities.js +155 -4
- package/dist/components/chat-settings-utilities.js.map +1 -1
- package/dist/components/chat-share-utilities.d.ts +39 -0
- package/dist/components/chat-share-utilities.d.ts.map +1 -1
- package/dist/components/chat-share-utilities.js +91 -0
- package/dist/components/chat-share-utilities.js.map +1 -1
- package/dist/components/chat-tips-utilities.d.ts +72 -7
- package/dist/components/chat-tips-utilities.d.ts.map +1 -1
- package/dist/components/chat-tips-utilities.js +68 -0
- package/dist/components/chat-tips-utilities.js.map +1 -1
- package/dist/components/context-usage-utilities.d.ts +32 -0
- package/dist/components/context-usage-utilities.d.ts.map +1 -0
- package/dist/components/context-usage-utilities.js +77 -0
- package/dist/components/context-usage-utilities.js.map +1 -0
- package/dist/components/headless-hooks.d.ts +89 -0
- package/dist/components/headless-hooks.d.ts.map +1 -0
- package/dist/components/headless-hooks.js +254 -0
- package/dist/components/headless-hooks.js.map +1 -0
- package/dist/components/preview-panel-logic.d.ts +182 -0
- package/dist/components/preview-panel-logic.d.ts.map +1 -0
- package/dist/components/preview-panel-logic.js +1993 -0
- package/dist/components/preview-panel-logic.js.map +1 -0
- package/dist/components/preview-panel-session.d.ts +62 -0
- package/dist/components/preview-panel-session.d.ts.map +1 -0
- package/dist/components/preview-panel-session.js +40 -0
- package/dist/components/preview-panel-session.js.map +1 -0
- package/dist/components/quick-picker-utilities.d.ts +19 -0
- package/dist/components/quick-picker-utilities.d.ts.map +1 -0
- package/dist/components/quick-picker-utilities.js +36 -0
- package/dist/components/quick-picker-utilities.js.map +1 -0
- package/dist/components/tests-bar-utilities.d.ts +27 -0
- package/dist/components/tests-bar-utilities.d.ts.map +1 -1
- package/dist/components/tests-bar-utilities.js +71 -0
- package/dist/components/tests-bar-utilities.js.map +1 -1
- package/dist/components/tool-call-utilities.d.ts +14 -5
- package/dist/components/tool-call-utilities.d.ts.map +1 -1
- package/dist/components/tool-call-utilities.js +111 -51
- package/dist/components/tool-call-utilities.js.map +1 -1
- package/dist/panels.d.ts +8 -2
- package/dist/panels.d.ts.map +1 -1
- package/dist/panels.js +8 -2
- package/dist/panels.js.map +1 -1
- package/dist/settings-metadata.d.ts +33 -2
- package/dist/settings-metadata.d.ts.map +1 -1
- package/dist/settings-metadata.js +138 -2
- package/dist/settings-metadata.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,1993 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live preview panel's behaviour, written once for every framework: server polling, stuck-load
|
|
3
|
+
* recovery, the `molecule:*` postMessage bridge, the health check, the freeze watchdog, the blank
|
|
4
|
+
* notice, wake patience, back/forward and the AI `uiCommand` relay.
|
|
5
|
+
*
|
|
6
|
+
* {@link usePreviewPanelLogic} is that behaviour as one hook-shaped function. It takes the four
|
|
7
|
+
* primitive hooks it needs ({@link PrimitiveHooks}) instead of importing a framework: the React
|
|
8
|
+
* panel passes React's own `useState`/`useRef`/`useEffect`/`useCallback`, so React runs exactly the
|
|
9
|
+
* code it always ran; the Vue, Svelte, Solid and Angular panels run the same function through
|
|
10
|
+
* `createPreviewPanelSession`, which supplies those hooks itself and exposes the result as a
|
|
11
|
+
* store (`getState`/`subscribe`). The panel's timing rules (which effect re-arms on what, what a
|
|
12
|
+
* render-time reset guarantees) are therefore defined in one place, and a port cannot drift from
|
|
13
|
+
* them.
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import { withCacheBuster } from '@molecule/app-live-preview';
|
|
18
|
+
import { get as storageGet, set as storageSet } from '@molecule/app-storage';
|
|
19
|
+
import { isDeviceRotatable } from './device-cycle.js';
|
|
20
|
+
/**
|
|
21
|
+
* Storage key for the persisted preview orientation. The orientation is a global,
|
|
22
|
+
* cross-device preview preference (it applies to every rotatable device and
|
|
23
|
+
* survives reloads), persisted via the bonded `@molecule/app-storage` provider.
|
|
24
|
+
*/
|
|
25
|
+
const ORIENTATION_STORAGE_KEY = 'molecule.ide.preview.orientation';
|
|
26
|
+
// --- Polling constants (exponential backoff, never gives up) ---
|
|
27
|
+
/** Initial poll interval when waiting for the server. */
|
|
28
|
+
const POLL_INITIAL_MS = 500;
|
|
29
|
+
/**
|
|
30
|
+
* How long the FIRST-mount server-up poll may run without the server answering
|
|
31
|
+
* before the panel surfaces the actionable "Preview can't load here" notice
|
|
32
|
+
* (ms). The poll itself keeps running underneath — the notice self-clears the
|
|
33
|
+
* moment a poll succeeds and mounts the iframe — so this is honesty, not a
|
|
34
|
+
* give-up: it hands the user Reload / Open-in-new-tab instead of an unbounded
|
|
35
|
+
* spinner. Before this existed the pre-mount poll was the one path with NO
|
|
36
|
+
* actionable escape at all: it "never gives up" by design, and the absolute
|
|
37
|
+
* ceiling that should have backstopped it fired once, stood down inside the
|
|
38
|
+
* wake window, and never re-checked — a viewer's fresh page load against a
|
|
39
|
+
* never-answering preview sat on "Loading preview…" indefinitely with no modal
|
|
40
|
+
* (observed 2026-08-31). Sized past a proxy cold-start + dev-server relaunch so
|
|
41
|
+
* a normal slow boot still resolves silently.
|
|
42
|
+
*/
|
|
43
|
+
const PREMOUNT_GIVEUP_MS = 45_000;
|
|
44
|
+
/** Re-check gap for the absolute readiness ceiling when it stands down for a benign hold (ms). */
|
|
45
|
+
const ABSOLUTE_STUCK_RECHECK_MS = 10_000;
|
|
46
|
+
/** Maximum poll interval after backoff. */
|
|
47
|
+
const POLL_MAX_MS = 5000;
|
|
48
|
+
/** Backoff multiplier applied after each failed poll. */
|
|
49
|
+
const POLL_BACKOFF_FACTOR = 2;
|
|
50
|
+
// --- Stuck-load detection constants ---
|
|
51
|
+
/**
|
|
52
|
+
* Base time to wait for the load to make progress after the iframe src is set
|
|
53
|
+
* before attempting recovery (ms). Raised from the old 5s — a cold/slow first
|
|
54
|
+
* Vite load after an idle (or a deps-cache wipe) routinely takes longer than 5s,
|
|
55
|
+
* and remounting mid-load (with a cache-buster that defeats Vite's transform
|
|
56
|
+
* cache) only made the next load slower. Recovery now also requires that the
|
|
57
|
+
* document has NOT loaded (see the stuck-detection effect), so a progressing-but-
|
|
58
|
+
* slow load is never interrupted.
|
|
59
|
+
*
|
|
60
|
+
* Raised again 8s → 15s: behind a preview proxy (e.g. a `*.mlcl.dev` edge that
|
|
61
|
+
* fronts a Fly Machine which Fly cold-starts on the first request), the initial
|
|
62
|
+
* load holds for the machine boot + dev-server start before the document even
|
|
63
|
+
* arrives — routinely longer than 8s. Remounting during that hold only restarts
|
|
64
|
+
* the clock and slows the boot.
|
|
65
|
+
*/
|
|
66
|
+
const STUCK_DETECT_MS = 15_000;
|
|
67
|
+
/** Exponential back-off applied to STUCK_DETECT_MS between recovery attempts. */
|
|
68
|
+
const STUCK_BACKOFF_FACTOR = 1.6;
|
|
69
|
+
/**
|
|
70
|
+
* Max recovery cycles (reload + remount) before giving up. After this cap the
|
|
71
|
+
* panel STOPS retrying and shows a themed loop-breaker (Reload + Open in new tab)
|
|
72
|
+
* instead of remounting indefinitely — the old `longRetry()` looped forever.
|
|
73
|
+
*/
|
|
74
|
+
export const MAX_RECOVERY_CYCLES = 3;
|
|
75
|
+
/**
|
|
76
|
+
* Max probe-driven automatic recoveries per dead-end episode. Every actionable
|
|
77
|
+
* notice ("Preview can't load here", "the preview is blank") used to be a true
|
|
78
|
+
* dead end: all in-budget retries had already run, and only a human clicking
|
|
79
|
+
* Reload could try again. But the server those retries ran against may simply
|
|
80
|
+
* not be up YET — an E2B resume of a long-paused sandbox pulls its snapshot
|
|
81
|
+
* from cold storage and can take minutes, outliving wake patience AND every
|
|
82
|
+
* retry budget (observed 2026-08-31: a 24h-asleep sandbox woke fine, but the
|
|
83
|
+
* panel had given up and a manual "Reload preview" was needed — which worked,
|
|
84
|
+
* because by then the server was serving). So while a dead-end notice is up
|
|
85
|
+
* over a DEAD document, the panel keeps probing the preview URL and, the
|
|
86
|
+
* moment the server answers, runs exactly the manual-retry path itself. This
|
|
87
|
+
* cap bounds that per episode so a server that answers probes but serves a
|
|
88
|
+
* broken app cannot ping-pong give-up → auto-retry forever; a confirmed render
|
|
89
|
+
* (or a human retry) resets the budget.
|
|
90
|
+
*/
|
|
91
|
+
const MAX_DEAD_END_AUTO_RECOVERS = 3;
|
|
92
|
+
// --- Backend-restart escalation (see PreviewPanelProps.onRestartBackend) ---
|
|
93
|
+
/**
|
|
94
|
+
* How long the app may sit with NO confirmed render before the panel may escalate
|
|
95
|
+
* to a backend dev-server restart (ms). Deliberately generous: it must outlast a
|
|
96
|
+
* heavy cold compile, wake patience, and multiple dead-end reload attempts, so a
|
|
97
|
+
* restart is only ever the answer when reloading has already been tried against a
|
|
98
|
+
* SERVING host and provably changed nothing (the poisoned-module-cache class —
|
|
99
|
+
* a document reload reuses the dev server's immutable `?v=` module URLs, so only
|
|
100
|
+
* a server restart, which mints a new version hash, can clear it).
|
|
101
|
+
*/
|
|
102
|
+
const BACKEND_RESTART_AFTER_MS = 180_000;
|
|
103
|
+
/** Cooldown between backend-restart escalations (ms) — one restart gets one full recovery cycle. */
|
|
104
|
+
const BACKEND_RESTART_COOLDOWN_MS = 600_000;
|
|
105
|
+
/** Cadence of the escalation watchdog's cheap pre-checks (ms). */
|
|
106
|
+
const BACKEND_RESTART_CHECK_MS = 10_000;
|
|
107
|
+
/**
|
|
108
|
+
* Absolute upper bound (ms) on how long the preview may sit on the loading overlay
|
|
109
|
+
* without ever CONFIRMING a render (`molecule:ready`), while not mid-build. A pure
|
|
110
|
+
* BACKSTOP: the targeted paths (onLoad grace, stuck-detection, blank-post-build) each
|
|
111
|
+
* resolve a specific failure faster, but a *combination* can still leave the overlay up
|
|
112
|
+
* forever — e.g. the document fired `onLoad` (so stuck-detection stands down) yet a
|
|
113
|
+
* crash/HMR-error storm keeps suppressing the onLoad grace, so `iframeReady` never flips
|
|
114
|
+
* and blank-post-build (which requires it) never fires. Past this ceiling the panel gives
|
|
115
|
+
* up to the actionable loop-breaker (Reload / open in tab) so the preview can NEVER be
|
|
116
|
+
* stuck on a spinner indefinitely. Self-correcting: a real render that lands later clears
|
|
117
|
+
* the loop-breaker (see the confirm effect), so an over-eager trip is harmless.
|
|
118
|
+
*/
|
|
119
|
+
const ABSOLUTE_STUCK_MS = 30_000;
|
|
120
|
+
/**
|
|
121
|
+
* How long a document may stay LOADED (onLoad fired) without confirming a render before
|
|
122
|
+
* we attempt a single auto-reload (ms). Targets the stale-document case: a Vite "server
|
|
123
|
+
* restarted" (or any dev-server bounce) drops every client's HMR connection mid-load, so
|
|
124
|
+
* an iframe that loaded just before the restart is left disconnected and never renders —
|
|
125
|
+
* recovered today only by a MANUAL reload. The post-ready health check never runs here
|
|
126
|
+
* (it requires a render first), and stuck-detection stands down once onLoad fired.
|
|
127
|
+
*/
|
|
128
|
+
const LOAD_RECOVER_AFTER_MS = 12_000;
|
|
129
|
+
/** Max auto-reloads of a loaded-but-unrendered document per load (then defer to the ceiling). */
|
|
130
|
+
const MAX_LOAD_RECOVERS = 2;
|
|
131
|
+
// --- onLoad grace fallback ---
|
|
132
|
+
/**
|
|
133
|
+
* After the iframe document fires `onLoad`, how long to wait for `molecule:ready`
|
|
134
|
+
* before treating the load as good anyway (ms). The handshake is the fast path;
|
|
135
|
+
* this is the safety net for a working app whose ready was dropped/suppressed.
|
|
136
|
+
*/
|
|
137
|
+
const ONLOAD_GRACE_MS = 2_500;
|
|
138
|
+
/**
|
|
139
|
+
* When a new document fires `onLoad`, how recently a `molecule:ready` must have arrived for the
|
|
140
|
+
* load to count as already-confirmed-rendered (ms). A working full-reload mounts React (→ ready)
|
|
141
|
+
* just before the load event, so its ready lands inside this window and confirmedContent is kept
|
|
142
|
+
* (no overlay flash). A reload that produced a blank app sends no ready, so the last ready is
|
|
143
|
+
* older than this → confirmedContent drops and the overlay re-covers the white iframe.
|
|
144
|
+
*/
|
|
145
|
+
const READY_FRESH_MS = 1_500;
|
|
146
|
+
// --- Last-good-frame snapshot (molecule:snapshot trust boundary) ---
|
|
147
|
+
/**
|
|
148
|
+
* Bounds on a viewport an inbound `molecule:viewport` may request. A spec
|
|
149
|
+
* drives this, so it is clamped rather than trusted: below the lower bound the
|
|
150
|
+
* frame is unusable, and above the upper one it would escape the panel.
|
|
151
|
+
*/
|
|
152
|
+
const MIN_REQUESTED_PX = 120;
|
|
153
|
+
/** Upper bound of the same clamp — see {@link MIN_REQUESTED_PX}. */
|
|
154
|
+
const MAX_REQUESTED_PX = 4000;
|
|
155
|
+
/**
|
|
156
|
+
* Max accepted size of an inbound `molecule:snapshot` data-URL (chars). The
|
|
157
|
+
* sandbox sender downscales + JPEG-compresses, so a legitimate frame is well
|
|
158
|
+
* under this; the cap defends the postMessage trust boundary against an oversized
|
|
159
|
+
* payload bloating React state.
|
|
160
|
+
*/
|
|
161
|
+
const MAX_SNAPSHOT_DATA_URL_LENGTH = 4_000_000;
|
|
162
|
+
// --- Freeze watchdog constants ---
|
|
163
|
+
/**
|
|
164
|
+
* Heartbeat gap beyond which the preview's main thread is treated as frozen (ms).
|
|
165
|
+
* The scaffold posts `molecule:heartbeat` every ~3s; this tolerates two missed
|
|
166
|
+
* beats plus jitter before declaring a freeze, so brief synchronous work (a heavy
|
|
167
|
+
* one-off render) doesn't trip it.
|
|
168
|
+
*/
|
|
169
|
+
const FREEZE_THRESHOLD_MS = 8_000;
|
|
170
|
+
/** How often the watchdog compares `now` against the last heartbeat (ms). */
|
|
171
|
+
const FREEZE_CHECK_INTERVAL_MS = 2_000;
|
|
172
|
+
/**
|
|
173
|
+
* Window within which an identical runtime-error signature (message+source+line+column)
|
|
174
|
+
* is treated as a duplicate and dropped before forwarding (ms). Both the centralized
|
|
175
|
+
* runtime bridge AND a template's baked sender can report the SAME uncaught error, and
|
|
176
|
+
* a render-looping app re-throws it continuously — de-duping by signature keeps one
|
|
177
|
+
* fault from flooding the agent with the same message over and over.
|
|
178
|
+
*/
|
|
179
|
+
const ERROR_DEDUP_WINDOW_MS = 4_000;
|
|
180
|
+
/**
|
|
181
|
+
* How long an ALREADY-rendered app that RELOADED to blank may stay loaded-but-unconfirmed
|
|
182
|
+
* (document loaded, no fresh `molecule:ready`) before the overlay's copy switches to the
|
|
183
|
+
* actionable "preview is blank — reload" notice (ms). This short window is ONLY used once the
|
|
184
|
+
* app has rendered at least once this session (`hasEverRendered`) — i.e. it WAS working and an
|
|
185
|
+
* edit reloaded it to blank — so a real regression surfaces quickly. It is NEVER used to accuse
|
|
186
|
+
* a first-cold-boot app that simply hasn't finished starting (see COLD_BOOT_PATIENCE_MS).
|
|
187
|
+
*/
|
|
188
|
+
const BLANK_CONFIRM_MS = 2_500;
|
|
189
|
+
/**
|
|
190
|
+
* How long a reported link-click intent stays valid for the document load that follows it.
|
|
191
|
+
* A click that never turns into a load (the SPA router handled it, the server was slow) must
|
|
192
|
+
* not certify some later, unrelated blank reload.
|
|
193
|
+
*/
|
|
194
|
+
const RAW_DOC_INTENT_MS = 30_000;
|
|
195
|
+
/**
|
|
196
|
+
* Extensions the browser shows with its own viewer rather than running an app: a feed, a
|
|
197
|
+
* provenance map, an llms.txt. Such a document carries no bridge, so it can never post
|
|
198
|
+
* `molecule:ready` — the silence is the document, not a blank app.
|
|
199
|
+
*/
|
|
200
|
+
const RAW_DOCUMENT_EXTENSIONS = new Set([
|
|
201
|
+
'json',
|
|
202
|
+
'xml',
|
|
203
|
+
'rss',
|
|
204
|
+
'atom',
|
|
205
|
+
'txt',
|
|
206
|
+
'md',
|
|
207
|
+
'markdown',
|
|
208
|
+
'csv',
|
|
209
|
+
'tsv',
|
|
210
|
+
'yaml',
|
|
211
|
+
'yml',
|
|
212
|
+
'svg',
|
|
213
|
+
'pdf',
|
|
214
|
+
'webmanifest',
|
|
215
|
+
'ics',
|
|
216
|
+
'log',
|
|
217
|
+
]);
|
|
218
|
+
/**
|
|
219
|
+
* Whether a URL points at a raw document (see {@link RAW_DOCUMENT_EXTENSIONS}) rather than
|
|
220
|
+
* an app page. Decided from the path's extension alone — the panel cannot read a
|
|
221
|
+
* cross-origin frame's content type.
|
|
222
|
+
*
|
|
223
|
+
* @param url - The absolute URL the preview is navigating to.
|
|
224
|
+
* @returns `true` when the browser will show the document itself, with no bridge.
|
|
225
|
+
*/
|
|
226
|
+
export function isRawDocumentUrl(url) {
|
|
227
|
+
let pathname;
|
|
228
|
+
try {
|
|
229
|
+
pathname = new URL(url).pathname;
|
|
230
|
+
}
|
|
231
|
+
catch (_error) {
|
|
232
|
+
// Not a URL at all — then it is not a raw document either.
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
const last = pathname.split('/').pop() ?? '';
|
|
236
|
+
const dot = last.lastIndexOf('.');
|
|
237
|
+
if (dot <= 0)
|
|
238
|
+
return false;
|
|
239
|
+
return RAW_DOCUMENT_EXTENSIONS.has(last.slice(dot + 1).toLowerCase());
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* For a NEVER-yet-rendered document, how long with NO liveness (no `molecule:heartbeat` for
|
|
243
|
+
* FREEZE_THRESHOLD_MS) before surfacing the actionable notice (ms). The scaffold's preview
|
|
244
|
+
* bridge is an INLINE script in `index.html`, so it runs (and starts heartbeating) the moment
|
|
245
|
+
* the HTML parses — even before the app's modules compile. So a loaded document that is NOT
|
|
246
|
+
* heartbeating at all means its inline bridge never ran: a broken/error page (or JS disabled),
|
|
247
|
+
* i.e. a genuine failure, not a cold boot in progress. The settle lets the first ~3s heartbeat
|
|
248
|
+
* arrive before we judge liveness.
|
|
249
|
+
*
|
|
250
|
+
* Raised 4s → 15s: behind a preview proxy fronting a Fly Machine, the first
|
|
251
|
+
* request COLD-STARTS the machine, and until the real app is served the proxy
|
|
252
|
+
* legitimately answers a bridge-less "starting"/transient page that never
|
|
253
|
+
* heartbeats — for as long as the cold-start takes (well past 4s). Accusing at 4s
|
|
254
|
+
* false-fired "The app loaded but didn't render anything" over a preview that was
|
|
255
|
+
* simply still booting. 15s clears a genuine bridge-less error page while giving a
|
|
256
|
+
* proxy cold-start room to serve the real (heartbeating) document; a still-dead
|
|
257
|
+
* doc is also auto-reloaded at LOAD_RECOVER_AFTER_MS and ceilinged at
|
|
258
|
+
* COLD_BOOT_PATIENCE_MS.
|
|
259
|
+
*/
|
|
260
|
+
const BLANK_DEAD_MS = 15_000;
|
|
261
|
+
/**
|
|
262
|
+
* Absolute patience (ms) for a first-cold-boot app that IS alive (heartbeating) but has not yet
|
|
263
|
+
* confirmed a render (`molecule:ready`). A cold Vite dev server on a fresh project legitimately
|
|
264
|
+
* takes many seconds to pre-bundle deps + compile the app before React mounts; during that whole
|
|
265
|
+
* window the honest "Starting your app…" overlay stays up and we must NOT accuse it of being
|
|
266
|
+
* blank or "unable to load" — that false accusation (with its "Open in new tab" button) was the
|
|
267
|
+
* whole "fresh project preview won't load until I open it in a new tab and refresh the IDE" bug.
|
|
268
|
+
* Only after this generous ceiling — alive the entire time yet still never mounted — do we treat
|
|
269
|
+
* it as genuinely stuck and surface the reload/open-in-tab notice. The scaffold's `molecule:ready`
|
|
270
|
+
* (reliable, fired the instant #root mounts) clears everything long before this on any real boot.
|
|
271
|
+
*/
|
|
272
|
+
const COLD_BOOT_PATIENCE_MS = 60_000;
|
|
273
|
+
/**
|
|
274
|
+
* How long after a detected wake (the preview's backing server/sandbox was just restarted) the
|
|
275
|
+
* panel stays in WAKE PATIENCE (ms). A wake is detected when the load target changes to a new
|
|
276
|
+
* preview URL — a wake always reassigns the sandbox's docker port, so a woken preview arrives on
|
|
277
|
+
* a fresh URL (the reliable signal) — or from the host's explicit `wakeAt` prop (a hint). A wake
|
|
278
|
+
* means the dev server behind the preview is restarting and cold-recompiling: the (re)loaded
|
|
279
|
+
* document legitimately shows nothing for a while — and behind a preview proxy the reload can even
|
|
280
|
+
* land on a transient error page that never runs the inline bridge. Both signatures are
|
|
281
|
+
* EXACTLY what the fast accusation windows (BLANK_CONFIRM_MS for an already-rendered app,
|
|
282
|
+
* BLANK_DEAD_MS for a bridge-less document) treat as a genuine failure — so right after a
|
|
283
|
+
* wake they false-fired a "preview is blank" notice over an app that rendered fine seconds
|
|
284
|
+
* later. During this window the panel re-enters the patient cold-boot regime (reveal on
|
|
285
|
+
* ready, honest starting status) and only the generous never-rendered ceiling may accuse.
|
|
286
|
+
* Sized to cover a fallback wake end-to-end: dev-server relaunch (~seconds) + the reload +
|
|
287
|
+
* a cold Vite recompile (up to tens of seconds). A real `molecule:ready` clears everything
|
|
288
|
+
* long before this on any healthy wake.
|
|
289
|
+
*
|
|
290
|
+
* Raised 45s → 90s for the Fly + proxy topology: a wake there is machine
|
|
291
|
+
* cold-start + dev-server relaunch + cold Vite recompile, ALL behind an extra
|
|
292
|
+
* proxy hop, and the mlcl.dev preview URL is STABLE (token-keyed), so the reliable
|
|
293
|
+
* load-target-change wake signal never fires — patience rests on the host `wakeAt`
|
|
294
|
+
* hint alone and must outlast the whole cold path. A real `molecule:ready` still
|
|
295
|
+
* clears it immediately, so the wider window only ever helps a genuinely slow boot.
|
|
296
|
+
*/
|
|
297
|
+
const WAKE_PATIENCE_MS = 90_000;
|
|
298
|
+
/**
|
|
299
|
+
* Duration of the overlay fade-out (ms) — kept in sync with the overlay's `transition:
|
|
300
|
+
* opacity` below. `fadingOut` is cleared on `onTransitionEnd`, but a timer matched to this
|
|
301
|
+
* is the robust fallback for when that event never fires (the overlay unmounts mid-fade,
|
|
302
|
+
* `prefers-reduced-motion` disables the transition, or a non-rendering env): a stuck
|
|
303
|
+
* `fadingOut` would pin the overlay at opacity 0 and block the post-build blank re-cover.
|
|
304
|
+
*/
|
|
305
|
+
const OVERLAY_FADE_MS = 500;
|
|
306
|
+
// --- Rate-limiting constants ---
|
|
307
|
+
/** Minimum interval between acting on ready/error messages (ms). */
|
|
308
|
+
const MSG_RATE_LIMIT_MS = 300;
|
|
309
|
+
/** Max ready↔error transitions before suppressing (per window). */
|
|
310
|
+
const MAX_TRANSITIONS = 10;
|
|
311
|
+
/** Window duration for transition counting (ms). */
|
|
312
|
+
const TRANSITION_WINDOW_MS = 5000;
|
|
313
|
+
/**
|
|
314
|
+
* The path a preview host may serve to report, in a form a cross-origin caller
|
|
315
|
+
* can actually READ, whether the app behind it is serving.
|
|
316
|
+
*
|
|
317
|
+
* A plain `no-cors` probe cannot tell up from down: the response is opaque, so
|
|
318
|
+
* it resolves for 200 and for an edge's "sandbox unavailable" error page alike,
|
|
319
|
+
* and the panel mounts the error page as though the app were ready — a page with
|
|
320
|
+
* no bridge in it, which can never self-heal. This path is answered by the
|
|
321
|
+
* preview edge with CORS headers, so `response.ok` is a real answer. A host that
|
|
322
|
+
* does not serve it (a plain dev server on localhost) falls back to the opaque
|
|
323
|
+
* probe below.
|
|
324
|
+
*/
|
|
325
|
+
const PREVIEW_STATUS_PATH = '/__mol/preview-status';
|
|
326
|
+
/**
|
|
327
|
+
* How long one server-up probe may take before it counts as a miss (ms).
|
|
328
|
+
*
|
|
329
|
+
* This used to be 500ms, sized for a loopback dev server. Behind a preview
|
|
330
|
+
* edge the same probe is browser → edge → proxy → token resolve → a HEAD at
|
|
331
|
+
* the sandbox upstream, measured live at 250–470ms from a healthy app — so at
|
|
332
|
+
* 500ms a healthy preview tripped it every few polls, and each trip was a
|
|
333
|
+
* cache-busted iframe reload ("the preview keeps reloading with nobody touching
|
|
334
|
+
* it", 2026-08-18). Probes are sequential (never stacked), so a generous bound
|
|
335
|
+
* costs nothing while the app is up and only delays the down verdict slightly.
|
|
336
|
+
*/
|
|
337
|
+
const PROBE_TIMEOUT_MS = 5_000;
|
|
338
|
+
/**
|
|
339
|
+
* Consecutive failed probes before the steady-state health check treats the app
|
|
340
|
+
* as down (and reloads it once it answers again). One miss is noise — a slow edge
|
|
341
|
+
* hop, an aborted fetch on a tab switch — and a single miss used to force a full
|
|
342
|
+
* reload. Mirrors the server-side stream's PREVIEW_HEALTH_DOWN_CONFIRM.
|
|
343
|
+
*/
|
|
344
|
+
const HEALTH_DOWN_CONFIRM = 2;
|
|
345
|
+
/** Gap (ms) between the END of one steady-state health probe and the next. */
|
|
346
|
+
const HEALTH_POLL_MS = 3_000;
|
|
347
|
+
/**
|
|
348
|
+
* Check whether the server at `url` is accepting connections.
|
|
349
|
+
*
|
|
350
|
+
* Asks {@link PREVIEW_STATUS_PATH} first, because that answer is readable; only
|
|
351
|
+
* a host that does not implement it falls back to the opaque `no-cors` probe,
|
|
352
|
+
* where "it responded at all" is the best available signal.
|
|
353
|
+
*
|
|
354
|
+
* Aborts after {@link PROBE_TIMEOUT_MS}. Every caller runs its probes one at a
|
|
355
|
+
* time (the next is scheduled only after the previous settles), so a slow probe
|
|
356
|
+
* never stacks up connections against the iframe. An optional `externalSignal`
|
|
357
|
+
* lets the caller abort the in-flight request on cleanup (e.g. when a poll chain
|
|
358
|
+
* is superseded), so a unmounting/restarting panel never leaves a fetch dangling.
|
|
359
|
+
* @param url - The URL to check.
|
|
360
|
+
* @param externalSignal - Optional signal; aborting it aborts this probe.
|
|
361
|
+
* @returns Whether the server responded within the timeout.
|
|
362
|
+
*/
|
|
363
|
+
async function isServerUp(url, externalSignal) {
|
|
364
|
+
const controller = new AbortController();
|
|
365
|
+
const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
|
|
366
|
+
const onExternalAbort = () => controller.abort();
|
|
367
|
+
if (externalSignal) {
|
|
368
|
+
if (externalSignal.aborted)
|
|
369
|
+
controller.abort();
|
|
370
|
+
else
|
|
371
|
+
externalSignal.addEventListener('abort', onExternalAbort);
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
try {
|
|
375
|
+
const statusUrl = new URL(PREVIEW_STATUS_PATH, url).toString();
|
|
376
|
+
const status = await fetch(statusUrl, {
|
|
377
|
+
method: 'GET',
|
|
378
|
+
mode: 'cors',
|
|
379
|
+
cache: 'no-store',
|
|
380
|
+
signal: controller.signal,
|
|
381
|
+
});
|
|
382
|
+
// A host that serves this path has told us the truth either way.
|
|
383
|
+
if (status.status !== 404)
|
|
384
|
+
return status.ok;
|
|
385
|
+
}
|
|
386
|
+
catch (_error) {
|
|
387
|
+
// No CORS status endpoint here (or it was blocked) — fall through to the
|
|
388
|
+
// opaque probe rather than reporting a healthy app as down.
|
|
389
|
+
}
|
|
390
|
+
if (controller.signal.aborted)
|
|
391
|
+
return false;
|
|
392
|
+
await fetch(url, { method: 'HEAD', mode: 'no-cors', signal: controller.signal });
|
|
393
|
+
return true;
|
|
394
|
+
}
|
|
395
|
+
catch (_error) {
|
|
396
|
+
// Fetch failure (or an abort) means the server is not usable right now —
|
|
397
|
+
// expected during polling / on cancellation. `false` is the correct result.
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
finally {
|
|
401
|
+
clearTimeout(timeout);
|
|
402
|
+
if (externalSignal)
|
|
403
|
+
externalSignal.removeEventListener('abort', onExternalAbort);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* The targetOrigin for an OUTBOUND postMessage into the preview iframe: the
|
|
408
|
+
* iframe's CURRENT src origin when that parses, `'*'` only when it doesn't.
|
|
409
|
+
*
|
|
410
|
+
* Why: the inbound side of this bridge is gated on window identity
|
|
411
|
+
* (`event.source === iframe.contentWindow`), but the outbound side grew six
|
|
412
|
+
* wildcard posts — commands that can drive the page (click/fill/navigate)
|
|
413
|
+
* deliverable to WHATEVER page ever ended up in this frame. Targeting the
|
|
414
|
+
* frame's current src origin pins delivery to the page the panel believes it
|
|
415
|
+
* is talking to. The fallback stays `'*'` (never break the bridge: a stranded
|
|
416
|
+
* command loop is the whole preview going dark), and an unparsable src is
|
|
417
|
+
* exactly the case where no origin is known anyway.
|
|
418
|
+
*
|
|
419
|
+
* @param iframe - The preview iframe element (may be null pre-mount).
|
|
420
|
+
* @returns The targetOrigin string for `postMessage`.
|
|
421
|
+
*/
|
|
422
|
+
export function previewTargetOrigin(iframe) {
|
|
423
|
+
const src = iframe?.getAttribute('src');
|
|
424
|
+
if (src) {
|
|
425
|
+
try {
|
|
426
|
+
return new URL(src).origin;
|
|
427
|
+
}
|
|
428
|
+
catch (_error) {
|
|
429
|
+
// Unparsable src — no known origin to target; keep the bridge alive.
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return '*';
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* The live preview panel's behaviour as one hook-shaped function (see the module docs). Call it
|
|
436
|
+
* once per render of the panel, at the top level, with the same `hooks` every time.
|
|
437
|
+
*
|
|
438
|
+
* @param hooks - The primitive hooks (React's own, or the headless session's).
|
|
439
|
+
* @param preview - The live-preview state and actions.
|
|
440
|
+
* @param props - The host's inputs.
|
|
441
|
+
* @returns The state the view renders and the handlers it wires.
|
|
442
|
+
*/
|
|
443
|
+
export function usePreviewPanelLogic(hooks, preview, props) {
|
|
444
|
+
const { useCallback, useEffect, useRef, useState } = hooks;
|
|
445
|
+
const { state, setDevice, recordNavigation, back, forward } = preview;
|
|
446
|
+
const { onPreviewError, onPreviewStuck, onRestartBackend, onRenderState, uiCommand, onUiResult, fileChangeTick, isBuilding, wakeAt, } = props;
|
|
447
|
+
const iframeRef = useRef(null);
|
|
448
|
+
// AI-driven live preview control: when the host sets a NEW `uiCommand` (keyed on `id`), relay
|
|
449
|
+
// it to the iframe's interaction bridge (`molecule:ui-command`); the bridge replies
|
|
450
|
+
// `molecule:ui-result`, handled in the message listener below → `onUiResult`. Lets Synthase
|
|
451
|
+
// drive + verify the app end-to-end in the preview the user is watching (no headless browser).
|
|
452
|
+
const lastUiCommandIdRef = useRef(null);
|
|
453
|
+
// Ids the bridge has already answered — flipped by the message listener below so the retry
|
|
454
|
+
// loop stops. A ref (not state) so the interval sees the latest value without re-subscribing.
|
|
455
|
+
const uiResolvedRef = useRef(new Set());
|
|
456
|
+
// The current unresolved command payload + its deadline, for EVENT-DRIVEN re-posts from the
|
|
457
|
+
// message listener (on the bridge's ready/heartbeat frames). In a hidden/backgrounded tab
|
|
458
|
+
// the retry interval below is throttled — Chrome's intensive throttling runs ONE tick per
|
|
459
|
+
// MINUTE — so a command posted while an iframe was mid-reload would never be re-sent in
|
|
460
|
+
// time; message events are NOT throttled, so the incoming bridge frames carry the retry.
|
|
461
|
+
const pendingUiPostRef = useRef(null);
|
|
462
|
+
useEffect(() => {
|
|
463
|
+
if (!uiCommand || uiCommand.id === lastUiCommandIdRef.current)
|
|
464
|
+
return;
|
|
465
|
+
lastUiCommandIdRef.current = uiCommand.id;
|
|
466
|
+
const cmdId = uiCommand.id;
|
|
467
|
+
const payload = {
|
|
468
|
+
type: 'molecule:ui-command',
|
|
469
|
+
id: cmdId,
|
|
470
|
+
action: uiCommand.action,
|
|
471
|
+
molId: uiCommand.molId,
|
|
472
|
+
selector: uiCommand.selector,
|
|
473
|
+
text: uiCommand.text,
|
|
474
|
+
value: uiCommand.value,
|
|
475
|
+
// Navigation only: only a document that loaded at or after this may answer, so the
|
|
476
|
+
// OUTGOING page can't reply with a pre-navigation snapshot.
|
|
477
|
+
minLoadedAt: uiCommand.minLoadedAt,
|
|
478
|
+
};
|
|
479
|
+
// Post repeatedly until the bridge replies (or ~40s, under the navigate tool's 45s wait). A
|
|
480
|
+
// single post races iframe/bridge readiness: the preview may be mid-mount (the view just
|
|
481
|
+
// switched to it) or mid-reload (navigate_preview reloads the iframe), so the first postMessage
|
|
482
|
+
// is silently dropped. The bridge dedups by command id, so re-sending a click/fill still
|
|
483
|
+
// executes it once. The window must outlast a slow dev server's COLD ROUTE COMPILE — a first
|
|
484
|
+
// hit to a Next.js/Nuxt/SvelteKit route commonly takes 10-30s (and an auth redirect compiles a
|
|
485
|
+
// SECOND route), so a 12s window timed out navigate_preview on every imported meta-framework app.
|
|
486
|
+
const post = () => {
|
|
487
|
+
iframeRef.current?.contentWindow?.postMessage(payload, previewTargetOrigin(iframeRef.current));
|
|
488
|
+
};
|
|
489
|
+
post();
|
|
490
|
+
const deadline = Date.now() + 40_000;
|
|
491
|
+
pendingUiPostRef.current = { payload, deadline };
|
|
492
|
+
const interval = window.setInterval(() => {
|
|
493
|
+
if (uiResolvedRef.current.has(cmdId) || Date.now() > deadline) {
|
|
494
|
+
window.clearInterval(interval);
|
|
495
|
+
uiResolvedRef.current.delete(cmdId);
|
|
496
|
+
if (pendingUiPostRef.current?.payload.id === cmdId)
|
|
497
|
+
pendingUiPostRef.current = null;
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
post();
|
|
501
|
+
}, 350);
|
|
502
|
+
return () => window.clearInterval(interval);
|
|
503
|
+
}, [uiCommand]);
|
|
504
|
+
// Preview-only iframe orientation (portrait ⇄ landscape) for fixed-frame
|
|
505
|
+
// devices. A purely visual preview concern, so it lives here rather than in the
|
|
506
|
+
// live-preview core state — but it is GLOBAL (one orientation for every
|
|
507
|
+
// rotatable device, never reset on a device switch) and PERSISTED across reloads
|
|
508
|
+
// via the bonded storage provider, so a chosen landscape carries everywhere.
|
|
509
|
+
const [orientation, setOrientation] = useState('portrait');
|
|
510
|
+
// A size the PREVIEWED PAGE asked for (`molecule:viewport`, posted by an e2e run's
|
|
511
|
+
// page.setViewportSize inside the preview). Overrides the device frame until the
|
|
512
|
+
// person picks a device again or the page asks for `width: null`.
|
|
513
|
+
const [requestedSize, setRequestedSize] = useState(null);
|
|
514
|
+
// Restore the persisted orientation once on mount. Best-effort: if no storage
|
|
515
|
+
// provider is bonded (tests / an app that didn't wire one) it just won't persist.
|
|
516
|
+
useEffect(() => {
|
|
517
|
+
let mounted = true;
|
|
518
|
+
void (async () => {
|
|
519
|
+
try {
|
|
520
|
+
const stored = await storageGet(ORIENTATION_STORAGE_KEY);
|
|
521
|
+
if (mounted && (stored === 'portrait' || stored === 'landscape')) {
|
|
522
|
+
setOrientation(stored);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
catch (_error) {
|
|
526
|
+
// No storage provider bonded / read failed — orientation simply won't persist.
|
|
527
|
+
}
|
|
528
|
+
})();
|
|
529
|
+
return () => {
|
|
530
|
+
mounted = false;
|
|
531
|
+
};
|
|
532
|
+
}, []);
|
|
533
|
+
// Device switching does NOT reset the orientation — it's a global preference, so
|
|
534
|
+
// a landscape choice applies to whichever rotatable device is selected next.
|
|
535
|
+
const handleDeviceChange = useCallback((device) => {
|
|
536
|
+
setRequestedSize(null);
|
|
537
|
+
setDevice(device);
|
|
538
|
+
}, [setDevice]);
|
|
539
|
+
const handleRotate = useCallback(() => {
|
|
540
|
+
const next = orientation === 'portrait' ? 'landscape' : 'portrait';
|
|
541
|
+
setOrientation(next);
|
|
542
|
+
void storageSet(ORIENTATION_STORAGE_KEY, next).catch((_error) => {
|
|
543
|
+
// Best-effort persist — no storage provider bonded; the in-memory value still applies.
|
|
544
|
+
});
|
|
545
|
+
}, [orientation]);
|
|
546
|
+
const canRotate = isDeviceRotatable(state.device);
|
|
547
|
+
// The preview's actual current location (updated by the scaffold's
|
|
548
|
+
// `molecule:navigate` message), falling back to the load target before the
|
|
549
|
+
// preview has reported a location.
|
|
550
|
+
const currentLocation = state.currentUrl || state.url;
|
|
551
|
+
// Whether the current location is served over a secure (https) origin. Drives
|
|
552
|
+
// the address bar's leading site-info glyph — a lock when secure, a globe
|
|
553
|
+
// otherwise — exactly like a real browser omnibox.
|
|
554
|
+
const isSecureLocation = /^https:/i.test(currentLocation);
|
|
555
|
+
// Has the server ever responded successfully?
|
|
556
|
+
const [everLoaded, setEverLoaded] = useState(false);
|
|
557
|
+
// Mirror everLoaded to a ref so the message handler (which is NOT re-subscribed
|
|
558
|
+
// when everLoaded changes) reads the live value, not a stale closure.
|
|
559
|
+
const everLoadedRef = useRef(everLoaded);
|
|
560
|
+
everLoadedRef.current = everLoaded;
|
|
561
|
+
// Is the iframe content ready to show?
|
|
562
|
+
const [iframeReady, setIframeReady] = useState(false);
|
|
563
|
+
// Fade-out transition in progress
|
|
564
|
+
const [fadingOut, setFadingOut] = useState(false);
|
|
565
|
+
const pollRef = useRef(null);
|
|
566
|
+
// Generation token: bumped on every clearPoll so a superseded poll() chain bails
|
|
567
|
+
// on its next guard instead of re-arming — guarantees only ONE live poll chain.
|
|
568
|
+
const pollEpochRef = useRef(0);
|
|
569
|
+
// AbortController for the in-flight server-up probe, so cleanup can cancel it.
|
|
570
|
+
const pollAbortRef = useRef(null);
|
|
571
|
+
// Deadline for the first-mount poll to surface the actionable notice while it
|
|
572
|
+
// keeps polling (see PREMOUNT_GIVEUP_MS). Cleared with the poll chain.
|
|
573
|
+
const pollGiveUpTimerRef = useRef(null);
|
|
574
|
+
const urlRef = useRef(state.url);
|
|
575
|
+
urlRef.current = state.url;
|
|
576
|
+
// The preview's live location (client-side route included), read by the stuck/freeze
|
|
577
|
+
// callbacks so a failure report names the route the user is actually on, not the
|
|
578
|
+
// initial load target.
|
|
579
|
+
const currentLocationRef = useRef(currentLocation);
|
|
580
|
+
currentLocationRef.current = currentLocation;
|
|
581
|
+
// De-dup ledger for forwarded runtime errors: signature → last-forwarded timestamp.
|
|
582
|
+
// Persists across message-handler re-subscriptions so a duplicate from the baked +
|
|
583
|
+
// centralized senders (or a re-throwing render loop) is dropped within the window.
|
|
584
|
+
const recentErrorSigRef = useRef(new Map());
|
|
585
|
+
// Tracks the iframe src to force reload when server recovers
|
|
586
|
+
const [iframeSrc, setIframeSrc] = useState('');
|
|
587
|
+
// --- Stuck-load detection state ---
|
|
588
|
+
const [stuckRetryCount, setStuckRetryCount] = useState(0);
|
|
589
|
+
const stuckTimerRef = useRef(null);
|
|
590
|
+
const [iframeMountKey, setIframeMountKey] = useState(0);
|
|
591
|
+
// Auto-reloads attempted for a loaded-but-unrendered document THIS load (stale-document
|
|
592
|
+
// recovery, e.g. after a Vite server restart) — bounded by MAX_LOAD_RECOVERS, reset per load.
|
|
593
|
+
const loadRecoverCountRef = useRef(0);
|
|
594
|
+
// True once the cap of recovery cycles is hit — stops the loop and shows the
|
|
595
|
+
// themed "Preview can't load here" panel (loop breaker) instead of thrashing.
|
|
596
|
+
const [previewGaveUp, setPreviewGaveUp] = useState(false);
|
|
597
|
+
// Probe-driven automatic recoveries fired this dead-end episode (see
|
|
598
|
+
// MAX_DEAD_END_AUTO_RECOVERS) — reset on a confirmed render or a manual retry.
|
|
599
|
+
const deadEndAutoRecoversRef = useRef(0);
|
|
600
|
+
// --- Backend-restart escalation state (see the escalation watchdog effect) ---
|
|
601
|
+
// When the current "no confirmed render" stretch began. Pushed forward by any
|
|
602
|
+
// confirm-state change, a new load target, and a wake — so the escalation clock
|
|
603
|
+
// only measures genuinely-stuck time, never healthy time or granted patience.
|
|
604
|
+
const notConfirmedSinceRef = useRef(Date.now());
|
|
605
|
+
// One escalation per broken episode; re-armed only by a confirmed render.
|
|
606
|
+
const backendRestartUsedRef = useRef(false);
|
|
607
|
+
const lastBackendRestartAtRef = useRef(0);
|
|
608
|
+
// Mirror iframeReady to a ref so timer callbacks read current value
|
|
609
|
+
const iframeReadyRef = useRef(iframeReady);
|
|
610
|
+
iframeReadyRef.current = iframeReady;
|
|
611
|
+
// Shows the iframe. When it was hidden, the overlay's fade starts in the same update: set
|
|
612
|
+
// from an effect a render later, a render with the overlay already gone would come first, so
|
|
613
|
+
// the overlay would be removed and mounted again instead of fading out.
|
|
614
|
+
const reveal = useCallback(() => {
|
|
615
|
+
if (!iframeReadyRef.current)
|
|
616
|
+
setFadingOut(true);
|
|
617
|
+
setIframeReady(true);
|
|
618
|
+
}, []);
|
|
619
|
+
// Whether the CURRENT iframe document has fired `onLoad`. When it has, the load
|
|
620
|
+
// reached the document and only the handshake is missing — the onLoad grace
|
|
621
|
+
// fallback (not a remount) clears the overlay, so the stuck-detector stands down.
|
|
622
|
+
const iframeLoadedRef = useRef(false);
|
|
623
|
+
// Pending onLoad grace timer (cleared on a new load / unmount).
|
|
624
|
+
const onLoadGraceRef = useRef(null);
|
|
625
|
+
// Timestamp of the last crash message — the onLoad fallback refuses to mask a
|
|
626
|
+
// load that just crashed (a crash within the grace window suppresses it).
|
|
627
|
+
const lastCrashAtRef = useRef(0);
|
|
628
|
+
// --- Last-good-frame (molecule:snapshot) ---
|
|
629
|
+
// The most recent rasterized frame the sandbox app posted while it was rendering
|
|
630
|
+
// fine. Shown BLURRED behind the overlay while the app is rebuilding or blank,
|
|
631
|
+
// so the user sees the last working UI instead of a white iframe.
|
|
632
|
+
const [lastGoodFrame, setLastGoodFrame] = useState(null);
|
|
633
|
+
// --- Content confirmation ---
|
|
634
|
+
// `iframeReady` only means the iframe was REVEALED (handshake OR the onLoad grace
|
|
635
|
+
// fallback) — it is true even for a blank/white app the grace path optimistically
|
|
636
|
+
// unmasked. `confirmedContent` is the stronger signal: the app actually reported it
|
|
637
|
+
// rendered visible content (molecule:ready, which a healthy app re-sends ~every 4s).
|
|
638
|
+
// The overlay keeps a status up until content is confirmed, so a half-built / blank /
|
|
639
|
+
// white iframe never shows as a bare white screen. Reset on a crash/blank/new load.
|
|
640
|
+
const [confirmedContent, setConfirmedContent] = useState(false);
|
|
641
|
+
const confirmedContentRef = useRef(false);
|
|
642
|
+
confirmedContentRef.current = confirmedContent;
|
|
643
|
+
// Timestamp of the last molecule:ready. When a NEW document loads (initial load, or a Vite
|
|
644
|
+
// full-reload that an edit triggers), we keep confirmedContent only if a ready landed in the
|
|
645
|
+
// moment before — otherwise the (re)loaded document has NOT shown content for THIS load and
|
|
646
|
+
// confirmedContent is dropped so the overlay re-covers a blank reload. This is what catches
|
|
647
|
+
// "the app rendered, then a reload left it blank."
|
|
648
|
+
const lastReadyAtRef = useRef(0);
|
|
649
|
+
// Settle-gated post-build blank: the build is not running, the document loaded, yet no content
|
|
650
|
+
// was ever confirmed — the app rendered nothing. Switches the overlay's copy to an ACTIONABLE
|
|
651
|
+
// notice (reload / open in tab) instead of the generic spinner.
|
|
652
|
+
const [blankPostBuild, setBlankPostBuild] = useState(false);
|
|
653
|
+
// Mirror blankPostBuild to a ref so the absolute-ceiling timer can tell "still on a
|
|
654
|
+
// bare spinner" (fire) from "already showing the actionable blank notice" (a way out
|
|
655
|
+
// exists — stand down).
|
|
656
|
+
const blankPostBuildRef = useRef(blankPostBuild);
|
|
657
|
+
blankPostBuildRef.current = blankPostBuild;
|
|
658
|
+
// Mirror isBuilding into a ref so timers/handlers read the current value.
|
|
659
|
+
const isBuildingRef = useRef(isBuilding);
|
|
660
|
+
isBuildingRef.current = isBuilding;
|
|
661
|
+
// Has the app at the CURRENT load target confirmed a render (`molecule:ready`) at least once
|
|
662
|
+
// this session? Set on the first ready, reset only on a genuinely NEW load target (url /
|
|
663
|
+
// loadNonce change), NOT on a plain Vite HMR full-reload of the same src. It is the switch
|
|
664
|
+
// between two regimes: a NEVER-yet-rendered app is treated as a patient cold boot (reveal only
|
|
665
|
+
// on ready, honest "Starting…" status, no false "blank"/"can't load"); an app that HAS rendered
|
|
666
|
+
// and then reloaded blank is a real regression (short blank-confirm window, fast onLoad-grace
|
|
667
|
+
// reveal). Conflating the two is what surfaced a false "blank" over a still-compiling fresh app.
|
|
668
|
+
const hasEverRenderedRef = useRef(false);
|
|
669
|
+
// Timestamp of the current document's last `onLoad` (0 = not loaded this target). Drives the
|
|
670
|
+
// elapsed-since-load math in the cold-boot evaluator without racing a stale closure.
|
|
671
|
+
const lastLoadAtRef = useRef(0);
|
|
672
|
+
// The raw document a link click inside the preview is about to load (reported by the bridge
|
|
673
|
+
// as a `molecule:navigate` intent, see {@link isRawDocumentUrl}), until its `onLoad` consumes
|
|
674
|
+
// it. That load is content by definition: the browser's own viewer, no bridge, no ready.
|
|
675
|
+
const rawDocIntentRef = useRef(null);
|
|
676
|
+
// Bumped on every iframe `onLoad` so the cold-boot evaluator effect re-runs when a fresh
|
|
677
|
+
// document loads (the reveal no longer flips `iframeReady` on the grace during a cold boot, so
|
|
678
|
+
// that flag can't be the trigger anymore).
|
|
679
|
+
const [docLoadedTick, setDocLoadedTick] = useState(0);
|
|
680
|
+
// --- Wake patience (see WAKE_PATIENCE_MS) ---
|
|
681
|
+
// Mirror the wakeAt prop into a ref so interval/timeout callbacks (the blank evaluator,
|
|
682
|
+
// the absolute ceiling) read the live value without re-subscribing.
|
|
683
|
+
const wakeAtRef = useRef(wakeAt ?? 0);
|
|
684
|
+
wakeAtRef.current = wakeAt ?? 0;
|
|
685
|
+
// THE reliable, self-contained wake signal: the load target (`state.url`) changed to a
|
|
686
|
+
// DIFFERENT non-empty preview URL. The only thing that repoints the preview at a new URL is the
|
|
687
|
+
// sandbox's dev server being (re)started — a wake reassigns the container's docker port EVERY
|
|
688
|
+
// time (the port binding uses an empty HostPort, so Docker hands out a fresh ephemeral port on
|
|
689
|
+
// each start), so a woken preview always arrives on a new `http://127.0.0.1:<newport>` URL.
|
|
690
|
+
// In-app navigation never changes `state.url` (it moves `currentUrl` via recordNavigation), so
|
|
691
|
+
// a change here is unambiguously "the preview server just restarted." This is far more reliable
|
|
692
|
+
// than the host's sandbox-status signal (stop/hibernate broadcasts are easily missed and the
|
|
693
|
+
// status can desync), so it — not the `wakeAt` prop — is the primary trigger for wake patience.
|
|
694
|
+
const prevUrlRef = useRef('');
|
|
695
|
+
const urlWakeAtRef = useRef(0);
|
|
696
|
+
if (state.url && prevUrlRef.current && state.url !== prevUrlRef.current) {
|
|
697
|
+
urlWakeAtRef.current = Date.now();
|
|
698
|
+
}
|
|
699
|
+
if (state.url)
|
|
700
|
+
prevUrlRef.current = state.url;
|
|
701
|
+
/**
|
|
702
|
+
* Whether the backing preview server was woken/restarted recently enough to owe patience —
|
|
703
|
+
* true within WAKE_PATIENCE_MS of EITHER a load-target change (the reliable signal) OR the
|
|
704
|
+
* host's explicit `wakeAt` prop (a secondary hint).
|
|
705
|
+
*/
|
|
706
|
+
const inWakeWindow = useCallback(() => {
|
|
707
|
+
const wokeAt = Math.max(wakeAtRef.current, urlWakeAtRef.current);
|
|
708
|
+
return wokeAt > 0 && Date.now() - wokeAt < WAKE_PATIENCE_MS;
|
|
709
|
+
}, []);
|
|
710
|
+
// A fresh wake re-enters the patient cold-boot regime for the CURRENT load target: the
|
|
711
|
+
// restarting dev server is about to reload the document (or already did) into a state
|
|
712
|
+
// that legitimately renders nothing for a while, so the "already rendered → any reload
|
|
713
|
+
// that doesn't re-confirm fast is a regression" contract no longer holds. Dropping
|
|
714
|
+
// hasEverRendered routes everything through the proven patient paths (reveal only on
|
|
715
|
+
// `molecule:ready`, no grace-unmasking of an unconfirmed reload, no BLANK_CONFIRM_MS
|
|
716
|
+
// fast accusation); the first ready after the wake restores the normal regime. Also
|
|
717
|
+
// withdraw any already-showing accusation (it described the pre-wake world) and grant a
|
|
718
|
+
// fresh stale-document recovery budget — those auto-reloads are the recovery engine for
|
|
719
|
+
// a wake that landed on a transient bridge-less error page. Runs on mount too, so a
|
|
720
|
+
// panel that remounts right after a wake (the sleeping-screen → running flow) inherits
|
|
721
|
+
// the same patience.
|
|
722
|
+
useEffect(() => {
|
|
723
|
+
if (!wakeAt || Date.now() - wakeAt >= WAKE_PATIENCE_MS)
|
|
724
|
+
return;
|
|
725
|
+
// FIRST-BOOT RELOAD. The load-target-change wake signal can never fire on
|
|
726
|
+
// a first boot: the URL is set once — before the server answers — and
|
|
727
|
+
// never changes, so the iframe keeps the stale pre-wake document (behind
|
|
728
|
+
// the preview proxy that is its "target unavailable" error page, which has
|
|
729
|
+
// no bridge and can never self-heal). If nothing has EVER rendered on this
|
|
730
|
+
// load target, a wake means "the app is up now — the current document is
|
|
731
|
+
// provably stale": reload it cache-busted immediately. Patience alone left
|
|
732
|
+
// that error page up until the slow stuck-retry cycle (observed live:
|
|
733
|
+
// served at 13:17:36, painted at 13:19:57). An already-rendered app keeps
|
|
734
|
+
// the old behavior — patience without a disruptive reload.
|
|
735
|
+
const neverRendered = !hasEverRenderedRef.current;
|
|
736
|
+
hasEverRenderedRef.current = false;
|
|
737
|
+
loadRecoverCountRef.current = 0;
|
|
738
|
+
setBlankPostBuild(false);
|
|
739
|
+
setPreviewGaveUp(false);
|
|
740
|
+
setStuckRetryCount(0);
|
|
741
|
+
// A wake grants a fresh escalation clock too — the relaunching server owes
|
|
742
|
+
// no restart while its own cold path plays out.
|
|
743
|
+
notConfirmedSinceRef.current = Date.now();
|
|
744
|
+
if (neverRendered && urlRef.current) {
|
|
745
|
+
setIframeSrc(withCacheBuster(urlRef.current));
|
|
746
|
+
}
|
|
747
|
+
}, [wakeAt]);
|
|
748
|
+
// --- Heartbeat tracking ---
|
|
749
|
+
const lastHeartbeatRef = useRef(0);
|
|
750
|
+
// True when heartbeats have stopped for FREEZE_THRESHOLD_MS while the app is up.
|
|
751
|
+
const [previewFrozen, setPreviewFrozen] = useState(false);
|
|
752
|
+
// Guards the freeze report so a single freeze episode notifies the host ONCE, not on
|
|
753
|
+
// every watchdog tick; reset when heartbeats resume so a later freeze re-reports.
|
|
754
|
+
const frozenReportedRef = useRef(false);
|
|
755
|
+
// --- Cycle detection: catch rapid ready↔error oscillations ---
|
|
756
|
+
const transitionTimesRef = useRef([]);
|
|
757
|
+
const suppressedRef = useRef(false);
|
|
758
|
+
// --- URL bar (browser-style: reflects the preview's CURRENT location) ---
|
|
759
|
+
// A local draft so the user can type freely; it's committed on Enter (a real
|
|
760
|
+
// load) and resynced to the live location whenever the preview navigates and
|
|
761
|
+
// the user isn't mid-edit. Editing never reloads per-keystroke.
|
|
762
|
+
const [urlDraft, setUrlDraft] = useState(currentLocation);
|
|
763
|
+
const [urlEditing, setUrlEditing] = useState(false);
|
|
764
|
+
useEffect(() => {
|
|
765
|
+
if (!urlEditing)
|
|
766
|
+
setUrlDraft(currentLocation);
|
|
767
|
+
}, [currentLocation, urlEditing]);
|
|
768
|
+
// --- Clear poll timer ---
|
|
769
|
+
// Also invalidates any in-flight poll chain: bumping the epoch makes a poll()
|
|
770
|
+
// that is mid-await bail on its next guard instead of re-arming a new timer, and
|
|
771
|
+
// aborting the controller releases the in-flight HEAD probe so it stops holding a
|
|
772
|
+
// per-origin connection (the leak the file's own comment warns about).
|
|
773
|
+
const clearPoll = useCallback(() => {
|
|
774
|
+
if (pollRef.current) {
|
|
775
|
+
clearTimeout(pollRef.current);
|
|
776
|
+
pollRef.current = null;
|
|
777
|
+
}
|
|
778
|
+
pollEpochRef.current += 1;
|
|
779
|
+
if (pollAbortRef.current) {
|
|
780
|
+
pollAbortRef.current.abort();
|
|
781
|
+
pollAbortRef.current = null;
|
|
782
|
+
}
|
|
783
|
+
if (pollGiveUpTimerRef.current) {
|
|
784
|
+
clearTimeout(pollGiveUpTimerRef.current);
|
|
785
|
+
pollGiveUpTimerRef.current = null;
|
|
786
|
+
}
|
|
787
|
+
}, []);
|
|
788
|
+
// --- Clear stuck timer ---
|
|
789
|
+
const clearStuckTimer = useCallback(() => {
|
|
790
|
+
if (stuckTimerRef.current) {
|
|
791
|
+
clearTimeout(stuckTimerRef.current);
|
|
792
|
+
stuckTimerRef.current = null;
|
|
793
|
+
}
|
|
794
|
+
}, []);
|
|
795
|
+
// --- Poll until server is up, then mount the iframe ---
|
|
796
|
+
// Uses exponential backoff: POLL_INITIAL_MS → POLL_MAX_MS. The poll itself never
|
|
797
|
+
// stops, but past PREMOUNT_GIVEUP_MS it surfaces the actionable notice while it
|
|
798
|
+
// keeps polling — the user always has a way out (Reload / Open in new tab), and a
|
|
799
|
+
// late success still mounts + withdraws the notice by itself.
|
|
800
|
+
const startPolling = useCallback((url) => {
|
|
801
|
+
// clearPoll() bumps the epoch + aborts the prior chain; capture the fresh
|
|
802
|
+
// epoch + a new AbortController so THIS chain is the only live one. Any older
|
|
803
|
+
// poll() awaiting a fetch now sees a stale epoch and bails.
|
|
804
|
+
clearPoll();
|
|
805
|
+
const epoch = pollEpochRef.current;
|
|
806
|
+
const abort = new AbortController();
|
|
807
|
+
pollAbortRef.current = abort;
|
|
808
|
+
setIframeReady(false);
|
|
809
|
+
setFadingOut(false);
|
|
810
|
+
setPreviewGaveUp(false);
|
|
811
|
+
// A (re)load hasn't confirmed content yet — the overlay governs until it does.
|
|
812
|
+
setConfirmedContent(false);
|
|
813
|
+
setBlankPostBuild(false);
|
|
814
|
+
// The poll never stops on its own, so past this deadline it surfaces the
|
|
815
|
+
// actionable notice (Reload / Open in new tab) INSTEAD of an unbounded
|
|
816
|
+
// spinner — and keeps polling underneath; a later success mounts the
|
|
817
|
+
// iframe and withdraws the notice. This was the one preview path with no
|
|
818
|
+
// escape hatch at all (see PREMOUNT_GIVEUP_MS).
|
|
819
|
+
pollGiveUpTimerRef.current = setTimeout(() => {
|
|
820
|
+
pollGiveUpTimerRef.current = null;
|
|
821
|
+
if (pollEpochRef.current !== epoch)
|
|
822
|
+
return;
|
|
823
|
+
// Deliberate breadcrumb: this state means the preview host never answered a
|
|
824
|
+
// probe for the whole deadline — the console line is the forensic trail for
|
|
825
|
+
// the next live debug of a "stuck on Loading preview" report.
|
|
826
|
+
console.warn(`[preview] server at ${url} has not answered for ${Math.round(PREMOUNT_GIVEUP_MS / 1000)}s — showing the reload notice, still polling`);
|
|
827
|
+
setPreviewGaveUp(true);
|
|
828
|
+
}, PREMOUNT_GIVEUP_MS);
|
|
829
|
+
let interval = POLL_INITIAL_MS;
|
|
830
|
+
const poll = async () => {
|
|
831
|
+
if (pollEpochRef.current !== epoch || urlRef.current !== url)
|
|
832
|
+
return;
|
|
833
|
+
const up = await isServerUp(url, abort.signal);
|
|
834
|
+
if (pollEpochRef.current !== epoch || urlRef.current !== url)
|
|
835
|
+
return;
|
|
836
|
+
if (up) {
|
|
837
|
+
if (pollGiveUpTimerRef.current) {
|
|
838
|
+
clearTimeout(pollGiveUpTimerRef.current);
|
|
839
|
+
pollGiveUpTimerRef.current = null;
|
|
840
|
+
}
|
|
841
|
+
setPreviewGaveUp(false);
|
|
842
|
+
setEverLoaded(true);
|
|
843
|
+
// Atomic remount (fresh <iframe> element + src in one commit), like the
|
|
844
|
+
// proven manual-reload/navigation paths: if `setUrl` was called more than
|
|
845
|
+
// once for this load target before the server came up (e.g. a sandbox-boot
|
|
846
|
+
// host reporting its preview URL from more than one code path), an earlier
|
|
847
|
+
// poll chain may already have raced partway through mounting an iframe for
|
|
848
|
+
// this exact url before being superseded — bumping the mount key here
|
|
849
|
+
// guarantees this success always creates a genuinely fresh OOPIF rather
|
|
850
|
+
// than reusing/navigating one a superseded chain may have touched.
|
|
851
|
+
setIframeMountKey((k) => k + 1);
|
|
852
|
+
setIframeSrc(url);
|
|
853
|
+
pollRef.current = null;
|
|
854
|
+
}
|
|
855
|
+
else {
|
|
856
|
+
pollRef.current = setTimeout(poll, interval);
|
|
857
|
+
interval = Math.min(interval * POLL_BACKOFF_FACTOR, POLL_MAX_MS);
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
void poll();
|
|
861
|
+
}, [clearPoll]);
|
|
862
|
+
// --- When URL changes, reset and start polling ---
|
|
863
|
+
useEffect(() => {
|
|
864
|
+
if (!state.url) {
|
|
865
|
+
clearPoll();
|
|
866
|
+
clearStuckTimer();
|
|
867
|
+
setEverLoaded(false);
|
|
868
|
+
setIframeReady(false);
|
|
869
|
+
setFadingOut(false);
|
|
870
|
+
setIframeSrc('');
|
|
871
|
+
setStuckRetryCount(0);
|
|
872
|
+
setPreviewGaveUp(false);
|
|
873
|
+
setLastGoodFrame(null);
|
|
874
|
+
setConfirmedContent(false);
|
|
875
|
+
setBlankPostBuild(false);
|
|
876
|
+
hasEverRenderedRef.current = false;
|
|
877
|
+
lastLoadAtRef.current = 0;
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
setStuckRetryCount(0);
|
|
881
|
+
setPreviewGaveUp(false);
|
|
882
|
+
loadRecoverCountRef.current = 0; // fresh stale-document recovery budget for this load
|
|
883
|
+
// A brand-new load target starts a fresh cold-boot regime: it has not rendered yet, so treat
|
|
884
|
+
// it patiently (reveal on ready, no premature blank/give-up) until ITS first molecule:ready.
|
|
885
|
+
hasEverRenderedRef.current = false;
|
|
886
|
+
lastLoadAtRef.current = 0;
|
|
887
|
+
// Fresh escalation clock for the new target.
|
|
888
|
+
notConfirmedSinceRef.current = Date.now();
|
|
889
|
+
// A new load target hasn't confirmed content yet.
|
|
890
|
+
setConfirmedContent(false);
|
|
891
|
+
setBlankPostBuild(false);
|
|
892
|
+
// A brand-new load target is a different app — drop the previous app's frame
|
|
893
|
+
// so a blank in the NEW app never flashes the OLD app's last-good frame.
|
|
894
|
+
setLastGoodFrame(null);
|
|
895
|
+
if (everLoadedRef.current) {
|
|
896
|
+
// NAVIGATION / refresh of an already-running preview (a chat-link route, the URL
|
|
897
|
+
// bar, Back/Forward, or a loadNonce refresh). The dev server is already up, so do an
|
|
898
|
+
// ATOMIC remount to the new target — bump the mount key (fresh <iframe> element) and
|
|
899
|
+
// set the src in ONE commit — EXACTLY like the manual-reload path (handleManualRetry),
|
|
900
|
+
// which is known to work. The OLD path blanked the live iframe (setIframeSrc('')) then
|
|
901
|
+
// re-added it after an async probe; that two-phase teardown→rebuild wedged the live
|
|
902
|
+
// sandboxed cross-origin (OOPIF) frame so the route "navigated but never loaded".
|
|
903
|
+
//
|
|
904
|
+
// CRUCIALLY use the cache-buster, like refresh does: navigating a cross-origin iframe
|
|
905
|
+
// to a URL it already treats as its CURRENT location (the app's own client-side router
|
|
906
|
+
// may have moved the iframe's location to this route already, or a bfcache entry
|
|
907
|
+
// exists) is a same-document no-op that never reloads — which is why a chat-link nav
|
|
908
|
+
// hung while the refresh button (cache-busted) worked. The `_r=<ts>` makes every nav a
|
|
909
|
+
// novel URL that forces a real document load; recordNavigation strips `_r` so the URL
|
|
910
|
+
// bar stays clean.
|
|
911
|
+
clearPoll();
|
|
912
|
+
setIframeMountKey((k) => k + 1);
|
|
913
|
+
setIframeSrc(withCacheBuster(state.url));
|
|
914
|
+
}
|
|
915
|
+
else {
|
|
916
|
+
// COLD / first load: the dev server may still be starting, so keep the empty state
|
|
917
|
+
// and poll until it answers, then mount.
|
|
918
|
+
setEverLoaded(false);
|
|
919
|
+
setIframeSrc('');
|
|
920
|
+
startPolling(state.url);
|
|
921
|
+
}
|
|
922
|
+
return () => {
|
|
923
|
+
clearPoll();
|
|
924
|
+
clearStuckTimer();
|
|
925
|
+
};
|
|
926
|
+
// state.loadNonce forces a reload even when the URL string is unchanged
|
|
927
|
+
// (refresh, or back/forward to the same load target). recordNavigation does
|
|
928
|
+
// NOT bump loadNonce, so an in-app navigation updates the URL bar without
|
|
929
|
+
// reloading here.
|
|
930
|
+
}, [state.url, state.loadNonce, startPolling, clearPoll, clearStuckTimer]);
|
|
931
|
+
// --- A new document is loading → reset per-load onLoad tracking ---
|
|
932
|
+
// Whenever the iframe gets a fresh src or is remounted, the onLoad flag and any
|
|
933
|
+
// pending grace timer belong to the PREVIOUS load — clear them so the new load's
|
|
934
|
+
// own onLoad drives the fallback.
|
|
935
|
+
//
|
|
936
|
+
// Reset DURING RENDER (the same ref-sync shape used for `wakeAt`/`prevUrl` above), NOT in a
|
|
937
|
+
// passive effect: these fields describe the CURRENT document, so they must flip in the same
|
|
938
|
+
// commit that changes the document. A passive effect is scheduled on a later task than the
|
|
939
|
+
// commit, so the new document's `onLoad` can be handled BEFORE the reset runs and then be
|
|
940
|
+
// silently discarded — after which the cold-boot evaluator never arms (it requires
|
|
941
|
+
// `iframeLoadedRef`) and a genuinely dead document is never accused, while the stuck detector
|
|
942
|
+
// "retries" a load that had already succeeded (CI flake 2026-10-18, run 39098572320: the
|
|
943
|
+
// "clears the blank notice once the app confirms it rendered" wait timed out at 60s with
|
|
944
|
+
// "Retry attempt 1" on screen). A test that delivers onLoad before the mount's passive effects
|
|
945
|
+
// flush reproduces it deterministically.
|
|
946
|
+
const loadedForSrcRef = useRef(iframeSrc);
|
|
947
|
+
const loadedForMountKeyRef = useRef(iframeMountKey);
|
|
948
|
+
if (loadedForSrcRef.current !== iframeSrc || loadedForMountKeyRef.current !== iframeMountKey) {
|
|
949
|
+
loadedForSrcRef.current = iframeSrc;
|
|
950
|
+
loadedForMountKeyRef.current = iframeMountKey;
|
|
951
|
+
iframeLoadedRef.current = false;
|
|
952
|
+
if (onLoadGraceRef.current) {
|
|
953
|
+
clearTimeout(onLoadGraceRef.current);
|
|
954
|
+
onLoadGraceRef.current = null;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
// The per-document fields are reset synchronously above; this is only the unmount cleanup.
|
|
958
|
+
useEffect(() => () => {
|
|
959
|
+
if (onLoadGraceRef.current) {
|
|
960
|
+
clearTimeout(onLoadGraceRef.current);
|
|
961
|
+
onLoadGraceRef.current = null;
|
|
962
|
+
}
|
|
963
|
+
}, []);
|
|
964
|
+
// --- When the preview is ready to SHOW, trigger fade-out ---
|
|
965
|
+
// Reveal is driven by `iframeReady`, set by the `molecule:ready` handshake (always) OR the
|
|
966
|
+
// `onLoad` grace — but the grace flips it ONLY for a RELOAD of an app that already rendered
|
|
967
|
+
// (`hasEverRendered`), NOT on a first cold boot (see handleIframeLoad). So:
|
|
968
|
+
// • first cold boot → reveal only on `molecule:ready` (the honest "Starting…" overlay stays
|
|
969
|
+
// up over the still-compiling app; no white flash, no false "blank"). The bridge reliably
|
|
970
|
+
// posts ready the instant #root mounts — verified to fire even under occlusion, so this
|
|
971
|
+
// does NOT deadlock (the old "overlay covers iframe → rAF frozen → ready never posts" stall
|
|
972
|
+
// was actually the overlay's `backdrop-filter` freezing the whole renderer, since removed).
|
|
973
|
+
// • reload of an already-rendered app → reveal on the onLoad grace (fast, flash-free), with
|
|
974
|
+
// ready faster still.
|
|
975
|
+
// A genuinely blank/crashed app is RE-COVERED by the explicit `molecule:blank`/crash handlers
|
|
976
|
+
// (which lower `iframeReady`). `confirmedContent` stays the diagnostic render-verdict signal.
|
|
977
|
+
useEffect(() => {
|
|
978
|
+
if (iframeReady) {
|
|
979
|
+
// (The fade itself started with the reveal: see reveal().)
|
|
980
|
+
// Content is showing again — tear down the loop-breaker panel so a later good render
|
|
981
|
+
// always clears it, and refund the dead-end auto-recovery budget (the episode ended
|
|
982
|
+
// in a working preview, so the next outage starts with a full budget).
|
|
983
|
+
setPreviewGaveUp(false);
|
|
984
|
+
deadEndAutoRecoversRef.current = 0;
|
|
985
|
+
// Clear fadingOut when the fade finishes. The overlay's onTransitionEnd is the primary
|
|
986
|
+
// trigger, but it never fires if the overlay unmounts mid-fade, the transition is disabled
|
|
987
|
+
// (prefers-reduced-motion), or in a non-rendering env — so a timer matched to the fade is
|
|
988
|
+
// the robust fallback. A stuck fadingOut pins the overlay at opacity 0 AND blocks the
|
|
989
|
+
// post-build blank re-cover (which is gated on !fadingOut).
|
|
990
|
+
const t = setTimeout(() => setFadingOut(false), OVERLAY_FADE_MS + 50);
|
|
991
|
+
return () => clearTimeout(t);
|
|
992
|
+
}
|
|
993
|
+
return undefined;
|
|
994
|
+
}, [iframeReady]);
|
|
995
|
+
// --- Stuck-load detection: recover ONLY when the load is genuinely stuck ---
|
|
996
|
+
// "Stuck" now means: we have a src, the iframe hasn't reported ready, AND we've
|
|
997
|
+
// given up (panel shown) is not the case. Critically, recovery is gated on the
|
|
998
|
+
// document NOT having fired `onLoad` — if the document loaded, the handshake (not
|
|
999
|
+
// the load) is what's missing and the onLoad grace fallback handles it, so we do
|
|
1000
|
+
// NOT remount (remounting would interrupt a progressing load and bust Vite's
|
|
1001
|
+
// cache). Delays back off, and after MAX_RECOVERY_CYCLES we STOP and show the
|
|
1002
|
+
// themed loop-breaker panel instead of remounting forever.
|
|
1003
|
+
useEffect(() => {
|
|
1004
|
+
if (!iframeSrc || iframeReady || previewGaveUp) {
|
|
1005
|
+
clearStuckTimer();
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
let cycleCount = 0;
|
|
1009
|
+
const scheduleNext = () => {
|
|
1010
|
+
const delay = STUCK_DETECT_MS * Math.pow(STUCK_BACKOFF_FACTOR, cycleCount);
|
|
1011
|
+
stuckTimerRef.current = setTimeout(() => {
|
|
1012
|
+
stuckTimerRef.current = null;
|
|
1013
|
+
// Read refs, not stale closures.
|
|
1014
|
+
if (iframeReadyRef.current)
|
|
1015
|
+
return;
|
|
1016
|
+
// The document loaded but ready never came → defer to the onLoad grace
|
|
1017
|
+
// fallback; do not interrupt a progressing load with a remount.
|
|
1018
|
+
if (iframeLoadedRef.current)
|
|
1019
|
+
return;
|
|
1020
|
+
// A heartbeating document is ALIVE and MID-LOAD: the inline bridge runs
|
|
1021
|
+
// from HTML parse, long before a large module graph finishes (a
|
|
1022
|
+
// multi-repo import behind a microVM edge takes ~30s for ~250 modules —
|
|
1023
|
+
// observed live 2026-08-31). Reloading it aborts every in-flight module
|
|
1024
|
+
// fetch, and the next document races onto the aborted entries and
|
|
1025
|
+
// memoizes spurious failures — the recovery loop MURDERS the loads it
|
|
1026
|
+
// guards ("stuck on Loading preview" while a fresh tab loads fine).
|
|
1027
|
+
// Keep watching instead; a dead doc (no heartbeat) still recovers, and
|
|
1028
|
+
// window `load` never firing at all is bounded by the ceilings.
|
|
1029
|
+
if (Date.now() - lastHeartbeatRef.current < FREEZE_THRESHOLD_MS) {
|
|
1030
|
+
scheduleNext();
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
cycleCount += 1;
|
|
1034
|
+
setStuckRetryCount(cycleCount);
|
|
1035
|
+
if (cycleCount <= MAX_RECOVERY_CYCLES) {
|
|
1036
|
+
if (cycleCount % 2 === 1) {
|
|
1037
|
+
// Odd cycles: force-reload iframe with cache buster
|
|
1038
|
+
setIframeSrc(withCacheBuster(urlRef.current));
|
|
1039
|
+
}
|
|
1040
|
+
else {
|
|
1041
|
+
// Even cycles: full iframe remount (unmount + remount)
|
|
1042
|
+
setIframeMountKey((k) => k + 1);
|
|
1043
|
+
}
|
|
1044
|
+
scheduleNext();
|
|
1045
|
+
}
|
|
1046
|
+
else {
|
|
1047
|
+
// Cap reached — HARD STOP. Never loop forever (the old longRetry()
|
|
1048
|
+
// remounted every 10s indefinitely, compounding the thrash). Notify the
|
|
1049
|
+
// host once, then surface the loop-breaker panel (Reload + open in tab).
|
|
1050
|
+
onPreviewStuck?.({ reason: 'load-failed', url: currentLocationRef.current });
|
|
1051
|
+
setPreviewGaveUp(true);
|
|
1052
|
+
}
|
|
1053
|
+
}, delay);
|
|
1054
|
+
};
|
|
1055
|
+
scheduleNext();
|
|
1056
|
+
return () => clearStuckTimer();
|
|
1057
|
+
}, [iframeSrc, iframeReady, previewGaveUp, onPreviewStuck, clearStuckTimer]);
|
|
1058
|
+
// --- Absolute readiness ceiling (backstop: never stuck on the overlay forever) ---
|
|
1059
|
+
// Independent of every intermediate flag (onLoad / iframeReady / stuck cycles): anchored
|
|
1060
|
+
// to the load, it first checks at ABSOLUTE_STUCK_MS and — if the app still hasn't
|
|
1061
|
+
// confirmed a render and no benign hold applies — surfaces the actionable loop-breaker
|
|
1062
|
+
// panel; a benign hold defers the CHECK, never disarms it. This is the guarantee that no
|
|
1063
|
+
// combination of failed sub-paths can leave the preview spinning forever. Read live refs
|
|
1064
|
+
// (not stale closures); a `molecule:ready` that lands later clears `previewGaveUp` via
|
|
1065
|
+
// the confirm effect, so an early trip is harmless.
|
|
1066
|
+
useEffect(() => {
|
|
1067
|
+
if (!state.url)
|
|
1068
|
+
return;
|
|
1069
|
+
let timer = null;
|
|
1070
|
+
const arm = (delay) => {
|
|
1071
|
+
timer = setTimeout(() => {
|
|
1072
|
+
// A revealed or confirmed preview is healthy — this load needs no ceiling.
|
|
1073
|
+
if (confirmedContentRef.current || iframeReadyRef.current)
|
|
1074
|
+
return;
|
|
1075
|
+
// Fire ONLY when still on a bare spinner. iframeReady above is the key gate: the
|
|
1076
|
+
// onLoad grace already revealed a loaded document, so the give-up panel must never
|
|
1077
|
+
// cover it — the panel is reserved for a preview that genuinely never loaded.
|
|
1078
|
+
// A benign hold — an active build, the actionable blank notice already showing, an
|
|
1079
|
+
// ALIVE (heartbeating) cold boot, or a just-woken server's patience window — does
|
|
1080
|
+
// NOT disarm the ceiling: it RE-CHECKS after a beat. The old one-shot timer stood
|
|
1081
|
+
// down permanently on any of these, so a wake window that swallowed the single
|
|
1082
|
+
// firing left a never-answering preview on the spinner forever with no notice
|
|
1083
|
+
// (the "no reload modal ever popped up" report, 2026-08-31).
|
|
1084
|
+
if (isBuildingRef.current ||
|
|
1085
|
+
blankPostBuildRef.current ||
|
|
1086
|
+
Date.now() - lastHeartbeatRef.current < FREEZE_THRESHOLD_MS ||
|
|
1087
|
+
inWakeWindow()) {
|
|
1088
|
+
arm(ABSOLUTE_STUCK_RECHECK_MS);
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
onPreviewStuck?.({ reason: 'load-timeout', url: currentLocationRef.current });
|
|
1092
|
+
setPreviewGaveUp(true);
|
|
1093
|
+
}, delay);
|
|
1094
|
+
};
|
|
1095
|
+
arm(ABSOLUTE_STUCK_MS);
|
|
1096
|
+
return () => {
|
|
1097
|
+
if (timer)
|
|
1098
|
+
clearTimeout(timer);
|
|
1099
|
+
};
|
|
1100
|
+
// Re-armed per load (url change or refresh/back-forward via loadNonce); a successful
|
|
1101
|
+
// render before the ceiling is honored by the live-ref check in the callback.
|
|
1102
|
+
}, [state.url, state.loadNonce, onPreviewStuck, inWakeWindow]);
|
|
1103
|
+
// --- Stale-document auto-recovery (loaded but never rendered → reload once) ---
|
|
1104
|
+
// The post-ready health check (below) only recovers a server drop AFTER a render; a Vite
|
|
1105
|
+
// "server restarted" mid-load drops the HMR connection and leaves the just-loaded iframe
|
|
1106
|
+
// disconnected, so it never renders and nothing reloads it (today only a MANUAL reload
|
|
1107
|
+
// recovers — the "loads in a new tab, then works on reload" symptom). Here: once the
|
|
1108
|
+
// document has fired onLoad (so it's a stale/blank LOADED doc, NOT a still-optimizing
|
|
1109
|
+
// pre-onLoad load we'd interrupt) and still hasn't confirmed a render, do a SINGLE
|
|
1110
|
+
// server-up check (not continuous polling — that competes for the load's connections) and,
|
|
1111
|
+
// if the server is up, reload ONCE. Bounded by MAX_LOAD_RECOVERS; defers to the ceiling.
|
|
1112
|
+
useEffect(() => {
|
|
1113
|
+
if (!iframeSrc || iframeReady || confirmedContent || previewGaveUp)
|
|
1114
|
+
return;
|
|
1115
|
+
if (loadRecoverCountRef.current >= MAX_LOAD_RECOVERS)
|
|
1116
|
+
return;
|
|
1117
|
+
const timer = setTimeout(() => {
|
|
1118
|
+
void (async () => {
|
|
1119
|
+
// Re-check live state — a render/build/give-up since scheduling cancels recovery.
|
|
1120
|
+
if (iframeReadyRef.current || confirmedContentRef.current || isBuildingRef.current)
|
|
1121
|
+
return;
|
|
1122
|
+
// Only act on a LOADED document; a still-loading one is progressing (slow optimize).
|
|
1123
|
+
if (!iframeLoadedRef.current)
|
|
1124
|
+
return;
|
|
1125
|
+
// A heartbeating document is ALIVE and still coming up on a cold boot — reloading it only
|
|
1126
|
+
// restarts the load and thrashes Vite's cold optimize (making the fresh-project first load
|
|
1127
|
+
// WORSE). Only recover a genuinely STALE doc — no heartbeat for FREEZE_THRESHOLD_MS, i.e.
|
|
1128
|
+
// its bridge is dead (a Vite "server restarted" dropped it mid-load) — the exact case this
|
|
1129
|
+
// recovery exists for.
|
|
1130
|
+
if (Date.now() - lastHeartbeatRef.current < FREEZE_THRESHOLD_MS)
|
|
1131
|
+
return;
|
|
1132
|
+
const up = await isServerUp(urlRef.current);
|
|
1133
|
+
if (!up || iframeReadyRef.current || confirmedContentRef.current)
|
|
1134
|
+
return;
|
|
1135
|
+
loadRecoverCountRef.current += 1;
|
|
1136
|
+
setIframeSrc(withCacheBuster(urlRef.current));
|
|
1137
|
+
})();
|
|
1138
|
+
}, LOAD_RECOVER_AFTER_MS);
|
|
1139
|
+
return () => clearTimeout(timer);
|
|
1140
|
+
}, [iframeSrc, iframeReady, confirmedContent, previewGaveUp, iframeMountKey]);
|
|
1141
|
+
// --- Listen for postMessage from scaffold template ---
|
|
1142
|
+
// molecule:ready = #root got children (app rendered) → hide overlay
|
|
1143
|
+
// molecule:error = pre-render error OR crash → forward/show overlay
|
|
1144
|
+
// molecule:runtime-error = JS runtime error in the iframe → forward to chat
|
|
1145
|
+
// molecule:heartbeat = scaffold alive signal
|
|
1146
|
+
// molecule:blank = page rendered but appears empty
|
|
1147
|
+
// molecule:navigate = preview's client-side location changed → update URL bar
|
|
1148
|
+
useEffect(() => {
|
|
1149
|
+
// Debounce runtime errors — HMR triggers rapid error/recovery cycles
|
|
1150
|
+
let errorBatch = [];
|
|
1151
|
+
let debounceTimer = null;
|
|
1152
|
+
const MAX_ERRORS_PER_BATCH = 5;
|
|
1153
|
+
// Rate-limit ready/error to prevent rapid state oscillation
|
|
1154
|
+
let lastMsgTime = 0;
|
|
1155
|
+
let lastMsgType = '';
|
|
1156
|
+
let pendingMsg = null;
|
|
1157
|
+
const flushErrors = () => {
|
|
1158
|
+
if (errorBatch.length > 0 && onPreviewError) {
|
|
1159
|
+
onPreviewError(errorBatch);
|
|
1160
|
+
errorBatch = [];
|
|
1161
|
+
}
|
|
1162
|
+
debounceTimer = null;
|
|
1163
|
+
};
|
|
1164
|
+
const queueError = (err) => {
|
|
1165
|
+
// Drop a signature already forwarded within the window — the baked sender and the
|
|
1166
|
+
// centralized runtime bridge can each report the SAME uncaught error, and a
|
|
1167
|
+
// render-looping app re-throws it endlessly; either way the agent needs it once.
|
|
1168
|
+
const signature = `${err.message}|${err.source ?? ''}|${err.line ?? ''}|${err.column ?? ''}`;
|
|
1169
|
+
const now = Date.now();
|
|
1170
|
+
const ledger = recentErrorSigRef.current;
|
|
1171
|
+
const lastSeen = ledger.get(signature);
|
|
1172
|
+
if (lastSeen !== undefined && now - lastSeen < ERROR_DEDUP_WINDOW_MS)
|
|
1173
|
+
return;
|
|
1174
|
+
ledger.set(signature, now);
|
|
1175
|
+
// Bound the ledger: evict entries older than the window so it can't grow unbounded
|
|
1176
|
+
// over a long session (a steady stream of distinct errors would otherwise leak).
|
|
1177
|
+
for (const [sig, ts] of ledger) {
|
|
1178
|
+
if (now - ts >= ERROR_DEDUP_WINDOW_MS)
|
|
1179
|
+
ledger.delete(sig);
|
|
1180
|
+
}
|
|
1181
|
+
if (errorBatch.length < MAX_ERRORS_PER_BATCH) {
|
|
1182
|
+
errorBatch.push(err);
|
|
1183
|
+
}
|
|
1184
|
+
if (debounceTimer)
|
|
1185
|
+
clearTimeout(debounceTimer);
|
|
1186
|
+
debounceTimer = setTimeout(flushErrors, 2000);
|
|
1187
|
+
};
|
|
1188
|
+
const handler = (event) => {
|
|
1189
|
+
// Trust boundary: accept molecule:* messages ONLY from the preview iframe's OWN window.
|
|
1190
|
+
// We compare the SOURCE WINDOW IDENTITY (event.source === the iframe's contentWindow), NOT
|
|
1191
|
+
// a fragile origin STRING match. event.origin can legitimately fail to byte-equal
|
|
1192
|
+
// new URL(state.url).origin — Origin-Agent-Cluster isolation, a host:port vs 127.0.0.1 vs
|
|
1193
|
+
// IP-literal preview URL, the load's cache-buster, or a redirect-on-load all diverge the
|
|
1194
|
+
// strings — and an origin-only gate then silently DROPS the real handshake (the
|
|
1195
|
+
// molecule:ready that lifts the overlay) and every nav/error report. Window identity is
|
|
1196
|
+
// both more robust AND strictly more secure: no other window (a malicious sub-iframe the
|
|
1197
|
+
// preview embeds, another tab/opener) can forge the source reference, and it needs no
|
|
1198
|
+
// cross-origin read. The iframe is always mounted before it can post, so contentWindow is
|
|
1199
|
+
// set by the time any message arrives.
|
|
1200
|
+
const previewWindow = iframeRef.current?.contentWindow;
|
|
1201
|
+
if (!previewWindow || event.source !== previewWindow)
|
|
1202
|
+
return;
|
|
1203
|
+
// Event-driven re-post of the pending ui-command: any frame from the preview iframe
|
|
1204
|
+
// (ready, heartbeat, nav) proves its bridge is alive, so re-send an unanswered command
|
|
1205
|
+
// now. This is what delivers commands while the IDE tab is hidden — the 350ms retry
|
|
1206
|
+
// interval above is throttled there (to one tick per MINUTE under Chrome's intensive
|
|
1207
|
+
// throttling), but message events are not. The bridge dedups by id; harmless when the
|
|
1208
|
+
// command already arrived.
|
|
1209
|
+
const pendingUi = pendingUiPostRef.current;
|
|
1210
|
+
if (pendingUi &&
|
|
1211
|
+
event.data?.type !== 'molecule:ui-result' &&
|
|
1212
|
+
Date.now() <= pendingUi.deadline &&
|
|
1213
|
+
!uiResolvedRef.current.has(pendingUi.payload.id)) {
|
|
1214
|
+
previewWindow.postMessage(pendingUi.payload, previewTargetOrigin(iframeRef.current));
|
|
1215
|
+
}
|
|
1216
|
+
// A spec asked for a viewport. The e2e preview client posts this and then
|
|
1217
|
+
// polls its own innerWidth until the host honours it (up to 4s), so all
|
|
1218
|
+
// this has to do is resize the frame — there is no reply to send.
|
|
1219
|
+
//
|
|
1220
|
+
// The state and the iframe's use of it already existed; nothing ever set
|
|
1221
|
+
// it, so every `page.setViewportSize` was answered with the unchanged
|
|
1222
|
+
// size and the bond warned "the preview host kept its own size". That is
|
|
1223
|
+
// why a phone layout could not be verified from a build: three of the
|
|
1224
|
+
// seven first-contact failures in X0 R83 were phone/geometry facts the
|
|
1225
|
+
// executor had no way to observe.
|
|
1226
|
+
if (event.data?.type === 'molecule:viewport') {
|
|
1227
|
+
const width = Number(event.data.width);
|
|
1228
|
+
const height = Number(event.data.height);
|
|
1229
|
+
if (Number.isFinite(width) && width > 0 && Number.isFinite(height) && height > 0) {
|
|
1230
|
+
setRequestedSize({
|
|
1231
|
+
width: Math.min(Math.max(Math.round(width), MIN_REQUESTED_PX), MAX_REQUESTED_PX),
|
|
1232
|
+
height: Math.min(Math.max(Math.round(height), MIN_REQUESTED_PX), MAX_REQUESTED_PX),
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
else {
|
|
1236
|
+
// A zero/NaN size means "stop overriding" — hand the frame back to
|
|
1237
|
+
// the device selector rather than pinning it at a nonsense width.
|
|
1238
|
+
setRequestedSize(null);
|
|
1239
|
+
}
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1242
|
+
if (event.data?.type === 'molecule:ready') {
|
|
1243
|
+
const now = Date.now();
|
|
1244
|
+
// Track transitions for cycle detection
|
|
1245
|
+
const times = transitionTimesRef.current;
|
|
1246
|
+
times.push(now);
|
|
1247
|
+
// Trim old entries
|
|
1248
|
+
while (times.length > 0 && now - times[0] > TRANSITION_WINDOW_MS)
|
|
1249
|
+
times.shift();
|
|
1250
|
+
if (times.length >= MAX_TRANSITIONS && !suppressedRef.current) {
|
|
1251
|
+
suppressedRef.current = true;
|
|
1252
|
+
console.warn('[PreviewPanel] Rapid ready/error cycle detected (%d transitions in %dms) — suppressing further toggles. This indicates a render loop in the preview iframe.', times.length, TRANSITION_WINDOW_MS);
|
|
1253
|
+
// Auto-recover after the storm passes
|
|
1254
|
+
setTimeout(() => {
|
|
1255
|
+
suppressedRef.current = false;
|
|
1256
|
+
transitionTimesRef.current = [];
|
|
1257
|
+
}, TRANSITION_WINDOW_MS);
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
if (suppressedRef.current)
|
|
1261
|
+
return;
|
|
1262
|
+
// Rate-limit: ignore duplicate ready within MSG_RATE_LIMIT_MS
|
|
1263
|
+
if (lastMsgType === 'molecule:ready' && now - lastMsgTime < MSG_RATE_LIMIT_MS)
|
|
1264
|
+
return;
|
|
1265
|
+
lastMsgTime = now;
|
|
1266
|
+
lastMsgType = 'molecule:ready';
|
|
1267
|
+
if (pendingMsg)
|
|
1268
|
+
clearTimeout(pendingMsg);
|
|
1269
|
+
clearPoll();
|
|
1270
|
+
setEverLoaded(true);
|
|
1271
|
+
reveal();
|
|
1272
|
+
setStuckRetryCount(0);
|
|
1273
|
+
// The app CONFIRMED it rendered visible content — the strong signal that clears the
|
|
1274
|
+
// status overlay (vs. the onLoad grace which only reveals the iframe). Also tears down
|
|
1275
|
+
// any post-build "blank" notice: a real render means it isn't blank anymore.
|
|
1276
|
+
setConfirmedContent(true);
|
|
1277
|
+
// This load target has now rendered at least once — leave cold-boot patience mode. A
|
|
1278
|
+
// subsequent reload that goes blank is a real regression handled by the short window.
|
|
1279
|
+
hasEverRenderedRef.current = true;
|
|
1280
|
+
lastReadyAtRef.current = now;
|
|
1281
|
+
setBlankPostBuild(false);
|
|
1282
|
+
// Handshake arrived (the fast path) — cancel any pending onLoad grace
|
|
1283
|
+
// fallback and clear the crash marker so a future onLoad isn't suppressed.
|
|
1284
|
+
if (onLoadGraceRef.current) {
|
|
1285
|
+
clearTimeout(onLoadGraceRef.current);
|
|
1286
|
+
onLoadGraceRef.current = null;
|
|
1287
|
+
}
|
|
1288
|
+
lastCrashAtRef.current = 0;
|
|
1289
|
+
}
|
|
1290
|
+
else if (event.data?.type === 'molecule:error' && event.data.crash) {
|
|
1291
|
+
const now = Date.now();
|
|
1292
|
+
// Track transitions
|
|
1293
|
+
const times = transitionTimesRef.current;
|
|
1294
|
+
times.push(now);
|
|
1295
|
+
while (times.length > 0 && now - times[0] > TRANSITION_WINDOW_MS)
|
|
1296
|
+
times.shift();
|
|
1297
|
+
if (times.length >= MAX_TRANSITIONS && !suppressedRef.current) {
|
|
1298
|
+
suppressedRef.current = true;
|
|
1299
|
+
console.warn('[PreviewPanel] Rapid ready/error cycle detected (%d transitions in %dms) — suppressing further toggles.', times.length, TRANSITION_WINDOW_MS);
|
|
1300
|
+
setTimeout(() => {
|
|
1301
|
+
suppressedRef.current = false;
|
|
1302
|
+
transitionTimesRef.current = [];
|
|
1303
|
+
}, TRANSITION_WINDOW_MS);
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
if (suppressedRef.current)
|
|
1307
|
+
return;
|
|
1308
|
+
// Rate-limit: debounce crash to let HMR settle
|
|
1309
|
+
if (lastMsgType === 'molecule:error' && now - lastMsgTime < MSG_RATE_LIMIT_MS)
|
|
1310
|
+
return;
|
|
1311
|
+
lastMsgTime = now;
|
|
1312
|
+
lastMsgType = 'molecule:error';
|
|
1313
|
+
if (pendingMsg)
|
|
1314
|
+
clearTimeout(pendingMsg);
|
|
1315
|
+
// Debounce crash — if a ready arrives within 300ms, skip the crash entirely
|
|
1316
|
+
pendingMsg = setTimeout(() => {
|
|
1317
|
+
pendingMsg = null;
|
|
1318
|
+
setIframeReady(false);
|
|
1319
|
+
setFadingOut(false);
|
|
1320
|
+
// The app crashed — it is no longer showing confirmed content, so the status
|
|
1321
|
+
// overlay must come back.
|
|
1322
|
+
setConfirmedContent(false);
|
|
1323
|
+
// Mark the crash so the onLoad grace fallback won't mask it as a good
|
|
1324
|
+
// load (a crash within the grace window suppresses the fallback).
|
|
1325
|
+
lastCrashAtRef.current = Date.now();
|
|
1326
|
+
}, MSG_RATE_LIMIT_MS);
|
|
1327
|
+
}
|
|
1328
|
+
else if (event.data?.type === 'molecule:error' && !event.data.crash && event.data.message) {
|
|
1329
|
+
// Pre-render error — app failed to mount (e.g., module export missing, import error).
|
|
1330
|
+
// Forward to the agent so it can fix the issue.
|
|
1331
|
+
queueError({
|
|
1332
|
+
message: String(event.data.message),
|
|
1333
|
+
source: event.data.source ? String(event.data.source) : 'pre-render',
|
|
1334
|
+
line: event.data.line ?? undefined,
|
|
1335
|
+
column: event.data.column ?? undefined,
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
else if (event.data?.type === 'molecule:runtime-error') {
|
|
1339
|
+
queueError({
|
|
1340
|
+
message: String(event.data.message ?? 'Unknown error'),
|
|
1341
|
+
source: event.data.source ?? undefined,
|
|
1342
|
+
line: event.data.line ?? undefined,
|
|
1343
|
+
column: event.data.column ?? undefined,
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
else if (event.data?.type === 'molecule:viewport') {
|
|
1347
|
+
// The previewed page asked for a viewport (an e2e spec's page.setViewportSize, relayed
|
|
1348
|
+
// by the preview e2e client). Size the frame to it — the same mechanism as a device
|
|
1349
|
+
// preset — and confirm; `width: null` returns to the selected device frame.
|
|
1350
|
+
const width = Number(event.data.width);
|
|
1351
|
+
const height = Number(event.data.height);
|
|
1352
|
+
if (Number.isFinite(width) && width > 0) {
|
|
1353
|
+
const next = {
|
|
1354
|
+
width: Math.round(width),
|
|
1355
|
+
height: Number.isFinite(height) && height > 0 ? Math.round(height) : 844,
|
|
1356
|
+
};
|
|
1357
|
+
setRequestedSize(next);
|
|
1358
|
+
previewWindow.postMessage({ type: 'molecule:viewport-result', id: event.data.id, ...next }, previewTargetOrigin(iframeRef.current));
|
|
1359
|
+
}
|
|
1360
|
+
else {
|
|
1361
|
+
setRequestedSize(null);
|
|
1362
|
+
previewWindow.postMessage({ type: 'molecule:viewport-result', id: event.data.id, width: null, height: null }, previewTargetOrigin(iframeRef.current));
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
else if (event.data?.type === 'molecule:heartbeat') {
|
|
1366
|
+
lastHeartbeatRef.current = Date.now();
|
|
1367
|
+
}
|
|
1368
|
+
else if (event.data?.type === 'molecule:ui-result') {
|
|
1369
|
+
// AI-driven preview interaction result — forward to the host, keyed by the command `id`
|
|
1370
|
+
// it round-trips on (see the uiCommand effect / onUiResult). The panel only relays it.
|
|
1371
|
+
if (typeof event.data.id === 'string') {
|
|
1372
|
+
// Mark resolved so the uiCommand retry loop stops re-sending this command.
|
|
1373
|
+
uiResolvedRef.current.add(event.data.id);
|
|
1374
|
+
if (pendingUiPostRef.current?.payload.id === event.data.id) {
|
|
1375
|
+
pendingUiPostRef.current = null;
|
|
1376
|
+
}
|
|
1377
|
+
if (onUiResult)
|
|
1378
|
+
onUiResult(event.data.id, event.data);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
else if (event.data?.type === 'molecule:navigate') {
|
|
1382
|
+
// The preview reported a client-side navigation (see the scaffold-injected
|
|
1383
|
+
// sender). recordNavigation validates the URL and updates the URL bar
|
|
1384
|
+
// (state.currentUrl) without reloading the iframe. `isReplace` (set by the
|
|
1385
|
+
// sender for replaceState) preserves the Forward stack on a redirect-on-load
|
|
1386
|
+
// instead of truncating it; a missing/garbage value coerces to false (push).
|
|
1387
|
+
if (typeof event.data.url === 'string') {
|
|
1388
|
+
// A click intent for a raw document (feed.xml, provenance.json): remember it so the
|
|
1389
|
+
// load that follows is taken for what it is. Any other intent clears a stale one.
|
|
1390
|
+
if (event.data.isIntent === true) {
|
|
1391
|
+
rawDocIntentRef.current = isRawDocumentUrl(event.data.url)
|
|
1392
|
+
? { url: event.data.url, at: Date.now() }
|
|
1393
|
+
: null;
|
|
1394
|
+
}
|
|
1395
|
+
recordNavigation(event.data.url, event.data.isReplace === true);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
else if (event.data?.type === 'molecule:blank') {
|
|
1399
|
+
// Page rendered but appears blank — re-cover it. Reveal is gated on `iframeReady`, so
|
|
1400
|
+
// dropping `confirmedContent` alone no longer re-covers; lower `iframeReady` too. The
|
|
1401
|
+
// onLoad grace already fired and won't re-arm, so the overlay stays (showing the
|
|
1402
|
+
// last-good frame) until a real `molecule:ready` re-reveals a non-blank render.
|
|
1403
|
+
setConfirmedContent(false);
|
|
1404
|
+
setIframeReady(false);
|
|
1405
|
+
setFadingOut(false);
|
|
1406
|
+
// Notify the agent
|
|
1407
|
+
if (onPreviewError) {
|
|
1408
|
+
onPreviewError([
|
|
1409
|
+
{
|
|
1410
|
+
message: String(event.data.message ?? 'Page appears blank — rendered but no visible content'),
|
|
1411
|
+
source: 'molecule:blank',
|
|
1412
|
+
},
|
|
1413
|
+
]);
|
|
1414
|
+
}
|
|
1415
|
+
// Marking content unconfirmed (above) already raises the overlay, and the blurred
|
|
1416
|
+
// last-good frame stands in behind it (it renders whenever a frame was captured) — so
|
|
1417
|
+
// a blanked app shows the last working UI instead of an empty white iframe.
|
|
1418
|
+
}
|
|
1419
|
+
else if (event.data?.type === 'molecule:snapshot') {
|
|
1420
|
+
// The sandbox app self-rasterized a stable render and posted it. Validate
|
|
1421
|
+
// defensively (postMessage trust boundary): a data:image/ URL within a sane
|
|
1422
|
+
// size cap. Stored as the blurred last-good placeholder shown during a
|
|
1423
|
+
// rebuild/blank window.
|
|
1424
|
+
const dataUrl = event.data.dataUrl;
|
|
1425
|
+
if (typeof dataUrl === 'string' &&
|
|
1426
|
+
dataUrl.startsWith('data:image/') &&
|
|
1427
|
+
dataUrl.length <= MAX_SNAPSHOT_DATA_URL_LENGTH) {
|
|
1428
|
+
setLastGoodFrame(dataUrl);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
};
|
|
1432
|
+
window.addEventListener('message', handler);
|
|
1433
|
+
return () => {
|
|
1434
|
+
window.removeEventListener('message', handler);
|
|
1435
|
+
if (debounceTimer)
|
|
1436
|
+
clearTimeout(debounceTimer);
|
|
1437
|
+
if (pendingMsg)
|
|
1438
|
+
clearTimeout(pendingMsg);
|
|
1439
|
+
};
|
|
1440
|
+
}, [clearPoll, onPreviewError, recordNavigation, onUiResult, reveal]);
|
|
1441
|
+
// --- iframe onLoad: grace fallback when molecule:ready never arrives ---
|
|
1442
|
+
// The document finished loading. `molecule:ready` is the fast path that clears
|
|
1443
|
+
// the overlay immediately; but if that handshake is dropped/suppressed/starved,
|
|
1444
|
+
// a perfectly good app would otherwise stay hidden behind the overlay forever
|
|
1445
|
+
// (the single point of failure that made the preview get permanently stuck). So
|
|
1446
|
+
// after a short grace, if no ready arrived AND no crash just fired, treat the
|
|
1447
|
+
// load as good and clear the overlay anyway.
|
|
1448
|
+
const handleIframeLoad = useCallback(() => {
|
|
1449
|
+
if (!urlRef.current)
|
|
1450
|
+
return;
|
|
1451
|
+
iframeLoadedRef.current = true;
|
|
1452
|
+
lastLoadAtRef.current = Date.now();
|
|
1453
|
+
// A pending ui-command (navigate) is answered by the document that loaded AT OR
|
|
1454
|
+
// AFTER its minLoadedAt; the load event is the one UNTHROTTLED signal that this
|
|
1455
|
+
// document now exists, so re-post here rather than waiting for its bridge's next
|
|
1456
|
+
// frame — in a hidden tab those frames are timer-scheduled and Chrome throttles
|
|
1457
|
+
// them to ~one per minute, which is how a navigate could outlive its 45s window
|
|
1458
|
+
// with the bridge alive the whole time (X0 rehearsal 28, G46).
|
|
1459
|
+
const pending = pendingUiPostRef.current;
|
|
1460
|
+
if (pending && Date.now() <= pending.deadline) {
|
|
1461
|
+
iframeRef.current?.contentWindow?.postMessage(pending.payload, previewTargetOrigin(iframeRef.current));
|
|
1462
|
+
}
|
|
1463
|
+
// The document that just loaded is the raw file a link click announced (feed.xml,
|
|
1464
|
+
// provenance.json, llms.txt): the browser shows it with its own viewer and no bridge will
|
|
1465
|
+
// ever post `molecule:ready` for it. It IS the content — reveal it and never accuse it of
|
|
1466
|
+
// being a blank app (the notice used to land on every feed and JSON link in a static site).
|
|
1467
|
+
const rawIntent = rawDocIntentRef.current;
|
|
1468
|
+
if (rawIntent && Date.now() - rawIntent.at < RAW_DOC_INTENT_MS) {
|
|
1469
|
+
rawDocIntentRef.current = null;
|
|
1470
|
+
if (onLoadGraceRef.current) {
|
|
1471
|
+
clearTimeout(onLoadGraceRef.current);
|
|
1472
|
+
onLoadGraceRef.current = null;
|
|
1473
|
+
}
|
|
1474
|
+
lastReadyAtRef.current = Date.now();
|
|
1475
|
+
setEverLoaded(true);
|
|
1476
|
+
setConfirmedContent(true);
|
|
1477
|
+
// Ends a fade left from an earlier reveal; reveal() starts one only if the iframe was hidden.
|
|
1478
|
+
setFadingOut(false);
|
|
1479
|
+
reveal();
|
|
1480
|
+
setBlankPostBuild(false);
|
|
1481
|
+
setStuckRetryCount(0);
|
|
1482
|
+
setDocLoadedTick((k) => k + 1);
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
// Re-trigger the cold-boot evaluator effect: during a first cold boot the reveal no longer
|
|
1486
|
+
// flips `iframeReady` on the grace, so this document-load tick is the effect's trigger.
|
|
1487
|
+
setDocLoadedTick((k) => k + 1);
|
|
1488
|
+
// A NEW document is now displayed — the initial load OR a Vite full-reload that an edit
|
|
1489
|
+
// (Synthase's or the user's) triggered, which reloads the SAME iframe src without remounting
|
|
1490
|
+
// it or changing state.url, so no other reset path runs. If this load did NOT just confirm a
|
|
1491
|
+
// render (no molecule:ready landed in the moment before — i.e. the reloaded app rendered
|
|
1492
|
+
// nothing), drop confirmedContent so the overlay re-covers the now-blank iframe instead of
|
|
1493
|
+
// leaving the stale "it rendered" state masking a white screen. A working full-reload mounts
|
|
1494
|
+
// React (→ molecule:ready) just before the load event, so its ready is fresh and
|
|
1495
|
+
// confirmedContent is KEPT (no flash); a slow/async render re-confirms via the ready that
|
|
1496
|
+
// follows (the bridge re-sends ready ~every 4s while content is visible).
|
|
1497
|
+
if (Date.now() - lastReadyAtRef.current > READY_FRESH_MS) {
|
|
1498
|
+
setConfirmedContent(false);
|
|
1499
|
+
// Re-cover the freshly (re)loaded document until ITS OWN onLoad grace re-reveals it (or a
|
|
1500
|
+
// fresh molecule:ready confirms sooner). Reveal is gated on `iframeReady`, so a full-reload
|
|
1501
|
+
// that an edit triggers must lower it — otherwise the previous load's reveal leaks through
|
|
1502
|
+
// and flashes the new, possibly-blank document uncovered. The grace timer armed just below
|
|
1503
|
+
// re-reveals it.
|
|
1504
|
+
setIframeReady(false);
|
|
1505
|
+
// Bring the overlay back SOLID over the blank reload — not mid-fade from the previous
|
|
1506
|
+
// app's confirmation (whose fade-out may still be in flight).
|
|
1507
|
+
setFadingOut(false);
|
|
1508
|
+
}
|
|
1509
|
+
if (onLoadGraceRef.current)
|
|
1510
|
+
clearTimeout(onLoadGraceRef.current);
|
|
1511
|
+
onLoadGraceRef.current = setTimeout(() => {
|
|
1512
|
+
onLoadGraceRef.current = null;
|
|
1513
|
+
if (iframeReadyRef.current)
|
|
1514
|
+
return;
|
|
1515
|
+
// A crash within the grace window means the load is NOT good — don't mask it.
|
|
1516
|
+
if (Date.now() - lastCrashAtRef.current < ONLOAD_GRACE_MS)
|
|
1517
|
+
return;
|
|
1518
|
+
// FIRST cold boot (this target has NEVER rendered): do NOT reveal on the grace. The
|
|
1519
|
+
// scaffold's inline bridge posts `molecule:ready` the instant #root mounts (reliable), so
|
|
1520
|
+
// we keep the honest "Starting your app…" overlay up until that REAL signal instead of
|
|
1521
|
+
// flashing a white, still-compiling iframe and then falsely accusing it of being blank —
|
|
1522
|
+
// the fresh-project "won't load until I open a new tab" bug. The grace reveal is purely a
|
|
1523
|
+
// flash-avoidance shortcut for RELOADS of an app that already rendered once; a genuinely
|
|
1524
|
+
// never-mounting app is surfaced honestly by the cold-boot evaluator (dead / 60s ceiling).
|
|
1525
|
+
//
|
|
1526
|
+
// A fresh wake is the SAME cold-boot regime even when the app already rendered pre-wake
|
|
1527
|
+
// (hasEverRendered stays true): the woken Vite mounts once then full-reloads mid-optimize,
|
|
1528
|
+
// and revealing that blank reload on the grace would flash a bare white iframe instead of
|
|
1529
|
+
// the honest "Starting…" spinner. Keep the overlay up until a REAL molecule:ready (which a
|
|
1530
|
+
// healthy wake posts within seconds); only that reveals during the wake window.
|
|
1531
|
+
if (!hasEverRenderedRef.current || inWakeWindow())
|
|
1532
|
+
return;
|
|
1533
|
+
setEverLoaded(true);
|
|
1534
|
+
reveal();
|
|
1535
|
+
setStuckRetryCount(0);
|
|
1536
|
+
}, ONLOAD_GRACE_MS);
|
|
1537
|
+
}, [inWakeWindow, reveal]);
|
|
1538
|
+
// --- Health check: periodically verify server is still up ---
|
|
1539
|
+
useEffect(() => {
|
|
1540
|
+
// Only run health checks after overlay is fully gone
|
|
1541
|
+
if (!iframeReady || fadingOut || !state.url)
|
|
1542
|
+
return;
|
|
1543
|
+
const url = state.url;
|
|
1544
|
+
// Cancellation flag — prevents orphaned closures from running after this
|
|
1545
|
+
// effect cleans up.
|
|
1546
|
+
let cancelled = false;
|
|
1547
|
+
let timer = null;
|
|
1548
|
+
// Consecutive misses. Self-scheduled (next probe only after this one
|
|
1549
|
+
// settles) so a slow edge never stacks probes, and a single miss is only a
|
|
1550
|
+
// strike — HEALTH_DOWN_CONFIRM in a row is the down verdict.
|
|
1551
|
+
let misses = 0;
|
|
1552
|
+
const check = async () => {
|
|
1553
|
+
if (cancelled)
|
|
1554
|
+
return;
|
|
1555
|
+
const up = await isServerUp(url);
|
|
1556
|
+
if (cancelled || urlRef.current !== url)
|
|
1557
|
+
return;
|
|
1558
|
+
// A document that is still heartbeating is ALIVE whatever the probe says. A
|
|
1559
|
+
// sandbox busy with a build (vite build, a prerender, a test run) answers the
|
|
1560
|
+
// status probe late — past PROBE_TIMEOUT_MS — while the page in the frame runs
|
|
1561
|
+
// on untouched; two such misses used to be the down verdict, and the reload
|
|
1562
|
+
// when the probe came back tore the app down and remounted it: "[vite]
|
|
1563
|
+
// connecting… connected." every 3–15 seconds for as long as the build ran, the
|
|
1564
|
+
// stuck-preview detector firing on the churn (X0 R78/R79, 2026-09-14). A server
|
|
1565
|
+
// that really went away drops the document's heartbeat (and its Vite client
|
|
1566
|
+
// reloads it itself once the server is back), so the down verdict is gated on
|
|
1567
|
+
// the heartbeat the freeze watchdog already trusts.
|
|
1568
|
+
const documentAlive = Date.now() - lastHeartbeatRef.current < FREEZE_THRESHOLD_MS;
|
|
1569
|
+
if (up || documentAlive) {
|
|
1570
|
+
misses = 0;
|
|
1571
|
+
timer = setTimeout(() => void check(), HEALTH_POLL_MS);
|
|
1572
|
+
return;
|
|
1573
|
+
}
|
|
1574
|
+
misses += 1;
|
|
1575
|
+
if (misses < HEALTH_DOWN_CONFIRM) {
|
|
1576
|
+
timer = setTimeout(() => void check(), HEALTH_POLL_MS);
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
// Server went down — show overlay, poll, reload when back
|
|
1580
|
+
setIframeReady(false);
|
|
1581
|
+
setFadingOut(false);
|
|
1582
|
+
let interval = POLL_INITIAL_MS;
|
|
1583
|
+
const poll = async () => {
|
|
1584
|
+
if (cancelled || urlRef.current !== url)
|
|
1585
|
+
return;
|
|
1586
|
+
const back = await isServerUp(url);
|
|
1587
|
+
if (cancelled || urlRef.current !== url)
|
|
1588
|
+
return;
|
|
1589
|
+
if (back) {
|
|
1590
|
+
// Force-reload iframe with cache buster
|
|
1591
|
+
setIframeSrc(withCacheBuster(url));
|
|
1592
|
+
}
|
|
1593
|
+
else {
|
|
1594
|
+
timer = setTimeout(poll, interval);
|
|
1595
|
+
interval = Math.min(interval * POLL_BACKOFF_FACTOR, POLL_MAX_MS);
|
|
1596
|
+
}
|
|
1597
|
+
};
|
|
1598
|
+
void poll();
|
|
1599
|
+
};
|
|
1600
|
+
timer = setTimeout(() => void check(), HEALTH_POLL_MS);
|
|
1601
|
+
return () => {
|
|
1602
|
+
cancelled = true;
|
|
1603
|
+
if (timer)
|
|
1604
|
+
clearTimeout(timer);
|
|
1605
|
+
};
|
|
1606
|
+
}, [iframeReady, fadingOut, state.url]);
|
|
1607
|
+
// --- Freeze watchdog ---
|
|
1608
|
+
// The scaffold's main thread posts `molecule:heartbeat` every ~3s. If that thread
|
|
1609
|
+
// locks up (an infinite loop or runaway render in the in-progress app), the beats
|
|
1610
|
+
// stop. Origin-Agent-Cluster isolation keeps that freeze off the IDE's thread, so
|
|
1611
|
+
// the IDE can notice the silence and offer a reload — a frozen frame can't recover
|
|
1612
|
+
// on its own. Auto-clears if heartbeats resume (transient jank, not a hard lock).
|
|
1613
|
+
//
|
|
1614
|
+
// VISIBILITY-AWARE, deliberately: in a hidden tab the browser throttles BOTH
|
|
1615
|
+
// sides — the iframe's heartbeats stop being delivered AND this interval only
|
|
1616
|
+
// wakes about once a minute — so every throttle wake used to read as an
|
|
1617
|
+
// 18–58s "freeze": the banner popped and the frozen report (with its alert
|
|
1618
|
+
// tone) fired once per minute for as long as the tab stayed backgrounded
|
|
1619
|
+
// (observed live 2026-08-29; forensics showed heap flat + thread idle, i.e.
|
|
1620
|
+
// pure throttling, no real freeze). A hidden tab renders nothing, so there is
|
|
1621
|
+
// nothing to accuse: skip checks while hidden and re-baseline on return to
|
|
1622
|
+
// the foreground so the hidden gap can never count against the app.
|
|
1623
|
+
useEffect(() => {
|
|
1624
|
+
if (!iframeReady || fadingOut || !state.url) {
|
|
1625
|
+
setPreviewFrozen(false);
|
|
1626
|
+
return;
|
|
1627
|
+
}
|
|
1628
|
+
// Baseline so a stale value from a prior load can't trip us immediately.
|
|
1629
|
+
lastHeartbeatRef.current = Date.now();
|
|
1630
|
+
const timer = setInterval(() => {
|
|
1631
|
+
if (document.visibilityState === 'hidden')
|
|
1632
|
+
return;
|
|
1633
|
+
// "Frozen" means a document that RENDERED and then stopped beating. A document
|
|
1634
|
+
// that was just (re)loaded — a navigation, a reload, an HMR full reload — has
|
|
1635
|
+
// not beaten yet, and on a sandbox busy with a build its first beat can take
|
|
1636
|
+
// longer than the freeze window; that gap is a load in progress, not a blocked
|
|
1637
|
+
// thread. Only a gap AFTER the current document's own beat counts (X0 R78/R79,
|
|
1638
|
+
// 2026-09-14: the frozen report fired within two minutes of a handoff, while the
|
|
1639
|
+
// harness's post-turn verification was loading the sandbox, and cost a turn).
|
|
1640
|
+
const beatSinceLoad = lastHeartbeatRef.current >= lastLoadAtRef.current;
|
|
1641
|
+
setPreviewFrozen(beatSinceLoad && Date.now() - lastHeartbeatRef.current > FREEZE_THRESHOLD_MS);
|
|
1642
|
+
}, FREEZE_CHECK_INTERVAL_MS);
|
|
1643
|
+
const onVisibility = () => {
|
|
1644
|
+
if (document.visibilityState !== 'visible')
|
|
1645
|
+
return;
|
|
1646
|
+
// Fresh grace window: heartbeats resume with the foreground; the gap that
|
|
1647
|
+
// accumulated while hidden was throttling, not the app.
|
|
1648
|
+
lastHeartbeatRef.current = Date.now();
|
|
1649
|
+
setPreviewFrozen(false);
|
|
1650
|
+
};
|
|
1651
|
+
document.addEventListener('visibilitychange', onVisibility);
|
|
1652
|
+
return () => {
|
|
1653
|
+
clearInterval(timer);
|
|
1654
|
+
document.removeEventListener('visibilitychange', onVisibility);
|
|
1655
|
+
};
|
|
1656
|
+
}, [iframeReady, fadingOut, state.url]);
|
|
1657
|
+
// --- Freeze → host report ---
|
|
1658
|
+
// A frozen preview is the worst case the iframe CANNOT self-report (its thread is
|
|
1659
|
+
// locked, so no molecule:error/runtime-error can ever be posted) — the banner alone
|
|
1660
|
+
// gives the user a reload but never tells the agent. Bridge that gap: on the
|
|
1661
|
+
// false→true freeze transition, hand the host a structured `frozen` report (with the
|
|
1662
|
+
// route) so it can, gated on the autofix setting, ask the agent to find and fix the
|
|
1663
|
+
// infinite loop / runaway render. Fires once per episode; re-arms when beats resume.
|
|
1664
|
+
useEffect(() => {
|
|
1665
|
+
if (previewFrozen && !frozenReportedRef.current) {
|
|
1666
|
+
frozenReportedRef.current = true;
|
|
1667
|
+
onPreviewStuck?.({ reason: 'frozen', url: currentLocationRef.current });
|
|
1668
|
+
}
|
|
1669
|
+
else if (!previewFrozen) {
|
|
1670
|
+
frozenReportedRef.current = false;
|
|
1671
|
+
}
|
|
1672
|
+
}, [previewFrozen, onPreviewStuck]);
|
|
1673
|
+
// --- Render verdict → host (→ server) ---
|
|
1674
|
+
// Collapse the panel's internal flags into the single render verdict the server needs:
|
|
1675
|
+
// did the app actually draw content, or is it blank/frozen/still loading? The host
|
|
1676
|
+
// forwards it so Synthase's post-loop verification can confirm a REAL render (not just
|
|
1677
|
+
// that the bundle compiled + served). Emit only on change, with the live route.
|
|
1678
|
+
const renderState = previewFrozen
|
|
1679
|
+
? 'frozen'
|
|
1680
|
+
: previewGaveUp || blankPostBuild
|
|
1681
|
+
? 'blank'
|
|
1682
|
+
: confirmedContent
|
|
1683
|
+
? 'rendered'
|
|
1684
|
+
: 'loading';
|
|
1685
|
+
const lastRenderStateRef = useRef(null);
|
|
1686
|
+
useEffect(() => {
|
|
1687
|
+
if (!state.url)
|
|
1688
|
+
return;
|
|
1689
|
+
if (lastRenderStateRef.current === renderState)
|
|
1690
|
+
return;
|
|
1691
|
+
lastRenderStateRef.current = renderState;
|
|
1692
|
+
onRenderState?.(renderState, currentLocationRef.current);
|
|
1693
|
+
}, [renderState, state.url, onRenderState]);
|
|
1694
|
+
// --- "Preview is in trouble" detection (signal-driven, NOT a naive timer) ---
|
|
1695
|
+
// Decides whether to swap the honest "Starting/Building…" status for the ACTIONABLE
|
|
1696
|
+
// "preview is blank — reload / open in new tab" notice. Driven by the scaffold bridge's OWN
|
|
1697
|
+
// signals — `molecule:ready` (rendered), `molecule:heartbeat` (alive) — instead of the old
|
|
1698
|
+
// "loaded + 2.5s + no ready ⇒ blank" guess, which FALSE-fired over a fresh project whose cold
|
|
1699
|
+
// Vite server was still pre-bundling/compiling the just-written app (the app WAS coming up and
|
|
1700
|
+
// would render seconds later). The regimes:
|
|
1701
|
+
// • confirmed / actively building / mid-fade / no document yet → never a problem.
|
|
1702
|
+
// • already rendered once, then reloaded blank (`hasEverRendered`) → real regression, surface
|
|
1703
|
+
// after the short BLANK_CONFIRM_MS.
|
|
1704
|
+
// • never rendered yet AND not alive (no heartbeat for FREEZE_THRESHOLD_MS after a settle) →
|
|
1705
|
+
// the inline bridge never ran ⇒ broken/error page ⇒ surface after BLANK_DEAD_MS.
|
|
1706
|
+
// • never rendered yet BUT alive (heartbeating) → a cold boot in progress → keep the honest
|
|
1707
|
+
// "Starting…" overlay; only surface after the generous COLD_BOOT_PATIENCE_MS ceiling
|
|
1708
|
+
// (alive the whole time yet never mounted ⇒ genuinely stuck).
|
|
1709
|
+
// Re-evaluated on an interval because liveness + elapsed-since-load change over time. An
|
|
1710
|
+
// explicit `molecule:blank` also raises the notice directly via its handler (setBlankPostBuild).
|
|
1711
|
+
useEffect(() => {
|
|
1712
|
+
if (!state.url || !iframeLoadedRef.current || confirmedContent || isBuilding || fadingOut) {
|
|
1713
|
+
setBlankPostBuild(false);
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
const evaluate = () => {
|
|
1717
|
+
if (confirmedContentRef.current || isBuildingRef.current) {
|
|
1718
|
+
setBlankPostBuild(false);
|
|
1719
|
+
return true;
|
|
1720
|
+
}
|
|
1721
|
+
const now = Date.now();
|
|
1722
|
+
const sinceLoad = now - (lastLoadAtRef.current || now);
|
|
1723
|
+
const aliveRecently = now - lastHeartbeatRef.current < FREEZE_THRESHOLD_MS;
|
|
1724
|
+
// Right after a wake, NEITHER fast accusation window may fire — only the generous
|
|
1725
|
+
// never-rendered ceiling. A wake relaunches the dev server, and cold Vite routinely
|
|
1726
|
+
// mounts the app once (→ molecule:ready, so hasEverRendered flips true) and THEN does a
|
|
1727
|
+
// full HMR reload while it finishes pre-bundling deps; that reload renders nothing for a
|
|
1728
|
+
// beat and would trip the already-rendered BLANK_CONFIRM_MS path. It can equally land on
|
|
1729
|
+
// a transient bridge-less error page the restarting proxy serves (the never-rendered
|
|
1730
|
+
// BLANK_DEAD_MS path). Both are EXPECTED during a restart, so the wake window overrides
|
|
1731
|
+
// both — matching the intent: accuse only when we're certain nothing ever rendered
|
|
1732
|
+
// (COLD_BOOT_PATIENCE_MS elapsed while alive-but-unmounted). The stale-document
|
|
1733
|
+
// auto-reloads still recover a genuinely dead doc in the meantime.
|
|
1734
|
+
// Inside the wake window: NEVER accuse. The old in-window ceiling used
|
|
1735
|
+
// `sinceLoad >= COLD_BOOT_PATIENCE_MS`, but on a wake `lastLoadAt` is the
|
|
1736
|
+
// PRE-HIBERNATION load — minutes-to-hours old — so the "generous ceiling"
|
|
1737
|
+
// tripped the instant the sleeping screen lifted and only cleared when the
|
|
1738
|
+
// wake reload reset the anchor (the observed blank-notice flash over a
|
|
1739
|
+
// 13-second relaunch). The window itself (WAKE_PATIENCE_MS) is shorter
|
|
1740
|
+
// than the ceiling anyway, so an in-window `sinceLoad` accusation could
|
|
1741
|
+
// ONLY ever fire off that stale anchor; a wake that genuinely never comes
|
|
1742
|
+
// up is accused by the normal branches the moment the window expires.
|
|
1743
|
+
const introuble = inWakeWindow()
|
|
1744
|
+
? false
|
|
1745
|
+
: hasEverRenderedRef.current
|
|
1746
|
+
? sinceLoad >= BLANK_CONFIRM_MS
|
|
1747
|
+
: (!aliveRecently && sinceLoad >= BLANK_DEAD_MS) || sinceLoad >= COLD_BOOT_PATIENCE_MS;
|
|
1748
|
+
setBlankPostBuild(introuble);
|
|
1749
|
+
return introuble;
|
|
1750
|
+
};
|
|
1751
|
+
if (evaluate())
|
|
1752
|
+
return;
|
|
1753
|
+
const id = setInterval(() => {
|
|
1754
|
+
if (evaluate())
|
|
1755
|
+
clearInterval(id);
|
|
1756
|
+
}, 500);
|
|
1757
|
+
return () => clearInterval(id);
|
|
1758
|
+
// docLoadedTick re-arms this when a fresh document loads (iframeReady no longer flips on the
|
|
1759
|
+
// cold-boot grace, so it can't be the trigger). iframeReady is still a dep so a real reveal
|
|
1760
|
+
// re-evaluates (and clears) immediately.
|
|
1761
|
+
}, [state.url, docLoadedTick, iframeReady, confirmedContent, isBuilding, fadingOut, inWakeWindow]);
|
|
1762
|
+
// --- Auto-reload when AI edits files — ONLY while the preview is broken ---
|
|
1763
|
+
// A healthy preview needs nothing from us: Vite HMR applies every edit live,
|
|
1764
|
+
// and Vite itself broadcasts a full reload when a change can't hot-apply. The
|
|
1765
|
+
// old "safety net" (force-reload 3s after EVERY edit even when healthy) made
|
|
1766
|
+
// each HMR-applied change get wiped by a redundant full reload moments later —
|
|
1767
|
+
// the "theme updated, then the whole preview reloaded anyway" flash. When the
|
|
1768
|
+
// preview IS broken (crashed / failed to mount), the document may be an error
|
|
1769
|
+
// page without a live Vite client, so HMR can't deliver the fix — there a
|
|
1770
|
+
// debounced reload after the next edit is the genuine recovery path.
|
|
1771
|
+
const fileChangTickRef = useRef(fileChangeTick);
|
|
1772
|
+
useEffect(() => {
|
|
1773
|
+
if (fileChangTickRef.current === fileChangeTick)
|
|
1774
|
+
return;
|
|
1775
|
+
fileChangTickRef.current = fileChangeTick;
|
|
1776
|
+
if (!everLoaded || !state.url)
|
|
1777
|
+
return;
|
|
1778
|
+
if (iframeReady)
|
|
1779
|
+
return; // healthy — trust HMR / Vite's own full-reload
|
|
1780
|
+
const timer = setTimeout(() => {
|
|
1781
|
+
setIframeSrc(withCacheBuster(state.url));
|
|
1782
|
+
}, 1500);
|
|
1783
|
+
return () => clearTimeout(timer);
|
|
1784
|
+
}, [fileChangeTick, iframeReady, everLoaded, state.url]);
|
|
1785
|
+
// --- Manual retry handler ---
|
|
1786
|
+
const handleManualRetry = useCallback(() => {
|
|
1787
|
+
// Clear the loop-breaker so a fresh attempt starts clean.
|
|
1788
|
+
setPreviewGaveUp(false);
|
|
1789
|
+
setIframeMountKey((k) => k + 1);
|
|
1790
|
+
setStuckRetryCount(0);
|
|
1791
|
+
if (state.url) {
|
|
1792
|
+
setIframeSrc(withCacheBuster(state.url));
|
|
1793
|
+
}
|
|
1794
|
+
}, [state.url]);
|
|
1795
|
+
// A HUMAN retry is a fresh episode — refund the probe-driven budget so the
|
|
1796
|
+
// panel keeps auto-recovering alongside them.
|
|
1797
|
+
const handleUserRetry = useCallback(() => {
|
|
1798
|
+
deadEndAutoRecoversRef.current = 0;
|
|
1799
|
+
handleManualRetry();
|
|
1800
|
+
}, [handleManualRetry]);
|
|
1801
|
+
// --- Dead-end auto-recovery: probe while an actionable notice is up, retry when the server answers ---
|
|
1802
|
+
// Both dead-end notices (the give-up loop-breaker and the blank notice) mean every
|
|
1803
|
+
// in-budget retry already ran — against a server that may simply not have been up YET
|
|
1804
|
+
// (the motivating case: an E2B resume pulling a long-paused snapshot from cold storage
|
|
1805
|
+
// takes minutes; see MAX_DEAD_END_AUTO_RECOVERS). So instead of waiting for a human to
|
|
1806
|
+
// click Reload, keep asking the preview host whether it is serving — sequentially, one
|
|
1807
|
+
// probe at a time, exactly like the steady-state health check — and when it finally
|
|
1808
|
+
// answers, run the manual-retry path automatically. Gated on the document being DEAD
|
|
1809
|
+
// (no recent heartbeat): a heartbeating app behind the blank notice is an app that runs
|
|
1810
|
+
// but renders nothing — an app bug a reload cannot fix, and auto-reloading it would
|
|
1811
|
+
// just flicker the actionable notice the user is reading. isServerUp prefers the
|
|
1812
|
+
// readable /__mol/preview-status (the mlcl.dev proxy reports the UPSTREAM truthfully,
|
|
1813
|
+
// so an edge answering FOR a down sandbox does not read as "up").
|
|
1814
|
+
useEffect(() => {
|
|
1815
|
+
if (!state.url || confirmedContent)
|
|
1816
|
+
return undefined;
|
|
1817
|
+
if (!previewGaveUp && !blankPostBuild)
|
|
1818
|
+
return undefined;
|
|
1819
|
+
const aborter = new AbortController();
|
|
1820
|
+
let timer = null;
|
|
1821
|
+
const tick = async () => {
|
|
1822
|
+
if (aborter.signal.aborted)
|
|
1823
|
+
return;
|
|
1824
|
+
if (deadEndAutoRecoversRef.current >= MAX_DEAD_END_AUTO_RECOVERS)
|
|
1825
|
+
return;
|
|
1826
|
+
if (Date.now() - lastHeartbeatRef.current < FREEZE_THRESHOLD_MS) {
|
|
1827
|
+
// Alive behind the notice — not our case; re-check later in case it dies.
|
|
1828
|
+
timer = setTimeout(() => void tick(), HEALTH_POLL_MS);
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
const up = await isServerUp(urlRef.current, aborter.signal);
|
|
1832
|
+
if (aborter.signal.aborted)
|
|
1833
|
+
return;
|
|
1834
|
+
if (up) {
|
|
1835
|
+
deadEndAutoRecoversRef.current += 1;
|
|
1836
|
+
handleManualRetry();
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
timer = setTimeout(() => void tick(), HEALTH_POLL_MS);
|
|
1840
|
+
};
|
|
1841
|
+
timer = setTimeout(() => void tick(), HEALTH_POLL_MS);
|
|
1842
|
+
return () => {
|
|
1843
|
+
aborter.abort();
|
|
1844
|
+
if (timer)
|
|
1845
|
+
clearTimeout(timer);
|
|
1846
|
+
};
|
|
1847
|
+
}, [previewGaveUp, blankPostBuild, confirmedContent, state.url, handleManualRetry]);
|
|
1848
|
+
// The escalation clock measures CONTINUOUS unconfirmed time: any change of the
|
|
1849
|
+
// confirm verdict (healthy→broken or broken→healthy) restarts it, so a stretch
|
|
1850
|
+
// of healthy rendering can never count toward a restart, and a confirmed render
|
|
1851
|
+
// re-arms the once-per-episode escalation budget.
|
|
1852
|
+
useEffect(() => {
|
|
1853
|
+
notConfirmedSinceRef.current = Date.now();
|
|
1854
|
+
if (confirmedContent)
|
|
1855
|
+
backendRestartUsedRef.current = false;
|
|
1856
|
+
}, [confirmedContent]);
|
|
1857
|
+
// --- Backend-restart escalation watchdog (see PreviewPanelProps.onRestartBackend) ---
|
|
1858
|
+
// The one recovery a document reload can NEVER perform: when the dev server's
|
|
1859
|
+
// module state is poisoned (observed live 2026-08-31: module failures memoized
|
|
1860
|
+
// against vite's immutable `?v=`-hashed URLs — every reload, manual and
|
|
1861
|
+
// automatic, rebuilt the same broken graph with zero errors anywhere), only a
|
|
1862
|
+
// SERVER restart mints new module URLs. Escalates at most once per broken
|
|
1863
|
+
// episode, and only when every cheaper explanation is exhausted:
|
|
1864
|
+
// • the app has confirmed nothing for BACKEND_RESTART_AFTER_MS straight
|
|
1865
|
+
// (clock reset by confirms, new targets, and wakes — patience is honored),
|
|
1866
|
+
// • at least one dead-end auto-reload already ran (so a plain cold boot,
|
|
1867
|
+
// which never engages the dead-end machinery, can never trip this),
|
|
1868
|
+
// • the server answers probes RIGHT NOW (a down server needs waking/time,
|
|
1869
|
+
// not a restart — the dead-end probe loop owns that case),
|
|
1870
|
+
// • no build is running (the executor owns the sandbox during a turn).
|
|
1871
|
+
// The host may DECLINE (return false: wrong role, hidden tab, sandbox not
|
|
1872
|
+
// running) — nothing is burned and the watchdog may ask again later.
|
|
1873
|
+
useEffect(() => {
|
|
1874
|
+
if (!state.url || !onRestartBackend)
|
|
1875
|
+
return undefined;
|
|
1876
|
+
const aborter = new AbortController();
|
|
1877
|
+
let inFlight = false;
|
|
1878
|
+
const interval = setInterval(() => {
|
|
1879
|
+
if (inFlight)
|
|
1880
|
+
return;
|
|
1881
|
+
inFlight = true;
|
|
1882
|
+
void (async () => {
|
|
1883
|
+
try {
|
|
1884
|
+
if (confirmedContentRef.current || isBuildingRef.current)
|
|
1885
|
+
return;
|
|
1886
|
+
if (deadEndAutoRecoversRef.current < 1)
|
|
1887
|
+
return;
|
|
1888
|
+
if (backendRestartUsedRef.current)
|
|
1889
|
+
return;
|
|
1890
|
+
const now = Date.now();
|
|
1891
|
+
if (now - notConfirmedSinceRef.current < BACKEND_RESTART_AFTER_MS)
|
|
1892
|
+
return;
|
|
1893
|
+
if (now - lastBackendRestartAtRef.current < BACKEND_RESTART_COOLDOWN_MS)
|
|
1894
|
+
return;
|
|
1895
|
+
const up = await isServerUp(urlRef.current, aborter.signal);
|
|
1896
|
+
if (aborter.signal.aborted || !up)
|
|
1897
|
+
return;
|
|
1898
|
+
// Re-check the fast-moving gates after the await.
|
|
1899
|
+
if (confirmedContentRef.current || isBuildingRef.current)
|
|
1900
|
+
return;
|
|
1901
|
+
const outcome = await onRestartBackend();
|
|
1902
|
+
if (aborter.signal.aborted || outcome === false)
|
|
1903
|
+
return;
|
|
1904
|
+
backendRestartUsedRef.current = true;
|
|
1905
|
+
lastBackendRestartAtRef.current = Date.now();
|
|
1906
|
+
notConfirmedSinceRef.current = Date.now();
|
|
1907
|
+
// The restarted server deserves a fresh reload budget so the dead-end
|
|
1908
|
+
// probe (or the wake reload) can bring the recovered app in.
|
|
1909
|
+
deadEndAutoRecoversRef.current = 0;
|
|
1910
|
+
// Deliberate breadcrumb — names the escalation in the console so a
|
|
1911
|
+
// "the preview restarted itself" report is traceable.
|
|
1912
|
+
console.warn('[preview] escalated to a backend dev-server restart — reloads could not produce a render against a serving host');
|
|
1913
|
+
}
|
|
1914
|
+
catch (_error) {
|
|
1915
|
+
// Escalation is strictly best-effort: a failed probe or a host error
|
|
1916
|
+
// must never break the panel; the next check re-evaluates.
|
|
1917
|
+
}
|
|
1918
|
+
finally {
|
|
1919
|
+
inFlight = false;
|
|
1920
|
+
}
|
|
1921
|
+
})();
|
|
1922
|
+
}, BACKEND_RESTART_CHECK_MS);
|
|
1923
|
+
return () => {
|
|
1924
|
+
aborter.abort();
|
|
1925
|
+
clearInterval(interval);
|
|
1926
|
+
};
|
|
1927
|
+
}, [state.url, onRestartBackend]);
|
|
1928
|
+
// --- Reload a frozen preview ---
|
|
1929
|
+
// Remounts the iframe (fresh load re-runs the app, clearing the locked thread).
|
|
1930
|
+
const handleReloadFrozen = useCallback(() => {
|
|
1931
|
+
setPreviewFrozen(false);
|
|
1932
|
+
lastHeartbeatRef.current = Date.now();
|
|
1933
|
+
handleManualRetry();
|
|
1934
|
+
}, [handleManualRetry]);
|
|
1935
|
+
// --- Back / Forward: client-side history, NOT a cold reload ---
|
|
1936
|
+
// Browser-grade Back/Forward must preserve scroll position + SPA state, so we
|
|
1937
|
+
// do NOT bump loadNonce (which would re-mount the iframe and re-run the app).
|
|
1938
|
+
// Instead we (1) move the host's history cursor via the provider — updating the
|
|
1939
|
+
// URL bar + button gating with NO reload — and (2) post a `molecule:nav-command`
|
|
1940
|
+
// to the iframe, whose scaffold-injected receiver runs `history.back()`/
|
|
1941
|
+
// `forward()` inside the preview. The resulting `molecule:navigate` dedupes
|
|
1942
|
+
// against the cursor we just moved, so the forward stack survives.
|
|
1943
|
+
//
|
|
1944
|
+
// Order matters: move the cursor FIRST (synchronously sets currentUrl) so the
|
|
1945
|
+
// reported navigation dedupes; posting first would let recordNavigation push a
|
|
1946
|
+
// fresh entry and truncate the forward stack. Back/Forward are only enabled once
|
|
1947
|
+
// the preview has reported navigations (history is built from them), so the
|
|
1948
|
+
// scaffold nav-bridge receiver is always present when these fire.
|
|
1949
|
+
const postNavCommand = useCallback((action) => {
|
|
1950
|
+
iframeRef.current?.contentWindow?.postMessage({ type: 'molecule:nav-command', action }, previewTargetOrigin(iframeRef.current));
|
|
1951
|
+
}, []);
|
|
1952
|
+
const handleBack = useCallback(() => {
|
|
1953
|
+
back();
|
|
1954
|
+
postNavCommand('back');
|
|
1955
|
+
}, [back, postNavCommand]);
|
|
1956
|
+
const handleForward = useCallback(() => {
|
|
1957
|
+
forward();
|
|
1958
|
+
postNavCommand('forward');
|
|
1959
|
+
}, [forward, postNavCommand]);
|
|
1960
|
+
return {
|
|
1961
|
+
iframeRef,
|
|
1962
|
+
orientation,
|
|
1963
|
+
requestedSize,
|
|
1964
|
+
canRotate,
|
|
1965
|
+
currentLocation,
|
|
1966
|
+
isSecureLocation,
|
|
1967
|
+
everLoaded,
|
|
1968
|
+
iframeReady,
|
|
1969
|
+
fadingOut,
|
|
1970
|
+
iframeSrc,
|
|
1971
|
+
iframeMountKey,
|
|
1972
|
+
stuckRetryCount,
|
|
1973
|
+
previewGaveUp,
|
|
1974
|
+
lastGoodFrame,
|
|
1975
|
+
confirmedContent,
|
|
1976
|
+
blankPostBuild,
|
|
1977
|
+
previewFrozen,
|
|
1978
|
+
urlDraft,
|
|
1979
|
+
urlEditing,
|
|
1980
|
+
renderState,
|
|
1981
|
+
setFadingOut,
|
|
1982
|
+
setUrlDraft,
|
|
1983
|
+
setUrlEditing,
|
|
1984
|
+
handleDeviceChange,
|
|
1985
|
+
handleRotate,
|
|
1986
|
+
handleIframeLoad,
|
|
1987
|
+
handleUserRetry,
|
|
1988
|
+
handleReloadFrozen,
|
|
1989
|
+
handleBack,
|
|
1990
|
+
handleForward,
|
|
1991
|
+
};
|
|
1992
|
+
}
|
|
1993
|
+
//# sourceMappingURL=preview-panel-logic.js.map
|