context_drop 0.1.3 → 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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +218 -49
  3. data/SPEC.md +74 -26
  4. data/app/assets/javascripts/context_drop/context_drop.js +5227 -652
  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/dashboard/feedbacks_controller.rb +62 -2
  8. data/app/controllers/context_drop/feedbacks_controller.rb +13 -3
  9. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  10. data/app/helpers/context_drop/dashboard_helper.rb +52 -0
  11. data/app/helpers/context_drop/widget_helper.rb +11 -1
  12. data/app/javascript/context_drop/__tests__/widget.test.ts +731 -92
  13. data/app/javascript/context_drop/api-client.ts +130 -11
  14. data/app/javascript/context_drop/element-picker.ts +247 -30
  15. data/app/javascript/context_drop/icons.ts +24 -0
  16. data/app/javascript/context_drop/markdown.ts +146 -0
  17. data/app/javascript/context_drop/sanitizer.ts +413 -2
  18. data/app/javascript/context_drop/screenshot.ts +102 -8
  19. data/app/javascript/context_drop/styles.ts +1528 -252
  20. data/app/javascript/context_drop/types.ts +147 -0
  21. data/app/javascript/context_drop/widget.ts +2629 -288
  22. data/app/models/context_drop/feedback.rb +34 -5
  23. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +166 -60
  24. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +178 -47
  25. data/app/views/layouts/context_drop/application.html.erb +416 -70
  26. data/config/routes.rb +11 -0
  27. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  28. data/lib/context_drop/agent/key_store.rb +290 -0
  29. data/lib/context_drop/agent/llm_client.rb +413 -0
  30. data/lib/context_drop/agent/orchestrator.rb +314 -0
  31. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  32. data/lib/context_drop/configuration.rb +216 -3
  33. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  34. data/lib/context_drop/mcp/environment_router.rb +115 -0
  35. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +87 -8
  36. data/lib/context_drop/mcp/remote_client.rb +120 -0
  37. data/lib/context_drop/mcp/server.rb +9 -2
  38. data/lib/context_drop/mcp/tools/get_feedback.rb +50 -4
  39. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +26 -4
  40. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  41. data/lib/context_drop/mcp/tools/list_feedbacks.rb +174 -22
  42. data/lib/context_drop/mcp/tools/update_feedback_status.rb +45 -4
  43. data/lib/context_drop/version.rb +1 -1
  44. data/lib/context_drop.rb +8 -2
  45. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  46. metadata +13 -2
@@ -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,10 +204,16 @@ 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;
@@ -90,24 +221,125 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
90
221
  private fileInputEl: HTMLInputElement | null = null;
91
222
  private submitBtn: HTMLButtonElement | null = null;
92
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
+
251
+ private lastPointerX: number = 0;
252
+ private lastPointerY: number = 0;
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
+ }
265
+
93
266
  public connectedCallback(): void {
94
267
  if (!this.shadow) {
95
268
  this.shadow = this.attachShadow({ mode: "open" });
96
269
  }
97
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";
98
288
  this.renderShadowDom();
99
289
 
290
+ this.boundTrackPointer = (ev: MouseEvent) => {
291
+ this.lastPointerX = ev.clientX;
292
+ this.lastPointerY = ev.clientY;
293
+ };
294
+
295
+ this.boundGlobalKeyDown = (ev: KeyboardEvent) => {
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
304
+ if (
305
+ !this.isSmartSelectionMode() &&
306
+ ev.altKey &&
307
+ ev.shiftKey &&
308
+ (ev.code === "KeyP" || (typeof ev.key === "string" && ev.key.toLowerCase() === "p"))
309
+ ) {
310
+ ev.preventDefault();
311
+ ev.stopPropagation();
312
+ if (typeof ev.stopImmediatePropagation === "function") {
313
+ ev.stopImmediatePropagation();
314
+ }
315
+ this.togglePinSelection();
316
+ }
317
+ };
318
+
319
+ if (typeof window !== "undefined") {
320
+ window.addEventListener("mousemove", this.boundTrackPointer, { capture: true, passive: true });
321
+ window.addEventListener("keydown", this.boundGlobalKeyDown, { capture: true });
322
+ }
323
+
100
324
  this.picker = new ElementPicker({
101
325
  onSelect: (snapshot, el) => {
102
326
  const added = this.addElementReference(snapshot, el);
103
327
  if (added) {
104
- const count = this.elementReferences.length;
105
- this.showStatus(
106
- count === 1
107
- ? `Pinned ${snapshot.selector}`
108
- : `Pinned ${count} elements (latest: ${snapshot.selector})`,
109
- "success"
110
- );
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
+ }
111
343
  }
112
344
  this.syncUiStates();
113
345
  },
@@ -115,42 +347,128 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
115
347
  this.removeElementReference(clientRef);
116
348
  },
117
349
  onExit: () => {
350
+ if (this.isPeelDragging) return;
118
351
  this.isMinimized = false;
119
352
  this.openComposer();
120
353
  this.syncUiStates();
121
354
  },
122
- 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,
123
358
  getExcludedSelectors: () => this.config.privacy.excluded_selectors,
359
+ getSelectionMode: () => (this.isSmartSelectionMode() ? "smart" : "verbose"),
124
360
  getPinnedElements: () =>
125
361
  this.elementReferences
126
362
  .map((ref) => {
127
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;
128
368
  return node
129
- ? { clientRef: ref.client_ref, selector: ref.selector, element: node }
369
+ ? { clientRef: ref.client_ref, selector: ref.selector, friendlyLabel, element: node }
130
370
  : null;
131
371
  })
132
372
  .filter(
133
- (item): item is { clientRef: string; selector: string; element: Element } =>
134
- item !== null
373
+ (
374
+ item
375
+ ): item is {
376
+ clientRef: string;
377
+ selector: string;
378
+ friendlyLabel: string | undefined;
379
+ element: Element;
380
+ } => item !== null
135
381
  ),
136
382
  onStateChange: (state) => {
137
383
  this.syncPinActiveIndicators(state.active);
138
- this.renderCompactCoachBar(state.active, state.candidateStack.length);
384
+ if (!this.isPeelDragging) {
385
+ this.renderCompactCoachBar(state.active, state.candidateStack.length);
386
+ }
139
387
  }
140
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
+ }
141
395
  }
