context_drop 0.1.4 → 0.2.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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +184 -107
  3. data/SPEC.md +74 -26
  4. data/app/assets/javascripts/context_drop/context_drop.js +5121 -651
  5. data/app/controllers/context_drop/agent_controller.rb +170 -0
  6. data/app/controllers/context_drop/configs_controller.rb +2 -1
  7. data/app/controllers/context_drop/feedbacks_controller.rb +13 -3
  8. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  9. data/app/helpers/context_drop/widget_helper.rb +11 -1
  10. data/app/javascript/context_drop/__tests__/widget.test.ts +661 -89
  11. data/app/javascript/context_drop/api-client.ts +130 -11
  12. data/app/javascript/context_drop/element-picker.ts +185 -33
  13. data/app/javascript/context_drop/icons.ts +24 -0
  14. data/app/javascript/context_drop/markdown.ts +146 -0
  15. data/app/javascript/context_drop/sanitizer.ts +413 -2
  16. data/app/javascript/context_drop/screenshot.ts +102 -8
  17. data/app/javascript/context_drop/styles.ts +1528 -252
  18. data/app/javascript/context_drop/types.ts +147 -0
  19. data/app/javascript/context_drop/widget.ts +2591 -290
  20. data/app/models/context_drop/feedback.rb +23 -0
  21. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +5 -0
  22. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +10 -0
  23. data/app/views/layouts/context_drop/application.html.erb +1 -0
  24. data/config/routes.rb +11 -0
  25. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  26. data/lib/context_drop/agent/key_store.rb +290 -0
  27. data/lib/context_drop/agent/llm_client.rb +413 -0
  28. data/lib/context_drop/agent/orchestrator.rb +314 -0
  29. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  30. data/lib/context_drop/configuration.rb +216 -3
  31. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  32. data/lib/context_drop/mcp/environment_router.rb +115 -0
  33. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +87 -8
  34. data/lib/context_drop/mcp/remote_client.rb +120 -0
  35. data/lib/context_drop/mcp/server.rb +9 -2
  36. data/lib/context_drop/mcp/tools/get_feedback.rb +50 -4
  37. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +26 -4
  38. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  39. data/lib/context_drop/mcp/tools/list_feedbacks.rb +174 -22
  40. data/lib/context_drop/mcp/tools/update_feedback_status.rb +45 -4
  41. data/lib/context_drop/version.rb +1 -1
  42. data/lib/context_drop.rb +8 -2
  43. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  44. metadata +11 -1
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Safe, zero-dependency Markdown and unified-diff renderer for ContextDrop Agent responses.
3
+ * Escapes all HTML entities before formatting inline code, bold text, lists, and code blocks.
4
+ */
5
+
6
+ export function escapeHtml(raw: string): string {
7
+ return String(raw)
8
+ .replace(/&/g, "&")
9
+ .replace(/</g, "&lt;")
10
+ .replace(/>/g, "&gt;")
11
+ .replace(/"/g, "&quot;")
12
+ .replace(/'/g, "&#39;");
13
+ }
14
+
15
+ function formatInlineMarkdown(escapedLine: string): string {
16
+ const codeTokens: string[] = [];
17
+ const withCodePlaceholders = escapedLine.replace(/`([^`]+)`/g, (_match, code) => {
18
+ const idx = codeTokens.length;
19
+ codeTokens.push(`<code class="cd-md-code">${code}</code>`);
20
+ return `\u0000CDCODE${idx}\u0000`;
21
+ });
22
+
23
+ const withBold = withCodePlaceholders.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
24
+
25
+ return withBold.replace(/\u0000CDCODE(\d+)\u0000/g, (_m, idxStr) => {
26
+ const idx = Number(idxStr);
27
+ return codeTokens[idx] ?? "";
28
+ });
29
+ }
30
+
31
+ export function renderSafeMarkdown(markdown: string): string {
32
+ const source = String(markdown || "").replace(/\r\n/g, "\n").trim();
33
+ if (!source) return "";
34
+
35
+ const fenceParts = source.split(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g);
36
+ const htmlBlocks: string[] = [];
37
+
38
+ for (let i = 0; i < fenceParts.length; i += 3) {
39
+ const proseChunk = fenceParts[i] || "";
40
+ if (proseChunk.trim().length > 0) {
41
+ htmlBlocks.push(renderProseBlocks(proseChunk));
42
+ }
43
+
44
+ if (i + 2 < fenceParts.length) {
45
+ const lang = escapeHtml((fenceParts[i + 1] || "").trim());
46
+ const codeBody = escapeHtml((fenceParts[i + 2] || "").replace(/\n$/, ""));
47
+ const langAttr = lang ? ` data-lang="${lang}"` : "";
48
+ htmlBlocks.push(
49
+ `<pre class="cd-md-pre"${langAttr}><code class="cd-md-code-block">${codeBody}</code></pre>`
50
+ );
51
+ }
52
+ }
53
+
54
+ return htmlBlocks.join("");
55
+ }
56
+
57
+ function renderProseBlocks(prose: string): string {
58
+ const lines = prose.split("\n");
59
+ const out: string[] = [];
60
+ let paragraphLines: string[] = [];
61
+ let listItems: string[] = [];
62
+ let listTag: "ul" | "ol" | null = null;
63
+
64
+ const flushParagraph = (): void => {
65
+ if (paragraphLines.length === 0) return;
66
+ out.push(`<p class="cd-md-p">${paragraphLines.join("<br>")}</p>`);
67
+ paragraphLines = [];
68
+ };
69
+
70
+ const flushList = (): void => {
71
+ if (!listTag || listItems.length === 0) return;
72
+ out.push(`<${listTag} class="cd-md-list">${listItems.join("")}</${listTag}>`);
73
+ listItems = [];
74
+ listTag = null;
75
+ };
76
+
77
+ for (const rawLine of lines) {
78
+ const trimmed = rawLine.trim();
79
+ if (!trimmed) {
80
+ flushParagraph();
81
+ flushList();
82
+ continue;
83
+ }
84
+
85
+ const headingMatch = trimmed.match(/^(#{1,3})\s+(.+)$/);
86
+ if (headingMatch) {
87
+ flushParagraph();
88
+ flushList();
89
+ out.push(
90
+ `<p class="cd-md-heading">${formatInlineMarkdown(escapeHtml(headingMatch[2]))}</p>`
91
+ );
92
+ continue;
93
+ }
94
+
95
+ const bulletMatch = trimmed.match(/^[-*]\s+(.+)$/);
96
+ if (bulletMatch) {
97
+ flushParagraph();
98
+ if (listTag && listTag !== "ul") flushList();
99
+ listTag = "ul";
100
+ listItems.push(`<li>${formatInlineMarkdown(escapeHtml(bulletMatch[1]))}</li>`);
101
+ continue;
102
+ }
103
+
104
+ const orderedMatch = trimmed.match(/^\d+\.\s+(.+)$/);
105
+ if (orderedMatch) {
106
+ flushParagraph();
107
+ if (listTag && listTag !== "ol") flushList();
108
+ listTag = "ol";
109
+ listItems.push(`<li>${formatInlineMarkdown(escapeHtml(orderedMatch[1]))}</li>`);
110
+ continue;
111
+ }
112
+
113
+ flushList();
114
+ paragraphLines.push(formatInlineMarkdown(escapeHtml(trimmed)));
115
+ }
116
+
117
+ flushParagraph();
118
+ flushList();
119
+ return out.join("");
120
+ }
121
+
122
+ export function buildUnifiedDiffElement(doc: Document, diffText: string): HTMLDivElement {
123
+ const container = doc.createElement("div");
124
+ container.className = "cd-diff-lines";
125
+
126
+ const lines = String(diffText || "").replace(/\r\n/g, "\n").split("\n");
127
+ for (const line of lines) {
128
+ if (line.startsWith("--- ") || line.startsWith("+++ ")) {
129
+ continue;
130
+ }
131
+ const row = doc.createElement("div");
132
+ if (line.startsWith("@@")) {
133
+ row.className = "cd-diff-line cd-diff-hunk";
134
+ } else if (line.startsWith("+")) {
135
+ row.className = "cd-diff-line cd-diff-add";
136
+ } else if (line.startsWith("-")) {
137
+ row.className = "cd-diff-line cd-diff-del";
138
+ } else {
139
+ row.className = "cd-diff-line cd-diff-ctx";
140
+ }
141
+ row.textContent = line.length > 0 ? line : " ";
142
+ container.appendChild(row);
143
+ }
144
+
145
+ return container;
146
+ }
@@ -3,6 +3,7 @@ import type {
3
3
  ElementCandidateInfo,
4
4
  ElementCandidateRelation,
5
5
  ElementReferenceSnapshot,
6
+ SmartComponentDescription,
6
7
  ViewportSnapshot
7
8
  } from "./types.ts";
8
9
 
@@ -30,6 +31,9 @@ export const ALLOWED_HTML_ATTRIBUTES: readonly string[] = [
30
31
  "data-test",
31
32
  "data-cy",
32
33
  "data-qa",
34
+ "data-component",
35
+ "data-controller",
36
+ "data-ui",
33
37
  "data-turbo-frame"
34
38
  ];
35
39
 
@@ -191,6 +195,13 @@ export function extractSanitizedText(el: Element, customSelectors: string[] = []
191
195
  if (elementMatchesAny(childEl, selectors)) return;
192
196
 
193
197
  const children = childEl.childNodes || [];
198
+ if (children.length === 0) {
199
+ const directText = (childEl as unknown as { textContent?: string }).textContent || "";
200
+ if (directText.trim().length > 0) {
201
+ parts.push(directText.trim());
202
+ }
203
+ return;
204
+ }
194
205
  for (let i = 0; i < children.length; i += 1) {
195
206
  walk(children[i]);
196
207
  }
@@ -310,18 +321,412 @@ export function describeElementCandidate(
310
321
  : rawText
311
322
  : null;
312
323
 
324
+ const smart = describeSmartComponent(el, customSelectors);
325
+
313
326
  return {
314
327
  element: el,
315
328
  tagName: (el.tagName || "div").toLowerCase(),
316
329
  selector: computeSelector(el),
317
330
  domPath: computeDomPath(el),
318
331
  textPreview,
332
+ friendlyLabel: smart.label,
333
+ componentKind: smart.kind,
319
334
  rect: computeBoundingRect(el),
320
335
  relation,
321
336
  depth
322
337
  };
323
338
  }
324
339
 
340
+ const INTERACTIVE_SMART_TAGS = new Set([
341
+ "button",
342
+ "a",
343
+ "input",
344
+ "select",
345
+ "textarea",
346
+ "summary",
347
+ "label"
348
+ ]);
349
+
350
+ const INTERACTIVE_SMART_ROLES = new Set([
351
+ "button",
352
+ "link",
353
+ "menuitem",
354
+ "tab",
355
+ "switch",
356
+ "checkbox",
357
+ "radio",
358
+ "combobox",
359
+ "option",
360
+ "searchbox",
361
+ "slider"
362
+ ]);
363
+
364
+ const SEMANTIC_COMPONENT_TAGS = new Set([
365
+ "dialog",
366
+ "article",
367
+ "aside",
368
+ "nav",
369
+ "header",
370
+ "footer",
371
+ "form",
372
+ "tr",
373
+ "li",
374
+ "figure",
375
+ "blockquote",
376
+ "fieldset",
377
+ "details",
378
+ "table",
379
+ "turbo-frame"
380
+ ]);
381
+
382
+ const SEMANTIC_COMPONENT_ROLES = new Set([
383
+ "dialog",
384
+ "alertdialog",
385
+ "alert",
386
+ "status",
387
+ "banner",
388
+ "navigation",
389
+ "search",
390
+ "region",
391
+ "tabpanel",
392
+ "listitem",
393
+ "row",
394
+ "toolbar",
395
+ "menu",
396
+ "card"
397
+ ]);
398
+
399
+ const INLINE_LEAF_TAGS = new Set([
400
+ "span",
401
+ "strong",
402
+ "em",
403
+ "b",
404
+ "i",
405
+ "u",
406
+ "small",
407
+ "mark",
408
+ "abbr",
409
+ "time",
410
+ "code",
411
+ "kbd",
412
+ "svg",
413
+ "path",
414
+ "circle",
415
+ "rect",
416
+ "line",
417
+ "polyline",
418
+ "polygon",
419
+ "g",
420
+ "use"
421
+ ]);
422
+
423
+ const COMPONENT_HINT_PATTERN =
424
+ /\b(card|panel|modal|drawer|dialog|toast|banner|alert|notice|callout|widget|navbar|topbar|header|sidebar|toolbar|dropdown|popover|menu|tile|pricing|checkout|summary|hero|stat|metric|item|row|badge|pill)\b/i;
425
+
426
+ function isInteractiveSmartNode(el: Element): boolean {
427
+ const tag = (el.tagName || "").toLowerCase();
428
+ if (INTERACTIVE_SMART_TAGS.has(tag)) return true;
429
+ const role = (el.getAttribute("role") || "").trim().toLowerCase();
430
+ return role.length > 0 && INTERACTIVE_SMART_ROLES.has(role);
431
+ }
432
+
433
+ function hasComponentBoundarySignal(el: Element): boolean {
434
+ const tag = (el.tagName || "").toLowerCase();
435
+ if (SEMANTIC_COMPONENT_TAGS.has(tag)) return true;
436
+
437
+ const role = (el.getAttribute("role") || "").trim().toLowerCase();
438
+ if (role && SEMANTIC_COMPONENT_ROLES.has(role)) return true;
439
+
440
+ for (const attr of [
441
+ "data-component",
442
+ "data-controller",
443
+ "data-turbo-frame",
444
+ "data-ui",
445
+ "data-testid",
446
+ "data-qa"
447
+ ]) {
448
+ const val = (el.getAttribute(attr) || "").trim();
449
+ if (val.length > 0) return true;
450
+ }
451
+
452
+ const classAndId = `${el.getAttribute("id") || ""} ${el.getAttribute("class") || ""}`;
453
+ return COMPONENT_HINT_PATTERN.test(classAndId);
454
+ }
455
+
456
+ function isOversizedPageShell(el: Element): boolean {
457
+ const tag = (el.tagName || "").toLowerCase();
458
+ if (tag === "main" || tag === "body" || tag === "html") return true;
459
+
460
+ const vw = typeof window !== "undefined" ? window.innerWidth || 1280 : 1280;
461
+ const vh = typeof window !== "undefined" ? window.innerHeight || 800 : 800;
462
+ const rect = computeBoundingRect(el);
463
+ return rect.width >= vw * 0.92 && rect.height >= vh * 0.82;
464
+ }
465
+
466
+ function findFirstHeadingText(
467
+ root: Element,
468
+ customSelectors: string[] = [],
469
+ maxDepth: number = 4
470
+ ): string | null {
471
+ const selectors = buildExcludedSelectorList(customSelectors);
472
+ const headingTags = new Set(["H1", "H2", "H3", "H4", "H5", "H6", "LEGEND", "CAPTION", "SUMMARY"]);
473
+
474
+ function search(node: Element, depth: number): string | null {
475
+ if (depth > maxDepth) return null;
476
+ const children = (node as unknown as { childNodes?: ArrayLike<Node> }).childNodes || [];
477
+ for (let i = 0; i < children.length; i += 1) {
478
+ const child = children[i];
479
+ if (!child || child.nodeType !== 1) continue;
480
+ const childEl = child as Element;
481
+ if (elementMatchesAny(childEl, selectors)) continue;
482
+
483
+ const cTag = (childEl.tagName || "").toUpperCase();
484
+ const cRole = (childEl.getAttribute("role") || "").trim().toLowerCase();
485
+ if (headingTags.has(cTag) || cRole === "heading") {
486
+ const headingText = extractSanitizedText(childEl, customSelectors);
487
+ if (headingText && headingText.length > 0) {
488
+ return headingText;
489
+ }
490
+ }
491
+
492
+ const nested = search(childEl, depth + 1);
493
+ if (nested) return nested;
494
+ }
495
+ return null;
496
+ }
497
+
498
+ return search(root, 1);
499
+ }
500
+
501
+ function humanizeIdentifierToken(raw: string): string | null {
502
+ const cleaned = raw
503
+ .trim()
504
+ .replace(/^(cd|js|app|ui|scenario|section|page)[-_]/i, "")
505
+ .replace(/[-_](btn|button|link|card|panel|section|wrapper|container|box|el|root|view|\d+)$/i, "")
506
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
507
+ .replace(/[-_./]+/g, " ")
508
+ .replace(/\s+/g, " ")
509
+ .trim();
510
+
511
+ if (!cleaned || cleaned.length < 2 || /^[0-9a-f]{7,}$/i.test(cleaned)) {
512
+ return null;
513
+ }
514
+
515
+ return cleaned
516
+ .split(" ")
517
+ .slice(0, 4)
518
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
519
+ .join(" ");
520
+ }
521
+
522
+ function inferFriendlyComponentKind(el: Element): string {
523
+ const tag = (el.tagName || "div").toLowerCase();
524
+ const role = (el.getAttribute("role") || "").trim().toLowerCase();
525
+ const classAndId = `${el.getAttribute("id") || ""} ${el.getAttribute("class") || ""}`.toLowerCase();
526
+
527
+ if (tag === "button" || role === "button") return "Button";
528
+ if (tag === "a" || role === "link") return "Link";
529
+ if (role === "tab") return "Tab";
530
+ if (role === "menuitem") return "Menu item";
531
+ if (role === "switch") return "Toggle";
532
+ if (tag === "select" || role === "combobox") return "Dropdown";
533
+ if (tag === "textarea") return "Text field";
534
+ if (tag === "input") {
535
+ const type = (el.getAttribute("type") || "text").toLowerCase();
536
+ if (type === "search" || role === "searchbox") return "Search box";
537
+ if (type === "checkbox" || role === "checkbox") return "Checkbox";
538
+ if (type === "radio" || role === "radio") return "Option";
539
+ if (type === "submit" || type === "button") return "Button";
540
+ return "Input field";
541
+ }
542
+ if (tag === "label") return "Field";
543
+ if (tag === "dialog" || role === "dialog" || role === "alertdialog" || /\b(modal|drawer|dialog)\b/.test(classAndId)) {
544
+ return "Dialog";
545
+ }
546
+ if (role === "alert" || role === "status" || /\b(toast|banner|alert|notice|callout)\b/.test(classAndId)) {
547
+ return "Banner";
548
+ }
549
+ if (tag === "nav" || role === "navigation" || /\b(navbar|topbar|Subnav|breadcrumb)\b/i.test(classAndId)) {
550
+ return "Navigation";
551
+ }
552
+ if (tag === "header" || /\bheader\b/.test(classAndId)) return "Header";
553
+ if (tag === "footer") return "Footer";
554
+ if (tag === "aside" || /\bsidebar\b/.test(classAndId)) return "Sidebar";
555
+ if (tag === "form") return "Form";
556
+ if (tag === "table") return "Table";
557
+ if (tag === "tr" || role === "row") return "Table row";
558
+ if (tag === "li" || role === "listitem") return "Item";
559
+ if (tag === "img" || tag === "figure" || tag === "svg" || tag === "picture") return "Image";
560
+ if (/^h[1-6]$/.test(tag) || role === "heading") return "Heading";
561
+ if (
562
+ tag === "article" ||
563
+ tag === "turbo-frame" ||
564
+ /\b(card|panel|tile|pricing|summary|widget|stat|metric|popover|dropdown)\b/.test(classAndId)
565
+ ) {
566
+ return "Card";
567
+ }
568
+ if (tag === "section" || role === "region") return "Section";
569
+ return "Page area";
570
+ }
571
+
572
+ function truncateCleanPhrase(raw: string, maxLen: number = 32): string {
573
+ const normalized = raw.replace(/\s+/g, " ").trim();
574
+ if (normalized.length <= maxLen) return normalized;
575
+ return `${normalized.slice(0, maxLen - 1).trimEnd()}…`;
576
+ }
577
+
578
+ /**
579
+ * Resolves a hovered/clicked DOM leaf into a meaningful, human-recognizable UI component
580
+ * for Production ("smart") mode so non-technical users never wrestle with tiny `<span>`/`<svg>`
581
+ * fragments or overlapping DevTools layer lists.
582
+ */
583
+ export function resolveSmartComponent(
584
+ primaryTarget: Element | null,
585
+ customSelectors: string[] = []
586
+ ): Element | null {
587
+ if (!primaryTarget || !isSelectableElement(primaryTarget, customSelectors)) {
588
+ return null;
589
+ }
590
+
591
+ // 1. If the user is pointing inside an interactive control (button, link, input, tab, menuitem),
592
+ // snap cleanly to that control rather than an inner <span> or <svg>.
593
+ let cursor: Element | null = primaryTarget;
594
+ let hops = 0;
595
+ while (cursor && hops < 6) {
596
+ if (isSelectableElement(cursor, customSelectors) && isInteractiveSmartNode(cursor)) {
597
+ return cursor;
598
+ }
599
+ cursor = getParentOrHostElement(cursor);
600
+ hops += 1;
601
+ }
602
+
603
+ // 2. Otherwise walk up to the nearest bounded semantic / visual component (Card, Banner, Form,
604
+ // Dialog, Table row, Navigation, Stimulus/Turbo component) without jumping to full-page <main>/<body>.
605
+ cursor = primaryTarget;
606
+ hops = 0;
607
+ let fallbackSection: Element | null = null;
608
+ while (cursor && hops < 6) {
609
+ if (isSelectableElement(cursor, customSelectors) && !isOversizedPageShell(cursor)) {
610
+ const rect = computeBoundingRect(cursor);
611
+ if (rect.width >= 24 && rect.height >= 18) {
612
+ if (hasComponentBoundarySignal(cursor)) {
613
+ return cursor;
614
+ }
615
+ const tag = (cursor.tagName || "").toLowerCase();
616
+ if (tag === "section" && !fallbackSection) {
617
+ fallbackSection = cursor;
618
+ }
619
+ }
620
+ }
621
+ cursor = getParentOrHostElement(cursor);
622
+ hops += 1;
623
+ }
624
+
625
+ if (fallbackSection) {
626
+ return fallbackSection;
627
+ }
628
+
629
+ // 3. If the leaf is a bare inline/SVG fragment, step up to its nearest clean block parent.
630
+ const leafTag = (primaryTarget.tagName || "").toLowerCase();
631
+ if (INLINE_LEAF_TAGS.has(leafTag)) {
632
+ let parent = getParentOrHostElement(primaryTarget);
633
+ let step = 0;
634
+ while (parent && step < 4) {
635
+ const pTag = (parent.tagName || "").toLowerCase();
636
+ if (
637
+ !INLINE_LEAF_TAGS.has(pTag) &&
638
+ isSelectableElement(parent, customSelectors) &&
639
+ !isOversizedPageShell(parent)
640
+ ) {
641
+ return parent;
642
+ }
643
+ parent = getParentOrHostElement(parent);
644
+ step += 1;
645
+ }
646
+ }
647
+
648
+ return primaryTarget;
649
+ }
650
+
651
+ /**
652
+ * Produces a plain-language, jargon-free label for any DOM element (e.g. `"Upgrade Cluster" button`,
653
+ * `"Order Summary" card`, `"Email Address" input field`) with zero CSS selectors or pixel metrics.
654
+ */
655
+ export function describeSmartComponent(
656
+ el: Element,
657
+ customSelectors: string[] = [],
658
+ originalLeaf?: Element | null
659
+ ): SmartComponentDescription {
660
+ const kind = inferFriendlyComponentKind(el);
661
+ let name: string | null = null;
662
+
663
+ const ariaLabel =
664
+ (el.getAttribute("aria-label") || "").trim() ||
665
+ (el.getAttribute("placeholder") || "").trim() ||
666
+ (el.getAttribute("alt") || "").trim() ||
667
+ (el.getAttribute("title") || "").trim();
668
+
669
+ if (ariaLabel) {
670
+ name = truncateCleanPhrase(ariaLabel, 30);
671
+ }
672
+
673
+ if (!name && isInteractiveSmartNode(el)) {
674
+ const ownText = extractSanitizedText(el, customSelectors);
675
+ if (ownText) {
676
+ name = truncateCleanPhrase(ownText, 28);
677
+ }
678
+ }
679
+
680
+ if (!name) {
681
+ const headingText = findFirstHeadingText(el, customSelectors);
682
+ if (headingText) {
683
+ name = truncateCleanPhrase(headingText, 30);
684
+ }
685
+ }
686
+
687
+ if (!name) {
688
+ for (const attr of ["data-component", "data-turbo-frame", "data-controller", "id", "name"]) {
689
+ const rawAttr = (el.getAttribute(attr) || "").trim();
690
+ if (rawAttr) {
691
+ const humanized = humanizeIdentifierToken(rawAttr);
692
+ if (humanized) {
693
+ name = truncateCleanPhrase(humanized, 28);
694
+ break;
695
+ }
696
+ }
697
+ }
698
+ }
699
+
700
+ if (!name) {
701
+ const snippet = extractSanitizedText(el, customSelectors);
702
+ if (snippet && snippet.length <= 42) {
703
+ name = truncateCleanPhrase(snippet, 28);
704
+ }
705
+ }
706
+
707
+ const lowerKind = kind.toLowerCase();
708
+ let label = kind;
709
+ if (name) {
710
+ const nameAlreadyHasKind = name.toLowerCase().endsWith(lowerKind);
711
+ label = nameAlreadyHasKind ? name : `“${name}” ${lowerKind}`;
712
+ }
713
+
714
+ return {
715
+ element: el,
716
+ label,
717
+ kind,
718
+ name,
719
+ promotedFromLeaf: Boolean(originalLeaf && originalLeaf !== el)
720
+ };
721
+ }
722
+
723
+ export function computeFriendlyComponentLabel(
724
+ el: Element,
725
+ customSelectors: string[] = []
726
+ ): string {
727
+ return describeSmartComponent(el, customSelectors).label;
728
+ }
729
+
325
730
  export function resolveAncestorChain(
326
731
  el: Element | null,
327
732
  customSelectors: string[] = [],
@@ -424,13 +829,15 @@ export function resolveCandidateStack(
424
829
  export function captureElementSnapshot(
425
830
  el: Element,
426
831
  customSelectors: string[] = [],
427
- clientRef?: string
832
+ clientRef?: string,
833
+ extraMetadata?: Record<string, unknown>
428
834
  ): ElementReferenceSnapshot | null {
429
835
  if (isElementExcluded(el, customSelectors)) {
430
836
  return null;
431
837
  }
432
838
 
433
839
  const boundingRect = computeBoundingRect(el);
840
+ const smart = describeSmartComponent(el, customSelectors);
434
841
 
435
842
  const viewport: ViewportSnapshot = {
436
843
  width: typeof window !== "undefined" ? window.innerWidth || 1024 : 1024,
@@ -448,7 +855,11 @@ export function captureElementSnapshot(
448
855
  attributes_snapshot: extractSanitizedAttributes(el),
449
856
  bounding_rect: boundingRect,
450
857
  viewport: viewport,
451
- metadata: {},
858
+ metadata: {
859
+ friendly_label: smart.label,
860
+ component_kind: smart.kind,
861
+ ...(extraMetadata || {})
862
+ },
452
863
  captured_at: new Date().toISOString()
453
864
  };
454
865
  }