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
@@ -1,40 +1,129 @@
1
1
  import type {
2
+ AgentChatMessage,
3
+ AgentProviderInfo,
4
+ AgentStatusResponse,
5
+ CrossEnvFeedbackItem,
2
6
  ElementReferenceSnapshot,
3
7
  FeedbackSubmissionPayload,
4
8
  PendingAttachmentItem,
9
+ ProposedFileEdit,
5
10
  SessionFeedbackEntry,
6
11
  WidgetConfig,
7
- WidgetPosition
12
+ WidgetPosition,
13
+ WidgetSurfaceMode
8
14
  } from "./types.ts";
9
- import { MANDATORY_EXCLUDED_SELECTORS } from "./sanitizer.ts";
15
+ import { MANDATORY_EXCLUDED_SELECTORS, describeSmartComponent } from "./sanitizer.ts";
10
16
  import {
11
17
  ICON_CAMERA,
12
- ICON_CHAT,
13
18
  ICON_CHECK,
14
19
  ICON_CHEVRON_DOWN,
20
+ ICON_CHEVRON_RIGHT,
15
21
  ICON_CHEVRON_UP,
16
22
  ICON_CLOSE,
23
+ ICON_CODE_PROMPT,
17
24
  ICON_EXPAND,
25
+ ICON_FILE_CODE,
18
26
  ICON_GRIP,
19
27
  ICON_IMAGE,
28
+ ICON_INBOX,
29
+ ICON_KEY,
20
30
  ICON_MINIMIZE,
21
31
  ICON_PIN,
32
+ ICON_PLUS,
33
+ ICON_PUSH_LAYOUT,
22
34
  ICON_SCROLL_VERTICAL,
23
- ICON_SEND
35
+ ICON_SEND,
36
+ ICON_SHIELD,
37
+ ICON_SIDEBAR,
38
+ ICON_SUN,
39
+ ICON_MOON,
40
+ ICON_UNDO
24
41
  } from "./icons.ts";
25
42
  import { WIDGET_SHADOW_STYLES } from "./styles.ts";
26
43
  import { ContextDropApiClient } from "./api-client.ts";
27
44
  import { ElementPicker } from "./element-picker.ts";
28
- import { captureElementScreenshot, captureViewportScreenshot } from "./screenshot.ts";
45
+ import {
46
+ captureElementScreenshot,
47
+ captureSurroundingContextScreenshot,
48
+ captureViewportScreenshot
49
+ } from "./screenshot.ts";
50
+ import { buildUnifiedDiffElement, renderSafeMarkdown } from "./markdown.ts";
51
+
52
+ const CORNER_SNAP_ZONE_PX = 68;
53
+ const PEEL_DRAG_THRESHOLD_PX = 6;
54
+
55
+ const DEFAULT_PROVIDERS_FALLBACK: AgentProviderInfo[] = [
56
+ {
57
+ id: "anthropic",
58
+ label: "Anthropic Claude",
59
+ configured: false,
60
+ source: null,
61
+ env_var_hint: "ANTHROPIC_API_KEY",
62
+ masked_key: null,
63
+ model: "claude-sonnet-4-20250514",
64
+ default_model: "claude-sonnet-4-20250514",
65
+ models: ["claude-sonnet-4-20250514", "claude-3-7-sonnet-latest", "claude-3-5-haiku-latest"],
66
+ supports_base_url: false
67
+ },
68
+ {
69
+ id: "gemini",
70
+ label: "Google Gemini",
71
+ configured: false,
72
+ source: null,
73
+ env_var_hint: "GEMINI_API_KEY",
74
+ masked_key: null,
75
+ model: "gemini-2.5-pro",
76
+ default_model: "gemini-2.5-pro",
77
+ models: ["gemini-2.5-pro", "gemini-2.5-flash"],
78
+ supports_base_url: false
79
+ },
80
+ {
81
+ id: "openai",
82
+ label: "OpenAI",
83
+ configured: false,
84
+ source: null,
85
+ env_var_hint: "OPENAI_API_KEY",
86
+ masked_key: null,
87
+ model: "gpt-4.1",
88
+ default_model: "gpt-4.1",
89
+ models: ["gpt-4.1", "gpt-4.1-mini", "o4-mini"],
90
+ supports_base_url: false
91
+ },
92
+ {
93
+ id: "custom",
94
+ label: "OpenAI-Compatible (OpenRouter / Ollama)",
95
+ configured: false,
96
+ source: null,
97
+ env_var_hint: "CONTEXT_DROP_LLM_API_KEY",
98
+ masked_key: null,
99
+ model: "anthropic/claude-sonnet-4",
100
+ default_model: "anthropic/claude-sonnet-4",
101
+ models: ["anthropic/claude-sonnet-4", "google/gemini-2.5-pro", "llama3.3"],
102
+ supports_base_url: true,
103
+ base_url: "https://openrouter.ai/api/v1"
104
+ }
105
+ ];
106
+
107
+ const BOOK_CORNER_SVG = `<svg class="cd-book-corner-svg" viewBox="0 0 40 40" fill="none" aria-hidden="true"><polygon points="0,0 36,0 0,36" fill="#c2410c"/><polygon points="0,0 36,0 0,36" fill="rgba(17, 19, 24, 0.08)"/><path d="M12.2 6.2l4.1 4.1-1.7 1.7-1.4-.5-2.5 2.5.5 2-1.3 1.3-2.4-2.4-2.3 2.3 2.3-2.3-2.4-2.4 1.3-1.3 2 .5 2.5-2.5-.5-1.4 1.8-1.6z" stroke="#faf9f6" stroke-width="1.35" stroke-linecap="round" stroke-linejoin="round"/><path d="M36 0Q35.5 21 33.5 33.5Q21 35.5 0 36Z" fill="rgba(17, 19, 24, 0.16)"/><path class="cd-corner-flap" d="M36 0Q34.5 18.5 31 31Q18.5 34.5 0 36L36 0Z" fill="#faf9f6" stroke="#d6d3cd" stroke-width="1.2" stroke-linejoin="round"/></svg>`;
108
+
109
+ const DEFAULT_VERBOSE_PLACEHOLDER = "Describe the issue or drop context from the page...";
110
+ const DEFAULT_SMART_PLACEHOLDER = "Tell us what's happening...";
111
+
112
+ export const DEFAULT_SIDEBAR_WIDTH = 560;
29
113
 