142
396
 
143
397
  public disconnectedCallback(): void {
398
+ if (this.cancelActivePeelDrag) {
399
+ this.cancelActivePeelDrag();
400
+ }
144
401
  if (this.picker && this.picker.isActive()) {
145
- this.picker.stop();
402
+ this.picker.stop({ silent: true });
146
403
  }
147
404
  this.picker?.hideExternalPreview();
405
+ this.syncHostPagePushMargin(false);
406
+
407
+ if (typeof window !== "undefined") {
408
+ window.removeEventListener("mousemove", this.boundTrackPointer, { capture: true });
409
+ window.removeEventListener("keydown", this.boundGlobalKeyDown, { capture: true });
410
+ }
148
411
  }
149
412
 
150
413
  public getConfig(): WidgetConfig {
151
414
  return this.config;
152
415
  }
153
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
+
154
472
  public getElementReferences(): ElementReferenceSnapshot[] {
155
473
  return [...this.elementReferences];
156
474
  }
@@ -163,20 +481,53 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
163
481
  return [...this.sessionHistory];
164
482
  }
165
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
+
166
516
  public openComposer(): void {
167
517
  this.isOpen = true;
168
518
  this.isMinimized = false;
169
- this.syncUiStates();
170
- if (this.textareaEl) {
171
- this.textareaEl.focus();
519
+ if (this.isAgentModeActive()) {
520
+ void this.ensureAgentStatusLoaded();
172
521
  }
522
+ this.syncUiStates();
523
+ this.focusActiveInput();
173
524
  }
174
525
 
175
526
  public closeComposer(): void {
176
527
  this.isOpen = false;
177
528
  this.isMinimized = false;
178
529
  if (this.picker && this.picker.isActive()) {
179
- this.picker.stop();
530
+ this.picker.stop({ silent: true });
180
531
  }
181
532
  this.picker?.hideExternalPreview();
182
533
  this.syncUiStates();
@@ -198,7 +549,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
198
549
 
199
550
  public expandFromCompactBar(): void {
200
551
  if (this.picker && this.picker.isActive()) {
201
- this.picker.stop();
552
+ this.picker.stop({ silent: true });
202
553
  }
203
554
  this.isMinimized = false;
204
555
  this.openComposer();
@@ -215,7 +566,10 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
215
566
  return;
216
567
  }
217
568
  this.minimizeToCompactBar();
218
- this.picker.start();
569
+ this.picker.start({ suppressCursorPin: false });
570
+ if (this.lastPointerX > 0 && this.lastPointerY > 0) {
571
+ this.picker.highlightAtPoint(this.lastPointerX, this.lastPointerY);
572
+ }
219
573
  this.syncUiStates();
220
574
  }
221
575
 
@@ -227,6 +581,141 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
227
581
  }
228
582
  }
229
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
+
230
719
  public setFreePosition(left: number, top: number): void {
231
720
  if (!this.rootContainer) return;
232
721
  const vw = typeof window !== "undefined" ? window.innerWidth || 1024 : 1024;
@@ -261,6 +750,10 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
261
750
  public removeElementReference(clientRef: string): void {
262
751
  this.elementReferences = this.elementReferences.filter((el) => el.client_ref !== clientRef);
263
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
+ );
264
757
  this.picker?.hideExternalPreview();
265
758
  this.picker?.refreshPinnedMarkers();
266
759
  this.renderTray();
@@ -273,6 +766,29 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
273
766
  this.syncUiStates();
274
767
  }
