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>, deadlineMs?: number) {
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 if (deadlineMs !== undefined && performance.now() >= deadlineMs) {
84 throw new DOMException(
85 "This browser request expired before it could start.",
86 "TimeoutError",
87 );
88 }
89 return run();
90 });
91 }
92
93 agentMayAct(agentId: string) {
94 return this.agentId === null || this.agentId === agentId;
95 }
96
97 agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {
98 if (!this.agentMayAct(agentId))
99 return Promise.reject(
100 new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),
101 );
102 if (this.owner !== null)
103 return Promise.reject(
104 new BrowserControlInterrupted("A human controls this tab.", "humanControl"),
105 );
106 return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);
107 }
108
109 agentCanActNow(agentId: string) {
110 return this.agentMayAct(agentId) && this.owner === null;
111 }
112
113 /** Read without control or queueing so agents can observe without delaying human input. */
114 observe<A>(run: () => Promise<A>) {
115 this.assertOpen();
116 return run();
117 }
118
119 system<A>(run: () => Promise<A>) {
120 this.assertOpen();
121 return this.enqueue(async () => {
122 this.assertOpen();
123 return run();
124 });
125 }
126
127 human<A>(viewerId: string, run: () => Promise<A>) {
128 return this.action(() => this.owner === viewerId, run);
129 }
130
131 async take(viewerId: string) {
132 this.assertOpen();
133 if (this.owner !== null && this.owner !== viewerId) {
134 throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
135 }
136 if (this.owner !== viewerId) this.changeOwner(viewerId);
137 return this.human(viewerId, async () => {});
138 }
139
140 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
141 this.assertOpen();
142 if (this.owner !== viewerId) {
143 throw new BrowserControlInterrupted(
144 "Only the controlling viewer can release this browser tab.",
145 );
146 }
147 this.changeOwner(null);
148 await this.enqueue(async () => {
149 await Promise.all(this.handoff);
150 await afterDrain();
151 });
152 }
153
154 async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
155 if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
156 }
157
158 async close() {
159 if (!this.closed) {
160 this.closed = true;
161 this.changeOwner(null);
162 }
163 await this.tail;
164 }
165}