Skip to content
TypeScript

fix(server): browser profiles reported by one client survive another client's report (#21745)

Ibrahim Elkamali50cdc2440afa
diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts
index 2f09e2b0846..3cf6d253832 100644
--- a/apps/server/src/preview/ServerBrowser.test.ts
+++ b/apps/server/src/preview/ServerBrowser.test.ts
@@ -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";
@@ -614,8 +616,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 }),
@@ -1453,7 +1456,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",
});
@@ -1498,3 +1502,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)),
+);
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
index 57e35be7786..0e52b5066c0 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
@@ -210,6 +210,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,
{
@@ -244,7 +246,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") {}
@@ -1384,6 +1386,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;
@@ -1392,16 +1396,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;
@@ -2618,7 +2651,7 @@ const make = Effect.gen(function* () {
return ServerBrowser.of({
attachViewer,
clearProfile,
- reportProfiles,
+ profileReporter,
openDownload,
answerFileChooser,
});
diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts
index d3f4781829a..5f2c685fa68 100644
--- a/apps/server/src/preview/ServerBrowserStream.test.ts
+++ b/apps/server/src/preview/ServerBrowserStream.test.ts
@@ -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) =>
@@ -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 }),
@@ -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: () => {
@@ -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);
@@ -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(() => {
@@ -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 })),
diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts
index 2c6adce82f3..d9dac8a0d9f 100644
--- a/apps/server/src/ws.test.ts
+++ b/apps/server/src/ws.test.ts
@@ -659,6 +659,7 @@ it.effect(
},
{},
yield* ServerBrowser.ServerBrowser,
+ () => Effect.void,
).pipe(Layer.provide(configRpcServices)),
),
);
@@ -826,6 +827,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", (
},
{},
yield* ServerBrowser.ServerBrowser,
+ () => Effect.void,
).pipe(Layer.provide(configRpcServices)),
),
);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index befad768da3..cfe49ad39d5 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -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* () {
@@ -3032,7 +3033,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),
@@ -3305,6 +3306,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(
@@ -3334,7 +3336,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),