275
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
+
276
792
  private readDataAttributes(): void {
277
793
  const endpoint = this.getAttribute("data-endpoint") || "/context_drop";
278
794
  this.apiClient = new ContextDropApiClient(endpoint);
@@ -281,9 +797,17 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
281
797
  if (rawConfig) {
282
798
  try {
283
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
+ }
284
807
  this.config = {
285
808
  ...this.config,
286
809
  ...parsed,
810
+ agent: { ...(this.config.agent || { enabled: false }), ...(parsed.agent || {}) },
287
811
  features: { ...this.config.features, ...(parsed.features || {}) },
288
812
  limits: { ...this.config.limits, ...(parsed.limits || {}) },
289
813
  privacy: { ...this.config.privacy, ...(parsed.privacy || {}) }
@@ -307,6 +831,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
307
831
  const placeholderOverride = this.getAttribute("data-placeholder");
308
832
  if (placeholderOverride) {
309
833
  this.config.placeholder = placeholderOverride;
834
+ this.customPlaceholderSet = true;
310
835
  }
311
836
 
312
837
  const rawMetadata = this.getAttribute("data-metadata");
@@ -317,37 +842,255 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
317
842
  this.customMetadata = {};
318
843
  }
319
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
+ }
320
894
  }
321
895
 
322
- private attachDragHandle(handleEl: HTMLElement, onClickFallback?: () => void): void {
896
+ private attachBookCornerLauncher(cornerBtn: HTMLButtonElement): void {
323
897
  let startX = 0;
324
898
  let startY = 0;
325
- let initialLeft = 0;
326
- let initialTop = 0;
327
- let dragging = false;
328
- let moved = false;
899
+ let pointerActive = false;
900
+ let peeled = false;
901
+ let leftOriginZone = false;
902
+ let activeSnapCorner: WidgetPosition | null = null;
329
903
  let suppressNextClick = false;
330
- let suppressClickTimer: ReturnType<typeof setTimeout> | null = null;
904
+ let suppressTimer: ReturnType<typeof setTimeout> | null = null;
331
905
 
332
- const clearSuppressClick = (): void => {
906
+ const clearSuppress = (): void => {
333
907
  suppressNextClick = false;
334
- if (suppressClickTimer !== null) {
335
- clearTimeout(suppressClickTimer);
336
- suppressClickTimer = null;
908
+ if (suppressTimer !== null) {
909
+ clearTimeout(suppressTimer);
910
+ suppressTimer = null;
337
911
  }
338
912
  };
339
913
 
340
- if (onClickFallback) {
341
- handleEl.addEventListener("click", (ev: MouseEvent) => {
342
- if (suppressNextClick) {
343
- clearSuppressClick();
344
- ev.preventDefault();
345
- ev.stopPropagation();
346
- 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);
347
962
  }
348
- onClickFallback();
349
- });
350
- }
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;
351
1094
 
352
1095
  const onPointerMove = (ev: PointerEvent): void => {
353
1096
  if (!dragging) return;
@@ -355,7 +1098,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
355
1098
  const dy = ev.clientY - startY;
356
1099
  if (!moved && Math.hypot(dx, dy) > 5) {
357
1100
  moved = true;
358
- this.pinDockEl?.classList.add("is-dragging");
359
1101
  }
360
1102
  if (moved) {
361
1103
  this.setFreePosition(initialLeft + dx, initialTop + dy);
@@ -364,35 +1106,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
364
1106
 
365
1107
  const cleanupDrag = (): void => {
366
1108
  dragging = false;
367
- this.pinDockEl?.classList.remove("is-dragging");
368
1109
  window.removeEventListener("pointermove", onPointerMove);
369
- window.removeEventListener("pointerup", onPointerUp);
370
- window.removeEventListener("pointercancel", onPointerCancel);
371
- };
372
-
373
- const onPointerUp = (): void => {
374
- if (!dragging) return;
375
- cleanupDrag();
376
- if (moved && onClickFallback) {
377
- suppressNextClick = true;
378
- if (suppressClickTimer !== null) {
379
- clearTimeout(suppressClickTimer);
380
- }
381
- suppressClickTimer = setTimeout(() => {
382
- suppressNextClick = false;
383
- suppressClickTimer = null;
384
- }, 0);
385
- }
386
- };
387
-
388
- const onPointerCancel = (): void => {
389
- if (!dragging) return;
390
- cleanupDrag();
391
- clearSuppressClick();
1110
+ window.removeEventListener("pointerup", cleanupDrag);
1111
+ window.removeEventListener("pointercancel", cleanupDrag);
392
1112
  };
393
1113
 
394
1114
  handleEl.addEventListener("pointerdown", (ev: PointerEvent) => {
395
- // Only primary mouse button or touch
396
1115
  if (ev.button !== 0) return;
397
1116
  const targetEl =
398
1117
  ev.target && typeof (ev.target as Element).closest === "function"
@@ -411,27 +1130,169 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
411
1130
  initialTop = this.freePos ? this.freePos.top : rect.top;
412
1131
  dragging = true;
413
1132
  moved = false;
414
- clearSuppressClick();
415
1133
 
416
1134
  window.addEventListener("pointermove", onPointerMove);
417
- window.addEventListener("pointerup", onPointerUp);
418
- window.addEventListener("pointercancel", onPointerCancel);
1135
+ window.addEventListener("pointerup", cleanupDrag);
1136
+ window.addEventListener("pointercancel", cleanupDrag);
419
1137
  });
420
1138
  }
421
1139
 
422
- private renderShadowDom(): void {
423
- if (!this.shadow) return;
424
- this.shadow.innerHTML = "";
425
-
426
- const styleEl = document.createElement("style");
427
- styleEl.textContent = WIDGET_SHADOW_STYLES;
428
- this.shadow.appendChild(styleEl);
1140
+ private attachSidebarResizer(resizerEl: HTMLDivElement): void {
1141
+ let startX = 0;
1142
+ let startWidth = this.sidebarWidth;
1143
+ let active = false;
429
1144
 
430
- const root = document.createElement("div");
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
+ };
1157
+
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");
431
1219
  root.className = `cd-root pos-${this.config.position}`;
432
1220
  this.rootContainer = root;
433
1221
 
434
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 {
435
1296
  const compactBar = document.createElement("div");
436
1297
  compactBar.className = "cd-compact-bar";
437
1298
  compactBar.setAttribute("role", "region");
@@ -449,7 +1310,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
449
1310
  const compactPinBtn = document.createElement("button");
450
1311
  compactPinBtn.type = "button";
451
1312
  compactPinBtn.className = "cd-pin-corner-btn is-active";
452
- compactPinBtn.setAttribute("aria-label", "Toggle element pin mode");
1313
+ compactPinBtn.title = "Toggle Freeze & Pin (⌥⇧P)";
1314
+ compactPinBtn.setAttribute("aria-label", "Toggle element pin mode (Option+Shift+P)");
453
1315
  compactPinBtn.innerHTML = `${ICON_PIN}<span>Pinning</span>`;
454
1316
  compactPinBtn.addEventListener("click", () => this.togglePinSelection());
455
1317
  this.compactPinBtn = compactPinBtn;
@@ -495,15 +1357,42 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
495
1357
  this.compactDoneBtn = expandBtn;
496
1358
  compactBar.appendChild(expandBtn);
497
1359
 
498
- // 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 {
499
1389
  const composer = document.createElement("div");
500
1390
  composer.className = "cd-composer";
501
1391
  composer.setAttribute("role", "dialog");
502
1392
  composer.setAttribute("aria-label", "ContextDrop Feedback Chatbox");
503
- composer.hidden = !this.isOpen;
1393
+ composer.hidden = true;
504
1394
  this.composerEl = composer;
505
1395
 
506
- // Drag-and-drop image support on the chatbox
507
1396
  composer.addEventListener("dragover", (ev) => {
508
1397
  ev.preventDefault();
509
1398
  composer.classList.add("is-dragging-over");
@@ -520,7 +1409,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
520
1409
  }
521
1410
  });
522
1411
 
523
- // Header with Top-Left Pin-Shaped Selector & Drag Handle
524
1412
  const header = document.createElement("div");
525
1413
  header.className = "cd-composer-header";
526
1414
  this.attachDragHandle(header);
@@ -532,8 +1420,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
532
1420
  const cornerPinBtn = document.createElement("button");
533
1421
  cornerPinBtn.type = "button";
534
1422
  cornerPinBtn.className = "cd-pin-corner-btn";
535
- cornerPinBtn.title = "Pin any HTML element on the page as context";
536
- cornerPinBtn.setAttribute("aria-label", "Select DOM element on page");
1423
+ cornerPinBtn.title = "Freeze & Pin element (⌥⇧P)";
1424
+ cornerPinBtn.setAttribute("aria-label", "Select DOM element on page (Option+Shift+P)");
537
1425
  cornerPinBtn.innerHTML = `${ICON_PIN}<span>Pin Element</span>`;
538
1426
  cornerPinBtn.addEventListener("click", () => this.startPinSelection());
539
1427
  this.cornerPinBtn = cornerPinBtn;
@@ -543,11 +1431,23 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
543
1431
  const title = document.createElement("h2");
544
1432
  title.className = "cd-composer-title";
545
1433
  title.textContent = "ContextDrop";
1434
+ this.composerTitleEl = title;
546
1435
  headerLeft.appendChild(title);
547
1436
 
548
1437
  const headerActions = document.createElement("div");
549
1438
  headerActions.className = "cd-header-actions";
550
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
+
551
1451
  const minBtn = document.createElement("button");
552
1452
  minBtn.type = "button";
553
1453
  minBtn.className = "cd-icon-btn";
@@ -555,6 +1455,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
555
1455
  minBtn.setAttribute("aria-label", "Minimize chatbox to compact bar");
556
1456
  minBtn.innerHTML = ICON_MINIMIZE;
557
1457
  minBtn.addEventListener("click", () => this.minimizeToCompactBar());
1458
+ this.composerMinBtn = minBtn;
558
1459
 
559
1460
  const closeBtn = document.createElement("button");
560
1461
  closeBtn.type = "button";
@@ -570,7 +1471,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
570
1471
  header.appendChild(headerActions);
571
1472
  composer.appendChild(header);
572
1473
 
573
- // Conversational Chat Thread
574
1474
  const chatThread = document.createElement("div");
575
1475
  chatThread.className = "cd-chat-thread";
576
1476
  chatThread.setAttribute("aria-live", "polite");
@@ -578,213 +1478,1425 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
578
1478
  composer.appendChild(chatThread);
579
1479
  this.renderChatThread();
580
1480
 
581
- // Pinned Elements & Attachments Chip Tray
582
- const tray = document.createElement("div");
583
- tray.className = "cd-tray";
584
- tray.setAttribute("aria-label", "Attached context items");
585
- this.trayEl = tray;
586
- 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
+ }
587
2431
 
588
- // Status message bar
589
- const status = document.createElement("div");
590
- status.className = "cd-status";
591
- status.setAttribute("role", "status");
592
- status.hidden = true;
593
- this.statusEl = status;
594
- composer.appendChild(status);
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
+ }
595
2455
 
596
- // Hidden file input
597
- const fileInput = document.createElement("input");
598
- fileInput.type = "file";
599
- fileInput.multiple = true;
600
- fileInput.accept = this.config.limits.allowed_content_types.join(",");
601
- fileInput.hidden = true;
602
- fileInput.addEventListener("change", () => {
603
- if (fileInput.files) {
604
- void this.handleFilesSelected(Array.from(fileInput.files));
605
- fileInput.value = "";
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
+ }
2462
+
2463
+ if (msg.proposedEdits && msg.proposedEdits.length > 0) {
2464
+ for (const edit of msg.proposedEdits) {
2465
+ card.appendChild(this.buildDiffCardDom(edit));
2466
+ }
2467
+ }
606
2468
  }
607
- });
608
- this.fileInputEl = fileInput;
609
- composer.appendChild(fileInput);
610
2469
 
611
- // Chatbox Prompt Input Shell
612
- const promptShell = document.createElement("div");
613
- promptShell.className = "cd-prompt-shell";
2470
+ this.agentStreamEl.appendChild(card);
2471
+ }
614
2472
 
615
- const textarea = document.createElement("textarea");
616
- textarea.className = "cd-textarea";
617
- textarea.placeholder = this.config.placeholder;
618
- textarea.setAttribute("aria-label", "Feedback description");
619
- textarea.addEventListener("keydown", (ev) => {
620
- if ((ev.metaKey || ev.ctrlKey) && ev.key === "Enter") {
621
- ev.preventDefault();
622
- void this.handleSubmit();
623
- } else if (ev.key === "Escape") {
624
- ev.preventDefault();
625
- this.closeComposer();
626
- }
627
- });
628
- textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
629
- this.textareaEl = textarea;
630
- 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
+ }
631
2488
 
