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 latestHuman: {
26 entry: { viewerId: string; key: string; input: unknown; run: (input: never) => Promise<void> };
27 result: Promise<void>;
28 } | null = null;
29 private pending: Promise<void> = Promise.resolve();
30 private readonly handoff = new Set<Promise<void>>();
31 private owner: string | null = null;
32 private epoch = 0;
33 private closed = false;
34
35 constructor(agentId: string | null, onGenerationChange: () => void = () => {}) {
36 this.agentId = agentId;
37 this.onGenerationChange = onGenerationChange;
38 }
39
40 get controller() {
41 return this.owner;
42 }
43
44 get generation() {
45 return this.epoch;
46 }
47
48 private enqueue<A>(run: () => Promise<A>): Promise<A> {
49 this.latestHuman = null;
50 const result = this.tail.then(run);
51 this.tail = result.then(
52 () => this.pending,
53 () => this.pending,
54 );
55 return result;
56 }
57
58 /** An action can respond before its navigation commits, while later actions still wait. */
59 track(work: Promise<unknown>) {
60 this.pending = Promise.all([this.pending, settle(work)]).then(() => undefined);
61 }
62
63 /** Viewer input stays responsive, but control handoffs still drain its navigations. */
64 trackUntilHandoff(work: Promise<unknown>) {
65 const settled = settle(work).finally(() => {
66 this.handoff.delete(settled);
67 });
68 this.handoff.add(settled);
69 }
70
71 private assertOpen() {
72 if (this.closed) throw new BrowserControlInterrupted("This browser tab is closed.", "closed");
73 }
74
75 private changeOwner(owner: string | null) {
76 this.latestHuman = null;
77 this.owner = owner;
78 this.epoch++;
79 this.onGenerationChange();
80 }
81
82 private async action<A>(allowed: () => boolean, run: () => Promise<A>, deadlineMs?: number) {
83 this.assertOpen();
84 if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab.");
85 const epoch = this.epoch;
86 return this.enqueue(async () => {
87 this.assertOpen();
88 if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted();
89 if (deadlineMs !== undefined && performance.now() >= deadlineMs) {
90 throw new DOMException(
91 "This browser request expired before it could start.",
92 "TimeoutError",
93 );
94 }
95 return run();
96 });
97 }
98
99 agentMayAct(agentId: string) {
100 return this.agentId === null || this.agentId === agentId;
101 }
102
103 agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {
104 if (!this.agentMayAct(agentId))
105 return Promise.reject(
106 new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),
107 );
108 if (this.owner !== null)
109 return Promise.reject(
110 new BrowserControlInterrupted("A human controls this tab.", "humanControl"),
111 );
112 return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);
113 }
114
115 agentCanActNow(agentId: string) {
116 return this.agentMayAct(agentId) && this.owner === null;
117 }
118
119 /** Read without control or queueing so agents can observe without delaying human input. */
120 observe<A>(run: () => Promise<A>) {
121 this.assertOpen();
122 return run();
123 }
124
125 system<A>(run: () => Promise<A>) {
126 this.assertOpen();
127 return this.enqueue(async () => {
128 this.assertOpen();
129 return run();
130 });
131 }
132
133 human<A>(viewerId: string, run: () => Promise<A>) {
134 return this.action(() => this.owner === viewerId, run);
135 }
136
137 /**
138 * Merge into only adjacent waiting work with the same key; the running action and
139 * intervening actions keep their order. Work sharing a key must share its input type.
140 */
141 humanLatest<A>(
142 viewerId: string,
143 key: string,
144 input: A,
145 run: (input: A) => Promise<void>,
146 merge: (waiting: A, next: A) => A = (_waiting, next) => next,
147 ): Promise<void> {
148 if (this.closed || this.owner !== viewerId) return this.human(viewerId, () => run(input));
149 const latest = this.latestHuman;
150 if (latest?.entry.viewerId === viewerId && latest.entry.key === key) {
151 latest.entry.input = merge(latest.entry.input as A, input);
152 latest.entry.run = run;
153 return latest.result;
154 }
155 const entry = { viewerId, key, input, run };
156 const result = this.human(viewerId, async () => {
157 if (this.latestHuman?.entry === entry) this.latestHuman = null;
158 await entry.run(entry.input);
159 });
160 this.latestHuman = { entry, result };
161 return result;
162 }
163
164 async take(viewerId: string) {
165 this.assertOpen();
166 if (this.owner !== null && this.owner !== viewerId) {
167 throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
168 }
169 if (this.owner !== viewerId) this.changeOwner(viewerId);
170 return this.human(viewerId, async () => {});
171 }
172
173 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
174 this.assertOpen();
175 if (this.owner !== viewerId) {
176 throw new BrowserControlInterrupted(
177 "Only the controlling viewer can release this browser tab.",
178 );
179 }
180 this.changeOwner(null);
181 await this.enqueue(async () => {
182 await Promise.all(this.handoff);
183 await afterDrain();
184 });
185 }
186
187 async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
188 if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
189 }
190
191 async close() {
192 if (!this.closed) {
193 this.closed = true;
194 this.changeOwner(null);
195 }
196 await this.tail;
197 }
198}