Skip to content

Commit 79294c9

Browse files
committed
fix(preview): handle cold opens and recover stream credentials
1 parent f7d42ba commit 79294c9

11 files changed

Lines changed: 115 additions & 32 deletions

File tree

‎apps/mobile/src/features/browser/PreviewStreamWebView.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ export function PreviewStreamWebView({
5656
...props
5757
}: PreviewStreamConfiguration & NativeStreamBridge) {
5858
const [attempt, setAttempt] = useState(0);
59+
const [previousAccess, setPreviousAccess] = useState(props.access);
60+
// Wait for refreshed access, including cookie credentials with unchanged JSON.
61+
if (props.access !== previousAccess) {
62+
setPreviousAccess(props.access);
63+
setAttempt((current) => current + 1);
64+
}
5965
const processRetried = useRef(false);
6066
const unauthorized = useRef(0);
6167
const refreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -91,7 +97,6 @@ export function PreviewStreamWebView({
9197
refreshTimer.current = setTimeout(
9298
() => {
9399
refreshTimer.current = null;
94-
setAttempt((current) => current + 1);
95100
props.onUnauthorized();
96101
},
97102
refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
@@ -101,7 +106,6 @@ export function PreviewStreamWebView({
101106
onRetry={() => {
102107
processRetried.current = false;
103108
unauthorized.current = 0;
104-
setAttempt((current) => current + 1);
105109
props.onUnauthorized();
106110
}}
107111
onStreaming={() => {

‎apps/server/src/mcp/PreviewAutomationBroker.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,44 @@ it.effect("announces a live replacement stream before delivering requests", () =
328328
),
329329
);
330330

331+
it.effect(
332+
"keeps a server-host open alive for installation without extending other operations",
333+
() =>
334+
Effect.scoped(
335+
Effect.gen(function* () {
336+
const broker = yield* makeBroker;
337+
const received = yield* Deferred.make<RoutedRequest>();
338+
const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true }));
339+
yield* Stream.runForEach(requests, (request) =>
340+
request.operation === "open"
341+
? Deferred.succeed(received, request)
342+
: broker.respond({
343+
clientId: "client-1",
344+
connectionId: request.connectionId,
345+
requestId: request.requestId,
346+
ok: true,
347+
result: request.timeoutMs,
348+
}),
349+
).pipe(Effect.forkScoped);
350+
const opening = yield* broker
351+
.invoke({ scope, operation: "open", input: {} })
352+
.pipe(Effect.forkScoped);
353+
const request = yield* Deferred.await(received);
354+
yield* TestClock.adjust(16_000);
355+
yield* broker.respond({
356+
clientId: "client-1",
357+
connectionId: request.connectionId,
358+
requestId: request.requestId,
359+
ok: true,
360+
result: "opened",
361+
});
362+
expect(yield* Fiber.join(opening)).toBe("opened");
363+
expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe(15_000);
364+
expect(yield* broker.invoke({ scope, operation: "navigate", input: {} })).toBe(15_000);
365+
}),
366+
),
367+
);
368+
331369
it.effect("preserves bounded request and remote selector diagnostics", () => {
332370
const locator = "role=button[name='request-secret']";
333371
const remoteMessage = "Unexpected token near remote-secret.";

‎apps/server/src/mcp/PreviewAutomationBroker.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,6 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
486486
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
487487
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
488488
): Effect.fn.Return<A, PreviewAutomationError> {
489-
const timeoutMs = input.timeoutMs ?? 15_000;
490489
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
491490
const route = yield* SynchronizedRef.modify(state, (current) => {
492491
const assignments = new Map(
@@ -540,6 +539,10 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
540539
if (!hasLiveAssignment) assignments.delete(assignmentKey);
541540
return [undefined, { ...current, assignments }] as const;
542541
}
542+
// The environment host may install Chromium on its first open (up to
543+
// ten minutes). Keep that request alive without replaying its effects.
544+
const timeoutMs =
545+
input.timeoutMs ?? (input.operation === "open" && connection.preferred ? 660_000 : 15_000);
543546
const canReuseAssignedTab =
544547
assigned !== undefined &&
545548
assigned.connectionId === connection.connectionId &&
@@ -588,6 +591,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
588591
});
589592
}
590593
const { connection, requestId, requestContext, requestSequence } = route;
594+
const { timeoutMs } = requestContext;
591595
input.onTargetTab?.(requestContext.tabId);
592596
const removePending = SynchronizedRef.update(state, (next) => {
593597
if (!next.pending.has(requestId)) return next;

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ interface ServerTab {
211211
loading: boolean;
212212
closing: boolean;
213213
recording: Recording | null;
214+
initialNavigation: Promise<void> | null;
214215
/** The latest queued start, so a stop can find a recording still starting. */
215216
recordingStart: Promise<Recording> | null;
216217
/** Serializes captures and recording start/stop. */
@@ -381,8 +382,9 @@ const make = Effect.gen(function* () {
381382
[...tab.viewers]
382383
.map((viewer) => viewer.requestedSize)
383384
.filter((requested) => requested !== null)
384-
.sort((left, right) => right.order - left.order)[0];
385-
if (size) await tab.page.setViewportSize({ width: size.width, height: size.height });
385+
.sort((left, right) => right.order - left.order)[0] ??
386+
UNATTACHED_FILL_VIEWPORT;
387+
await tab.page.setViewportSize({ width: size.width, height: size.height });
386388
broadcastViewport(tab);
387389
};
388390

@@ -419,6 +421,7 @@ const make = Effect.gen(function* () {
419421
closing: false,
420422
recording: null,
421423
recordingStart: null,
424+
initialNavigation: null,
422425
captureLock: Promise.resolve(),
423426
capturing: 0,
424427
};
@@ -502,21 +505,25 @@ const make = Effect.gen(function* () {
502505
tabs.set(tabKey(tab.threadId, tab.tabId), tab);
503506
reportLiveTabs();
504507
if (snapshot.navStatus._tag === "Loading") {
505-
void page.goto(snapshot.navStatus.url).catch(() => undefined);
508+
tab.initialNavigation = page
509+
.goto(snapshot.navStatus.url, { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS })
510+
.then(
511+
() => undefined,
512+
() => undefined,
513+
);
506514
}
507515
return tab;
508516
};
509517

510518
const ensureTab = (snapshot: PreviewSessionSnapshot): Promise<ServerTab> => {
511519
const key = tabKey(snapshot.threadId, snapshot.tabId);
520+
const pending = pendingTabs.get(key);
521+
if (pending) return pending;
512522
const existing = tabs.get(key);
513523
if (existing) return Promise.resolve(existing);
514-
let pending = pendingTabs.get(key);
515-
if (!pending) {
516-
pending = createTab(snapshot).finally(() => pendingTabs.delete(key));
517-
pendingTabs.set(key, pending);
518-
}
519-
return pending;
524+
const opening = createTab(snapshot).finally(() => pendingTabs.delete(key));
525+
pendingTabs.set(key, opening);
526+
return opening;
520527
};
521528

522529
/** Server tabs that exist in PreviewManager but have not finished opening here. */
@@ -872,8 +879,9 @@ const make = Effect.gen(function* () {
872879
}),
873880
);
874881
};
882+
const navigationTimeout = Math.min(request.timeoutMs, NAVIGATION_TIMEOUT_MS);
875883
if (existing) {
876-
if (url) await navigate(existing, url, "load", request.timeoutMs);
884+
if (url) await navigate(existing, url, "load", navigationTimeout);
877885
await revealTab(existing);
878886
return statusWithTitle(existing);
879887
}
@@ -886,10 +894,12 @@ const make = Effect.gen(function* () {
886894
}),
887895
);
888896
const tab = await ensureTab(snapshot);
897+
// Wait for the requested document without blocking manager events for other tabs.
898+
await tab.initialNavigation;
889899
await revealTab(tab);
890900
if (url) {
891901
await tab.page
892-
.waitForLoadState("load", { timeout: request.timeoutMs })
902+
.waitForLoadState("load", { timeout: navigationTimeout })
893903
.catch(() => undefined);
894904
}
895905
return statusWithTitle(tab);

‎apps/server/src/preview/ServerBrowserToolchain.ts‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ const make = Effect.gen(function* () {
298298
Effect.orElseSucceed(() => false),
299299
);
300300

301-
/** Stages, publishes, and prunes `<baseDir>/tools/<tool>/<version>` unless it is already complete. */
301+
/** Stages and atomically publishes `<baseDir>/tools/<tool>/<version>` if not already complete. */
302302
const installOnce = Effect.fn("ServerBrowserToolchain.installOnce")(function* (
303303
tool: string,
304304
version: string,
@@ -310,9 +310,6 @@ const make = Effect.gen(function* () {
310310
const installDir = path.join(parentDir, version);
311311
if (yield* isInstalled(installDir, version)) return;
312312

313-
yield* fs
314-
.remove(installDir, { recursive: true, force: true })
315-
.pipe(Effect.mapError(fail("removing an incomplete install")));
316313
yield* fs
317314
.makeDirectory(parentDir, { recursive: true })
318315
.pipe(Effect.mapError(fail("preparing the install directory")));
@@ -325,6 +322,8 @@ const make = Effect.gen(function* () {
325322
yield* fs
326323
.writeFileString(path.join(stagingDir, SENTINEL), `${version}\n`)
327324
.pipe(Effect.mapError(fail("recording the completed install")));
325+
// Published versions may be in use by other servers. Never remove them;
326+
// rename cannot replace a completed, nonempty install directory.
328327
yield* fs.rename(stagingDir, installDir).pipe(
329328
Effect.catch((cause) =>
330329
// A concurrent server may have published the same version first.
@@ -335,12 +334,6 @@ const make = Effect.gen(function* () {
335334
),
336335
),
337336
);
338-
// Only runs right after an upgrade; dot entries are other installs' staging dirs.
339-
const names = yield* fs.readDirectory(parentDir).pipe(Effect.orElseSucceed(() => []));
340-
yield* Effect.forEach(
341-
names.filter((name) => !name.startsWith(".") && name !== version),
342-
(name) => fs.remove(path.join(parentDir, name), { recursive: true, force: true }),
343-
).pipe(Effect.ignore);
344337
}).pipe(
345338
Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
346339
);

‎apps/web/src/browser/ServerBrowserSurface.tsx‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ export function ServerBrowserSurface(props: {
125125
const containerRef = useRef<HTMLDivElement | null>(null);
126126
const canvasRef = useRef<HTMLCanvasElement | null>(null);
127127
const inputRef = useRef<HTMLTextAreaElement | null>(null);
128+
const keySentRef = useRef(false);
128129
const clientRef = useRef<PreviewStreamClient | null>(null);
129130
const viewportRef = useRef<PreviewStreamViewport | null>(null);
130131
const sizeRef = useRef<{ width: number; height: number } | null>(null);
@@ -535,6 +536,7 @@ export function ServerBrowserSurface(props: {
535536
};
536537

537538
const resetInput = (textarea: HTMLTextAreaElement) => {
539+
keySentRef.current = false;
538540
textarea.value = INPUT_SENTINEL;
539541
textarea.setSelectionRange(INPUT_SENTINEL.length, INPUT_SENTINEL.length);
540542
};
@@ -545,6 +547,7 @@ export function ServerBrowserSurface(props: {
545547
};
546548

547549
const handleKey = (action: "down" | "up", event: KeyboardEvent<HTMLTextAreaElement>) => {
550+
keySentRef.current = false;
548551
// IME and soft keyboards deliver text through composition and input events.
549552
if (
550553
event.nativeEvent.isComposing ||
@@ -554,6 +557,13 @@ export function ServerBrowserSurface(props: {
554557
) {
555558
return;
556559
}
560+
// Keep plain Escape and Tab in the page; Shift+Escape returns to the app.
561+
if (event.key === "Escape" && event.shiftKey) {
562+
event.preventDefault();
563+
event.stopPropagation();
564+
if (action === "down") event.currentTarget.blur();
565+
return;
566+
}
557567
const shortcut = event.ctrlKey || event.metaKey;
558568
// Paste arrives as a paste event carrying this device's clipboard.
559569
if (shortcut && event.key.toLowerCase() === "v") return;
@@ -574,6 +584,11 @@ export function ServerBrowserSurface(props: {
574584
...(action === "down" && text !== undefined ? { text } : {}),
575585
modifiers: previewStreamModifiers(event),
576586
});
587+
// Some Android keyboards edit the textarea even when keydown is prevented.
588+
keySentRef.current =
589+
action === "down" &&
590+
!shortcut &&
591+
(text !== undefined || event.key === "Backspace" || event.key === "Delete");
577592
// Shortcuts stay with the app (copy, paste, keybindings); other keys belong to the page.
578593
if (shortcut) return;
579594
event.preventDefault();
@@ -585,7 +600,8 @@ export function ServerBrowserSurface(props: {
585600
if (native instanceof InputEvent && native.isComposing) return;
586601
const textarea = event.currentTarget;
587602
const inputType = native instanceof InputEvent ? native.inputType : "";
588-
if (inputType === "deleteContentBackward") sendKeyPress(BACKSPACE);
603+
if (keySentRef.current) keySentRef.current = false;
604+
else if (inputType === "deleteContentBackward") sendKeyPress(BACKSPACE);
589605
else if (inputType === "deleteContentForward") sendKeyPress(DELETE);
590606
else {
591607
const text = textarea.value.replaceAll(INPUT_SENTINEL, "");
@@ -627,6 +643,7 @@ export function ServerBrowserSurface(props: {
627643
<textarea
628644
ref={inputRef}
629645
aria-label="Browser page"
646+
aria-description="Press Shift+Escape to leave the browser page."
630647
autoCapitalize="off"
631648
autoComplete="off"
632649
autoCorrect="off"

‎apps/web/src/components/preview/usePreviewSession.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
4444
const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
4545
if (!AsyncResult.isSuccess(result)) return;
4646
reconcilePreviewServerSessions(threadRef, result.value);
47+
if (!result.waiting && !readThreadPreviewState(threadRef).listLoaded) {
48+
// An event overtook the first list. Retry the authoritative baseline;
49+
// do not declare a partial event-only index ready for surface cleanup.
50+
queueMicrotask(() => {
51+
if (!disposed) get.refresh(sessionsAtom);
52+
});
53+
}
4754
};
4855

4956
const applyLatestEvent = (result: Atom.Type<typeof eventsAtom>) => {

‎apps/web/src/previewStateStore.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,19 @@ describe("previewStateStore (single-tab)", () => {
466466
reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 0 });
467467

468468
expect(readThreadPreviewState(ref).sessions).toEqual({ [snapshot.tabId]: snapshot });
469+
expect(readThreadPreviewState(ref).listLoaded).toBe(false);
470+
471+
const olderTab = makeSnapshot({ tabId: "tab_before_event" });
472+
reconcilePreviewServerSessions(ref, {
473+
sessions: [olderTab, snapshot],
474+
serverEpoch,
475+
revision: 2,
476+
});
477+
expect(readThreadPreviewState(ref).listLoaded).toBe(true);
478+
expect(readThreadPreviewState(ref).sessions).toEqual({
479+
[olderTab.tabId]: olderTab,
480+
[snapshot.tabId]: snapshot,
481+
});
469482
});
470483

471484
it("does not resurrect a tab from an event older than its close", () => {

‎apps/web/src/previewStateStore.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ export function reconcilePreviewServerSessions(
315315
updateThreadPreviewState(ref, (current) => {
316316
const sameServer = current.serverEpoch === result.serverEpoch;
317317
if (sameServer && result.revision < current.serverRevision) {
318-
return current.listLoaded ? current : { ...current, listLoaded: true };
318+
return current;
319319
}
320320
const snapshots = result.sessions;
321321
const sessions: Record<string, PreviewSessionSnapshot> = {};

‎knip.jsonc‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
"plugins/*.cjs",
7474
"scripts/generate-device-stream.mts",
7575
"src/features/devices/device-stream.browser.ts!",
76+
"src/features/browser/preview-stream.browser.ts!",
7677
],
7778
// Fonts are configured as asset paths; Expo autolinks the native packages.
7879
"ignoreDependencies": [

0 commit comments

Comments
 (0)