Repository navigation
Expand file tree
/
Copy pathSessionControl.ts
More file actions
214 lines (191 loc) · 6.48 KB
/
Copy pathSessionControl.ts
File metadata and controls
214 lines (191 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { PreviewAutomationControlReason } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
export class BrowserControlInterrupted extends Schema.TaggedError<BrowserControlInterrupted>()(
"BrowserControlInterrupted",
{
message: Schema.String.pipe(
Schema.withConstructorDefault(
Effect.succeed("Browser control changed. Refresh the snapshot before trying again."),
),
),
reason: PreviewAutomationControlReason.pipe(
Schema.withConstructorDefault(Effect.succeed("interrupted" as const)),
),
},
) {}
const settle = (work: Promise<unknown>) =>
work.then(
() => undefined,
() => undefined,
);
/** Reserves control immediately, but drains running work before the new owner can act. */
export class SessionControl {
readonly agentId: string | null;
private readonly onGenerationChange: () => void;
private tail: Promise<unknown> = Promise.resolve();
private latestHuman: {
entry: { viewerId: string; key: string; input: unknown; run: (input: never) => Promise<void> };
result: Promise<void>;
} | null = null;
private pending: Promise<void> = Promise.resolve();
private readonly handoff = new Set<Promise<void>>();
private owner: string | null = null;
private epoch = 0;
private closed = false;
constructor(agentId: string | null, onGenerationChange: () => void = () => {}) {
this.agentId = agentId;
this.onGenerationChange = onGenerationChange;
}
get controller() {
return this.owner;
}
get generation() {
return this.epoch;
}
private enqueue<A>(run: () => Promise<A>): Promise<A> {
this.latestHuman = null;
const result = this.tail.then(run);
this.tail = result.then(
() => this.pending,
() => this.pending,
);
return result;
}
/** An action can respond before its navigation commits, while later actions still wait. */
track(work: Promise<unknown>) {
this.pending = Promise.all([this.pending, settle(work)]).then(() => undefined);
}
/** Viewer input stays responsive, but control handoffs still drain its navigations. */
trackUntilHandoff(work: Promise<unknown>) {
const settled = settle(work).finally(() => {
this.handoff.delete(settled);
});
this.handoff.add(settled);
}
private assertOpen() {
if (this.closed)
throw new BrowserControlInterrupted({
message: "This browser tab is closed.",
reason: "closed",
});
}
private changeOwner(owner: string | null) {
this.latestHuman = null;
this.owner = owner;
this.epoch++;
this.onGenerationChange();
}
private async action<A>(allowed: () => boolean, run: () => Promise<A>, deadlineMs?: number) {
this.assertOpen();
if (!allowed())
throw new BrowserControlInterrupted({ message: "You do not control this browser tab." });
const epoch = this.epoch;
return this.enqueue(async () => {
this.assertOpen();
if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted();
if (deadlineMs !== undefined && performance.now() >= deadlineMs) {
throw new DOMException(
"This browser request expired before it could start.",
"TimeoutError",
);
}
return run();
});
}
agentMayAct(agentId: string) {
return this.agentId === null || this.agentId === agentId;
}
agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {
if (!this.agentMayAct(agentId))
return Promise.reject(
new BrowserControlInterrupted({
message: "This tab belongs to another agent.",
reason: "agentMismatch",
}),
);
if (this.owner !== null)
return Promise.reject(
new BrowserControlInterrupted({
message: "A human controls this tab.",
reason: "humanControl",
}),
);
return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);
}
agentCanActNow(agentId: string) {
return this.agentMayAct(agentId) && this.owner === null;
}
/** Read without control or queueing so agents can observe without delaying human input. */
observe<A>(run: () => Promise<A>) {
this.assertOpen();
return run();
}
system<A>(run: () => Promise<A>) {
this.assertOpen();
return this.enqueue(async () => {
this.assertOpen();
return run();
});
}
human<A>(viewerId: string, run: () => Promise<A>) {
return this.action(() => this.owner === viewerId, run);
}
/**
* Merge into only adjacent waiting work with the same key; the running action and
* intervening actions keep their order. Work sharing a key must share its input type.
*/
humanLatest<A>(
viewerId: string,
key: string,
input: A,
run: (input: A) => Promise<void>,
merge: (waiting: A, next: A) => A = (_waiting, next) => next,
): Promise<void> {
if (this.closed || this.owner !== viewerId) return this.human(viewerId, () => run(input));
const latest = this.latestHuman;
if (latest?.entry.viewerId === viewerId && latest.entry.key === key) {
latest.entry.input = merge(latest.entry.input as A, input);
latest.entry.run = run;
return latest.result;
}
const entry = { viewerId, key, input, run };
const result = this.human(viewerId, async () => {
if (this.latestHuman?.entry === entry) this.latestHuman = null;
await entry.run(entry.input);
});
this.latestHuman = { entry, result };
return result;
}
async take(viewerId: string) {
this.assertOpen();
if (this.owner !== null && this.owner !== viewerId) {
throw new BrowserControlInterrupted({ message: "Another viewer controls this browser tab." });
}
if (this.owner !== viewerId) this.changeOwner(viewerId);
return this.human(viewerId, async () => {});
}
async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
this.assertOpen();
if (this.owner !== viewerId) {
throw new BrowserControlInterrupted({
message: "Only the controlling viewer can release this browser tab.",
});
}
this.changeOwner(null);
await this.enqueue(async () => {
await Promise.all(this.handoff);
await afterDrain();
});
}
async disconnect(viewerId: string, afterDrain?: () => Promise<void>) {
if (!this.closed && this.owner === viewerId) await this.release(viewerId, afterDrain);
}
async close() {
if (!this.closed) {
this.closed = true;
this.changeOwner(null);
}
await this.tail;
}
}