@jeffawe/understudy 0.2.0 → 0.2.2

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.
@@ -37,6 +37,46 @@ function narrow(s, loc, pw, warn) {
37
37
  loc += h.nth < 0 ? '.last()' : pw ? `.nth(${h.nth})` : `.eq(${h.nth})`;
38
38
  return loc;
39
39
  }
40
+ /** hints.by → the Playwright lookup that found the name (script.ts NameLookup). */
41
+ const NAME_LOOKUP = {
42
+ placeholder: 'getByPlaceholder', label: 'getByLabel', title: 'getByTitle', alt: 'getByAltText',
43
+ };
44
+ /** A text matcher as source: a regex stays a regex. */
45
+ const matcher = (s, flag, flags) => s.hints?.[flag] ? `/${s.value ?? ''}/${String(s.hints[flags] ?? '')}` : quote(s.value ?? '');
46
+ /** An assert step as `expect(...)`, or a Cypress `should`. */
47
+ function assertion(s, loc, value, pw, warn) {
48
+ const kind = String(s.hints?.assert ?? 'visible');
49
+ const expected = s.valueRef ? value : matcher(s, 'valueRegex', 'valueFlags');
50
+ if (pw) {
51
+ switch (kind) {
52
+ case 'title': return `await expect(page).toHaveTitle(${expected});`;
53
+ case 'visible': return `await expect(${loc}).toBeVisible();`;
54
+ case 'hidden': return `await expect(${loc}).toBeHidden();`;
55
+ case 'text': return `await expect(${loc}).toHaveText(${expected});`;
56
+ case 'contains': return `await expect(${loc}).toContainText(${expected});`;
57
+ case 'value': return `await expect(${loc}).toHaveValue(${expected});`;
58
+ case 'checked': return `await expect(${loc}).toBeChecked();`;
59
+ case 'unchecked': return `await expect(${loc}).not.toBeChecked();`;
60
+ }
61
+ }
62
+ else {
63
+ if (s.hints?.valueRegex)
64
+ warn(`"${describe(s)}" checks a regex, which this Cypress output emits as a substring`);
65
+ const v = s.valueRef ? value : quote(s.value ?? '');
66
+ switch (kind) {
67
+ case 'title': return `cy.title().should('eq', ${v});`;
68
+ case 'visible': return `${loc}.should('be.visible');`;
69
+ case 'hidden': return `${loc}.should('not.be.visible');`;
70
+ case 'text': return `${loc}.invoke('text').should('eq', ${v});`;
71
+ case 'contains': return `${loc}.should('contain.text', ${v});`;
72
+ case 'value': return `${loc}.should('have.value', ${v});`;
73
+ case 'checked': return `${loc}.should('be.checked');`;
74
+ case 'unchecked': return `${loc}.should('not.be.checked');`;
75
+ }
76
+ }
77
+ warn(`"${describe(s)}" is an assertion of a kind this output doesn't know (${kind}); skipped`);
78
+ return `// TODO: assert ${kind}`;
79
+ }
40
80
  /** Best locator first — the same order replay tries, so the code fails where replay would. */
