Route preview automation through live owner streams #3548
Mergedjuliusmarmingemerged 12 commits into
main fromrefs/pull/3548/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -347,9 +337,14 @@347- providerInstanceId: input.scope.providerInstanceId,348- clientId: owner.clientId,349- });350- }351337 const timeoutMs = input.timeoutMs ?? 15_000;352338 const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();353- const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {354- const requestId = `preview-${next.requestSequence}`;355- const tabId = input.tabId ?? owner.tabId ?? undefined;339+ const route = yield* SynchronizedRef.modify(state, (current) => {340+ const connection = Array.from(current.clients.values())341+ .filter(342+ (owner) =>343+ owner.environmentId === input.scope.environmentId &&344+ owner.threadId === input.scope.threadId &&345+ owner.supportsAutomation,346+ )347+ .sort(348+ (left, right) =>349+ Number(right.focused) - Number(left.focused) || right.focusOrder - left.focusOrder,350+ )[0];apps/web/src/components/preview/previewAutomationRequestConsumer.ts line 57Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -54,11 +48,10 @@54- (value) =>55- options.respond({56- requestId: request.requestId,57- ok: true,58- ...(value === undefined ? {} : { result: value }),59- }),60- (error) =>61- options.respond({62- requestId: request.requestId,63- ok: false,64- error: serializePreviewAutomationError(error, {48+ const event = result.value;49+ if (event.type === "connected") {50+ activeConnectionId = event.connectionId;51+ connectionExplicitlyAnnounced = true;52+ } else if (activeConnectionId === null) {53+ activeConnectionId = event.connectionId;54+ } else if (activeConnectionId !== event.connectionId) {55+ if (connectionExplicitlyAnnounced) return;56+ activeConnectionId = event.connectionId;57+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/preview/PreviewAutomationHosts.tsx line 309Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +176,21 @@176+ };177+ let tabId = request.tabId ?? null;178+ try {179+ let state = readThreadPreviewState(threadRef);180+ const needsSessionSync =181+ Object.keys(state.sessions).length === 0 ||182+ (request.tabId !== undefined && state.sessions[request.tabId] === undefined);183+ if (needsSessionSync) {184+ const listTarget = {185+ environmentId,186+ input: { threadId: request.threadId },187+ } as const;188+ registry.refresh(previewEnvironment.list(listTarget));189+ const result = await listPreviews(listTarget);190+ if (result._tag === "Failure") {191+ throw squashAtomCommandFailure(result);192+ }193+ for (const snapshot of result.value.sessions) {194+ applyPreviewServerSnapshot(threadRef, snapshot);195+ }196+ state = readThreadPreviewState(threadRef);apps/web/src/components/preview/PreviewAutomationHosts.tsx line 377Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +233,21 @@233+ if (result._tag === "Failure") {234+ throw squashAtomCommandFailure(result);235+ }236+ const snapshot = result.value;237+ applyPreviewServerSnapshot(threadRef, snapshot);238+ activeTabId = snapshot.tabId;239+ tabId = activeTabId;240+ }241+ if (input.show ?? true) {242+ useRightPanelStore.getState().openBrowser(threadRef, activeTabId);243+ }244+ await waitForDesktopOverlay(245+ threadRef,246+ request.requestId,247+ activeTabId,248+ request.timeoutMs,249+ );250+ if (reusedExistingTab && input.url && previewBridge) {251+ await previewBridge.navigate(activeTabId, input.url);252+ }253+ return await currentStatus(threadRef, activeTabId);
- apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 354 to 377Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +233,21 @@233+ if (result._tag === "Failure") {234+ throw squashAtomCommandFailure(result);235+ }236+ const snapshot = result.value;237+ applyPreviewServerSnapshot(threadRef, snapshot);238+ activeTabId = snapshot.tabId;239+ tabId = activeTabId;240+ }241+ if (input.show ?? true) {242+ useRightPanelStore.getState().openBrowser(threadRef, activeTabId);243+ }244+ await waitForDesktopOverlay(245+ threadRef,246+ request.requestId,247+ activeTabId,248+ request.timeoutMs,249+ );250+ if (reusedExistingTab && input.url && previewBridge) {251+ await previewBridge.navigate(activeTabId, input.url);252+ }253+ return await currentStatus(threadRef, activeTabId);apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 94 to 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ if (!status.loading) return;81+ }82+ await new Promise<void>((resolve) => window.setTimeout(resolve, 50));83+ }84+ throw new PreviewAutomationNavigationTimeoutError({85+ requestId,86+ environmentId: threadRef.environmentId,87+ threadId: threadRef.threadId,88+ tabId,89+ readiness: targetReadiness,90+ timeoutMs,91+ });92+};93+94+const currentStatus = async (95+ threadRef: ScopedThreadRef,96+ requestedTabId: string | null,97+): Promise<PreviewAutomationStatus> => {98+ const state = readThreadPreviewState(threadRef);99+ const tabId = requestedTabId ?? state.snapshot?.tabId ?? null;100+ const snapshot = (tabId ? state.sessions[tabId] : null) ?? state.snapshot;packages/client-runtime/src/state/preview.ts line 107Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -86,16 +85,9 @@86- },87- }),88- reportAutomationOwner: createEnvironmentRpcCommand(runtime, {89- label: "environment-data:preview:automation-report-owner",90- tag: WS_METHODS.previewAutomationReportOwner,91- scheduler: automationScheduler,92- concurrency: {93- mode: "serial",94- key: ({ environmentId, input }) => JSON.stringify([environmentId, input.clientId]),85+ key: ({ environmentId, input }) =>86+ JSON.stringify([environmentId, input.connectionId, input.requestId]),9587 },9688 }),97- clearAutomationOwner: createEnvironmentRpcCommand(runtime, {98- label: "environment-data:preview:automation-clear-owner",99- tag: WS_METHODS.previewAutomationClearOwner,89+ focusAutomationHost: createEnvironmentRpcCommand(runtime, {90+ label: "environment-data:preview:automation-focus-host",91+ tag: WS_METHODS.previewAutomationFocusHost,10092 scheduler: automationScheduler,10193 concurrency: {
- @@ -0,0 +367,21 @@367+ environmentId,368+ input: {369+ threadId: request.threadId,370+ tabId: ready.tabId,371+ viewport: setting,372+ },373+ });374+ if (result._tag === "Failure") {375+ throw squashAtomCommandFailure(result);376+ }377+ applyPreviewServerSnapshot(threadRef, result.value);378+ const viewport = await waitForRenderedViewport(379+ ready.tabId,380+ setting,381+ input.timeoutMs ?? request.timeoutMs,382+ );383+ return {384+ tabId: ready.tabId,385+ setting,386+ viewport,387+ } satisfies PreviewAutomationResizeResult;@@ -91,0 +132,21 @@132+ const active = presentation.visible && presentation.rect !== null;133+ const lastRect = presentation.rect;134+ const sourceViewportKey = viewportSettingKey(viewport);135+ const effectiveViewport =136+ dragViewport?.sourceKey === sourceViewportKey137+ ? ({138+ _tag: "freeform",139+ width: dragViewport.width,140+ height: dragViewport.height,141+ } as const satisfies PreviewViewportSetting)142+ : viewport;143+ const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;144+ const hiddenSize =145+ effectiveViewport._tag !== "fill"146+ ? {147+ width: effectiveViewport.width * normalizedZoomFactor,148+ height: effectiveViewport.height * normalizedZoomFactor,149+ }150+ : { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };151+ const containerSize = active && lastRect ? lastRect : hiddenSize;152+ const layout = resolveBrowserViewportLayout(containerSize, effectiveViewport, zoomFactor);@@ -355,0 +379,21 @@379+ // Electron cookie/DOM state. A live assignment that predates an380+ // operation is not silently moved to a newer client: the caller gets a381+ // capability failure and can deliberately start a fresh provider382+ // session. A dead lease is pruned above and may fail over.383+ const connection =384+ hasLiveAssignment && supportsOperation(assignedConnection, input.operation)385+ ? assignedConnection386+ : hasLiveAssignment387+ ? undefined388+ : Array.from(current.clients.values())389+ .filter(390+ (host) =>391+ host.environmentId === input.scope.environmentId &&392+ supportsOperation(host, input.operation),393+ )394+ .sort(395+ (left, right) =>396+ right.supportedOperations.size - left.supportedOperations.size ||397+ Number(right.focused) - Number(left.focused) ||398+ right.focusOrder - left.focusOrder,399+ )[0];
- apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 267 to 269OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +249,21 @@249+ "preview automation response",250+ );251+ const focusAutomationHost = useAtomCommand(252+ previewEnvironment.focusAutomationHost,253+ "preview automation host focus",254+ );255+ const [automationConnectionAtom] = useState(() => Atom.make<string | null>(null));256+ const automationConnectionId = useAtomValue(automationConnectionAtom);257+258+ const handleRequest = useCallback(259+ async (request: PreviewAutomationRequest): Promise<unknown> => {260+ const threadRef: ScopedThreadRef = {261+ environmentId,262+ threadId: request.threadId,263+ };264+ let tabId = request.tabId ?? null;265+ try {266+ let state = readThreadPreviewState(threadRef);267+ const needsSessionSync =268+ Object.keys(state.sessions).length === 0 ||269+ (request.tabId !== undefined && state.sessions[request.tabId] === undefined);apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 444 to 446OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +426,21 @@426+ );427+ }428+ case "waitFor": {429+ const ready = await requireReadyTab();430+ return await ready.bridge.automation.waitFor(431+ ready.tabId,432+ request.input as Parameters<typeof ready.bridge.automation.waitFor>[1],433+ );434+ }435+ case "recordingStart": {436+ const ready = await requireReadyTab();437+ const startedAt = await startBrowserRecording(ready.tabId);438+ return {439+ tabId: ready.tabId,440+ recording: true,441+ startedAt,442+ };443+ }444+ case "recordingStop": {445+ const ready = await requireReadyTab();446+ const artifact = await stopBrowserRecording(ready.tabId);apps/web/src/components/preview/PreviewView.tsx line 154Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -131,3 +148,4 @@131148 if (previewBridge && tabId) void previewBridge.resetZoom(tabId);132149 }, [tabId]);133150151+ const handleViewportChange = useCallback(apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 216 to 229Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +179,21 @@179+ : false;180+ const viewportSetting = snapshot ? (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT) : undefined;181+ const viewport = tabId ? await readRenderedViewport(tabId).catch(() => null) : null;182+ const viewportStatus = {183+ ...(viewportSetting === undefined ? {} : { viewportSetting }),184+ ...(viewport === null ? {} : { viewport }),185+ };186+ if (tabId && previewBridge && state.desktopByTabId[tabId]) {187+ const status = await previewBridge.automation.status(tabId);188+ return { ...status, visible, ...viewportStatus };189+ }190+ const navStatus = snapshot?.navStatus;191+ return {192+ available: Boolean(previewBridge?.automation),193+ visible,194+ tabId,195+ url: navStatus && navStatus._tag !== "Idle" ? navStatus.url : null,196+ title: navStatus && navStatus._tag !== "Idle" ? navStatus.title : null,197+ loading: navStatus?._tag === "Loading",198+ ...viewportStatus,199+ };
- apps/web/src/browser/BrowserDeviceToolbar.tsx lines 154 to 165OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +145,21 @@145+ </Select>146+147+ <form148+ className="m-0 flex min-w-0 shrink-0 items-center gap-1 border-0 p-0"149+ aria-label="Viewport dimensions"150+ onSubmit={(event) => {151+ event.preventDefault();152+ applyCustomSize();153+ }}154+ onBlur={(event) => {155+ const nextTarget = event.relatedTarget;156+ if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;157+ if (158+ nextTarget instanceof HTMLElement &&159+ nextTarget.closest("[data-browser-device-toolbar]")160+ ) {161+ setCustomSize(null);162+ return;163+ }164+ applyCustomSize();165+ }}apps/web/src/browser/HostedBrowserWebview.tsx lines 153 to 157OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -91,0 +137,21 @@137+ if (!wrapper) return;138+ useBrowserSurfaceStore.getState().presentContent(tabId, {139+ x: layout.viewportX,140+ y: layout.viewportY,141+ width: layout.viewportWidth,142+ height: layout.viewportHeight,143+ scrollLeft: wrapper.scrollLeft,144+ scrollTop: wrapper.scrollTop,145+ });146+ }, [layout, tabId]);147+148+ useEffect(() => {149+ const frameId = window.requestAnimationFrame(syncContentPresentation);150+ return () => window.cancelAnimationFrame(frameId);151+ }, [syncContentPresentation]);152+153+ useEffect(() => {154+ const wrapper = wrapperRef.current;155+ if (!wrapper) return;156+ wrapper.scrollTo({ left: 0, top: 0 });157+ }, [tabId, viewport]);apps/web/src/browser/browserViewportActions.ts line 41Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,18 @@1+import type { PreviewViewportSetting } from "@t3tools/contracts";2+3+type BrowserViewportHandler = (setting: PreviewViewportSetting) => Promise<void>;4+5+const handlers = new Map<string, BrowserViewportHandler>();6+const commitTails = new Map<string, Promise<void>>();7+8+export function subscribeBrowserViewportChange(9+ tabId: string,10+ handler: BrowserViewportHandler,11+): () => void {12+ handlers.set(tabId, handler);13+ return () => {14+ if (handlers.get(tabId) === handler) handlers.delete(tabId);15+ };16+}17+18+export function commitBrowserViewportChange(
- apps/web/src/browser/useBrowserViewportResize.ts line 156Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +96,21 @@96+ const controlsWidth = direction.includes("east") || direction.includes("west");97+ const controlsHeight = direction.includes("north") || direction.includes("south");98+ const step = (event.shiftKey ? 50 : 10) * normalizedZoomFactor;99+ const delta =100+ event.key === "ArrowLeft" && controlsWidth101+ ? { x: -step, y: 0 }102+ : event.key === "ArrowRight" && controlsWidth103+ ? { x: step, y: 0 }104+ : event.key === "ArrowUp" && controlsHeight105+ ? { x: 0, y: -step }106+ : event.key === "ArrowDown" && controlsHeight107+ ? { x: 0, y: step }108+ : null;109+ if (!delta) return;110+ event.preventDefault();111+ event.stopPropagation();112+ const next = resizeFreeformViewport(effectiveViewport, delta, zoomFactor, direction);113+ if (next.width === effectiveViewport.width && next.height === effectiveViewport.height) return;114+ setDragViewport({ sourceKey: sourceViewportKey, ...next, direction });115+ commitDrag({ _tag: "freeform", ...next });116+ };apps/web/src/browser/BrowserDeviceToolbar.tsx line 165OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +145,21 @@145+ </Select>146+147+ <form148+ className="m-0 flex min-w-0 shrink-0 items-center gap-1 border-0 p-0"149+ aria-label="Viewport dimensions"150+ onSubmit={(event) => {151+ event.preventDefault();152+ applyCustomSize();153+ }}154+ onBlur={(event) => {155+ const nextTarget = event.relatedTarget;156+ if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;157+ if (158+ nextTarget instanceof HTMLElement &&159+ nextTarget.closest("[data-browser-device-toolbar]")160+ ) {161+ setCustomSize(null);162+ return;163+ }164+ applyCustomSize();165+ }}@@ -0,0 +70,21 @@70+ setPending(false);71+ setCustomSize(null);72+ },73+ () => setPending(false),74+ );75+ };76+77+ const applyCustomSize = () => {78+ if (!customValid || (customWidth === setting.width && customHeight === setting.height)) {79+ setCustomSize(null);80+ return;81+ }82+ apply({ _tag: "freeform", width: customWidth, height: customHeight });83+ };84+85+ const selectViewport = (value: string | null) => {86+ if (!value) return;87+ if (value === RESPONSIVE_VALUE) {88+ if (setting._tag === "freeform") return;89+ apply({ _tag: "freeform", width: setting.width, height: setting.height });90+ return;
- apps/web/src/components/preview/PreviewAutomationHosts.tsx line 377OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +357,21 @@357+ input.readiness ?? "load",358+ input.timeoutMs ?? request.timeoutMs,359+ );360+ return await currentStatus(threadRef, ready.tabId);361+ }362+ case "resize": {363+ const ready = await requireReadyTab();364+ const input = request.input as PreviewAutomationResizeInput;365+ const setting = resolvePreviewViewport(input);366+ const result = await resize({367+ environmentId,368+ input: {369+ threadId: request.threadId,370+ tabId: ready.tabId,371+ viewport: setting,372+ },373+ });374+ if (result._tag === "Failure") {375+ throw squashAtomCommandFailure(result);376+ }377+ applyPreviewServerSnapshot(threadRef, result.value);apps/web/src/components/preview/PreviewView.tsx line 192Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -133,0 +166,21 @@166+ title: "Unable to resize browser viewport",167+ description: error instanceof Error ? error.message : "An error occurred.",168+ });169+ throw error;170+ }171+ applyPreviewServerSnapshot(threadRef, result.value);172+ },173+ [resize, tabId, threadRef],174+ );175+176+ const handleToggleDeviceToolbar = () => {177+ if (viewport._tag !== "fill") {178+ void handleViewportChange(FILL_PREVIEW_VIEWPORT).catch(() => undefined);179+ return;180+ }181+182+ const responsiveSize = panelRect183+ ? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)184+ : { width: 1024, height: 768 };185+ void handleViewportChange({ _tag: "freeform", ...responsiveSize }).catch(() => undefined);186+ };
- @@ -89,3 +105,14 @@89105 };90106 }, [config, tabId]);91107108+ const active = presentation.visible && presentation.rect !== null;109+ const lastRect = presentation.rect;110+ const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;111+ const hiddenSize =112+ viewport._tag !== "fill"113+ ? {114+ width: viewport.width * normalizedZoomFactor,115+ height: viewport.height * normalizedZoomFactor,116+ }117+ : { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };118+ const containerSize = active && lastRect ? lastRect : hiddenSize;
- @@ -0,0 +116,21 @@116+ width: axis === "width" ? value : (current?.width ?? String(setting.width)),117+ height: axis === "height" ? value : (current?.height ?? String(setting.height)),118+ };119+ const numeric = Number(value);120+ if (121+ aspectRatio === null ||122+ !Number.isInteger(numeric) ||123+ numeric < PREVIEW_VIEWPORT_MIN_DIMENSION ||124+ numeric > PREVIEW_VIEWPORT_MAX_DIMENSION125+ ) {126+ return next;127+ }128+ const resized = resizeFreeformViewport(129+ setting,130+ axis === "width"131+ ? { x: numeric - setting.width, y: 0 }132+ : { x: 0, y: numeric - setting.height },133+ 1,134+ axis === "width" ? "east" : "south",135+ aspectRatio,136+ );apps/web/src/browser/browserViewportActions.ts line 28Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +12,21 @@12+ }13+}14+15+const handlers = new Map<string, BrowserViewportHandler>();16+const commitTails = new Map<string, Promise<void>>();17+18+const runHandlerWithTimeout = (19+ tabId: string,20+ handler: BrowserViewportHandler,21+ setting: PreviewViewportSetting,22+): Promise<void> => {23+ let timeoutId: ReturnType<typeof setTimeout> | undefined;24+ const timeout = new Promise<never>((_resolve, reject) => {25+ timeoutId = setTimeout(26+ () => reject(new BrowserViewportCommitTimeoutError(tabId)),27+ BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,28+ );29+ });30+ return Promise.race([Promise.resolve().then(() => handler(setting)), timeout]).finally(() => {31+ if (timeoutId !== undefined) clearTimeout(timeoutId);32+ });
- apps/web/src/browser/browserViewportActions.ts line 18OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,18 @@1+import type { PreviewViewportSetting } from "@t3tools/contracts";2+3+type BrowserViewportHandler = (setting: PreviewViewportSetting) => Promise<void>;4+5+export const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;6+7+export class BrowserViewportCommitTimeoutError extends Error {8+ override readonly name = "BrowserViewportCommitTimeoutError";9+10+ constructor(readonly tabId: string) {11+ super(`Timed out committing the browser viewport for tab ${tabId}`);12+ }13+}14+15+const handlers = new Map<string, BrowserViewportHandler>();16+const commitTails = new Map<string, Promise<void>>();17+18+const runHandlerWithTimeout = (apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 486 to 499Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +455,21 @@455+ const ready = await requireReadyTab();456+ const startedAt = await startBrowserRecording(ready.tabId);457+ return {458+ tabId: ready.tabId,459+ recording: true,460+ startedAt,461+ };462+ }463+ case "recordingStop": {464+ const recordingTabId = readActiveBrowserRecordingTabId();465+ const artifact = recordingTabId ? await stopBrowserRecording(recordingTabId) : null;466+ if (!artifact) {467+ throw new PreviewAutomationRecordingNotActiveError({468+ requestId: request.requestId,469+ environmentId,470+ threadId: request.threadId,471+ tabId: recordingTabId ?? tabId,472+ });473+ }474+ return artifact;475+ }
- apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 160 to 199Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +172,21 @@172+ renderedViewport &&173+ isPreviewViewportReady({174+ setting,175+ appliedSettingKey,176+ declaredViewport,177+ renderedViewport,178+ })179+ ) {180+ return renderedViewport;181+ }182+ } catch (error) {183+ // Registration and navigation can transiently replace the guest while184+ // React applies the server snapshot. Retry until the operation deadline.185+ lastError = error;186+ }187+ await new Promise<void>((resolve) => window.setTimeout(resolve, 50));188+ }189+ throw new Error(`Timed out applying browser viewport for tab ${tabId}`, {190+ cause: lastError,191+ });192+};apps/desktop/src/preview/Manager.ts line 1353OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1297,3 +1350,4 @@12971350 }12981351 yield* attachListeners(tabId, wc);12991352 runFork(ensureControlSession(wc).pipe(Effect.ignore));1353+ const zoomFactor = yield* attempt(
- apps/desktop/src/preview/Manager.ts line 2196Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2059,3 +2136,8 @@20592136 ...automationSelectorDiagnostics(input),20602137 });20612138 }2139+ if ("notEditable" in result) {2140+ return yield* new PreviewAutomationTargetNotEditableError({2141+ tabId,2142+ ...automationSelectorDiagnostics(input),2143+ });apps/desktop/src/preview/Manager.ts line 1162Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1100 +1122,21 @@1122+ // navigated anywhere. Keep the failure until a new load actually starts.1123+ const navStatus =1124+ current.navStatus.kind === "LoadFailed" && computedNavStatus.kind === "Success"1125+ ? current.navStatus1126+ : computedNavStatus;1127+ const state: PreviewTabState = {1128+ ...current,1129+ navStatus,1130+ canGoBack,1131+ canGoForward,1132+ zoomFactor,1133+ updatedAt,1134+ };1135+ return [1136+ Option.some(state),1137+ replaceMap(tabs, (copy) => {1138+ copy.set(tabId, state);1139+ }),1140+ ] as const;11001141 });1142+ if (Option.isSome(next)) yield* emit(tabId, next.value);@@ -2035,4 +2097,18 @@2035- if ("value" in element) element.value = "";2036- else if (element.isContentEditable) element.textContent = "";2037- element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));2097+ if (document.activeElement !== element) return { notEditable: true };2098+ const clear = ${input.clear ?? false};2099+ if (clear) {2100+ if (textControl) {2101+ element.select();2102+ } else {2103+ const range = document.createRange();2104+ range.selectNodeContents(element);2105+ const selection = document.getSelection();2106+ selection?.removeAllRanges();2107+ selection?.addRange(range);2108+ }20382109 }2110+ const text = ${textJson};2111+ const inserted = text.length > 02112+ ? document.execCommand("insertText", false, text)2113+ : !clear || document.execCommand("delete", false);2114+ if (!inserted) return { notEditable: true };
- apps/desktop/src/preview/Manager.ts line 2268Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2125,0 +2211,21 @@2211+ const releaseInput = Effect.gen(function* () {2212+ if (!keyReleased) {2213+ yield* sendCleanup("Input.dispatchKeyEvent", { type: "keyUp", ...params }).pipe(2214+ Effect.ignore,2215+ );2216+ }2217+ yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(2218+ Effect.ignore,2219+ );2220+ });2221+2222+ // Hidden/background guest WebContents do not have document focus until a user2223+ // clicks them. CDP focus emulation makes native key dispatch deterministic2224+ // without bringing another thread's preview to the foreground.2225+ yield* Effect.gen(function* () {2226+ yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });2227+ yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });2228+ yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });2229+ yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });2230+ keyReleased = true;2231+ }).pipe(Effect.ensuring(releaseInput));
- @@ -0,0 +475,21 @@475+ );476+ }477+ case "recordingStart": {478+ const ready = await requireReadyTab();479+ const startedAt = await startBrowserRecording(ready.tabId);480+ return {481+ tabId: ready.tabId,482+ recording: true,483+ startedAt,484+ };485+ }486+ case "recordingStop": {487+ const recordingTabId = readActiveBrowserRecordingTabId();488+ const stopTabId = resolveBrowserRecordingStopTarget(tabId, recordingTabId);489+ const artifact = stopTabId ? await stopBrowserRecording(stopTabId) : null;490+ if (!artifact) {491+ throw new PreviewAutomationRecordingNotActiveError({492+ requestId: request.requestId,493+ environmentId,494+ threadId: request.threadId,495+ tabId,
- @@ -0,0 +1 @@1+export function resolveBrowserRecordingStopTarget(
- @@ -1097,3 +1130,18 @@1097- navStatus: computeNavStatus(wc),1098- canGoBack: wc.navigationHistory.canGoBack(),1099- canGoForward: wc.navigationHistory.canGoForward(),1130+ const zoomFactor = yield* attempt(1131+ { operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },1132+ () => wc.getZoomFactor(),1133+ ).pipe(Effect.option);1134+ const computedNavStatus = computeNavStatus(wc);1135+ const canGoBack = wc.navigationHistory.canGoBack();1136+ const canGoForward = wc.navigationHistory.canGoForward();1137+ const updatedAt = yield* currentIso;1138+ const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {1139+ const current = tabs.get(tabId);1140+ if (!current) return [Option.none<PreviewTabState>(), tabs] as const;1141+ // Electron emits did-stop-loading after did-fail-load. At that point the1142+ // failed guest is no longer "loading", but it has not successfully1143+ // navigated anywhere. Keep the failure until a new load actually starts.1144+ const navStatus =1145+ current.navStatus.kind === "LoadFailed" && computedNavStatus.kind === "Success"1146+ ? current.navStatus1147+ : computedNavStatus;
- apps/server/src/mcp/PreviewAutomationBroker.ts line 321Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -235,4 +291,17 @@235- )(function* (owner) {236- const clientId = owner.clientId;237- const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();238- const previous = yield* SynchronizedRef.modify(state, (current) => {291+ const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (292+ host: PreviewAutomationHost,293+ ) {294+ const clientId = host.clientId;295+ const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();296+ const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);297+ yield* Queue.offer(queue, { type: "connected", connectionId });298+ const connection: ClientConnection = {299+ clientId,300+ connectionId,301+ environmentId: host.environmentId,302+ supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),303+ focused: false,304+ focusOrder: 0,305+ queue,306+ };307+ const registration = yield* SynchronizedRef.modify(state, (current) => {apps/desktop/src/preview/Manager.ts lines 372 to 372OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -370,4 +369,4 @@370369 left.kind === "key" &&371370 right.kind === "key" &&372371 left.key === right.key &&373- left.code === right.code372+ (left.code === undefined || right.code === undefined || left.code === right.code)apps/web/src/components/preview/PreviewView.tsx lines 194 to 197OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -133,0 +177,21 @@177+ );178+179+ const handleToggleDeviceToolbar = () => {180+ if (!tabId) return;181+ if (viewport._tag !== "fill") {182+ void commitBrowserViewportChange(tabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);183+ return;184+ }185+186+ const responsiveSize = panelRect187+ ? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)188+ : { width: 1024, height: 768 };189+ void commitBrowserViewportChange(tabId, { _tag: "freeform", ...responsiveSize }).catch(190+ () => undefined,191+ );192+ };193+194+ useEffect(() => {195+ if (!tabId || !visible) return;196+ return subscribeBrowserViewportChange(tabId, handleViewportChange);197+ }, [handleViewportChange, tabId, visible]);
- apps/desktop/src/window/DesktopWindow.ts lines 336 to 347Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -279,0 +327,21 @@327+ return undefined;328+ }329+330+ const retryIndex = Math.min(331+ developmentLoadRetryIndex,332+ DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,333+ );334+ const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;335+ developmentLoadRetryIndex += 1;336+ developmentLoadRetryFiber = runFork(337+ Effect.sleep(retryInMs).pipe(338+ Effect.andThen(339+ Effect.sync(() => {340+ developmentLoadRetryFiber = undefined;341+ if (!window.isDestroyed()) {342+ window.webContents.reload();343+ }344+ }),345+ ),346+ ),347+ );
- apps/desktop/src/window/DesktopWindow.ts line 343Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -279,0 +323,21 @@323+ void window.loadURL(applicationUrl).catch(() => undefined);324+ };325+ const scheduleDevelopmentLoadRetry = () => {326+ if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {327+ return undefined;328+ }329+330+ const retryIndex = Math.min(331+ developmentLoadRetryIndex,332+ DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,333+ );334+ const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;335+ developmentLoadRetryIndex += 1;336+ developmentLoadRetryFiber = runFork(337+ Effect.sleep(retryInMs).pipe(338+ Effect.andThen(339+ Effect.sync(() => {340+ developmentLoadRetryFiber = undefined;341+ if (!window.isDestroyed()) {342+ window.webContents.reload();343+ }
- @@ -0,0 +102,21 @@102+ const number = Number(functionKey[1]);103+ return { code: input.key, key: input.key, keyCode: 111 + number };104+ }105+106+ if (/^[a-z]$/i.test(input.key)) {107+ const upper = input.key.toUpperCase();108+ const shifted = input.modifiers?.includes("Shift") ?? false;109+ const key = shifted || input.key === upper ? upper : input.key;110+ return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };111+ }112+113+ const printable = PRINTABLE_KEYS.find(114+ (definition) => definition.key === input.key || definition.shiftedKey === input.key,115+ );116+ if (printable) {117+ const shifted = input.modifiers?.includes("Shift") ?? false;118+ const key =119+ printable.shiftedKey && (shifted || input.key === printable.shiftedKey)120+ ? printable.shiftedKey121+ : printable.key;122+ return { ...printable, key, text: key };
- apps/web/src/browser/HostedBrowserWebview.tsx lines 146 to 169Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -91,0 +143,21 @@143+ useBrowserSurfaceStore.getState().presentContent(tabId, {144+ x: layout.viewportX,145+ y: layout.viewportY,146+ width: layout.viewportWidth,147+ height: layout.viewportHeight,148+ scale: layout.viewportScale,149+ scrollLeft: wrapper.scrollLeft,150+ scrollTop: wrapper.scrollTop,151+ });152+ }, [layout, tabId]);153+154+ useEffect(() => {155+ const frameId = window.requestAnimationFrame(syncContentPresentation);156+ return () => window.cancelAnimationFrame(frameId);157+ }, [syncContentPresentation]);158+159+ useEffect(() => {160+ const wrapper = wrapperRef.current;161+ if (!wrapper) return;162+ wrapper.scrollTo({ left: 0, top: 0 });163+ }, [tabId, viewport._tag, viewportHeight, viewportWidth]);
juliusmarminge merged thisffae541
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
c01c7ab5-4800-4ff2-b223-d826cd062a91You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.