Open History to see the last commit
1import type { PreviewAutomationControlReason } from "@t3tools/contracts";
2
3export class BrowserControlInterrupted extends Error {
4 readonly reason: PreviewAutomationControlReason;
5 constructor(
6 message = "Browser control changed. Refresh the snapshot before trying again.",
7 reason: PreviewAutomationControlReason = "interrupted",
8 ) {
9 super(message);
10 this.reason = reason;
11 }
12}
13
14/** Reserves control immediately, but drains running work before the new owner can act. */
15export class SessionControl {
16 readonly agentId: string | null;
17 private readonly onGenerationChange: () => void;
18 private tail: Promise<unknown> = Promise.resolve();
19 private pending: Promise<void> = Promise.resolve();
20 private owner: string | null = null;
21 private epoch = 0;
22 private closed = false;
23
24 constructor(agentId: string | null, onGenerationChange: () => void = () => {}) {
25 this.agentId = agentId;
26 this.onGenerationChange = onGenerationChange;
27 }
28
29 get controller() {
30 return this.owner;
31 }
32
33 get generation() {
34 return this.epoch;
35 }
36
37 private enqueue<A>(run: () => Promise<A>): Promise<A> {
38 const result = this.tail.then(run);
39 this.tail = result.then(
40 () => this.pending,
41 () => this.pending,
42 );
43 return result;
44 }
45
46 /** An action can respond before its navigation commits, while later actions still wait. */
47 track(work: Promise<unknown>) {
48 const settled = work.then(
49 () => undefined,
50 () => undefined,
51 );
52 this.pending = Promise.all([this.pending, settled]).then(() => undefined);
53 }
54
55 private assertOpen() {
56 if (this.closed) throw new BrowserControlInterrupted("This browser tab is closed.", "closed");
57 }
58
59 private changeOwner(owner: string | null) {
60 this.owner = owner;
61 this.epoch++;
62 this.onGenerationChange();
63 }
64
65 private async action<A>(allowed: () => boolean, run: () => Promise<A>) {
66 this.assertOpen();
67 if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab.");
68 const epoch = this.epoch;
69 return this.enqueue(async () => {
70 this.assertOpen();
71 if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted();
72 return run();
73 });
74 }
75
76 agent<A>(agentId: string, run: () => Promise<A>) {
77 if (this.agentId !== agentId)
78 return Promise.reject(
79 new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),
80 );
81 if (this.owner !== null)
82 return Promise.reject(
83 new BrowserControlInterrupted("A human controls this tab.", "humanControl"),
84 );
85 return this.action(() => this.agentId === agentId && this.owner === null, run);
86 }
87
88 /**
89 * Work any client may ask for, such as a viewport or appearance change. It
90 * waits its turn behind running actions but needs no control.
91 */
92 system<A>(run: () => Promise<A>) {
93 this.assertOpen();
94 return this.enqueue(async () => {
95 this.assertOpen();
96 return run();
97 });
98 }
99
100 human<A>(viewerId: string, run: () => Promise<A>) {
101 return this.action(() => this.owner === viewerId, run);
102 }
103
104 async take(viewerId: string) {
105 this.assertOpen();
106 if (this.owner !== null && this.owner !== viewerId) {
107 throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
108 }
109 if (this.owner !== viewerId) this.changeOwner(viewerId);
110 return this.human(viewerId, async () => {});
111 }
112
113 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
114 this.assertOpen();
115 if (this.owner !== viewerId) {
116 throw new BrowserControlInterrupted(
117 "Only the controlling viewer can release this browser tab.",
118 );
119 }
120 this.changeOwner(null);
121 await this.enqueue(afterDrain);
122 }
123
124 async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
125 if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
126 }
127
128 async close() {
129 if (!this.closed) {
130 this.closed = true;
131 this.changeOwner(null);
132 }
133 await this.tail;
134 }
135}