context_drop 0.1.4 → 0.3.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 (50) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +330 -116
  3. data/Rakefile +110 -1
  4. data/SPEC.md +74 -26
  5. data/app/assets/javascripts/context_drop/context_drop.js +6329 -682
  6. data/app/controllers/context_drop/agent_controller.rb +170 -0
  7. data/app/controllers/context_drop/application_controller.rb +52 -3
  8. data/app/controllers/context_drop/configs_controller.rb +12 -2
  9. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  10. data/app/controllers/context_drop/feedbacks_controller.rb +396 -20
  11. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  12. data/app/helpers/context_drop/widget_helper.rb +11 -1
  13. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  14. data/app/javascript/context_drop/__tests__/widget.test.ts +1015 -89
  15. data/app/javascript/context_drop/api-client.ts +422 -19
  16. data/app/javascript/context_drop/element-picker.ts +186 -34
  17. data/app/javascript/context_drop/icons.ts +28 -0
  18. data/app/javascript/context_drop/markdown.ts +146 -0
  19. data/app/javascript/context_drop/sanitizer.ts +413 -2
  20. data/app/javascript/context_drop/screenshot.ts +103 -9
  21. data/app/javascript/context_drop/styles.ts +1705 -248
  22. data/app/javascript/context_drop/types.ts +243 -6
  23. data/app/javascript/context_drop/widget.ts +3318 -294
  24. data/app/models/context_drop/feedback.rb +88 -8
  25. data/app/services/context_drop/ownership_token.rb +114 -0
  26. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +13 -0
  27. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +19 -0
  28. data/app/views/layouts/context_drop/application.html.erb +6 -0
  29. data/config/routes.rb +22 -0
  30. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  31. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  32. data/lib/context_drop/agent/key_store.rb +290 -0
  33. data/lib/context_drop/agent/llm_client.rb +413 -0
  34. data/lib/context_drop/agent/orchestrator.rb +314 -0
  35. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  36. data/lib/context_drop/configuration.rb +242 -3
  37. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  38. data/lib/context_drop/mcp/environment_router.rb +115 -0
  39. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +90 -9
  40. data/lib/context_drop/mcp/remote_client.rb +120 -0
  41. data/lib/context_drop/mcp/server.rb +9 -2
  42. data/lib/context_drop/mcp/tools/get_feedback.rb +62 -5
  43. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +29 -4
  44. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  45. data/lib/context_drop/mcp/tools/list_feedbacks.rb +195 -23
  46. data/lib/context_drop/mcp/tools/update_feedback_status.rb +48 -5
  47. data/lib/context_drop/version.rb +1 -1
  48. data/lib/context_drop.rb +8 -2
  49. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  50. metadata +14 -2
@@ -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
  }
@@ -11,7 +11,7 @@ export interface ScreenshotCaptureResult {
11
11
  }
12
12
 