632
- // Toolbar inside prompt shell
633
- const toolbar = document.createElement("div");
634
- toolbar.className = "cd-toolbar";
2489
+ this.agentStreamEl.scrollTop = this.agentStreamEl.scrollHeight;
2490
+ }
635
2491
 
636
- const actions = document.createElement("div");
637
- 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);
638
2496
 
639
- if (this.config.features.element_selection) {
640
- const pickBtn = document.createElement("button");
641
- pickBtn.type = "button";
642
- pickBtn.className = "cd-btn";
643
- pickBtn.setAttribute("aria-label", "Pin HTML element as context");
644
- pickBtn.innerHTML = `${ICON_PIN}<span>Pin</span>`;
645
- pickBtn.addEventListener("click", () => this.startPinSelection());
646
- 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);
647
2531
  }
648
2532
 
649
- if (this.config.features.screenshot_capture) {
650
- const screenshotBtn = document.createElement("button");
651
- screenshotBtn.type = "button";
652
- screenshotBtn.className = "cd-btn";
653
- screenshotBtn.setAttribute("aria-label", "Capture viewport screenshot");
654
- screenshotBtn.innerHTML = `${ICON_CAMERA}<span>Screenshot</span>`;
655
- screenshotBtn.addEventListener("click", () => {
656
- void this.handleViewportScreenshot();
657
- });
658
- 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";
659
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
+ });
660
2562
 
