@usercase/mcp 0.2.3-next.0 → 0.2.3-next.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.
package/README.md CHANGED
@@ -106,7 +106,7 @@ Claude suggests the moment, the question and its answers, and saves it only afte
106
106
  - They stay on your site and block analytics tools such as Google Analytics and Hotjar.
107
107
  - Either way they never pay, delete, connect a wallet, sign out or change a password, and never type into personal fields such as email or phone.
108
108
  - They stop when blocked. They do not solve CAPTCHAs or get around bot protection.
109
- - When they cannot do something on your site, a short diagnostic (what failed and the element's shape, never its text) is sent to Usercase so the tool gets better. Turn it off with `USERCASE_DIAGNOSTICS=off`.
109
+ - When the tool cannot do something on your site or misreads the screen, a diagnostic is sent to Usercase so the tool gets better: what failed, the page path, the HTML around the element and a screenshot of that moment. Only the Usercase team sees it, and it is kept for 30 days. Turn it off with `USERCASE_DIAGNOSTICS=off`.
110
110
 
111
111
  ## Running on a production site
112
112
 
@@ -133,7 +133,7 @@ Pass with `claude mcp add ... -e NAME=value`.
133
133
  | `USERCASE_API_KEY` | Your project API key. Without it, visits stay on your machine only. |
134
134
  | `USERCASE_AGENT_KEY` | Your firewall secret (see above). 16+ characters. |
135
135
  | `USERCASE_ALLOW_WRITE_PATHS` | Comma-separated path patterns where non-GET requests are allowed, for sites that load pages with `POST` after sign-in. Everything else stays blocked. |
136
- | `USERCASE_DIAGNOSTICS` | `off` stops sending diagnostics. On by default: when a visitor cannot do something (a button cut off, covered or unreachable), the kind of failure and the element's shape (tag, icon or not, inside a carousel or dialog, size) are sent to Usercase to improve the tool. No text, addresses or input from your site are sent. |
136
+ | `USERCASE_DIAGNOSTICS` | `off` stops sending diagnostics. On by default: when the tool cannot do something or misreads the screen (a button cut off or covered, a click that landed elsewhere, a change it did not notice), Usercase receives the kind of failure, the element's shape, the page path, the HTML around the element and a screenshot of that moment, to improve the tool. Only the Usercase team sees them; they are kept for 30 days. |
137
137
  | `USERCASE_HEADED` | `1` shows the visitors' browser on screen. |
138
138
  | `USERCASE_DIR` | Working folder. Default: `.usercase` in your repository. |
139
139
 
package/mcp/hub.js CHANGED
@@ -200,10 +200,10 @@ class Hub {
200
200
  ? "· Writes: SENT — visitors really sign up, post, comment and save on this site (payments, deleting and sign-out stay blocked). Change with set_writes"
201
201
  : "· Writes: not sent — visitors may press Post or Save, but nothing is written to the site. Ask the user before the first round whether to send them (set_writes)",
202
202
  );
203
- // 도구가 하지 못한 것(진단) — 사이트 글자·주소 없이 종류와 요소 생김새만 우리 서버로 간다
203
+ // 도구가 하지 못한 것(진단) — 그 순간의 화면·요소 주변 HTML·페이지 경로가 우리 서버로 간다. 고객에게 숨기지 않는다
204
204
  out.push(
205
205
  require("../src/run/diag.js").enabled()
206
- ? "· Diagnostics on — when a visitor cannot do something (a button cut off, covered, unreachable), the kind of failure and the element's shape (tag, icon, in a carousel …) go to Usercase to improve the tool. No text, addresses or input from the site. Turn off with USERCASE_DIAGNOSTICS=off"
206
+ ? "· Diagnostics on — when the tool cannot do something or misreads the screen, Usercase gets what failed, the page path, the HTML around the element and a screenshot of that moment, to fix the tool. Only the Usercase team sees them; they are not shown in your dashboard. Turn off with USERCASE_DIAGNOSTICS=off"
207
207
  : "· Diagnostics off (USERCASE_DIAGNOSTICS=off)",
208
208
  );
209
209
  // 지키는 선을 고객이 볼 수 있게. 막혔는데 왜인지 모르면 우리 도구 탓으로 읽힌다
@@ -516,15 +516,15 @@ class Hub {
516
516
  ms: Date.now() - rec.startedAt,
517
517
  sdkReady: rec.visit ? !!rec.visit.sdk?.ready : null,
518
518
  ...(rec.account ? { account: rec.account } : {}),
519
- // 도구가 하지 못한 것 — 고객도 자기 기록에서 볼 수 있게 같이 남긴다(서버로 가는 것과 같은 내용)
520
- ...(rec.visit && rec.visit.diag && rec.visit.diag.length ? { diag: rec.visit.diag } : {}),
519
+ // 도구가 하지 못한 것 — 고객도 자기 기록에서 볼 수 있게 종류만 남긴다(HTML·화면은 서버로만)
520
+ ...(rec.visit && rec.visit.diag && rec.visit.diag.length ? { diag: rec.visit.diag.map(({ kind, action, shape, detail }) => ({ kind, action, shape, detail })) } : {}),
521
521
  ...extra,
522
522
  };
523
523
  ws.appendRun(row);
524
524
  // 대시보드로 — 키가 없으면 건너뛴다. 실패해도 방문은 끝낸다
525
525
  const uploaded = await report.sendVisit(row, rec.person, rec.startedAt, rec.visit ? rec.visit.screens : []).catch((e) => `⚠ Could not upload to the dashboard (${e.message})`);
526
- // 도구가 하지 못한 것들 — 우리 쪽 진단으로(사이트 글자 없음). 기본으로 켜져 있다, USERCASE_DIAGNOSTICS=off 로 끈다
527
- if (rec.visit && rec.visit.diag && rec.visit.diag.length) await report.sendDiagnostics(rec.visit.diag, rec.person.device).catch(() => 0);
526
+ // 도구가 하지 못한 것들 — 우리 쪽 진단으로(화면·HTML 포함, 고객 대시보드에는 안 보인다). 기본으로 켜져 있다, USERCASE_DIAGNOSTICS=off 로 끈다
527
+ if (rec.visit && rec.visit.diag && rec.visit.diag.length) await report.sendDiagnostics(rec.visit.diag, rec.person.device, rec.visit.diagShots).catch(() => 0);
528
528
  const doc = ws.loadPeople();
529
529
  const p = doc.people.find((x) => x.id === rec.person.id);
530
530
  if (p) {
package/mcp/report.js CHANGED
@@ -168,14 +168,17 @@ async function sendVisit(row, person, startedAt, screens = []) {
168
168
  }
169
169
 
170
170
  /**
171
- * 도구가 하지 못한 것들(진단)을 보낸다 — 우리 도구를 고치려고. 사이트 글자·주소는 없다(src/run/diag.js).
171
+ * 도구가 하지 못했거나 잘못 본 것들(진단)을 보낸다 — 우리 도구를 고치려고. 고객 대시보드에는 안 보인다.
172
+ * 그 순간의 페이지 경로·요소 주변 HTML·화면을 같이 보낸다 — 종류만으로는 못 고친다(10/22, src/run/diag.js).
172
173
  * 키가 있고 꺼 두지 않았을 때만. 실패해도 조용히 넘어간다 — 방문과는 상관없다
173
174
  */
174
- async function sendDiagnostics(events, device) {
175
+ async function sendDiagnostics(events, device, shots = []) {
175
176
  const diag = require("../src/run/diag.js");
176
177
  if (!events || !events.length || !diag.enabled() || !KEY_RE.test(apiKey())) return 0;
177
178
  try {
178
179
  const out = await call("POST", "/agent/diagnostics", { run: RUN_REF, version: require("../package.json").version, device, events: events.slice(0, 100) });
180
+ // 화면은 진단 줄이 생긴 뒤에 — 진단 id 로 붙는다
181
+ for (const s of shots) await call("POST", "/agent/diagnostics/screen", { id: s.id, image: s.image.toString("base64") }).catch(() => null);
179
182
  return (out && out.saved) || 0;
180
183
  } catch {
181
184
  return 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usercase/mcp",
3
- "version": "0.2.3-next.0",
3
+ "version": "0.2.3-next.2",
4
4
  "description": "Virtual users that browse your website and tell you what they thought — an MCP server for Claude Code",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://usercase.io",
@@ -137,6 +137,83 @@ async function coveredBy(page, el) {
137
137
  return { invisible: true, x: cx, y: cy };
138
138
  }
139
139
 
140
+ /** 그 점을 지금 누르면 그 요소에 닿나 */
141
+ async function hits(el, x, y) {
142
+ return el
143
+ .evaluate((node, [qx, qy]) => {
144
+ const hit = document.elementFromPoint(qx, qy);
145
+ return !!hit && (node === hit || node.contains(hit) || hit.contains(node));
146
+ }, [x, y])
147
+ .catch(() => false);
148
+ }
149
+
150
+ /**
151
+ * 겨눈 곳으로 가서 누른다. 누르기 직전에 그 자리에 아직 그것이 있나 본다 — 저절로 넘어가는 배너는
152
+ * 커서가 가는 사이 다음 카드가 와서, OKX 를 누르려다 Uniswap 이 열렸다(10/22 실험실 k5). 옮겨 갔으면 다시 겨눈다.
153
+ * 헛클릭(missed)은 원래 빈 곳이라 그대로 누른다. 끝내 못 맞추면 null
154
+ */
155
+ async function pressAt(page, state, el, aim) {
156
+ for (let t = 0; t < 3 && aim; t++) {
157
+ await moveTo(page, state, aim.x, aim.y);
158
+ await sleep(rand(40, 140));
159
+ if (aim.missed || (await hits(el, aim.x, aim.y))) {
160
+ await page.mouse.click(aim.x, aim.y);
161
+ return aim;
162
+ }
163
+ aim = await aimAt(page, state, el);
164
+ }
165
+ return null;
166
+ }
167
+
168
+ /**
169
+ * 화면 안에 보이는 같은 것(쌍둥이). 무한히 도는 배너(slick 등)는 카드마다 복사본을 앞뒤에 깔아 둔다 —
170
+ * 잡은 것이 화면 밖 복사본이면 사람은 화면에 보이는 그 카드를 누른다(10/22 실험실 k5: 같은 카드가 3벌)
171
+ */
172
+ async function visibleTwin(page, el, vw) {
173
+ const h = await el
174
+ .evaluateHandle((node, w) => {
175
+ const key = (n) => [n.tagName, n.getAttribute("href") || "", (n.textContent || "").replace(/\s+/g, " ").trim()].join("|");
176
+ const k = key(node);
177
+ if (k.length < 8) return null;
178
+ for (const n of document.querySelectorAll(node.tagName)) {
179
+ if (n === node || key(n) !== k) continue;
180
+ const r = n.getBoundingClientRect();
181
+ const cx = r.x + r.width / 2;
182
+ const cy = r.y + r.height / 2;
183
+ if (r.width > 0 && cx > 1 && cx < w - 1 && cy > 1 && cy < innerHeight - 1) return n;
184
+ }
185
+ return null;
186
+ }, vw)
187
+ .catch(() => null);
188
+ const twin = h && h.asElement();
189
+ return twin || null;
190
+ }
191
+
192
+ /**
193
+ * 저절로 넘어가는 줄(자동 배너)에서 잘린 것 — 사람은 밀지 않고 그 카드가 돌아와 화면 안에 들 때까지 본다.
194
+ * 3.5초 동안 안 움직이면 멈춰 있는 줄이다(null — 밀어야 한다). 8초 안에 화면 가운데쯤 오면 그것(또는 복사본)
195
+ */
196
+ async function waitComeAround(page, el, vw) {
197
+ const first = await el.boundingBox().catch(() => null);
198
+ if (!first) return null;
199
+ let moved = false;
200
+ for (let i = 0; i < 32; i++) {
201
+ await sleep(250);
202
+ const b = await el.boundingBox().catch(() => null);
203
+ if (!b) return null;
204
+ if (Math.abs(b.x - first.x) > 3) moved = true;
205
+ // 자동 배너는 보통 3초마다 넘어간다
206
+ if (!moved && i >= 14) return null;
207
+ if (!moved) continue;
208
+ const c = b.x + b.width / 2;
209
+ if (c > vw * 0.15 && c < vw * 0.85) return el;
210
+ // 무한 배너는 복사본이 대신 돌아온다
211
+ const twin = await visibleTwin(page, el, vw);
212
+ if (twin) return twin;
213
+ }
214
+ return null;
215
+ }
216
+
140
217
  /** 손가락으로 옆으로 민다(Chrome 터치 입력). 터치가 없는 화면이면 아무 일 없다 */
141
218
  async function touchSwipe(page, x0, x1, y) {
142
219
  const cdp = await page.context().newCDPSession(page);
@@ -283,17 +360,29 @@ async function clickLikePerson(page, state, el) {
283
360
  // 가로로 넘치는 줄(회전 배너·가로 목록) 안에서 잘린 것이면, 사람은 그 줄을 옆으로 밀어 가져온 뒤 누른다
284
361
  // (10/15 실험실 p1·p3: 모바일 첫 화면 배너 끝에 걸친 카드를 끝내 못 눌렀다)
285
362
  if (bb && (bb.x + bb.width / 2 > vw - 1 || bb.x + bb.width / 2 < 1)) {
286
- const swiped = await swipeIntoView(page, state, el, vw).catch(() => false);
287
- if (swiped) {
288
- bb = await el.boundingBox().catch(() => null);
289
- const again = await aimAt(page, state, el);
290
- if (again && bb && bb.x + bb.width / 2 > 1 && bb.x + bb.width / 2 < vw - 1) {
291
- await moveTo(page, state, again.x, again.y);
292
- await sleep(rand(40, 140));
293
- await page.mouse.click(again.x, again.y);
294
- return { missed: again.missed, swiped: true };
295
- }
363
+ const twin = await visibleTwin(page, el, vw);
364
+ if (twin) {
365
+ const got = await pressAt(page, state, twin, await aimAt(page, state, twin));
366
+ if (got) return { missed: got.missed };
296
367
  }
368
+ // 저절로 넘어가는 줄이면 밀지 않고 돌아오길 기다린다. 넘어가는 줄을 밀면 반쯤은 엇나가 "잘렸다" 로 끝났다(10/22 실험실 k5)
369
+ const round = await waitComeAround(page, el, vw);
370
+ if (round) {
371
+ const came = await pressAt(page, state, round, await aimAt(page, state, round));
372
+ if (came) return { missed: came.missed };
373
+ }
374
+ await swipeIntoView(page, state, el, vw).catch(() => false);
375
+ // 무한 배너는 밀고 나면 잡은 것 대신 그 복사본이 화면에 와 있다 — 화면에 든 쪽을 누른다(10/22 실험실 k5)
376
+ bb = await el.boundingBox().catch(() => null);
377
+ const inView = bb && bb.x + bb.width / 2 > 1 && bb.x + bb.width / 2 < vw - 1;
378
+ const target = inView ? el : await visibleTwin(page, el, vw);
379
+ const done = target ? await pressAt(page, state, target, await aimAt(page, state, target)) : null;
380
+ if (done) return { missed: done.missed, swiped: true };
381
+ // 밀어도 못 가져왔다 — 저절로 넘어가는 줄이면 한 번 더 돌아오길 기다린다
382
+ const later = await waitComeAround(page, el, vw);
383
+ const came = later ? await pressAt(page, state, later, await aimAt(page, state, later)) : null;
384
+ if (came) return { missed: came.missed, swiped: true };
385
+ bb = await el.boundingBox().catch(() => null);
297
386
  }
298
387
  if (bb && (bb.x + bb.width / 2 > vw - 1 || bb.x + bb.width / 2 < 1)) {
299
388
  const say = bb.x < vw && bb.x + bb.width > 0 ? "it is cut off at the edge of the screen — only a sliver of it shows, and you cannot reach it" : "it is off the edge of the screen and you cannot reach it";
@@ -305,10 +394,24 @@ async function clickLikePerson(page, state, el) {
305
394
  await el.click({ timeout: 8000 });
306
395
  return { missed: false };
307
396
  }
308
- await moveTo(page, state, aim.x, aim.y);
309
- await sleep(rand(40, 140));
310
- await page.mouse.click(aim.x, aim.y);
311
- return { missed: aim.missed };
397
+ const done = await pressAt(page, state, el, aim);
398
+ if (done) return { missed: done.missed };
399
+ // 누르려는 사이 자꾸 옮겨 갔다 — 저절로 넘어가는 줄이다. 한 번 돌아오길 기다려 본다
400
+ const vw = (page.viewportSize() || { width: 1200 }).width;
401
+ const twin = await visibleTwin(page, el, vw);
402
+ if (twin) {
403
+ const got = await pressAt(page, state, twin, await aimAt(page, state, twin));
404
+ if (got) return { missed: got.missed };
405
+ }
406
+ const round = await waitComeAround(page, el, vw);
407
+ if (round) {
408
+ const came = await pressAt(page, state, round, await aimAt(page, state, round));
409
+ if (came) return { missed: came.missed };
410
+ }
411
+ const say = "it slid away as you went to tap it — that row moves by itself";
412
+ const e = new Error(say);
413
+ e.human = say;
414
+ throw e;
312
415
  }
313
416
 
314
417
  const NEAR = { a: "s", s: "d", d: "f", f: "g", g: "h", h: "j", j: "k", k: "l", l: "k", q: "w", w: "e", e: "r", r: "t", t: "y", y: "u", u: "i", i: "o", o: "p", p: "o", z: "x", x: "c", c: "v", v: "b", b: "n", n: "m", m: "n" };
package/src/run/diag.js CHANGED
@@ -5,8 +5,10 @@
5
5
  * 사이트마다 다른 이유로 막힌다(회전 배너를 밀 수 없어서, 화면 밖으로 잘려서, 덮개 때문에 …).
6
6
  * bluetags 하나로는 다 못 찾는다(10/15 — 스와이프가 없어서 배너 끝 카드를 못 눌렀다).
7
7
  *
8
- * **사이트 글자·주소·입력값은 보내지 않는다.** 실패의 종류와 요소의 생김새(태그·역할·아이콘인지·회전 배너 안인지·
9
- * 고정 위치인지·대화상자 안인지·크기)만. 고객 방문 기록(/agent/visits)과 따로 간다.
8
+ * 실패의 종류와 요소의 생김새(태그·역할·아이콘인지·회전 배너 안인지·고정 위치인지·대화상자 안인지·크기)에 더해
9
+ * 그 순간의 페이지 경로·요소 주변 HTML·화면을 보낸다(10/22 — 종류만으로는 무한 배너 복사본 같은 원인을 못 찾았다).
10
+ * 우리만 본다 — 고객 대시보드에는 안 보인다. 고객 방문 기록(/agent/visits)과 따로 간다.
11
+ * 도구가 못 한 것뿐 아니라 잘못 본 것도 — 방문자의 다음 말과 도구 판단이 엇갈리면(visit.js checkLastJudgement)
10
12
  * 기본으로 켜져 있고 USERCASE_DIAGNOSTICS=off 로 끈다. API 키가 있을 때만 간다(키가 프로젝트를 정한다).
11
13
  */
12
14
 
@@ -17,6 +19,7 @@ const enabled = () => !OFF.test(String(process.env.USERCASE_DIAGNOSTICS || "").t
17
19
  function kindOf(skipped) {
18
20
  const s = String(skipped || "");
19
21
  if (/cut off at the edge|off the edge of the screen/.test(s)) return "cut_off";
22
+ if (/slid away as you went to tap it/.test(s)) return "moving";
20
23
  if (/survey card is on top/.test(s)) return "covered_by_card";
21
24
  if (/on top of it/.test(s)) return "covered";
22
25
  if (/greyed out/.test(s)) return "disabled";
package/src/run/visit.js CHANGED
@@ -18,6 +18,7 @@
18
18
  */
19
19
  const fs = require("fs");
20
20
  const path = require("path");
21
+ const { randomUUID } = require("crypto");
21
22
  const { listControls, visibleText, handleAt, clickBlocked } = require("../browser/page.js");
22
23
  const { readCard, waitCard, screenText, answerCard, noteReason, sleep, waitForSdk } = require("../browser/card.js");
23
24
  const hand = require("../browser/hand.js");
@@ -47,14 +48,50 @@ const MAX_TIMES = { click: 4, scroll: 5, scroll_up: 5 };
47
48
  * 걸음마다 찍지 않는다. 영상(세션 리플레이)은 봇의 움직임이 드러나 쓰지 않기로 했다(10/21)
48
49
  * no_change 눌렀는데 화면이 그대로
49
50
  * left_unhappy 원하던 걸 못 이루고 떠남(leave, done=false) — 마지막 화면
50
- * bounced 들어오자마자 뒤로
51
- * card 질문 카드가 뜬 화면 — 카드는 걸음이 아니라 바로 앞 걸음에 붙인다(첫 걸음 전이면 다음 걸음)
51
+ * covered 사이트의 무언가(팝업 등)가 덮어 못 누름 — 우리 카드·위젯이 덮은 것은 뺀다
52
+ * error 화면이 깨짐 — 문서가 오류로 옴(4xx·5xx), 오류 문구뿐인 화면.
53
+ * 끝내 안 열리는 화면은 못 찍는다 — 불러오는 중에는 브라우저가 화면을 안 내준다(10/22 시험)
54
+ * 우리 카드(Usercase 질문 카드)는 찍지 않는다 — 사이트 문제가 아니다. 카드가 떠 있는 동안도 안 찍는다(10/22)
52
55
  * 누른 곳(box)은 사진에 그리지 않고 걸음에 비율(0~1)로 적는다. 대시보드가 위에 그린다
53
56
  */
54
57
  const MAX_SCREENS = 6;
58
+ /** 진단(도구가 못 했거나 잘못 본 것)마다 찍는 화면 — 우리만 본다. 고객 대시보드에는 안 간다(10/22) */
59
+ const MAX_DIAG_SHOTS = 6;
60
+ /** 진단에 붙이는 요소 주변 HTML 길이 */
61
+ const MAX_DIAG_HTML = 6000;
62
+ /** 진단으로 볼 만한 것이 아니다 — 의도한 동작(밀어서 가져옴·사람 같은 헛클릭) */
63
+ const DIAG_NO_CONTEXT = new Set(["swiped", "missed"]);
64
+ // 방문자가 바로 다음에 하는 말 — 도구 판단과 엇갈리면 도구가 잘못 본 것이다
65
+ const SAYS_CHANGED = /\b(saved|bookmarked|liked|went (blue|red|green|grey|gray|dark|bold)|turned (blue|red|green|on|off)|it (worked|opened|changed)|that (worked|opened)|now (shows|says)|popped (up|open)|opened up)\b/i;
66
+ const SAYS_NOTHING = /\b(nothing happened|nothing changed|didn.?t (open|work|do anything|respond|change|load|go anywhere)|not (working|responding|loading)|won.?t (open|load|work)|still the same|no response|dead)\b/i;
55
67
  // 서버 앞 nginx 의 기본 본문 한도가 1MB 다 — base64 로 커지니 원본은 600KB 아래로
56
68
  const MAX_SCREEN_BYTES = 600 * 1024;
57
69
 
70
+ /**
71
+ * 오류 문구뿐인 화면인가 — 404·"not found"·"application error" 등. 글이 짧은 화면만 본다(기사 속 "404" 는 아니다).
72
+ * 클라이언트에서 그리는 404(Next.js 등)는 문서가 200 으로 와서 상태로는 모른다
73
+ */
74
+ async function errorScreen(page) {
75
+ return page
76
+ .evaluate(() => {
77
+ const t = ((document.body && document.body.innerText) || "").replace(/\s+/g, " ").trim();
78
+ if (t.length > 600) return false;
79
+ return /\b(404|500|502|503)\b|not found|page (doesn.?t|does not|could not|cannot) (exist|be found)|application error|something went wrong|internal server error/i.test(t);
80
+ })
81
+ .catch(() => false);
82
+ }
83
+
84
+ /** 같은 사이트 주소의 경로(+쿼리). 다른 사이트면 null */
85
+ function sameDocPath(href, base) {
86
+ try {
87
+ const u = new URL(href, base);
88
+ if (u.origin !== new URL(base).origin) return null;
89
+ return (u.pathname.replace(/\/+$/, "") || "/") + u.search;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+
58
95
  /** 요소가 화면에서 차지한 곳(화면 비율). 화면 밖이거나 사라졌으면 null */
59
96
  async function boxOf(page, el) {
60
97
  const b = el ? await el.boundingBox().catch(() => null) : null;
@@ -70,13 +107,22 @@ async function boxOf(page, el) {
70
107
  }
71
108
 
72
109
  /**
73
- * 누르기 전후를 견줄 지문 — 주소, 페이지 전체 글(보이는 것만, 굴려도 같다), 누른 요소의 상태(색만 바뀌는 좋아요·토글).
110
+ * 누르기 전후를 견줄 지문 — 주소, 페이지 전체 글(보이는 것만, 굴려도 같다), 보이는 입력칸·그림, 누른 요소와 감싼 버튼의 상태·HTML(색만 바뀌는 좋아요·저장·토글).
111
+ * 입력칸은 글(innerText)에 안 잡힌다 — 검색 아이콘을 눌러 검색칸이 열렸는데 "그대로" 로 찍혔다(10/22 실험실 e4)
74
112
  * 글이 저절로 바뀌는 사이트(넘어가는 배너)에서는 "바뀌었다" 로 본다 — 그대로라고 잘못 찍는 것보다 낫다
75
113
  */
76
114
  async function clickPrint(page, el) {
77
115
  const doc = await page
78
116
  .evaluate(() => {
79
- const t = (document.body && document.body.innerText) || "";
117
+ const shown = (n) => {
118
+ const r = n.getBoundingClientRect();
119
+ return r.width > 0 && r.height > 0 && getComputedStyle(n).visibility !== "hidden";
120
+ };
121
+ const extra = [...document.querySelectorAll("input,textarea,select,[contenteditable=true],img,video,iframe,canvas")]
122
+ .filter(shown)
123
+ .map((n) => [n.tagName, n.getAttribute("placeholder"), n.getAttribute("aria-label"), n.getAttribute("src")].join(":"))
124
+ .join("|");
125
+ const t = ((document.body && document.body.innerText) || "") + "|" + extra;
80
126
  let h = 5381;
81
127
  for (let i = 0; i < t.length; i++) h = ((h << 5) + h + t.charCodeAt(i)) | 0;
82
128
  return `${t.length}:${h}`;
@@ -84,11 +130,21 @@ async function clickPrint(page, el) {
84
130
  .catch(() => null);
85
131
  const own = el
86
132
  ? await el
87
- .evaluate((n) =>
88
- n.isConnected
89
- ? [n.className && String(n.className), ...["aria-pressed", "aria-expanded", "aria-checked", "aria-selected", "aria-current", "data-state"].map((a) => n.getAttribute(a)), n.checked, n.value, (n.textContent || "").slice(0, 200)].join("|")
90
- : null,
91
- )
133
+ .evaluate((n) => {
134
+ if (!n.isConnected) return null;
135
+ // 색만 바뀌는 아이콘(저장·좋아요)은 속의 svg 나 감싼 버튼의 속성·클래스가 바뀐다 — 그 HTML 까지 본다.
136
+ // 누른 요소만 봤더니 북마크가 파랗게 됐는데 "그대로" 로 찍혔다(10/22 bluetags 저장).
137
+ // 계산된 색은 안 본다 — 누르기 전에는 커서가 없어서 마우스를 올린 색(hover)만으로 "바뀌었다" 가 된다
138
+ const host = n.closest("a,button,[role],label") || n.parentElement || n;
139
+ return [
140
+ n.className && String(n.className),
141
+ ...["aria-pressed", "aria-expanded", "aria-checked", "aria-selected", "aria-current", "data-state"].map((a) => n.getAttribute(a)),
142
+ n.checked,
143
+ n.value,
144
+ (n.textContent || "").slice(0, 200),
145
+ host.outerHTML.slice(0, 3000),
146
+ ].join("|");
147
+ })
92
148
  .catch(() => null)
93
149
  : null;
94
150
  return { url: page.url(), doc, own };
@@ -349,10 +405,19 @@ class Visit {
349
405
  this.externalTold = new Set();
350
406
  /** 도구가 하지 못한 것들 — 방문이 끝나면 hub 가 서버로 보낸다(diag.js). 사이트 글자는 없다 */
351
407
  this.diag = [];
408
+ /** 진단 순간의 화면 { id(진단 id), image } — 우리 쪽으로만 간다 */
409
+ this.diagShots = [];
352
410
  this.log = log;
353
411
  // 손은 방문 내내 이어진다 — 커서가 있던 자리에서 다음 곳으로 간다
354
412
  this.handState = { rhythm, mouse: null };
355
413
  this.steps = [];
414
+ /** 이번 조작으로 받은 문서의 상태 코드(본 탭의 화면 이동만). 조작마다 비운다 */
415
+ this.docStatus = null;
416
+ page.on("response", (res) => {
417
+ try {
418
+ if (res.request().isNavigationRequest() && res.frame() === page.mainFrame()) this.docStatus = res.status();
419
+ } catch {}
420
+ });
356
421
  /** 문제가 있던 순간의 화면 { step, image(JPEG) } — 방문이 끝나면 hub 가 서버로 올린다 */
357
422
  this.screens = [];
358
423
  this.history = [];
@@ -447,9 +512,6 @@ class Visit {
447
512
  async answer(decision) {
448
513
  const shown = this.pending;
449
514
  if (!shown) throw new Error("No card is showing");
450
- // 첫 걸음 전에 뜬 카드(들어오자마자)는 붙일 걸음이 없다 — 찍어 두었다가 다음 걸음에 붙인다(10/22 실험실 w5)
451
- if (this.steps.length) await this.shoot(this.steps[this.steps.length - 1], "card");
452
- else this.early = { kind: "card", image: await this.snap() };
453
515
  const act = answer.toAction(decision, shown);
454
516
  // 카드를 읽고 정하는 시간. 닫는 건 금방, 쓰는 건 치는 만큼
455
517
  await sleep(act.kind === "close" ? 600 + Math.random() * 1800 : 1500 + Math.random() * 3000);
@@ -500,13 +562,8 @@ class Visit {
500
562
  const view = this.lastView || (await listControls(page));
501
563
  const item = view.items[decision.index];
502
564
  const record = { step: this.steps.length + 1, t: Date.now() - this.t0, path: view.path, action: decision.action, why: decision.why, label: item?.label ?? null };
503
- if (this.early) {
504
- if (this.early.image && this.screens.length < MAX_SCREENS) {
505
- record.screen = { kind: this.early.kind, box: null };
506
- this.screens.push({ step: record.step, image: this.early.image });
507
- }
508
- this.early = null;
509
- }
565
+ await this.checkLastJudgement(decision);
566
+ const diagFrom = this.diag.length;
510
567
  const times = Math.max(1, Math.min(MAX_TIMES[decision.action] || 1, Math.round(Number(decision.times) || 1)));
511
568
  if (times > 1) record.times = times;
512
569
  // 한 번에 할 수 있는 수보다 많이 달라고 했다. 말없이 줄이면 "사이트가 클릭을 삼킨다" 로 읽었다(10/20 실험실 p7: 15·20·30번이 다 4번)
@@ -517,6 +574,7 @@ class Visit {
517
574
  const externalBefore = this.external.length;
518
575
  this.fileWindow = null;
519
576
  this.lastAction = decision.action;
577
+ this.docStatus = null;
520
578
 
521
579
  if (decision.action === "leave") {
522
580
  record.done = !!decision.done;
@@ -556,10 +614,6 @@ class Visit {
556
614
  }
557
615
  await sleep(250);
558
616
  } else if (decision.action === "back") {
559
- // 이 화면에 와서 한 걸음도 채 안 하고 돌아간다 — 들어오자마자 뒤로. 돌아가기 전 화면을 찍는다
560
- let here = 0;
561
- for (let i = this.steps.length - 1; i >= 0 && this.steps[i].path === view.path; i--) here++;
562
- if (here <= 1) await this.shoot(record, "bounced");
563
617
  await page.goBack({ waitUntil: "domcontentloaded" }).catch(() => {});
564
618
  if ((await settle(page, before, net)).navTimeout) this.diag.push({ kind: "nav_timeout", action: "back" });
565
619
  } else if (decision.action === "type") {
@@ -660,9 +714,13 @@ class Visit {
660
714
  })
661
715
  .catch(() => {});
662
716
  // 사람 손이라 빗나갈 수 있다. 빈 곳을 누르면 아무 일도 안 일어난다 — 그게 헛클릭이다
717
+ let ours = false;
663
718
  const clicked = await hand
664
719
  .clickLikePerson(page, this.handState, el)
665
- .catch((e) => ((record.skipped = e.human || humanClickError(e)), { missed: false }));
720
+ .catch((e) => ((record.skipped = e.human || humanClickError(e)), (ours = /eb-insight|eb-plugin/.test(String(e.message))), { missed: false }));
721
+ // 사이트의 무언가가 덮어 못 눌렀다. 우리 카드·위젯이 덮은 것은 사이트 탓이 아니다
722
+ if (record.skipped && /on top of it/.test(record.skipped) && !/survey card/.test(record.skipped) && !ours)
723
+ await this.shoot(record, "covered", await boxOf(page, el));
666
724
  if (clicked.missed) {
667
725
  record.missed = true;
668
726
  this.history.push("Your click landed just outside it and nothing happened.");
@@ -696,11 +754,6 @@ class Visit {
696
754
  // "다른 앱을 열려 했다" 고 알리면 방문자가 사이트 탓으로 적었다(10/22 실험실 q4)
697
755
  if (decision.action === "back") {
698
756
  record.backOut = true;
699
- // 돌아가지 못했다 — 들어오자마자 뒤로(bounced)로 찍은 것은 무른다
700
- if (record.screen && record.screen.kind === "bounced") {
701
- delete record.screen;
702
- this.screens = this.screens.filter((s) => s.step !== record.step);
703
- }
704
757
  } else {
705
758
  record.openedApp = true;
706
759
  this.diag.push({ kind: "left_to_blank", action: decision.action, shape: null });
@@ -734,6 +787,15 @@ class Visit {
734
787
  if (this.fileWindow) record.fileWindow = fileWindowNote(this.fileWindow);
735
788
  await this.noteDiag(record, decision, diagEl);
736
789
 
790
+ // 화면이 깨졌다 — 오류로 온 문서, 오류 문구뿐인 화면. 바깥 사이트·앱·빈 페이지로 간 것은 뺀다
791
+ if (
792
+ !record.offsite &&
793
+ !record.openedApp &&
794
+ !record.backOut &&
795
+ ((this.docStatus && this.docStatus >= 400) || (page.url() !== before && (await errorScreen(page))))
796
+ )
797
+ await this.shoot(record, "error");
798
+
737
799
  // 눌렀는데 그대로. 우리 쪽 사정(빗나감·막은 요청·바깥 사이트·파일 창)으로 그대로인 것은 빼고, 같은 것은 한 번만
738
800
  if (
739
801
  probe &&
@@ -754,6 +816,15 @@ class Visit {
754
816
  await this.shoot(record, "no_change", await boxOf(page, probe.el));
755
817
  }
756
818
 
819
+ // 누른 링크와 다른 곳으로 왔다 — 움직이는 줄에서 다른 카드를 눌렀을 수 있다(10/22 실험실 k5: OKX 를 눌렀는데 Uniswap).
820
+ // 사이트가 돌려보낸 것(로그인 등)일 수도 있다 — 우리가 보고 가린다
821
+ if (decision.action === "click" && !record.skipped && !record.offsite && item?.href && page.url() !== before) {
822
+ const want = sameDocPath(item.href, before);
823
+ const got = sameDocPath(page.url(), before);
824
+ if (want && got && want !== got) this.diag.push({ kind: "landed_elsewhere", action: "click", shape: await diag.shapeOf(probe && probe.el) });
825
+ }
826
+ await this.diagContext(record, diagFrom, probe ? probe.el : diagEl);
827
+
757
828
  this.steps.push(record);
758
829
  this.history.push(
759
830
  `${decision.action}${times > 1 ? ` ×${times}` : ""}${item ? ` "${item.label}"` : ""} — ${decision.why}${record.skipped ? ` (${record.skipped})` : ""}${record.cappedTimes ? " (that is the most in one go)" : ""}${record.offsite ? ` (it leads to another website, ${record.offsite})` : ""}${record.notSent ? " (it would have sent something to the site; it was not sent)" : ""}${record.fileWindow ? " (a window to choose a file opened; you closed it without choosing)" : ""}${record.personalField !== undefined ? " (you chose not to enter personal details there)" : ""}${record.openedApp ? " (it tried to open another app; nothing opened)" : ""}${record.backOut ? " (going back from here would have taken you off the site; you stayed)" : ""}`,
@@ -780,11 +851,72 @@ class Visit {
780
851
  }
781
852
 
782
853
  /**
783
- * 지금 화면을 찍어 이 걸음에 붙인다(record.screen). 보이는 만큼만(뷰포트). 크면 한 번 더 작게, 그래도 크면 안 찍는다
854
+ * 바로 앞 걸음에 대한 도구 판단이 방문자의 다음 말과 엇갈리나. 엇갈리면 도구가 잘못 본 것이다 — 진단으로 남긴다.
855
+ * - "눌렀는데 그대로" 로 찍었는데 방문자는 "저장됐다·파랗게 됐다·열렸다" 고 한다 → 그 사진은 고객에게 안 보낸다
856
+ * (10/22 bluetags 저장: 북마크가 파랗게 됐는데 그대로로 찍혔다)
857
+ * - 화면이 바뀌었다고 봤는데 방문자는 "아무 일 없다·안 열린다" 고 한다
858
+ * 방문자의 말은 사이트 글자가 아니라 우리 AI 가 쓴 말이다
859
+ */
860
+ async checkLastJudgement(decision) {
861
+ const last = this.steps[this.steps.length - 1];
862
+ if (!last || last.action !== "click" || last.skipped || !decision.why) return;
863
+ const from = this.diag.length;
864
+ if (last.screen && last.screen.kind === "no_change" && SAYS_CHANGED.test(decision.why)) {
865
+ this.diag.push({ kind: "no_change_doubt", action: "click", detail: `step ${last.step}` });
866
+ this.screens = this.screens.filter((x) => x.step !== last.step);
867
+ delete last.screen;
868
+ } else if (!last.screen && !last.missed && !last.closedOverlay && SAYS_NOTHING.test(decision.why)) {
869
+ this.diag.push({ kind: "visitor_saw_nothing", action: "click", detail: `step ${last.step}` });
870
+ }
871
+ // 지금 화면이 그 걸음 바로 뒤의 화면이다
872
+ if (this.diag.length > from) await this.diagContext(last, from, null);
873
+ }
874
+
875
+ /**
876
+ * 이번 걸음에 생긴 진단에 그 순간을 붙인다 — 화면(우리만 본다), 요소 주변 HTML, 페이지 경로.
877
+ * 종류와 생김새만으로는 못 고친다: 10/22 무한 배너는 "잘림·회전 배너" 까지만 알았고, 같은 카드 복사본 때문인 건 열어 봐야 알았다
878
+ */
879
+ async diagContext(record, from, el) {
880
+ const events = this.diag.slice(from).filter((e) => !e.id && !DIAG_NO_CONTEXT.has(e.kind));
881
+ if (!events.length) return;
882
+ let pagePath = null;
883
+ try {
884
+ const u = new URL(this.page.url());
885
+ pagePath = (u.pathname + u.search).slice(0, 300);
886
+ } catch {}
887
+ const html = el
888
+ ? await el
889
+ .evaluate((n, max) => {
890
+ if (!n.isConnected) return null;
891
+ let best = n;
892
+ for (let p = n.parentElement, d = 0; p && p !== document.body && d < 4; p = p.parentElement, d++) if (p.outerHTML.length <= max) best = p;
893
+ return best.outerHTML.slice(0, max);
894
+ }, MAX_DIAG_HTML)
895
+ .catch(() => null)
896
+ : null;
897
+ let shotId = null;
898
+ if (this.diagShots.length < MAX_DIAG_SHOTS) {
899
+ const image = await this.snap();
900
+ if (image) shotId = randomUUID();
901
+ if (image) this.diagShots.push({ id: shotId, image });
902
+ }
903
+ events.forEach((e, i) => {
904
+ e.id = i === 0 && shotId ? shotId : randomUUID();
905
+ e.step = record.step;
906
+ if (pagePath) e.path = pagePath;
907
+ if (html) e.html = html;
908
+ });
909
+ }
910
+
911
+ /**
912
+ * 문제가 있던 화면을 찍어 이 걸음에 붙인다(record.screen). 보이는 만큼만(뷰포트). 크면 한 번 더 작게, 그래도 크면 안 찍는다
784
913
  * 실패해도 방문은 그대로 간다
785
914
  */
786
915
  async shoot(record, kind, box = null) {
787
916
  if (!record || record.screen || this.screens.length >= MAX_SCREENS) return;
917
+ // 우리 카드가 떠 있다. 눌렀는데 그대로인 것도 카드가 가로챈 것일 수 있다 — 사이트 탓으로 찍지 않는다
918
+ const card = await readCard(this.page).catch(() => null);
919
+ if (card && card.visible) return;
788
920
  const image = await this.snap();
789
921
  if (!image) return;
790
922
  record.screen = { kind, box };