@jeffawe/understudy 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +127 -0
- package/README.md +69 -160
- package/REASONER.md +76 -86
- package/dist/adapters/recorder/script.d.ts +25 -2
- package/dist/adapters/recorder/script.js +126 -31
- package/dist/core/outline.d.ts +43 -0
- package/dist/core/outline.js +121 -0
- package/dist/core/recording.d.ts +19 -1
- package/dist/core/recording.js +38 -2
- package/dist/core/replay.d.ts +62 -1
- package/dist/core/replay.js +162 -106
- package/dist/entry/cli.js +185 -30
- package/dist/entry/mcp.d.ts +2 -0
- package/dist/entry/mcp.js +128 -23
- package/dist/flows/destructive.js +1 -1
- package/dist/flows/distill.js +11 -6
- package/dist/flows/emit.d.ts +7 -0
- package/dist/flows/emit.js +26 -10
- package/dist/flows/execute.d.ts +12 -0
- package/dist/flows/execute.js +23 -16
- package/dist/flows/runs.d.ts +2 -0
- package/dist/flows/runs.js +7 -3
- package/dist/flows/save.d.ts +5 -2
- package/dist/flows/save.js +38 -23
- package/dist/flows/session.d.ts +176 -0
- package/dist/flows/session.js +383 -0
- package/dist/flows/variants.d.ts +81 -0
- package/dist/flows/variants.js +139 -0
- package/dist/memory/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +260 -0
- package/dist/memory/pages.d.ts +34 -0
- package/dist/memory/pages.js +60 -0
- package/dist/memory/recall.d.ts +87 -25
- package/dist/memory/recall.js +242 -45
- package/dist/plan/planner.d.ts +11 -1
- package/dist/plan/planner.js +36 -19
- package/dist/store/app-settings.d.ts +26 -0
- package/dist/store/app-settings.js +49 -0
- package/dist/store/db.js +8 -1
- package/dist/store/reembed.js +18 -7
- package/dist/store/types.d.ts +50 -0
- package/package.json +3 -2
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent sessions: an agent explores an app THROUGH Understudy, one step at a
|
|
3
|
+
* time, and keeps the steps that worked as a flow.
|
|
4
|
+
*
|
|
5
|
+
* Before this, an agent explored with throwaway Playwright scripts (page
|
|
6
|
+
* dumps, "which question appears after this answer?"), then rewrote the path
|
|
7
|
+
* that worked in the format `understudy_save` reads, then had it replayed.
|
|
8
|
+
* Most of its tokens went on the first part, and everything it learned there
|
|
9
|
+
* was lost. Here exploring IS recording:
|
|
10
|
+
*
|
|
11
|
+
* start open a browser — at an address, or partway along a saved flow
|
|
12
|
+
* (`upTo`), which is also how a stale flow is repaired: replay it to
|
|
13
|
+
* the step that fails and explore from there
|
|
14
|
+
* step one click, fill, pick… run by the same Stepper replay uses, so a
|
|
15
|
+
* step that works here works when the flow replays. Returns only
|
|
16
|
+
* what changed: controls that appeared or went, the address, errors,
|
|
17
|
+
* API calls
|
|
18
|
+
* look the page's controls — role, name, state, options; no field values
|
|
19
|
+
* save the steps the agent keeps, PROVEN BY A REPLAY IN A FRESH BROWSER
|
|
20
|
+
* (up to a commit, as any save). One pass in a warm, slow session
|
|
21
|
+
* proves little: the agent paused to think between steps, which
|
|
22
|
+
* hides every wait the flow really needs.
|
|
23
|
+
*
|
|
24
|
+
* No model here either: the agent decides what to do; this does it and keeps
|
|
25
|
+
* the record. Sessions live in this process (the MCP server); a restart loses
|
|
26
|
+
* them, and one left alone closes after IDLE_MS.
|
|
27
|
+
*/
|
|
28
|
+
import { randomBytes } from 'node:crypto';
|
|
29
|
+
import { openLease } from '../core/browser.js';
|
|
30
|
+
import { Stepper, describeLocator } from '../core/replay.js';
|
|
31
|
+
import { buildRecording, rebase, redactValue, valueRefsOf } from '../core/recording.js';
|
|
32
|
+
import { outlineOf, diffOutline, describeControl } from '../core/outline.js';
|
|
33
|
+
import { changesSince, pageOf, rememberOutline } from '../memory/pages.js';
|
|
34
|
+
import { ensureSchema } from '../store/db.js';
|
|
35
|
+
import { valuesFromEnv, valueEnvNames, reloadEnvFiles } from '../store/settings.js';
|
|
36
|
+
import { timeoutFor } from '../store/app-settings.js';
|
|
37
|
+
import { lessonsFor, destructiveControls } from '../memory/notes.js';
|
|
38
|
+
import { destructiveReason } from './destructive.js';
|
|
39
|
+
import { recordingFrom, proveAndSave } from './save.js';
|
|
40
|
+
import { restoreSession } from './execute.js';
|
|
41
|
+
import { saveRecording } from '../core/recording-store.js';
|
|
42
|
+
import { checkVariant, resolveFlow } from './variants.js';
|
|
43
|
+
/** A session nobody has used for this long is closed. */
|
|
44
|
+
export const IDLE_MS = 15 * 60_000;
|
|
45
|
+
/** Open at once — each is a browser. */
|
|
46
|
+
const MAX_SESSIONS = 3;
|
|
47
|
+
/** Actions an agent may take in a session. A person's step (`human`) is a flow's, written in a script. */
|
|
48
|
+
const SESSION_ACTIONS = new Set([
|
|
49
|
+
'goto', 'click', 'fill', 'press', 'select', 'check', 'uncheck', 'scroll_container',
|
|
50
|
+
'wait_url', 'wait_text', 'wait_response', 'assert',
|
|
51
|
+
]);
|
|
52
|
+
/** Step fields an agent may set — the stored step shape, minus what Understudy fills in. */
|
|
53
|
+
const STEP_FIELDS = new Set(['action', 'role', 'name', 'exact', 'value', 'valueRef', 'css', 'testId', 'testIdAttr', 'frameHint', 'hints']);
|
|
54
|
+
const sessions = new Map();
|
|
55
|
+
function touch(s) {
|
|
56
|
+
if (s.timer)
|
|
57
|
+
clearTimeout(s.timer);
|
|
58
|
+
s.timer = setTimeout(() => { void closeSession(s.id); }, IDLE_MS);
|
|
59
|
+
s.timer.unref?.();
|
|
60
|
+
}
|
|
61
|
+
function get(id) {
|
|
62
|
+
const s = sessions.get(id);
|
|
63
|
+
if (!s)
|
|
64
|
+
throw new Error(`no session ${id} — it was closed, left idle for ${IDLE_MS / 60_000} min, or the server restarted; start another`);
|
|
65
|
+
touch(s);
|
|
66
|
+
return s;
|
|
67
|
+
}
|
|
68
|
+
/** Login values for these refs: the agent's, then the environment's (re-read, so a line just added counts). */
|
|
69
|
+
function valuesFor(s, refs) {
|
|
70
|
+
reloadEnvFiles();
|
|
71
|
+
return { ...valuesFromEnv(refs, s.app), ...s.values };
|
|
72
|
+
}
|
|
73
|
+
async function pageNow(s, within) {
|
|
74
|
+
const page = s.lease.page;
|
|
75
|
+
const all = await outlineOf(page);
|
|
76
|
+
s.outline = all;
|
|
77
|
+
const needle = within?.toLowerCase();
|
|
78
|
+
const shown = needle
|
|
79
|
+
? all.filter((c) => [c.name, c.group, c.text, ...(c.options ?? [])].some((t) => t?.toLowerCase().includes(needle)))
|
|
80
|
+
: all;
|
|
81
|
+
return {
|
|
82
|
+
url: page.url(), title: await page.title().catch(() => ''),
|
|
83
|
+
controls: shown.map(describeControl), ...(all.length >= 150 ? { more: true } : {}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** What a step outcome tells an agent: did it work, and if not, why. */
|
|
87
|
+
const result = (o) => ({
|
|
88
|
+
ok: o.ok, ...(o.error ? { error: o.error } : {}), ...(o.saw ? { saw: o.saw } : {}),
|
|
89
|
+
...(o.matched !== undefined && o.matched > 1 ? { matched: o.matched } : {}),
|
|
90
|
+
...(o.roleHadNoMatch ? { foundBy: o.roleHadNoMatch.fellBackTo } : {}),
|
|
91
|
+
});
|
|
92
|
+
export async function startSession(opts) {
|
|
93
|
+
if (!opts.url === !opts.flow)
|
|
94
|
+
throw new Error('start needs a url, or a flow to start along — one of them');
|
|
95
|
+
if (sessions.size >= MAX_SESSIONS)
|
|
96
|
+
throw new Error(`${MAX_SESSIONS} sessions are open already — close one first`);
|
|
97
|
+
// A session writes to the page map from its first step: make sure the
|
|
98
|
+
// collections and their indexes exist first, rather than created on write.
|
|
99
|
+
await ensureSchema();
|
|
100
|
+
const app = opts.app;
|
|
101
|
+
const variant = checkVariant(opts.variant);
|
|
102
|
+
if (opts.baseUrl !== undefined && !/^https?:\/\/[^/]/.test(opts.baseUrl))
|
|
103
|
+
throw new Error(`baseUrl must be an http(s) address, not "${opts.baseUrl}"`);
|
|
104
|
+
let fromFlow = [];
|
|
105
|
+
let entry;
|
|
106
|
+
let startUrl = opts.url ?? '';
|
|
107
|
+
const values = { ...(opts.values ?? {}) };
|
|
108
|
+
let storageState;
|
|
109
|
+
if (opts.flow) {
|
|
110
|
+
const flow = await resolveFlow(app, opts.flow, variant);
|
|
111
|
+
if (!flow)
|
|
112
|
+
throw new Error(`no flow '${opts.flow}' for app '${app}'`);
|
|
113
|
+
const saved = recordingFrom(flow);
|
|
114
|
+
const rec = opts.baseUrl ? rebase(saved, opts.baseUrl) : saved;
|
|
115
|
+
const upTo = opts.upTo ?? rec.events.length;
|
|
116
|
+
if (!Number.isInteger(upTo) || upTo < 0 || upTo > rec.events.length)
|
|
117
|
+
throw new Error(`upTo must be 0 to ${rec.events.length}, the flow's step count`);
|
|
118
|
+
fromFlow = rec.events.slice(0, upTo);
|
|
119
|
+
startUrl = rec.startUrl;
|
|
120
|
+
if (flow.requiresSession)
|
|
121
|
+
entry = { requiresSession: true, ...(flow.session ? { session: flow.session } : {}) };
|
|
122
|
+
const refs = valueRefsOf(fromFlow);
|
|
123
|
+
const found = valuesFor({ app, values }, refs);
|
|
124
|
+
const missing = refs.filter((r) => !(r in found));
|
|
125
|
+
if (missing.length) {
|
|
126
|
+
throw new Error(`missing login value(s) for the flow's steps — nothing was opened: ${missing.map((r) => `${r} (set ${valueEnvNames(r, app)[0]})`).join(', ')}`);
|
|
127
|
+
}
|
|
128
|
+
({ storageState } = await restoreSession({ ...rec, ...(entry ? { entry } : {}) }, found));
|
|
129
|
+
}
|
|
130
|
+
const lease = await openLease({ headless: !opts.headed, ...(storageState ? { storageState } : {}) });
|
|
131
|
+
const timeoutMs = await timeoutFor(app);
|
|
132
|
+
// The same object the session adds login values to, so each step sees them.
|
|
133
|
+
const stepper = new Stepper(lease, {
|
|
134
|
+
values,
|
|
135
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
136
|
+
lessonsFor: (ctx) => lessonsFor(app, ctx),
|
|
137
|
+
}, [], () => false);
|
|
138
|
+
const s = {
|
|
139
|
+
id: randomBytes(4).toString('hex'), app, lease, stepper, tried: [], startUrl, values,
|
|
140
|
+
allowPurchases: Boolean(opts.allowPurchases), outline: [], ...(entry ? { entry } : {}), ...(variant ? { variant } : {}),
|
|
141
|
+
};
|
|
142
|
+
sessions.set(s.id, s);
|
|
143
|
+
touch(s);
|
|
144
|
+
try {
|
|
145
|
+
// Along the flow: its steps run first, and are kept like any other.
|
|
146
|
+
if (opts.url)
|
|
147
|
+
fromFlow = [{ seq: 0, ts: 0, action: 'goto', value: opts.url, url: opts.url, resolution: 'synthesized' }];
|
|
148
|
+
let sinceLastSeen;
|
|
149
|
+
for (const e of fromFlow) {
|
|
150
|
+
const n = s.tried.length;
|
|
151
|
+
const event = { ...e, seq: n, ts: n };
|
|
152
|
+
// Its own login values, read the same way replay reads them.
|
|
153
|
+
Object.assign(s.values, valuesFor(s, valueRefsOf([event])));
|
|
154
|
+
const o = await stepper.run(event);
|
|
155
|
+
if (o.sig && o.outline) {
|
|
156
|
+
sinceLastSeen = await changesSince(app, o.sig, o.outline);
|
|
157
|
+
await rememberOutline(app, o.sig, o.outline);
|
|
158
|
+
}
|
|
159
|
+
const { seq: _s, ts: _t, ...step } = event;
|
|
160
|
+
s.tried.push({ n, step: { ...step, url: o.at ?? step.url, ...(o.sig ? { expectedSig: o.sig } : {}) }, ok: o.ok, ...(o.error ? { error: o.error } : {}), ...(opts.flow ? { fromFlow: true } : {}) });
|
|
161
|
+
if (!o.ok) {
|
|
162
|
+
return {
|
|
163
|
+
session: s.id, ran: n, stoppedAt: { n, ...result(o), step: describeLocator(event) },
|
|
164
|
+
...(opts.flow ? { how: 'The flow fails here: this is the step to repair. Look, try other steps, then save.' } : {}),
|
|
165
|
+
page: await pageNow(s), ...(sinceLastSeen ? { sinceLastSeen } : {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return { session: s.id, ran: s.tried.length, page: await pageNow(s), ...(sinceLastSeen ? { sinceLastSeen } : {}) };
|
|
170
|
+
}
|
|
171
|
+
catch (e) {
|
|
172
|
+
await closeSession(s.id);
|
|
173
|
+
throw e;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** Check a step the agent sent; return the problems, or the step. */
|
|
177
|
+
function readStep(raw) {
|
|
178
|
+
const problems = [];
|
|
179
|
+
const extra = Object.keys(raw).filter((k) => !STEP_FIELDS.has(k));
|
|
180
|
+
if (extra.length)
|
|
181
|
+
problems.push(`a step can't have ${extra.join(', ')} (it can have ${[...STEP_FIELDS].join(', ')})`);
|
|
182
|
+
const action = raw.action;
|
|
183
|
+
if (!SESSION_ACTIONS.has(action))
|
|
184
|
+
problems.push(`action must be one of ${[...SESSION_ACTIONS].join(', ')}`);
|
|
185
|
+
for (const k of ['role', 'name', 'value', 'valueRef', 'css', 'testId', 'testIdAttr', 'frameHint']) {
|
|
186
|
+
if (raw[k] !== undefined && typeof raw[k] !== 'string')
|
|
187
|
+
problems.push(`${k} must be a string`);
|
|
188
|
+
}
|
|
189
|
+
if (raw.hints !== undefined && (typeof raw.hints !== 'object' || raw.hints === null || Array.isArray(raw.hints)))
|
|
190
|
+
problems.push('hints must be an object');
|
|
191
|
+
if (action === 'goto' && typeof raw.value !== 'string')
|
|
192
|
+
problems.push('a goto needs value: the address');
|
|
193
|
+
return problems.length ? { problems } : { step: raw, problems };
|
|
194
|
+
}
|
|
195
|
+
export async function step(id, raw) {
|
|
196
|
+
const s = get(id);
|
|
197
|
+
const { step: given, problems } = readStep(raw);
|
|
198
|
+
if (!given)
|
|
199
|
+
throw new Error(`step not run — ${problems.join('; ')}`);
|
|
200
|
+
const page = s.lease.page;
|
|
201
|
+
// A typed password is never kept: the agent says which login value it is.
|
|
202
|
+
if (given.action === 'fill' && given.value !== undefined) {
|
|
203
|
+
const hint = given.name ?? given.testId ?? given.css ?? 'field';
|
|
204
|
+
const redacted = redactValue(hint, given.value, undefined, [given.name, given.css, given.testId].filter(Boolean).join(' '));
|
|
205
|
+
if (redacted.valueRef) {
|
|
206
|
+
throw new Error(`"${hint}" looks like a password field — pass valueRef "${redacted.valueRef}" instead of the value (set ${valueEnvNames(redacted.valueRef, s.app)[0]}, or pass it in values at start)`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
// A commit runs only when allowed; saving proves a flow up to it anyway.
|
|
210
|
+
const fact = given.name ? (await destructiveControls(s.app)).get(given.name.toLowerCase()) : undefined;
|
|
211
|
+
const commits = destructiveReason({ action: given.action, ...(given.name ? { name: given.name } : {}), url: page.url() })
|
|
212
|
+
?? (fact && ['click', 'press'].includes(given.action) ? `a fact says it commits something real: ${fact}` : null);
|
|
213
|
+
if (commits && !s.allowPurchases) {
|
|
214
|
+
return {
|
|
215
|
+
ok: false, refused: commits,
|
|
216
|
+
how: 'Not run. Save now (a save checks this control and never presses it), or start a session with allowPurchases if running it is fine.',
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
const n = s.tried.length;
|
|
220
|
+
const event = { ...given, seq: n, ts: n, url: page.url(), resolution: 'script-literal' };
|
|
221
|
+
if (event.valueRef) {
|
|
222
|
+
const found = valuesFor(s, [event.valueRef]);
|
|
223
|
+
if (!(event.valueRef in found)) {
|
|
224
|
+
throw new Error(`no value for ${event.valueRef} — nothing was typed. Ask the user to add ${valueEnvNames(event.valueRef, s.app)[0]}=… to their env file (never to paste it in chat), or pass it in values at start`);
|
|
225
|
+
}
|
|
226
|
+
Object.assign(s.values, found);
|
|
227
|
+
}
|
|
228
|
+
const before = s.outline.length ? s.outline : await outlineOf(page);
|
|
229
|
+
const signalsBefore = s.stepper.signals.length;
|
|
230
|
+
const sigBefore = s.stepper.sigSequence.at(-1);
|
|
231
|
+
const startedAt = Date.now();
|
|
232
|
+
const o = await s.stepper.run(event);
|
|
233
|
+
const ms = Date.now() - startedAt;
|
|
234
|
+
const after = o.outline ?? await outlineOf(page);
|
|
235
|
+
s.outline = after;
|
|
236
|
+
// A new page: say how it differs from the last time it looked otherwise, then keep it.
|
|
237
|
+
const sinceLastSeen = o.sig && o.sig !== sigBefore ? await changesSince(s.app, o.sig, after) : undefined;
|
|
238
|
+
if (o.sig)
|
|
239
|
+
await rememberOutline(s.app, o.sig, after);
|
|
240
|
+
const diff = diffOutline(before, after);
|
|
241
|
+
const samePage = !(o.sig && o.sig !== sigBefore) || pageOf(o.sig) === pageOf(sigBefore ?? '');
|
|
242
|
+
s.tried.push({
|
|
243
|
+
n, step: { ...given, url: o.at ?? event.url, resolution: 'script-literal', ...(o.sig ? { expectedSig: o.sig } : {}) }, ok: o.ok,
|
|
244
|
+
...(o.error ? { error: o.error } : {}), ...(o.ok && samePage && diff.appeared.length ? { revealed: diff.appeared } : {}),
|
|
245
|
+
});
|
|
246
|
+
const during = s.stepper.signals.slice(signalsBefore);
|
|
247
|
+
return {
|
|
248
|
+
n, ...result(o), ms,
|
|
249
|
+
url: page.url(),
|
|
250
|
+
...(o.sig && o.sig !== sigBefore ? { newPage: true } : {}),
|
|
251
|
+
...(diff.appeared.length ? { appeared: diff.appeared } : {}),
|
|
252
|
+
...(diff.gone.length ? { gone: diff.gone } : {}),
|
|
253
|
+
...(diff.changed.length ? { changed: diff.changed } : {}),
|
|
254
|
+
...(sinceLastSeen ? { sinceLastSeen } : {}),
|
|
255
|
+
...(during.some((x) => x.kind === 'http')
|
|
256
|
+
? { responses: during.filter((x) => x.kind === 'http').slice(0, 15).map((x) => `${x.text} ${shortUrl(x.url)}`) }
|
|
257
|
+
: {}),
|
|
258
|
+
...(during.some((x) => x.kind !== 'http')
|
|
259
|
+
? { errors: during.filter((x) => x.kind !== 'http' && !(x.kind === 'console' && x.level === 'warning')).slice(0, 8).map((x) => `${x.kind}: ${x.text.slice(0, 200)}`) }
|
|
260
|
+
: {}),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/** `https://app.test/api/visits?x=1` → `/api/visits` — enough to know which call. */
|
|
264
|
+
function shortUrl(url) {
|
|
265
|
+
if (!url)
|
|
266
|
+
return '';
|
|
267
|
+
try {
|
|
268
|
+
return new URL(url).pathname;
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
return url;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
export async function look(id, within) {
|
|
275
|
+
const s = get(id);
|
|
276
|
+
return { ...(await pageNow(s, within)), steps: s.tried.map((t) => `${t.n} ${t.ok ? 'ok ' : 'FAILED'} ${t.step.action} ${describeLocator({ ...t.step, seq: t.n, ts: 0 })}${t.fromFlow ? ' (from the flow)' : ''}`) };
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Keep the session's steps as a flow — proven by replaying them in a fresh
|
|
280
|
+
* browser first, exactly as `understudy_save` proves a recording.
|
|
281
|
+
*/
|
|
282
|
+
export async function saveSession(id, opts) {
|
|
283
|
+
const s = get(id);
|
|
284
|
+
const picked = opts.keep
|
|
285
|
+
? opts.keep.map((n) => {
|
|
286
|
+
const t = s.tried[n];
|
|
287
|
+
if (!t)
|
|
288
|
+
throw new Error(`no step ${n} in this session (it has 0–${s.tried.length - 1})`);
|
|
289
|
+
if (!t.ok)
|
|
290
|
+
throw new Error(`step ${n} failed in the session (${t.error}) — keep only steps that worked`);
|
|
291
|
+
return t;
|
|
292
|
+
})
|
|
293
|
+
: s.tried.filter((t) => t.ok);
|
|
294
|
+
if (!picked.some((t) => t.step.action !== 'goto'))
|
|
295
|
+
throw new Error('nothing to save — no step that worked besides opening the page');
|
|
296
|
+
const first = picked[0].step;
|
|
297
|
+
const events = picked.map((t, i) => ({ ...t.step, seq: i, ts: i }));
|
|
298
|
+
if (first.action !== 'goto') {
|
|
299
|
+
events.unshift({ seq: 0, ts: 0, action: 'goto', value: first.url, url: first.url, resolution: 'synthesized' });
|
|
300
|
+
events.forEach((e, i) => { e.seq = i; e.ts = i; });
|
|
301
|
+
}
|
|
302
|
+
const recording = buildRecording({ source: 'live', origin: `session:${s.id}`, appSlug: s.app, startUrl: s.startUrl || first.url, ...(s.entry ? { entry: s.entry } : {}) }, events);
|
|
303
|
+
await saveRecording(recording);
|
|
304
|
+
const refs = valueRefsOf(events);
|
|
305
|
+
const variant = checkVariant(opts.variant) ?? s.variant;
|
|
306
|
+
const out = await proveAndSave(recording, {
|
|
307
|
+
title: opts.name, madeBy: 'agent', values: valuesFor(s, refs), ...(variant ? { variant } : {}),
|
|
308
|
+
...(opts.intent ? { intent: opts.intent } : {}), ...(opts.slug ? { slug: opts.slug } : {}),
|
|
309
|
+
});
|
|
310
|
+
if (!out.saved)
|
|
311
|
+
return { recording, out };
|
|
312
|
+
const suggestions = suggest(s.tried, picked, first.action !== 'goto' ? 1 : 0, out.proven?.result.steps ?? [], (await timeoutFor(s.app)) ?? 10_000);
|
|
313
|
+
return { recording, out, ...(suggestions ? { suggestions } : {}) };
|
|
314
|
+
}
|
|
315
|
+
const keyOf = (s) => [s.action, s.role ?? '', s.name ?? '', s.testId ?? '', s.css ?? ''].join('\u0000');
|
|
316
|
+
const NOT_READY = /not enabled|not visible|not stable|timeout|matched no elements/i;
|
|
317
|
+
/**
|
|
318
|
+
* Pure: what the session's own record says the saved flow may need. Exported
|
|
319
|
+
* for tests.
|
|
320
|
+
*
|
|
321
|
+
* a step that failed at first and worked when tried again → the page wasn't ready: a wait before it
|
|
322
|
+
* a step that took over half the time a step may wait, in
|
|
323
|
+
* the fresh-browser replay → a wait before it, with room to spare
|
|
324
|
+
* a kept step that revealed controls on the same page → a fact: "picking Yes shows Which bundle?"
|
|
325
|
+
* a step that failed "not enabled", never done after → a control that stayed disabled: an app state?
|
|
326
|
+
*/
|
|
327
|
+
export function suggest(tried, kept, offset, proof, timeoutMs) {
|
|
328
|
+
const waits = [];
|
|
329
|
+
const at = (t) => kept.indexOf(t) + offset;
|
|
330
|
+
const check = (t, assert, ms, why) => {
|
|
331
|
+
if (!t.step.role || !t.step.name || waits.some((w) => w.before === at(t)))
|
|
332
|
+
return;
|
|
333
|
+
waits.push({ before: at(t), step: { action: 'assert', role: t.step.role, name: t.step.name, hints: { assert, timeoutMs: Math.min(600_000, ms) } }, why });
|
|
334
|
+
};
|
|
335
|
+
for (const t of kept) {
|
|
336
|
+
if (t.fromFlow || !['click', 'fill', 'select', 'check', 'uncheck', 'press'].includes(t.step.action))
|
|
337
|
+
continue;
|
|
338
|
+
const earlier = tried.find((f) => f.n < t.n && !f.ok && keyOf(f.step) === keyOf(t.step) && NOT_READY.test(f.error ?? ''));
|
|
339
|
+
if (earlier) {
|
|
340
|
+
check(t, /not enabled/i.test(earlier.error) ? 'enabled' : 'visible', Math.max(timeoutMs * 2, 15_000), `step ${at(t)} failed at first in the session (${earlier.error.slice(0, 120)}) and worked when tried again — the page wasn't ready yet`);
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
const took = proof.find((p) => p.seq === at(t))?.durationMs ?? 0;
|
|
344
|
+
if (took > timeoutMs / 2) {
|
|
345
|
+
check(t, 'enabled', Math.ceil((took * 2) / 1000) * 1000, `step ${at(t)} took ${(took / 1000).toFixed(1)} s of the ${timeoutMs / 1000} s a step may wait, replayed in a fresh browser`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
const facts = kept
|
|
349
|
+
.filter((t) => t.revealed?.length)
|
|
350
|
+
.slice(0, 5)
|
|
351
|
+
.map((t) => ({
|
|
352
|
+
text: `On ${pageOf(t.step.expectedSig ?? '') || t.step.url}, ${t.step.action} ${t.step.role ?? ''} "${t.step.name ?? t.step.value ?? ''}" shows: ${t.revealed.slice(0, 3).join('; ')}`.replace(/\s+/g, ' '),
|
|
353
|
+
why: `seen in the session at step ${t.n}`,
|
|
354
|
+
}));
|
|
355
|
+
const done = new Set(kept.map((t) => keyOf(t.step)));
|
|
356
|
+
const states = tried
|
|
357
|
+
.filter((t) => !t.ok && /not enabled/i.test(t.error ?? '') && !done.has(keyOf(t.step)) && t.step.name)
|
|
358
|
+
.filter((t, i, all) => all.findIndex((x) => keyOf(x.step) === keyOf(t.step)) === i)
|
|
359
|
+
.map((t) => ({
|
|
360
|
+
control: `${t.step.role ?? ''} "${t.step.name}"`.trim(),
|
|
361
|
+
why: `it stayed disabled when tried at step ${t.n} — if the account has to be in some state first (e.g. "has-no-active-bundle"), that's a requires state for this flow`,
|
|
362
|
+
}));
|
|
363
|
+
if (!waits.length && !facts.length && !states.length)
|
|
364
|
+
return undefined;
|
|
365
|
+
return {
|
|
366
|
+
...(waits.length ? { waits } : {}), ...(facts.length ? { facts } : {}), ...(states.length ? { states } : {}),
|
|
367
|
+
how: 'Put these to the user. Add approved waits with understudy_save { flow, add }, facts with understudy_remember; a state goes in requires when the flow is distilled. Nothing here was written.',
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
export async function closeSession(id) {
|
|
371
|
+
const s = sessions.get(id);
|
|
372
|
+
if (!s)
|
|
373
|
+
return { closed: false };
|
|
374
|
+
sessions.delete(id);
|
|
375
|
+
if (s.timer)
|
|
376
|
+
clearTimeout(s.timer);
|
|
377
|
+
await s.lease.close().catch(() => { });
|
|
378
|
+
return { closed: true };
|
|
379
|
+
}
|
|
380
|
+
/** Close every session — on shutdown, and in tests. */
|
|
381
|
+
export async function closeAllSessions() {
|
|
382
|
+
await Promise.all([...sessions.keys()].map(closeSession));
|
|
383
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Variants: a flow's copy for one version of the app — a branch under test, a
|
|
3
|
+
* preview deploy — kept beside the main flow under the same name.
|
|
4
|
+
*
|
|
5
|
+
* Testing a branch used to mean saving its version of a flow over the main
|
|
6
|
+
* one, so the branch's change became everyone's baseline before it merged.
|
|
7
|
+
* Now:
|
|
8
|
+
*
|
|
9
|
+
* - a variant is its own flow document, `variant: "<name>"`; the main flow
|
|
10
|
+
* has no `variant` at all
|
|
11
|
+
* - anything run with a variant uses that variant's copy of a flow where it
|
|
12
|
+
* has one, and the main flow where it doesn't — a branch that changed the
|
|
13
|
+
* intake form needs a copy of the intake flow only
|
|
14
|
+
* - saving with a variant never touches the main flow
|
|
15
|
+
* - `promote` makes a variant the main flow, once the branch has merged
|
|
16
|
+
*
|
|
17
|
+
* Segments stay main-only: they are shared building blocks, and a branch's
|
|
18
|
+
* copy of one would compete with the real one in every plan.
|
|
19
|
+
*/
|
|
20
|
+
import type { Filter } from 'mongodb';
|
|
21
|
+
import type { Flow, Run } from '../store/types.js';
|
|
22
|
+
/** Throws on a name that can't be a variant; returns it trimmed, or undefined for none. */
|
|
23
|
+
export declare function checkVariant(v: string | undefined): string | undefined;
|
|
24
|
+
/** The filter for one flow: the variant's copy, or (no variant) the main one. */
|
|
25
|
+
export declare const flowKey: (app: string, slug: string, variant?: string) => {
|
|
26
|
+
app: string;
|
|
27
|
+
slug: string;
|
|
28
|
+
variant: string;
|
|
29
|
+
} | {
|
|
30
|
+
app: string;
|
|
31
|
+
slug: string;
|
|
32
|
+
variant: {
|
|
33
|
+
$exists: false;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
/** Main flows only — for anything shared across versions (segments, calibration). */
|
|
37
|
+
export declare const MAIN: {
|
|
38
|
+
variant: {
|
|
39
|
+
$exists: false;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* The flow a name means when running with this variant: its copy if it has
|
|
44
|
+
* one, else the main flow.
|
|
45
|
+
*/
|
|
46
|
+
export declare function resolveFlow(app: string, slug: string, variant?: string): Promise<Flow | null>;
|
|
47
|
+
/**
|
|
48
|
+
* Pure: of flows found by a search, the ones this variant sees — its own
|
|
49
|
+
* copies in place of the main flows they copy, and no other variant's.
|
|
50
|
+
*/
|
|
51
|
+
export declare function pickVariant<T extends Pick<Flow, 'slug' | 'variant'>>(found: T[], variant?: string): T[];
|
|
52
|
+
/** The filter for runs made with this variant — or with none. */
|
|
53
|
+
export declare const runsOf: (variant?: string) => Filter<Run>;
|
|
54
|
+
export interface Promoted {
|
|
55
|
+
flow: string;
|
|
56
|
+
variant: string;
|
|
57
|
+
/** There was a main flow, and the variant replaced it. */
|
|
58
|
+
replaced: boolean;
|
|
59
|
+
/** Segments cut from the old main flow, which still hold its old steps. */
|
|
60
|
+
staleSegments: string[];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Make a variant the main flow: its steps, proof and search entry replace the
|
|
64
|
+
* main flow's (or become it, if there was none), and the variant is gone.
|
|
65
|
+
*/
|
|
66
|
+
export declare function promoteVariant(app: string, slug: string, variant: string): Promise<Promoted>;
|
|
67
|
+
/**
|
|
68
|
+
* Pure: how a variant's steps differ from the main flow's, one line per
|
|
69
|
+
* change, numbered as in the variant (removed steps as in main). Lined up by
|
|
70
|
+
* longest common run of steps, so an inserted step shows as one insertion,
|
|
71
|
+
* not as every step after it changing.
|
|
72
|
+
*/
|
|
73
|
+
export declare function diffFromMain(main: Pick<Flow, 'steps'>, copy: Pick<Flow, 'steps'>, max?: number): string[];
|
|
74
|
+
/** How a variant differs from its main flow, or why there's nothing to compare. */
|
|
75
|
+
export declare function variantDiff(app: string, slug: string, variant: string): Promise<string[]>;
|
|
76
|
+
/** Delete a variant's copy, so runs with that variant use the main flow again. */
|
|
77
|
+
export declare function dropVariant(app: string, slug: string, variant: string): Promise<{
|
|
78
|
+
flow: string;
|
|
79
|
+
variant: string;
|
|
80
|
+
dropped: boolean;
|
|
81
|
+
}>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Variants: a flow's copy for one version of the app — a branch under test, a
|
|
3
|
+
* preview deploy — kept beside the main flow under the same name.
|
|
4
|
+
*
|
|
5
|
+
* Testing a branch used to mean saving its version of a flow over the main
|
|
6
|
+
* one, so the branch's change became everyone's baseline before it merged.
|
|
7
|
+
* Now:
|
|
8
|
+
*
|
|
9
|
+
* - a variant is its own flow document, `variant: "<name>"`; the main flow
|
|
10
|
+
* has no `variant` at all
|
|
11
|
+
* - anything run with a variant uses that variant's copy of a flow where it
|
|
12
|
+
* has one, and the main flow where it doesn't — a branch that changed the
|
|
13
|
+
* intake form needs a copy of the intake flow only
|
|
14
|
+
* - saving with a variant never touches the main flow
|
|
15
|
+
* - `promote` makes a variant the main flow, once the branch has merged
|
|
16
|
+
*
|
|
17
|
+
* Segments stay main-only: they are shared building blocks, and a branch's
|
|
18
|
+
* copy of one would compete with the real one in every plan.
|
|
19
|
+
*/
|
|
20
|
+
import { collections } from '../store/db.js';
|
|
21
|
+
/** `feature/new-intake`, `pr-412`, `staging`. */
|
|
22
|
+
const VARIANT = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/;
|
|
23
|
+
/** Throws on a name that can't be a variant; returns it trimmed, or undefined for none. */
|
|
24
|
+
export function checkVariant(v) {
|
|
25
|
+
if (v === undefined || v.trim() === '')
|
|
26
|
+
return undefined;
|
|
27
|
+
const t = v.trim();
|
|
28
|
+
if (!VARIANT.test(t))
|
|
29
|
+
throw new Error(`variant "${v}" — use letters, digits, . _ / - (a branch name works), up to 80`);
|
|
30
|
+
return t;
|
|
31
|
+
}
|
|
32
|
+
/** The filter for one flow: the variant's copy, or (no variant) the main one. */
|
|
33
|
+
export const flowKey = (app, slug, variant) => variant ? { app, slug, variant } : { app, slug, variant: { $exists: false } };
|
|
34
|
+
/** Main flows only — for anything shared across versions (segments, calibration). */
|
|
35
|
+
export const MAIN = { variant: { $exists: false } };
|
|
36
|
+
/**
|
|
37
|
+
* The flow a name means when running with this variant: its copy if it has
|
|
38
|
+
* one, else the main flow.
|
|
39
|
+
*/
|
|
40
|
+
export async function resolveFlow(app, slug, variant) {
|
|
41
|
+
const { flows } = await collections();
|
|
42
|
+
if (variant) {
|
|
43
|
+
const own = await flows.findOne({ app, slug, variant });
|
|
44
|
+
if (own)
|
|
45
|
+
return own;
|
|
46
|
+
}
|
|
47
|
+
return flows.findOne(flowKey(app, slug));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Pure: of flows found by a search, the ones this variant sees — its own
|
|
51
|
+
* copies in place of the main flows they copy, and no other variant's.
|
|
52
|
+
*/
|
|
53
|
+
export function pickVariant(found, variant) {
|
|
54
|
+
const own = new Set(found.filter((f) => variant && f.variant === variant).map((f) => f.slug));
|
|
55
|
+
return found.filter((f) => (f.variant === undefined ? !own.has(f.slug) : f.variant === variant));
|
|
56
|
+
}
|
|
57
|
+
/** The filter for runs made with this variant — or with none. */
|
|
58
|
+
export const runsOf = (variant) => variant ? { variant } : { variant: { $exists: false } };
|
|
59
|
+
/**
|
|
60
|
+
* Make a variant the main flow: its steps, proof and search entry replace the
|
|
61
|
+
* main flow's (or become it, if there was none), and the variant is gone.
|
|
62
|
+
*/
|
|
63
|
+
export async function promoteVariant(app, slug, variant) {
|
|
64
|
+
const { flows } = await collections();
|
|
65
|
+
const v = await flows.findOne({ app, slug, variant });
|
|
66
|
+
if (!v)
|
|
67
|
+
throw new Error(`no variant "${variant}" of '${slug}' for app '${app}'`);
|
|
68
|
+
const main = await flows.findOne(flowKey(app, slug));
|
|
69
|
+
const { _id, variant: _v, ...rest } = v;
|
|
70
|
+
await flows.replaceOne(flowKey(app, slug), { ...rest, createdAt: main?.createdAt ?? v.createdAt, updatedAt: new Date() }, { upsert: true });
|
|
71
|
+
await flows.deleteOne({ _id: _id });
|
|
72
|
+
const segments = main ? await flows.find({ app, kind: 'segment', 'from.flow': slug, ...MAIN }, { projection: { slug: 1 } }).toArray() : [];
|
|
73
|
+
return { flow: slug, variant, replaced: Boolean(main), staleSegments: segments.map((s) => s.slug) };
|
|
74
|
+
}
|
|
75
|
+
/** One step, as a line a person can compare: `check radio "Yes"`, `fill textbox "Email" = "a@b.c"`. */
|
|
76
|
+
function stepText(s) {
|
|
77
|
+
const target = s.role && s.name ? `${s.role} ${JSON.stringify(s.name)}` : s.name ? JSON.stringify(s.name) : s.testId ? `[${s.testId}]` : s.css ? `[${s.css}]` : '';
|
|
78
|
+
const what = s.valueRef ? ` = <${s.valueRef}>` : s.value !== undefined ? ` = ${JSON.stringify(s.value)}` : '';
|
|
79
|
+
return `${s.action}${target ? ` ${target}` : ''}${what}`;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Pure: how a variant's steps differ from the main flow's, one line per
|
|
83
|
+
* change, numbered as in the variant (removed steps as in main). Lined up by
|
|
84
|
+
* longest common run of steps, so an inserted step shows as one insertion,
|
|
85
|
+
* not as every step after it changing.
|
|
86
|
+
*/
|
|
87
|
+
export function diffFromMain(main, copy, max = 12) {
|
|
88
|
+
const a = main.steps.map(stepText);
|
|
89
|
+
const b = copy.steps.map(stepText);
|
|
90
|
+
const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
|
|
91
|
+
for (let i = a.length - 1; i >= 0; i--)
|
|
92
|
+
for (let j = b.length - 1; j >= 0; j--) {
|
|
93
|
+
lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
94
|
+
}
|
|
95
|
+
const out = [];
|
|
96
|
+
let i = 0;
|
|
97
|
+
let j = 0;
|
|
98
|
+
while (i < a.length || j < b.length) {
|
|
99
|
+
if (i < a.length && j < b.length && a[i] === b[j]) {
|
|
100
|
+
i++;
|
|
101
|
+
j++;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
// A step removed and one added in the same place is one step changed.
|
|
105
|
+
if (i < a.length && j < b.length && lcs[i + 1][j + 1] === lcs[i][j]) {
|
|
106
|
+
out.push(`step ${j}: ${a[i]} → ${b[j]}`);
|
|
107
|
+
i++;
|
|
108
|
+
j++;
|
|
109
|
+
}
|
|
110
|
+
else if (j < b.length && (i >= a.length || lcs[i][j + 1] > lcs[i + 1][j])) {
|
|
111
|
+
out.push(`step ${j} added: ${b[j]}`);
|
|
112
|
+
j++;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
out.push(`main's step ${i} removed: ${a[i]}`);
|
|
116
|
+
i++;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return out.length > max ? [...out.slice(0, max), `…and ${out.length - max} more`] : out;
|
|
120
|
+
}
|
|
121
|
+
/** How a variant differs from its main flow, or why there's nothing to compare. */
|
|
122
|
+
export async function variantDiff(app, slug, variant) {
|
|
123
|
+
const { flows } = await collections();
|
|
124
|
+
const [main, copy] = await Promise.all([flows.findOne(flowKey(app, slug)), flows.findOne({ app, slug, variant })]);
|
|
125
|
+
if (!copy)
|
|
126
|
+
return [];
|
|
127
|
+
if (!main)
|
|
128
|
+
return ['no main flow: this exists only on the variant'];
|
|
129
|
+
const diff = diffFromMain(main, copy);
|
|
130
|
+
return diff.length ? diff : ['same steps as the main flow'];
|
|
131
|
+
}
|
|
132
|
+
/** Delete a variant's copy, so runs with that variant use the main flow again. */
|
|
133
|
+
export async function dropVariant(app, slug, variant) {
|
|
134
|
+
const { flows } = await collections();
|
|
135
|
+
const { deletedCount } = await flows.deleteOne({ app, slug, variant });
|
|
136
|
+
if (!deletedCount)
|
|
137
|
+
throw new Error(`no variant "${variant}" of '${slug}' for app '${app}'`);
|
|
138
|
+
return { flow: slug, variant, dropped: true };
|
|
139
|
+
}
|