661
- const uploadBtn = document.createElement("button");
662
- uploadBtn.type = "button";
663
- uploadBtn.className = "cd-btn";
664
- uploadBtn.setAttribute("aria-label", "Upload image attachment");
665
- uploadBtn.innerHTML = `${ICON_IMAGE}<span>Image</span>`;
666
- uploadBtn.addEventListener("click", () => this.fileInputEl?.click());
667
- 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
+ });
668
2570
 
669
- const submitBtn = document.createElement("button");
670
- submitBtn.type = "button";
671
- submitBtn.className = "cd-btn cd-btn-primary";
672
- submitBtn.setAttribute("aria-label", "Submit feedback");
673
- submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
674
- submitBtn.addEventListener("click", () => {
675
- void this.handleSubmit();
676
- });
677
- 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
+ }
678
2583
 
679
- toolbar.appendChild(actions);
680
- toolbar.appendChild(submitBtn);
681
- promptShell.appendChild(toolbar);
682
- composer.appendChild(promptShell);
2584
+ footer.appendChild(btnGroup);
2585
+ card.appendChild(footer);
2586
+ return card;
2587
+ }
683
2588
 
684
- // 3. Freely Draggable Floating Pin Dock (visible when chatbox is closed, or draggable launcher)
685
- const pinDock = document.createElement("div");
686
- pinDock.className = "cd-pin-dock";
687
- 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
+ }
688
2615
 
