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 agentMayAct(agentId: string) {
77 return this.agentId === null || this.agentId === agentId;
78 }
79
80 agent<A>(agentId: string, run: () => Promise<A>) {
81 if (!this.agentMayAct(agentId))
82 return Promise.reject(
83 new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),
84 );
85 if (this.owner !== null)
86 return Promise.reject(
87 new BrowserControlInterrupted("A human controls this tab.", "humanControl"),
88 );
89 return this.action(() => this.agentMayAct(agentId) && this.owner === null, run);
90 }
91
92 agentCanActNow(agentId: string) {
93 return this.agentMayAct(agentId) && this.owner === null;
94 }
95
96 /**
97 * A read that needs no control and does not queue, so an agent can look at
98 * a page while a human drives it without holding up the human's input.
99 */
100 observe<A>(run: () => Promise<A>) {
101 this.assertOpen();
102 return run();
103 }
104
105 system<A>(run: () => Promise<A>) {
106 this.assertOpen();
107 return this.enqueue(async () => {
108 this.assertOpen();
109 return run();
110 });
111 }
112
113 human<A>(viewerId: string, run: () => Promise<A>) {
114 return this.action(() => this.owner === viewerId, run);
115 }
116
117 async take(viewerId: string) {
118 this.assertOpen();
119 if (this.owner !== null && this.owner !== viewerId) {
120 throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
121 }
122 if (this.owner !== viewerId) this.changeOwner(viewerId);
123 return this.human(viewerId, async () => {});
124 }
125
126 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
127 this.assertOpen();
128 if (this.owner !== viewerId) {
129 throw new BrowserControlInterrupted(
130 "Only the controlling viewer can release this browser tab.",
131 );
132 }
133 this.changeOwner(null);
134 await this.enqueue(afterDrain);
135 }
136
137 async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
138 if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
139 }
140
141 async close() {
142 if (!this.closed) {
143 this.closed = true;
144 this.changeOwner(null);
145 }
146 await this.tail;
147 }
148}