30
114
  const DEFAULT_CONFIG: WidgetConfig = {
31
115
  enabled: true,
32
- position: "top_left",
33
- placeholder: "Describe the issue or drop context from the page...",
116
+ environment: "production",
117
+ position: "bottom_right",
118
+ placeholder: DEFAULT_VERBOSE_PLACEHOLDER,
119
+ agent: {
120
+ enabled: false
121
+ },
34
122
  features: {
35
123
  element_selection: true,
36
124
  screenshot_capture: true,
37
- element_capture_padding: 16
125
+ element_capture_padding: 16,
126
+ smart_capture_padding: 84
38
127
  },
39
128
  limits: {
40
129
  max_attachments: 10,
@@ -54,6 +143,10 @@ const BaseHTMLElement: typeof HTMLElement =
54
143
  : (class {} as unknown as typeof HTMLElement);
55
144
 
56
145
  export class ContextDropWidgetElement extends BaseHTMLElement {
146
+ public static get observedAttributes(): string[] {
147
+ return ["data-position", "data-config", "data-theme", "data-cd-theme"];
148
+ }
149
+
57
150
  public shadow: ShadowRoot | null = null;
58
151
  private config: WidgetConfig = structuredClone(DEFAULT_CONFIG);
59
152
  private customMetadata: Record<string, unknown> = {};
@@ -63,15 +156,47 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
63
156
  private isOpen: boolean = false;
64
157
  private isMinimized: boolean = false;
65
158
  private isSubmitting: boolean = false;
159
+ private isAgentBusy: boolean = false;
160
+ private surfaceMode: WidgetSurfaceMode = "feedback";
161
+ private sidebarSide: "right" | "left" = "right";
162
+ private sidebarWidth: number = DEFAULT_SIDEBAR_WIDTH;
163
+ private currentTheme: "light" | "dark" = "light";
164
+ private composerThemeToggleBtn: HTMLButtonElement | null = null;
165
+ private sidebarThemeToggleBtn: HTMLButtonElement | null = null;
166
+ private pushPageLayout: boolean = false;
66
167
  private freePos: { left: number; top: number } | null = null;
168
+ private isPeelDragging: boolean = false;
169
+ private customPlaceholderSet: boolean = false;
170
+ private pendingSmartCaptures: Set<Promise<void>> = new Set();
67
171
 
68
172
  private elementReferences: ElementReferenceSnapshot[] = [];
69
173
  private elementDomNodes: Map<string, Element> = new Map();
70
174
  private attachments: PendingAttachmentItem[] = [];
71
175
  private sessionHistory: SessionFeedbackEntry[] = [];
72
176
 
177
+ // Local Agent state
178
+ private agentStatusLoaded: boolean = false;
179
+ private agentWorkspaceName: string = "rails-app";
180
+ private agentMcpEnvironments: string[] = ["local"];
181
+ private agentProviders: AgentProviderInfo[] = structuredClone(DEFAULT_PROVIDERS_FALLBACK);
182
+ private activeProviderId: string = "anthropic";
183
+ private selectedVaultProviderId: string = "anthropic";
184
+ private isByokDrawerOpen: boolean = false;
185
+ private isFeedbacksDrawerOpen: boolean = false;
186
+ private feedbacksEnvFilter: string = "all";
187
+ private crossEnvFeedbacks: CrossEnvFeedbackItem[] = [];
188
+ private isLoadingFeedbacks: boolean = false;
189
+ private agentMessages: AgentChatMessage[] = [];
190
+
191
+ // Shadow DOM references
73
192
  private rootContainer: HTMLDivElement | null = null;
74
- private composerEl: HTMLDivElement | null = null;
193
+ private bookCornerBtn: HTMLButtonElement | null = null;
194
+ private bookCornerCountEl: HTMLSpanElement | null = null;
195
+ private bookCornerAgentDotEl: HTMLSpanElement | null = null;
196
+ private bookCornerHintEl: HTMLSpanElement | null = null;
197
+ private dragPinEl: HTMLDivElement | null = null;
198
+ private cornerSnapGhostEl: HTMLDivElement | null = null;
199
+
75
200
  private compactBarEl: HTMLDivElement | null = null;
76
201
  private compactStatusEl: HTMLDivElement | null = null;
77
202
  private compactStepGroupEl: HTMLDivElement | null = null;
@@ -79,26 +204,87 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
79
204
  private compactLayerDownBtn: HTMLButtonElement | null = null;
80
205
  private compactDoneBtn: HTMLButtonElement | null = null;
81
206
  private compactPinBtn: HTMLButtonElement | null = null;
82
- private pinDockEl: HTMLDivElement | null = null;
83
- private floatingPinBtn: HTMLButtonElement | null = null;
84
- private triggerBtn: HTMLButtonElement | null = null;
207
+
208
+ // Floating Feedback Composer elements
209
+ private composerEl: HTMLDivElement | null = null;
210
+ private composerTitleEl: HTMLHeadingElement | null = null;
211
+ private composerMinBtn: HTMLButtonElement | null = null;
85
212
  private cornerPinBtn: HTMLButtonElement | null = null;
213
+ private composerModeSwitchWrap: HTMLDivElement | null = null;
214
+ private composerToolbarPickBtn: HTMLButtonElement | null = null;
215
+ private composerToolbarScreenshotBtn: HTMLButtonElement | null = null;
216
+ private composerToolbarUploadBtn: HTMLButtonElement | null = null;
86
217
  private chatThreadEl: HTMLDivElement | null = null;
87
218
  private textareaEl: HTMLTextAreaElement | null = null;
88
219
  private trayEl: HTMLDivElement | null = null;
89
220
  private statusEl: HTMLDivElement | null = null;
90
221
  private fileInputEl: HTMLInputElement | null = null;
91
222
  private submitBtn: HTMLButtonElement | null = null;
223
+
224
+ // Docked Local Agent Sidebar elements
225
+ private agentSidebarEl: HTMLElement | null = null;
226
+ private sidebarPinBtn: HTMLButtonElement | null = null;
227
+ private sidebarEnvPillEl: HTMLSpanElement | null = null;
228
+ private sidebarPushBtn: HTMLButtonElement | null = null;
229
+ private providerPillBtn: HTMLButtonElement | null = null;
230
+ private keyDotEl: HTMLSpanElement | null = null;
231
+ private providerPillLabelEl: HTMLSpanElement | null = null;
232
+ private keysToggleBtn: HTMLButtonElement | null = null;
233
+ private feedbacksToggleBtn: HTMLButtonElement | null = null;
234
+ private byokDrawerEl: HTMLDivElement | null = null;
235
+ private byokProviderSelect: HTMLSelectElement | null = null;
236
+ private byokModelInput: HTMLInputElement | null = null;
237
+ private byokModelPresetsSelect: HTMLSelectElement | null = null;
238
+ private byokBaseUrlField: HTMLDivElement | null = null;
239
+ private byokBaseUrlInput: HTMLInputElement | null = null;
240
+ private byokKeySourceBadge: HTMLSpanElement | null = null;
241
+ private byokKeyInput: HTMLInputElement | null = null;
242
+ private feedbacksDrawerEl: HTMLDivElement | null = null;
243
+ private feedbacksTabsEl: HTMLDivElement | null = null;
244
+ private feedbacksListEl: HTMLDivElement | null = null;
245
+ private agentStreamEl: HTMLDivElement | null = null;
246
+ private agentTrayEl: HTMLDivElement | null = null;
247
+ private agentStatusEl: HTMLDivElement | null = null;
248
+ private agentTextareaEl: HTMLTextAreaElement | null = null;
249
+ private agentSendBtn: HTMLButtonElement | null = null;
250
+
92
251
  private lastPointerX: number = 0;
93
252
  private lastPointerY: number = 0;
94
- private boundTrackPointer: (ev: MouseEvent) => void;
95
- private boundGlobalKeyDown: (ev: KeyboardEvent) => void;
253
+ private boundTrackPointer: (ev: MouseEvent) => void = () => {};
254
+ private boundGlobalKeyDown: (ev: KeyboardEvent) => void = () => {};
255
+ private cancelActivePeelDrag: (() => void) | null = null;
256
+
257
+ public attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {
258
+ if (oldValue === newValue) return;
259
+ if ((name === "data-theme" || name === "data-cd-theme") && (newValue === "dark" || newValue === "light")) {
260
+ this.applyTheme(newValue, false);
261
+ } else if (name === "data-position" && newValue) {
262
+ this.setCornerPosition(newValue as WidgetPosition);
263
+ }
264
+ }
96
265
 
97
266
  public connectedCallback(): void {
98
267
  if (!this.shadow) {
99
268
  this.shadow = this.attachShadow({ mode: "open" });
100
269
  }
101
270
  this.readDataAttributes();
271
+ this.initTheme();
272
+
273
+ try {
274
+ const storedWidth =
275
+ typeof localStorage !== "undefined" ? localStorage.getItem("context_drop_sidebar_width") : null;
276
+ if (storedWidth) {
277
+ const parsed = parseInt(storedWidth, 10);
278
+ if (!Number.isNaN(parsed) && parsed >= 360 && parsed <= 920) {
279
+ // If stored width was from the old cramped v0.2-alpha default (<= 440px), upgrade to DEFAULT_SIDEBAR_WIDTH
280
+ this.sidebarWidth = parsed <= 440 ? DEFAULT_SIDEBAR_WIDTH : parsed;
281
+ }
282
+ }
283
+ } catch {
284
+ // Non-fatal
285
+ }
286
+
287
+ this.surfaceMode = this.config.agent?.enabled ? "agent" : "feedback";
102
288
  this.renderShadowDom();
103
289
 
104
290
  this.boundTrackPointer = (ev: MouseEvent) => {
@@ -107,8 +293,16 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
107
293
  };
108
294
 
109
295
  this.boundGlobalKeyDown = (ev: KeyboardEvent) => {
110
- // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode from anywhere on the host page
296
+ if (ev.key === "Escape" && this.isPeelDragging && this.cancelActivePeelDrag) {
297
+ ev.preventDefault();
298
+ ev.stopPropagation();
299
+ this.cancelActivePeelDrag();
300
+ return;
301
+ }
302
+
303
+ // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
111
304
  if (
305
+ !this.isSmartSelectionMode() &&
112
306
  ev.altKey &&
113
307
  ev.shiftKey &&
114
308
  (ev.code === "KeyP" || (typeof ev.key === "string" && ev.key.toLowerCase() === "p"))
@@ -131,13 +325,21 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
131
325
  onSelect: (snapshot, el) => {
132
326
  const added = this.addElementReference(snapshot, el);
133
327
  if (added) {
134
- const count = this.elementReferences.length;
135
- this.showStatus(
136
- count === 1
137
- ? `Pinned ${snapshot.selector}`
138
- : `Pinned ${count} elements (latest: ${snapshot.selector})`,
139
- "success"
140
- );
328
+ if (this.isSmartSelectionMode()) {
329
+ this.hideStatus();
330
+ if (this.config.features.screenshot_capture) {
331
+ const friendlyLabel = this.getElementFriendlyLabel(snapshot, el);
332
+ void this.captureSmartSurroundingContext(el, snapshot.client_ref, friendlyLabel);
333
+ }
334
+ } else {
335
+ const count = this.elementReferences.length;
336
+ this.showStatus(
337
+ count === 1
338
+ ? `Pinned ${snapshot.selector}`
339
+ : `Pinned ${count} elements (latest: ${snapshot.selector})`,
340
+ "success"
341
+ );
342
+ }
141
343
  }
142
344
  this.syncUiStates();
143
345
  },
@@ -145,36 +347,62 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
145
347
  this.removeElementReference(clientRef);
146
348
  },
147
349
  onExit: () => {
350
+ if (this.isPeelDragging) return;
148
351
  this.isMinimized = false;
149
352
  this.openComposer();
150
353
  this.syncUiStates();
151
354
  },
152
- canSelectMore: () => this.elementReferences.length < this.config.limits.max_element_references,
355
+ canSelectMore: () =>
356
+ this.isPeelDragging ||
357
+ this.elementReferences.length < this.config.limits.max_element_references,
153
358
  getExcludedSelectors: () => this.config.privacy.excluded_selectors,
359
+ getSelectionMode: () => (this.isSmartSelectionMode() ? "smart" : "verbose"),
154
360
  getPinnedElements: () =>
155
361
  this.elementReferences
156
362
  .map((ref) => {
157
363
  const node = this.elementDomNodes.get(ref.client_ref);
364
+ const friendlyLabel =
365
+ typeof ref.metadata?.friendly_label === "string"
366
+ ? ref.metadata.friendly_label
367
+ : undefined;
158
368
  return node
159
- ? { clientRef: ref.client_ref, selector: ref.selector, element: node }
369
+ ? { clientRef: ref.client_ref, selector: ref.selector, friendlyLabel, element: node }
160
370
  : null;
161
371
  })
162
372
  .filter(
163
- (item): item is { clientRef: string; selector: string; element: Element } =>
164
- item !== null
373
+ (
374
+ item
375
+ ): item is {
376
+ clientRef: string;
377
+ selector: string;
378
+ friendlyLabel: string | undefined;
379
+ element: Element;
380
+ } => item !== null
165
381
  ),
166
382
  onStateChange: (state) => {
167
383
  this.syncPinActiveIndicators(state.active);
168
- this.renderCompactCoachBar(state.active, state.candidateStack.length);
384
+ if (!this.isPeelDragging) {
385
+ this.renderCompactCoachBar(state.active, state.candidateStack.length);
386
+ }
169
387
  }
170
388
  });
389
+
390
+ const hasInlineConfig =
391
+ typeof this.hasAttribute === "function" && this.hasAttribute("data-config");
392
+ if (!hasInlineConfig && typeof fetch === "function") {
393
+ void this.hydrateConfigFromServer();
394
+ }
171
395
  }
172
396
 
173
397
  public disconnectedCallback(): void {
398
+ if (this.cancelActivePeelDrag) {
399
+ this.cancelActivePeelDrag();
400
+ }
174
401
  if (this.picker && this.picker.isActive()) {
175
- this.picker.stop();
402
+ this.picker.stop({ silent: true });
176
403
  }
177
404
  this.picker?.hideExternalPreview();
405
+ this.syncHostPagePushMargin(false);
178
406
 
179
407
  if (typeof window !== "undefined") {
180
408
  window.removeEventListener("mousemove", this.boundTrackPointer, { capture: true });
@@ -186,6 +414,61 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
186
414
  return this.config;
187
415
  }
188
416
 
417
+ public setWidgetConfig(partial: Partial<WidgetConfig>): void {
418
+ const wasAgentEnabled = Boolean(this.config.agent?.enabled);
419
+ if (
420
+ typeof partial.placeholder === "string" &&
421
+ partial.placeholder !== DEFAULT_VERBOSE_PLACEHOLDER &&
422
+ partial.placeholder !== DEFAULT_SMART_PLACEHOLDER
423
+ ) {
424
+ this.customPlaceholderSet = true;
425
+ }
426
+ this.config = {
427
+ ...this.config,
428
+ ...partial,
429
+ agent: { ...(this.config.agent || { enabled: false }), ...(partial.agent || {}) },
430
+ features: { ...this.config.features, ...(partial.features || {}) },
431
+ limits: { ...this.config.limits, ...(partial.limits || {}) },
432
+ privacy: { ...this.config.privacy, ...(partial.privacy || {}) }
433
+ };
434
+ if (partial.csrf_token) {
435
+ this.apiClient.setCsrfToken(partial.csrf_token);
436
+ }
437
+ if (partial.position) {
438
+ this.setCornerPosition(partial.position);
439
+ }
440
+ const nowAgentEnabled = Boolean(this.config.agent?.enabled);
441
+ if (nowAgentEnabled && !wasAgentEnabled) {
442
+ this.surfaceMode = "agent";
443
+ if (this.isOpen) {
444
+ void this.ensureAgentStatusLoaded();
445
+ }
446
+ } else if (!nowAgentEnabled) {
447
+ this.surfaceMode = "feedback";
448
+ }
449
+ this.renderTray();
450
+ this.renderChatThread();
451
+ this.syncUiStates();
452
+ }
453
+
454
+ public getSurfaceMode(): WidgetSurfaceMode {
455
+ return this.isAgentModeActive() ? "agent" : "feedback";
456
+ }
457
+
458
+ public setSurfaceMode(mode: WidgetSurfaceMode): void {
459
+ if (mode === "agent" && !this.config.agent?.enabled) {
460
+ return;
461
+ }
462
+ this.surfaceMode = mode;
463
+ if (mode === "agent" && this.isOpen) {
464
+ void this.ensureAgentStatusLoaded();
465
+ }
466
+ this.renderTray();
467
+ this.renderChatThread();
468
+ this.syncUiStates();
469
+ this.focusActiveInput();
470
+ }
471
+
189
472
  public getElementReferences(): ElementReferenceSnapshot[] {
190
473
  return [...this.elementReferences];
191
474
  }
@@ -198,20 +481,53 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
198
481
  return [...this.sessionHistory];
199
482
  }
200
483
 
484
+ public getAgentMessages(): AgentChatMessage[] {
485
+ return [...this.agentMessages];
486
+ }
487
+
488
+ public isAgentModeActive(): boolean {
489
+ return Boolean(this.config.agent?.enabled) && this.surfaceMode === "agent";
490
+ }
491
+
492
+ public isSmartSelectionMode(): boolean {
493
+ if (this.isAgentModeActive()) {
494
+ return false;
495
+ }
496
+ if (this.config.features.selection_mode === "smart") {
497
+ return true;
498
+ }
499
+ if (this.config.features.selection_mode === "verbose") {
500
+ return false;
501
+ }
502
+ return (this.config.environment || "").toLowerCase() === "production";
503
+ }
504
+
505
+ private getElementFriendlyLabel(ref: ElementReferenceSnapshot, domNode?: Element): string {
506
+ const metaLabel = ref.metadata?.friendly_label;
507
+ if (typeof metaLabel === "string" && metaLabel.trim().length > 0) {
508
+ return metaLabel.trim();
509
+ }
510
+ if (domNode) {
511
+ return describeSmartComponent(domNode).label;
512
+ }
513
+ return ref.tag_name ? `Selected ${ref.tag_name} area` : "Selected page area";
514
+ }
515
+
201
516
  public openComposer(): void {
202
517
  this.isOpen = true;
203
518
  this.isMinimized = false;
204
- this.syncUiStates();
205
- if (this.textareaEl) {
206
- this.textareaEl.focus();
519
+ if (this.isAgentModeActive()) {
520
+ void this.ensureAgentStatusLoaded();
207
521
  }
522
+ this.syncUiStates();
523
+ this.focusActiveInput();
208
524
  }
209
525
 
210
526
  public closeComposer(): void {
211
527
  this.isOpen = false;
212
528
  this.isMinimized = false;
213
529
  if (this.picker && this.picker.isActive()) {
214
- this.picker.stop();
530
+ this.picker.stop({ silent: true });
215
531
  }
216
532
  this.picker?.hideExternalPreview();
217
533
  this.syncUiStates();
@@ -233,7 +549,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
233
549
 
234
550
  public expandFromCompactBar(): void {
235
551
  if (this.picker && this.picker.isActive()) {
236
- this.picker.stop();
552
+ this.picker.stop({ silent: true });
237
553
  }
238
554
  this.isMinimized = false;
239
555
  this.openComposer();
@@ -250,7 +566,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
250
566
  return;
251
567
  }
252
568
  this.minimizeToCompactBar();
253
- this.picker.start();
569
+ this.picker.start({ suppressCursorPin: false });
254
570
  if (this.lastPointerX > 0 && this.lastPointerY > 0) {
255
571
  this.picker.highlightAtPoint(this.lastPointerX, this.lastPointerY);
256
572
  }
@@ -265,6 +581,141 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
265
581
  }
266
582
  }
267
583
 
584
+ public getTheme(): "light" | "dark" {
585
+ return this.currentTheme;
586
+ }
587
+
588
+ public setTheme(theme: "light" | "dark"): void {
589
+ this.applyTheme(theme, true);
590
+ }
591
+
592
+ public toggleTheme(): void {
593
+ const next = this.currentTheme === "dark" ? "light" : "dark";
594
+ this.applyTheme(next, true);
595
+ }
596
+
597
+ private initTheme(): void {
598
+ let theme: "light" | "dark" = "light";
599
+ try {
600
+ const stored =
601
+ typeof localStorage !== "undefined" ? localStorage.getItem("context_drop_theme") : null;
602
+ if (stored === "dark" || stored === "light") {
603
+ theme = stored;
604
+ } else {
605
+ const attr = this.getAttribute("data-cd-theme") || this.getAttribute("data-theme");
606
+ if (attr === "dark" || attr === "light") {
607
+ theme = attr;
608
+ } else if (
609
+ typeof window !== "undefined" &&
610
+ window.matchMedia &&
611
+ window.matchMedia("(prefers-color-scheme: dark)").matches
612
+ ) {
613
+ theme = "dark";
614
+ }
615
+ }
616
+ } catch {
617
+ // Non-fatal if localStorage is restricted
618
+ }
619
+ this.applyTheme(theme, false);
620
+
621
+ if (typeof window !== "undefined" && window.matchMedia) {
622
+ try {
623
+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
624
+ mediaQuery.addEventListener?.("change", (e) => {
625
+ try {
626
+ if (!localStorage.getItem("context_drop_theme")) {
627
+ this.applyTheme(e.matches ? "dark" : "light", false);
628
+ }
629
+ } catch {
630
+ // ignore
631
+ }
632
+ });
633
+ } catch {
634
+ // ignore
635
+ }
636
+ }
637
+ }
638
+
639
+ private applyTheme(theme: "light" | "dark", persist: boolean = true): void {
640
+ this.currentTheme = theme;
641
+ if (persist) {
642
+ try {
643
+ localStorage.setItem("context_drop_theme", theme);
644
+ } catch {
645
+ // Non-fatal
646
+ }
647
+ }
648
+
649
+ // Use namespaced `data-cd-theme` on the custom element host so host CSS frameworks
650
+ // (e.g. DaisyUI / Bootstrap `[data-theme="dark"]` or `body:has([data-theme="dark"])`)
651
+ // never alter the host page theme when toggling the widget theme.
652
+ if (typeof this.setAttribute === "function") {
653
+ this.setAttribute("data-cd-theme", theme);
654
+ }
655
+ this.rootContainer?.setAttribute("data-theme", theme);
656
+ this.agentSidebarEl?.setAttribute("data-theme", theme);
657
+ this.composerEl?.setAttribute("data-theme", theme);
658
+ this.compactBarEl?.setAttribute("data-theme", theme);
659
+ this.bookCornerBtn?.setAttribute("data-theme", theme);
660
+ this.dragPinEl?.setAttribute("data-theme", theme);
661
+ this.cornerSnapGhostEl?.setAttribute("data-theme", theme);
662
+
663
+ if (this.composerThemeToggleBtn) {
664
+ this.updateThemeToggleBtn(this.composerThemeToggleBtn);
665
+ }
666
+ if (this.sidebarThemeToggleBtn) {
667
+ this.updateThemeToggleBtn(this.sidebarThemeToggleBtn);
668
+ }
669
+
670
+ if (typeof this.dispatchEvent === "function") {
671
+ try {
672
+ this.dispatchEvent(
673
+ new CustomEvent("contextdrop:themechange", {
674
+ bubbles: false,
675
+ composed: false,
676
+ detail: { theme }
677
+ })
678
+ );
679
+ } catch {
680
+ // ignore
681
+ }
682
+ }
683
+ }
684
+
685
+ private buildThemeToggleBtn(): HTMLButtonElement {
686
+ const btn = document.createElement("button");
687
+ btn.type = "button";
688
+ btn.className = "cd-icon-btn cd-theme-toggle";
689
+ this.updateThemeToggleBtn(btn);
690
+ btn.addEventListener("click", () => {
691
+ this.toggleTheme();
692
+ });
693
+ return btn;
694
+ }
695
+
696
+ private updateThemeToggleBtn(btn: HTMLButtonElement): void {
697
+ const isDark = this.currentTheme === "dark";
698
+ btn.title = isDark ? "Switch to light theme" : "Switch to dark theme";
699
+ btn.setAttribute("aria-label", isDark ? "Switch to light theme" : "Switch to dark theme");
700
+ btn.innerHTML = isDark ? ICON_SUN : ICON_MOON;
701
+ }
702
+
703
+ public setCornerPosition(position: WidgetPosition): void {
704
+ if (!["top_left", "top_right", "bottom_left", "bottom_right"].includes(position)) {
705
+ return;
706
+ }
707
+ this.config.position = position;
708
+ this.freePos = null;
709
+ if (this.rootContainer) {
710
+ this.rootContainer.className = `cd-root pos-${position}`;
711
+ this.rootContainer.style.left = "";
712
+ this.rootContainer.style.top = "";
713
+ }
714
+ if (this.bookCornerBtn) {
715
+ this.bookCornerBtn.className = `cd-book-corner corner-${position}`;
716
+ }
717
+ }
718
+
268
719
  public setFreePosition(left: number, top: number): void {
269
720
  if (!this.rootContainer) return;
270
721
  const vw = typeof window !== "undefined" ? window.innerWidth || 1024 : 1024;
@@ -299,6 +750,10 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
299
750
  public removeElementReference(clientRef: string): void {
300
751
  this.elementReferences = this.elementReferences.filter((el) => el.client_ref !== clientRef);
301
752
  this.elementDomNodes.delete(clientRef);
753
+ this.attachments = this.attachments.filter(
754
+ (att) =>
755
+ !(att.element_reference_ref === clientRef && att.metadata?.auto_smart_context === true)
756
+ );
302
757
  this.picker?.hideExternalPreview();
303
758
  this.picker?.refreshPinnedMarkers();
304
759
  this.renderTray();
@@ -311,6 +766,29 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
311
766
  this.syncUiStates();
312
767
  }
313
768
 
769
+ private focusActiveInput(): void {
770
+ if (this.isAgentModeActive()) {
771
+ this.agentTextareaEl?.focus();
772
+ } else {
773
+ this.textareaEl?.focus();
774
+ }
775
+ }
776
+
777
+ private async hydrateConfigFromServer(): Promise<void> {
778
+ try {
779
+ const remoteConfig = await this.apiClient.fetchConfig();
780
+ if (remoteConfig && typeof remoteConfig === "object") {
781
+ const posOverride = this.getAttribute("data-position") as WidgetPosition | null;
782
+ this.setWidgetConfig({
783
+ ...remoteConfig,
784
+ position: posOverride || remoteConfig.position || this.config.position
785
+ });
786
+ }
787
+ } catch {
788
+ // Non-fatal in static/offline environments
789
+ }
790
+ }
791
+
314
792
  private readDataAttributes(): void {
315
793
  const endpoint = this.getAttribute("data-endpoint") || "/context_drop";
316
794
  this.apiClient = new ContextDropApiClient(endpoint);
@@ -319,9 +797,17 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
319
797
  if (rawConfig) {
320
798
  try {
321
799
  const parsed = JSON.parse(rawConfig) as Partial<WidgetConfig>;
800
+ if (
801
+ typeof parsed.placeholder === "string" &&
802
+ parsed.placeholder !== DEFAULT_VERBOSE_PLACEHOLDER &&
803
+ parsed.placeholder !== DEFAULT_SMART_PLACEHOLDER
804
+ ) {
805
+ this.customPlaceholderSet = true;
806
+ }
322
807
  this.config = {
323
808
  ...this.config,
324
809
  ...parsed,
810
+ agent: { ...(this.config.agent || { enabled: false }), ...(parsed.agent || {}) },
325
811
  features: { ...this.config.features, ...(parsed.features || {}) },
326
812
  limits: { ...this.config.limits, ...(parsed.limits || {}) },
327
813
  privacy: { ...this.config.privacy, ...(parsed.privacy || {}) }
@@ -345,6 +831,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
345
831
  const placeholderOverride = this.getAttribute("data-placeholder");
346
832
  if (placeholderOverride) {
347
833
  this.config.placeholder = placeholderOverride;
834
+ this.customPlaceholderSet = true;
348
835
  }
349
836
 
350
837
  const rawMetadata = this.getAttribute("data-metadata");
@@ -355,37 +842,255 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
355
842
  this.customMetadata = {};
356
843
  }
357
844
  }
845
+
846
+ const themeOverride = this.getAttribute("data-cd-theme") || this.getAttribute("data-theme");
847
+ if (themeOverride === "dark" || themeOverride === "light") {
848
+ this.currentTheme = themeOverride;
849
+ }
850
+ }
851
+
852
+ private detectViewportSnapCorner(
853
+ clientX: number,
854
+ clientY: number,
855
+ originCorner: WidgetPosition,
856
+ leftOriginZone: boolean
857
+ ): WidgetPosition | null {
858
+ if (typeof window === "undefined") return null;
859
+ const vw = window.innerWidth || 1024;
860
+ const vh = window.innerHeight || 768;
861
+
862
+ let candidate: WidgetPosition | null = null;
863
+ if (clientX <= CORNER_SNAP_ZONE_PX && clientY <= CORNER_SNAP_ZONE_PX) {
864
+ candidate = "top_left";
865
+ } else if (clientX >= vw - CORNER_SNAP_ZONE_PX && clientY <= CORNER_SNAP_ZONE_PX) {
866
+ candidate = "top_right";
867
+ } else if (clientX <= CORNER_SNAP_ZONE_PX && clientY >= vh - CORNER_SNAP_ZONE_PX) {
868
+ candidate = "bottom_left";
869
+ } else if (clientX >= vw - CORNER_SNAP_ZONE_PX && clientY >= vh - CORNER_SNAP_ZONE_PX) {
870
+ candidate = "bottom_right";
871
+ }
872
+
873
+ if (!candidate) return null;
874
+ if (candidate === originCorner && !leftOriginZone) return null;
875
+ return candidate;
876
+ }
877
+
878
+ private isOutsideCornerZone(clientX: number, clientY: number, corner: WidgetPosition): boolean {
879
+ if (typeof window === "undefined") return true;
880
+ const vw = window.innerWidth || 1024;
881
+ const vh = window.innerHeight || 768;
882
+ const exitRadius = CORNER_SNAP_ZONE_PX + 10;
883
+
884
+ switch (corner) {
885
+ case "top_left":
886
+ return clientX > exitRadius || clientY > exitRadius;
887
+ case "top_right":
888
+ return clientX < vw - exitRadius || clientY > exitRadius;
889
+ case "bottom_left":
890
+ return clientX > exitRadius || clientY < vh - exitRadius;
891
+ case "bottom_right":
892
+ return clientX < vw - exitRadius || clientY < vh - exitRadius;
893
+ }
358
894
  }
359
895
 
360
- private attachDragHandle(handleEl: HTMLElement, onClickFallback?: () => void): void {
896
+ private attachBookCornerLauncher(cornerBtn: HTMLButtonElement): void {
361
897
  let startX = 0;
362
898
  let startY = 0;
363
- let initialLeft = 0;
364
- let initialTop = 0;
365
- let dragging = false;
366
- let moved = false;
899
+ let pointerActive = false;
900
+ let peeled = false;
901
+ let leftOriginZone = false;
902
+ let activeSnapCorner: WidgetPosition | null = null;
367
903
  let suppressNextClick = false;
368
- let suppressClickTimer: ReturnType<typeof setTimeout> | null = null;
904
+ let suppressTimer: ReturnType<typeof setTimeout> | null = null;
369
905
 
370
- const clearSuppressClick = (): void => {
906
+ const clearSuppress = (): void => {
371
907
  suppressNextClick = false;
372
- if (suppressClickTimer !== null) {
373
- clearTimeout(suppressClickTimer);
374
- suppressClickTimer = null;
908
+ if (suppressTimer !== null) {
909
+ clearTimeout(suppressTimer);
910
+ suppressTimer = null;
375
911
  }
376
912
  };
377
913
 
378
- if (onClickFallback) {
379
- handleEl.addEventListener("click", (ev: MouseEvent) => {
380
- if (suppressNextClick) {
381
- clearSuppressClick();
382
- ev.preventDefault();
383
- ev.stopPropagation();
384
- return;
914
+ const updateDragPinPosition = (x: number, y: number): void => {
915
+ if (!this.dragPinEl) return;
916
+ this.dragPinEl.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`;
917
+ };
918
+
919
+ const finishPeelVisuals = (): void => {
920
+ pointerActive = false;
921
+ this.isPeelDragging = false;
922
+ this.cancelActivePeelDrag = null;
923
+ cornerBtn.classList.remove("is-peeled");
924
+ if (this.dragPinEl) {
925
+ this.dragPinEl.hidden = true;
926
+ this.dragPinEl.classList.remove("has-target", "is-snapping-corner");
927
+ }
928
+ if (this.cornerSnapGhostEl) {
929
+ this.cornerSnapGhostEl.hidden = true;
930
+ }
931
+ if (typeof window !== "undefined") {
932
+ window.removeEventListener("pointermove", onPointerMove);
933
+ window.removeEventListener("pointerup", onPointerUp);
934
+ window.removeEventListener("pointercancel", onPointerCancel);
935
+ }
936
+ };
937
+
938
+ cornerBtn.addEventListener("click", (ev: MouseEvent) => {
939
+ if (suppressNextClick) {
940
+ clearSuppress();
941
+ ev.preventDefault();
942
+ ev.stopPropagation();
943
+ return;
944
+ }
945
+ this.openComposer();
946
+ });
947
+
948
+ const onPointerMove = (ev: PointerEvent): void => {
949
+ if (!pointerActive) return;
950
+ this.lastPointerX = ev.clientX;
951
+ this.lastPointerY = ev.clientY;
952
+
953
+ const travel = Math.hypot(ev.clientX - startX, ev.clientY - startY);
954
+ if (!peeled && travel > PEEL_DRAG_THRESHOLD_PX) {
955
+ peeled = true;
956
+ this.isPeelDragging = true;
957
+ cornerBtn.classList.add("is-peeled");
958
+
959
+ if (this.dragPinEl) {
960
+ this.dragPinEl.hidden = false;
961
+ updateDragPinPosition(ev.clientX, ev.clientY);
385
962
  }
386
- onClickFallback();
387
- });
388
- }
963
+
964
+ if (
965
+ this.config.features.element_selection &&
966
+ this.picker &&
967
+ this.elementReferences.length < this.config.limits.max_element_references
968
+ ) {
969
+ this.picker.start({ suppressCursorPin: true });
970
+ }
971
+ }
972
+
973
+ if (!peeled) return;
974
+
975
+ updateDragPinPosition(ev.clientX, ev.clientY);
976
+
977
+ if (!leftOriginZone && this.isOutsideCornerZone(ev.clientX, ev.clientY, this.config.position)) {
978
+ leftOriginZone = true;
979
+ }
980
+
981
+ activeSnapCorner = this.detectViewportSnapCorner(
982
+ ev.clientX,
983
+ ev.clientY,
984
+ this.config.position,
985
+ leftOriginZone
986
+ );
987
+
988
+ if (activeSnapCorner) {
989
+ this.picker?.clearCandidateHighlight();
990
+ if (this.cornerSnapGhostEl) {
991
+ this.cornerSnapGhostEl.className = `cd-corner-snap-ghost corner-${activeSnapCorner}`;
992
+ this.cornerSnapGhostEl.hidden = false;
993
+ }
994
+ if (this.dragPinEl) {
995
+ this.dragPinEl.classList.add("is-snapping-corner");
996
+ this.dragPinEl.classList.remove("has-target");
997
+ }
998
+ } else {
999
+ if (this.cornerSnapGhostEl) {
1000
+ this.cornerSnapGhostEl.hidden = true;
1001
+ }
1002
+ if (this.dragPinEl) {
1003
+ this.dragPinEl.classList.remove("is-snapping-corner");
1004
+ }
1005
+ this.picker?.highlightAtPoint(ev.clientX, ev.clientY, ev);
1006
+ const hasTarget = Boolean(this.picker?.getActiveCandidate());
1007
+ this.dragPinEl?.classList.toggle("has-target", hasTarget);
1008
+ }
1009
+ };
1010
+
1011
+ const armClickSuppression = (): void => {
1012
+ suppressNextClick = true;
1013
+ if (suppressTimer !== null) {
1014
+ clearTimeout(suppressTimer);
1015
+ }
1016
+ suppressTimer = setTimeout(() => {
1017
+ suppressNextClick = false;
1018
+ suppressTimer = null;
1019
+ }, 40);
1020
+ };
1021
+
1022
+ const onPointerUp = (ev: PointerEvent): void => {
1023
+ if (!pointerActive) return;
1024
+ const wasPeeled = peeled;
1025
+ const snapTarget = activeSnapCorner;
1026
+ peeled = false;
1027
+ activeSnapCorner = null;
1028
+
1029
+ if (!wasPeeled) {
1030
+ finishPeelVisuals();
1031
+ return;
1032
+ }
1033
+
1034
+ armClickSuppression();
1035
+
1036
+ if (snapTarget) {
1037
+ this.picker?.stop({ silent: true });
1038
+ finishPeelVisuals();
1039
+ this.setCornerPosition(snapTarget);
1040
+ this.syncUiStates();
1041
+ return;
1042
+ }
1043
+
1044
+ this.picker?.highlightAtPoint(ev.clientX, ev.clientY, ev);
1045
+ const committed = this.picker ? this.picker.commitActiveCandidate(ev.clientX, ev.clientY) : false;
1046
+ this.picker?.stop({ silent: true });
1047
+ finishPeelVisuals();
1048
+
1049
+ if (committed) {
1050
+ this.openComposer();
1051
+ } else {
1052
+ this.syncUiStates();
1053
+ }
1054
+ };
1055
+
1056
+ const onPointerCancel = (): void => {
1057
+ if (!pointerActive) return;
1058
+ peeled = false;
1059
+ activeSnapCorner = null;
1060
+ this.picker?.stop({ silent: true });
1061
+ finishPeelVisuals();
1062
+ clearSuppress();
1063
+ this.syncUiStates();
1064
+ };
1065
+
1066
+ cornerBtn.addEventListener("pointerdown", (ev: PointerEvent) => {
1067
+ if (ev.button !== 0 || typeof window === "undefined") return;
1068
+ startX = ev.clientX;
1069
+ startY = ev.clientY;
1070
+ pointerActive = true;
1071
+ peeled = false;
1072
+ leftOriginZone = false;
1073
+ activeSnapCorner = null;
1074
+ clearSuppress();
1075
+
1076
+ this.cancelActivePeelDrag = () => {
1077
+ armClickSuppression();
1078
+ onPointerCancel();
1079
+ };
1080
+
1081
+ window.addEventListener("pointermove", onPointerMove);
1082
+ window.addEventListener("pointerup", onPointerUp);
1083
+ window.addEventListener("pointercancel", onPointerCancel);
1084
+ });
1085
+ }
1086
+
1087
+ private attachDragHandle(handleEl: HTMLElement): void {
1088
+ let startX = 0;
1089
+ let startY = 0;
1090
+ let initialLeft = 0;
1091
+ let initialTop = 0;
1092
+ let dragging = false;
1093
+ let moved = false;
389
1094
 
390
1095
  const onPointerMove = (ev: PointerEvent): void => {
391
1096
  if (!dragging) return;
@@ -393,7 +1098,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
393
1098
  const dy = ev.clientY - startY;
394
1099
  if (!moved && Math.hypot(dx, dy) > 5) {
395
1100
  moved = true;
396
- this.pinDockEl?.classList.add("is-dragging");
397
1101
  }
398
1102
  if (moved) {
399
1103
  this.setFreePosition(initialLeft + dx, initialTop + dy);
@@ -402,35 +1106,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
402
1106
 
403
1107
  const cleanupDrag = (): void => {
404
1108
  dragging = false;
405
- this.pinDockEl?.classList.remove("is-dragging");
406
1109
  window.removeEventListener("pointermove", onPointerMove);
407
- window.removeEventListener("pointerup", onPointerUp);
408
- window.removeEventListener("pointercancel", onPointerCancel);
409
- };
410
-
411
- const onPointerUp = (): void => {
412
- if (!dragging) return;
413
- cleanupDrag();
414
- if (moved && onClickFallback) {
415
- suppressNextClick = true;
416
- if (suppressClickTimer !== null) {
417
- clearTimeout(suppressClickTimer);
418
- }
419
- suppressClickTimer = setTimeout(() => {
420
- suppressNextClick = false;
421
- suppressClickTimer = null;
422
- }, 0);
423
- }
424
- };
425
-
426
- const onPointerCancel = (): void => {
427
- if (!dragging) return;
428
- cleanupDrag();
429
- clearSuppressClick();
1110
+ window.removeEventListener("pointerup", cleanupDrag);
1111
+ window.removeEventListener("pointercancel", cleanupDrag);
430
1112
  };
431
1113
 
432
1114
  handleEl.addEventListener("pointerdown", (ev: PointerEvent) => {
433
- // Only primary mouse button or touch
434
1115
  if (ev.button !== 0) return;
435
1116
  const targetEl =
436
1117
  ev.target && typeof (ev.target as Element).closest === "function"
@@ -449,27 +1130,169 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
449
1130
  initialTop = this.freePos ? this.freePos.top : rect.top;
450
1131
  dragging = true;
451
1132
  moved = false;
452
- clearSuppressClick();
453
1133
 
454
1134
  window.addEventListener("pointermove", onPointerMove);
455
- window.addEventListener("pointerup", onPointerUp);
456
- window.addEventListener("pointercancel", onPointerCancel);
1135
+ window.addEventListener("pointerup", cleanupDrag);
1136
+ window.addEventListener("pointercancel", cleanupDrag);
457
1137
  });
458
1138
  }
459
1139
 
460
- private renderShadowDom(): void {
461
- if (!this.shadow) return;
462
- this.shadow.innerHTML = "";
463
-
464
- const styleEl = document.createElement("style");
465
- styleEl.textContent = WIDGET_SHADOW_STYLES;
466
- this.shadow.appendChild(styleEl);
1140
+ private attachSidebarResizer(resizerEl: HTMLDivElement): void {
1141
+ let startX = 0;
1142
+ let startWidth = this.sidebarWidth;
1143
+ let active = false;
467
1144
 
468
- const root = document.createElement("div");
469
- root.className = `cd-root pos-${this.config.position}`;
470
- this.rootContainer = root;
1145
+ const onPointerMove = (ev: PointerEvent): void => {
1146
+ if (!active || typeof window === "undefined") return;
1147
+ const delta = this.sidebarSide === "right" ? startX - ev.clientX : ev.clientX - startX;
1148
+ const maxAllowed = Math.max(360, (window.innerWidth || 1024) - 80);
1149
+ this.sidebarWidth = Math.max(360, Math.min(Math.min(920, maxAllowed), startWidth + delta));
1150
+ if (this.agentSidebarEl) {
1151
+ this.agentSidebarEl.style.width = `${Math.round(this.sidebarWidth)}px`;
1152
+ }
1153
+ if (this.pushPageLayout && this.isOpen && !this.isMinimized && this.isAgentModeActive()) {
1154
+ this.syncHostPagePushMargin(true);
1155
+ }
1156
+ };
471
1157
 
472
- // 1. Compact Minimized Pinning Bar (visible while pinning elements on the page or minimized)
1158
+ const stopResize = (): void => {
1159
+ active = false;
1160
+ resizerEl.classList.remove("is-resizing");
1161
+ try {
1162
+ localStorage.setItem("context_drop_sidebar_width", String(Math.round(this.sidebarWidth)));
1163
+ } catch {
1164
+ // Non-fatal
1165
+ }
1166
+ window.removeEventListener("pointermove", onPointerMove);
1167
+ window.removeEventListener("pointerup", stopResize);
1168
+ window.removeEventListener("pointercancel", stopResize);
1169
+ };
1170
+
1171
+ resizerEl.addEventListener("pointerdown", (ev: PointerEvent) => {
1172
+ if (ev.button !== 0 || typeof window === "undefined") return;
1173
+ ev.preventDefault();
1174
+ active = true;
1175
+ startX = ev.clientX;
1176
+ startWidth = this.sidebarWidth;
1177
+ resizerEl.classList.add("is-resizing");
1178
+ window.addEventListener("pointermove", onPointerMove);
1179
+ window.addEventListener("pointerup", stopResize);
1180
+ window.addEventListener("pointercancel", stopResize);
1181
+ });
1182
+ }
1183
+
1184
+ private syncHostPagePushMargin(shouldPush: boolean): void {
1185
+ if (typeof document === "undefined" || !document.documentElement) return;
1186
+ const htmlEl = document.documentElement;
1187
+ if (!shouldPush) {
1188
+ if (htmlEl.getAttribute("data-context-drop-pushed") === "true") {
1189
+ htmlEl.style.marginRight = "";
1190
+ htmlEl.style.marginLeft = "";
1191
+ if (typeof htmlEl.removeAttribute === "function") {
1192
+ htmlEl.removeAttribute("data-context-drop-pushed");
1193
+ } else {
1194
+ htmlEl.setAttribute("data-context-drop-pushed", "");
1195
+ }
1196
+ }
1197
+ return;
1198
+ }
1199
+
1200
+ htmlEl.setAttribute("data-context-drop-pushed", "true");
1201
+ if (this.sidebarSide === "right") {
1202
+ htmlEl.style.marginLeft = "";
1203
+ htmlEl.style.marginRight = `${Math.round(this.sidebarWidth)}px`;
1204
+ } else {
1205
+ htmlEl.style.marginRight = "";
1206
+ htmlEl.style.marginLeft = `${Math.round(this.sidebarWidth)}px`;
1207
+ }
1208
+ }
1209
+
1210
+ private renderShadowDom(): void {
1211
+ if (!this.shadow) return;
1212
+ this.shadow.innerHTML = "";
1213
+
1214
+ const styleEl = document.createElement("style");
1215
+ styleEl.textContent = WIDGET_SHADOW_STYLES;
1216
+ this.shadow.appendChild(styleEl);
1217
+
1218
+ const root = document.createElement("div");
1219
+ root.className = `cd-root pos-${this.config.position}`;
1220
+ this.rootContainer = root;
1221
+
1222
+ // 1. Compact Minimized Pinning Bar (visible while pinning elements on the page or minimized)
1223
+ const compactBar = this.buildCompactBarDom();
1224
+ root.appendChild(compactBar);
1225
+
1226
+ // 2. Standard Floating Feedback Chatbox Composer
1227
+ const composer = this.buildFeedbackComposerDom();
1228
+ root.appendChild(composer);
1229
+
1230
+ this.shadow.appendChild(root);
1231
+
1232
+ // 3. Docked Local BYOK Agentic Coding Sidebar (active in local development mode)
1233
+ const sidebar = this.buildAgentSidebarDom();
1234
+ this.shadow.appendChild(sidebar);
1235
+
1236
+ // 4. Book-Corner Fold Launcher (flush at viewport corner, peels into pushpin on drag)
1237
+ const bookCorner = document.createElement("button");
1238
+ bookCorner.type = "button";
1239
+ bookCorner.className = `cd-book-corner corner-${this.config.position}`;
1240
+ bookCorner.setAttribute(
1241
+ "aria-label",
1242
+ "Open ContextDrop chatbox, or drag corner to pin an element on the page"
1243
+ );
1244
+ bookCorner.setAttribute("aria-expanded", String(this.isOpen));
1245
+
1246
+ const cornerArt = document.createElement("span");
1247
+ cornerArt.className = "cd-book-corner-art";
1248
+ cornerArt.innerHTML = BOOK_CORNER_SVG;
1249
+ bookCorner.appendChild(cornerArt);
1250
+
1251
+ const agentDot = document.createElement("span");
1252
+ agentDot.className = "cd-corner-agent-dot";
1253
+ agentDot.hidden = true;
1254
+ this.bookCornerAgentDotEl = agentDot;
1255
+ bookCorner.appendChild(agentDot);
1256
+
1257
+ const countBadge = document.createElement("span");
1258
+ countBadge.className = "cd-corner-count";
1259
+ countBadge.hidden = true;
1260
+ this.bookCornerCountEl = countBadge;
1261
+ bookCorner.appendChild(countBadge);
1262
+
1263
+ const hoverHint = document.createElement("span");
1264
+ hoverHint.className = "cd-corner-hint";
1265
+ hoverHint.setAttribute("aria-hidden", "true");
1266
+ hoverHint.textContent = "Click to chat · Drag to pin";
1267
+ this.bookCornerHintEl = hoverHint;
1268
+ bookCorner.appendChild(hoverHint);
1269
+
1270
+ this.attachBookCornerLauncher(bookCorner);
1271
+ this.bookCornerBtn = bookCorner;
1272
+ this.shadow.appendChild(bookCorner);
1273
+
1274
+ // 5. Morphing Drag Pushpin + Viewport Corner Snap Ghost
1275
+ const snapGhost = document.createElement("div");
1276
+ snapGhost.className = `cd-corner-snap-ghost corner-${this.config.position}`;
1277
+ snapGhost.hidden = true;
1278
+ this.cornerSnapGhostEl = snapGhost;
1279
+ this.shadow.appendChild(snapGhost);
1280
+
1281
+ const dragPin = document.createElement("div");
1282
+ dragPin.className = "cd-drag-pin";
1283
+ dragPin.hidden = true;
1284
+ const dragPinHead = document.createElement("div");
1285
+ dragPinHead.className = "cd-drag-pin-head";
1286
+ dragPinHead.innerHTML = ICON_PIN;
1287
+ dragPin.appendChild(dragPinHead);
1288
+ this.dragPinEl = dragPin;
1289
+ this.shadow.appendChild(dragPin);
1290
+
1291
+ this.applyTheme(this.currentTheme, false);
1292
+ this.syncUiStates();
1293
+ }
1294
+
1295
+ private buildCompactBarDom(): HTMLDivElement {
473
1296
  const compactBar = document.createElement("div");
474
1297
  compactBar.className = "cd-compact-bar";
475
1298
  compactBar.setAttribute("role", "region");
@@ -534,15 +1357,42 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
534
1357
  this.compactDoneBtn = expandBtn;
535
1358
  compactBar.appendChild(expandBtn);
536
1359
 
537
- // 2. Main Floating Chatbox Composer Window
1360
+ return compactBar;
1361
+ }
1362
+
1363
+ private buildModeSwitchDom(activeMode: WidgetSurfaceMode): HTMLDivElement {
1364
+ const wrap = document.createElement("div");
1365
+ wrap.className = "cd-mode-switch";
1366
+ wrap.setAttribute("role", "tablist");
1367
+ wrap.setAttribute("aria-label", "ContextDrop mode");
1368
+
1369
+ const agentBtn = document.createElement("button");
1370
+ agentBtn.type = "button";
1371
+ agentBtn.className = `cd-mode-btn${activeMode === "agent" ? " is-active" : ""}`;
1372
+ agentBtn.setAttribute("aria-selected", String(activeMode === "agent"));
1373
+ agentBtn.innerHTML = `${ICON_CODE_PROMPT}<span>Agent</span>`;
1374
+ agentBtn.addEventListener("click", () => this.setSurfaceMode("agent"));
1375
+
1376
+ const feedbackBtn = document.createElement("button");
1377
+ feedbackBtn.type = "button";
1378
+ feedbackBtn.className = `cd-mode-btn${activeMode === "feedback" ? " is-active" : ""}`;
1379
+ feedbackBtn.setAttribute("aria-selected", String(activeMode === "feedback"));
1380
+ feedbackBtn.textContent = "Feedback";
1381
+ feedbackBtn.addEventListener("click", () => this.setSurfaceMode("feedback"));
1382
+
1383
+ wrap.appendChild(agentBtn);
1384
+ wrap.appendChild(feedbackBtn);
1385
+ return wrap;
1386
+ }
1387
+
1388
+ private buildFeedbackComposerDom(): HTMLDivElement {
538
1389
  const composer = document.createElement("div");
539
1390
  composer.className = "cd-composer";
540
1391
  composer.setAttribute("role", "dialog");
541
1392
  composer.setAttribute("aria-label", "ContextDrop Feedback Chatbox");
542
- composer.hidden = !this.isOpen;
1393
+ composer.hidden = true;
543
1394
  this.composerEl = composer;
544
1395
 
545
- // Drag-and-drop image support on the chatbox
546
1396
  composer.addEventListener("dragover", (ev) => {
547
1397
  ev.preventDefault();
548
1398
  composer.classList.add("is-dragging-over");
@@ -559,7 +1409,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
559
1409
  }
560
1410
  });
561
1411
 
562
- // Header with Top-Left Pin-Shaped Selector & Drag Handle
563
1412
  const header = document.createElement("div");
564
1413
  header.className = "cd-composer-header";
565
1414
  this.attachDragHandle(header);
@@ -582,11 +1431,23 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
582
1431
  const title = document.createElement("h2");
583
1432
  title.className = "cd-composer-title";
584
1433
  title.textContent = "ContextDrop";
1434
+ this.composerTitleEl = title;
585
1435
  headerLeft.appendChild(title);
586
1436
 
587
1437
  const headerActions = document.createElement("div");
588
1438
  headerActions.className = "cd-header-actions";
589
1439
 
1440
+ const modeSwitchHolder = document.createElement("div");
1441
+ modeSwitchHolder.className = "cd-composer-mode-switch-wrap";
1442
+ modeSwitchHolder.hidden = !this.config.agent?.enabled;
1443
+ modeSwitchHolder.appendChild(this.buildModeSwitchDom("feedback"));
1444
+ this.composerModeSwitchWrap = modeSwitchHolder;
1445
+ headerActions.appendChild(modeSwitchHolder);
1446
+
1447
+ const themeBtn = this.buildThemeToggleBtn();
1448
+ this.composerThemeToggleBtn = themeBtn;
1449
+ headerActions.appendChild(themeBtn);
1450
+
590
1451
  const minBtn = document.createElement("button");
591
1452
  minBtn.type = "button";
592
1453
  minBtn.className = "cd-icon-btn";
@@ -594,6 +1455,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
594
1455
  minBtn.setAttribute("aria-label", "Minimize chatbox to compact bar");
595
1456
  minBtn.innerHTML = ICON_MINIMIZE;
596
1457
  minBtn.addEventListener("click", () => this.minimizeToCompactBar());
1458
+ this.composerMinBtn = minBtn;
597
1459
 
598
1460
  const closeBtn = document.createElement("button");
599
1461
  closeBtn.type = "button";
@@ -609,7 +1471,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
609
1471
  header.appendChild(headerActions);
610
1472
  composer.appendChild(header);
611
1473
 
612
- // Conversational Chat Thread
613
1474
  const chatThread = document.createElement("div");
614
1475
  chatThread.className = "cd-chat-thread";
615
1476
  chatThread.setAttribute("aria-live", "polite");
@@ -617,214 +1478,1425 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
617
1478
  composer.appendChild(chatThread);
618
1479
  this.renderChatThread();
619
1480
 
620
- // Pinned Elements & Attachments Chip Tray
621
- const tray = document.createElement("div");
622
- tray.className = "cd-tray";
623
- tray.setAttribute("aria-label", "Attached context items");
624
- this.trayEl = tray;
625
- composer.appendChild(tray);
1481
+ const tray = document.createElement("div");
1482
+ tray.className = "cd-tray";
1483
+ tray.setAttribute("aria-label", "Attached context items");
1484
+ this.trayEl = tray;
1485
+ composer.appendChild(tray);
1486
+
1487
+ const status = document.createElement("div");
1488
+ status.className = "cd-status";
1489
+ status.setAttribute("role", "status");
1490
+ status.hidden = true;
1491
+ this.statusEl = status;
1492
+ composer.appendChild(status);
1493
+
1494
+ const fileInput = document.createElement("input");
1495
+ fileInput.type = "file";
1496
+ fileInput.multiple = true;
1497
+ fileInput.accept = this.config.limits.allowed_content_types.join(",");
1498
+ fileInput.hidden = true;
1499
+ fileInput.addEventListener("change", () => {
1500
+ if (fileInput.files) {
1501
+ void this.handleFilesSelected(Array.from(fileInput.files));
1502
+ fileInput.value = "";
1503
+ }
1504
+ });
1505
+ this.fileInputEl = fileInput;
1506
+ composer.appendChild(fileInput);
1507
+
1508
+ const promptShell = document.createElement("div");
1509
+ promptShell.className = "cd-prompt-shell";
1510
+
1511
+ const textarea = document.createElement("textarea");
1512
+ textarea.className = "cd-textarea";
1513
+ textarea.placeholder = this.config.placeholder;
1514
+ textarea.setAttribute("aria-label", "Feedback description");
1515
+ textarea.addEventListener("keydown", (ev) => {
1516
+ if ((ev.metaKey || ev.ctrlKey) && ev.key === "Enter") {
1517
+ ev.preventDefault();
1518
+ void this.handleSubmit();
1519
+ } else if (ev.key === "Escape") {
1520
+ ev.preventDefault();
1521
+ this.closeComposer();
1522
+ }
1523
+ });
1524
+ textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
1525
+ this.textareaEl = textarea;
1526
+ promptShell.appendChild(textarea);
1527
+
1528
+ const toolbar = document.createElement("div");
1529
+ toolbar.className = "cd-toolbar";
1530
+
1531
+ const actions = this.buildPromptToolbarActions(false);
1532
+
1533
+ const submitBtn = document.createElement("button");
1534
+ submitBtn.type = "button";
1535
+ submitBtn.className = "cd-btn cd-btn-primary";
1536
+ submitBtn.setAttribute("aria-label", "Submit feedback");
1537
+ submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
1538
+ submitBtn.addEventListener("click", () => {
1539
+ void this.handleSubmit();
1540
+ });
1541
+ this.submitBtn = submitBtn;
1542
+
1543
+ toolbar.appendChild(actions);
1544
+ toolbar.appendChild(submitBtn);
1545
+ promptShell.appendChild(toolbar);
1546
+ composer.appendChild(promptShell);
1547
+
1548
+ return composer;
1549
+ }
1550
+
1551
+ private buildPromptToolbarActions(forAgentSidebar: boolean = false): HTMLDivElement {
1552
+ const actions = document.createElement("div");
1553
+ actions.className = "cd-toolbar-actions";
1554
+
1555
+ if (this.config.features.element_selection) {
1556
+ const pickBtn = document.createElement("button");
1557
+ pickBtn.type = "button";
1558
+ pickBtn.className = "cd-btn";
1559
+ pickBtn.title = "Freeze & Pin element (⌥⇧P)";
1560
+ pickBtn.setAttribute("aria-label", "Pin HTML element as context (Option+Shift+P)");
1561
+ pickBtn.innerHTML = `${ICON_PIN}<span>Pin</span><kbd class="cd-kbd">⌥⇧P</kbd>`;
1562
+ pickBtn.addEventListener("click", () => this.startPinSelection());
1563
+ if (!forAgentSidebar) {
1564
+ this.composerToolbarPickBtn = pickBtn;
1565
+ }
1566
+ actions.appendChild(pickBtn);
1567
+ }
1568
+
1569
+ if (this.config.features.screenshot_capture) {
1570
+ const screenshotBtn = document.createElement("button");
1571
+ screenshotBtn.type = "button";
1572
+ screenshotBtn.className = "cd-btn";
1573
+ screenshotBtn.setAttribute("aria-label", "Capture viewport screenshot");
1574
+ screenshotBtn.innerHTML = `${ICON_CAMERA}<span>Screenshot</span>`;
1575
+ screenshotBtn.addEventListener("click", () => {
1576
+ void this.handleViewportScreenshot();
1577
+ });
1578
+ if (!forAgentSidebar) {
1579
+ this.composerToolbarScreenshotBtn = screenshotBtn;
1580
+ }
1581
+ actions.appendChild(screenshotBtn);
1582
+ }
1583
+
1584
+ const uploadBtn = document.createElement("button");
1585
+ uploadBtn.type = "button";
1586
+ uploadBtn.className = "cd-btn";
1587
+ uploadBtn.setAttribute("aria-label", "Upload image attachment");
1588
+ uploadBtn.innerHTML = `${ICON_IMAGE}<span>Image</span>`;
1589
+ uploadBtn.addEventListener("click", () => this.fileInputEl?.click());
1590
+ if (!forAgentSidebar) {
1591
+ this.composerToolbarUploadBtn = uploadBtn;
1592
+ }
1593
+ actions.appendChild(uploadBtn);
1594
+
1595
+ return actions;
1596
+ }
1597
+
1598
+ private buildAgentSidebarDom(): HTMLElement {
1599
+ const sidebar = document.createElement("aside");
1600
+ sidebar.className = `cd-agent-sidebar side-${this.sidebarSide}`;
1601
+ sidebar.setAttribute("role", "dialog");
1602
+ sidebar.setAttribute("aria-label", "ContextDrop Local Coding Agent Sidebar");
1603
+ sidebar.style.width = `${this.sidebarWidth}px`;
1604
+ sidebar.hidden = true;
1605
+ this.agentSidebarEl = sidebar;
1606
+
1607
+ sidebar.addEventListener("dragover", (ev) => {
1608
+ ev.preventDefault();
1609
+ sidebar.classList.add("is-dragging-over");
1610
+ });
1611
+ sidebar.addEventListener("dragleave", () => {
1612
+ sidebar.classList.remove("is-dragging-over");
1613
+ });
1614
+ sidebar.addEventListener("drop", (ev) => {
1615
+ ev.preventDefault();
1616
+ sidebar.classList.remove("is-dragging-over");
1617
+ const files = ev.dataTransfer?.files;
1618
+ if (files && files.length > 0) {
1619
+ void this.handleFilesSelected(Array.from(files));
1620
+ }
1621
+ });
1622
+
1623
+ const resizer = document.createElement("div");
1624
+ resizer.className = "cd-sidebar-resizer";
1625
+ resizer.title = "Drag edge to resize sidebar";
1626
+ this.attachSidebarResizer(resizer);
1627
+ sidebar.appendChild(resizer);
1628
+
1629
+ // 1. Sidebar Header
1630
+ const header = document.createElement("div");
1631
+ header.className = "cd-sidebar-header";
1632
+
1633
+ const headerLeft = document.createElement("div");
1634
+ headerLeft.className = "cd-header-left";
1635
+
1636
+ if (this.config.features.element_selection) {
1637
+ const pinBtn = document.createElement("button");
1638
+ pinBtn.type = "button";
1639
+ pinBtn.className = "cd-pin-corner-btn";
1640
+ pinBtn.title = "Freeze & Pin element (⌥⇧P)";
1641
+ pinBtn.setAttribute("aria-label", "Pin DOM element for agent (Option+Shift+P)");
1642
+ pinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>`;
1643
+ pinBtn.addEventListener("click", () => this.startPinSelection());
1644
+ this.sidebarPinBtn = pinBtn;
1645
+ headerLeft.appendChild(pinBtn);
1646
+ }
1647
+
1648
+ const title = document.createElement("h2");
1649
+ title.className = "cd-composer-title";
1650
+ title.textContent = "ContextDrop";
1651
+ headerLeft.appendChild(title);
1652
+
1653
+ const envPill = document.createElement("span");
1654
+ envPill.className = "cd-env-pill is-local";
1655
+ envPill.textContent = this.getShortEnvironmentSlug();
1656
+ this.sidebarEnvPillEl = envPill;
1657
+ headerLeft.appendChild(envPill);
1658
+
1659
+ const headerActions = document.createElement("div");
1660
+ headerActions.className = "cd-header-actions";
1661
+
1662
+ headerActions.appendChild(this.buildModeSwitchDom("agent"));
1663
+
1664
+ const themeBtn = this.buildThemeToggleBtn();
1665
+ this.sidebarThemeToggleBtn = themeBtn;
1666
+ headerActions.appendChild(themeBtn);
1667
+
1668
+ const newThreadBtn = document.createElement("button");
1669
+ newThreadBtn.type = "button";
1670
+ newThreadBtn.className = "cd-icon-btn";
1671
+ newThreadBtn.title = "New agent conversation";
1672
+ newThreadBtn.setAttribute("aria-label", "Start new agent conversation");
1673
+ newThreadBtn.innerHTML = ICON_PLUS;
1674
+ newThreadBtn.addEventListener("click", () => {
1675
+ this.agentMessages = [];
1676
+ this.renderAgentStream();
1677
+ this.agentTextareaEl?.focus();
1678
+ });
1679
+
1680
+ const pushLayoutBtn = document.createElement("button");
1681
+ pushLayoutBtn.type = "button";
1682
+ pushLayoutBtn.className = "cd-icon-btn";
1683
+ pushLayoutBtn.title = "Toggle pushing page layout alongside sidebar";
1684
+ pushLayoutBtn.setAttribute("aria-label", "Toggle push page layout");
1685
+ pushLayoutBtn.innerHTML = ICON_PUSH_LAYOUT;
1686
+ pushLayoutBtn.addEventListener("click", () => {
1687
+ this.pushPageLayout = !this.pushPageLayout;
1688
+ this.syncUiStates();
1689
+ });
1690
+ this.sidebarPushBtn = pushLayoutBtn;
1691
+
1692
+ const flipSideBtn = document.createElement("button");
1693
+ flipSideBtn.type = "button";
1694
+ flipSideBtn.className = "cd-icon-btn";
1695
+ flipSideBtn.title = "Dock sidebar on left or right";
1696
+ flipSideBtn.setAttribute("aria-label", "Switch sidebar dock side");
1697
+ flipSideBtn.innerHTML = ICON_SIDEBAR;
1698
+ flipSideBtn.addEventListener("click", () => {
1699
+ this.sidebarSide = this.sidebarSide === "right" ? "left" : "right";
1700
+ sidebar.className = `cd-agent-sidebar side-${this.sidebarSide}`;
1701
+ this.syncUiStates();
1702
+ });
1703
+
1704
+ const minBtn = document.createElement("button");
1705
+ minBtn.type = "button";
1706
+ minBtn.className = "cd-icon-btn";
1707
+ minBtn.title = "Minimize sidebar";
1708
+ minBtn.setAttribute("aria-label", "Minimize agent sidebar");
1709
+ minBtn.innerHTML = ICON_MINIMIZE;
1710
+ minBtn.addEventListener("click", () => this.minimizeToCompactBar());
1711
+
1712
+ const closeBtn = document.createElement("button");
1713
+ closeBtn.type = "button";
1714
+ closeBtn.className = "cd-icon-btn";
1715
+ closeBtn.title = "Close sidebar (Esc)";
1716
+ closeBtn.setAttribute("aria-label", "Close agent sidebar");
1717
+ closeBtn.innerHTML = ICON_CLOSE;
1718
+ closeBtn.addEventListener("click", () => this.closeComposer());
1719
+
1720
+ headerActions.appendChild(newThreadBtn);
1721
+ headerActions.appendChild(pushLayoutBtn);
1722
+ headerActions.appendChild(flipSideBtn);
1723
+ headerActions.appendChild(minBtn);
1724
+ headerActions.appendChild(closeBtn);
1725
+
1726
+ header.appendChild(headerLeft);
1727
+ header.appendChild(headerActions);
1728
+ sidebar.appendChild(header);
1729
+
1730
+ // 2. Provider + BYOK Vault + Cross-Environment Feedbacks Subbar
1731
+ const subbar = document.createElement("div");
1732
+ subbar.className = "cd-agent-subbar";
1733
+
1734
+ const providerPill = document.createElement("button");
1735
+ providerPill.type = "button";
1736
+ providerPill.className = "cd-provider-pill-btn";
1737
+ providerPill.title = "Configure BYOK provider & model";
1738
+ providerPill.setAttribute("aria-label", "Configure BYOK provider and model");
1739
+ const keyDot = document.createElement("span");
1740
+ keyDot.className = "cd-key-dot";
1741
+ this.keyDotEl = keyDot;
1742
+ const providerLabel = document.createElement("span");
1743
+ providerLabel.className = "cd-provider-pill-label";
1744
+ providerLabel.textContent = "claude-sonnet-4 · BYOK";
1745
+ this.providerPillLabelEl = providerLabel;
1746
+ providerPill.appendChild(keyDot);
1747
+ providerPill.appendChild(providerLabel);
1748
+ providerPill.addEventListener("click", () => this.toggleByokDrawer());
1749
+ this.providerPillBtn = providerPill;
1750
+
1751
+ const subbarRight = document.createElement("div");
1752
+ subbarRight.className = "cd-subbar-right";
1753
+
1754
+ const keysBtn = document.createElement("button");
1755
+ keysBtn.type = "button";
1756
+ keysBtn.className = "cd-btn";
1757
+ keysBtn.setAttribute("aria-label", "Open BYOK API key settings");
1758
+ keysBtn.innerHTML = `${ICON_KEY}<span>BYOK</span>`;
1759
+ keysBtn.addEventListener("click", () => this.toggleByokDrawer());
1760
+ this.keysToggleBtn = keysBtn;
1761
+
1762
+ const feedbacksBtn = document.createElement("button");
1763
+ feedbacksBtn.type = "button";
1764
+ feedbacksBtn.className = "cd-btn";
1765
+ feedbacksBtn.setAttribute("aria-label", "Browse feedbacks across environments");
1766
+ feedbacksBtn.innerHTML = `${ICON_INBOX}<span>Feedbacks</span>`;
1767
+ feedbacksBtn.addEventListener("click", () => this.toggleFeedbacksDrawer());
1768
+ this.feedbacksToggleBtn = feedbacksBtn;
1769
+
1770
+ subbarRight.appendChild(keysBtn);
1771
+ subbarRight.appendChild(feedbacksBtn);
1772
+ subbar.appendChild(providerPill);
1773
+ subbar.appendChild(subbarRight);
1774
+ sidebar.appendChild(subbar);
1775
+
1776
+ // 3. Inline BYOK Vault Drawer
1777
+ sidebar.appendChild(this.buildByokDrawerDom());
1778
+
1779
+ // 4. Inline Cross-Environment Feedbacks Drawer
1780
+ sidebar.appendChild(this.buildFeedbacksDrawerDom());
1781
+
1782
+ // 5. Agent Conversation Stream
1783
+ const stream = document.createElement("div");
1784
+ stream.className = "cd-agent-stream";
1785
+ stream.setAttribute("aria-live", "polite");
1786
+ this.agentStreamEl = stream;
1787
+ sidebar.appendChild(stream);
1788
+ this.renderAgentStream();
1789
+
1790
+ // 6. Shared Context Tray + Status + Prompt Input Shell
1791
+ const agentTray = document.createElement("div");
1792
+ agentTray.className = "cd-tray";
1793
+ agentTray.setAttribute("aria-label", "Pinned DOM context for agent");
1794
+ this.agentTrayEl = agentTray;
1795
+ sidebar.appendChild(agentTray);
1796
+
1797
+ const agentStatus = document.createElement("div");
1798
+ agentStatus.className = "cd-status";
1799
+ agentStatus.setAttribute("role", "status");
1800
+ agentStatus.hidden = true;
1801
+ this.agentStatusEl = agentStatus;
1802
+ sidebar.appendChild(agentStatus);
1803
+
1804
+ const promptShell = document.createElement("div");
1805
+ promptShell.className = "cd-prompt-shell";
1806
+
1807
+ const textarea = document.createElement("textarea");
1808
+ textarea.className = "cd-textarea";
1809
+ textarea.placeholder =
1810
+ "Ask the local agent to inspect pinned DOM elements, read Rails views, or propose a fix...";
1811
+ textarea.setAttribute("aria-label", "Agent prompt");
1812
+ textarea.addEventListener("keydown", (ev) => {
1813
+ if ((ev.metaKey || ev.ctrlKey) && ev.key === "Enter") {
1814
+ ev.preventDefault();
1815
+ void this.handleAgentSubmit();
1816
+ } else if (ev.key === "Escape") {
1817
+ ev.preventDefault();
1818
+ this.closeComposer();
1819
+ }
1820
+ });
1821
+ textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
1822
+ this.agentTextareaEl = textarea;
1823
+ promptShell.appendChild(textarea);
1824
+
1825
+ const toolbar = document.createElement("div");
1826
+ toolbar.className = "cd-toolbar";
1827
+ toolbar.appendChild(this.buildPromptToolbarActions(true));
1828
+
1829
+ const sendBtn = document.createElement("button");
1830
+ sendBtn.type = "button";
1831
+ sendBtn.className = "cd-btn cd-btn-primary";
1832
+ sendBtn.setAttribute("aria-label", "Send prompt to local agent");
1833
+ sendBtn.innerHTML = `${ICON_SEND}<span>Ask Agent</span>`;
1834
+ sendBtn.addEventListener("click", () => {
1835
+ void this.handleAgentSubmit();
1836
+ });
1837
+ this.agentSendBtn = sendBtn;
1838
+
1839
+ toolbar.appendChild(sendBtn);
1840
+ promptShell.appendChild(toolbar);
1841
+ sidebar.appendChild(promptShell);
1842
+
1843
+ this.syncProviderControls();
1844
+ return sidebar;
1845
+ }
1846
+
1847
+ private buildByokDrawerDom(): HTMLDivElement {
1848
+ const drawer = document.createElement("div");
1849
+ drawer.className = "cd-inline-drawer cd-byok-drawer";
1850
+ drawer.hidden = true;
1851
+ this.byokDrawerEl = drawer;
1852
+
1853
+ const securityNote = document.createElement("div");
1854
+ securityNote.className = "cd-vault-security-note";
1855
+ securityNote.innerHTML = `${ICON_SHIELD}<span>Keys stay encrypted on disk in <code>tmp/context_drop_byok.enc</code> (AES-256-GCM) or read from server ENV—never stored in browser storage.</span>`;
1856
+ drawer.appendChild(securityNote);
1857
+
1858
+ const grid = document.createElement("div");
1859
+ grid.className = "cd-form-grid";
1860
+
1861
+ // Provider field
1862
+ const provField = document.createElement("div");
1863
+ provField.className = "cd-field";
1864
+ const provLabel = document.createElement("label");
1865
+ provLabel.className = "cd-field-label";
1866
+ provLabel.textContent = "Provider";
1867
+ const provSelect = document.createElement("select");
1868
+ provSelect.className = "cd-select";
1869
+ provSelect.setAttribute("aria-label", "LLM Provider");
1870
+ provSelect.addEventListener("change", () => {
1871
+ this.selectedVaultProviderId = provSelect.value;
1872
+ this.syncByokDrawerFields();
1873
+ });
1874
+ this.byokProviderSelect = provSelect;
1875
+ provField.appendChild(provLabel);
1876
+ provField.appendChild(provSelect);
1877
+ grid.appendChild(provField);
1878
+
1879
+ // Preset model picker
1880
+ const presetField = document.createElement("div");
1881
+ presetField.className = "cd-field";
1882
+ const presetLabel = document.createElement("label");
1883
+ presetLabel.className = "cd-field-label";
1884
+ presetLabel.textContent = "Preset";
1885
+ const presetSelect = document.createElement("select");
1886
+ presetSelect.className = "cd-select";
1887
+ presetSelect.setAttribute("aria-label", "Model preset");
1888
+ presetSelect.addEventListener("change", () => {
1889
+ if (this.byokModelInput && presetSelect.value) {
1890
+ this.byokModelInput.value = presetSelect.value;
1891
+ }
1892
+ });
1893
+ this.byokModelPresetsSelect = presetSelect;
1894
+ presetField.appendChild(presetLabel);
1895
+ presetField.appendChild(presetSelect);
1896
+ grid.appendChild(presetField);
1897
+
1898
+ // Editable model ID
1899
+ const modelField = document.createElement("div");
1900
+ modelField.className = "cd-field is-full";
1901
+ const modelLabel = document.createElement("label");
1902
+ modelLabel.className = "cd-field-label";
1903
+ modelLabel.textContent = "Model ID";
1904
+ const modelInput = document.createElement("input");
1905
+ modelInput.type = "text";
1906
+ modelInput.className = "cd-input is-mono";
1907
+ modelInput.setAttribute("aria-label", "Model identifier");
1908
+ this.byokModelInput = modelInput;
1909
+ modelField.appendChild(modelLabel);
1910
+ modelField.appendChild(modelInput);
1911
+ grid.appendChild(modelField);
1912
+
1913
+ // Optional Base URL field (for custom OpenAI-compatible provider)
1914
+ const baseUrlField = document.createElement("div");
1915
+ baseUrlField.className = "cd-field is-full";
1916
+ baseUrlField.hidden = true;
1917
+ const baseUrlLabel = document.createElement("label");
1918
+ baseUrlLabel.className = "cd-field-label";
1919
+ baseUrlLabel.textContent = "OpenAI-Compatible Base URL";
1920
+ const baseUrlInput = document.createElement("input");
1921
+ baseUrlInput.type = "url";
1922
+ baseUrlInput.className = "cd-input is-mono";
1923
+ baseUrlInput.placeholder = "https://openrouter.ai/api/v1 or http://localhost:11434/v1";
1924
+ baseUrlInput.setAttribute("aria-label", "Custom OpenAI-compatible Base URL");
1925
+ this.byokBaseUrlInput = baseUrlInput;
1926
+ baseUrlField.appendChild(baseUrlLabel);
1927
+ baseUrlField.appendChild(baseUrlInput);
1928
+ this.byokBaseUrlField = baseUrlField;
1929
+ grid.appendChild(baseUrlField);
1930
+
1931
+ // API Key field
1932
+ const keyField = document.createElement("div");
1933
+ keyField.className = "cd-field is-full";
1934
+ const keyLabel = document.createElement("label");
1935
+ keyLabel.className = "cd-field-label";
1936
+ const keyLabelText = document.createElement("span");
1937
+ keyLabelText.textContent = "API Key";
1938
+ const keyBadge = document.createElement("span");
1939
+ keyBadge.className = "cd-key-source-badge";
1940
+ keyBadge.hidden = true;
1941
+ this.byokKeySourceBadge = keyBadge;
1942
+ keyLabel.appendChild(keyLabelText);
1943
+ keyLabel.appendChild(keyBadge);
1944
+
1945
+ const keyInput = document.createElement("input");
1946
+ keyInput.type = "password";
1947
+ keyInput.autocomplete = "off";
1948
+ keyInput.className = "cd-input is-mono";
1949
+ keyInput.placeholder = "Paste API key (leave blank to keep existing key)";
1950
+ keyInput.setAttribute("aria-label", "Provider API Key");
1951
+ this.byokKeyInput = keyInput;
1952
+ keyField.appendChild(keyLabel);
1953
+ keyField.appendChild(keyInput);
1954
+ grid.appendChild(keyField);
1955
+
1956
+ drawer.appendChild(grid);
1957
+
1958
+ const actions = document.createElement("div");
1959
+ actions.className = "cd-drawer-actions";
1960
+
1961
+ const clearBtn = document.createElement("button");
1962
+ clearBtn.type = "button";
1963
+ clearBtn.className = "cd-btn cd-btn-danger-outline";
1964
+ clearBtn.textContent = "Clear Vault Key";
1965
+ clearBtn.addEventListener("click", () => {
1966
+ void this.handleClearByokKey();
1967
+ });
1968
+
1969
+ const rightGroup = document.createElement("div");
1970
+ rightGroup.className = "cd-diff-btn-group";
1971
+
1972
+ const closeBtn = document.createElement("button");
1973
+ closeBtn.type = "button";
1974
+ closeBtn.className = "cd-btn";
1975
+ closeBtn.textContent = "Close";
1976
+ closeBtn.addEventListener("click", () => {
1977
+ this.isByokDrawerOpen = false;
1978
+ this.syncUiStates();
1979
+ });
1980
+
1981
+ const saveBtn = document.createElement("button");
1982
+ saveBtn.type = "button";
1983
+ saveBtn.className = "cd-btn cd-btn-primary";
1984
+ saveBtn.textContent = "Use & Save";
1985
+ saveBtn.addEventListener("click", () => {
1986
+ void this.handleSaveByokSettings();
1987
+ });
1988
+
1989
+ rightGroup.appendChild(closeBtn);
1990
+ rightGroup.appendChild(saveBtn);
1991
+ actions.appendChild(clearBtn);
1992
+ actions.appendChild(rightGroup);
1993
+ drawer.appendChild(actions);
1994
+
1995
+ return drawer;
1996
+ }
1997
+
1998
+ private buildFeedbacksDrawerDom(): HTMLDivElement {
1999
+ const drawer = document.createElement("div");
2000
+ drawer.className = "cd-inline-drawer cd-feedbacks-drawer";
2001
+ drawer.hidden = true;
2002
+ this.feedbacksDrawerEl = drawer;
2003
+
2004
+ const filterRow = document.createElement("div");
2005
+ filterRow.className = "cd-env-filter-row";
2006
+
2007
+ const tabs = document.createElement("div");
2008
+ tabs.className = "cd-env-tabs";
2009
+ this.feedbacksTabsEl = tabs;
2010
+ filterRow.appendChild(tabs);
2011
+
2012
+ const refreshBtn = document.createElement("button");
2013
+ refreshBtn.type = "button";
2014
+ refreshBtn.className = "cd-btn";
2015
+ refreshBtn.textContent = "Refresh";
2016
+ refreshBtn.addEventListener("click", () => {
2017
+ void this.loadCrossEnvFeedbacks(this.feedbacksEnvFilter);
2018
+ });
2019
+ filterRow.appendChild(refreshBtn);
2020
+ drawer.appendChild(filterRow);
2021
+
2022
+ const list = document.createElement("div");
2023
+ list.className = "cd-feedbacks-list";
2024
+ this.feedbacksListEl = list;
2025
+ drawer.appendChild(list);
2026
+
2027
+ return drawer;
2028
+ }
2029
+
2030
+ private getShortEnvironmentSlug(): string {
2031
+ const raw = (this.config.environment || "development").toLowerCase();
2032
+ if (raw === "development") return "dev";
2033
+ if (raw === "production") return "prod";
2034
+ return raw;
2035
+ }
2036
+
2037
+ private toggleByokDrawer(): void {
2038
+ this.isByokDrawerOpen = !this.isByokDrawerOpen;
2039
+ if (this.isByokDrawerOpen) {
2040
+ this.isFeedbacksDrawerOpen = false;
2041
+ this.selectedVaultProviderId = this.activeProviderId;
2042
+ this.syncProviderControls();
2043
+ }
2044
+ this.syncUiStates();
2045
+ }
2046
+
2047
+ private toggleFeedbacksDrawer(): void {
2048
+ this.isFeedbacksDrawerOpen = !this.isFeedbacksDrawerOpen;
2049
+ if (this.isFeedbacksDrawerOpen) {
2050
+ this.isByokDrawerOpen = false;
2051
+ void this.loadCrossEnvFeedbacks(this.feedbacksEnvFilter);
2052
+ }
2053
+ this.syncUiStates();
2054
+ }
2055
+
2056
+ private async ensureAgentStatusLoaded(): Promise<void> {
2057
+ if (this.agentStatusLoaded) return;
2058
+ try {
2059
+ const status: AgentStatusResponse = await this.apiClient.fetchAgentStatus();
2060
+ this.agentStatusLoaded = true;
2061
+ this.agentWorkspaceName = status.workspace_name || this.agentWorkspaceName;
2062
+ if (Array.isArray(status.mcp_environments) && status.mcp_environments.length > 0) {
2063
+ this.agentMcpEnvironments = status.mcp_environments.map((e) => e.name);
2064
+ }
2065
+ if (Array.isArray(status.providers) && status.providers.length > 0) {
2066
+ this.agentProviders = status.providers;
2067
+ }
2068
+ if (status.active_provider) {
2069
+ this.activeProviderId = status.active_provider;
2070
+ this.selectedVaultProviderId = status.active_provider;
2071
+ }
2072
+ this.syncProviderControls();
2073
+ this.renderAgentStream();
2074
+ } catch {
2075
+ // Keep fallback provider definitions if offline
2076
+ }
2077
+ }
2078
+
2079
+ private getActiveProviderInfo(): AgentProviderInfo {
2080
+ return (
2081
+ this.agentProviders.find((p) => p.id === this.activeProviderId) ||
2082
+ this.agentProviders[0] ||
2083
+ DEFAULT_PROVIDERS_FALLBACK[0]
2084
+ );
2085
+ }
2086
+
2087
+ private syncProviderControls(): void {
2088
+ const active = this.getActiveProviderInfo();
2089
+ if (this.keyDotEl) {
2090
+ this.keyDotEl.classList.toggle("is-ready", Boolean(active.configured));
2091
+ }
2092
+ if (this.providerPillLabelEl) {
2093
+ const sourceTag =
2094
+ active.source === "env"
2095
+ ? "ENV"
2096
+ : active.source === "vault"
2097
+ ? "Vault"
2098
+ : active.source === "local_no_key"
2099
+ ? "Local"
2100
+ : "Set BYOK";
2101
+ this.providerPillLabelEl.textContent = `${active.model} · ${sourceTag}`;
2102
+ }
2103
+
2104
+ if (this.byokProviderSelect) {
2105
+ this.byokProviderSelect.innerHTML = "";
2106
+ for (const prov of this.agentProviders) {
2107
+ const opt = document.createElement("option");
2108
+ opt.value = prov.id;
2109
+ opt.textContent = prov.configured ? `${prov.label} (Ready)` : prov.label;
2110
+ if (prov.id === this.selectedVaultProviderId) {
2111
+ opt.selected = true;
2112
+ }
2113
+ this.byokProviderSelect.appendChild(opt);
2114
+ }
2115
+ this.byokProviderSelect.value = this.selectedVaultProviderId;
2116
+ }
2117
+
2118
+ this.syncByokDrawerFields();
2119
+ }
2120
+
2121
+ private syncByokDrawerFields(): void {
2122
+ const selected =
2123
+ this.agentProviders.find((p) => p.id === this.selectedVaultProviderId) ||
2124
+ this.getActiveProviderInfo();
2125
+
2126
+ if (this.byokModelPresetsSelect) {
2127
+ this.byokModelPresetsSelect.innerHTML = "";
2128
+ for (const modelName of selected.models || [selected.default_model]) {
2129
+ const opt = document.createElement("option");
2130
+ opt.value = modelName;
2131
+ opt.textContent = modelName;
2132
+ if (modelName === selected.model) {
2133
+ opt.selected = true;
2134
+ }
2135
+ this.byokModelPresetsSelect.appendChild(opt);
2136
+ }
2137
+ }
2138
+
2139
+ if (this.byokModelInput) {
2140
+ this.byokModelInput.value = selected.model || selected.default_model;
2141
+ }
2142
+
2143
+ if (this.byokBaseUrlField && this.byokBaseUrlInput) {
2144
+ this.byokBaseUrlField.hidden = !selected.supports_base_url;
2145
+ this.byokBaseUrlInput.value = selected.base_url || "";
2146
+ }
2147
+
2148
+ if (this.byokKeySourceBadge) {
2149
+ if (selected.configured) {
2150
+ this.byokKeySourceBadge.hidden = false;
2151
+ const src =
2152
+ selected.source === "env"
2153
+ ? `ENV ${selected.env_var_hint}`
2154
+ : selected.source === "vault"
2155
+ ? "Vault"
2156
+ : "Local URL";
2157
+ this.byokKeySourceBadge.textContent = selected.masked_key
2158
+ ? `${src} (${selected.masked_key})`
2159
+ : src;
2160
+ } else {
2161
+ this.byokKeySourceBadge.hidden = true;
2162
+ }
2163
+ }
2164
+
2165
+ if (this.byokKeyInput) {
2166
+ this.byokKeyInput.value = "";
2167
+ this.byokKeyInput.placeholder = selected.configured
2168
+ ? "Leave blank to keep configured key, or paste to override"
2169
+ : `Paste key or export ${selected.env_var_hint}`;
2170
+ }
2171
+ }
2172
+
2173
+ private async handleSaveByokSettings(): Promise<void> {
2174
+ const provider = this.byokProviderSelect?.value || this.selectedVaultProviderId;
2175
+ const model = (this.byokModelInput?.value || "").trim();
2176
+ const rawKey = (this.byokKeyInput?.value || "").trim();
2177
+ const baseUrl = (this.byokBaseUrlInput?.value || "").trim();
2178
+
2179
+ try {
2180
+ const payload: {
2181
+ provider: string;
2182
+ model?: string;
2183
+ api_key?: string;
2184
+ base_url?: string;
2185
+ make_active: boolean;
2186
+ } = {
2187
+ provider,
2188
+ model: model || undefined,
2189
+ make_active: true
2190
+ };
2191
+ if (rawKey.length > 0) {
2192
+ payload.api_key = rawKey;
2193
+ }
2194
+ if (provider === "custom") {
2195
+ payload.base_url = baseUrl;
2196
+ }
2197
+
2198
+ const updated = await this.apiClient.saveAgentKeys(payload);
2199
+ if (this.byokKeyInput) {
2200
+ this.byokKeyInput.value = "";
2201
+ }
2202
+ this.activeProviderId = updated.active_provider || provider;
2203
+ this.selectedVaultProviderId = this.activeProviderId;
2204
+ if (Array.isArray(updated.providers)) {
2205
+ this.agentProviders = updated.providers;
2206
+ }
2207
+ this.isByokDrawerOpen = false;
2208
+ this.syncProviderControls();
2209
+ this.syncUiStates();
2210
+ this.showStatus("Saved provider settings in local encrypted vault.", "success");
2211
+ } catch (err) {
2212
+ const msg = err instanceof Error ? err.message : "Failed to save BYOK settings.";
2213
+ this.showStatus(msg, "error");
2214
+ }
2215
+ }
2216
+
2217
+ private async handleClearByokKey(): Promise<void> {
2218
+ const provider = this.byokProviderSelect?.value || this.selectedVaultProviderId;
2219
+ try {
2220
+ const updated = await this.apiClient.deleteAgentKeys(provider);
2221
+ if (this.byokKeyInput) {
2222
+ this.byokKeyInput.value = "";
2223
+ }
2224
+ if (Array.isArray(updated.providers)) {
2225
+ this.agentProviders = updated.providers;
2226
+ }
2227
+ this.activeProviderId = updated.active_provider || this.activeProviderId;
2228
+ this.syncProviderControls();
2229
+ this.showStatus(`Cleared stored vault key for ${provider}.`, "success");
2230
+ } catch (err) {
2231
+ const msg = err instanceof Error ? err.message : "Failed to clear key.";
2232
+ this.showStatus(msg, "error");
2233
+ }
2234
+ }
2235
+
2236
+ private async loadCrossEnvFeedbacks(environment: string): Promise<void> {
2237
+ this.feedbacksEnvFilter = environment;
2238
+ this.isLoadingFeedbacks = true;
2239
+ this.renderFeedbacksDrawerContent();
2240
+
2241
+ try {
2242
+ const res = await this.apiClient.fetchAgentFeedbacks(environment, "new");
2243
+ this.crossEnvFeedbacks = Array.isArray(res.feedbacks) ? res.feedbacks : [];
2244
+ if (Array.isArray(res.environments_queried) && res.environments_queried.length > 0) {
2245
+ for (const envName of res.environments_queried) {
2246
+ if (!this.agentMcpEnvironments.includes(envName)) {
2247
+ this.agentMcpEnvironments.push(envName);
2248
+ }
2249
+ }
2250
+ }
2251
+ } catch (err) {
2252
+ const msg = err instanceof Error ? err.message : "Failed to query feedbacks.";
2253
+ this.showStatus(msg, "error");
2254
+ } finally {
2255
+ this.isLoadingFeedbacks = false;
2256
+ this.renderFeedbacksDrawerContent();
2257
+ }
2258
+ }
2259
+
2260
+ private renderFeedbacksDrawerContent(): void {
2261
+ if (this.feedbacksTabsEl) {
2262
+ this.feedbacksTabsEl.innerHTML = "";
2263
+ const envOptions = ["all", ...this.agentMcpEnvironments];
2264
+ for (const envName of envOptions) {
2265
+ const tab = document.createElement("button");
2266
+ tab.type = "button";
2267
+ tab.className = `cd-env-tab${this.feedbacksEnvFilter === envName ? " is-active" : ""}`;
2268
+ tab.textContent = envName;
2269
+ tab.addEventListener("click", () => {
2270
+ void this.loadCrossEnvFeedbacks(envName);
2271
+ });
2272
+ this.feedbacksTabsEl.appendChild(tab);
2273
+ }
2274
+ }
2275
+
2276
+ if (!this.feedbacksListEl) return;
2277
+ this.feedbacksListEl.innerHTML = "";
2278
+
2279
+ if (this.isLoadingFeedbacks) {
2280
+ const loading = document.createElement("div");
2281
+ loading.className = "cd-chat-empty-hint";
2282
+ loading.textContent = "Querying connected MCP environments...";
2283
+ this.feedbacksListEl.appendChild(loading);
2284
+ return;
2285
+ }
2286
+
2287
+ if (this.crossEnvFeedbacks.length === 0) {
2288
+ const empty = document.createElement("div");
2289
+ empty.className = "cd-chat-empty-hint";
2290
+ empty.textContent = `No open feedbacks found in ${this.feedbacksEnvFilter}.`;
2291
+ this.feedbacksListEl.appendChild(empty);
2292
+ return;
2293
+ }
2294
+
2295
+ for (const item of this.crossEnvFeedbacks) {
2296
+ const row = document.createElement("div");
2297
+ row.className = "cd-feedback-row";
2298
+
2299
+ const top = document.createElement("div");
2300
+ top.className = "cd-feedback-row-top";
2301
+
2302
+ const idBadge = document.createElement("span");
2303
+ idBadge.className = "cd-feedback-row-id";
2304
+ const qid = item.qualified_id || `${item.environment}:${item.id}`;
2305
+ idBadge.textContent = item.primary_selector ? `${qid} · ${item.primary_selector}` : qid;
2306
+
2307
+ const investigateBtn = document.createElement("button");
2308
+ investigateBtn.type = "button";
2309
+ investigateBtn.className = "cd-btn";
2310
+ investigateBtn.textContent = "Investigate";
2311
+ investigateBtn.addEventListener("click", () => {
2312
+ const prompt = `Investigate feedback ${qid} ("${item.message}")${item.primary_selector ? ` targeting \`${item.primary_selector}\`` : ""} and propose a fix if needed.`;
2313
+ if (this.agentTextareaEl) {
2314
+ this.agentTextareaEl.value = prompt;
2315
+ this.agentTextareaEl.focus();
2316
+ }
2317
+ this.isFeedbacksDrawerOpen = false;
2318
+ this.syncUiStates();
2319
+ });
2320
+
2321
+ top.appendChild(idBadge);
2322
+ top.appendChild(investigateBtn);
2323
+
2324
+ const msgP = document.createElement("p");
2325
+ msgP.className = "cd-feedback-row-msg";
2326
+ msgP.textContent = item.message || "(Context drop without text)";
2327
+
2328
+ row.appendChild(top);
2329
+ row.appendChild(msgP);
2330
+ this.feedbacksListEl.appendChild(row);
2331
+ }
2332
+ }
2333
+
2334
+ private renderAgentStream(): void {
2335
+ if (!this.agentStreamEl) return;
2336
+ this.agentStreamEl.innerHTML = "";
2337
+
2338
+ if (this.agentMessages.length === 0 && !this.isAgentBusy) {
2339
+ const empty = document.createElement("div");
2340
+ empty.className = "cd-agent-empty";
2341
+
2342
+ const title = document.createElement("p");
2343
+ title.className = "cd-agent-empty-title";
2344
+ title.textContent = `Inspect & edit ${this.agentWorkspaceName} from the live DOM.`;
2345
+
2346
+ const desc = document.createElement("p");
2347
+ desc.className = "cd-agent-empty-desc";
2348
+ desc.textContent = `Connected MCP environments: ${this.agentMcpEnvironments.join(", ")}. File edits always stage an inline diff for your approval.`;
2349
+
2350
+ const starters = document.createElement("div");
2351
+ starters.className = "cd-starter-list";
2352
+
2353
+ const starterItems: Array<{ label: string; action: () => void }> = [
2354
+ {
2355
+ label: "Pin an element on this page & find its Rails template",
2356
+ action: () => {
2357
+ if (this.elementReferences.length === 0) {
2358
+ this.startPinSelection();
2359
+ } else if (this.agentTextareaEl) {
2360
+ this.agentTextareaEl.value =
2361
+ "Locate the Rails view/partial rendering the pinned element and explain how it is styled.";
2362
+ void this.handleAgentSubmit();
2363
+ }
2364
+ }
2365
+ },
2366
+ {
2367
+ label: "Triage open feedbacks across all environments",
2368
+ action: () => {
2369
+ if (this.agentTextareaEl) {
2370
+ this.agentTextareaEl.value =
2371
+ "List open ContextDrop feedbacks across all environments and summarize the highest-priority UI issues.";
2372
+ void this.handleAgentSubmit();
2373
+ }
2374
+ }
2375
+ },
2376
+ {
2377
+ label: "Inspect pinned element spacing & propose a clean CSS/ERB fix",
2378
+ action: () => {
2379
+ if (this.agentTextareaEl) {
2380
+ this.agentTextareaEl.value =
2381
+ "Inspect the pinned element in the workspace and stage a proposed file edit to polish its layout and accessibility.";
2382
+ this.agentTextareaEl.focus();
2383
+ }
2384
+ }
2385
+ }
2386
+ ];
2387
+
2388
+ for (const item of starterItems) {
2389
+ const btn = document.createElement("button");
2390
+ btn.type = "button";
2391
+ btn.className = "cd-starter-btn";
2392
+ const span = document.createElement("span");
2393
+ span.textContent = item.label;
2394
+ const arrow = document.createElement("span");
2395
+ arrow.innerHTML = ICON_CHEVRON_RIGHT;
2396
+ btn.appendChild(span);
2397
+ btn.appendChild(arrow);
2398
+ btn.addEventListener("click", item.action);
2399
+ starters.appendChild(btn);
2400
+ }
2401
+
2402
+ empty.appendChild(title);
2403
+ empty.appendChild(desc);
2404
+ empty.appendChild(starters);
2405
+ this.agentStreamEl.appendChild(empty);
2406
+ return;
2407
+ }
2408
+
2409
+ for (const msg of this.agentMessages) {
2410
+ const card = document.createElement("div");
2411
+ card.className = `cd-agent-msg is-${msg.role}`;
2412
+
2413
+ if (msg.role === "user") {
2414
+ if ((msg.elements && msg.elements.length > 0) || (msg.attachments && msg.attachments.length > 0)) {
2415
+ const pills = document.createElement("div");
2416
+ pills.className = "cd-chat-msg-pills";
2417
+ for (const el of msg.elements || []) {
2418
+ const pill = document.createElement("span");
2419
+ pill.className = "cd-chat-msg-pill";
2420
+ pill.textContent = el.selector;
2421
+ pills.appendChild(pill);
2422
+ }
2423
+ for (const att of msg.attachments || []) {
2424
+ const pill = document.createElement("span");
2425
+ pill.className = "cd-chat-msg-pill";
2426
+ pill.textContent = att.label;
2427
+ pills.appendChild(pill);
2428
+ }
2429
+ card.appendChild(pills);
2430
+ }
2431
+
2432
+ const textP = document.createElement("p");
2433
+ textP.className = "cd-chat-msg-text";
2434
+ textP.textContent = msg.content;
2435
+ card.appendChild(textP);
2436
+ } else {
2437
+ if (msg.toolCalls && msg.toolCalls.length > 0) {
2438
+ const traces = document.createElement("div");
2439
+ traces.className = "cd-tool-traces";
2440
+ for (const trace of msg.toolCalls) {
2441
+ const row = document.createElement("div");
2442
+ row.className = `cd-tool-trace${trace.status === "error" ? " is-error" : ""}`;
2443
+ const badge = document.createElement("span");
2444
+ badge.className = "cd-tool-trace-badge";
2445
+ badge.textContent = trace.name;
2446
+ const summary = document.createElement("span");
2447
+ summary.className = "cd-tool-trace-summary";
2448
+ summary.textContent = trace.summary;
2449
+ row.appendChild(badge);
2450
+ row.appendChild(summary);
2451
+ traces.appendChild(row);
2452
+ }
2453
+ card.appendChild(traces);
2454
+ }
626
2455
 
627
- // Status message bar
628
- const status = document.createElement("div");
629
- status.className = "cd-status";
630
- status.setAttribute("role", "status");
631
- status.hidden = true;
632
- this.statusEl = status;
633
- composer.appendChild(status);
2456
+ if (msg.content) {
2457
+ const mdBody = document.createElement("div");
2458
+ mdBody.className = "cd-md-body";
2459
+ mdBody.innerHTML = renderSafeMarkdown(msg.content);
2460
+ card.appendChild(mdBody);
2461
+ }
634
2462
 
635
- // Hidden file input
636
- const fileInput = document.createElement("input");
637
- fileInput.type = "file";
638
- fileInput.multiple = true;
639
- fileInput.accept = this.config.limits.allowed_content_types.join(",");
640
- fileInput.hidden = true;
641
- fileInput.addEventListener("change", () => {
642
- if (fileInput.files) {
643
- void this.handleFilesSelected(Array.from(fileInput.files));
644
- fileInput.value = "";
2463
+ if (msg.proposedEdits && msg.proposedEdits.length > 0) {
2464
+ for (const edit of msg.proposedEdits) {
2465
+ card.appendChild(this.buildDiffCardDom(edit));
2466
+ }
2467
+ }
645
2468
  }
646
- });
647
- this.fileInputEl = fileInput;
648
- composer.appendChild(fileInput);
649
2469
 
650
- // Chatbox Prompt Input Shell
651
- const promptShell = document.createElement("div");
652
- promptShell.className = "cd-prompt-shell";
2470
+ this.agentStreamEl.appendChild(card);
2471
+ }
653
2472
 
654
- const textarea = document.createElement("textarea");
655
- textarea.className = "cd-textarea";
656
- textarea.placeholder = this.config.placeholder;
657
- textarea.setAttribute("aria-label", "Feedback description");
658
- textarea.addEventListener("keydown", (ev) => {
659
- if ((ev.metaKey || ev.ctrlKey) && ev.key === "Enter") {
660
- ev.preventDefault();
661
- void this.handleSubmit();
662
- } else if (ev.key === "Escape") {
663
- ev.preventDefault();
664
- this.closeComposer();
665
- }
666
- });
667
- textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
668
- this.textareaEl = textarea;
669
- promptShell.appendChild(textarea);
2473
+ if (this.isAgentBusy) {
2474
+ const thinking = document.createElement("div");
2475
+ thinking.className = "cd-agent-thinking";
2476
+ const lbl = document.createElement("span");
2477
+ lbl.className = "cd-thinking-label";
2478
+ lbl.textContent = "Inspecting workspace & DOM context...";
2479
+ const b1 = document.createElement("div");
2480
+ b1.className = "cd-skeleton-bar";
2481
+ const b2 = document.createElement("div");
2482
+ b2.className = "cd-skeleton-bar is-short";
2483
+ thinking.appendChild(lbl);
2484
+ thinking.appendChild(b1);
2485
+ thinking.appendChild(b2);
2486
+ this.agentStreamEl.appendChild(thinking);
2487
+ }
670
2488
 
671
- // Toolbar inside prompt shell
672
- const toolbar = document.createElement("div");
673
- toolbar.className = "cd-toolbar";
2489
+ this.agentStreamEl.scrollTop = this.agentStreamEl.scrollHeight;
2490
+ }
674
2491
 
675
- const actions = document.createElement("div");
676
- actions.className = "cd-toolbar-actions";
2492
+ private buildDiffCardDom(edit: ProposedFileEdit): HTMLDivElement {
2493
+ const card = document.createElement("div");
2494
+ card.className = "cd-diff-card";
2495
+ card.setAttribute("data-edit-id", edit.id);
677
2496
 
678
- if (this.config.features.element_selection) {
679
- const pickBtn = document.createElement("button");
680
- pickBtn.type = "button";
681
- pickBtn.className = "cd-btn";
682
- pickBtn.title = "Freeze & Pin element (⌥⇧P)";
683
- pickBtn.setAttribute("aria-label", "Pin HTML element as context (Option+Shift+P)");
684
- pickBtn.innerHTML = `${ICON_PIN}<span>Pin</span><kbd class="cd-kbd">⌥⇧P</kbd>`;
685
- pickBtn.addEventListener("click", () => this.startPinSelection());
686
- actions.appendChild(pickBtn);
2497
+ const header = document.createElement("div");
2498
+ header.className = "cd-diff-card-header";
2499
+
2500
+ const pathGroup = document.createElement("div");
2501
+ pathGroup.className = "cd-diff-path-group";
2502
+ const iconSpan = document.createElement("span");
2503
+ iconSpan.innerHTML = ICON_FILE_CODE;
2504
+ const pathSpan = document.createElement("span");
2505
+ pathSpan.className = "cd-diff-path";
2506
+ pathSpan.textContent = edit.path;
2507
+ pathSpan.title = edit.path;
2508
+ pathGroup.appendChild(iconSpan);
2509
+ pathGroup.appendChild(pathSpan);
2510
+
2511
+ const stats = document.createElement("div");
2512
+ stats.className = "cd-diff-stats";
2513
+ const addSpan = document.createElement("span");
2514
+ addSpan.className = "cd-diff-stat-add";
2515
+ addSpan.textContent = `+${edit.added_lines}`;
2516
+ const delSpan = document.createElement("span");
2517
+ delSpan.className = "cd-diff-stat-del";
2518
+ delSpan.textContent = `-${edit.removed_lines}`;
2519
+ stats.appendChild(addSpan);
2520
+ stats.appendChild(delSpan);
2521
+
2522
+ header.appendChild(pathGroup);
2523
+ header.appendChild(stats);
2524
+ card.appendChild(header);
2525
+
2526
+ if (edit.summary) {
2527
+ const summary = document.createElement("div");
2528
+ summary.className = "cd-diff-summary";
2529
+ summary.textContent = edit.summary;
2530
+ card.appendChild(summary);
687
2531
  }
688
2532
 
689
- if (this.config.features.screenshot_capture) {
690
- const screenshotBtn = document.createElement("button");
691
- screenshotBtn.type = "button";
692
- screenshotBtn.className = "cd-btn";
693
- screenshotBtn.setAttribute("aria-label", "Capture viewport screenshot");
694
- screenshotBtn.innerHTML = `${ICON_CAMERA}<span>Screenshot</span>`;
695
- screenshotBtn.addEventListener("click", () => {
696
- void this.handleViewportScreenshot();
697
- });
698
- actions.appendChild(screenshotBtn);
2533
+ card.appendChild(buildUnifiedDiffElement(document, edit.diff));
2534
+
2535
+ const footer = document.createElement("div");
2536
+ footer.className = "cd-diff-footer";
2537
+
2538
+ const statusPill = document.createElement("span");
2539
+ statusPill.className = `cd-diff-status-pill${edit.status === "applied" ? " is-applied" : edit.status === "rejected" ? " is-rejected" : ""}`;
2540
+ if (edit.status === "applied") {
2541
+ statusPill.innerHTML = `${ICON_CHECK}<span>Applied to workspace</span>`;
2542
+ } else if (edit.status === "rejected") {
2543
+ statusPill.textContent = "Rejected";
2544
+ } else if (edit.status === "reverted") {
2545
+ statusPill.textContent = "Reverted";
2546
+ } else {
2547
+ statusPill.textContent = "Staged · Awaiting approval";
699
2548
  }
2549
+ footer.appendChild(statusPill);
2550
+
2551
+ const btnGroup = document.createElement("div");
2552
+ btnGroup.className = "cd-diff-btn-group";
2553
+
2554
+ if (edit.status === "pending") {
2555
+ const rejectBtn = document.createElement("button");
2556
+ rejectBtn.type = "button";
2557
+ rejectBtn.className = "cd-btn";
2558
+ rejectBtn.textContent = "Reject";
2559
+ rejectBtn.addEventListener("click", () => {
2560
+ void this.handleEditDecision(edit, "reject");
2561
+ });
700
2562
 
701
- const uploadBtn = document.createElement("button");
702
- uploadBtn.type = "button";
703
- uploadBtn.className = "cd-btn";
704
- uploadBtn.setAttribute("aria-label", "Upload image attachment");
705
- uploadBtn.innerHTML = `${ICON_IMAGE}<span>Image</span>`;
706
- uploadBtn.addEventListener("click", () => this.fileInputEl?.click());
707
- actions.appendChild(uploadBtn);
2563
+ const applyBtn = document.createElement("button");
2564
+ applyBtn.type = "button";
2565
+ applyBtn.className = "cd-btn cd-btn-apply";
2566
+ applyBtn.innerHTML = `${ICON_CHECK}<span>Apply Change</span>`;
2567
+ applyBtn.addEventListener("click", () => {
2568
+ void this.handleEditDecision(edit, "apply");
2569
+ });
708
2570
 
709
- const submitBtn = document.createElement("button");
710
- submitBtn.type = "button";
711
- submitBtn.className = "cd-btn cd-btn-primary";
712
- submitBtn.setAttribute("aria-label", "Submit feedback");
713
- submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
714
- submitBtn.addEventListener("click", () => {
715
- void this.handleSubmit();
716
- });
717
- this.submitBtn = submitBtn;
2571
+ btnGroup.appendChild(rejectBtn);
2572
+ btnGroup.appendChild(applyBtn);
2573
+ } else if (edit.status === "applied") {
2574
+ const revertBtn = document.createElement("button");
2575
+ revertBtn.type = "button";
2576
+ revertBtn.className = "cd-btn";
2577
+ revertBtn.innerHTML = `${ICON_UNDO}<span>Revert</span>`;
2578
+ revertBtn.addEventListener("click", () => {
2579
+ void this.handleEditDecision(edit, "revert");
2580
+ });
2581
+ btnGroup.appendChild(revertBtn);
2582
+ }
718
2583
 
719
- toolbar.appendChild(actions);
720
- toolbar.appendChild(submitBtn);
721
- promptShell.appendChild(toolbar);
722
- composer.appendChild(promptShell);
2584
+ footer.appendChild(btnGroup);
2585
+ card.appendChild(footer);
2586
+ return card;
2587
+ }
723
2588
 
724
- // 3. Freely Draggable Floating Pin Dock (visible when chatbox is closed, or draggable launcher)
725
- const pinDock = document.createElement("div");
726
- pinDock.className = "cd-pin-dock";
727
- this.pinDockEl = pinDock;
2589
+ private async handleEditDecision(
2590
+ edit: ProposedFileEdit,
2591
+ action: "apply" | "reject" | "revert"
2592
+ ): Promise<void> {
2593
+ try {
2594
+ const res =
2595
+ action === "apply"
2596
+ ? await this.apiClient.applyEdit(edit.id)
2597
+ : action === "reject"
2598
+ ? await this.apiClient.rejectEdit(edit.id)
2599
+ : await this.apiClient.revertEdit(edit.id);
2600
+
2601
+ if (res?.edit) {
2602
+ edit.status = res.edit.status;
2603
+ }
2604
+ this.renderAgentStream();
2605
+ if (action === "apply") {
2606
+ this.showStatus(`Applied change to ${edit.path}. Reload page if needed.`, "success");
2607
+ } else if (action === "revert") {
2608
+ this.showStatus(`Reverted ${edit.path} to original contents.`, "success");
2609
+ }
2610
+ } catch (err) {
2611
+ const msg = err instanceof Error ? err.message : `Failed to ${action} edit.`;
2612
+ this.showStatus(msg, "error");
2613
+ }
2614
+ }
728
2615
 
729
- const dockGrip = document.createElement("span");
730
- dockGrip.className = "cd-pin-dock-grip";
731
- dockGrip.title = "Drag to float anywhere on screen";
732
- dockGrip.innerHTML = ICON_GRIP;
733
- this.attachDragHandle(dockGrip);
734
- pinDock.appendChild(dockGrip);
2616
+ public async handleAgentSubmit(): Promise<void> {
2617
+ if (this.isAgentBusy) return;
735
2618
 
736
- if (this.config.features.element_selection) {
737
- const floatingPinBtn = document.createElement("button");
738
- floatingPinBtn.type = "button";
739
- floatingPinBtn.className = "cd-floating-pin-btn";
740
- floatingPinBtn.title = "Freeze & Pin element (⌥⇧P, or drag to move)";
741
- floatingPinBtn.setAttribute("aria-label", "Freeze & Pin element on page (Option+Shift+P)");
742
- floatingPinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>`;
743
- this.attachDragHandle(floatingPinBtn, () => this.startPinSelection());
744
- this.floatingPinBtn = floatingPinBtn;
745
- pinDock.appendChild(floatingPinBtn);
746
- }
747
-
748
- const trigger = document.createElement("button");
749
- trigger.type = "button";
750
- trigger.className = "cd-trigger";
751
- trigger.setAttribute("aria-label", "Open feedback composer");
752
- trigger.setAttribute("aria-expanded", String(this.isOpen));
753
- trigger.innerHTML = `${ICON_CHAT}<span>ContextDrop</span>`;
754
- this.attachDragHandle(trigger, () => this.toggleComposer());
755
- this.triggerBtn = trigger;
756
- pinDock.appendChild(trigger);
2619
+ const rawPrompt = (this.agentTextareaEl?.value || "").trim();
2620
+ if (
2621
+ rawPrompt.length === 0 &&
2622
+ this.elementReferences.length === 0 &&
2623
+ this.attachments.length === 0
2624
+ ) {
2625
+ this.showStatus("Enter a prompt or pin an element on the page first.", "error");
2626
+ return;
2627
+ }
757
2628
 
758
- root.appendChild(compactBar);
759
- root.appendChild(composer);
760
- root.appendChild(pinDock);
761
- this.shadow.appendChild(root);
2629
+ const promptText =
2630
+ rawPrompt || "Inspect the pinned DOM element(s) in this Rails workspace and explain how they work.";
2631
+
2632
+ const attachedElements = [...this.elementReferences];
2633
+ const attachedMedia = this.attachments.map((att) => ({
2634
+ id: att.id,
2635
+ label: att.label,
2636
+ preview_url: att.preview_url,
2637
+ attachment_type: att.attachment_type
2638
+ }));
2639
+ const requestAttachments = this.attachments.map((att) => ({
2640
+ attachment_type: att.attachment_type,
2641
+ filename: att.filename,
2642
+ data_url: att.data_url
2643
+ }));
2644
+
2645
+ const now = new Date();
2646
+ const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
2647
+
2648
+ const userMsg: AgentChatMessage = {
2649
+ id: `msg_${Date.now()}_u`,
2650
+ role: "user",
2651
+ content: promptText,
2652
+ createdAt: timeLabel,
2653
+ elements: attachedElements,
2654
+ attachments: attachedMedia
2655
+ };
2656
+ this.agentMessages.push(userMsg);
2657
+
2658
+ if (this.agentTextareaEl) {
2659
+ this.agentTextareaEl.value = "";
2660
+ }
2661
+ this.elementReferences = [];
2662
+ this.elementDomNodes.clear();
2663
+ this.attachments = [];
2664
+ this.picker?.hideExternalPreview();
2665
+ this.renderTray();
762
2666
 
2667
+ this.isAgentBusy = true;
2668
+ if (this.agentSendBtn) {
2669
+ this.agentSendBtn.disabled = true;
2670
+ this.agentSendBtn.innerHTML = `<span>Working...</span>`;
2671
+ }
2672
+ this.renderAgentStream();
763
2673
  this.syncUiStates();
2674
+
2675
+ try {
2676
+ const activeProv = this.getActiveProviderInfo();
2677
+ const res = await this.apiClient.sendAgentChat({
2678
+ messages: this.agentMessages.map((m) => ({ role: m.role, content: m.content })),
2679
+ page_url: typeof window !== "undefined" ? window.location.href : "/",
2680
+ element_references: attachedElements,
2681
+ attachments: requestAttachments,
2682
+ provider: activeProv.id,
2683
+ model: activeProv.model
2684
+ });
2685
+
2686
+ this.agentMessages.push({
2687
+ id: `msg_${Date.now()}_a`,
2688
+ role: "assistant",
2689
+ content: res.reply || "",
2690
+ createdAt: timeLabel,
2691
+ toolCalls: res.tool_calls || [],
2692
+ proposedEdits: res.proposed_edits || [],
2693
+ provider: res.provider,
2694
+ model: res.model
2695
+ });
2696
+ this.hideStatus();
2697
+ } catch (err) {
2698
+ const msg = err instanceof Error ? err.message : "Agent request failed.";
2699
+ if (/no api key|byok|api_key/i.test(msg)) {
2700
+ this.isByokDrawerOpen = true;
2701
+ }
2702
+ this.showStatus(msg, "error");
2703
+ } finally {
2704
+ this.isAgentBusy = false;
2705
+ if (this.agentSendBtn) {
2706
+ this.agentSendBtn.disabled = false;
2707
+ this.agentSendBtn.innerHTML = `${ICON_SEND}<span>Ask Agent</span>`;
2708
+ }
2709
+ this.renderAgentStream();
2710
+ this.syncUiStates();
2711
+ }
764
2712
  }
765
2713
 
766
2714
  private syncPinActiveIndicators(pickerActive: boolean): void {
767
- if (this.cornerPinBtn) {
768
- this.cornerPinBtn.classList.toggle("is-active", pickerActive);
769
- this.cornerPinBtn.setAttribute("aria-pressed", String(pickerActive));
770
- }
771
- if (this.floatingPinBtn) {
772
- this.floatingPinBtn.classList.toggle("is-active", pickerActive);
773
- this.floatingPinBtn.setAttribute("aria-pressed", String(pickerActive));
2715
+ for (const btn of [this.cornerPinBtn, this.sidebarPinBtn]) {
2716
+ if (btn) {
2717
+ btn.classList.toggle("is-active", pickerActive);
2718
+ btn.setAttribute("aria-pressed", String(pickerActive));
2719
+ }
774
2720
  }
775
2721
  if (this.compactPinBtn) {
2722
+ const smartMode = this.isSmartSelectionMode();
776
2723
  this.compactPinBtn.classList.toggle("is-active", pickerActive);
777
- this.compactPinBtn.innerHTML = pickerActive
778
- ? `${ICON_PIN}<span>Pinning</span>`
779
- : `${ICON_PIN}<span>Pin Element</span>`;
2724
+ if (smartMode) {
2725
+ this.compactPinBtn.title = "Highlight an area on the page";
2726
+ this.compactPinBtn.setAttribute("aria-label", "Toggle page highlight mode");
2727
+ this.compactPinBtn.innerHTML = pickerActive
2728
+ ? `${ICON_PIN}<span>Selecting</span>`
2729
+ : `${ICON_PIN}<span>Select area</span>`;
2730
+ } else {
2731
+ this.compactPinBtn.title = "Toggle Freeze & Pin (⌥⇧P)";
2732
+ this.compactPinBtn.setAttribute("aria-label", "Toggle element pin mode (Option+Shift+P)");
2733
+ this.compactPinBtn.innerHTML = pickerActive
2734
+ ? `${ICON_PIN}<span>Pinning</span>`
2735
+ : `${ICON_PIN}<span>Pin Element</span>`;
2736
+ }
2737
+ }
2738
+ }
2739
+
2740
+ private getVisibleContextCount(): number {
2741
+ if (!this.isSmartSelectionMode()) {
2742
+ return this.elementReferences.length + this.attachments.length;
780
2743
  }
2744
+ const unlinkedAttachments = this.attachments.filter(
2745
+ (att) =>
2746
+ !(
2747
+ att.metadata?.auto_smart_context === true &&
2748
+ att.element_reference_ref &&
2749
+ this.elementReferences.some((el) => el.client_ref === att.element_reference_ref)
2750
+ )
2751
+ );
2752
+ return this.elementReferences.length + unlinkedAttachments.length;
781
2753
  }
782
2754
 
783
2755
  private syncUiStates(): void {
784
2756
  const pickerActive = this.picker ? this.picker.isActive() : false;
785
- const totalContextCount = this.elementReferences.length + this.attachments.length;
2757
+ const totalContextCount = this.getVisibleContextCount();
2758
+ const agentMode = this.isAgentModeActive();
2759
+ const smartMode = this.isSmartSelectionMode();
2760
+
2761
+ const showAgentSidebar = this.isOpen && !this.isMinimized && agentMode;
2762
+ const showFeedbackComposer = this.isOpen && !this.isMinimized && !agentMode;
786
2763
 
787
2764
  if (this.composerEl) {
788
- this.composerEl.hidden = !this.isOpen || this.isMinimized;
2765
+ this.composerEl.hidden = !showFeedbackComposer;
2766
+ this.composerEl.classList.toggle("is-smart-mode", smartMode);
2767
+ }
2768
+ if (this.composerTitleEl) {
2769
+ this.composerTitleEl.textContent = smartMode ? "Send Feedback" : "ContextDrop";
2770
+ }
2771
+ if (this.composerMinBtn) {
2772
+ this.composerMinBtn.hidden = smartMode;
2773
+ }
2774
+ if (this.composerModeSwitchWrap) {
2775
+ this.composerModeSwitchWrap.hidden = !this.config.agent?.enabled;
2776
+ }
2777
+ if (this.textareaEl && !this.customPlaceholderSet) {
2778
+ this.textareaEl.placeholder = smartMode
2779
+ ? DEFAULT_SMART_PLACEHOLDER
2780
+ : DEFAULT_VERBOSE_PLACEHOLDER;
2781
+ }
2782
+ if (this.composerToolbarPickBtn) {
2783
+ if (smartMode) {
2784
+ this.composerToolbarPickBtn.title = "Highlight an area on the page";
2785
+ this.composerToolbarPickBtn.setAttribute("aria-label", "Highlight an area on the page");
2786
+ this.composerToolbarPickBtn.innerHTML = `${ICON_PIN}<span>Select area</span>`;
2787
+ } else {
2788
+ this.composerToolbarPickBtn.title = "Freeze & Pin element (⌥⇧P)";
2789
+ this.composerToolbarPickBtn.setAttribute(
2790
+ "aria-label",
2791
+ "Pin HTML element as context (Option+Shift+P)"
2792
+ );
2793
+ this.composerToolbarPickBtn.innerHTML = `${ICON_PIN}<span>Pin</span><kbd class="cd-kbd">⌥⇧P</kbd>`;
2794
+ }
2795
+ }
2796
+ if (this.composerToolbarScreenshotBtn) {
2797
+ this.composerToolbarScreenshotBtn.hidden = smartMode;
2798
+ }
2799
+ if (this.composerToolbarUploadBtn) {
2800
+ this.composerToolbarUploadBtn.innerHTML = smartMode
2801
+ ? `${ICON_IMAGE}<span>Add image</span>`
2802
+ : `${ICON_IMAGE}<span>Image</span>`;
2803
+ }
2804
+
2805
+ if (this.agentSidebarEl) {
2806
+ this.agentSidebarEl.hidden = !showAgentSidebar;
2807
+ }
2808
+ if (this.sidebarEnvPillEl) {
2809
+ this.sidebarEnvPillEl.textContent = this.getShortEnvironmentSlug();
789
2810
  }
2811
+ if (this.sidebarPushBtn) {
2812
+ this.sidebarPushBtn.classList.toggle("is-active", this.pushPageLayout);
2813
+ }
2814
+ if (this.byokDrawerEl) {
2815
+ this.byokDrawerEl.hidden = !this.isByokDrawerOpen;
2816
+ }
2817
+ if (this.keysToggleBtn) {
2818
+ this.keysToggleBtn.classList.toggle("is-active", this.isByokDrawerOpen);
2819
+ }
2820
+ if (this.feedbacksDrawerEl) {
2821
+ this.feedbacksDrawerEl.hidden = !this.isFeedbacksDrawerOpen;
2822
+ }
2823
+ if (this.feedbacksToggleBtn) {
2824
+ this.feedbacksToggleBtn.classList.toggle("is-active", this.isFeedbacksDrawerOpen);
2825
+ }
2826
+
2827
+ this.syncHostPagePushMargin(showAgentSidebar && this.pushPageLayout);
2828
+
790
2829
  if (this.compactBarEl) {
791
2830
  this.compactBarEl.hidden = !(this.isOpen && this.isMinimized);
792
- }
793
- if (this.pinDockEl) {
794
- this.pinDockEl.hidden = this.isOpen;
2831
+ this.compactBarEl.classList.toggle("is-smart-mode", smartMode);
795
2832
  }
796
2833
 
797
- if (this.triggerBtn) {
798
- this.triggerBtn.setAttribute("aria-expanded", String(this.isOpen && !this.isMinimized));
799
- const countBadge =
800
- totalContextCount > 0 ? `<span class="cd-count-pill">${totalContextCount}</span>` : "";
801
- this.triggerBtn.innerHTML = `${ICON_CHAT}<span>ContextDrop</span>${countBadge}`;
2834
+ if (this.bookCornerBtn) {
2835
+ this.bookCornerBtn.hidden = this.isOpen;
2836
+ this.bookCornerBtn.setAttribute("aria-expanded", String(this.isOpen && !this.isMinimized));
2837
+ this.bookCornerBtn.setAttribute(
2838
+ "aria-label",
2839
+ smartMode
2840
+ ? "Send feedback or drag corner to highlight part of the page"
2841
+ : "Open ContextDrop chatbox, or drag corner to pin an element on the page"
2842
+ );
2843
+ }
2844
+ if (this.bookCornerHintEl) {
2845
+ this.bookCornerHintEl.textContent = this.config.agent?.enabled
2846
+ ? "Open Agent · Drag to pin"
2847
+ : smartMode
2848
+ ? "Send feedback · Drag to highlight"
2849
+ : "Click to chat · Drag to pin";
2850
+ }
2851
+ if (this.bookCornerAgentDotEl) {
2852
+ this.bookCornerAgentDotEl.hidden = !this.config.agent?.enabled;
2853
+ }
2854
+ if (this.bookCornerCountEl) {
2855
+ this.bookCornerCountEl.hidden = totalContextCount === 0;
2856
+ this.bookCornerCountEl.textContent = String(totalContextCount);
802
2857
  }
803
2858
 
2859
+ const pinCountHtml =
2860
+ this.elementReferences.length > 0
2861
+ ? `<span class="cd-count-pill">${this.elementReferences.length}</span>`
2862
+ : "";
804
2863
  if (this.cornerPinBtn) {
805
- const pinCount =
806
- this.elementReferences.length > 0
807
- ? `<span class="cd-count-pill">${this.elementReferences.length}</span>`
808
- : "";
809
- this.cornerPinBtn.innerHTML = `${ICON_PIN}<span>Pin Element</span>${pinCount}`;
2864
+ if (smartMode) {
2865
+ this.cornerPinBtn.title = "Highlight an area on the page";
2866
+ this.cornerPinBtn.setAttribute("aria-label", "Highlight an area on the page");
2867
+ this.cornerPinBtn.innerHTML = `${ICON_PIN}<span>Select area</span>${pinCountHtml}`;
2868
+ } else {
2869
+ this.cornerPinBtn.title = "Freeze & Pin element (⌥⇧P)";
2870
+ this.cornerPinBtn.setAttribute(
2871
+ "aria-label",
2872
+ "Select DOM element on page (Option+Shift+P)"
2873
+ );
2874
+ this.cornerPinBtn.innerHTML = `${ICON_PIN}<span>Pin Element</span>${pinCountHtml}`;
2875
+ }
2876
+ }
2877
+ if (this.sidebarPinBtn) {
2878
+ this.sidebarPinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>${pinCountHtml}`;
810
2879
  }
811
2880
 
812
2881
  this.syncPinActiveIndicators(pickerActive);
813
- this.renderCompactCoachBar(
814
- pickerActive,
815
- this.picker ? this.picker.getCandidateStack().length : 0
816
- );
2882
+ if (!this.isPeelDragging) {
2883
+ this.renderCompactCoachBar(
2884
+ pickerActive,
2885
+ this.picker ? this.picker.getCandidateStack().length : 0
2886
+ );
2887
+ }
817
2888
  }
818
2889
 
819
2890
  private renderCompactCoachBar(pickerActive: boolean, candidateCount: number = 0): void {
820
2891
  if (!this.compactStatusEl) return;
821
2892
  this.compactStatusEl.innerHTML = "";
822
2893
 
2894
+ const smartMode = this.isSmartSelectionMode();
823
2895
  const pinnedCount = this.elementReferences.length;
824
- const totalContextCount = pinnedCount + this.attachments.length;
2896
+ const totalContextCount = this.getVisibleContextCount();
825
2897
 
826
2898
  if (this.compactStepGroupEl) {
827
- this.compactStepGroupEl.hidden = !pickerActive;
2899
+ this.compactStepGroupEl.hidden = !pickerActive || smartMode;
828
2900
  }
829
2901
  if (this.compactLayerUpBtn) {
830
2902
  this.compactLayerUpBtn.disabled = candidateCount <= 1;
@@ -833,6 +2905,20 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
833
2905
  this.compactLayerDownBtn.disabled = candidateCount <= 1;
834
2906
  }
835
2907
 
2908
+ if (pickerActive && smartMode) {
2909
+ const coach = document.createElement("span");
2910
+ coach.className = "cd-compact-coach-text";
2911
+ coach.textContent = "Click any part of the page to highlight it";
2912
+ this.compactStatusEl.appendChild(coach);
2913
+
2914
+ if (this.compactDoneBtn) {
2915
+ this.compactDoneBtn.className = "cd-btn";
2916
+ this.compactDoneBtn.setAttribute("aria-label", "Cancel selection and return to feedback");
2917
+ this.compactDoneBtn.innerHTML = `<span>Cancel</span>`;
2918
+ }
2919
+ return;
2920
+ }
2921
+
836
2922
  if (pickerActive) {
837
2923
  if (pinnedCount === 0) {
838
2924
  const coach = document.createElement("span");
@@ -892,45 +2978,63 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
892
2978
  return;
893
2979
  }
894
2980
 
895
- // Minimized while not actively in Pin Mode
896
2981
  const summary = document.createElement("span");
897
2982
  summary.className = "cd-compact-coach-text";
898
2983
  summary.textContent =
899
2984
  totalContextCount > 0
900
2985
  ? `${totalContextCount} context item${totalContextCount > 1 ? "s" : ""} attached`
901
- : "Chatbox minimized";
2986
+ : this.isAgentModeActive()
2987
+ ? "Agent sidebar minimized"
2988
+ : "Chatbox minimized";
902
2989
  this.compactStatusEl.appendChild(summary);
903
2990
 
904
2991
  if (this.compactDoneBtn) {
905
2992
  this.compactDoneBtn.className = "cd-btn cd-btn-primary";
906
2993
  this.compactDoneBtn.setAttribute("aria-label", "Return to chatbox");
907
- this.compactDoneBtn.innerHTML = `${ICON_EXPAND}<span>Chat</span>`;
2994
+ this.compactDoneBtn.innerHTML = `${ICON_EXPAND}<span>${this.isAgentModeActive() ? "Agent" : "Chat"}</span>`;
908
2995
  }
909
2996
  }
910
2997
 
911
2998
  private renderChatThread(): void {
912
2999
  if (!this.chatThreadEl) return;
913
3000
  this.chatThreadEl.innerHTML = "";
3001
+ const smartMode = this.isSmartSelectionMode();
914
3002
 
915
3003
  if (this.sessionHistory.length === 0) {
916
- const emptyBox = document.createElement("div");
917
- emptyBox.className = "cd-chat-empty";
3004
+ if (smartMode && (this.elementReferences.length > 0 || this.attachments.length > 0)) {
3005
+ this.chatThreadEl.hidden = true;
3006
+ return;
3007
+ }
3008
+ this.chatThreadEl.hidden = false;
918
3009
 
919
- const p1 = document.createElement("p");
920
- p1.className = "cd-chat-empty-text";
921
- p1.textContent = "Drop context directly from this page.";
3010
+ const emptyBox = document.createElement("div");
3011
+ emptyBox.className = smartMode ? "cd-chat-empty is-smart" : "cd-chat-empty";
3012
+
3013
+ if (smartMode) {
3014
+ const hint = document.createElement("p");
3015
+ hint.className = "cd-chat-empty-hint";
3016
+ hint.textContent =
3017
+ "Drag the corner or select an area on the page, or write a quick note below.";
3018
+ emptyBox.appendChild(hint);
3019
+ } else {
3020
+ const p1 = document.createElement("p");
3021
+ p1.className = "cd-chat-empty-text";
3022
+ p1.textContent = "Drop context directly from this page.";
922
3023
 
923
- const p2 = document.createElement("p");
924
- p2.className = "cd-chat-empty-hint";
925
- p2.innerHTML =
926
- "Press <kbd class=\"cd-kbd\">⌥⇧P</kbd> anywhere or click Pin to freeze &amp; pin, scroll to cycle layers, and press <kbd class=\"cd-kbd\">Space</kbd> to pin instantly.";
3024
+ const p2 = document.createElement("p");
3025
+ p2.className = "cd-chat-empty-hint";
3026
+ p2.innerHTML =
3027
+ 'Drag the folded corner onto any element, or press <kbd class="cd-kbd">⌥⇧P</kbd> to freeze &amp; pin, scroll to cycle layers, and press <kbd class="cd-kbd">Space</kbd> to pin.';
927
3028
 
928
- emptyBox.appendChild(p1);
929
- emptyBox.appendChild(p2);
3029
+ emptyBox.appendChild(p1);
3030
+ emptyBox.appendChild(p2);
3031
+ }
930
3032
  this.chatThreadEl.appendChild(emptyBox);
931
3033
  return;
932
3034
  }
933
3035
 
3036
+ this.chatThreadEl.hidden = false;
3037
+
934
3038
  for (const entry of this.sessionHistory) {
935
3039
  const msgCard = document.createElement("div");
936
3040
  msgCard.className = "cd-chat-msg";
@@ -941,17 +3045,22 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
941
3045
 
942
3046
  for (const el of entry.elements) {
943
3047
  const pill = document.createElement("span");
944
- pill.className = "cd-chat-msg-pill";
945
- pill.textContent = el.selector;
3048
+ pill.className = smartMode ? "cd-chat-msg-pill is-friendly" : "cd-chat-msg-pill";
3049
+ pill.textContent = smartMode ? this.getElementFriendlyLabel(el) : el.selector;
946
3050
  pills.appendChild(pill);
947
3051
  }
948
3052
  for (const att of entry.attachments) {
3053
+ if (smartMode && att.attachment_type === "screenshot" && entry.elements.length > 0) {
3054
+ continue;
3055
+ }
949
3056
  const pill = document.createElement("span");
950
- pill.className = "cd-chat-msg-pill";
3057
+ pill.className = smartMode ? "cd-chat-msg-pill is-friendly" : "cd-chat-msg-pill";
951
3058
  pill.textContent = att.label;
952
3059
  pills.appendChild(pill);
953
3060
  }
954
- msgCard.appendChild(pills);
3061
+ if (pills.childNodes.length > 0) {
3062
+ msgCard.appendChild(pills);
3063
+ }
955
3064
  }
956
3065
 
957
3066
  if (entry.message) {
@@ -964,7 +3073,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
964
3073
  const meta = document.createElement("div");
965
3074
  meta.className = "cd-chat-msg-meta";
966
3075
  const idSpan = document.createElement("span");
967
- idSpan.textContent = `Dropped #${entry.id}`;
3076
+ idSpan.textContent = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
968
3077
  const timeSpan = document.createElement("span");
969
3078
  timeSpan.textContent = entry.createdAt;
970
3079
  meta.appendChild(idSpan);
@@ -978,10 +3087,125 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
978
3087
  }
979
3088
 
980
3089
  private renderTray(): void {
981
- if (!this.trayEl) return;
982
- this.trayEl.innerHTML = "";
3090
+ for (const targetTray of [this.trayEl, this.agentTrayEl]) {
3091
+ if (!targetTray) continue;
3092
+ this.populateTrayElement(targetTray);
3093
+ }
3094
+ if (this.sessionHistory.length === 0) {
3095
+ this.renderChatThread();
3096
+ }
3097
+ }
3098
+
3099
+ private populateTrayElement(trayContainer: HTMLDivElement): void {
3100
+ trayContainer.innerHTML = "";
3101
+ const smartTray = trayContainer === this.trayEl && this.isSmartSelectionMode();
3102
+
3103
+ if (smartTray) {
3104
+ const linkedShotIds = new Set<string>();
3105
+
3106
+ for (const elRef of this.elementReferences) {
3107
+ const domNode = this.elementDomNodes.get(elRef.client_ref);
3108
+ const friendlyLabel = this.getElementFriendlyLabel(elRef, domNode);
3109
+ const linkedShot = this.attachments.find(
3110
+ (att) => att.element_reference_ref === elRef.client_ref
3111
+ );
3112
+ if (linkedShot) {
3113
+ linkedShotIds.add(linkedShot.id);
3114
+ }
3115
+
3116
+ const card = document.createElement("div");
3117
+ card.className = "cd-smart-card";
3118
+ card.setAttribute("data-chip-type", "smart-context");
3119
+
3120
+ if (domNode) {
3121
+ card.addEventListener("mouseenter", () => this.picker?.showExternalPreview(domNode));
3122
+ card.addEventListener("mouseleave", () => this.picker?.hideExternalPreview());
3123
+ }
3124
+
3125
+ if (linkedShot?.preview_url) {
3126
+ const thumb = document.createElement("img");
3127
+ thumb.className = "cd-smart-card-thumb";
3128
+ thumb.src = linkedShot.preview_url;
3129
+ thumb.alt = friendlyLabel;
3130
+ card.appendChild(thumb);
3131
+ } else {
3132
+ const iconBadge = document.createElement("span");
3133
+ iconBadge.className = "cd-smart-card-icon";
3134
+ iconBadge.innerHTML = ICON_PIN;
3135
+ card.appendChild(iconBadge);
3136
+ }
3137
+
3138
+ const body = document.createElement("div");
3139
+ body.className = "cd-smart-card-body";
3140
+
3141
+ const title = document.createElement("span");
3142
+ title.className = "cd-smart-card-title";
3143
+ title.textContent = friendlyLabel;
3144
+
3145
+ const sub = document.createElement("span");
3146
+ sub.className = "cd-smart-card-sub";
3147
+ sub.textContent = linkedShot
3148
+ ? "Area & surrounding context captured"
3149
+ : "Highlighted on page";
3150
+
3151
+ body.appendChild(title);
3152
+ body.appendChild(sub);
3153
+ card.appendChild(body);
3154
+
3155
+ const removeBtn = document.createElement("button");
3156
+ removeBtn.type = "button";
3157
+ removeBtn.className = "cd-chip-remove";
3158
+ removeBtn.setAttribute("aria-label", `Remove ${friendlyLabel}`);
3159
+ removeBtn.innerHTML = ICON_CLOSE;
3160
+ removeBtn.addEventListener("click", () => this.removeElementReference(elRef.client_ref));
3161
+ card.appendChild(removeBtn);
3162
+
3163
+ trayContainer.appendChild(card);
3164
+ }
3165
+
3166
+ for (const att of this.attachments) {
3167
+ if (linkedShotIds.has(att.id)) continue;
3168
+
3169
+ const card = document.createElement("div");
3170
+ card.className = "cd-smart-card";
3171
+ card.setAttribute("data-chip-type", att.attachment_type);
3172
+
3173
+ if (att.preview_url) {
3174
+ const thumb = document.createElement("img");
3175
+ thumb.className = "cd-smart-card-thumb";
3176
+ thumb.src = att.preview_url;
3177
+ thumb.alt = att.label;
3178
+ card.appendChild(thumb);
3179
+ }
3180
+
3181
+ const body = document.createElement("div");
3182
+ body.className = "cd-smart-card-body";
3183
+
3184
+ const title = document.createElement("span");
3185
+ title.className = "cd-smart-card-title";
3186
+ title.textContent = att.label;
3187
+
3188
+ const sub = document.createElement("span");
3189
+ sub.className = "cd-smart-card-sub";
3190
+ sub.textContent = "Attached image";
3191
+
3192
+ body.appendChild(title);
3193
+ body.appendChild(sub);
3194
+ card.appendChild(body);
3195
+
3196
+ const removeBtn = document.createElement("button");
3197
+ removeBtn.type = "button";
3198
+ removeBtn.className = "cd-chip-remove";
3199
+ removeBtn.setAttribute("aria-label", `Remove ${att.label}`);
3200
+ removeBtn.innerHTML = ICON_CLOSE;
3201
+ removeBtn.addEventListener("click", () => this.removeAttachment(att.id));
3202
+ card.appendChild(removeBtn);
3203
+
3204
+ trayContainer.appendChild(card);
3205
+ }
3206
+ return;
3207
+ }
983
3208
 
984
- // Render ElementReference chips
985
3209
  for (const elRef of this.elementReferences) {
986
3210
  const chip = document.createElement("div");
987
3211
  chip.className = "cd-chip";
@@ -1005,10 +3229,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1005
3229
  chip.appendChild(badge);
1006
3230
  chip.appendChild(label);
1007
3231
 
1008
- if (
1009
- this.config.features.screenshot_capture &&
1010
- domNode
1011
- ) {
3232
+ if (this.config.features.screenshot_capture && domNode) {
1012
3233
  const snapBtn = document.createElement("button");
1013
3234
  snapBtn.type = "button";
1014
3235
  snapBtn.className = "cd-chip-action";
@@ -1029,10 +3250,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1029
3250
  removeBtn.addEventListener("click", () => this.removeElementReference(elRef.client_ref));
1030
3251
 
1031
3252
  chip.appendChild(removeBtn);
1032
- this.trayEl.appendChild(chip);
3253
+ trayContainer.appendChild(chip);
1033
3254
  }
1034
3255
 
1035
- // Render Attachment chips (uploaded images & screenshots)
1036
3256
  for (const att of this.attachments) {
1037
3257
  const chip = document.createElement("div");
1038
3258
  chip.className = "cd-chip";
@@ -1064,7 +3284,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1064
3284
  chip.appendChild(badge);
1065
3285
  chip.appendChild(label);
1066
3286
  chip.appendChild(removeBtn);
1067
- this.trayEl.appendChild(chip);
3287
+ trayContainer.appendChild(chip);
1068
3288
  }
1069
3289
  }
1070
3290
 
@@ -1190,8 +3410,68 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1190
3410
  }
1191
3411
  }
1192
3412
 
3413
+ private captureSmartSurroundingContext(
3414
+ element: Element,
3415
+ elementClientRef: string,
3416
+ friendlyLabel: string
3417
+ ): Promise<void> {
3418
+ const task = (async (): Promise<void> => {
3419
+ if (this.attachments.length >= this.config.limits.max_attachments) {
3420
+ return;
3421
+ }
3422
+ try {
3423
+ const result = await captureSurroundingContextScreenshot(
3424
+ element,
3425
+ this.config.features.smart_capture_padding ?? 84,
3426
+ this.config.privacy.excluded_selectors,
3427
+ elementClientRef
3428
+ );
3429
+ if (!this.elementReferences.some((ref) => ref.client_ref === elementClientRef)) {
3430
+ return;
3431
+ }
3432
+ this.attachments = this.attachments.filter(
3433
+ (att) =>
3434
+ !(
3435
+ att.element_reference_ref === elementClientRef &&
3436
+ att.metadata?.auto_smart_context === true
3437
+ )
3438
+ );
3439
+ this.attachments.push({
3440
+ id: `smartshot_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
3441
+ attachment_type: "screenshot",
3442
+ label: `Context around ${friendlyLabel}`,
3443
+ preview_url: result.dataUrl,
3444
+ blob: result.blob,
3445
+ data_url: result.dataUrl,
3446
+ filename: `context-${Date.now()}.png`,
3447
+ element_reference_ref: elementClientRef,
3448
+ metadata: {
3449
+ ...result.metadata,
3450
+ auto_smart_context: true,
3451
+ friendly_label: friendlyLabel
3452
+ }
3453
+ });
3454
+ this.renderTray();
3455
+ this.syncUiStates();
3456
+ } catch {
3457
+ // Non-fatal in headless or non-canvas environments; smart element card still renders
3458
+ }
3459
+ })();
3460
+
3461
+ this.pendingSmartCaptures.add(task);
3462
+ void task.finally(() => {
3463
+ this.pendingSmartCaptures.delete(task);
3464
+ });
3465
+ return task;
3466
+ }
3467
+
1193
3468
  public async handleSubmit(): Promise<void> {
1194
3469
  if (this.isSubmitting) return;
3470
+ const smartMode = this.isSmartSelectionMode();
3471
+
3472
+ if (this.pendingSmartCaptures.size > 0) {
3473
+ await Promise.allSettled(Array.from(this.pendingSmartCaptures));
3474
+ }
1195
3475
 
1196
3476
  const message = (this.textareaEl?.value || "").trim();
1197
3477
  if (
@@ -1199,7 +3479,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1199
3479
  this.attachments.length === 0 &&
1200
3480
  this.elementReferences.length === 0
1201
3481
  ) {
1202
- this.showStatus("Enter a note, pin an element, or attach a screenshot first.", "error");
3482
+ this.showStatus(
3483
+ smartMode
3484
+ ? "Write a short note or highlight part of the page first."
3485
+ : "Enter a note, pin an element, or attach a screenshot first.",
3486
+ "error"
3487
+ );
1203
3488
  return;
1204
3489
  }
1205
3490
 
@@ -1224,6 +3509,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1224
3509
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
1225
3510
  metadata: {
1226
3511
  ...this.customMetadata,
3512
+ environment: this.config.environment,
3513
+ selection_mode: smartMode ? "smart" : "verbose",
1227
3514
  viewport: {
1228
3515
  width: typeof window !== "undefined" ? window.innerWidth : 0,
1229
3516
  height: typeof window !== "undefined" ? window.innerHeight : 0
@@ -1247,7 +3534,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1247
3534
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
1248
3535
  this.sessionHistory.push({
1249
3536
  id: res?.id ?? this.sessionHistory.length + 1,
1250
- message: message || "(Context drop without text)",
3537
+ message:
3538
+ message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
1251
3539
  createdAt: timeLabel,
1252
3540
  elements: submittedElements,
1253
3541
  attachments: submittedAttachments
@@ -1263,7 +3551,10 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1263
3551
  this.renderTray();
1264
3552
  this.renderChatThread();
1265
3553
  this.syncUiStates();
1266
- this.showStatus("Context drop saved.", "success");
3554
+ this.showStatus(
3555
+ smartMode ? "Thanks! Your feedback was sent." : "Context drop saved.",
3556
+ "success"
3557
+ );
1267
3558
  } catch (err) {
1268
3559
  const msg = err instanceof Error ? err.message : "Failed to submit feedback.";
1269
3560
  this.showStatus(msg, "error");
@@ -1276,11 +3567,21 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1276
3567
  }
1277
3568
  }
1278
3569
 
3570
+ private hideStatus(): void {
3571
+ for (const bar of [this.statusEl, this.agentStatusEl]) {
3572
+ if (bar) {
3573
+ bar.hidden = true;
3574
+ }
3575
+ }
3576
+ }
3577
+
1279
3578
  private showStatus(text: string, kind: "error" | "success"): void {
1280
- if (!this.statusEl) return;
1281
- this.statusEl.textContent = text;
1282
- this.statusEl.className = `cd-status ${kind}`;
1283
- this.statusEl.hidden = false;
3579
+ for (const bar of [this.statusEl, this.agentStatusEl]) {
3580
+ if (!bar) continue;
3581
+ bar.textContent = text;
3582
+ bar.className = `cd-status ${kind}`;
3583
+ bar.hidden = false;
3584
+ }
1284
3585
  }
1285
3586
  }
1286
3587