Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions apps/server/src/preview/DesktopBrowserChannel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeStream from "@effect/platform-node/NodeStream";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
Expand Down Expand Up @@ -66,6 +67,47 @@ it.effect("protects unknown desktop visibility until an explicit hidden report a
),
);

it.effect("awaitShown resolves once a hidden tab is reported shown", () =>
Effect.gen(function* () {
const input = yield* Queue.unbounded<Uint8Array>();
vi.mocked(NodeStream.fromReadable).mockReturnValue(Stream.fromQueue(input));
const config = yield* ServerConfig.ServerConfig;
yield* Effect.gen(function* () {
const channel = yield* DesktopBrowserChannel.DesktopBrowserChannel;
const key = { threadId: "thread-1", tabId: "tab-1" };
const send = (event: object) =>
Queue.offer(
input,
new TextEncoder().encode(`${JSON.stringify(event)}
`),
);

expect(yield* channel.awaitShown(key, "5 seconds")).toBe(true);
yield* send({ type: "shown", ...key, shown: false });
yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel" });
yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel" }, "5 seconds");

const shown = yield* channel.awaitShown(key, "5 seconds").pipe(Effect.forkChild);
yield* send({ type: "shown", ...key, shown: true });
expect(yield* Fiber.join(shown)).toBe(true);
}).pipe(
Effect.provide(
DesktopBrowserChannel.layer.pipe(
Layer.provide(
ServerConfig.layer({ ...config, desktopBrowserFd: 41, desktopBrowserControlFd: 42 }),
),
),
),
);
}).pipe(
Effect.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "desktop-browser-channel-" }).pipe(
Layer.provide(NodeServices.layer),
),
),
),
);

it.live("closes a tab's relay connection when the desktop detaches the tab", () =>
Effect.gen(function* () {
const input = yield* Queue.unbounded<Uint8Array>();
Expand Down
23 changes: 22 additions & 1 deletion apps/server/src/preview/DesktopBrowserChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ export class DesktopBrowserChannel extends Context.Service<
readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
/** Whether a desktop window draws the tab on screen, which no streamed viewer counts. */
readonly isShown: (key: DesktopTabKey) => boolean;
/** Resolves true once the desktop reports the tab shown; subscribes before checking, like awaitAttached. */
readonly awaitShown: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect<boolean>;
/** A load failure the desktop saw, possibly before the server connected to the tab. */
readonly loadFailure: (key: DesktopTabKey) => PreviewAutomationLoadError | undefined;
readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
Expand All @@ -64,6 +66,7 @@ const make = Effect.gen(function* () {
const inputFd = config.desktopBrowserFd;
const controlFd = config.desktopBrowserControlFd;
const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
const shownChanges = yield* PubSub.unbounded<{ key: DesktopTabKey; shown: boolean }>();
const attachedTabs = new Set<string>();
// Missing reports protect desktop tabs until the renderer explicitly marks them hidden.
const shownTabs = new Map<string, boolean>();
Expand Down Expand Up @@ -92,6 +95,9 @@ const make = Effect.gen(function* () {
return Effect.void;
}),
isShown: () => false,
awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function () {
return Effect.succeed(false);
}),
loadFailure: () => undefined,
});
}
Expand Down Expand Up @@ -149,7 +155,7 @@ const make = Effect.gen(function* () {
}
case "shown":
shownTabs.set(id, event.shown);
return Effect.void;
return PubSub.publish(shownChanges, { key, shown: event.shown });
}
}),
Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
Expand Down Expand Up @@ -253,6 +259,21 @@ const make = Effect.gen(function* () {
return Effect.sync(() => attachedTabs.has(keyOf(key)));
}),
isShown: (key) => shownTabs.get(keyOf(key)) ?? true,
awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function (key, timeout) {
return Effect.scoped(
Effect.gen(function* () {
const subscription = yield* PubSub.subscribe(shownChanges);
if (shownTabs.get(keyOf(key)) ?? true) return true;
return yield* Stream.fromSubscription(subscription).pipe(
Stream.filter((change) => change.shown && keyOf(change.key) === keyOf(key)),
Stream.runHead,
Effect.map(Option.isSome),
Effect.timeoutOption(timeout),
Effect.map((result) => Option.getOrElse(result, () => false)),
);
}),
);
}),
loadFailure: (key) => loadFailures.get(keyOf(key)),
endpoint,
turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {
Expand Down
82 changes: 82 additions & 0 deletions apps/server/src/preview/ServerBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,12 @@ const desktopRenders = (tabId: string) => {
let desktopAttachesLate = false;
let desktopAttachWaiting = Promise.withResolvers<void>();
const shownDesktopTabs = new Set<string>();
/** Marks a desktop tab shown the way the renderer's report does. */
const showDesktopTab = (tabId: string) => {
shownDesktopTabs.add(tabId);
desktopDetaches.emit("shown", tabId);
};
let desktopShowWaiting = Promise.withResolvers<void>();
const releasedDesktopTabs: Array<string> = [];
const desktopLoadFailures = new Map<string, PreviewAutomationLoadError>();
const desktopTurns = new NodeEvents.EventEmitter();
Expand Down Expand Up @@ -509,6 +515,28 @@ const dependencies = Layer.mergeAll(
),
isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
isShown: (key) => shownDesktopTabs.has(key.tabId),
awaitShown: (key, timeout) =>
Effect.raceFirst(
Stream.callback<string>((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
const onShown = (tabId: string) => Queue.offerUnsafe(queue, tabId);
desktopDetaches.on("shown", onShown);
if (shownDesktopTabs.has(key.tabId)) Queue.offerUnsafe(queue, key.tabId);
return onShown;
}),
(onShown) => Effect.sync(() => desktopDetaches.off("shown", onShown)),
),
).pipe(
Stream.filter((tabId) => tabId === key.tabId),
Stream.runHead,
Effect.as(true),
),
Effect.sync(() => desktopShowWaiting.resolve()).pipe(
Effect.andThen(Effect.sleep(timeout)),
Effect.as(false),
),
),
loadFailure: (key) => desktopLoadFailures.get(key.tabId),
endpoint: (key) =>
Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () =>
Expand Down Expand Up @@ -592,6 +620,7 @@ beforeEach(() => {
focusedFrame = null;
desktopTabs.clear();
shownDesktopTabs.clear();
desktopShowWaiting = Promise.withResolvers<void>();
desktopLoadFailures.clear();
desktopRendersNext = false;
desktopAttachesLate = false;
Expand Down Expand Up @@ -3303,6 +3332,59 @@ it.effect("preview_open reports a tab it shows as visible once the client attach
).pipe(Effect.provide(layer)),
);

it.effect(
"preview_open reports a hidden desktop tab it reveals as visible once the desktop shows it",
() =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* Broker.PreviewAutomationBroker;
const manager = yield* Manager.PreviewManager;
const events = yield* manager.subscribeEvents;
yield* ServerBrowser.ServerBrowser;
yield* Effect.yieldNow;
// Like the renderer, the desktop reports the tab shown a round trip after the reveal.
yield* Effect.gen(function* () {
let event;
do event = yield* PubSub.take(events);
while (event.type !== "navigated" || !event.snapshot.revealRequest);
yield* Effect.promise(() => desktopShowWaiting.promise);
showDesktopTab(event.tabId);
}).pipe(Effect.forkScoped);

desktopRendersNext = true;
const opened = yield* broker.invoke<PreviewAutomationStatus>({
scope,
operation: "open",
input: { reuseExistingTab: false, open: true },
});

expect(opened.visible).toBe(true);
}),
).pipe(Effect.provide(layer)),
);

