Skip to content
Merged
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
5 changes: 3 additions & 2 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 @@ -38,9 +39,9 @@ it.effect("protects unknown desktop visibility until an explicit hidden report a
yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-1" }, "5 seconds");
expect(channel.isShown(key)).toBe(false);

const shown = yield* channel.awaitShown(key, "5 seconds").pipe(Effect.forkChild);
yield* send({ type: "shown", ...key, shown: true });
yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel-2" });
yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-2" }, "5 seconds");
expect(yield* Fiber.join(shown)).toBe(true);
expect(channel.isShown(key)).toBe(true);

yield* send({ type: "shown", ...key, shown: false });
Expand Down
27 changes: 25 additions & 2 deletions 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 tab is shown, or false on timeout. */
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 @@ -67,6 +69,7 @@ const make = Effect.gen(function* () {
const attachedTabs = new Set<string>();
// Missing reports protect desktop tabs until the renderer explicitly marks them hidden.
const shownTabs = new Map<string, boolean>();
const shownReports = yield* PubSub.unbounded<string>();
const loadFailures = new Map<string, PreviewAutomationLoadError>();
const inbound = new Map<string, Queue.Queue<string>>();
const writeLock = yield* Semaphore.make(1);
Expand All @@ -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 event.shown ? PubSub.publish(shownReports, id) : Effect.void;
}
}),
Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
Expand Down Expand Up @@ -224,6 +230,8 @@ const make = Effect.gen(function* () {
return `ws://127.0.0.1:${address.port}/${secret}`;
});

const isShown = (key: DesktopTabKey) => shownTabs.get(keyOf(key)) ?? true;

return DesktopBrowserChannel.of({
available: true,
awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function (key, timeout) {
Expand Down Expand Up @@ -252,7 +260,22 @@ const make = Effect.gen(function* () {
isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) {
return Effect.sync(() => attachedTabs.has(keyOf(key)));
}),
isShown: (key) => shownTabs.get(keyOf(key)) ?? true,
isShown,
awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function (key, timeout) {
return Effect.scoped(
Effect.gen(function* () {
const subscription = yield* PubSub.subscribe(shownReports);
if (isShown(key)) return true;
return yield* Stream.fromSubscription(subscription).pipe(
Stream.filter((id) => id === 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
57 changes: 56 additions & 1 deletion apps/server/src/preview/ServerBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,13 @@ const desktopRenders = (tabId: string) => {
/** When set, a desktop that has not attached a tab waits for it the way the real channel does. */
let desktopAttachesLate = false;
let desktopAttachWaiting = Promise.withResolvers<void>();
const shownDesktopTabs = new Set<string>();
const shownDesktopTabs = new (class extends Set<string> {
override add(tabId: string) {
super.add(tabId);
desktopDetaches.emit("shown", tabId);
return this;
}
})();
const releasedDesktopTabs: Array<string> = [];
const desktopLoadFailures = new Map<string, PreviewAutomationLoadError>();
const desktopTurns = new NodeEvents.EventEmitter();
Expand Down Expand Up @@ -509,6 +515,16 @@ const dependencies = Layer.mergeAll(
),
isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
isShown: (key) => shownDesktopTabs.has(key.tabId),
awaitShown: (key, timeout) =>
shownDesktopTabs.has(key.tabId)
? Effect.succeed(true)
: Effect.callback<boolean>((resume) => {
const onShown = (tabId: string) => {
if (tabId === key.tabId) resume(Effect.succeed(true));
};
desktopDetaches.on("shown", onShown);
return Effect.sync(() => desktopDetaches.off("shown", onShown));
}).pipe(Effect.timeoutOrElse({ duration: timeout, orElse: () => Effect.succeed(false) })),
loadFailure: (key) => desktopLoadFailures.get(key.tabId),
endpoint: (key) =>
Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () =>
Expand Down Expand Up @@ -3303,6 +3319,45 @@ 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", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* Broker.PreviewAutomationBroker;
const manager = yield* Manager.PreviewManager;
yield* ServerBrowser.ServerBrowser;
const events = yield* manager.subscribeEvents;
yield* Effect.yieldNow;
desktopRendersNext = true;
const created = yield* broker.invoke<PreviewAutomationStatus>({
scope,
operation: "open",
input: { reuseExistingTab: false, open: false },
});
const tabId = PreviewTabId.make(created.tabId!);
expect(created.visible).toBe(false);
// Like the desktop renderer, the docked panel reports the tab shown after the reveal arrives.
yield* Effect.gen(function* () {
let event;
do event = yield* PubSub.take(events);
while (event.type !== "navigated" || !event.snapshot.revealRequest);
// The report crosses the client, the desktop main process and its pipe, so it lands a task later.
yield* Effect.yieldNow;
yield* Effect.sync(() => shownDesktopTabs.add(tabId));
}).pipe(Effect.forkScoped);

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

expect(opened.visible).toBe(true);
expect(opened.tabs).toEqual([expect.objectContaining({ tabId, visible: true })]);
}),
).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
16 changes: 12 additions & 4 deletions apps/server/src/preview/ServerBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ const DESKTOP_VIEWPORT_READ_TIMEOUT = "1 second";
const DESKTOP_RESIZE_WAIT_MS = 1000;
// A revealed tab's client opens the panel and attaches its stream a few round trips later, remote ones included.
const REVEAL_VIEWER_WAIT_MS = 1000;
// A desktop panel's shown report waits on the renderer's layout, which a busy machine can push past a second.
const REVEAL_DESKTOP_SHOWN_WAIT_MS = 3000;

const sleepUntil = (deadline: number) =>
new Promise<void>((resolve) => setTimeout(resolve, Math.max(0, deadline - Date.now())));
Expand Down Expand Up @@ -2649,11 +2651,17 @@ const make = Effect.gen(function* () {
}),
);
// Only an explicit show is sure to reach a client; desktop tabs are visible without a viewer.
const remainingMs = 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, Math.min(REVEAL_VIEWER_WAIT_MS, remainingMs));
// A desktop panel reports the revealed tab shown a few hops after the reveal.
else if (reveal === true && !isVisible(tab))
shown = runPromise(
desktopChannel.awaitShown(
tab,
Math.max(0, Math.min(REVEAL_DESKTOP_SHOWN_WAIT_MS, remainingMs)),
),
).then(constVoid);
}
await shown;
return statusWithTitle(tab, request.agentSessionId);
Expand Down
Loading