Harden preview ownership and option-based secret handling (#3172)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-06-19 17:38:45 -07:00
1 parent e29ad7604b
commit 753bc4672d
13 files changed
+691 -406

No files matched your search

+9 -1
View File
@@ -107,7 +107,15 @@ it.effect("registers annotated tools and preserves authenticated request context
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const requests = yield* broker.connect("mcp-test-client");
const requests = yield* broker.connect({
clientId: "mcp-test-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
@@ -2,10 +2,13 @@ import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
type PreviewAutomationOwner,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Stream from "effect/Stream";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
@@ -20,11 +23,22 @@ const scope = {
expiresAt: 2,
};
it.effect("routes a request to the focused owner and correlates its response", () =>
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: null,
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
...overrides,
});
it.effect("atomically registers a connected owner and correlates its response", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect("client-1");
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
@@ -33,15 +47,6 @@ it.effect("routes a request to the focused owner and correlates its response", (
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: null,
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const result = yield* broker.invoke<{ available: boolean }>({
scope,
@@ -68,22 +73,119 @@ it.effect("routes interactive commands to a hidden durable browser host", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect("client-hidden");
const requests = yield* broker.connect(
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
);
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "client-hidden",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: "tab-hidden",
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
}),
),
);
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect(makeOwner({ tabId: null }));
let routedTabId: string | undefined;
yield* Stream.runForEach(requests, (request) => {
routedTabId = request.tabId;
return broker.respond({ requestId: request.requestId, ok: true });
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
expect(routedTabId).toBeUndefined();
}),
),
);
it.effect("preserves current owner metadata when its request stream reconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const firstRequests = yield* broker.connect(makeOwner());
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
const reconnectedRequests = yield* broker.connect(makeOwner());
let routedTabId: string | undefined;
yield* Stream.runForEach(reconnectedRequests, (request) => {
routedTabId = request.tabId;
return broker.respond({ requestId: request.requestId, ok: true });
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
expect(routedTabId).toBe("tab-current");
}),
),
);
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.clearOwner({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: ThreadId.make("thread-stale"),
});
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
}),
),
);
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const _requests = yield* broker.connect(makeOwner());
const pending = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
const _replacementRequests = yield* broker.connect(makeOwner());
const error = yield* Fiber.join(pending);
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
}),
),
);
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner(
makeOwner({
clientId: "client-report-only",
focusedAt: "2026-06-11T00:00:01.000Z",
}),
);
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
expect(result).toBe("connected");
}),
),
);
+40 -25
View File
@@ -11,6 +11,7 @@ import {
type PreviewAutomationError,
type PreviewAutomationOperation,
type PreviewAutomationOwner,
type PreviewAutomationOwnerIdentity,
type PreviewAutomationRequest,
type PreviewAutomationResponse,
type PreviewTabId,
@@ -35,11 +36,13 @@ export interface PreviewAutomationInvokeInput {
}
export interface PreviewAutomationBrokerShape {
readonly connect: (clientId: string) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
readonly connect: (
owner: PreviewAutomationOwner,
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
readonly reportOwner: (
owner: PreviewAutomationOwner,
) => Effect.Effect<void, PreviewAutomationError>;
readonly clearOwner: (clientId: string) => Effect.Effect<void>;
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
readonly respond: (
response: PreviewAutomationResponse,
) => Effect.Effect<void, PreviewAutomationError>;
@@ -63,7 +66,7 @@ interface ClientConnection {
}
interface PendingRequest {
readonly clientId: string;
readonly queue: ClientConnection["queue"];
readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
}
@@ -133,17 +136,16 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
queue: ClientConnection["queue"],
) {
const toFail = yield* SynchronizedRef.modify(state, (current) => {
if (current.clients.get(clientId)?.queue !== queue) {
return [[] as ReadonlyArray<PendingRequest>, current] as const;
}
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const pending = new Map(current.pending);
const disconnected: PendingRequest[] = [];
clients.delete(clientId);
owners.delete(clientId);
if (current.clients.get(clientId)?.queue === queue) {
clients.delete(clientId);
owners.delete(clientId);
}
for (const [requestId, entry] of pending) {
if (entry.clientId === clientId) {
if (entry.queue === queue) {
pending.delete(requestId);
disconnected.push(entry);
}
@@ -166,12 +168,22 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const connect: PreviewAutomationBrokerShape["connect"] = Effect.fn(
"PreviewAutomationBroker.connect",
)(function* (clientId) {
)(function* (owner) {
const clientId = owner.clientId;
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
const previous = yield* SynchronizedRef.modify(state, (current) => {
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const existingOwner = current.owners.get(clientId);
clients.set(clientId, { clientId, queue });
return [current.clients.get(clientId), { ...current, clients }] as const;
owners.set(
clientId,
existingOwner?.environmentId === owner.environmentId &&
existingOwner.threadId === owner.threadId
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
: owner,
);
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
});
if (previous) yield* disconnect(clientId, previous.queue);
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
@@ -189,10 +201,18 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const clearOwner: PreviewAutomationBrokerShape["clearOwner"] = Effect.fn(
"PreviewAutomationBroker.clearOwner",
)(function* (clientId) {
)(function* (owner) {
yield* SynchronizedRef.update(state, (current) => {
const currentOwner = current.owners.get(owner.clientId);
if (
!currentOwner ||
currentOwner.environmentId !== owner.environmentId ||
currentOwner.threadId !== owner.threadId
) {
return current;
}
const owners = new Map(current.owners);
owners.delete(clientId);
owners.delete(owner.clientId);
return { ...current, owners };
});
});
@@ -234,8 +254,13 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
owner.supportsAutomation,
)
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
const owner = candidates[0];
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
if (!owner) {
if (candidates.length > 0) {
return yield* new PreviewAutomationUnavailableError({
message: "The browser host is not connected.",
});
}
return yield* new PreviewAutomationNoFocusedOwnerError({
message: "No desktop browser host is available for this thread.",
});
@@ -246,22 +271,12 @@ const make = Effect.gen(function* PreviewAutomationBrokerMake() {
message: "The browser host is not connected.",
});
}
if (
input.operation !== "open" &&
input.operation !== "status" &&
!owner.tabId &&
!input.tabId
) {
return yield* new PreviewAutomationTabNotFoundError({
message: "The browser host does not have an active tab.",
});
}
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const requestId = yield* SynchronizedRef.modify(state, (next) => {
const requestId = `preview-${next.requestSequence}`;
const pending = new Map(next.pending);
pending.set(requestId, { clientId: owner.clientId, deferred });
pending.set(requestId, { queue: connection.queue, deferred });
return [requestId, { ...next, pending, requestSequence: next.requestSequence + 1 }] as const;
});
const removePending = SynchronizedRef.update(state, (next) => {
+2 -2
View File
@@ -1489,7 +1489,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
[WS_METHODS.previewAutomationConnect]: (input) =>
observeRpcStreamEffect(
WS_METHODS.previewAutomationConnect,
previewAutomationBroker.connect(input.clientId),
previewAutomationBroker.connect(input),
{ "rpc.aggregate": "preview-automation" },
),
[WS_METHODS.previewAutomationRespond]: (input) =>
@@ -1507,7 +1507,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
[WS_METHODS.previewAutomationClearOwner]: (input) =>
observeRpcEffect(
WS_METHODS.previewAutomationClearOwner,
previewAutomationBroker.clearOwner(input.clientId),
previewAutomationBroker.clearOwner(input),
{ "rpc.aggregate": "preview-automation" },
),
[WS_METHODS.subscribePreviewEvents]: (_input) =>
@@ -3,11 +3,11 @@ import { describe, expect, it } from "vite-plus/test";
import { observeAutomationOwnerConnectedGeneration } from "./PreviewAutomationOwner";
describe("observeAutomationOwnerConnectedGeneration", () => {
it("re-reports ownership only after a later transport generation connects", () => {
it("reports ownership when the initial transport generation connects", () => {
const initial = observeAutomationOwnerConnectedGeneration(null, 1);
expect(initial).toEqual({
nextGeneration: 1,
shouldReport: false,
shouldReport: true,
});
const disconnected = observeAutomationOwnerConnectedGeneration(initial.nextGeneration, null);
@@ -1,15 +1,16 @@
"use client";
import { useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type {
PreviewAutomationNavigateInput,
PreviewAutomationOpenInput,
PreviewAutomationRequest,
PreviewAutomationResponse,
PreviewAutomationOwner as PreviewAutomationOwnerState,
PreviewAutomationStatus,
ScopedThreadRef,
} from "@t3tools/contracts";
import { useCallback, useEffect, useId, useRef } from "react";
import { useCallback, useEffect, useEffectEvent, useId, useMemo, useRef, useState } from "react";
import {
applyPreviewServerSnapshot,
@@ -20,11 +21,14 @@ import { useRightPanelStore } from "~/rightPanelStore";
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
import { startBrowserRecording, stopBrowserRecording } from "~/browser/browserRecording";
import { previewEnvironment } from "~/state/preview";
import { useEnvironmentQuery } from "~/state/query";
import { useEnvironmentConnectionState } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
import {
createLatestPreviewAutomationRequestHandler,
createPreviewAutomationRequestConsumerAtom,
} from "./previewAutomationRequestConsumer";
export function observeAutomationOwnerConnectedGeneration(
previousGeneration: number | null,
@@ -41,7 +45,7 @@ export function observeAutomationOwnerConnectedGeneration(
}
return {
nextGeneration: connectedGeneration,
shouldReport: previousGeneration !== null && previousGeneration !== connectedGeneration,
shouldReport: previousGeneration !== connectedGeneration,
};
}
@@ -109,24 +113,10 @@ const currentStatus = async (
};
};
const serializeError = (error: unknown): NonNullable<PreviewAutomationResponse["error"]> => {
if (error instanceof Error) {
const detail =
"detail" in error && (error as { detail?: unknown }).detail !== undefined
? (error as { detail?: unknown }).detail
: undefined;
return {
_tag: error.name.startsWith("PreviewAutomation")
? error.name
: "PreviewAutomationExecutionError",
message: error.message,
...(detail === undefined ? {} : { detail }),
};
}
return {
_tag: "PreviewAutomationExecutionError",
message: String(error),
};
const previewTabNotFoundError = (): Error => {
const error = new Error("Preview tab is not initialized.");
error.name = "PreviewAutomationTabNotFoundError";
return error;
};
export function PreviewAutomationOwner(props: {
@@ -135,12 +125,22 @@ export function PreviewAutomationOwner(props: {
}) {
const { threadRef, visible } = props;
const automationClientId = useId();
const automationRequests = useEnvironmentQuery(
previewEnvironment.automationRequests({
const initialAutomationOwner = useMemo<PreviewAutomationOwnerState>(
() => ({
clientId: automationClientId,
environmentId: threadRef.environmentId,
input: { clientId: automationClientId },
threadId: threadRef.threadId,
tabId: null,
visible: false,
supportsAutomation: Boolean(previewBridge?.automation),
focusedAt: new Date().toISOString(),
}),
[automationClientId, threadRef.environmentId, threadRef.threadId],
);
const automationRequestsAtom = previewEnvironment.automationRequests({
environmentId: threadRef.environmentId,
input: initialAutomationOwner,
});
const connectionState = useEnvironmentConnectionState(threadRef.environmentId).data;
const connectedGeneration =
connectionState?.phase === "connected" ? connectionState.generation : null;
@@ -159,13 +159,24 @@ export function PreviewAutomationOwner(props: {
previewEnvironment.clearAutomationOwner,
"preview automation owner clear",
);
const ownerStateRef = useRef({ threadRef, visible });
const connectedGenerationRef = useRef<number | null>(null);
const handlerRef = useRef<(request: PreviewAutomationRequest) => Promise<unknown>>(
async () => undefined,
);
const reportCurrentAutomationOwner = useEffectEvent(() => {
const state = readThreadPreviewState(threadRef);
return reportAutomationOwner({
environmentId: threadRef.environmentId,
input: {
clientId: automationClientId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId: state.snapshot?.tabId ?? null,
visible,
supportsAutomation: Boolean(previewBridge?.automation),
focusedAt: new Date().toISOString(),
},
});
});
useEffect(() => {
ownerStateRef.current = { threadRef, visible };
void reportCurrentAutomationOwner();
}, [threadRef, visible]);
const handleRequest = useCallback(
@@ -208,7 +219,7 @@ export function PreviewAutomationOwner(props: {
return currentStatus(threadRef, input.show ?? true);
}
case "navigate": {
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
const input = request.input as PreviewAutomationNavigateInput;
const resolution = resolveBrowserNavigationTarget(
threadRef.environmentId,
@@ -223,46 +234,46 @@ export function PreviewAutomationOwner(props: {
return currentStatus(threadRef, visible);
}
case "snapshot":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.snapshot(tabId);
case "click":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.click(
tabId,
request.input as Parameters<typeof previewBridge.automation.click>[1],
);
case "type":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.type(
tabId,
request.input as Parameters<typeof previewBridge.automation.type>[1],
);
case "press":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.press(
tabId,
request.input as Parameters<typeof previewBridge.automation.press>[1],
);
case "scroll":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.scroll(
tabId,
request.input as Parameters<typeof previewBridge.automation.scroll>[1],
);
case "evaluate":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.evaluate(
tabId,
request.input as Parameters<typeof previewBridge.automation.evaluate>[1],
);
case "waitFor":
if (!previewBridge || !tabId) throw new Error("Preview tab is not initialized.");
if (!previewBridge || !tabId) throw previewTabNotFoundError();
return previewBridge.automation.waitFor(
tabId,
request.input as Parameters<typeof previewBridge.automation.waitFor>[1],
);
case "recordingStart": {
if (!tabId) throw new Error("Preview tab is not initialized.");
if (!tabId) throw previewTabNotFoundError();
const startedAt = await startBrowserRecording(tabId);
return {
tabId,
@@ -271,7 +282,7 @@ export function PreviewAutomationOwner(props: {
};
}
case "recordingStop": {
if (!tabId) throw new Error("Preview tab is not initialized.");
if (!tabId) throw previewTabNotFoundError();
const artifact = await stopBrowserRecording(tabId);
if (!artifact) throw new Error("No active recording exists for this preview tab.");
return artifact;
@@ -280,34 +291,34 @@ export function PreviewAutomationOwner(props: {
},
[open, threadRef, visible],
);
const [requestHandler] = useState(() =>
createLatestPreviewAutomationRequestHandler(handleRequest),
);
useEffect(() => {
handlerRef.current = handleRequest;
}, [handleRequest]);
requestHandler.set(handleRequest);
}, [handleRequest, requestHandler]);
useEffect(() => {
const request = automationRequests.data;
if (!request) return;
void handlerRef.current(request).then(
(result) =>
respondToAutomation({
environmentId: threadRef.environmentId,
input: {
requestId: request.requestId,
ok: true,
...(result === undefined ? {} : { result }),
},
}),
(error) =>
respondToAutomation({
environmentId: threadRef.environmentId,
input: {
requestId: request.requestId,
ok: false,
error: serializeError(error),
},
}),
);
}, [automationRequests.data, respondToAutomation, threadRef.environmentId]);
const automationRequestConsumerAtom = useMemo(
() =>
createPreviewAutomationRequestConsumerAtom({
requestsAtom: automationRequestsAtom,
handleRequest: requestHandler.handle,
respond: (response) =>
respondToAutomation({
environmentId: threadRef.environmentId,
input: response,
}),
label: `preview:automation-request-consumer:${automationClientId}`,
}),
[
automationClientId,
automationRequestsAtom,
requestHandler,
respondToAutomation,
threadRef.environmentId,
],
);
useAtomValue(automationRequestConsumerAtom);
useEffect(() => {
const observation = observeAutomationOwnerConnectedGeneration(
@@ -317,39 +328,11 @@ export function PreviewAutomationOwner(props: {
connectedGenerationRef.current = observation.nextGeneration;
if (!observation.shouldReport) return;
const ownerState = ownerStateRef.current;
const state = readThreadPreviewState(ownerState.threadRef);
void reportAutomationOwner({
environmentId: ownerState.threadRef.environmentId,
input: {
clientId: automationClientId,
environmentId: ownerState.threadRef.environmentId,
threadId: ownerState.threadRef.threadId,
tabId: state.snapshot?.tabId ?? null,
visible: ownerState.visible,
supportsAutomation: Boolean(previewBridge?.automation),
focusedAt: new Date().toISOString(),
},
});
}, [automationClientId, connectedGeneration, reportAutomationOwner]);
void reportCurrentAutomationOwner();
}, [connectedGeneration]);
useEffect(() => {
const report = () => {
const state = readThreadPreviewState(threadRef);
void reportAutomationOwner({
environmentId: threadRef.environmentId,
input: {
clientId: automationClientId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId: state.snapshot?.tabId ?? null,
visible,
supportsAutomation: Boolean(previewBridge?.automation),
focusedAt: new Date().toISOString(),
},
});
};
report();
const report = () => void reportCurrentAutomationOwner();
window.addEventListener("focus", report);
const unsubscribe = subscribeThreadPreviewState(threadRef, (state, previous) => {
if (state.snapshot?.tabId !== previous.snapshot?.tabId) {
@@ -361,10 +344,14 @@ export function PreviewAutomationOwner(props: {
unsubscribe();
void clearAutomationOwner({
environmentId: threadRef.environmentId,
input: { clientId: automationClientId },
input: {
clientId: automationClientId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
},
});
};
}, [automationClientId, clearAutomationOwner, reportAutomationOwner, threadRef, visible]);
}, [automationClientId, clearAutomationOwner, threadRef]);
return null;
}
@@ -0,0 +1,81 @@
import type { PreviewAutomationRequest, PreviewAutomationResponse } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { describe, expect, it, vi } from "vite-plus/test";
import {
createPreviewAutomationRequestConsumerAtom,
serializePreviewAutomationError,
} from "./previewAutomationRequestConsumer";
const request = (requestId: string): PreviewAutomationRequest => ({
requestId,
threadId: ThreadId.make("thread-1"),
operation: "status",
input: {},
timeoutMs: 15_000,
});
describe("previewAutomationRequestConsumer", () => {
it("consumes every request emitted before React can render", async () => {
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationRequest, Error>>(
AsyncResult.initial<PreviewAutomationRequest, Error>(false),
);
const handleRequest = vi.fn(async (value: PreviewAutomationRequest) => ({
requestId: value.requestId,
}));
const responses: PreviewAutomationResponse[] = [];
const respond = vi.fn(async (response: PreviewAutomationResponse) => {
responses.push(response);
});
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
handleRequest,
respond,
label: "test:preview-automation-consumer",
});
const registry = AtomRegistry.make();
registry.mount(consumerAtom);
registry.set(requestsAtom, AsyncResult.success(request("request-1")));
registry.set(requestsAtom, AsyncResult.success(request("request-2")));
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(2));
expect(handleRequest.mock.calls.map(([value]) => value.requestId)).toEqual([
"request-1",
"request-2",
]);
expect(responses.map((response) => response.requestId)).toEqual(["request-1", "request-2"]);
registry.dispose();
});
it("consumes a request that arrived immediately before the consumer mounted", async () => {
const requestsAtom = Atom.make(
AsyncResult.success<PreviewAutomationRequest, Error>(request("request-ready")),
);
const respond = vi.fn(async (_response: PreviewAutomationResponse) => undefined);
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
handleRequest: async () => undefined,
respond,
label: "test:preview-automation-initial-request",
});
const registry = AtomRegistry.make();
registry.mount(consumerAtom);
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
expect(respond).toHaveBeenCalledWith({ requestId: "request-ready", ok: true });
registry.dispose();
});
it("preserves typed automation errors in responses", () => {
const error = new Error("No preview tab");
error.name = "PreviewAutomationTabNotFoundError";
expect(serializePreviewAutomationError(error)).toEqual({
_tag: "PreviewAutomationTabNotFoundError",
message: "No preview tab",
});
});
});
@@ -0,0 +1,83 @@
import type { PreviewAutomationRequest, PreviewAutomationResponse } from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
type AutomationRequestResult<E> = AsyncResult.AsyncResult<PreviewAutomationRequest, E>;
type AutomationRequestHandler = (request: PreviewAutomationRequest) => Promise<unknown>;
export function createLatestPreviewAutomationRequestHandler(initial: AutomationRequestHandler): {
readonly set: (handler: AutomationRequestHandler) => void;
readonly handle: AutomationRequestHandler;
} {
let current = initial;
return {
set: (handler) => {
current = handler;
},
handle: (request) => current(request),
};
}
export function serializePreviewAutomationError(
error: unknown,
): NonNullable<PreviewAutomationResponse["error"]> {
if (error instanceof Error) {
const detail =
"detail" in error && (error as { detail?: unknown }).detail !== undefined
? (error as { detail?: unknown }).detail
: undefined;
return {
_tag: error.name.startsWith("PreviewAutomation")
? error.name
: "PreviewAutomationExecutionError",
message: error.message,
...(detail === undefined ? {} : { detail }),
};
}
return {
_tag: "PreviewAutomationExecutionError",
message: String(error),
};
}
export function createPreviewAutomationRequestConsumerAtom<E>(options: {
readonly requestsAtom: Atom.Atom<AutomationRequestResult<E>>;
readonly handleRequest: (request: PreviewAutomationRequest) => Promise<unknown>;
readonly respond: (response: PreviewAutomationResponse) => Promise<unknown>;
readonly label: string;
}): Atom.Atom<void> {
return Atom.make((get) => {
let disposed = false;
let requestsVersion = 0;
const consume = (result: AutomationRequestResult<E>) => {
if (!AsyncResult.isSuccess(result)) return;
const request = result.value;
void options.handleRequest(request).then(
(value) =>
options.respond({
requestId: request.requestId,
ok: true,
...(value === undefined ? {} : { result: value }),
}),
(error) =>
options.respond({
requestId: request.requestId,
ok: false,
error: serializePreviewAutomationError(error),
}),
);
};
get.addFinalizer(() => {
disposed = true;
});
const initialRequest = get.once(options.requestsAtom);
get.subscribe(options.requestsAtom, (result) => {
requestsVersion += 1;
consume(result);
});
queueMicrotask(() => {
if (!disposed && requestsVersion === 0) consume(initialRequest);
});
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(options.label));
}
@@ -37,6 +37,10 @@ export function createPreviewEnvironmentAtoms<R, E>(
automationRequests: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
label: "environment-data:preview:automation-requests",
tag: WS_METHODS.previewAutomationConnect,
// Automation requests are commands, not cached query data. Dispose the
// stream immediately with its owner so stale requests cannot replay when
// a thread remounts and the server can clear disconnected hosts promptly.
idleTtlMs: 0,
}),
open: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:open",
+2 -1
View File
@@ -75,6 +75,7 @@ import {
PreviewAutomationClickInput,
PreviewAutomationEvaluateInput,
PreviewAutomationOwner,
PreviewAutomationOwnerIdentity,
PreviewAutomationPressInput,
PreviewAutomationRequest,
PreviewAutomationResponse,
@@ -1165,7 +1166,7 @@ export interface EnvironmentApi {
) => () => void;
respond: (response: PreviewAutomationResponse) => Promise<void>;
reportOwner: (owner: PreviewAutomationOwner) => Promise<void>;
clearOwner: (input: { clientId: string }) => Promise<void>;
clearOwner: (input: PreviewAutomationOwnerIdentity) => Promise<void>;
};
onEvent: (
callback: (event: PreviewEvent) => void,
+6 -1
View File
@@ -410,10 +410,15 @@ export const PreviewAutomationRecordingArtifact = Schema.Struct({
});
export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
export const PreviewAutomationOwner = Schema.Struct({
export const PreviewAutomationOwnerIdentity = Schema.Struct({
clientId: TrimmedNonEmptyString,
environmentId: EnvironmentId,
threadId: ThreadId,
});
export type PreviewAutomationOwnerIdentity = typeof PreviewAutomationOwnerIdentity.Type;
export const PreviewAutomationOwner = Schema.Struct({
...PreviewAutomationOwnerIdentity.fields,
tabId: Schema.NullOr(PreviewTabId),
visible: Schema.Boolean,
supportsAutomation: Schema.Boolean,
+3 -2
View File
@@ -108,6 +108,7 @@ import {
import {
PreviewAutomationError,
PreviewAutomationOwner,
PreviewAutomationOwnerIdentity,
PreviewAutomationRequest,
PreviewAutomationResponse,
} from "./previewAutomation.ts";
@@ -549,7 +550,7 @@ export const WsPreviewReportStatusRpc = Rpc.make(WS_METHODS.previewReportStatus,
});
export const WsPreviewAutomationConnectRpc = Rpc.make(WS_METHODS.previewAutomationConnect, {
payload: Schema.Struct({ clientId: Schema.String }),
payload: PreviewAutomationOwner,
success: PreviewAutomationRequest,
error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),
stream: true,
@@ -566,7 +567,7 @@ export const WsPreviewAutomationReportOwnerRpc = Rpc.make(WS_METHODS.previewAuto
});
export const WsPreviewAutomationClearOwnerRpc = Rpc.make(WS_METHODS.previewAutomationClearOwner, {
payload: Schema.Struct({ clientId: Schema.String }),
payload: PreviewAutomationOwnerIdentity,
error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),
});
+250 -252
View File
File diff suppressed because it is too large. Load diff