it.effect("preview_open stops waiting for a desktop tab that never shows", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* Broker.PreviewAutomationBroker;
yield* ServerBrowser.ServerBrowser;
yield* Effect.yieldNow;
desktopRendersNext = true;
const opening = yield* broker
.invoke<PreviewAutomationStatus>({
scope,
operation: "open",
input: { reuseExistingTab: false, open: true },
})
.pipe(Effect.forkScoped);
yield* Effect.promise(() => desktopShowWaiting.promise);
yield* TestClock.adjust("1 second");

expect((yield* Fiber.join(opening)).visible).toBe(false);
}),
).pipe(Effect.provide(layer)),
);

it.effect("a session's own tab stays its default while other sessions' tabs are listed", () =>
Effect.scoped(
Effect.gen(function* () {
Expand Down
9 changes: 6 additions & 3 deletions apps/server/src/preview/ServerBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2649,10 +2649,13 @@ const make = Effect.gen(function* () {
}),
);
// Only an explicit show is sure to reach a client; desktop tabs are visible without a viewer.
const waitMs = Math.min(REVEAL_VIEWER_WAIT_MS, deadlineMs - performance.now());
if (reveal === true && tab.viewers.size === 0 && tab.desktop === null)
shown = awaitViewer(
tab,
Math.min(REVEAL_VIEWER_WAIT_MS, deadlineMs - performance.now()),
shown = awaitViewer(tab, waitMs);
// A desktop tab mounted hidden keeps reporting hidden until its panel opens.
else if (reveal === true && tab.desktop !== null && !isVisible(tab))
shown = runPromise(desktopChannel.awaitShown(tab, Math.max(0, waitMs))).then(
constVoid,
);
}
await shown;
Expand Down
Loading