689
- const dockGrip = document.createElement("span");
690
- dockGrip.className = "cd-pin-dock-grip";
691
- dockGrip.title = "Drag to float anywhere on screen";
692
- dockGrip.innerHTML = ICON_GRIP;
693
- this.attachDragHandle(dockGrip);
694
- pinDock.appendChild(dockGrip);
2616
+ public async handleAgentSubmit(): Promise<void> {
2617
+ if (this.isAgentBusy) return;
695
2618
 
696
- if (this.config.features.element_selection) {
697
- const floatingPinBtn = document.createElement("button");
698
- floatingPinBtn.type = "button";
699
- floatingPinBtn.className = "cd-floating-pin-btn";
700
- floatingPinBtn.title = "Pin an element on the page (or drag to move)";
701
- floatingPinBtn.setAttribute("aria-label", "Pin element on page");
702
- floatingPinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>`;
703
- this.attachDragHandle(floatingPinBtn, () => this.startPinSelection());
704
- this.floatingPinBtn = floatingPinBtn;
705
- pinDock.appendChild(floatingPinBtn);
706
- }
707
-
708
- const trigger = document.createElement("button");
709
- trigger.type = "button";
710
- trigger.className = "cd-trigger";
711
- trigger.setAttribute("aria-label", "Open feedback composer");
712
- trigger.setAttribute("aria-expanded", String(this.isOpen));
713
- trigger.innerHTML = `${ICON_CHAT}<span>ContextDrop</span>`;
714
- this.attachDragHandle(trigger, () => this.toggleComposer());
715
- this.triggerBtn = trigger;
716
- 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
+ }
717
2628
 
718
- root.appendChild(compactBar);
719
- root.appendChild(composer);
720
- root.appendChild(pinDock);
721
- 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();
722
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();
723
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
+ }
724
2712
  }
725
2713
 
726
2714
  private syncPinActiveIndicators(pickerActive: boolean): void {
727
- if (this.cornerPinBtn) {
728
- this.cornerPinBtn.classList.toggle("is-active", pickerActive);
729
- this.cornerPinBtn.setAttribute("aria-pressed", String(pickerActive));
730
- }
731
- if (this.floatingPinBtn) {
732
- this.floatingPinBtn.classList.toggle("is-active", pickerActive);
733
- 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
+ }
734
2720
  }
735
2721
  if (this.compactPinBtn) {
2722
+ const smartMode = this.isSmartSelectionMode();
736
2723
  this.compactPinBtn.classList.toggle("is-active", pickerActive);
737
- this.compactPinBtn.innerHTML = pickerActive
738
- ? `${ICON_PIN}<span>Pinning</span>`
739
- : `${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;
740
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;
741
2753
  }
742
2754
 
743
2755
  private syncUiStates(): void {
744
2756
  const pickerActive = this.picker ? this.picker.isActive() : false;
745
- 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;
746
2763
 
747
2764
  if (this.composerEl) {
748
- 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();
749
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
+
750
2829
  if (this.compactBarEl) {
751
2830
  this.compactBarEl.hidden = !(this.isOpen && this.isMinimized);
752
- }
753
- if (this.pinDockEl) {
754
- this.pinDockEl.hidden = this.isOpen;
2831
+ this.compactBarEl.classList.toggle("is-smart-mode", smartMode);
755
2832
  }
756
2833
 
757
- if (this.triggerBtn) {
758
- this.triggerBtn.setAttribute("aria-expanded", String(this.isOpen && !this.isMinimized));
759
- const countBadge =
760
- totalContextCount > 0 ? `<span class="cd-count-pill">${totalContextCount}</span>` : "";
761
- 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);
762
2857
  }
763
2858
 
2859
+ const pinCountHtml =
2860
+ this.elementReferences.length > 0
2861
+ ? `<span class="cd-count-pill">${this.elementReferences.length}</span>`
2862
+ : "";
764
2863
  if (this.cornerPinBtn) {
765
- const pinCount =
766
- this.elementReferences.length > 0
767
- ? `<span class="cd-count-pill">${this.elementReferences.length}</span>`
768
- : "";
769
- 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}`;
770
2879
  }
771
2880
 
772
2881
  this.syncPinActiveIndicators(pickerActive);
773
- this.renderCompactCoachBar(
774
- pickerActive,
775
- this.picker ? this.picker.getCandidateStack().length : 0
776
- );
2882
+ if (!this.isPeelDragging) {
2883
+ this.renderCompactCoachBar(
2884
+ pickerActive,
2885
+ this.picker ? this.picker.getCandidateStack().length : 0
2886
+ );
2887
+ }
777
2888
  }
778
2889
 
779
2890
  private renderCompactCoachBar(pickerActive: boolean, candidateCount: number = 0): void {
780
2891
  if (!this.compactStatusEl) return;
781
2892
  this.compactStatusEl.innerHTML = "";
782
2893
 
2894
+ const smartMode = this.isSmartSelectionMode();
783
2895
  const pinnedCount = this.elementReferences.length;
784
- const totalContextCount = pinnedCount + this.attachments.length;
2896
+ const totalContextCount = this.getVisibleContextCount();
785
2897
 
786
2898
  if (this.compactStepGroupEl) {
787
- this.compactStepGroupEl.hidden = !pickerActive;
2899
+ this.compactStepGroupEl.hidden = !pickerActive || smartMode;
788
2900
  }
789
2901
  if (this.compactLayerUpBtn) {
790
2902
  this.compactLayerUpBtn.disabled = candidateCount <= 1;
@@ -793,11 +2905,25 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
793
2905
  this.compactLayerDownBtn.disabled = candidateCount <= 1;
794
2906
  }
795
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
+
796
2922
  if (pickerActive) {
797
2923
  if (pinnedCount === 0) {
798
2924
  const coach = document.createElement("span");
799
2925
  coach.className = "cd-compact-coach-text";
800
- coach.innerHTML = `<strong>Click</strong><span>element to pin</span><span>·</span><span class="cd-compact-wheel-icon">${ICON_SCROLL_VERTICAL}</span><strong>Scroll</strong><span>layers</span>`;
2926
+ coach.innerHTML = `<strong>Space</strong><span>or click to pin</span><span>·</span><span class="cd-compact-wheel-icon">${ICON_SCROLL_VERTICAL}</span><strong>Scroll</strong><span>layers</span><span>·</span><kbd class="cd-kbd">⌥⇧P</kbd><span>freeze</span>`;
801
2927
  this.compactStatusEl.appendChild(coach);
802
2928
  } else {
803
2929
  const latest = this.elementReferences[pinnedCount - 1];
@@ -831,7 +2957,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
831
2957
 
832
2958
  const addMore = document.createElement("span");
833
2959
  addMore.className = "cd-compact-coach-text";
834
- addMore.textContent = "Click another to add";
2960
+ addMore.innerHTML = `<strong>Space</strong><span>or click to add more</span>`;
835
2961
  this.compactStatusEl.appendChild(addMore);
836
2962
  }
837
2963
 
@@ -852,45 +2978,63 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
852
2978
  return;
853
2979
  }
854
2980
 
855
- // Minimized while not actively in Pin Mode
856
2981
  const summary = document.createElement("span");
857
2982
  summary.className = "cd-compact-coach-text";
858
2983
  summary.textContent =
859
2984
  totalContextCount > 0
860
2985
  ? `${totalContextCount} context item${totalContextCount > 1 ? "s" : ""} attached`
861
- : "Chatbox minimized";
2986
+ : this.isAgentModeActive()
2987
+ ? "Agent sidebar minimized"
2988
+ : "Chatbox minimized";
862
2989
  this.compactStatusEl.appendChild(summary);
863
2990
 
864
2991
  if (this.compactDoneBtn) {
865
2992
  this.compactDoneBtn.className = "cd-btn cd-btn-primary";
866
2993
  this.compactDoneBtn.setAttribute("aria-label", "Return to chatbox");
867
- this.compactDoneBtn.innerHTML = `${ICON_EXPAND}<span>Chat</span>`;
2994
+ this.compactDoneBtn.innerHTML = `${ICON_EXPAND}<span>${this.isAgentModeActive() ? "Agent" : "Chat"}</span>`;
868
2995
  }
869
2996
  }
870
2997
 
871
2998
  private renderChatThread(): void {
872
2999
  if (!this.chatThreadEl) return;
873
3000
  this.chatThreadEl.innerHTML = "";
3001
+ const smartMode = this.isSmartSelectionMode();
874
3002
 
875
3003
  if (this.sessionHistory.length === 0) {
876
- const emptyBox = document.createElement("div");
877
- 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;
878
3009
 
879
- const p1 = document.createElement("p");
880
- p1.className = "cd-chat-empty-text";
881
- 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.";
882
3023
 
883
- const p2 = document.createElement("p");
884
- p2.className = "cd-chat-empty-hint";
885
- p2.textContent =
886
- "Click Pin Element, scroll the wheel to step through overlapping layers, click once to pin, and press Esc when done.";
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.';
887
3028
 
888
- emptyBox.appendChild(p1);
889
- emptyBox.appendChild(p2);
3029
+ emptyBox.appendChild(p1);
3030
+ emptyBox.appendChild(p2);
3031
+ }
890
3032
  this.chatThreadEl.appendChild(emptyBox);
891
3033
  return;
892
3034
  }
893
3035
 
3036
+ this.chatThreadEl.hidden = false;
3037
+
894
3038
  for (const entry of this.sessionHistory) {
895
3039
  const msgCard = document.createElement("div");
896
3040
  msgCard.className = "cd-chat-msg";
@@ -901,17 +3045,22 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
901
3045
 
902
3046
  for (const el of entry.elements) {
903
3047
  const pill = document.createElement("span");
904
- pill.className = "cd-chat-msg-pill";
905
- 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;
906
3050
  pills.appendChild(pill);
907
3051
  }
908
3052
  for (const att of entry.attachments) {
3053
+ if (smartMode && att.attachment_type === "screenshot" && entry.elements.length > 0) {
3054
+ continue;
3055
+ }
909
3056
  const pill = document.createElement("span");
910
- pill.className = "cd-chat-msg-pill";
3057
+ pill.className = smartMode ? "cd-chat-msg-pill is-friendly" : "cd-chat-msg-pill";
911
3058
  pill.textContent = att.label;
912
3059
  pills.appendChild(pill);
913
3060
  }
914
- msgCard.appendChild(pills);
3061
+ if (pills.childNodes.length > 0) {
3062
+ msgCard.appendChild(pills);
3063
+ }
915
3064
  }
916
3065
 
917
3066
  if (entry.message) {
@@ -924,7 +3073,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
924
3073
  const meta = document.createElement("div");
925
3074
  meta.className = "cd-chat-msg-meta";
926
3075
  const idSpan = document.createElement("span");
927
- idSpan.textContent = `Dropped #${entry.id}`;
3076
+ idSpan.textContent = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
928
3077
  const timeSpan = document.createElement("span");
929
3078
  timeSpan.textContent = entry.createdAt;
930
3079
  meta.appendChild(idSpan);
@@ -938,10 +3087,125 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
938
3087
  }
939
3088
 
940
3089
  private renderTray(): void {
941
- if (!this.trayEl) return;
942
- 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
+ }
943
3208
 
944
- // Render ElementReference chips
945
3209
  for (const elRef of this.elementReferences) {
946
3210
  const chip = document.createElement("div");
947
3211
  chip.className = "cd-chip";
@@ -965,10 +3229,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
965
3229
  chip.appendChild(badge);
966
3230
  chip.appendChild(label);
967
3231
 
968
- if (
969
- this.config.features.screenshot_capture &&
970
- domNode
971
- ) {
3232
+ if (this.config.features.screenshot_capture && domNode) {
972
3233
  const snapBtn = document.createElement("button");
973
3234
  snapBtn.type = "button";
974
3235
  snapBtn.className = "cd-chip-action";
@@ -989,10 +3250,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
989
3250
  removeBtn.addEventListener("click", () => this.removeElementReference(elRef.client_ref));
990
3251
 
991
3252
  chip.appendChild(removeBtn);
992
- this.trayEl.appendChild(chip);
3253
+ trayContainer.appendChild(chip);
993
3254
  }
994
3255
 
995
- // Render Attachment chips (uploaded images & screenshots)
996
3256
  for (const att of this.attachments) {
997
3257
  const chip = document.createElement("div");
998
3258
  chip.className = "cd-chip";
@@ -1024,7 +3284,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1024
3284
  chip.appendChild(badge);
1025
3285
  chip.appendChild(label);
1026
3286
  chip.appendChild(removeBtn);
1027
- this.trayEl.appendChild(chip);
3287
+ trayContainer.appendChild(chip);
1028
3288
  }
1029
3289
  }
1030
3290
 
@@ -1150,8 +3410,68 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1150
3410
  }
1151
3411
  }
1152
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
+
1153
3468
  public async handleSubmit(): Promise<void> {
1154
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
+ }
1155
3475
 
1156
3476
  const message = (this.textareaEl?.value || "").trim();
1157
3477
  if (
@@ -1159,7 +3479,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1159
3479
  this.attachments.length === 0 &&
1160
3480
  this.elementReferences.length === 0
1161
3481
  ) {
1162
- 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
+ );
1163
3488
  return;
1164
3489
  }
