@devries-cameron20 / t3code Mirror · read-only / commits / 30a26dbb64
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 18:30 UTC

fix(server): agents keep named browser profiles after a server restart (#23484)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Victor committed Nov 12, 2026 at 16:46 UTC 30a26dbb64f80f288f0b379061a254d4c574d29c
2 files changed +285 -9
apps/server/src/preview/ServerBrowser.test.ts
+197
@@ -17,12 +17,14 @@ import {
17 type PreviewAutomationSnapshot,
18 type PreviewAutomationStatus,
19 } from "@t3tools/contracts";
20 +import * as Deferred from "effect/Deferred";
21 import * as Effect from "effect/Effect";
22 import * as Exit from "effect/Exit";
23 import * as Scope from "effect/Scope";
24 import * as Fiber from "effect/Fiber";
25 import * as FileSystem from "effect/FileSystem";
26 import * as Layer from "effect/Layer";
27 +import * as Logger from "effect/Logger";
28 import * as Option from "effect/Option";
29 import * as Path from "effect/Path";
30 import * as PubSub from "effect/PubSub";
@@ -2675,6 +2677,201 @@ it.live(
2677 ).pipe(Effect.provide(layer)),
2678 );
2679
2680 +// Holds the next profile save at its temp-file cleanup, after the rename, until released.
2681 +const gateSaveCleanup = Effect.gen(function* () {
2682 + const fs = yield* FileSystem.FileSystem;
2683 + const cleanupStarted = yield* Deferred.make<void>();
2684 + const releaseCleanup = yield* Deferred.make<void>();
2685 + let paused = false;
2686 + return {
2687 + cleanupStarted,
2688 + releaseCleanup,
2689 + pauseNext: () => {
2690 + paused = true;
2691 + },
2692 + fs: FileSystem.FileSystem.of({
2693 + ...fs,
2694 + remove: (target, options) =>
2695 + fs.remove(target, options).pipe(
2696 + Effect.tap(() => {
2697 + if (!paused) return Effect.void;
2698 + paused = false;
2699 + return Deferred.succeed(cleanupStarted, undefined).pipe(
2700 + Effect.andThen(Deferred.await(releaseCleanup)),
2701 + );
2702 + }),
2703 + ),
2704 + }),
2705 + };
2706 +});
2707 +
2708 +it.live("an agent opens a reported profile after a restart, before any client reports again", () =>
2709 + Effect.gen(function* () {
2710 + const gate = yield* gateSaveCleanup;
2711 + const persistent = (name: string) =>
2712 + ({ id: `profile-${name.toLowerCase()}`, name, kind: "persistent" }) as const;
2713 + // Together the two clients report more profiles than one report may hold.
2714 + const fromA = [
2715 + persistent("Work"),
2716 + ...Array.from({ length: 12 }, (_, n) => persistent(`A${n}`)),
2717 + ];
2718 + const fromB = [
2719 + persistent("Shared"),
2720 + ...Array.from({ length: 12 }, (_, n) => persistent(`B${n}`)),
2721 + ];
2722 + yield* Effect.gen(function* () {
2723 + const browser = yield* ServerBrowser.ServerBrowser;
2724 + const clientA = yield* Scope.make();
2725 + const reportFromA = yield* browser.profileReporter.pipe(
2726 + Effect.provideService(Scope.Scope, clientA),
2727 + );
2728 + const reportFromB = yield* browser.profileReporter;
2729 + const reportFromC = yield* browser.profileReporter;
2730 + yield* reportFromA({ profiles: fromA, defaultProfileId: "profile-work" });
2731 + gate.pauseNext();
2732 + const savingB = yield* reportFromB({
2733 + profiles: fromB,
2734 + defaultProfileId: "profile-shared",
2735 + }).pipe(Effect.forkScoped({ startImmediately: true }));
2736 + // A save that ends without reaching the gate fails the test instead of hanging it.
2737 + yield* Effect.raceFirst(
2738 + Deferred.await(gate.cleanupStarted),
2739 + Fiber.join(savingB).pipe(
2740 + Effect.andThen(Effect.die("save finished before the cleanup gate")),
2741 + ),
2742 + );
2743 + // C's save waits behind B's while the client that reported Work disconnects, as at shutdown.
2744 + const savingC = yield* reportFromC({ profiles: [], defaultProfileId: "profile-shared" }).pipe(
2745 + Effect.forkScoped({ startImmediately: true }),
2746 + );
2747 + yield* Scope.close(clientA, Exit.void);
2748 + yield* Deferred.succeed(gate.releaseCleanup, undefined);
2749 + yield* Fiber.join(savingB);
2750 + yield* Fiber.join(savingC);
2751 + }).pipe(
2752 + Effect.scoped,
2753 + Effect.provide(
2754 + Layer.fresh(ServerBrowser.layer).pipe(
2755 + Layer.provide(Layer.succeed(FileSystem.FileSystem, gate.fs)),
2756 + ),
2757 + ),
2758 + );
2759 +
2760 + const restarted = yield* Effect.gen(function* () {
2761 + const broker = yield* Broker.PreviewAutomationBroker;
2762 + yield* ServerBrowser.ServerBrowser;
2763 + yield* Effect.yieldNow;
2764 + return yield* broker.invoke<PreviewAutomationStatus>({
2765 + scope,
2766 + operation: "open",
2767 + input: { reuseExistingTab: false, show: false, profileId: "Work" },
2768 + });
2769 + }).pipe(Effect.provide(Layer.fresh(ServerBrowser.layer)));
2770 +
2771 + expect(contextRequests).toEqual([{ profileId: "profile-work", isolated: false }]);
2772 + expect(restarted.tabs).toMatchObject([{ profileId: "profile-work" }]);
2773 + expect(restarted).toMatchObject({
2774 + defaultProfileId: "profile-shared",
2775 + profiles: [
2776 + { id: "default", name: "Default" },
2777 + { id: "incognito", name: "Incognito", incognito: true },
2778 + ...[...fromA, ...fromB].map(({ id, name }) => ({ id, name })),
2779 + ],
2780 + });
2781 + }).pipe(Effect.provide(dependencies)),
2782 +);
2783 +
2784 +it.live("warns at startup about a saved profile catalog it cannot read or decode", () =>
2785 + Effect.gen(function* () {
2786 + const fs = yield* FileSystem.FileSystem;
2787 + const path = yield* Path.Path;
2788 + const { stateDir } = yield* ServerConfig.ServerConfig;
2789 + const savedPath = path.join(stateDir, "server-browser", "reported-profiles.json");
2790 + const startupWarnings = (saved: "missing" | "empty" | "invalid" | "unreadable") =>
2791 + Effect.gen(function* () {
2792 + const messages: string[] = [];
2793 + yield* fs.remove(savedPath, { recursive: true, force: true });
2794 + yield* fs.makeDirectory(path.dirname(savedPath), { recursive: true });
2795 + if (saved === "empty") yield* fs.writeFileString(savedPath, "");
2796 + if (saved === "invalid") yield* fs.writeFileString(savedPath, "{");
2797 + if (saved === "unreadable") yield* fs.makeDirectory(savedPath);
2798 + const logger = Logger.make(({ message }) => {
2799 + messages.push(String(message));
2800 + });
2801 + yield* ServerBrowser.ServerBrowser.pipe(
2802 + Effect.provide(
2803 + Layer.fresh(ServerBrowser.layer).pipe(
2804 + Layer.provide(Logger.layer([logger], { mergeWithExisting: false })),
2805 + ),
2806 + ),
2807 + );
2808 + return messages.filter((message) => message.includes("saved browser profiles"));
2809 + });
2810 +
2811 + expect(yield* startupWarnings("missing")).toEqual([]);
2812 + expect(yield* startupWarnings("empty")).toEqual([]);
2813 + expect(yield* startupWarnings("invalid")).toEqual([
2814 + expect.stringContaining("ignoring invalid saved browser profiles"),
2815 + ]);
2816 + expect(yield* startupWarnings("unreadable")).toEqual([
2817 + expect.stringContaining("failed to read saved browser profiles"),
2818 + ]);
2819 + }).pipe(Effect.provide(dependencies)),
2820 +);
2821 +
2822 +it.live("a report interrupted while an earlier save holds the lock is still saved", () =>
2823 + Effect.gen(function* () {
2824 + const gate = yield* gateSaveCleanup;
2825 + const work = { id: "profile-work", name: "Work", kind: "persistent" } as const;
2826 + const late = { id: "profile-late", name: "Late", kind: "persistent" } as const;
2827 + yield* Effect.gen(function* () {
2828 + const report = yield* (yield* ServerBrowser.ServerBrowser).profileReporter;
2829 + gate.pauseNext();
2830 + const saving = yield* report({ profiles: [work], defaultProfileId: "profile-work" }).pipe(
2831 + Effect.forkScoped({ startImmediately: true }),
2832 + );
2833 + yield* Effect.raceFirst(
2834 + Deferred.await(gate.cleanupStarted),
2835 + Fiber.join(saving).pipe(
2836 + Effect.andThen(Effect.die("save finished before the cleanup gate")),
2837 + ),
2838 + );
2839 + // The client disconnects while its report waits for the save in progress.
2840 + const waiting = yield* report({
2841 + profiles: [work, late],
2842 + defaultProfileId: "profile-late",
2843 + }).pipe(Effect.forkScoped({ startImmediately: true }));
2844 + waiting.interruptUnsafe();
2845 + yield* Deferred.succeed(gate.releaseCleanup, undefined);
2846 + yield* Fiber.join(saving);
2847 + yield* Fiber.await(waiting);
2848 + }).pipe(
2849 + Effect.scoped,
2850 + Effect.provide(
2851 + Layer.fresh(ServerBrowser.layer).pipe(
2852 + Layer.provide(Layer.succeed(FileSystem.FileSystem, gate.fs)),
2853 + ),
2854 + ),
2855 + );
2856 +
2857 + const restarted = yield* Effect.gen(function* () {
2858 + const broker = yield* Broker.PreviewAutomationBroker;
2859 + yield* ServerBrowser.ServerBrowser;
2860 + yield* Effect.yieldNow;
2861 + return yield* broker.invoke<PreviewAutomationStatus>({
2862 + scope,
2863 + operation: "open",
2864 + input: { reuseExistingTab: false, show: false, profileId: "Late" },
2865 + });
2866 + }).pipe(Effect.provide(Layer.fresh(ServerBrowser.layer)));
2867 +
2868 + expect(restarted).toMatchObject({
2869 + defaultProfileId: "profile-late",
2870 + tabs: [{ profileId: "profile-late" }],
2871 + });
2872 + }).pipe(Effect.provide(dependencies)),
2873 +);
2874 +
2875 it.live("profiles reported by one client survive another client's report", () =>
2876 Effect.scoped(
2877 Effect.gen(function* () {
apps/server/src/preview/ServerBrowser.ts
+88 -9
@@ -2,14 +2,16 @@
2 // Screencasts ignore emulated device scale; real 2x keeps captures sharp.
3 // --disable-gpu uses cheaper software compositing while preserving SwiftShader WebGL.
4 import {
5 + BrowserProfile,
6 + BrowserProfileId,
7 BUILT_IN_BROWSER_PROFILES,
8 DEFAULT_BROWSER_PROFILE_ID,
9 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
10 FILL_PREVIEW_VIEWPORT,
11 findBrowserProfile,
12 INCOGNITO_BROWSER_PROFILE_ID,
13 + isBuiltInBrowserProfileId,
14 resolveBrowserProfiles,
12 - type BrowserProfile,
15 type PreviewReportProfilesInput,
16 PREVIEW_AUTOMATION_SERVER_OPERATIONS,
17 PreviewViewportSetting as PreviewViewportSettingSchema,
@@ -46,6 +48,7 @@ import {
48 type PreviewAppearancePreference,
49 } from "@t3tools/contracts";
50 import { AgentScope, agentScopeLauncherScript } from "@t3tools/shared/AgentScope";
51 +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
52 import * as HostProcess from "@t3tools/shared/HostProcess";
53 import { normalizePreviewUrl } from "@t3tools/shared/preview";
54 import { resolvePreviewViewport } from "@t3tools/shared/previewViewport";
@@ -54,12 +57,15 @@ import * as NodeFSP from "node:fs/promises";
57 import * as NodePath from "node:path";
58 import * as Context from "effect/Context";
59 import * as Effect from "effect/Effect";
60 +import * as FileSystem from "effect/FileSystem";
61 import { constVoid } from "effect/Function";
62 import * as Layer from "effect/Layer";
63 import * as Option from "effect/Option";
64 +import type * as Path from "effect/Path";
65 import * as Queue from "effect/Queue";
66 import * as Schedule from "effect/Schedule";
67 import * as Schema from "effect/Schema";
68 +import * as Semaphore from "effect/Semaphore";
69 import * as Exit from "effect/Exit";
70 import * as Scope from "effect/Scope";
71 import * as Stream from "effect/Stream";
@@ -90,6 +96,12 @@ import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";
96 import { installPdfDocumentNavigation, isPdfAssetUrl } from "./PdfDocumentNavigation.ts";
97
98 const SERVER_HOST_CLIENT_ID = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
99 +// Each client's report is capped, but the saved catalog is their union, so it has no cap.
100 +const SavedProfilesJson = Schema.fromJsonString(
101 + Schema.Struct({ profiles: Schema.Array(BrowserProfile), defaultProfileId: BrowserProfileId }),
102 +);
103 +const decodeSavedProfiles = Schema.decodeUnknownEffect(SavedProfilesJson);
104 +const encodeSavedProfiles = Schema.encodeSync(SavedProfilesJson);
105 const RENDER_SCALE = 2;
106 // Chromium allows three unacked frames, so 100 ms pacing caps viewers near 30 fps.
107 const SCREENCAST_ACK_PACE_MS = 100;
@@ -1602,12 +1614,55 @@ const make = Effect.gen(function* () {
1614 ? ("agent" as const)
1615 : ("unclaimed" as const);
1616
1617 + const resolveReportedProfiles = (input: PreviewReportProfilesInput) => {
1618 + const profiles = resolveBrowserProfiles(input.profiles);
1619 + return {
1620 + profiles,
1621 + defaultProfileId:
1622 + findBrowserProfile(profiles, input.defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID,
1623 + };
1624 + };
1625 +
1626 + // Clients report profiles only when they connect, so the catalog at the last report is
1627 + // kept on disk for agents and scheduled tasks that open a profile after a restart.
1628 + const savedProfilesPath = NodePath.join(
1629 + config.stateDir,
1630 + "server-browser",
1631 + "reported-profiles.json",
1632 + );
1633 + const fileServices = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
1634 + const saveProfilesLock = yield* Semaphore.make(1);
1635 + let savedProfiles = yield* (yield* FileSystem.FileSystem).readFileString(savedProfilesPath).pipe(
1636 + Effect.tapError((cause) =>
1637 + cause.reason._tag === "NotFound"
1638 + ? Effect.void
1639 + : Effect.logWarning("failed to read saved browser profiles", {
1640 + path: savedProfilesPath,
1641 + cause,
1642 + }),
1643 + ),
1644 + Effect.orElseSucceed(() => ""),
1645 + );
1646 const reportsByClient = new Map<number, PreviewReportProfilesInput>();
1647 let nextClient = 0;
1648 let reportedProfiles: {
1649 readonly profiles: ReadonlyArray<BrowserProfile>;
1650 readonly defaultProfileId: string;
1610 - } | null = null;
1651 + } | null = yield* decodeSavedProfiles(savedProfiles).pipe(
1652 + Effect.map(resolveReportedProfiles),
1653 + Effect.tapError((cause) =>
1654 + savedProfiles === ""
1655 + ? Effect.void
1656 + : Effect.logWarning("ignoring invalid saved browser profiles", {
1657 + path: savedProfilesPath,
1658 + cause,
1659 + }),
1660 + ),
1661 + Effect.orElseSucceed(() => null),
1662 + );
1663 + // Only reports change what is saved, so the order clients disconnect in at shutdown,
1664 + // even while a save waits for the lock, cannot shrink the saved catalog.
1665 + let catalogToSave = reportedProfiles;
1666 // Agent recordings encode here, so they need the client's Browser recording frame rate. The
1667 // last report outlives the client, which lets agents record while no client is connected.
1668 let recordingFrameRate = DEFAULT_BROWSER_RECORDING_FRAME_RATE;
@@ -1623,14 +1678,32 @@ const make = Effect.gen(function* () {
1678 latest = report;
1679 }
1680 if (latest === undefined) return;
1626 - const profiles = resolveBrowserProfiles([...byId.values()]);
1627 - reportedProfiles = {
1628 - profiles,
1629 - defaultProfileId:
1630 - findBrowserProfile(profiles, latest.defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID,
1631 - };
1681 + reportedProfiles = resolveReportedProfiles({
1682 + profiles: [...byId.values()],
1683 + defaultProfileId: latest.defaultProfileId,
1684 + });
1685 };
1686
1687 + const saveReportedProfiles = Effect.fn("ServerBrowser.saveReportedProfiles")(function* () {
1688 + if (catalogToSave === null) return;
1689 + const contents = encodeSavedProfiles({
1690 + profiles: catalogToSave.profiles.filter((profile) => !isBuiltInBrowserProfileId(profile.id)),
1691 + defaultProfileId: catalogToSave.defaultProfileId,
1692 + });
1693 + if (contents === savedProfiles) return;
1694 + yield* writeFileStringAtomically({ filePath: savedProfilesPath, contents }).pipe(
1695 + Effect.provideContext(fileServices),
1696 + Effect.tap(() =>
1697 + Effect.sync(() => {
1698 + savedProfiles = contents;
1699 + }),
1700 + ),
1701 + Effect.catch((cause) =>
1702 + Effect.logWarning("failed to save reported browser profiles", { cause }),
1703 + ),
1704 + );
1705 + }, saveProfilesLock.withPermits(1));
1706 +
1707 const profileReporter: ServerBrowser["Service"]["profileReporter"] = Effect.acquireRelease(
1708 Effect.sync(() => nextClient++),
1709 (client) =>
@@ -1648,7 +1721,13 @@ const make = Effect.gen(function* () {
1721 reportsByClient.delete(client);
1722 reportsByClient.set(client, input);
1723 rebuildReportedProfiles();
1651 - }),
1724 + catalogToSave = reportedProfiles;
1725 + }).pipe(
1726 + Effect.andThen(saveReportedProfiles),
1727 + // A disconnect, even while an earlier save holds the lock, must not drop this
1728 + // report's save or leave the saved-content cache stale.
1729 + Effect.uninterruptible,
1730 + ),
1731 ),
1732 );
1733