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
51 changes: 49 additions & 2 deletions apps/server/src/preview/ServerBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
type PreviewAutomationStatus,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -559,8 +561,9 @@ it.live.each([
Effect.scoped(
Effect.gen(function* () {
const { browser, broker, tabId } = yield* ready;
const reportProfiles = yield* browser.profileReporter;
for (const recordingFrameRate of reports) {
yield* browser.reportProfiles({
yield* reportProfiles({
profiles: [],
defaultProfileId: "default",
...(recordingFrameRate === undefined ? {} : { recordingFrameRate }),
Expand Down Expand Up @@ -1256,7 +1259,8 @@ it.live(
const broker = yield* Broker.PreviewAutomationBroker;
const manager = yield* Manager.PreviewManager;
yield* Effect.yieldNow;
yield* browser.reportProfiles({
const reportProfiles = yield* browser.profileReporter;
yield* reportProfiles({
profiles: [{ id: "profile-work", name: "Work", kind: "persistent" }],
defaultProfileId: "profile-work",
});
Expand Down Expand Up @@ -1301,3 +1305,46 @@ it.live(
}),
).pipe(Effect.provide(layer)),
);

it.live("profiles reported by one client survive another client's report", () =>
Effect.scoped(
Effect.gen(function* () {
const { browser, broker } = yield* ready;
contextRequests.length = 0;
const work = { id: "profile-work", name: "Work", kind: "persistent" } as const;
const shared = { id: "profile-shared", name: "Shared", kind: "persistent" } as const;
const openWork = () =>
broker.invoke<PreviewAutomationStatus>({
scope,
operation: "open",
input: { reuseExistingTab: false, show: false, profileId: work.id },
});
const reportFromA = yield* browser.profileReporter;
const clientB = yield* Scope.make();
const reportFromB = yield* browser.profileReporter.pipe(
Effect.provideService(Scope.Scope, clientB),
);
yield* reportFromA({ profiles: [work, shared], defaultProfileId: work.id });
yield* reportFromB({ profiles: [shared], defaultProfileId: shared.id });
expect(yield* openWork()).toMatchObject({
defaultProfileId: shared.id,
profiles: [
{ id: "default", name: "Default" },
{ id: "incognito", name: "Incognito", incognito: true },
{ id: work.id, name: work.name },
{ id: shared.id, name: shared.name },
],
});
expect(contextRequests).toEqual([{ profileId: work.id, isolated: false }]);
yield* Scope.close(clientB, Exit.void);
expect(yield* openWork()).toMatchObject({ defaultProfileId: work.id });
yield* reportFromA({ profiles: [shared], defaultProfileId: shared.id });
const removed = yield* openWork().pipe(Effect.flip);
expect(removed).toMatchObject({
_tag: "PreviewAutomationExecutionError",
reason:
'No browser profile is named "profile-work". Use one of: Default (id default), Incognito (id incognito), Shared (id profile-shared).',
});
}),
).pipe(Effect.provide(layer)),
);
57 changes: 45 additions & 12 deletions apps/server/src/preview/ServerBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ export interface ServerBrowserViewer {
readonly input: (message: unknown) => Effect.Effect<void>;
}

export type ProfileReporter = (input: PreviewReportProfilesInput) => Effect.Effect<void>;

export class ServerBrowser extends Context.Service<
ServerBrowser,
{
Expand Down Expand Up @@ -241,7 +243,7 @@ export class ServerBrowser extends Context.Service<

readonly clearProfile: (profileId: string) => Effect.Effect<void, PreviewClearProfileError>;

readonly reportProfiles: (input: PreviewReportProfilesInput) => Effect.Effect<void>;
readonly profileReporter: Effect.Effect<ProfileReporter, never, Scope.Scope>;
}
>()("t3/preview/ServerBrowser") {}

Expand Down Expand Up @@ -1306,6 +1308,8 @@ const make = Effect.gen(function* () {
? ("agent" as const)
: ("unclaimed" as const);

const reportsByClient = new Map<number, PreviewReportProfilesInput>();
let nextClient = 0;
let reportedProfiles: {
readonly profiles: ReadonlyArray<BrowserProfile>;
readonly defaultProfileId: string;
Expand All @@ -1314,16 +1318,45 @@ const make = Effect.gen(function* () {
// last report outlives the client, which lets agents record while no client is connected.
let recordingFrameRate = DEFAULT_BROWSER_RECORDING_FRAME_RATE;

const reportProfiles: ServerBrowser["Service"]["reportProfiles"] = (input) =>
Effect.sync(() => {
if (input.recordingFrameRate !== undefined) recordingFrameRate = input.recordingFrameRate;
const profiles = resolveBrowserProfiles(input.profiles);
reportedProfiles = {
profiles,
defaultProfileId:
findBrowserProfile(profiles, input.defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID,
};
});
// Each client reports only the profiles in its own settings, so the catalog is
// their union while they stay connected. The last catalog stays usable after
// every client disconnects, as a single report did before.
const rebuildReportedProfiles = () => {
const byId = new Map<string, BrowserProfile>();
let latest: PreviewReportProfilesInput | undefined;
for (const report of reportsByClient.values()) {
for (const profile of report.profiles) byId.set(profile.id, profile);
latest = report;
}
if (latest === undefined) return;
const profiles = resolveBrowserProfiles([...byId.values()]);
reportedProfiles = {
profiles,
defaultProfileId:
findBrowserProfile(profiles, latest.defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID,
};
};

const profileReporter: ServerBrowser["Service"]["profileReporter"] = Effect.acquireRelease(
Effect.sync(() => nextClient++),
(client) =>
Effect.sync(() => {
reportsByClient.delete(client);
rebuildReportedProfiles();
}),
).pipe(
Effect.map(
(client): ProfileReporter =>
(input) =>
Effect.sync(() => {
if (input.recordingFrameRate !== undefined)
recordingFrameRate = input.recordingFrameRate;
reportsByClient.delete(client);
reportsByClient.set(client, input);
rebuildReportedProfiles();
}),
),
);

const profileStatus = () => {
const profiles = reportedProfiles?.profiles ?? BUILT_IN_BROWSER_PROFILES;
Expand Down Expand Up @@ -2533,7 +2566,7 @@ const make = Effect.gen(function* () {
return ServerBrowser.of({
attachViewer,
clearProfile,
reportProfiles,
profileReporter,
openDownload,
answerFileChooser,
});
Expand Down
12 changes: 6 additions & 6 deletions apps/server/src/preview/ServerBrowserStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ it.effect.each([
});
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
profileReporter: Effect.succeed(() => Effect.void),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: (input) =>
Expand Down Expand Up @@ -163,7 +163,7 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a
});
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
profileReporter: Effect.succeed(() => Effect.void),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: () => Effect.succeed({ output, input: () => Effect.void }),
Expand Down Expand Up @@ -234,7 +234,7 @@ it.effect.each([
let attachments = 0;
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
profileReporter: Effect.succeed(() => Effect.void),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: () => {
Expand Down Expand Up @@ -275,7 +275,7 @@ it.effect("serves a tab's download only to an authorized session", () =>
const requests: Array<unknown> = [];
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
profileReporter: Effect.succeed(() => Effect.void),
openDownload: (input) =>
Effect.sync(() => {
requests.push(input);
Expand Down Expand Up @@ -323,7 +323,7 @@ it.effect("passes uploaded files to the page's open picker and needs operate sco
const answers: Array<{ chooserId: string; files: Array<{ name: string; text: string }> }> = [];
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
profileReporter: Effect.succeed(() => Effect.void),
openDownload: () => Effect.succeedNone,
answerFileChooser: (input) =>
Effect.sync(() => {
Expand Down Expand Up @@ -392,7 +392,7 @@ it.effect.each([
Effect.gen(function* () {
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
profileReporter: Effect.succeed(() => Effect.void),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: () => Effect.fail(new ServerBrowser.ServerBrowserLaunchError({ cause: error })),
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,7 @@ it.effect(
},
{},
yield* ServerBrowser.ServerBrowser,
() => Effect.void,
).pipe(Layer.provide(configRpcServices)),
),
);
Expand Down Expand Up @@ -826,6 +827,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", (
},
{},
yield* ServerBrowser.ServerBrowser,
() => Effect.void,
).pipe(Layer.provide(configRpcServices)),
),
);
Expand Down
6 changes: 4 additions & 2 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1222,6 +1222,7 @@ export const layerWsRpc = (
currentSession: EnvironmentAuth.AuthenticatedSession,
clientAnalyticsProps: Readonly<Record<string, unknown>>,
serverBrowser: ServerBrowser.ServerBrowser["Service"],
reportProfiles: ServerBrowser.ProfileReporter,
) =>
Layer.effectContext(
Effect.gen(function* () {
Expand Down Expand Up @@ -3026,7 +3027,7 @@ export const layerWsRpc = (
[WS_METHODS.previewClose]: (input) => previewManager.close(input),
[WS_METHODS.previewList]: (input) => previewManager.list(input),
[WS_METHODS.previewClearProfile]: (input) => serverBrowser.clearProfile(input.profileId),
[WS_METHODS.previewReportProfiles]: (input) => serverBrowser.reportProfiles(input),
[WS_METHODS.previewReportProfiles]: (input) => reportProfiles(input),
[WS_METHODS.previewReportStatus]: (input) => previewManager.reportStatus(input),
[WS_METHODS.subscribePreviewEvents]: (_input) => previewManager.events,
[WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input),
Expand Down Expand Up @@ -3299,6 +3300,7 @@ export const layer = Layer.unwrap(
);
const clientAnalyticsProps = readClientAnalyticsProps(request);
yield* analytics.recordOwners(readClientOwners(request), "client");
const reportProfiles = yield* serverBrowser.profileReporter;
const rpcWebSocketHttpEffect = yield* Effect.gen(function* () {
const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket;
yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe(
Expand Down Expand Up @@ -3328,7 +3330,7 @@ export const layer = Layer.unwrap(
return httpEffect;
}).pipe(
Effect.provide(
layerWsRpc(session, clientAnalyticsProps, serverBrowser).pipe(
layerWsRpc(session, clientAnalyticsProps, serverBrowser, reportProfiles).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
// Handler-context reporters see only request defects, not server-wide defects.
Layer.provide(DefectReporter.layer),
Expand Down
Loading