13
13
  export function collectRedactionRects(customExcludedSelectors: string[] = []): BoundingRectSnapshot[] {
14
- if (typeof document === "undefined") return [];
14
+ if (typeof document === "undefined" || typeof document.querySelectorAll !== "function") return [];
15
15
 
16
16
  const selectors = buildExcludedSelectorList(customExcludedSelectors);
17
17
  const selectorQuery = [
@@ -69,15 +69,23 @@ function dataUrlToBlob(dataUrl: string): Blob {
69
69
  return new Blob([bytes], { type: mime });
70
70
  }
71
71
 
72
+ export interface CaptureViewportOptions {
73
+ highlightRect?: BoundingRectSnapshot | null;
74
+ }
75
+
72
76
  export async function captureViewportScreenshot(
73
77
  customExcludedSelectors: string[] = [],
74
- cropRegion?: BoundingRectSnapshot
78
+ cropRegion?: BoundingRectSnapshot,
79
+ options?: CaptureViewportOptions
75
80
  ): Promise<ScreenshotCaptureResult> {
76
81
  if (typeof document === "undefined" || typeof window === "undefined") {
77
82
  throw new Error("Screenshot capture is only available in a browser environment.");
78
83
  }
79
84
 
80
- const widgets = Array.from(document.querySelectorAll("context-drop-widget, [data-context-drop-ui]")) as HTMLElement[];
85
+ const widgets =
86
+ typeof document.querySelectorAll === "function"
87
+ ? (Array.from(document.querySelectorAll("context-drop-widget, [data-context-drop-ui]")) as HTMLElement[])
88
+ : [];
81
89
  const previousVisibility = widgets.map((el) => el.style.visibility);
82
90
 
83
91
  try {
@@ -102,7 +110,7 @@ export async function captureViewportScreenshot(
102
110
  const canvas = document.createElement("canvas");
103
111
  canvas.width = Math.round(region.width);
104
112
  canvas.height = Math.round(region.height);
105
- const ctx = canvas.getContext("2d");
113
+ const ctx = typeof canvas.getContext === "function" ? canvas.getContext("2d") : null;
106
114
 
107
115
  if (!ctx) {
108
116
  throw new Error("Canvas 2D context is unavailable or restricted by browser policy.");
@@ -110,19 +118,22 @@ export async function captureViewportScreenshot(
110
118
 
111
119
  // Paint page background
112
120
  const bodyBg =
113
- window.getComputedStyle && document.body
121
+ typeof window.getComputedStyle === "function" && document.body
114
122
  ? window.getComputedStyle(document.body).backgroundColor
115
123
  : "#ffffff";
116
124
  ctx.fillStyle = bodyBg && bodyBg !== "rgba(0, 0, 0, 0)" ? bodyBg : "#ffffff";
117
125
  ctx.fillRect(0, 0, canvas.width, canvas.height);
118
126
 
119
127
  // Paint visible non-excluded DOM elements approximation onto canvas
120
- const visibleNodes = document.body ? Array.from(document.body.querySelectorAll("*")) : [];
128
+ const visibleNodes =
129
+ document.body && typeof document.body.querySelectorAll === "function"
130
+ ? Array.from(document.body.querySelectorAll("*"))
131
+ : [];
121
132
  for (const node of visibleNodes) {
122
133
  if (
123
- node.closest("context-drop-widget") ||
124
- node.hasAttribute("data-context-drop-ui") ||
125
- node.closest("[data-context-drop-ui]")
134
+ (typeof node.closest === "function" &&
135
+ (node.closest("context-drop-widget") || node.closest("[data-context-drop-ui]"))) ||
136
+ node.hasAttribute("data-context-drop-ui")
126
137
  ) {
127
138
  continue;
128
139
  }
@@ -148,9 +159,35 @@ export async function captureViewportScreenshot(
148
159
  ctx.lineWidth = Math.min(parseFloat(style.borderWidth), 4);
149
160
  ctx.strokeRect(rx, ry, r.width, r.height);
150
161
  }
162
+
163
+ // Render leaf text labels so surrounding-context previews are legible
164
+ if (node.children && node.children.length === 0 && typeof ctx.fillText === "function") {
165
+ const text = (node.textContent || "").replace(/\s+/g, " ").trim();
166
+ if (text.length > 0 && r.height >= 10) {
167
+ ctx.fillStyle = style.color || "#111318";
168
+ const fontSize = Math.min(18, Math.max(10, parseFloat(style.fontSize || "12") || 12));
169
+ ctx.font = `${style.fontWeight || "400"} ${Math.round(fontSize)}px sans-serif`;
170
+ ctx.fillText(text.slice(0, 48), rx + 4, ry + Math.min(r.height - 3, fontSize + 3));
171
+ }
172
+ }
151
173
  }
152
174
  }
153
175
 
176
+ // Optional visual callout box highlighting the selected component inside surrounding context
177
+ if (options?.highlightRect) {
178
+ const hr = options.highlightRect;
179
+ const hx = hr.x - region.x;
180
+ const hy = hr.y - region.y;
181
+ ctx.strokeStyle = "#c2410c";
182
+ ctx.lineWidth = 2;
183
+ ctx.strokeRect(
184
+ Math.max(1, hx),
185
+ Math.max(1, hy),
186
+ Math.min(region.width - 2, hr.width),
187
+ Math.min(region.height - 2, hr.height)
188
+ );
189
+ }
190
+
154
191
  // 2. Enforce pre-capture visual redaction of all sensitive/excluded elements
155
192
  for (const red of redactionRects) {
156
193
  const rx = red.x - region.x;
@@ -218,3 +255,60 @@ export async function captureElementScreenshot(
218
255
  }
219
256
  return result;
220
257
  }
258
+
259
+ /**
260
+ * Captures a privacy-redacted screenshot of a selected component together with generous
261
+ * surrounding page context (used automatically in Production "smart" mode) and frames the
262
+ * selected component inside the captured region.
263
+ */
264
+ export async function captureSurroundingContextScreenshot(
265
+ element: Element,
266
+ padding: number = 84,
267
+ customExcludedSelectors: string[] = [],
268
+ elementClientRef?: string
269
+ ): Promise<ScreenshotCaptureResult> {
270
+ if (isElementExcluded(element, customExcludedSelectors)) {
271
+ throw new Error("Cannot capture screenshot of an excluded or sensitive DOM element.");
272
+ }
273
+
274
+ const vw = typeof window !== "undefined" ? Math.max(window.innerWidth || 1024, 1) : 1024;
275
+ const vh = typeof window !== "undefined" ? Math.max(window.innerHeight || 768, 1) : 768;
276
+ const r = element.getBoundingClientRect();
277
+ const baseX = r.x ?? r.left ?? 0;
278
+ const baseY = r.y ?? r.top ?? 0;
279
+ const pad = Math.max(32, padding);
280
+
281
+ // Ensure a comfortable minimum surrounding neighborhood (340x220px) around small controls
282
+ const desiredWidth = Math.min(vw, Math.max(r.width + pad * 2, 340));
283
+ const desiredHeight = Math.min(vh, Math.max(r.height + pad * 2, 220));
284
+ const centerX = baseX + r.width / 2;
285
+ const centerY = baseY + r.height / 2;
286
+
287
+ const cropX = Math.max(0, Math.min(centerX - desiredWidth / 2, vw - desiredWidth));
288
+ const cropY = Math.max(0, Math.min(centerY - desiredHeight / 2, vh - desiredHeight));
289
+
290
+ const cropRegion: BoundingRectSnapshot = {
291
+ x: cropX,
292
+ y: cropY,
293
+ width: desiredWidth,
294
+ height: desiredHeight
295
+ };
296
+
297
+ const targetRect: BoundingRectSnapshot = {
298
+ x: baseX,
299
+ y: baseY,
300
+ width: r.width,
301
+ height: r.height
302
+ };
303
+
304
+ const result = await captureViewportScreenshot(customExcludedSelectors, cropRegion, {
305
+ highlightRect: targetRect
306
+ });
307
+ result.metadata.capture_type = "surrounding_context";
308
+ result.metadata.context_padding = pad;
309
+ result.metadata.highlighted_rect = targetRect;
310
+ if (elementClientRef) {
311
+ result.metadata.element_attachment_ref = elementClientRef;
312
+ }
313
+ return result;
314
+ }