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
14const settle = (work: Promise<unknown>) =>
15 work.then(
16 () => undefined,
17 () => undefined,
18 );
19
20/** Reserves control immediately, but drains running work before the new owner can act. */
21export class SessionControl {
22 readonly agentId: string | null;
23 private readonly onGenerationChange: () => void;
24 private tail: Promise<unknown> = Promise.resolve();
25 private pending: Promise<void> = Promise.resolve();
26 private readonly handoff = new Set<Promise<void>>();
27 private owner: string | null = null;
28 private epoch = 0;
29 private closed = false;
30
31 constructor(agentId: string | null, onGenerationChange: () => void = () => {}) {
32 this.agentId = agentId;
33 this.onGenerationChange = onGenerationChange;
34 }
35
36 get controller() {
37 return this.owner;
38 }
39
40 get generation() {
41 return this.epoch;
42 }
43
44 private enqueue<A>(run: () => Promise<A>): Promise<A> {
45 const result = this.tail.then(run);
46 this.tail = result.then(
47 () => this.pending,
48 () => this.pending,
49 );
50 return result;
51 }
52
53 /** An action can respond before its navigation commits, while later actions still wait. */
54 track(work: Promise<unknown>) {
55 this.pending = Promise.all([this.pending, settle(work)]).then(() => undefined);
56 }
57
58 /** Viewer input stays responsive, but control handoffs still drain its navigations. */
59 trackUntilHandoff(work: Promise<unknown>) {
60 const settled = settle(work).finally(() => {
61 this.handoff.delete(settled);
62 });
63 this.handoff.add(settled);
64 }
65
66 private assertOpen() {
67 if (this.closed) throw new BrowserControlInterrupted("This browser tab is closed.", "closed");
68 }
69
70 private changeOwner(owner: string | null) {
71 this.owner = owner;
72 this.epoch++;
73 this.onGenerationChange();
74 }
75
76 private async action<A>(allowed: () => boolean, run: () => Promise<A>) {
77 this.assertOpen();
78 if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab.");
79 const epoch = this.epoch;
80 return this.enqueue(async () => {
81 this.assertOpen();
82 if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted();
83 return run();
84 });
85 }
86
87 agentMayAct(agentId: string) {
88 return this.agentId === null || this.agentId === agentId;
89 }
90
91 agent<A>(agentId: string, run: () => Promise<A>) {
92 if (!this.agentMayAct(agentId))
93 return Promise.reject(
94 new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),
95 );
96 if (this.owner !== null)
97 return Promise.reject(
98 new BrowserControlInterrupted("A human controls this tab.", "humanControl"),
99 );
100 return this.action(() => this.agentMayAct(agentId) && this.owner === null, run);
101 }
102
103 agentCanActNow(agentId: string) {
104 return this.agentMayAct(agentId) && this.owner === null;
105 }
106
107 /**
108 * A read that needs no control and does not queue, so an agent can look at
109 * a page while a human drives it without holding up the human's input.
110 */
111 observe<A>(run: () => Promise<A>) {
112 this.assertOpen();
113 return run();
114 }
115
116 system<A>(run: () => Promise<A>) {
117 this.assertOpen();
118 return this.enqueue(async () => {
119 this.assertOpen();
120 return run();
121 });
122 }
123
124 human<A>(viewerId: string, run: () => Promise<A>) {
125 return this.action(() => this.owner === viewerId, run);
126 }
127
128 async take(viewerId: string) {
129 this.assertOpen();
130 if (this.owner !== null && this.owner !== viewerId) {
131 throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
132 }
133 if (this.owner !== viewerId) this.changeOwner(viewerId);
134 return this.human(viewerId, async () => {});
135 }
136
137 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
138 this.assertOpen();
139 if (this.owner !== viewerId) {
140 throw new BrowserControlInterrupted(
141 "Only the controlling viewer can release this browser tab.",
142 );
143 }
144 this.changeOwner(null);
145 await this.enqueue(async () => {
146 await Promise.all(this.handoff);
147 await afterDrain();
148 });
149 }
150
151 async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
152 if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
153 }
154
155 async close() {
156 if (!this.closed) {
157 this.closed = true;
158 this.changeOwner(null);
159 }
160 await this.tail;
161 }
162}