41
81
  function playwrightLocator(s, warn) {
42
82
  const scope = s.frameHint ? `page.frameLocator(${quote(`[id$="${s.frameHint}"]`)})` : 'page';
@@ -46,7 +86,7 @@ function playwrightLocator(s, warn) {
46
86
  if (s.testId)
47
87
  return `${scope}.locator(${quote(`[${s.testIdAttr ?? 'data-testid'}="${s.testId}"]`)})`;
48
88
  if (s.name)
49
- return `${scope}.getByText(${quote(s.name)})`;
89
+ return `${scope}.${NAME_LOOKUP[String(s.hints?.by)] ?? 'getByText'}(${quote(s.name)}${s.exact ? ', { exact: true }' : ''})`;
50
90
  if (s.css) {
51
91
  warn(`"${describe(s)}" is addressed only by CSS — it breaks on any markup change`);
52
92
  return `${scope}.locator(${quote(s.css)})`;
@@ -80,9 +120,10 @@ export function emitFlow(flow, framework = 'playwright-ts') {
80
120
  warnings.push('this flow starts signed in; the generated test starts signed out — add a login first');
81
121
  const lines = [];
82
122
  for (const s of flow.steps) {
83
- if (s.action === 'snapshot' || s.action === 'assert')
123
+ if (s.action === 'snapshot')
84
124
  continue;
85
- const loc = s.action === 'goto' ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
125
+ const pageLevel = s.action === 'goto' || s.action === 'wait_url' || s.action === 'wait_text' || (s.action === 'assert' && s.hints?.assert === 'title');
126
+ const loc = pageLevel ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
86
127
  const value = s.valueRef ? (required.add(s.valueRef), envName(s.valueRef).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
87
128
  switch (s.action) {
88
129
  case 'goto':
@@ -113,7 +154,12 @@ export function emitFlow(flow, framework = 'playwright-ts') {
113
154
  lines.push(pw ? `await ${loc}.scrollIntoViewIfNeeded();` : `${loc}.scrollIntoView();`);
114
155
  break;
115
156
  case 'wait_url':
116
- lines.push(pw ? `await page.waitForURL(new RegExp(${quote(s.value ?? '')}));` : `cy.url().should('include', ${value});`);
157
+ lines.push(pw
158
+ ? `await page.waitForURL(${s.hints?.urlRegex ? matcher(s, 'urlRegex', 'urlFlags') : s.value?.includes('*') ? quote(s.value) : `(u) => u.href.includes(${value})`});`
159
+ : `cy.url().should('${s.hints?.urlRegex ? 'match' : 'include'}', ${s.hints?.urlRegex ? matcher(s, 'urlRegex', 'urlFlags') : value});`);
160
+ break;
161
+ case 'assert':
162
+ lines.push(assertion(s, loc, value, pw, warn));
117
163
  break;
118
164
  case 'wait_text':
119
165
  lines.push(pw ? `await page.getByText(${value}).waitFor();` : `cy.contains(${value});`);
@@ -127,7 +173,7 @@ export function emitFlow(flow, framework = 'playwright-ts') {
127
173
  const header = `// ${flow.intent}\n// Generated by understudy from flow "${flow.app}/${flow.slug}". Regenerate rather than edit.\n\n`;
128
174
  const body = (indent) => lines.map((l) => indent + l).join('\n');
129
175
  const code = pw
130
- ? `import { test } from '@playwright/test';\n\n${header}${preamble}test(${quote(flow.title)}, async ({ page }) => {\n${body(' ')}\n});\n`
176
+ ? `import { test${lines.some((l) => l.includes('expect(')) ? ', expect' : ''} } from '@playwright/test';\n\n${header}${preamble}test(${quote(flow.title)}, async ({ page }) => {\n${body(' ')}\n});\n`
131
177
  : `${header}${preamble}describe(${quote(flow.title)}, () => {\n it(${quote(flow.title)}, () => {\n${body(' ')}\n });\n});\n`;
132
178
  return { framework, code, warnings, requiredValues: refs };
133
179
  }
@@ -21,6 +21,17 @@ export declare function extractFindings(result: Pick<ReplayResult, 'signals' | '
21
21
  * occurrence. A finding someone already triaged keeps its status.
22
22
  */
23
23
  export declare function saveFindings(coll: Collection<Finding>, app: string, drafts: FindingDraft[], at?: Date): Promise<void>;
24
+ /**
25
+ * Findings for an app, MOST SEVERE FIRST, then most frequent, then newest.
26
+ *
27
+ * Frequency alone put eight framework image warnings above the one real
28
+ * regression: a noisy console fires on every page, a broken route once.
29
+ * Sorted here rather than in the query because severity is a word, not a rank.
30
+ */
31
+ export declare function listFindings(coll: Collection<Finding>, app: string, opts?: {
32
+ all?: boolean;
33
+ limit?: number;
34
+ }): Promise<Finding[]>;
24
35
  export type Verdict = 'issue' | 'lesson' | 'noise';
25
36
  /**
26
37
  * Route open findings. issue: the app is wrong and someone should fix it.
@@ -12,7 +12,9 @@ export function stable(text) {
12
12
  return text
13
13
  .replace(/(https?:\/\/[^\s'"?#]+)\?[^\s'"]*/g, '$1')
14
14
  .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, ':uuid')
15
- .replace(/\b\d{3,}\b/g, ':n')
15
+ // Not a port: `localhost:3000` is where the app is, not a varying id, and
16
+ // replacing it produced `localhost::n`.
17
+ .replace(/(?<![\w\]]:)\b\d{3,}\b/g, ':n')
16
18
  .replace(/\s+/g, ' ')
17
19
  .trim()
18
20
  .slice(0, 300);
@@ -111,6 +113,21 @@ export async function saveFindings(coll, app, drafts, at = new Date()) {
111
113
  },
112
114
  })));
113
115
  }
116
+ const SEVERITY_RANK = { high: 3, medium: 2, low: 1 };
117
+ /**
118
+ * Findings for an app, MOST SEVERE FIRST, then most frequent, then newest.
119
+ *
120
+ * Frequency alone put eight framework image warnings above the one real
121
+ * regression: a noisy console fires on every page, a broken route once.
122
+ * Sorted here rather than in the query because severity is a word, not a rank.
123
+ */
124
+ export async function listFindings(coll, app, opts = {}) {
125
+ const rows = await coll.find(opts.all ? { app } : { app, status: 'open' }).toArray();
126
+ rows.sort((a, b) => (SEVERITY_RANK[b.severity] ?? 0) - (SEVERITY_RANK[a.severity] ?? 0)
127
+ || (b.occurrences ?? 0) - (a.occurrences ?? 0)
128
+ || +new Date(b.lastSeen) - +new Date(a.lastSeen));
129
+ return rows.slice(0, opts.limit ?? 40);
130
+ }
114
131
  /**
115
132
  * Route open findings. issue: the app is wrong and someone should fix it.
116
133
  * lesson: accepted — the agent works around it (pass the lesson to store).
@@ -32,7 +32,7 @@ export async function recordRun(opts) {
32
32
  // page it never reached as "gone", which is noise, not drift.
33
33
  const drift = result.ok
34
34
  ? compareToHistory(result.sigSequence, history.map((h) => h.sigSequence))
35
- : compareToHistory([], []);
35
+ : { ...compareToHistory([], []), firstRun: false, notCompared: 'the run failed, so its path is incomplete' };
36
36
  // 2. Findings.
37
37
  const name = plan.join(' + ');
38
38
  const drafts = extractFindings(result, name);
@@ -98,6 +98,11 @@ async function block(run, why, detail) {
98
98
  async function advance(run) {
99
99
  const planning = (run.planning ??= {});
100
100
  const { flows } = await collections();
101
+ // 0. Nothing to plan with. Asking how to split a goal across flows that
102
+ // don't exist wastes a round trip and suggests memory knows something.
103
+ if (!(await flows.countDocuments({ app: run.app }, { limit: 1 }))) {
104
+ return block(run, `"${run.app}" has no saved flows yet — record one (understudy_record, then understudy_save), or drive it yourself and save the script (understudy_save with script)`);
105
+ }
101
106
  // 1. Split the goal.
102
107
  if (!planning.subGoals) {
103
108
  return ask(run, { kind: 'decompose', goal: run.goal, how: DECOMPOSE_HOW, vocabulary: await vocabulary(run.app) });
@@ -5,7 +5,13 @@ signed in or not — instead of a fresh browser that Understudy opens.
5
5
 
6
6
  ## Install (once)
7
7
 
8
- `understudy extension` prints where this folder is.
8
+ **Chrome, Brave, Arc, Opera, Vivaldi, Edge:** install it from the
9
+ [Chrome Web Store](https://chromewebstore.google.com/detail/understudy-recorder/mdobdjogkgimabdpmbmhhcdeoahoapjf), then pin it (puzzle-piece icon → pin
10
+ **Understudy recorder**) so it's one click away. Edge asks you to allow
11
+ extensions from other stores first.
12
+
13
+ **Or load it by hand**= — `understudy extension`
14
+ prints where this folder is:
9
15
 
10
16
  1. Open your browser's extensions page and turn on **Developer mode**:
11
17
  | Browser | Extensions page |
@@ -17,15 +23,6 @@ signed in or not — instead of a fresh browser that Understudy opens.
17
23
  2. Click **Load unpacked** and choose this `extension/` folder.
18
24
  3. Pin it (puzzle-piece icon → pin **Understudy recorder**) so it's one click away.
19
25
 
20
- Tested in Chrome and Chromium. Other Chromium-based browsers load Chrome
21
- extensions the same way and should work.
22
-
23
- **Firefox:** until it's listed on Firefox Add-ons, load the Firefox build
24
- yourself — it ships with Understudy, and `understudy extension` prints where.
25
- In Firefox open `about:debugging#/runtime/this-firefox` → **Load Temporary
26
- Add-on…** → choose `manifest.json` in that folder. Firefox removes temporary
27
- add-ons when it restarts.
28
-
29
26
  **Safari (and anywhere else the extension won't run):** record in a fresh
30
27
  browser that Understudy opens instead. It's a one-time extra download — the
31
28
  full Chromium browser, about 350 MB:
@@ -52,7 +49,7 @@ in the terminal to start recording from there.
52
49
  will start signed in too. Not sure? Leave it: Understudy copies the tab's
53
50
  sign-in anyway, then when you `save` it tries the flow without it first,
54
51
  and deletes the copy if it wasn't needed. Either way it's a file on your
55
- machine (`.understudy/sessions/`, readable only by you), never sent
52
+ machine (`~/.understudy/sessions/`, readable only by you), never sent
56
53
  anywhere else.
57
54
  4. Use the page as normal. The icon shows **REC**.
58
55
  5. Click the icon → say what the flow does → **Stop**. With **Save as a flow
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jeffawe/understudy",
3
- "version": "0.2.0",
4
- "description": "End-to-end tests for your own web apps: record a flow once, and Understudy remembers it, replays it, notices when the app changes, and runs goals you describe in words \u2014 on its own or as an MCP server for AI agents.",
3
+ "version": "0.2.2",
4
+ "description": "End-to-end tests for your own web apps: record a flow once, and Understudy remembers it, replays it, notices when the app changes, and runs goals you describe in words — on its own or as an MCP server for AI agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -26,8 +26,8 @@
26
26
  "node": ">=22"
27
27
  },
28
28
  "bin": {
29
- "understudy": "./dist/entry/cli.js",
30
- "understudy-mcp": "./dist/entry/mcp.js"
29
+ "understudy": "dist/entry/cli.js",
30
+ "understudy-mcp": "dist/entry/mcp.js"
31
31
  },
32
32
  "files": [
33
33
  "dist",
@@ -42,7 +42,7 @@
42
42
  "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
43
43
  "build": "npm run clean && tsc",
44
44
  "typecheck": "tsc --noEmit",
45
- "test": "node --import tsx --test test/*.test.ts",
45
+ "test": "node --import tsx --import ./test/setup.ts --test test/*.test.ts",
46
46
  "prepack": "npm run extension:package && npm run build",
47
47
  "understudy": "tsx src/entry/cli.ts",
48
48
  "mcp": "tsx src/entry/mcp.ts",