Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SessionControl.ts

168 lines5.0 KB

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 }
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 /**
114 * A read that needs no control and does not queue, so an agent can look at
115 * a page while a human drives it without holding up the human's input.
116 */
117 observe<A>(run: () => Promise<A>) {
118 this.assertOpen();
119 return run();
120 }
121​
122 system<A>(run: () => Promise<A>) {
123 this.assertOpen();
124 return this.enqueue(async () => {
125 this.assertOpen();
126 return run();
127 });
128 }
129​
130 human<A>(viewerId: string, run: () => Promise<A>) {
131 return this.action(() => this.owner === viewerId, run);
132 }
133​
134 async take(viewerId: string) {
135 this.assertOpen();
136 if (this.owner !== null && this.owner !== viewerId) {
137 throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
138 }
139 if (this.owner !== viewerId) this.changeOwner(viewerId);
140 return this.human(viewerId, async () => {});
141 }
142​
143 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
144 this.assertOpen();
145 if (this.owner !== viewerId) {
146 throw new BrowserControlInterrupted(
147 "Only the controlling viewer can release this browser tab.",
148 );
149 }
150 this.changeOwner(null);
151 await this.enqueue(async () => {
152 await Promise.all(this.handoff);
153 await afterDrain();
154 });
155 }
156​
157 async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
158 if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
159 }
160​
161 async close() {
162 if (!this.closed) {
163 this.closed = true;
164 this.changeOwner(null);
165 }
166 await this.tail;
167 }