1165
3490
 
@@ -1184,6 +3509,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1184
3509
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
1185
3510
  metadata: {
1186
3511
  ...this.customMetadata,
3512
+ environment: this.config.environment,
3513
+ selection_mode: smartMode ? "smart" : "verbose",
1187
3514
  viewport: {
1188
3515
  width: typeof window !== "undefined" ? window.innerWidth : 0,
1189
3516
  height: typeof window !== "undefined" ? window.innerHeight : 0
@@ -1207,7 +3534,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1207
3534
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
1208
3535
  this.sessionHistory.push({
1209
3536
  id: res?.id ?? this.sessionHistory.length + 1,
1210
- message: message || "(Context drop without text)",
3537
+ message:
3538
+ message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
1211
3539
  createdAt: timeLabel,
1212
3540
  elements: submittedElements,
1213
3541
  attachments: submittedAttachments
@@ -1223,7 +3551,10 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1223
3551
  this.renderTray();
1224
3552
  this.renderChatThread();
1225
3553
  this.syncUiStates();
1226
- this.showStatus("Context drop saved.", "success");
3554
+ this.showStatus(
3555
+ smartMode ? "Thanks! Your feedback was sent." : "Context drop saved.",
3556
+ "success"
3557
+ );
1227
3558
  } catch (err) {
1228
3559
  const msg = err instanceof Error ? err.message : "Failed to submit feedback.";
1229
3560
  this.showStatus(msg, "error");
@@ -1236,11 +3567,21 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1236
3567
  }
1237
3568
  }
1238
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
+
1239
3578
  private showStatus(text: string, kind: "error" | "success"): void {
1240
- if (!this.statusEl) return;
1241
- this.statusEl.textContent = text;
1242
- this.statusEl.className = `cd-status ${kind}`;
1243
- 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
+ }
1244
3585
  }
1245
3586
  }
1246
3587