context_drop 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +330 -116
  3. data/Rakefile +110 -1
  4. data/SPEC.md +74 -26
  5. data/app/assets/javascripts/context_drop/context_drop.js +6329 -682
  6. data/app/controllers/context_drop/agent_controller.rb +170 -0
  7. data/app/controllers/context_drop/application_controller.rb +52 -3
  8. data/app/controllers/context_drop/configs_controller.rb +12 -2
  9. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  10. data/app/controllers/context_drop/feedbacks_controller.rb +396 -20
  11. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  12. data/app/helpers/context_drop/widget_helper.rb +11 -1
  13. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  14. data/app/javascript/context_drop/__tests__/widget.test.ts +1015 -89
  15. data/app/javascript/context_drop/api-client.ts +422 -19
  16. data/app/javascript/context_drop/element-picker.ts +186 -34
  17. data/app/javascript/context_drop/icons.ts +28 -0
  18. data/app/javascript/context_drop/markdown.ts +146 -0
  19. data/app/javascript/context_drop/sanitizer.ts +413 -2
  20. data/app/javascript/context_drop/screenshot.ts +103 -9
  21. data/app/javascript/context_drop/styles.ts +1705 -248
  22. data/app/javascript/context_drop/types.ts +243 -6
  23. data/app/javascript/context_drop/widget.ts +3318 -294
  24. data/app/models/context_drop/feedback.rb +88 -8
  25. data/app/services/context_drop/ownership_token.rb +114 -0
  26. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +13 -0
  27. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +19 -0
  28. data/app/views/layouts/context_drop/application.html.erb +6 -0
  29. data/config/routes.rb +22 -0
  30. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  31. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  32. data/lib/context_drop/agent/key_store.rb +290 -0
  33. data/lib/context_drop/agent/llm_client.rb +413 -0
  34. data/lib/context_drop/agent/orchestrator.rb +314 -0
  35. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  36. data/lib/context_drop/configuration.rb +242 -3
  37. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  38. data/lib/context_drop/mcp/environment_router.rb +115 -0
  39. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +90 -9
  40. data/lib/context_drop/mcp/remote_client.rb +120 -0
  41. data/lib/context_drop/mcp/server.rb +9 -2
  42. data/lib/context_drop/mcp/tools/get_feedback.rb +62 -5
  43. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +29 -4
  44. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  45. data/lib/context_drop/mcp/tools/list_feedbacks.rb +195 -23
  46. data/lib/context_drop/mcp/tools/update_feedback_status.rb +48 -5
  47. data/lib/context_drop/version.rb +1 -1
  48. data/lib/context_drop.rb +8 -2
  49. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  50. metadata +14 -2
@@ -1,40 +1,136 @@
1
1
  import type {
2
+ AgentChatMessage,
3
+ AgentProviderInfo,
4
+ AgentStatusResponse,
5
+ ContextDropApiClientOptions,
6
+ CrossEnvFeedbackItem,
2
7
  ElementReferenceSnapshot,
3
8
  FeedbackSubmissionPayload,
9
+ FeedbackUpdatePayload,
10
+ OwnFeedbackRecord,
4
11
  PendingAttachmentItem,
12
+ ProposedFileEdit,
13
+ SelectionMode,
14
+ SessionFeedbackAttachmentItem,
5
15
  SessionFeedbackEntry,
6
16
  WidgetConfig,
7
- WidgetPosition
17
+ WidgetPosition,
18
+ WidgetSurfaceMode
8
19
  } from "./types.ts";
9
- import { MANDATORY_EXCLUDED_SELECTORS } from "./sanitizer.ts";
20
+ import { MANDATORY_EXCLUDED_SELECTORS, describeSmartComponent } from "./sanitizer.ts";
10
21
  import {
11
22
  ICON_CAMERA,
12
- ICON_CHAT,
13
23
  ICON_CHECK,
14
24
  ICON_CHEVRON_DOWN,
25
+ ICON_CHEVRON_RIGHT,
15
26
  ICON_CHEVRON_UP,
16
27
  ICON_CLOSE,
28
+ ICON_CODE_PROMPT,
29
+ ICON_EDIT,
17
30
  ICON_EXPAND,
31
+ ICON_FILE_CODE,
18
32
  ICON_GRIP,
19
33
  ICON_IMAGE,
34
+ ICON_INBOX,
35
+ ICON_KEY,
20
36
  ICON_MINIMIZE,
21
37
  ICON_PIN,
38
+ ICON_PLUS,
39
+ ICON_PUSH_LAYOUT,
22
40
  ICON_SCROLL_VERTICAL,
23
- ICON_SEND
41
+ ICON_SEND,
42
+ ICON_SHIELD,
43
+ ICON_SIDEBAR,
44
+ ICON_SUN,
45
+ ICON_MOON,
46
+ ICON_TRASH,
47
+ ICON_UNDO
24
48
  } from "./icons.ts";
25
49
  import { WIDGET_SHADOW_STYLES } from "./styles.ts";
26
50
  import { ContextDropApiClient } from "./api-client.ts";
27
51
  import { ElementPicker } from "./element-picker.ts";
28
- import { captureElementScreenshot, captureViewportScreenshot } from "./screenshot.ts";
52
+ import {
53
+ captureElementScreenshot,
54
+ captureSurroundingContextScreenshot,
55
+ captureViewportScreenshot
56
+ } from "./screenshot.ts";
57
+ import { buildUnifiedDiffElement, renderSafeMarkdown } from "./markdown.ts";
58
+
59
+ const CORNER_SNAP_ZONE_PX = 68;
60
+ const PEEL_DRAG_THRESHOLD_PX = 6;
61
+
62
+ const DEFAULT_PROVIDERS_FALLBACK: AgentProviderInfo[] = [
63
+ {
64
+ id: "anthropic",
65
+ label: "Anthropic Claude",
66
+ configured: false,
67
+ source: null,
68
+ env_var_hint: "ANTHROPIC_API_KEY",
69
+ masked_key: null,
70
+ model: "claude-sonnet-4-20250514",
71
+ default_model: "claude-sonnet-4-20250514",
72
+ models: ["claude-sonnet-4-20250514", "claude-3-7-sonnet-latest", "claude-3-5-haiku-latest"],
73
+ supports_base_url: false
74
+ },
75
+ {
76
+ id: "gemini",
77
+ label: "Google Gemini",
78
+ configured: false,
79
+ source: null,
80
+ env_var_hint: "GEMINI_API_KEY",
81
+ masked_key: null,
82
+ model: "gemini-2.5-pro",
83
+ default_model: "gemini-2.5-pro",
84
+ models: ["gemini-2.5-pro", "gemini-2.5-flash"],
85
+ supports_base_url: false
86
+ },
87
+ {
88
+ id: "openai",
89
+ label: "OpenAI",
90
+ configured: false,
91
+ source: null,
92
+ env_var_hint: "OPENAI_API_KEY",
93
+ masked_key: null,
94
+ model: "gpt-4.1",
95
+ default_model: "gpt-4.1",
96
+ models: ["gpt-4.1", "gpt-4.1-mini", "o4-mini"],
97
+ supports_base_url: false
98
+ },
99
+ {
100
+ id: "custom",
101
+ label: "OpenAI-Compatible (OpenRouter / Ollama)",
102
+ configured: false,
103
+ source: null,
104
+ env_var_hint: "CONTEXT_DROP_LLM_API_KEY",
105
+ masked_key: null,
106
+ model: "anthropic/claude-sonnet-4",
107
+ default_model: "anthropic/claude-sonnet-4",
108
+ models: ["anthropic/claude-sonnet-4", "google/gemini-2.5-pro", "llama3.3"],
109
+ supports_base_url: true,
110
+ base_url: "https://openrouter.ai/api/v1"
111
+ }
112
+ ];
113
+
114
+ 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>`;
115
+
116
+ const DEFAULT_VERBOSE_PLACEHOLDER = "Describe the issue or drop context from the page...";
117
+ const DEFAULT_SMART_PLACEHOLDER = "Tell us what's happening...";
118
+
119
+ export const DEFAULT_SIDEBAR_WIDTH = 560;
29
120
 
30
121
  const DEFAULT_CONFIG: WidgetConfig = {
31
122
  enabled: true,
32
- position: "top_left",
33
- placeholder: "Describe the issue or drop context from the page...",
123
+ environment: "production",
124
+ position: "bottom_right",
125
+ placeholder: DEFAULT_VERBOSE_PLACEHOLDER,
126
+ agent: {
127
+ enabled: false
128
+ },
34
129
  features: {
35
130
  element_selection: true,
36
131
  screenshot_capture: true,
37
- element_capture_padding: 16
132
+ element_capture_padding: 16,
133
+ smart_capture_padding: 84
38
134
  },
39
135
  limits: {
40
136
  max_attachments: 10,
@@ -54,24 +150,83 @@ const BaseHTMLElement: typeof HTMLElement =
54
150
  : (class {} as unknown as typeof HTMLElement);
55
151
 
56
152
  export class ContextDropWidgetElement extends BaseHTMLElement {
153
+ public static get observedAttributes(): string[] {
154
+ return [
155
+ "data-endpoint",
156
+ "data-position",
157
+ "data-placeholder",
158
+ "data-config",
159
+ "data-metadata",
160
+ "data-credentials",
161
+ "data-selection-mode",
162
+ "data-environment",
163
+ "data-theme",
164
+ "data-cd-theme"
165
+ ];
166
+ }
167
+
57
168
  public shadow: ShadowRoot | null = null;
58
169
  private config: WidgetConfig = structuredClone(DEFAULT_CONFIG);
59
170
  private customMetadata: Record<string, unknown> = {};
171
+ private customHeaders: Record<string, string> = {};
60
172
  private apiClient: ContextDropApiClient = new ContextDropApiClient("/context_drop");
61
173
  private picker: ElementPicker | null = null;
62
174
 
63
175
  private isOpen: boolean = false;
64
176
  private isMinimized: boolean = false;
65
177
  private isSubmitting: boolean = false;
178
+ private isAgentBusy: boolean = false;
179
+ private surfaceMode: WidgetSurfaceMode = "feedback";
180
+ private sidebarSide: "right" | "left" = "right";
181
+ private sidebarWidth: number = DEFAULT_SIDEBAR_WIDTH;
182
+ private currentTheme: "light" | "dark" = "light";
183
+ private composerThemeToggleBtn: HTMLButtonElement | null = null;
184
+ private sidebarThemeToggleBtn: HTMLButtonElement | null = null;
185
+ private pushPageLayout: boolean = false;
66
186
  private freePos: { left: number; top: number } | null = null;
187
+ private isPeelDragging: boolean = false;
188
+ private customPlaceholderSet: boolean = false;
189
+ private pendingSmartCaptures: Set<Promise<void>> = new Set();
67
190
 
68
191
  private elementReferences: ElementReferenceSnapshot[] = [];
69
192
  private elementDomNodes: Map<string, Element> = new Map();
70
193
  private attachments: PendingAttachmentItem[] = [];
71
194
  private sessionHistory: SessionFeedbackEntry[] = [];
72
-
195
+ private ownFeedbacksLoaded: boolean = false;
196
+ private inFlightOwnFeedbacksPromise: Promise<SessionFeedbackEntry[]> | null = null;
197
+ private editingFeedbackId: string | null = null;
198
+ private confirmingDeleteId: string | null = null;
199
+ private deletingFeedbackId: string | null = null;
200
+ private stashedDraftBeforeEdit: {
201
+ message: string;
202
+ elementReferences: ElementReferenceSnapshot[];
203
+ elementDomNodes: Map<string, Element>;
204
+ attachments: PendingAttachmentItem[];
205
+ } | null = null;
206
+
207
+ // Local Agent state
208
+ private agentStatusLoaded: boolean = false;
209
+ private agentWorkspaceName: string = "rails-app";
210
+ private agentMcpEnvironments: string[] = ["local"];
211
+ private agentProviders: AgentProviderInfo[] = structuredClone(DEFAULT_PROVIDERS_FALLBACK);
212
+ private activeProviderId: string = "anthropic";
213
+ private selectedVaultProviderId: string = "anthropic";
214
+ private isByokDrawerOpen: boolean = false;
215
+ private isFeedbacksDrawerOpen: boolean = false;
216
+ private feedbacksEnvFilter: string = "all";
217
+ private crossEnvFeedbacks: CrossEnvFeedbackItem[] = [];
218
+ private isLoadingFeedbacks: boolean = false;
219
+ private agentMessages: AgentChatMessage[] = [];
220
+
221
+ // Shadow DOM references
73
222
  private rootContainer: HTMLDivElement | null = null;
74
- private composerEl: HTMLDivElement | null = null;
223
+ private bookCornerBtn: HTMLButtonElement | null = null;
224
+ private bookCornerCountEl: HTMLSpanElement | null = null;
225
+ private bookCornerAgentDotEl: HTMLSpanElement | null = null;
226
+ private bookCornerHintEl: HTMLSpanElement | null = null;
227
+ private dragPinEl: HTMLDivElement | null = null;
228
+ private cornerSnapGhostEl: HTMLDivElement | null = null;
229
+
75
230
  private compactBarEl: HTMLDivElement | null = null;
76
231
  private compactStatusEl: HTMLDivElement | null = null;
77
232
  private compactStepGroupEl: HTMLDivElement | null = null;
@@ -79,26 +234,119 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
79
234
  private compactLayerDownBtn: HTMLButtonElement | null = null;
80
235
  private compactDoneBtn: HTMLButtonElement | null = null;
81
236
  private compactPinBtn: HTMLButtonElement | null = null;
82
- private pinDockEl: HTMLDivElement | null = null;
83
- private floatingPinBtn: HTMLButtonElement | null = null;
84
- private triggerBtn: HTMLButtonElement | null = null;
237
+
238
+ // Floating Feedback Composer elements
239
+ private composerEl: HTMLDivElement | null = null;
240
+ private composerTitleEl: HTMLHeadingElement | null = null;
241
+ private composerMinBtn: HTMLButtonElement | null = null;
85
242
  private cornerPinBtn: HTMLButtonElement | null = null;
243
+ private composerModeSwitchWrap: HTMLDivElement | null = null;
244
+ private composerToolbarPickBtn: HTMLButtonElement | null = null;
245
+ private composerToolbarScreenshotBtn: HTMLButtonElement | null = null;
246
+ private composerToolbarUploadBtn: HTMLButtonElement | null = null;
86
247
  private chatThreadEl: HTMLDivElement | null = null;
248
+ private editBannerEl: HTMLDivElement | null = null;
249
+ private editBannerInfoEl: HTMLSpanElement | null = null;
87
250
  private textareaEl: HTMLTextAreaElement | null = null;
88
251
  private trayEl: HTMLDivElement | null = null;
89
252
  private statusEl: HTMLDivElement | null = null;
90
253
  private fileInputEl: HTMLInputElement | null = null;
91
254
  private submitBtn: HTMLButtonElement | null = null;
255
+
256
+ // Docked Local Agent Sidebar elements
257
+ private agentSidebarEl: HTMLElement | null = null;
258
+ private sidebarPinBtn: HTMLButtonElement | null = null;
259
+ private sidebarEnvPillEl: HTMLSpanElement | null = null;
260
+ private sidebarPushBtn: HTMLButtonElement | null = null;
261
+ private keyDotEl: HTMLSpanElement | null = null;
262
+ private providerPillLabelEl: HTMLSpanElement | null = null;
263
+ private keysToggleBtn: HTMLButtonElement | null = null;
264
+ private feedbacksToggleBtn: HTMLButtonElement | null = null;
265
+ private byokDrawerEl: HTMLDivElement | null = null;
266
+ private byokProviderSelect: HTMLSelectElement | null = null;
267
+ private byokModelInput: HTMLInputElement | null = null;
268
+ private byokModelPresetsSelect: HTMLSelectElement | null = null;
269
+ private byokBaseUrlField: HTMLDivElement | null = null;
270
+ private byokBaseUrlInput: HTMLInputElement | null = null;
271
+ private byokKeySourceBadge: HTMLSpanElement | null = null;
272
+ private byokKeyInput: HTMLInputElement | null = null;
273
+ private feedbacksDrawerEl: HTMLDivElement | null = null;
274
+ private feedbacksTabsEl: HTMLDivElement | null = null;
275
+ private feedbacksListEl: HTMLDivElement | null = null;
276
+ private agentStreamEl: HTMLDivElement | null = null;
277
+ private agentTrayEl: HTMLDivElement | null = null;
278
+ private agentStatusEl: HTMLDivElement | null = null;
279
+ private agentTextareaEl: HTMLTextAreaElement | null = null;
280
+ private agentSendBtn: HTMLButtonElement | null = null;
281
+
92
282
  private lastPointerX: number = 0;
93
283
  private lastPointerY: number = 0;
94
- private boundTrackPointer: (ev: MouseEvent) => void;
95
- private boundGlobalKeyDown: (ev: KeyboardEvent) => void;
284
+ private boundTrackPointer: (ev: MouseEvent) => void = () => {};
285
+ private boundGlobalKeyDown: (ev: KeyboardEvent) => void = () => {};
286
+ private cancelActivePeelDrag: (() => void) | null = null;
287
+
288
+ public attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {
289
+ if (oldValue === newValue) return;
290
+ if ((name === "data-theme" || name === "data-cd-theme") && (newValue === "dark" || newValue === "light")) {
291
+ this.applyTheme(newValue, false);
292
+ } else if (name === "data-position" && newValue) {
293
+ this.setCornerPosition(newValue as WidgetPosition);
294
+ } else if (name === "data-endpoint" && newValue && this.shadow) {
295
+ this.setEndpoint(newValue);
296
+ } else if (name === "data-credentials" && newValue && this.shadow) {
297
+ if (newValue === "same-origin" || newValue === "include" || newValue === "omit") {
298
+ this.apiClient.setCredentials(newValue);
299
+ }
300
+ } else if (name === "data-placeholder" && newValue && this.shadow) {
301
+ this.setWidgetConfig({ placeholder: newValue });
302
+ } else if (name === "data-metadata" && this.shadow) {
303
+ if (newValue) {
304
+ try {
305
+ this.customMetadata = JSON.parse(newValue) as Record<string, unknown>;
306
+ } catch {
307
+ this.customMetadata = {};
308
+ }
309
+ } else {
310
+ this.customMetadata = {};
311
+ }
312
+ } else if (name === "data-selection-mode" && newValue && this.shadow) {
313
+ if (newValue === "smart" || newValue === "verbose") {
314
+ this.setWidgetConfig({ features: { ...this.config.features, selection_mode: newValue } });
315
+ }
316
+ } else if (name === "data-environment" && newValue && this.shadow) {
317
+ this.setWidgetConfig({ environment: newValue });
318
+ } else if (name === "data-config" && newValue && this.shadow) {
319
+ try {
320
+ const parsed = JSON.parse(newValue) as Partial<WidgetConfig>;
321
+ this.setWidgetConfig(parsed);
322
+ } catch {
323
+ // Ignore malformed JSON
324
+ }
325
+ }
326
+ }
96
327
 
97
328
  public connectedCallback(): void {
98
329
  if (!this.shadow) {
99
330
  this.shadow = this.attachShadow({ mode: "open" });
100
331
  }
101
332
  this.readDataAttributes();
333
+ this.initTheme();
334
+
335
+ try {
336
+ const storedWidth =
337
+ typeof localStorage !== "undefined" ? localStorage.getItem("context_drop_sidebar_width") : null;
338
+ if (storedWidth) {
339
+ const parsed = parseInt(storedWidth, 10);
340
+ if (!Number.isNaN(parsed) && parsed >= 360 && parsed <= 920) {
341
+ // If stored width was from the old cramped v0.2-alpha default (<= 440px), upgrade to DEFAULT_SIDEBAR_WIDTH
342
+ this.sidebarWidth = parsed <= 440 ? DEFAULT_SIDEBAR_WIDTH : parsed;
343
+ }
344
+ }
345
+ } catch {
346
+ // Non-fatal
347
+ }
348
+
349
+ this.surfaceMode = this.config.agent?.enabled ? "agent" : "feedback";
102
350
  this.renderShadowDom();
103
351
 
104
352
  this.boundTrackPointer = (ev: MouseEvent) => {
@@ -107,8 +355,35 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
107
355
  };
108
356
 
109
357
  this.boundGlobalKeyDown = (ev: KeyboardEvent) => {
110
- // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode from anywhere on the host page
358
+ if (ev.key === "Escape" && this.isPeelDragging && this.cancelActivePeelDrag) {
359
+ ev.preventDefault();
360
+ ev.stopPropagation();
361
+ this.cancelActivePeelDrag();
362
+ return;
363
+ }
364
+
365
+ if (
366
+ ev.key === "Escape" &&
367
+ !(this.picker && this.picker.isActive()) &&
368
+ this.isOpen &&
369
+ !this.isMinimized &&
370
+ !this.isAgentModeActive()
371
+ ) {
372
+ if (this.confirmingDeleteId !== null) {
373
+ ev.preventDefault();
374
+ this.cancelDeleteFeedback();
375
+ return;
376
+ }
377
+ if (this.editingFeedbackId !== null) {
378
+ ev.preventDefault();
379
+ this.cancelEditingFeedback();
380
+ return;
381
+ }
382
+ }
383
+
384
+ // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
111
385
  if (
386
+ !this.isSmartSelectionMode() &&
112
387
  ev.altKey &&
113
388
  ev.shiftKey &&
114
389
  (ev.code === "KeyP" || (typeof ev.key === "string" && ev.key.toLowerCase() === "p"))
@@ -131,13 +406,21 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
131
406
  onSelect: (snapshot, el) => {
132
407
  const added = this.addElementReference(snapshot, el);
133
408
  if (added) {
134
- const count = this.elementReferences.length;
135
- this.showStatus(
136
- count === 1
137
- ? `Pinned ${snapshot.selector}`
138
- : `Pinned ${count} elements (latest: ${snapshot.selector})`,
139
- "success"
140
- );
409
+ if (this.isSmartSelectionMode()) {
410
+ this.hideStatus();
411
+ if (this.config.features.screenshot_capture) {
412
+ const friendlyLabel = this.getElementFriendlyLabel(snapshot, el);
413
+ void this.captureSmartSurroundingContext(el, snapshot.client_ref, friendlyLabel);
414
+ }
415
+ } else {
416
+ const count = this.elementReferences.length;
417
+ this.showStatus(
418
+ count === 1
419
+ ? `Pinned ${snapshot.selector}`
420
+ : `Pinned ${count} elements (latest: ${snapshot.selector})`,
421
+ "success"
422
+ );
423
+ }
141
424
  }
142
425
  this.syncUiStates();
143
426
  },
@@ -145,36 +428,62 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
145
428
  this.removeElementReference(clientRef);
146
429
  },
147
430
  onExit: () => {
431
+ if (this.isPeelDragging) return;
148
432
  this.isMinimized = false;
149
433
  this.openComposer();
150
434
  this.syncUiStates();
151
435
  },
152
- canSelectMore: () => this.elementReferences.length < this.config.limits.max_element_references,
436
+ canSelectMore: () =>
437
+ this.isPeelDragging ||
438
+ this.elementReferences.length < this.config.limits.max_element_references,
153
439
  getExcludedSelectors: () => this.config.privacy.excluded_selectors,
440
+ getSelectionMode: () => (this.isSmartSelectionMode() ? "smart" : "verbose"),
154
441
  getPinnedElements: () =>
155
442
  this.elementReferences
156
443
  .map((ref) => {
157
444
  const node = this.elementDomNodes.get(ref.client_ref);
445
+ const friendlyLabel =
446
+ typeof ref.metadata?.friendly_label === "string"
447
+ ? ref.metadata.friendly_label
448
+ : undefined;
158
449
  return node
159
- ? { clientRef: ref.client_ref, selector: ref.selector, element: node }
450
+ ? { clientRef: ref.client_ref, selector: ref.selector, friendlyLabel, element: node }
160
451
  : null;
161
452
  })
162
453
  .filter(
163
- (item): item is { clientRef: string; selector: string; element: Element } =>
164
- item !== null
454
+ (
455
+ item
456
+ ): item is {
457
+ clientRef: string;
458
+ selector: string;
459
+ friendlyLabel: string | undefined;
460
+ element: Element;
461
+ } => item !== null
165
462
  ),
166
463
  onStateChange: (state) => {
167
464
  this.syncPinActiveIndicators(state.active);
168
- this.renderCompactCoachBar(state.active, state.candidateStack.length);
465
+ if (!this.isPeelDragging) {
466
+ this.renderCompactCoachBar(state.active, state.candidateStack.length);
467
+ }
169
468
  }
170
469
  });
470
+
471
+ const hasInlineConfig =
472
+ typeof this.hasAttribute === "function" && this.hasAttribute("data-config");
473
+ if (!hasInlineConfig && typeof fetch === "function") {
474
+ void this.hydrateConfigFromServer();
475
+ }
171
476
  }
172
477
 
173
478
  public disconnectedCallback(): void {
479
+ if (this.cancelActivePeelDrag) {
480
+ this.cancelActivePeelDrag();
481
+ }
174
482
  if (this.picker && this.picker.isActive()) {
175
- this.picker.stop();
483
+ this.picker.stop({ silent: true });
176
484
  }
177
485
  this.picker?.hideExternalPreview();
486
+ this.syncHostPagePushMargin(false);
178
487
 
179
488
  if (typeof window !== "undefined") {
180
489
  window.removeEventListener("mousemove", this.boundTrackPointer, { capture: true });
@@ -186,6 +495,110 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
186
495
  return this.config;
187
496
  }
188
497
 
498
+ public setEndpoint(endpoint: string, options: ContextDropApiClientOptions = {}): void {
499
+ const resolvedCredentials =
500
+ options.credentials ||
501
+ (this.getAttribute("data-credentials") as RequestCredentials | null) ||
502
+ "same-origin";
503
+ const resolvedHeaders = options.headers || this.customHeaders;
504
+ this.customHeaders = { ...resolvedHeaders };
505
+ this.ownFeedbacksLoaded = false;
506
+ this.inFlightOwnFeedbacksPromise = null;
507
+ this.apiClient = new ContextDropApiClient(endpoint || "/context_drop", {
508
+ credentials: resolvedCredentials,
509
+ headers: this.customHeaders
510
+ });
511
+ }
512
+
513
+ public setHeaders(headers: Record<string, string>): void {
514
+ this.customHeaders = { ...headers };
515
+ this.apiClient.setHeaders(this.customHeaders);
516
+ }
517
+
518
+ public setCredentials(credentials: RequestCredentials): void {
519
+ this.apiClient.setCredentials(credentials);
520
+ }
521
+
522
+ public setCustomMetadata(metadata: Record<string, unknown>): void {
523
+ this.customMetadata = { ...metadata };
524
+ }
525
+
526
+ private emitWidgetEvent(name: string, detail?: Record<string, unknown>): void {
527
+ if (typeof CustomEvent !== "function" || typeof this.dispatchEvent !== "function") {
528
+ return;
529
+ }
530
+ try {
531
+ this.dispatchEvent(
532
+ new CustomEvent(name, {
533
+ bubbles: true,
534
+ composed: true,
535
+ detail
536
+ })
537
+ );
538
+ } catch {
539
+ // Non-fatal in synthetic DOM environments
540
+ }
541
+ }
542
+
543
+ public setWidgetConfig(partial: Partial<WidgetConfig>): void {
544
+ const wasAgentEnabled = Boolean(this.config.agent?.enabled);
545
+ if (
546
+ typeof partial.placeholder === "string" &&
547
+ partial.placeholder !== DEFAULT_VERBOSE_PLACEHOLDER &&
548
+ partial.placeholder !== DEFAULT_SMART_PLACEHOLDER
549
+ ) {
550
+ this.customPlaceholderSet = true;
551
+ }
552
+ this.config = {
553
+ ...this.config,
554
+ ...partial,
555
+ agent: { ...(this.config.agent || { enabled: false }), ...(partial.agent || {}) },
556
+ features: { ...this.config.features, ...(partial.features || {}) },
557
+ limits: { ...this.config.limits, ...(partial.limits || {}) },
558
+ privacy: { ...this.config.privacy, ...(partial.privacy || {}) }
559
+ };
560
+ if (partial.csrf_token) {
561
+ this.apiClient.setCsrfToken(partial.csrf_token);
562
+ }
563
+ if (partial.position) {
564
+ this.setCornerPosition(partial.position);
565
+ }
566
+ const nowAgentEnabled = Boolean(this.config.agent?.enabled);
567
+ if (nowAgentEnabled && !wasAgentEnabled) {
568
+ this.surfaceMode = "agent";
569
+ if (this.isOpen) {
570
+ void this.ensureAgentStatusLoaded();
571
+ }
572
+ } else if (!nowAgentEnabled) {
573
+ this.surfaceMode = "feedback";
574
+ }
575
+ this.renderTray();
576
+ this.renderChatThread();
577
+ this.syncUiStates();
578
+ }
579
+
580
+ public getSurfaceMode(): WidgetSurfaceMode {
581
+ return this.isAgentModeActive() ? "agent" : "feedback";
582
+ }
583
+
584
+ public setSurfaceMode(mode: WidgetSurfaceMode): void {
585
+ if (mode === "agent" && !this.config.agent?.enabled) {
586
+ return;
587
+ }
588
+ this.surfaceMode = mode;
589
+ if (this.isOpen) {
590
+ if (mode === "agent") {
591
+ void this.ensureAgentStatusLoaded();
592
+ } else if (!this.isMinimized) {
593
+ void this.ensureOwnFeedbacksLoaded();
594
+ }
595
+ }
596
+ this.renderTray();
597
+ this.renderChatThread();
598
+ this.syncUiStates();
599
+ this.focusActiveInput();
600
+ }
601
+
189
602
  public getElementReferences(): ElementReferenceSnapshot[] {
190
603
  return [...this.elementReferences];
191
604
  }
@@ -198,23 +611,361 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
198
611
  return [...this.sessionHistory];
199
612
  }
200
613
 
614
+ public getEditingFeedbackId(): string | null {
615
+ return this.editingFeedbackId;
616
+ }
617
+
618
+ private formatTimestampLabel(isoOrLabel?: string): string {
619
+ if (isoOrLabel && /^\d{2}:\d{2}$/.test(isoOrLabel.trim())) {
620
+ return isoOrLabel.trim();
621
+ }
622
+ const parsed = isoOrLabel ? new Date(isoOrLabel) : new Date();
623
+ const valid = Number.isNaN(parsed.getTime()) ? new Date() : parsed;
624
+ return `${String(valid.getHours()).padStart(2, "0")}:${String(valid.getMinutes()).padStart(2, "0")}`;
625
+ }
626
+
627
+ private mapOwnRecordToSessionEntry(
628
+ record: OwnFeedbackRecord,
629
+ existingEntry?: SessionFeedbackEntry
630
+ ): SessionFeedbackEntry {
631
+ const smartMode = this.isSmartSelectionMode();
632
+ const rawMessage = typeof record.message === "string" ? record.message : "";
633
+ const displayMessage =
634
+ rawMessage || (smartMode ? "(Highlighted page area)" : "(Context drop without text)");
635
+ const token =
636
+ record.ownership_token ||
637
+ existingEntry?.ownershipToken ||
638
+ this.apiClient.getOwnershipToken(record.id) ||
639
+ undefined;
640
+ const isEdited = Boolean(
641
+ record.created_at && record.updated_at && record.updated_at !== record.created_at
642
+ );
643
+
644
+ const serverAttachments = Array.isArray(record.attachments) ? record.attachments : [];
645
+ const mappedAttachments: SessionFeedbackAttachmentItem[] = serverAttachments.map((att, idx) => {
646
+ const existingAtt = existingEntry?.attachments.find(
647
+ (a) =>
648
+ (a.server_id !== undefined && String(a.server_id) === String(att.id)) ||
649
+ (a.server_id === undefined &&
650
+ idx < (existingEntry?.attachments.length || 0) &&
651
+ existingEntry?.attachments[idx]?.filename === att.filename)
652
+ );
653
+
654
+ const previewUrl =
655
+ existingAtt?.preview_url &&
656
+ (existingAtt.preview_url.startsWith("data:") || existingAtt.preview_url.startsWith("blob:"))
657
+ ? existingAtt.preview_url
658
+ : this.apiClient.buildAttachmentPreviewUrl(record.id, att.id, token);
659
+
660
+ const meta =
661
+ att.metadata && typeof att.metadata === "object" && !Array.isArray(att.metadata)
662
+ ? { ...att.metadata }
663
+ : existingAtt?.metadata
664
+ ? { ...existingAtt.metadata }
665
+ : {};
666
+
667
+ let label = existingAtt?.label || "";
668
+ if (!label) {
669
+ if (meta.auto_smart_context === true && typeof meta.friendly_label === "string") {
670
+ label = `Context around ${meta.friendly_label}`;
671
+ } else if (att.filename) {
672
+ label = att.filename;
673
+ } else {
674
+ label = att.attachment_type === "screenshot" ? "Screenshot" : "Attached image";
675
+ }
676
+ }
677
+
678
+ return {
679
+ id: existingAtt?.id || `srv_att_${record.id}_${att.id}`,
680
+ server_id: att.id,
681
+ label,
682
+ preview_url: previewUrl,
683
+ attachment_type: att.attachment_type === "screenshot" ? "screenshot" : "image",
684
+ filename: att.filename,
685
+ element_reference_ref: att.element_reference_ref ?? existingAtt?.element_reference_ref ?? null,
686
+ metadata: meta
687
+ };
688
+ });
689
+
690
+ const elements = Array.isArray(record.element_references)
691
+ ? structuredClone(record.element_references)
692
+ : existingEntry?.elements
693
+ ? structuredClone(existingEntry.elements)
694
+ : [];
695
+
696
+ return {
697
+ id: record.id,
698
+ message: displayMessage,
699
+ rawMessage,
700
+ createdAt: this.formatTimestampLabel(record.created_at || existingEntry?.rawCreatedAt),
701
+ rawCreatedAt: record.created_at,
702
+ rawUpdatedAt: record.updated_at,
703
+ isEdited: isEdited || Boolean(existingEntry?.isEdited),
704
+ status: record.status,
705
+ ownershipToken: token,
706
+ elements,
707
+ attachments: mappedAttachments
708
+ };
709
+ }
710
+
711
+ public async refreshOwnFeedbacks(): Promise<SessionFeedbackEntry[]> {
712
+ if (typeof fetch !== "function") {
713
+ return [...this.sessionHistory];
714
+ }
715
+ if (this.inFlightOwnFeedbacksPromise) {
716
+ return this.inFlightOwnFeedbacksPromise;
717
+ }
718
+
719
+ this.inFlightOwnFeedbacksPromise = (async () => {
720
+ try {
721
+ const res = await this.apiClient.fetchOwnFeedbacks();
722
+ this.ownFeedbacksLoaded = true;
723
+ const records = Array.isArray(res?.feedbacks) ? res.feedbacks : [];
724
+ if (records.length === 0) {
725
+ return [...this.sessionHistory];
726
+ }
727
+
728
+ const existingById = new Map<string, SessionFeedbackEntry>();
729
+ for (const entry of this.sessionHistory) {
730
+ existingById.set(String(entry.id), entry);
731
+ }
732
+
733
+ const chronologicalServerRecords = [...records].reverse();
734
+ const serverIds = new Set<string>();
735
+ const merged: SessionFeedbackEntry[] = [];
736
+
737
+ for (const record of chronologicalServerRecords) {
738
+ if (!record || record.id === undefined || record.id === null) continue;
739
+ const idKey = String(record.id);
740
+ serverIds.add(idKey);
741
+ merged.push(this.mapOwnRecordToSessionEntry(record, existingById.get(idKey)));
742
+ }
743
+
744
+ for (const localEntry of this.sessionHistory) {
745
+ if (!serverIds.has(String(localEntry.id))) {
746
+ merged.push(localEntry);
747
+ }
748
+ }
749
+
750
+ this.sessionHistory = merged;
751
+ this.renderChatThread();
752
+ this.syncUiStates();
753
+ } catch {
754
+ // Non-fatal when offline or using minimal synthetic endpoints
755
+ } finally {
756
+ this.inFlightOwnFeedbacksPromise = null;
757
+ }
758
+ return [...this.sessionHistory];
759
+ })();
760
+
761
+ return this.inFlightOwnFeedbacksPromise;
762
+ }
763
+
764
+ private async ensureOwnFeedbacksLoaded(): Promise<void> {
765
+ if (this.ownFeedbacksLoaded) return;
766
+ await this.refreshOwnFeedbacks();
767
+ }
768
+
769
+ public startEditingFeedback(feedbackId: number | string): boolean {
770
+ const targetKey = String(feedbackId);
771
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
772
+ if (!entry) return false;
773
+
774
+ this.confirmingDeleteId = null;
775
+ this.hideStatus();
776
+
777
+ if (this.editingFeedbackId === null) {
778
+ this.stashedDraftBeforeEdit = {
779
+ message: this.textareaEl?.value || "",
780
+ elementReferences: [...this.elementReferences],
781
+ elementDomNodes: new Map(this.elementDomNodes),
782
+ attachments: [...this.attachments]
783
+ };
784
+ }
785
+
786
+ this.editingFeedbackId = targetKey;
787
+
788
+ if (this.textareaEl) {
789
+ this.textareaEl.value = entry.rawMessage !== undefined ? entry.rawMessage : entry.message;
790
+ }
791
+
792
+ this.elementReferences = structuredClone(entry.elements);
793
+ this.elementDomNodes.clear();
794
+ if (typeof document !== "undefined" && typeof document.querySelector === "function") {
795
+ for (const elRef of this.elementReferences) {
796
+ if (!elRef.selector) continue;
797
+ try {
798
+ const liveNode = document.querySelector(elRef.selector);
799
+ if (liveNode) {
800
+ this.elementDomNodes.set(elRef.client_ref, liveNode);
801
+ }
802
+ } catch {
803
+ // Ignore invalid or complex selectors not resolvable on current page
804
+ }
805
+ }
806
+ }
807
+
808
+ this.attachments = entry.attachments.map((att) => ({
809
+ id: att.id,
810
+ existing_attachment_id: att.server_id,
811
+ attachment_type: att.attachment_type,
812
+ label: att.label,
813
+ preview_url: att.preview_url,
814
+ signed_blob_id: att.signed_blob_id,
815
+ data_url: att.data_url,
816
+ filename: att.filename || att.label || "attachment.png",
817
+ element_reference_ref: att.element_reference_ref || undefined,
818
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
819
+ }));
820
+
821
+ this.picker?.refreshPinnedMarkers();
822
+ this.renderTray();
823
+ this.renderChatThread();
824
+ this.syncUiStates();
825
+ this.textareaEl?.focus();
826
+ return true;
827
+ }
828
+
829
+ public cancelEditingFeedback(): void {
830
+ if (this.editingFeedbackId === null) return;
831
+ this.editingFeedbackId = null;
832
+
833
+ if (this.stashedDraftBeforeEdit) {
834
+ if (this.textareaEl) {
835
+ this.textareaEl.value = this.stashedDraftBeforeEdit.message;
836
+ }
837
+ this.elementReferences = this.stashedDraftBeforeEdit.elementReferences;
838
+ this.elementDomNodes = this.stashedDraftBeforeEdit.elementDomNodes;
839
+ this.attachments = this.stashedDraftBeforeEdit.attachments;
840
+ this.stashedDraftBeforeEdit = null;
841
+ } else {
842
+ if (this.textareaEl) {
843
+ this.textareaEl.value = "";
844
+ }
845
+ this.elementReferences = [];
846
+ this.elementDomNodes.clear();
847
+ this.attachments = [];
848
+ }
849
+
850
+ this.picker?.hideExternalPreview();
851
+ this.picker?.refreshPinnedMarkers();
852
+ this.renderTray();
853
+ this.renderChatThread();
854
+ this.syncUiStates();
855
+ }
856
+
857
+ public requestDeleteFeedback(feedbackId: number | string): void {
858
+ const targetKey = String(feedbackId);
859
+ if (!this.sessionHistory.some((item) => String(item.id) === targetKey)) return;
860
+ this.confirmingDeleteId = this.confirmingDeleteId === targetKey ? null : targetKey;
861
+ this.renderChatThread();
862
+ }
863
+
864
+ public cancelDeleteFeedback(): void {
865
+ if (this.confirmingDeleteId === null) return;
866
+ this.confirmingDeleteId = null;
867
+ this.renderChatThread();
868
+ }
869
+
870
+ public async confirmDeleteFeedback(feedbackId: number | string): Promise<void> {
871
+ if (this.deletingFeedbackId !== null) return;
872
+ const targetKey = String(feedbackId);
873
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
874
+ if (!entry) return;
875
+
876
+ this.deletingFeedbackId = targetKey;
877
+ this.renderChatThread();
878
+
879
+ try {
880
+ const res = await this.apiClient.deleteFeedback(entry.id, entry.ownershipToken);
881
+ if (this.editingFeedbackId === targetKey) {
882
+ this.cancelEditingFeedback();
883
+ }
884
+ this.sessionHistory = this.sessionHistory.filter((item) => String(item.id) !== targetKey);
885
+ this.confirmingDeleteId = null;
886
+ this.deletingFeedbackId = null;
887
+ this.renderChatThread();
888
+ this.renderTray();
889
+ this.syncUiStates();
890
+ this.showStatus(
891
+ this.isSmartSelectionMode() ? "Your feedback was deleted." : "Feedback deleted.",
892
+ "success"
893
+ );
894
+ this.emitWidgetEvent("context-drop:delete", {
895
+ response: res,
896
+ id: entry.id
897
+ });
898
+ } catch (err) {
899
+ this.deletingFeedbackId = null;
900
+ this.renderChatThread();
901
+ const msg = err instanceof Error ? err.message : "Failed to delete feedback.";
902
+ this.showStatus(msg, "error");
903
+ this.emitWidgetEvent("context-drop:error", {
904
+ error: msg
905
+ });
906
+ }
907
+ }
908
+
909
+ public getAgentMessages(): AgentChatMessage[] {
910
+ return [...this.agentMessages];
911
+ }
912
+
913
+ public isAgentModeActive(): boolean {
914
+ return Boolean(this.config.agent?.enabled) && this.surfaceMode === "agent";
915
+ }
916
+
917
+ public isSmartSelectionMode(): boolean {
918
+ if (this.isAgentModeActive()) {
919
+ return false;
920
+ }
921
+ if (this.config.features.selection_mode === "smart") {
922
+ return true;
923
+ }
924
+ if (this.config.features.selection_mode === "verbose") {
925
+ return false;
926
+ }
927
+ return (this.config.environment || "").toLowerCase() === "production";
928
+ }
929
+
930
+ private getElementFriendlyLabel(ref: ElementReferenceSnapshot, domNode?: Element): string {
931
+ const metaLabel = ref.metadata?.friendly_label;
932
+ if (typeof metaLabel === "string" && metaLabel.trim().length > 0) {
933
+ return metaLabel.trim();
934
+ }
935
+ if (domNode) {
936
+ return describeSmartComponent(domNode).label;
937
+ }
938
+ return ref.tag_name ? `Selected ${ref.tag_name} area` : "Selected page area";
939
+ }
940
+
201
941
  public openComposer(): void {
942
+ const wasOpen = this.isOpen && !this.isMinimized;
202
943
  this.isOpen = true;
203
944
  this.isMinimized = false;
945
+ if (this.isAgentModeActive()) {
946
+ void this.ensureAgentStatusLoaded();
947
+ } else {
948
+ void this.ensureOwnFeedbacksLoaded();
949
+ }
204
950
  this.syncUiStates();
205
- if (this.textareaEl) {
206
- this.textareaEl.focus();
951
+ this.focusActiveInput();
952
+ if (!wasOpen) {
953
+ this.emitWidgetEvent("context-drop:open", { open: true });
207
954
  }
208
955
  }
209
956
 
210
957
  public closeComposer(): void {
958
+ const wasOpen = this.isOpen;
211
959
  this.isOpen = false;
212
960
  this.isMinimized = false;
213
961
  if (this.picker && this.picker.isActive()) {
214
- this.picker.stop();
962
+ this.picker.stop({ silent: true });
215
963
  }
216
964
  this.picker?.hideExternalPreview();
217
965
  this.syncUiStates();
966
+ if (wasOpen) {
967
+ this.emitWidgetEvent("context-drop:close", { open: false });
968
+ }
218
969
  }
219
970
 
220
971
  public toggleComposer(): void {
@@ -233,7 +984,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
233
984
 
234
985
  public expandFromCompactBar(): void {
235
986
  if (this.picker && this.picker.isActive()) {
236
- this.picker.stop();
987
+ this.picker.stop({ silent: true });
237
988
  }
238
989
  this.isMinimized = false;
239
990
  this.openComposer();
@@ -250,7 +1001,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
250
1001
  return;
251
1002
  }
252
1003
  this.minimizeToCompactBar();
253
- this.picker.start();
1004
+ this.picker.start({ suppressCursorPin: false });
254
1005
  if (this.lastPointerX > 0 && this.lastPointerY > 0) {
255
1006
  this.picker.highlightAtPoint(this.lastPointerX, this.lastPointerY);
256
1007
  }
@@ -265,63 +1016,241 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
265
1016
  }
266
1017
  }
267
1018
 
268
- public setFreePosition(left: number, top: number): void {
269
- if (!this.rootContainer) return;
270
- const vw = typeof window !== "undefined" ? window.innerWidth || 1024 : 1024;
271
- const vh = typeof window !== "undefined" ? window.innerHeight || 768 : 768;
272
- const clampedLeft = Math.max(8, Math.min(left, vw - 72));
273
- const clampedTop = Math.max(8, Math.min(top, vh - 48));
274
-
275
- this.freePos = { left: clampedLeft, top: clampedTop };
276
- this.rootContainer.classList.add("is-free-positioned");
277
- this.rootContainer.style.left = `${clampedLeft}px`;
278
- this.rootContainer.style.top = `${clampedTop}px`;
1019
+ public getTheme(): "light" | "dark" {
1020
+ return this.currentTheme;
279
1021
  }
280
1022
 
281
- public addElementReference(snapshot: ElementReferenceSnapshot, elementNode?: Element): boolean {
282
- if (this.elementReferences.length >= this.config.limits.max_element_references) {
283
- this.showStatus(
284
- `Maximum of ${this.config.limits.max_element_references} DOM elements reached.`,
285
- "error"
286
- );
287
- return false;
288
- }
289
- this.elementReferences.push(snapshot);
290
- if (elementNode) {
291
- this.elementDomNodes.set(snapshot.client_ref, elementNode);
292
- }
293
- this.picker?.refreshPinnedMarkers();
294
- this.renderTray();
295
- this.syncUiStates();
296
- return true;
1023
+ public setTheme(theme: "light" | "dark"): void {
1024
+ this.applyTheme(theme, true);
297
1025
  }
298
1026
 
299
- public removeElementReference(clientRef: string): void {
300
- this.elementReferences = this.elementReferences.filter((el) => el.client_ref !== clientRef);
301
- this.elementDomNodes.delete(clientRef);
302
- this.picker?.hideExternalPreview();
303
- this.picker?.refreshPinnedMarkers();
304
- this.renderTray();
305
- this.syncUiStates();
1027
+ public toggleTheme(): void {
1028
+ const next = this.currentTheme === "dark" ? "light" : "dark";
1029
+ this.applyTheme(next, true);
306
1030
  }
307
1031
 
308
- public removeAttachment(attachmentId: string): void {
1032
+ private initTheme(): void {
1033
+ let theme: "light" | "dark" = "light";
1034
+ try {
1035
+ const stored =
1036
+ typeof localStorage !== "undefined" ? localStorage.getItem("context_drop_theme") : null;
1037
+ if (stored === "dark" || stored === "light") {
1038
+ theme = stored;
1039
+ } else {
1040
+ const attr = this.getAttribute("data-cd-theme") || this.getAttribute("data-theme");
1041
+ if (attr === "dark" || attr === "light") {
1042
+ theme = attr;
1043
+ } else if (
1044
+ typeof window !== "undefined" &&
1045
+ window.matchMedia &&
1046
+ window.matchMedia("(prefers-color-scheme: dark)").matches
1047
+ ) {
1048
+ theme = "dark";
1049
+ }
1050
+ }
1051
+ } catch {
1052
+ // Non-fatal if localStorage is restricted
1053
+ }
1054
+ this.applyTheme(theme, false);
1055
+
1056
+ if (typeof window !== "undefined" && window.matchMedia) {
1057
+ try {
1058
+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
1059
+ mediaQuery.addEventListener?.("change", (e) => {
1060
+ try {
1061
+ if (!localStorage.getItem("context_drop_theme")) {
1062
+ this.applyTheme(e.matches ? "dark" : "light", false);
1063
+ }
1064
+ } catch {
1065
+ // ignore
1066
+ }
1067
+ });
1068
+ } catch {
1069
+ // ignore
1070
+ }
1071
+ }
1072
+ }
1073
+
1074
+ private applyTheme(theme: "light" | "dark", persist: boolean = true): void {
1075
+ this.currentTheme = theme;
1076
+ if (persist) {
1077
+ try {
1078
+ localStorage.setItem("context_drop_theme", theme);
1079
+ } catch {
1080
+ // Non-fatal
1081
+ }
1082
+ }
1083
+
1084
+ // Use namespaced `data-cd-theme` on the custom element host so host CSS frameworks
1085
+ // (e.g. DaisyUI / Bootstrap `[data-theme="dark"]` or `body:has([data-theme="dark"])`)
1086
+ // never alter the host page theme when toggling the widget theme.
1087
+ if (typeof this.setAttribute === "function") {
1088
+ this.setAttribute("data-cd-theme", theme);
1089
+ }
1090
+ this.rootContainer?.setAttribute("data-theme", theme);
1091
+ this.agentSidebarEl?.setAttribute("data-theme", theme);
1092
+ this.composerEl?.setAttribute("data-theme", theme);
1093
+ this.compactBarEl?.setAttribute("data-theme", theme);
1094
+ this.bookCornerBtn?.setAttribute("data-theme", theme);
1095
+ this.dragPinEl?.setAttribute("data-theme", theme);
1096
+ this.cornerSnapGhostEl?.setAttribute("data-theme", theme);
1097
+
1098
+ if (this.composerThemeToggleBtn) {
1099
+ this.updateThemeToggleBtn(this.composerThemeToggleBtn);
1100
+ }
1101
+ if (this.sidebarThemeToggleBtn) {
1102
+ this.updateThemeToggleBtn(this.sidebarThemeToggleBtn);
1103
+ }
1104
+
1105
+ if (typeof this.dispatchEvent === "function") {
1106
+ try {
1107
+ this.dispatchEvent(
1108
+ new CustomEvent("contextdrop:themechange", {
1109
+ bubbles: false,
1110
+ composed: false,
1111
+ detail: { theme }
1112
+ })
1113
+ );
1114
+ } catch {
1115
+ // ignore
1116
+ }
1117
+ }
1118
+ }
1119
+
1120
+ private buildThemeToggleBtn(): HTMLButtonElement {
1121
+ const btn = document.createElement("button");
1122
+ btn.type = "button";
1123
+ btn.className = "cd-icon-btn cd-theme-toggle";
1124
+ this.updateThemeToggleBtn(btn);
1125
+ btn.addEventListener("click", () => {
1126
+ this.toggleTheme();
1127
+ });
1128
+ return btn;
1129
+ }
1130
+
1131
+ private updateThemeToggleBtn(btn: HTMLButtonElement): void {
1132
+ const isDark = this.currentTheme === "dark";
1133
+ btn.title = isDark ? "Switch to light theme" : "Switch to dark theme";
1134
+ btn.setAttribute("aria-label", isDark ? "Switch to light theme" : "Switch to dark theme");
1135
+ btn.innerHTML = isDark ? ICON_SUN : ICON_MOON;
1136
+ }
1137
+
1138
+ public setCornerPosition(position: WidgetPosition): void {
1139
+ if (!["top_left", "top_right", "bottom_left", "bottom_right"].includes(position)) {
1140
+ return;
1141
+ }
1142
+ this.config.position = position;
1143
+ this.freePos = null;
1144
+ if (this.rootContainer) {
1145
+ this.rootContainer.className = `cd-root pos-${position}`;
1146
+ this.rootContainer.style.left = "";
1147
+ this.rootContainer.style.top = "";
1148
+ }
1149
+ if (this.bookCornerBtn) {
1150
+ this.bookCornerBtn.className = `cd-book-corner corner-${position}`;
1151
+ }
1152
+ }
1153
+
1154
+ public setFreePosition(left: number, top: number): void {
1155
+ if (!this.rootContainer) return;
1156
+ const vw = typeof window !== "undefined" ? window.innerWidth || 1024 : 1024;
1157
+ const vh = typeof window !== "undefined" ? window.innerHeight || 768 : 768;
1158
+ const clampedLeft = Math.max(8, Math.min(left, vw - 72));
1159
+ const clampedTop = Math.max(8, Math.min(top, vh - 48));
1160
+
1161
+ this.freePos = { left: clampedLeft, top: clampedTop };
1162
+ this.rootContainer.classList.add("is-free-positioned");
1163
+ this.rootContainer.style.left = `${clampedLeft}px`;
1164
+ this.rootContainer.style.top = `${clampedTop}px`;
1165
+ }
1166
+
1167
+ public addElementReference(snapshot: ElementReferenceSnapshot, elementNode?: Element): boolean {
1168
+ if (this.elementReferences.length >= this.config.limits.max_element_references) {
1169
+ this.showStatus(
1170
+ `Maximum of ${this.config.limits.max_element_references} DOM elements reached.`,
1171
+ "error"
1172
+ );
1173
+ return false;
1174
+ }
1175
+ this.elementReferences.push(snapshot);
1176
+ if (elementNode) {
1177
+ this.elementDomNodes.set(snapshot.client_ref, elementNode);
1178
+ }
1179
+ this.picker?.refreshPinnedMarkers();
1180
+ this.renderTray();
1181
+ this.syncUiStates();
1182
+ return true;
1183
+ }
1184
+
1185
+ public removeElementReference(clientRef: string): void {
1186
+ this.elementReferences = this.elementReferences.filter((el) => el.client_ref !== clientRef);
1187
+ this.elementDomNodes.delete(clientRef);
1188
+ this.attachments = this.attachments.filter(
1189
+ (att) =>
1190
+ !(att.element_reference_ref === clientRef && att.metadata?.auto_smart_context === true)
1191
+ );
1192
+ this.picker?.hideExternalPreview();
1193
+ this.picker?.refreshPinnedMarkers();
1194
+ this.renderTray();
1195
+ this.syncUiStates();
1196
+ }
1197
+
1198
+ public removeAttachment(attachmentId: string): void {
309
1199
  this.attachments = this.attachments.filter((att) => att.id !== attachmentId);
310
1200
  this.renderTray();
311
1201
  this.syncUiStates();
312
1202
  }
313
1203
 
1204
+ private focusActiveInput(): void {
1205
+ if (this.isAgentModeActive()) {
1206
+ this.agentTextareaEl?.focus();
1207
+ } else {
1208
+ this.textareaEl?.focus();
1209
+ }
1210
+ }
1211
+
1212
+ private async hydrateConfigFromServer(): Promise<void> {
1213
+ try {
1214
+ const remoteConfig = await this.apiClient.fetchConfig();
1215
+ if (remoteConfig && typeof remoteConfig === "object") {
1216
+ const posOverride = this.getAttribute("data-position") as WidgetPosition | null;
1217
+ this.setWidgetConfig({
1218
+ ...remoteConfig,
1219
+ position: posOverride || remoteConfig.position || this.config.position
1220
+ });
1221
+ }
1222
+ } catch {
1223
+ // Non-fatal in static/offline environments
1224
+ }
1225
+ }
1226
+
314
1227
  private readDataAttributes(): void {
315
1228
  const endpoint = this.getAttribute("data-endpoint") || "/context_drop";
316
- this.apiClient = new ContextDropApiClient(endpoint);
1229
+ const rawCredentials = this.getAttribute("data-credentials");
1230
+ const credentials: RequestCredentials =
1231
+ rawCredentials === "include" || rawCredentials === "omit" || rawCredentials === "same-origin"
1232
+ ? rawCredentials
1233
+ : "same-origin";
1234
+ this.apiClient = new ContextDropApiClient(endpoint, {
1235
+ credentials,
1236
+ headers: this.customHeaders
1237
+ });
317
1238
 
318
1239
  const rawConfig = this.getAttribute("data-config");
319
1240
  if (rawConfig) {
320
1241
  try {
321
1242
  const parsed = JSON.parse(rawConfig) as Partial<WidgetConfig>;
1243
+ if (
1244
+ typeof parsed.placeholder === "string" &&
1245
+ parsed.placeholder !== DEFAULT_VERBOSE_PLACEHOLDER &&
1246
+ parsed.placeholder !== DEFAULT_SMART_PLACEHOLDER
1247
+ ) {
1248
+ this.customPlaceholderSet = true;
1249
+ }
322
1250
  this.config = {
323
1251
  ...this.config,
324
1252
  ...parsed,
1253
+ agent: { ...(this.config.agent || { enabled: false }), ...(parsed.agent || {}) },
325
1254
  features: { ...this.config.features, ...(parsed.features || {}) },
326
1255
  limits: { ...this.config.limits, ...(parsed.limits || {}) },
327
1256
  privacy: { ...this.config.privacy, ...(parsed.privacy || {}) }
@@ -345,6 +1274,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
345
1274
  const placeholderOverride = this.getAttribute("data-placeholder");
346
1275
  if (placeholderOverride) {
347
1276
  this.config.placeholder = placeholderOverride;
1277
+ this.customPlaceholderSet = true;
348
1278
  }
349
1279
 
350
1280
  const rawMetadata = this.getAttribute("data-metadata");
@@ -355,37 +1285,265 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
355
1285
  this.customMetadata = {};
356
1286
  }
357
1287
  }
1288
+
1289
+ const themeOverride = this.getAttribute("data-cd-theme") || this.getAttribute("data-theme");
1290
+ if (themeOverride === "dark" || themeOverride === "light") {
1291
+ this.currentTheme = themeOverride;
1292
+ }
1293
+
1294
+ const selectionModeOverride = this.getAttribute("data-selection-mode") as SelectionMode | null;
1295
+ if (selectionModeOverride === "smart" || selectionModeOverride === "verbose") {
1296
+ this.config.features.selection_mode = selectionModeOverride;
1297
+ }
1298
+
1299
+ const envOverride = this.getAttribute("data-environment");
1300
+ if (envOverride && envOverride.trim().length > 0) {
1301
+ this.config.environment = envOverride.trim();
1302
+ }
1303
+ }
1304
+
1305
+ private detectViewportSnapCorner(
1306
+ clientX: number,
1307
+ clientY: number,
1308
+ originCorner: WidgetPosition,
1309
+ leftOriginZone: boolean
1310
+ ): WidgetPosition | null {
1311
+ if (typeof window === "undefined") return null;
1312
+ const vw = window.innerWidth || 1024;
1313
+ const vh = window.innerHeight || 768;
1314
+
1315
+ let candidate: WidgetPosition | null = null;
1316
+ if (clientX <= CORNER_SNAP_ZONE_PX && clientY <= CORNER_SNAP_ZONE_PX) {
1317
+ candidate = "top_left";
1318
+ } else if (clientX >= vw - CORNER_SNAP_ZONE_PX && clientY <= CORNER_SNAP_ZONE_PX) {
1319
+ candidate = "top_right";
1320
+ } else if (clientX <= CORNER_SNAP_ZONE_PX && clientY >= vh - CORNER_SNAP_ZONE_PX) {
1321
+ candidate = "bottom_left";
1322
+ } else if (clientX >= vw - CORNER_SNAP_ZONE_PX && clientY >= vh - CORNER_SNAP_ZONE_PX) {
1323
+ candidate = "bottom_right";
1324
+ }
1325
+
1326
+ if (!candidate) return null;
1327
+ if (candidate === originCorner && !leftOriginZone) return null;
1328
+ return candidate;
358
1329
  }
359
1330
 
360
- private attachDragHandle(handleEl: HTMLElement, onClickFallback?: () => void): void {
1331
+ private isOutsideCornerZone(clientX: number, clientY: number, corner: WidgetPosition): boolean {
1332
+ if (typeof window === "undefined") return true;
1333
+ const vw = window.innerWidth || 1024;
1334
+ const vh = window.innerHeight || 768;
1335
+ const exitRadius = CORNER_SNAP_ZONE_PX + 10;
1336
+
1337
+ switch (corner) {
1338
+ case "top_left":
1339
+ return clientX > exitRadius || clientY > exitRadius;
1340
+ case "top_right":
1341
+ return clientX < vw - exitRadius || clientY > exitRadius;
1342
+ case "bottom_left":
1343
+ return clientX > exitRadius || clientY < vh - exitRadius;
1344
+ case "bottom_right":
1345
+ return clientX < vw - exitRadius || clientY < vh - exitRadius;
1346
+ }
1347
+ }
1348
+
1349
+ private attachBookCornerLauncher(cornerBtn: HTMLButtonElement): void {
361
1350
  let startX = 0;
362
1351
  let startY = 0;
363
- let initialLeft = 0;
364
- let initialTop = 0;
365
- let dragging = false;
366
- let moved = false;
1352
+ let pointerActive = false;
1353
+ let peeled = false;
1354
+ let leftOriginZone = false;
1355
+ let activeSnapCorner: WidgetPosition | null = null;
367
1356
  let suppressNextClick = false;
368
- let suppressClickTimer: ReturnType<typeof setTimeout> | null = null;
1357
+ let suppressTimer: ReturnType<typeof setTimeout> | null = null;
369
1358
 
370
- const clearSuppressClick = (): void => {
1359
+ const clearSuppress = (): void => {
371
1360
  suppressNextClick = false;
372
- if (suppressClickTimer !== null) {
373
- clearTimeout(suppressClickTimer);
374
- suppressClickTimer = null;
1361
+ if (suppressTimer !== null) {
1362
+ clearTimeout(suppressTimer);
1363
+ suppressTimer = null;
375
1364
  }
376
1365
  };
377
1366
 
378
- if (onClickFallback) {
379
- handleEl.addEventListener("click", (ev: MouseEvent) => {
380
- if (suppressNextClick) {
381
- clearSuppressClick();
382
- ev.preventDefault();
383
- ev.stopPropagation();
384
- return;
1367
+ const updateDragPinPosition = (x: number, y: number): void => {
1368
+ if (!this.dragPinEl) return;
1369
+ this.dragPinEl.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`;
1370
+ };
1371
+
1372
+ const finishPeelVisuals = (): void => {
1373
+ pointerActive = false;
1374
+ this.isPeelDragging = false;
1375
+ this.cancelActivePeelDrag = null;
1376
+ cornerBtn.classList.remove("is-peeled");
1377
+ if (this.dragPinEl) {
1378
+ this.dragPinEl.hidden = true;
1379
+ this.dragPinEl.classList.remove("has-target", "is-snapping-corner");
1380
+ }
1381
+ if (this.cornerSnapGhostEl) {
1382
+ this.cornerSnapGhostEl.hidden = true;
1383
+ }
1384
+ if (typeof window !== "undefined") {
1385
+ window.removeEventListener("pointermove", onPointerMove);
1386
+ window.removeEventListener("pointerup", onPointerUp);
1387
+ window.removeEventListener("pointercancel", onPointerCancel);
1388
+ }
1389
+ };
1390
+
1391
+ cornerBtn.addEventListener("click", (ev: MouseEvent) => {
1392
+ if (suppressNextClick) {
1393
+ clearSuppress();
1394
+ ev.preventDefault();
1395
+ ev.stopPropagation();
1396
+ return;
1397
+ }
1398
+ this.openComposer();
1399
+ });
1400
+
1401
+ const onPointerMove = (ev: PointerEvent): void => {
1402
+ if (!pointerActive) return;
1403
+ this.lastPointerX = ev.clientX;
1404
+ this.lastPointerY = ev.clientY;
1405
+
1406
+ const travel = Math.hypot(ev.clientX - startX, ev.clientY - startY);
1407
+ if (!peeled && travel > PEEL_DRAG_THRESHOLD_PX) {
1408
+ peeled = true;
1409
+ this.isPeelDragging = true;
1410
+ cornerBtn.classList.add("is-peeled");
1411
+
1412
+ if (this.dragPinEl) {
1413
+ this.dragPinEl.hidden = false;
1414
+ updateDragPinPosition(ev.clientX, ev.clientY);
385
1415
  }
386
- onClickFallback();
387
- });
388
- }
1416
+
1417
+ if (
1418
+ this.config.features.element_selection &&
1419
+ this.picker &&
1420
+ this.elementReferences.length < this.config.limits.max_element_references
1421
+ ) {
1422
+ this.picker.start({ suppressCursorPin: true });
1423
+ }
1424
+ }
1425
+
1426
+ if (!peeled) return;
1427
+
1428
+ updateDragPinPosition(ev.clientX, ev.clientY);
1429
+
1430
+ if (!leftOriginZone && this.isOutsideCornerZone(ev.clientX, ev.clientY, this.config.position)) {
1431
+ leftOriginZone = true;
1432
+ }
1433
+
1434
+ activeSnapCorner = this.detectViewportSnapCorner(
1435
+ ev.clientX,
1436
+ ev.clientY,
1437
+ this.config.position,
1438
+ leftOriginZone
1439
+ );
1440
+
1441
+ if (activeSnapCorner) {
1442
+ this.picker?.clearCandidateHighlight();
1443
+ if (this.cornerSnapGhostEl) {
1444
+ this.cornerSnapGhostEl.className = `cd-corner-snap-ghost corner-${activeSnapCorner}`;
1445
+ this.cornerSnapGhostEl.hidden = false;
1446
+ }
1447
+ if (this.dragPinEl) {
1448
+ this.dragPinEl.classList.add("is-snapping-corner");
1449
+ this.dragPinEl.classList.remove("has-target");
1450
+ }
1451
+ } else {
1452
+ if (this.cornerSnapGhostEl) {
1453
+ this.cornerSnapGhostEl.hidden = true;
1454
+ }
1455
+ if (this.dragPinEl) {
1456
+ this.dragPinEl.classList.remove("is-snapping-corner");
1457
+ }
1458
+ this.picker?.highlightAtPoint(ev.clientX, ev.clientY, ev);
1459
+ const hasTarget = Boolean(this.picker?.getActiveCandidate());
1460
+ this.dragPinEl?.classList.toggle("has-target", hasTarget);
1461
+ }
1462
+ };
1463
+
1464
+ const armClickSuppression = (): void => {
1465
+ suppressNextClick = true;
1466
+ if (suppressTimer !== null) {
1467
+ clearTimeout(suppressTimer);
1468
+ }
1469
+ suppressTimer = setTimeout(() => {
1470
+ suppressNextClick = false;
1471
+ suppressTimer = null;
1472
+ }, 40);
1473
+ };
1474
+
1475
+ const onPointerUp = (ev: PointerEvent): void => {
1476
+ if (!pointerActive) return;
1477
+ const wasPeeled = peeled;
1478
+ const snapTarget = activeSnapCorner;
1479
+ peeled = false;
1480
+ activeSnapCorner = null;
1481
+
1482
+ if (!wasPeeled) {
1483
+ finishPeelVisuals();
1484
+ return;
1485
+ }
1486
+
1487
+ armClickSuppression();
1488
+
1489
+ if (snapTarget) {
1490
+ this.picker?.stop({ silent: true });
1491
+ finishPeelVisuals();
1492
+ this.setCornerPosition(snapTarget);
1493
+ this.syncUiStates();
1494
+ return;
1495
+ }
1496
+
1497
+ this.picker?.highlightAtPoint(ev.clientX, ev.clientY, ev);
1498
+ const committed = this.picker ? this.picker.commitActiveCandidate(ev.clientX, ev.clientY) : false;
1499
+ this.picker?.stop({ silent: true });
1500
+ finishPeelVisuals();
1501
+
1502
+ if (committed) {
1503
+ this.openComposer();
1504
+ } else {
1505
+ this.syncUiStates();
1506
+ }
1507
+ };
1508
+
1509
+ const onPointerCancel = (): void => {
1510
+ if (!pointerActive) return;
1511
+ peeled = false;
1512
+ activeSnapCorner = null;
1513
+ this.picker?.stop({ silent: true });
1514
+ finishPeelVisuals();
1515
+ clearSuppress();
1516
+ this.syncUiStates();
1517
+ };
1518
+
1519
+ cornerBtn.addEventListener("pointerdown", (ev: PointerEvent) => {
1520
+ if (ev.button !== 0 || typeof window === "undefined") return;
1521
+ startX = ev.clientX;
1522
+ startY = ev.clientY;
1523
+ pointerActive = true;
1524
+ peeled = false;
1525
+ leftOriginZone = false;
1526
+ activeSnapCorner = null;
1527
+ clearSuppress();
1528
+
1529
+ this.cancelActivePeelDrag = () => {
1530
+ armClickSuppression();
1531
+ onPointerCancel();
1532
+ };
1533
+
1534
+ window.addEventListener("pointermove", onPointerMove);
1535
+ window.addEventListener("pointerup", onPointerUp);
1536
+ window.addEventListener("pointercancel", onPointerCancel);
1537
+ });
1538
+ }
1539
+
1540
+ private attachDragHandle(handleEl: HTMLElement): void {
1541
+ let startX = 0;
1542
+ let startY = 0;
1543
+ let initialLeft = 0;
1544
+ let initialTop = 0;
1545
+ let dragging = false;
1546
+ let moved = false;
389
1547
 
390
1548
  const onPointerMove = (ev: PointerEvent): void => {
391
1549
  if (!dragging) return;
@@ -393,7 +1551,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
393
1551
  const dy = ev.clientY - startY;
394
1552
  if (!moved && Math.hypot(dx, dy) > 5) {
395
1553
  moved = true;
396
- this.pinDockEl?.classList.add("is-dragging");
397
1554
  }
398
1555
  if (moved) {
399
1556
  this.setFreePosition(initialLeft + dx, initialTop + dy);
@@ -402,35 +1559,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
402
1559
 
403
1560
  const cleanupDrag = (): void => {
404
1561
  dragging = false;
405
- this.pinDockEl?.classList.remove("is-dragging");
406
1562
  window.removeEventListener("pointermove", onPointerMove);
407
- window.removeEventListener("pointerup", onPointerUp);
408
- window.removeEventListener("pointercancel", onPointerCancel);
409
- };
410
-
411
- const onPointerUp = (): void => {
412
- if (!dragging) return;
413
- cleanupDrag();
414
- if (moved && onClickFallback) {
415
- suppressNextClick = true;
416
- if (suppressClickTimer !== null) {
417
- clearTimeout(suppressClickTimer);
418
- }
419
- suppressClickTimer = setTimeout(() => {
420
- suppressNextClick = false;
421
- suppressClickTimer = null;
422
- }, 0);
423
- }
424
- };
425
-
426
- const onPointerCancel = (): void => {
427
- if (!dragging) return;
428
- cleanupDrag();
429
- clearSuppressClick();
1563
+ window.removeEventListener("pointerup", cleanupDrag);
1564
+ window.removeEventListener("pointercancel", cleanupDrag);
430
1565
  };
431
1566
 
432
1567
  handleEl.addEventListener("pointerdown", (ev: PointerEvent) => {
433
- // Only primary mouse button or touch
434
1568
  if (ev.button !== 0) return;
435
1569
  const targetEl =
436
1570
  ev.target && typeof (ev.target as Element).closest === "function"
@@ -449,14 +1583,83 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
449
1583
  initialTop = this.freePos ? this.freePos.top : rect.top;
450
1584
  dragging = true;
451
1585
  moved = false;
452
- clearSuppressClick();
453
1586
 
454
1587
  window.addEventListener("pointermove", onPointerMove);
455
- window.addEventListener("pointerup", onPointerUp);
456
- window.addEventListener("pointercancel", onPointerCancel);
1588
+ window.addEventListener("pointerup", cleanupDrag);
1589
+ window.addEventListener("pointercancel", cleanupDrag);
1590
+ });
1591
+ }
1592
+
1593
+ private attachSidebarResizer(resizerEl: HTMLDivElement): void {
1594
+ let startX = 0;
1595
+ let startWidth = this.sidebarWidth;
1596
+ let active = false;
1597
+
1598
+ const onPointerMove = (ev: PointerEvent): void => {
1599
+ if (!active || typeof window === "undefined") return;
1600
+ const delta = this.sidebarSide === "right" ? startX - ev.clientX : ev.clientX - startX;
1601
+ const maxAllowed = Math.max(360, (window.innerWidth || 1024) - 80);
1602
+ this.sidebarWidth = Math.max(360, Math.min(Math.min(920, maxAllowed), startWidth + delta));
1603
+ if (this.agentSidebarEl) {
1604
+ this.agentSidebarEl.style.width = `${Math.round(this.sidebarWidth)}px`;
1605
+ }
1606
+ if (this.pushPageLayout && this.isOpen && !this.isMinimized && this.isAgentModeActive()) {
1607
+ this.syncHostPagePushMargin(true);
1608
+ }
1609
+ };
1610
+
1611
+ const stopResize = (): void => {
1612
+ active = false;
1613
+ resizerEl.classList.remove("is-resizing");
1614
+ try {
1615
+ localStorage.setItem("context_drop_sidebar_width", String(Math.round(this.sidebarWidth)));
1616
+ } catch {
1617
+ // Non-fatal
1618
+ }
1619
+ window.removeEventListener("pointermove", onPointerMove);
1620
+ window.removeEventListener("pointerup", stopResize);
1621
+ window.removeEventListener("pointercancel", stopResize);
1622
+ };
1623
+
1624
+ resizerEl.addEventListener("pointerdown", (ev: PointerEvent) => {
1625
+ if (ev.button !== 0 || typeof window === "undefined") return;
1626
+ ev.preventDefault();
1627
+ active = true;
1628
+ startX = ev.clientX;
1629
+ startWidth = this.sidebarWidth;
1630
+ resizerEl.classList.add("is-resizing");
1631
+ window.addEventListener("pointermove", onPointerMove);
1632
+ window.addEventListener("pointerup", stopResize);
1633
+ window.addEventListener("pointercancel", stopResize);
457
1634
  });
458
1635
  }
459
1636
 
1637
+ private syncHostPagePushMargin(shouldPush: boolean): void {
1638
+ if (typeof document === "undefined" || !document.documentElement) return;
1639
+ const htmlEl = document.documentElement;
1640
+ if (!shouldPush) {
1641
+ if (htmlEl.getAttribute("data-context-drop-pushed") === "true") {
1642
+ htmlEl.style.marginRight = "";
1643
+ htmlEl.style.marginLeft = "";
1644
+ if (typeof htmlEl.removeAttribute === "function") {
1645
+ htmlEl.removeAttribute("data-context-drop-pushed");
1646
+ } else {
1647
+ htmlEl.setAttribute("data-context-drop-pushed", "");
1648
+ }
1649
+ }
1650
+ return;
1651
+ }
1652
+
1653
+ htmlEl.setAttribute("data-context-drop-pushed", "true");
1654
+ if (this.sidebarSide === "right") {
1655
+ htmlEl.style.marginLeft = "";
1656
+ htmlEl.style.marginRight = `${Math.round(this.sidebarWidth)}px`;
1657
+ } else {
1658
+ htmlEl.style.marginRight = "";
1659
+ htmlEl.style.marginLeft = `${Math.round(this.sidebarWidth)}px`;
1660
+ }
1661
+ }
1662
+
460
1663
  private renderShadowDom(): void {
461
1664
  if (!this.shadow) return;
462
1665
  this.shadow.innerHTML = "";
@@ -470,6 +1673,79 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
470
1673
  this.rootContainer = root;
471
1674
 
472
1675
  // 1. Compact Minimized Pinning Bar (visible while pinning elements on the page or minimized)
1676
+ const compactBar = this.buildCompactBarDom();
1677
+ root.appendChild(compactBar);
1678
+
1679
+ // 2. Standard Floating Feedback Chatbox Composer
1680
+ const composer = this.buildFeedbackComposerDom();
1681
+ root.appendChild(composer);
1682
+
1683
+ this.shadow.appendChild(root);
1684
+
1685
+ // 3. Docked Local BYOK Agentic Coding Sidebar (active in local development mode)
1686
+ const sidebar = this.buildAgentSidebarDom();
1687
+ this.shadow.appendChild(sidebar);
1688
+
1689
+ // 4. Book-Corner Fold Launcher (flush at viewport corner, peels into pushpin on drag)
1690
+ const bookCorner = document.createElement("button");
1691
+ bookCorner.type = "button";
1692
+ bookCorner.className = `cd-book-corner corner-${this.config.position}`;
1693
+ bookCorner.setAttribute(
1694
+ "aria-label",
1695
+ "Open ContextDrop chatbox, or drag corner to pin an element on the page"
1696
+ );
1697
+ bookCorner.setAttribute("aria-expanded", String(this.isOpen));
1698
+
1699
+ const cornerArt = document.createElement("span");
1700
+ cornerArt.className = "cd-book-corner-art";
1701
+ cornerArt.innerHTML = BOOK_CORNER_SVG;
1702
+ bookCorner.appendChild(cornerArt);
1703
+
1704
+ const agentDot = document.createElement("span");
1705
+ agentDot.className = "cd-corner-agent-dot";
1706
+ agentDot.hidden = true;
1707
+ this.bookCornerAgentDotEl = agentDot;
1708
+ bookCorner.appendChild(agentDot);
1709
+
1710
+ const countBadge = document.createElement("span");
1711
+ countBadge.className = "cd-corner-count";
1712
+ countBadge.hidden = true;
1713
+ this.bookCornerCountEl = countBadge;
1714
+ bookCorner.appendChild(countBadge);
1715
+
1716
+ const hoverHint = document.createElement("span");
1717
+ hoverHint.className = "cd-corner-hint";
1718
+ hoverHint.setAttribute("aria-hidden", "true");
1719
+ hoverHint.textContent = "Click to chat · Drag to pin";
1720
+ this.bookCornerHintEl = hoverHint;
1721
+ bookCorner.appendChild(hoverHint);
1722
+
1723
+ this.attachBookCornerLauncher(bookCorner);
1724
+ this.bookCornerBtn = bookCorner;
1725
+ this.shadow.appendChild(bookCorner);
1726
+
1727
+ // 5. Morphing Drag Pushpin + Viewport Corner Snap Ghost
1728
+ const snapGhost = document.createElement("div");
1729
+ snapGhost.className = `cd-corner-snap-ghost corner-${this.config.position}`;
1730
+ snapGhost.hidden = true;
1731
+ this.cornerSnapGhostEl = snapGhost;
1732
+ this.shadow.appendChild(snapGhost);
1733
+
1734
+ const dragPin = document.createElement("div");
1735
+ dragPin.className = "cd-drag-pin";
1736
+ dragPin.hidden = true;
1737
+ const dragPinHead = document.createElement("div");
1738
+ dragPinHead.className = "cd-drag-pin-head";
1739
+ dragPinHead.innerHTML = ICON_PIN;
1740
+ dragPin.appendChild(dragPinHead);
1741
+ this.dragPinEl = dragPin;
1742
+ this.shadow.appendChild(dragPin);
1743
+
1744
+ this.applyTheme(this.currentTheme, false);
1745
+ this.syncUiStates();
1746
+ }
1747
+
1748
+ private buildCompactBarDom(): HTMLDivElement {
473
1749
  const compactBar = document.createElement("div");
474
1750
  compactBar.className = "cd-compact-bar";
475
1751
  compactBar.setAttribute("role", "region");
@@ -534,15 +1810,42 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
534
1810
  this.compactDoneBtn = expandBtn;
535
1811
  compactBar.appendChild(expandBtn);
536
1812
 
537
- // 2. Main Floating Chatbox Composer Window
1813
+ return compactBar;
1814
+ }
1815
+
1816
+ private buildModeSwitchDom(activeMode: WidgetSurfaceMode): HTMLDivElement {
1817
+ const wrap = document.createElement("div");
1818
+ wrap.className = "cd-mode-switch";
1819
+ wrap.setAttribute("role", "tablist");
1820
+ wrap.setAttribute("aria-label", "ContextDrop mode");
1821
+
1822
+ const agentBtn = document.createElement("button");
1823
+ agentBtn.type = "button";
1824
+ agentBtn.className = `cd-mode-btn${activeMode === "agent" ? " is-active" : ""}`;
1825
+ agentBtn.setAttribute("aria-selected", String(activeMode === "agent"));
1826
+ agentBtn.innerHTML = `${ICON_CODE_PROMPT}<span>Agent</span>`;
1827
+ agentBtn.addEventListener("click", () => this.setSurfaceMode("agent"));
1828
+
1829
+ const feedbackBtn = document.createElement("button");
1830
+ feedbackBtn.type = "button";
1831
+ feedbackBtn.className = `cd-mode-btn${activeMode === "feedback" ? " is-active" : ""}`;
1832
+ feedbackBtn.setAttribute("aria-selected", String(activeMode === "feedback"));
1833
+ feedbackBtn.textContent = "Feedback";
1834
+ feedbackBtn.addEventListener("click", () => this.setSurfaceMode("feedback"));
1835
+
1836
+ wrap.appendChild(agentBtn);
1837
+ wrap.appendChild(feedbackBtn);
1838
+ return wrap;
1839
+ }
1840
+
1841
+ private buildFeedbackComposerDom(): HTMLDivElement {
538
1842
  const composer = document.createElement("div");
539
1843
  composer.className = "cd-composer";
540
1844
  composer.setAttribute("role", "dialog");
541
1845
  composer.setAttribute("aria-label", "ContextDrop Feedback Chatbox");
542
- composer.hidden = !this.isOpen;
1846
+ composer.hidden = true;
543
1847
  this.composerEl = composer;
544
1848
 
545
- // Drag-and-drop image support on the chatbox
546
1849
  composer.addEventListener("dragover", (ev) => {
547
1850
  ev.preventDefault();
548
1851
  composer.classList.add("is-dragging-over");
@@ -559,7 +1862,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
559
1862
  }
560
1863
  });
561
1864
 
562
- // Header with Top-Left Pin-Shaped Selector & Drag Handle
563
1865
  const header = document.createElement("div");
564
1866
  header.className = "cd-composer-header";
565
1867
  this.attachDragHandle(header);
@@ -582,11 +1884,23 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
582
1884
  const title = document.createElement("h2");
583
1885
  title.className = "cd-composer-title";
584
1886
  title.textContent = "ContextDrop";
1887
+ this.composerTitleEl = title;
585
1888
  headerLeft.appendChild(title);
586
1889
 
587
1890
  const headerActions = document.createElement("div");
588
1891
  headerActions.className = "cd-header-actions";
589
1892
 
1893
+ const modeSwitchHolder = document.createElement("div");
1894
+ modeSwitchHolder.className = "cd-composer-mode-switch-wrap";
1895
+ modeSwitchHolder.hidden = !this.config.agent?.enabled;
1896
+ modeSwitchHolder.appendChild(this.buildModeSwitchDom("feedback"));
1897
+ this.composerModeSwitchWrap = modeSwitchHolder;
1898
+ headerActions.appendChild(modeSwitchHolder);
1899
+
1900
+ const themeBtn = this.buildThemeToggleBtn();
1901
+ this.composerThemeToggleBtn = themeBtn;
1902
+ headerActions.appendChild(themeBtn);
1903
+
590
1904
  const minBtn = document.createElement("button");
591
1905
  minBtn.type = "button";
592
1906
  minBtn.className = "cd-icon-btn";
@@ -594,6 +1908,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
594
1908
  minBtn.setAttribute("aria-label", "Minimize chatbox to compact bar");
595
1909
  minBtn.innerHTML = ICON_MINIMIZE;
596
1910
  minBtn.addEventListener("click", () => this.minimizeToCompactBar());
1911
+ this.composerMinBtn = minBtn;
597
1912
 
598
1913
  const closeBtn = document.createElement("button");
599
1914
  closeBtn.type = "button";
@@ -609,7 +1924,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
609
1924
  header.appendChild(headerActions);
610
1925
  composer.appendChild(header);
611
1926
 
612
- // Conversational Chat Thread
613
1927
  const chatThread = document.createElement("div");
614
1928
  chatThread.className = "cd-chat-thread";
615
1929
  chatThread.setAttribute("aria-live", "polite");
@@ -617,14 +1931,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
617
1931
  composer.appendChild(chatThread);
618
1932
  this.renderChatThread();
619
1933
 
620
- // Pinned Elements & Attachments Chip Tray
621
1934
  const tray = document.createElement("div");
622
1935
  tray.className = "cd-tray";
623
1936
  tray.setAttribute("aria-label", "Attached context items");
624
1937
  this.trayEl = tray;
625
1938
  composer.appendChild(tray);
626
1939
 
627
- // Status message bar
628
1940
  const status = document.createElement("div");
629
1941
  status.className = "cd-status";
630
1942
  status.setAttribute("role", "status");
@@ -632,7 +1944,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
632
1944
  this.statusEl = status;
633
1945
  composer.appendChild(status);
634
1946
 
635
- // Hidden file input
636
1947
  const fileInput = document.createElement("input");
637
1948
  fileInput.type = "file";
638
1949
  fileInput.multiple = true;
@@ -647,10 +1958,30 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
647
1958
  this.fileInputEl = fileInput;
648
1959
  composer.appendChild(fileInput);
649
1960
 
650
- // Chatbox Prompt Input Shell
651
1961
  const promptShell = document.createElement("div");
652
1962
  promptShell.className = "cd-prompt-shell";
653
1963
 
1964
+ const editBanner = document.createElement("div");
1965
+ editBanner.className = "cd-edit-banner";
1966
+ editBanner.hidden = true;
1967
+
1968
+ const editBannerInfo = document.createElement("span");
1969
+ editBannerInfo.className = "cd-edit-banner-info";
1970
+ this.editBannerInfoEl = editBannerInfo;
1971
+ editBanner.appendChild(editBannerInfo);
1972
+
1973
+ const cancelEditBtn = document.createElement("button");
1974
+ cancelEditBtn.type = "button";
1975
+ cancelEditBtn.className = "cd-btn cd-btn-xs";
1976
+ cancelEditBtn.setAttribute("aria-label", "Cancel editing feedback");
1977
+ cancelEditBtn.textContent = "Cancel";
1978
+ cancelEditBtn.addEventListener("click", () => {
1979
+ this.cancelEditingFeedback();
1980
+ });
1981
+ editBanner.appendChild(cancelEditBtn);
1982
+ this.editBannerEl = editBanner;
1983
+ promptShell.appendChild(editBanner);
1984
+
654
1985
  const textarea = document.createElement("textarea");
655
1986
  textarea.className = "cd-textarea";
656
1987
  textarea.placeholder = this.config.placeholder;
@@ -660,171 +1991,1421 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
660
1991
  ev.preventDefault();
661
1992
  void this.handleSubmit();
662
1993
  } else if (ev.key === "Escape") {
1994
+ if (ev.defaultPrevented) return;
663
1995
  ev.preventDefault();
664
- this.closeComposer();
1996
+ if (this.confirmingDeleteId !== null) {
1997
+ this.cancelDeleteFeedback();
1998
+ } else if (this.editingFeedbackId !== null) {
1999
+ this.cancelEditingFeedback();
2000
+ } else {
2001
+ this.closeComposer();
2002
+ }
665
2003
  }
666
2004
  });
667
2005
  textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
668
2006
  this.textareaEl = textarea;
669
2007
  promptShell.appendChild(textarea);
670
2008
 
671
- // Toolbar inside prompt shell
672
- const toolbar = document.createElement("div");
673
- toolbar.className = "cd-toolbar";
2009
+ const toolbar = document.createElement("div");
2010
+ toolbar.className = "cd-toolbar";
2011
+
2012
+ const actions = this.buildPromptToolbarActions(false);
2013
+
2014
+ const submitBtn = document.createElement("button");
2015
+ submitBtn.type = "button";
2016
+ submitBtn.className = "cd-btn cd-btn-primary";
2017
+ submitBtn.setAttribute("aria-label", "Submit feedback");
2018
+ submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
2019
+ submitBtn.addEventListener("click", () => {
2020
+ void this.handleSubmit();
2021
+ });
2022
+ this.submitBtn = submitBtn;
2023
+
2024
+ toolbar.appendChild(actions);
2025
+ toolbar.appendChild(submitBtn);
2026
+ promptShell.appendChild(toolbar);
2027
+ composer.appendChild(promptShell);
2028
+
2029
+ return composer;
2030
+ }
2031
+
2032
+ private buildPromptToolbarActions(forAgentSidebar: boolean = false): HTMLDivElement {
2033
+ const actions = document.createElement("div");
2034
+ actions.className = "cd-toolbar-actions";
2035
+
2036
+ if (this.config.features.element_selection) {
2037
+ const pickBtn = document.createElement("button");
2038
+ pickBtn.type = "button";
2039
+ pickBtn.className = "cd-btn";
2040
+ pickBtn.title = "Freeze & Pin element (⌥⇧P)";
2041
+ pickBtn.setAttribute("aria-label", "Pin HTML element as context (Option+Shift+P)");
2042
+ pickBtn.innerHTML = `${ICON_PIN}<span>Pin</span><kbd class="cd-kbd">⌥⇧P</kbd>`;
2043
+ pickBtn.addEventListener("click", () => this.startPinSelection());
2044
+ if (!forAgentSidebar) {
2045
+ this.composerToolbarPickBtn = pickBtn;
2046
+ }
2047
+ actions.appendChild(pickBtn);
2048
+ }
2049
+
2050
+ if (this.config.features.screenshot_capture) {
2051
+ const screenshotBtn = document.createElement("button");
2052
+ screenshotBtn.type = "button";
2053
+ screenshotBtn.className = "cd-btn";
2054
+ screenshotBtn.setAttribute("aria-label", "Capture viewport screenshot");
2055
+ screenshotBtn.innerHTML = `${ICON_CAMERA}<span>Screenshot</span>`;
2056
+ screenshotBtn.addEventListener("click", () => {
2057
+ void this.handleViewportScreenshot();
2058
+ });
2059
+ if (!forAgentSidebar) {
2060
+ this.composerToolbarScreenshotBtn = screenshotBtn;
2061
+ }
2062
+ actions.appendChild(screenshotBtn);
2063
+ }
2064
+
2065
+ const uploadBtn = document.createElement("button");
2066
+ uploadBtn.type = "button";
2067
+ uploadBtn.className = "cd-btn";
2068
+ uploadBtn.setAttribute("aria-label", "Upload image attachment");
2069
+ uploadBtn.innerHTML = `${ICON_IMAGE}<span>Image</span>`;
2070
+ uploadBtn.addEventListener("click", () => this.fileInputEl?.click());
2071
+ if (!forAgentSidebar) {
2072
+ this.composerToolbarUploadBtn = uploadBtn;
2073
+ }
2074
+ actions.appendChild(uploadBtn);
2075
+
2076
+ return actions;
2077
+ }
2078
+
2079
+ private buildAgentSidebarDom(): HTMLElement {
2080
+ const sidebar = document.createElement("aside");
2081
+ sidebar.className = `cd-agent-sidebar side-${this.sidebarSide}`;
2082
+ sidebar.setAttribute("role", "dialog");
2083
+ sidebar.setAttribute("aria-label", "ContextDrop Local Coding Agent Sidebar");
2084
+ sidebar.style.width = `${this.sidebarWidth}px`;
2085
+ sidebar.hidden = true;
2086
+ this.agentSidebarEl = sidebar;
2087
+
2088
+ sidebar.addEventListener("dragover", (ev) => {
2089
+ ev.preventDefault();
2090
+ sidebar.classList.add("is-dragging-over");
2091
+ });
2092
+ sidebar.addEventListener("dragleave", () => {
2093
+ sidebar.classList.remove("is-dragging-over");
2094
+ });
2095
+ sidebar.addEventListener("drop", (ev) => {
2096
+ ev.preventDefault();
2097
+ sidebar.classList.remove("is-dragging-over");
2098
+ const files = ev.dataTransfer?.files;
2099
+ if (files && files.length > 0) {
2100
+ void this.handleFilesSelected(Array.from(files));
2101
+ }
2102
+ });
2103
+
2104
+ const resizer = document.createElement("div");
2105
+ resizer.className = "cd-sidebar-resizer";
2106
+ resizer.title = "Drag edge to resize sidebar";
2107
+ this.attachSidebarResizer(resizer);
2108
+ sidebar.appendChild(resizer);
2109
+
2110
+ // 1. Sidebar Header
2111
+ const header = document.createElement("div");
2112
+ header.className = "cd-sidebar-header";
2113
+
2114
+ const headerLeft = document.createElement("div");
2115
+ headerLeft.className = "cd-header-left";
2116
+
2117
+ if (this.config.features.element_selection) {
2118
+ const pinBtn = document.createElement("button");
2119
+ pinBtn.type = "button";
2120
+ pinBtn.className = "cd-pin-corner-btn";
2121
+ pinBtn.title = "Freeze & Pin element (⌥⇧P)";
2122
+ pinBtn.setAttribute("aria-label", "Pin DOM element for agent (Option+Shift+P)");
2123
+ pinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>`;
2124
+ pinBtn.addEventListener("click", () => this.startPinSelection());
2125
+ this.sidebarPinBtn = pinBtn;
2126
+ headerLeft.appendChild(pinBtn);
2127
+ }
2128
+
2129
+ const title = document.createElement("h2");
2130
+ title.className = "cd-composer-title";
2131
+ title.textContent = "ContextDrop";
2132
+ headerLeft.appendChild(title);
2133
+
2134
+ const envPill = document.createElement("span");
2135
+ envPill.className = "cd-env-pill is-local";
2136
+ envPill.textContent = this.getShortEnvironmentSlug();
2137
+ this.sidebarEnvPillEl = envPill;
2138
+ headerLeft.appendChild(envPill);
2139
+
2140
+ const headerActions = document.createElement("div");
2141
+ headerActions.className = "cd-header-actions";
2142
+
2143
+ headerActions.appendChild(this.buildModeSwitchDom("agent"));
2144
+
2145
+ const themeBtn = this.buildThemeToggleBtn();
2146
+ this.sidebarThemeToggleBtn = themeBtn;
2147
+ headerActions.appendChild(themeBtn);
2148
+
2149
+ const newThreadBtn = document.createElement("button");
2150
+ newThreadBtn.type = "button";
2151
+ newThreadBtn.className = "cd-icon-btn";
2152
+ newThreadBtn.title = "New agent conversation";
2153
+ newThreadBtn.setAttribute("aria-label", "Start new agent conversation");
2154
+ newThreadBtn.innerHTML = ICON_PLUS;
2155
+ newThreadBtn.addEventListener("click", () => {
2156
+ this.agentMessages = [];
2157
+ this.renderAgentStream();
2158
+ this.agentTextareaEl?.focus();
2159
+ });
2160
+
2161
+ const pushLayoutBtn = document.createElement("button");
2162
+ pushLayoutBtn.type = "button";
2163
+ pushLayoutBtn.className = "cd-icon-btn";
2164
+ pushLayoutBtn.title = "Toggle pushing page layout alongside sidebar";
2165
+ pushLayoutBtn.setAttribute("aria-label", "Toggle push page layout");
2166
+ pushLayoutBtn.innerHTML = ICON_PUSH_LAYOUT;
2167
+ pushLayoutBtn.addEventListener("click", () => {
2168
+ this.pushPageLayout = !this.pushPageLayout;
2169
+ this.syncUiStates();
2170
+ });
2171
+ this.sidebarPushBtn = pushLayoutBtn;
2172
+
2173
+ const flipSideBtn = document.createElement("button");
2174
+ flipSideBtn.type = "button";
2175
+ flipSideBtn.className = "cd-icon-btn";
2176
+ flipSideBtn.title = "Dock sidebar on left or right";
2177
+ flipSideBtn.setAttribute("aria-label", "Switch sidebar dock side");
2178
+ flipSideBtn.innerHTML = ICON_SIDEBAR;
2179
+ flipSideBtn.addEventListener("click", () => {
2180
+ this.sidebarSide = this.sidebarSide === "right" ? "left" : "right";
2181
+ sidebar.className = `cd-agent-sidebar side-${this.sidebarSide}`;
2182
+ this.syncUiStates();
2183
+ });
2184
+
2185
+ const minBtn = document.createElement("button");
2186
+ minBtn.type = "button";
2187
+ minBtn.className = "cd-icon-btn";
2188
+ minBtn.title = "Minimize sidebar";
2189
+ minBtn.setAttribute("aria-label", "Minimize agent sidebar");
2190
+ minBtn.innerHTML = ICON_MINIMIZE;
2191
+ minBtn.addEventListener("click", () => this.minimizeToCompactBar());
2192
+
2193
+ const closeBtn = document.createElement("button");
2194
+ closeBtn.type = "button";
2195
+ closeBtn.className = "cd-icon-btn";
2196
+ closeBtn.title = "Close sidebar (Esc)";
2197
+ closeBtn.setAttribute("aria-label", "Close agent sidebar");
2198
+ closeBtn.innerHTML = ICON_CLOSE;
2199
+ closeBtn.addEventListener("click", () => this.closeComposer());
2200
+
2201
+ headerActions.appendChild(newThreadBtn);
2202
+ headerActions.appendChild(pushLayoutBtn);
2203
+ headerActions.appendChild(flipSideBtn);
2204
+ headerActions.appendChild(minBtn);
2205
+ headerActions.appendChild(closeBtn);
2206
+
2207
+ header.appendChild(headerLeft);
2208
+ header.appendChild(headerActions);
2209
+ sidebar.appendChild(header);
2210
+
2211
+ // 2. Provider + BYOK Vault + Cross-Environment Feedbacks Subbar
2212
+ const subbar = document.createElement("div");
2213
+ subbar.className = "cd-agent-subbar";
2214
+
2215
+ const providerPill = document.createElement("button");
2216
+ providerPill.type = "button";
2217
+ providerPill.className = "cd-provider-pill-btn";
2218
+ providerPill.title = "Configure BYOK provider & model";
2219
+ providerPill.setAttribute("aria-label", "Configure BYOK provider and model");
2220
+ const keyDot = document.createElement("span");
2221
+ keyDot.className = "cd-key-dot";
2222
+ this.keyDotEl = keyDot;
2223
+ const providerLabel = document.createElement("span");
2224
+ providerLabel.className = "cd-provider-pill-label";
2225
+ providerLabel.textContent = "claude-sonnet-4 · BYOK";
2226
+ this.providerPillLabelEl = providerLabel;
2227
+ providerPill.appendChild(keyDot);
2228
+ providerPill.appendChild(providerLabel);
2229
+ providerPill.addEventListener("click", () => this.toggleByokDrawer());
2230
+
2231
+ const subbarRight = document.createElement("div");
2232
+ subbarRight.className = "cd-subbar-right";
2233
+
2234
+ const keysBtn = document.createElement("button");
2235
+ keysBtn.type = "button";
2236
+ keysBtn.className = "cd-btn";
2237
+ keysBtn.setAttribute("aria-label", "Open BYOK API key settings");
2238
+ keysBtn.innerHTML = `${ICON_KEY}<span>BYOK</span>`;
2239
+ keysBtn.addEventListener("click", () => this.toggleByokDrawer());
2240
+ this.keysToggleBtn = keysBtn;
2241
+
2242
+ const feedbacksBtn = document.createElement("button");
2243
+ feedbacksBtn.type = "button";
2244
+ feedbacksBtn.className = "cd-btn";
2245
+ feedbacksBtn.setAttribute("aria-label", "Browse feedbacks across environments");
2246
+ feedbacksBtn.innerHTML = `${ICON_INBOX}<span>Feedbacks</span>`;
2247
+ feedbacksBtn.addEventListener("click", () => this.toggleFeedbacksDrawer());
2248
+ this.feedbacksToggleBtn = feedbacksBtn;
2249
+
2250
+ subbarRight.appendChild(keysBtn);
2251
+ subbarRight.appendChild(feedbacksBtn);
2252
+ subbar.appendChild(providerPill);
2253
+ subbar.appendChild(subbarRight);
2254
+ sidebar.appendChild(subbar);
2255
+
2256
+ // 3. Inline BYOK Vault Drawer
2257
+ sidebar.appendChild(this.buildByokDrawerDom());
2258
+
2259
+ // 4. Inline Cross-Environment Feedbacks Drawer
2260
+ sidebar.appendChild(this.buildFeedbacksDrawerDom());
2261
+
2262
+ // 5. Agent Conversation Stream
2263
+ const stream = document.createElement("div");
2264
+ stream.className = "cd-agent-stream";
2265
+ stream.setAttribute("aria-live", "polite");
2266
+ this.agentStreamEl = stream;
2267
+ sidebar.appendChild(stream);
2268
+ this.renderAgentStream();
2269
+
2270
+ // 6. Shared Context Tray + Status + Prompt Input Shell
2271
+ const agentTray = document.createElement("div");
2272
+ agentTray.className = "cd-tray";
2273
+ agentTray.setAttribute("aria-label", "Pinned DOM context for agent");
2274
+ this.agentTrayEl = agentTray;
2275
+ sidebar.appendChild(agentTray);
2276
+
2277
+ const agentStatus = document.createElement("div");
2278
+ agentStatus.className = "cd-status";
2279
+ agentStatus.setAttribute("role", "status");
2280
+ agentStatus.hidden = true;
2281
+ this.agentStatusEl = agentStatus;
2282
+ sidebar.appendChild(agentStatus);
2283
+
2284
+ const promptShell = document.createElement("div");
2285
+ promptShell.className = "cd-prompt-shell";
2286
+
2287
+ const textarea = document.createElement("textarea");
2288
+ textarea.className = "cd-textarea";
2289
+ textarea.placeholder =
2290
+ "Ask the local agent to inspect pinned DOM elements, read Rails views, or propose a fix...";
2291
+ textarea.setAttribute("aria-label", "Agent prompt");
2292
+ textarea.addEventListener("keydown", (ev) => {
2293
+ if ((ev.metaKey || ev.ctrlKey) && ev.key === "Enter") {
2294
+ ev.preventDefault();
2295
+ void this.handleAgentSubmit();
2296
+ } else if (ev.key === "Escape") {
2297
+ ev.preventDefault();
2298
+ this.closeComposer();
2299
+ }
2300
+ });
2301
+ textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
2302
+ this.agentTextareaEl = textarea;
2303
+ promptShell.appendChild(textarea);
2304
+
2305
+ const toolbar = document.createElement("div");
2306
+ toolbar.className = "cd-toolbar";
2307
+ toolbar.appendChild(this.buildPromptToolbarActions(true));
2308
+
2309
+ const sendBtn = document.createElement("button");
2310
+ sendBtn.type = "button";
2311
+ sendBtn.className = "cd-btn cd-btn-primary";
2312
+ sendBtn.setAttribute("aria-label", "Send prompt to local agent");
2313
+ sendBtn.innerHTML = `${ICON_SEND}<span>Ask Agent</span>`;
2314
+ sendBtn.addEventListener("click", () => {
2315
+ void this.handleAgentSubmit();
2316
+ });
2317
+ this.agentSendBtn = sendBtn;
2318
+
2319
+ toolbar.appendChild(sendBtn);
2320
+ promptShell.appendChild(toolbar);
2321
+ sidebar.appendChild(promptShell);
2322
+
2323
+ this.syncProviderControls();
2324
+ return sidebar;
2325
+ }
2326
+
2327
+ private buildByokDrawerDom(): HTMLDivElement {
2328
+ const drawer = document.createElement("div");
2329
+ drawer.className = "cd-inline-drawer cd-byok-drawer";
2330
+ drawer.hidden = true;
2331
+ this.byokDrawerEl = drawer;
2332
+
2333
+ const securityNote = document.createElement("div");
2334
+ securityNote.className = "cd-vault-security-note";
2335
+ 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>`;
2336
+ drawer.appendChild(securityNote);
2337
+
2338
+ const grid = document.createElement("div");
2339
+ grid.className = "cd-form-grid";
2340
+
2341
+ // Provider field
2342
+ const provField = document.createElement("div");
2343
+ provField.className = "cd-field";
2344
+ const provLabel = document.createElement("label");
2345
+ provLabel.className = "cd-field-label";
2346
+ provLabel.textContent = "Provider";
2347
+ const provSelect = document.createElement("select");
2348
+ provSelect.className = "cd-select";
2349
+ provSelect.setAttribute("aria-label", "LLM Provider");
2350
+ provSelect.addEventListener("change", () => {
2351
+ this.selectedVaultProviderId = provSelect.value;
2352
+ this.syncByokDrawerFields();
2353
+ });
2354
+ this.byokProviderSelect = provSelect;
2355
+ provField.appendChild(provLabel);
2356
+ provField.appendChild(provSelect);
2357
+ grid.appendChild(provField);
2358
+
2359
+ // Preset model picker
2360
+ const presetField = document.createElement("div");
2361
+ presetField.className = "cd-field";
2362
+ const presetLabel = document.createElement("label");
2363
+ presetLabel.className = "cd-field-label";
2364
+ presetLabel.textContent = "Preset";
2365
+ const presetSelect = document.createElement("select");
2366
+ presetSelect.className = "cd-select";
2367
+ presetSelect.setAttribute("aria-label", "Model preset");
2368
+ presetSelect.addEventListener("change", () => {
2369
+ if (this.byokModelInput && presetSelect.value) {
2370
+ this.byokModelInput.value = presetSelect.value;
2371
+ }
2372
+ });
2373
+ this.byokModelPresetsSelect = presetSelect;
2374
+ presetField.appendChild(presetLabel);
2375
+ presetField.appendChild(presetSelect);
2376
+ grid.appendChild(presetField);
2377
+
2378
+ // Editable model ID
2379
+ const modelField = document.createElement("div");
2380
+ modelField.className = "cd-field is-full";
2381
+ const modelLabel = document.createElement("label");
2382
+ modelLabel.className = "cd-field-label";
2383
+ modelLabel.textContent = "Model ID";
2384
+ const modelInput = document.createElement("input");
2385
+ modelInput.type = "text";
2386
+ modelInput.className = "cd-input is-mono";
2387
+ modelInput.setAttribute("aria-label", "Model identifier");
2388
+ this.byokModelInput = modelInput;
2389
+ modelField.appendChild(modelLabel);
2390
+ modelField.appendChild(modelInput);
2391
+ grid.appendChild(modelField);
2392
+
2393
+ // Optional Base URL field (for custom OpenAI-compatible provider)
2394
+ const baseUrlField = document.createElement("div");
2395
+ baseUrlField.className = "cd-field is-full";
2396
+ baseUrlField.hidden = true;
2397
+ const baseUrlLabel = document.createElement("label");
2398
+ baseUrlLabel.className = "cd-field-label";
2399
+ baseUrlLabel.textContent = "OpenAI-Compatible Base URL";
2400
+ const baseUrlInput = document.createElement("input");
2401
+ baseUrlInput.type = "url";
2402
+ baseUrlInput.className = "cd-input is-mono";
2403
+ baseUrlInput.placeholder = "https://openrouter.ai/api/v1 or http://localhost:11434/v1";
2404
+ baseUrlInput.setAttribute("aria-label", "Custom OpenAI-compatible Base URL");
2405
+ this.byokBaseUrlInput = baseUrlInput;
2406
+ baseUrlField.appendChild(baseUrlLabel);
2407
+ baseUrlField.appendChild(baseUrlInput);
2408
+ this.byokBaseUrlField = baseUrlField;
2409
+ grid.appendChild(baseUrlField);
2410
+
2411
+ // API Key field
2412
+ const keyField = document.createElement("div");
2413
+ keyField.className = "cd-field is-full";
2414
+ const keyLabel = document.createElement("label");
2415
+ keyLabel.className = "cd-field-label";
2416
+ const keyLabelText = document.createElement("span");
2417
+ keyLabelText.textContent = "API Key";
2418
+ const keyBadge = document.createElement("span");
2419
+ keyBadge.className = "cd-key-source-badge";
2420
+ keyBadge.hidden = true;
2421
+ this.byokKeySourceBadge = keyBadge;
2422
+ keyLabel.appendChild(keyLabelText);
2423
+ keyLabel.appendChild(keyBadge);
2424
+
2425
+ const keyInput = document.createElement("input");
2426
+ keyInput.type = "password";
2427
+ keyInput.autocomplete = "off";
2428
+ keyInput.className = "cd-input is-mono";
2429
+ keyInput.placeholder = "Paste API key (leave blank to keep existing key)";
2430
+ keyInput.setAttribute("aria-label", "Provider API Key");
2431
+ this.byokKeyInput = keyInput;
2432
+ keyField.appendChild(keyLabel);
2433
+ keyField.appendChild(keyInput);
2434
+ grid.appendChild(keyField);
2435
+
2436
+ drawer.appendChild(grid);
2437
+
2438
+ const actions = document.createElement("div");
2439
+ actions.className = "cd-drawer-actions";
2440
+
2441
+ const clearBtn = document.createElement("button");
2442
+ clearBtn.type = "button";
2443
+ clearBtn.className = "cd-btn cd-btn-danger-outline";
2444
+ clearBtn.textContent = "Clear Vault Key";
2445
+ clearBtn.addEventListener("click", () => {
2446
+ void this.handleClearByokKey();
2447
+ });
2448
+
2449
+ const rightGroup = document.createElement("div");
2450
+ rightGroup.className = "cd-diff-btn-group";
2451
+
2452
+ const closeBtn = document.createElement("button");
2453
+ closeBtn.type = "button";
2454
+ closeBtn.className = "cd-btn";
2455
+ closeBtn.textContent = "Close";
2456
+ closeBtn.addEventListener("click", () => {
2457
+ this.isByokDrawerOpen = false;
2458
+ this.syncUiStates();
2459
+ });
2460
+
2461
+ const saveBtn = document.createElement("button");
2462
+ saveBtn.type = "button";
2463
+ saveBtn.className = "cd-btn cd-btn-primary";
2464
+ saveBtn.textContent = "Use & Save";
2465
+ saveBtn.addEventListener("click", () => {
2466
+ void this.handleSaveByokSettings();
2467
+ });
2468
+
2469
+ rightGroup.appendChild(closeBtn);
2470
+ rightGroup.appendChild(saveBtn);
2471
+ actions.appendChild(clearBtn);
2472
+ actions.appendChild(rightGroup);
2473
+ drawer.appendChild(actions);
2474
+
2475
+ return drawer;
2476
+ }
2477
+
2478
+ private buildFeedbacksDrawerDom(): HTMLDivElement {
2479
+ const drawer = document.createElement("div");
2480
+ drawer.className = "cd-inline-drawer cd-feedbacks-drawer";
2481
+ drawer.hidden = true;
2482
+ this.feedbacksDrawerEl = drawer;
2483
+
2484
+ const filterRow = document.createElement("div");
2485
+ filterRow.className = "cd-env-filter-row";
2486
+
2487
+ const tabs = document.createElement("div");
2488
+ tabs.className = "cd-env-tabs";
2489
+ this.feedbacksTabsEl = tabs;
2490
+ filterRow.appendChild(tabs);
2491
+
2492
+ const refreshBtn = document.createElement("button");
2493
+ refreshBtn.type = "button";
2494
+ refreshBtn.className = "cd-btn";
2495
+ refreshBtn.textContent = "Refresh";
2496
+ refreshBtn.addEventListener("click", () => {
2497
+ void this.loadCrossEnvFeedbacks(this.feedbacksEnvFilter);
2498
+ });
2499
+ filterRow.appendChild(refreshBtn);
2500
+ drawer.appendChild(filterRow);
2501
+
2502
+ const list = document.createElement("div");
2503
+ list.className = "cd-feedbacks-list";
2504
+ this.feedbacksListEl = list;
2505
+ drawer.appendChild(list);
2506
+
2507
+ return drawer;
2508
+ }
2509
+
2510
+ private getShortEnvironmentSlug(): string {
2511
+ const raw = (this.config.environment || "development").toLowerCase();
2512
+ if (raw === "development") return "dev";
2513
+ if (raw === "production") return "prod";
2514
+ return raw;
2515
+ }
2516
+
2517
+ private toggleByokDrawer(): void {
2518
+ this.isByokDrawerOpen = !this.isByokDrawerOpen;
2519
+ if (this.isByokDrawerOpen) {
2520
+ this.isFeedbacksDrawerOpen = false;
2521
+ this.selectedVaultProviderId = this.activeProviderId;
2522
+ this.syncProviderControls();
2523
+ }
2524
+ this.syncUiStates();
2525
+ }
2526
+
2527
+ private toggleFeedbacksDrawer(): void {
2528
+ this.isFeedbacksDrawerOpen = !this.isFeedbacksDrawerOpen;
2529
+ if (this.isFeedbacksDrawerOpen) {
2530
+ this.isByokDrawerOpen = false;
2531
+ void this.loadCrossEnvFeedbacks(this.feedbacksEnvFilter);
2532
+ }
2533
+ this.syncUiStates();
2534
+ }
2535
+
2536
+ private async ensureAgentStatusLoaded(): Promise<void> {
2537
+ if (this.agentStatusLoaded) return;
2538
+ try {
2539
+ const status: AgentStatusResponse = await this.apiClient.fetchAgentStatus();
2540
+ this.agentStatusLoaded = true;
2541
+ this.agentWorkspaceName = status.workspace_name || this.agentWorkspaceName;
2542
+ if (Array.isArray(status.mcp_environments) && status.mcp_environments.length > 0) {
2543
+ this.agentMcpEnvironments = status.mcp_environments.map((e) => e.name);
2544
+ }
2545
+ if (Array.isArray(status.providers) && status.providers.length > 0) {
2546
+ this.agentProviders = status.providers;
2547
+ }
2548
+ if (status.active_provider) {
2549
+ this.activeProviderId = status.active_provider;
2550
+ this.selectedVaultProviderId = status.active_provider;
2551
+ }
2552
+ this.syncProviderControls();
2553
+ this.renderAgentStream();
2554
+ } catch {
2555
+ // Keep fallback provider definitions if offline
2556
+ }
2557
+ }
2558
+
2559
+ private getActiveProviderInfo(): AgentProviderInfo {
2560
+ return (
2561
+ this.agentProviders.find((p) => p.id === this.activeProviderId) ||
2562
+ this.agentProviders[0] ||
2563
+ DEFAULT_PROVIDERS_FALLBACK[0]
2564
+ );
2565
+ }
2566
+
2567
+ private syncProviderControls(): void {
2568
+ const active = this.getActiveProviderInfo();
2569
+ if (this.keyDotEl) {
2570
+ this.keyDotEl.classList.toggle("is-ready", Boolean(active.configured));
2571
+ }
2572
+ if (this.providerPillLabelEl) {
2573
+ const sourceTag =
2574
+ active.source === "env"
2575
+ ? "ENV"
2576
+ : active.source === "vault"
2577
+ ? "Vault"
2578
+ : active.source === "local_no_key"
2579
+ ? "Local"
2580
+ : "Set BYOK";
2581
+ this.providerPillLabelEl.textContent = `${active.model} · ${sourceTag}`;
2582
+ }
2583
+
2584
+ if (this.byokProviderSelect) {
2585
+ this.byokProviderSelect.innerHTML = "";
2586
+ for (const prov of this.agentProviders) {
2587
+ const opt = document.createElement("option");
2588
+ opt.value = prov.id;
2589
+ opt.textContent = prov.configured ? `${prov.label} (Ready)` : prov.label;
2590
+ if (prov.id === this.selectedVaultProviderId) {
2591
+ opt.selected = true;
2592
+ }
2593
+ this.byokProviderSelect.appendChild(opt);
2594
+ }
2595
+ this.byokProviderSelect.value = this.selectedVaultProviderId;
2596
+ }
2597
+
2598
+ this.syncByokDrawerFields();
2599
+ }
2600
+
2601
+ private syncByokDrawerFields(): void {
2602
+ const selected =
2603
+ this.agentProviders.find((p) => p.id === this.selectedVaultProviderId) ||
2604
+ this.getActiveProviderInfo();
2605
+
2606
+ if (this.byokModelPresetsSelect) {
2607
+ this.byokModelPresetsSelect.innerHTML = "";
2608
+ for (const modelName of selected.models || [selected.default_model]) {
2609
+ const opt = document.createElement("option");
2610
+ opt.value = modelName;
2611
+ opt.textContent = modelName;
2612
+ if (modelName === selected.model) {
2613
+ opt.selected = true;
2614
+ }
2615
+ this.byokModelPresetsSelect.appendChild(opt);
2616
+ }
2617
+ }
2618
+
2619
+ if (this.byokModelInput) {
2620
+ this.byokModelInput.value = selected.model || selected.default_model;
2621
+ }
2622
+
2623
+ if (this.byokBaseUrlField && this.byokBaseUrlInput) {
2624
+ this.byokBaseUrlField.hidden = !selected.supports_base_url;
2625
+ this.byokBaseUrlInput.value = selected.base_url || "";
2626
+ }
2627
+
2628
+ if (this.byokKeySourceBadge) {
2629
+ if (selected.configured) {
2630
+ this.byokKeySourceBadge.hidden = false;
2631
+ const src =
2632
+ selected.source === "env"
2633
+ ? `ENV ${selected.env_var_hint}`
2634
+ : selected.source === "vault"
2635
+ ? "Vault"
2636
+ : "Local URL";
2637
+ this.byokKeySourceBadge.textContent = selected.masked_key
2638
+ ? `${src} (${selected.masked_key})`
2639
+ : src;
2640
+ } else {
2641
+ this.byokKeySourceBadge.hidden = true;
2642
+ }
2643
+ }
2644
+
2645
+ if (this.byokKeyInput) {
2646
+ this.byokKeyInput.value = "";
2647
+ this.byokKeyInput.placeholder = selected.configured
2648
+ ? "Leave blank to keep configured key, or paste to override"
2649
+ : `Paste key or export ${selected.env_var_hint}`;
2650
+ }
2651
+ }
2652
+
2653
+ private async handleSaveByokSettings(): Promise<void> {
2654
+ const provider = this.byokProviderSelect?.value || this.selectedVaultProviderId;
2655
+ const model = (this.byokModelInput?.value || "").trim();
2656
+ const rawKey = (this.byokKeyInput?.value || "").trim();
2657
+ const baseUrl = (this.byokBaseUrlInput?.value || "").trim();
2658
+
2659
+ try {
2660
+ const payload: {
2661
+ provider: string;
2662
+ model?: string;
2663
+ api_key?: string;
2664
+ base_url?: string;
2665
+ make_active: boolean;
2666
+ } = {
2667
+ provider,
2668
+ model: model || undefined,
2669
+ make_active: true
2670
+ };
2671
+ if (rawKey.length > 0) {
2672
+ payload.api_key = rawKey;
2673
+ }
2674
+ if (provider === "custom") {
2675
+ payload.base_url = baseUrl;
2676
+ }
2677
+
2678
+ const updated = await this.apiClient.saveAgentKeys(payload);
2679
+ if (this.byokKeyInput) {
2680
+ this.byokKeyInput.value = "";
2681
+ }
2682
+ this.activeProviderId = updated.active_provider || provider;
2683
+ this.selectedVaultProviderId = this.activeProviderId;
2684
+ if (Array.isArray(updated.providers)) {
2685
+ this.agentProviders = updated.providers;
2686
+ }
2687
+ this.isByokDrawerOpen = false;
2688
+ this.syncProviderControls();
2689
+ this.syncUiStates();
2690
+ this.showStatus("Saved provider settings in local encrypted vault.", "success");
2691
+ } catch (err) {
2692
+ const msg = err instanceof Error ? err.message : "Failed to save BYOK settings.";
2693
+ this.showStatus(msg, "error");
2694
+ }
2695
+ }
2696
+
2697
+ private async handleClearByokKey(): Promise<void> {
2698
+ const provider = this.byokProviderSelect?.value || this.selectedVaultProviderId;
2699
+ try {
2700
+ const updated = await this.apiClient.deleteAgentKeys(provider);
2701
+ if (this.byokKeyInput) {
2702
+ this.byokKeyInput.value = "";
2703
+ }
2704
+ if (Array.isArray(updated.providers)) {
2705
+ this.agentProviders = updated.providers;
2706
+ }
2707
+ this.activeProviderId = updated.active_provider || this.activeProviderId;
2708
+ this.syncProviderControls();
2709
+ this.showStatus(`Cleared stored vault key for ${provider}.`, "success");
2710
+ } catch (err) {
2711
+ const msg = err instanceof Error ? err.message : "Failed to clear key.";
2712
+ this.showStatus(msg, "error");
2713
+ }
2714
+ }
2715
+
2716
+ private async loadCrossEnvFeedbacks(environment: string): Promise<void> {
2717
+ this.feedbacksEnvFilter = environment;
2718
+ this.isLoadingFeedbacks = true;
2719
+ this.renderFeedbacksDrawerContent();
2720
+
2721
+ try {
2722
+ const res = await this.apiClient.fetchAgentFeedbacks(environment, "new");
2723
+ this.crossEnvFeedbacks = Array.isArray(res.feedbacks) ? res.feedbacks : [];
2724
+ if (Array.isArray(res.environments_queried) && res.environments_queried.length > 0) {
2725
+ for (const envName of res.environments_queried) {
2726
+ if (!this.agentMcpEnvironments.includes(envName)) {
2727
+ this.agentMcpEnvironments.push(envName);
2728
+ }
2729
+ }
2730
+ }
2731
+ } catch (err) {
2732
+ const msg = err instanceof Error ? err.message : "Failed to query feedbacks.";
2733
+ this.showStatus(msg, "error");
2734
+ } finally {
2735
+ this.isLoadingFeedbacks = false;
2736
+ this.renderFeedbacksDrawerContent();
2737
+ }
2738
+ }
2739
+
2740
+ private renderFeedbacksDrawerContent(): void {
2741
+ if (this.feedbacksTabsEl) {
2742
+ this.feedbacksTabsEl.innerHTML = "";
2743
+ const envOptions = ["all", ...this.agentMcpEnvironments];
2744
+ for (const envName of envOptions) {
2745
+ const tab = document.createElement("button");
2746
+ tab.type = "button";
2747
+ tab.className = `cd-env-tab${this.feedbacksEnvFilter === envName ? " is-active" : ""}`;
2748
+ tab.textContent = envName;
2749
+ tab.addEventListener("click", () => {
2750
+ void this.loadCrossEnvFeedbacks(envName);
2751
+ });
2752
+ this.feedbacksTabsEl.appendChild(tab);
2753
+ }
2754
+ }
2755
+
2756
+ if (!this.feedbacksListEl) return;
2757
+ this.feedbacksListEl.innerHTML = "";
2758
+
2759
+ if (this.isLoadingFeedbacks) {
2760
+ const loading = document.createElement("div");
2761
+ loading.className = "cd-chat-empty-hint";
2762
+ loading.textContent = "Querying connected MCP environments...";
2763
+ this.feedbacksListEl.appendChild(loading);
2764
+ return;
2765
+ }
2766
+
2767
+ if (this.crossEnvFeedbacks.length === 0) {
2768
+ const empty = document.createElement("div");
2769
+ empty.className = "cd-chat-empty-hint";
2770
+ empty.textContent = `No open feedbacks found in ${this.feedbacksEnvFilter}.`;
2771
+ this.feedbacksListEl.appendChild(empty);
2772
+ return;
2773
+ }
2774
+
2775
+ for (const item of this.crossEnvFeedbacks) {
2776
+ const row = document.createElement("div");
2777
+ row.className = "cd-feedback-row";
2778
+
2779
+ const top = document.createElement("div");
2780
+ top.className = "cd-feedback-row-top";
2781
+
2782
+ const idBadge = document.createElement("span");
2783
+ idBadge.className = "cd-feedback-row-id";
2784
+ const qid = item.qualified_id || `${item.environment}:${item.id}`;
2785
+ idBadge.textContent = item.primary_selector ? `${qid} · ${item.primary_selector}` : qid;
2786
+
2787
+ const investigateBtn = document.createElement("button");
2788
+ investigateBtn.type = "button";
2789
+ investigateBtn.className = "cd-btn";
2790
+ investigateBtn.textContent = "Investigate";
2791
+ investigateBtn.addEventListener("click", () => {
2792
+ const prompt = `Investigate feedback ${qid} ("${item.message}")${item.primary_selector ? ` targeting \`${item.primary_selector}\`` : ""} and propose a fix if needed.`;
2793
+ if (this.agentTextareaEl) {
2794
+ this.agentTextareaEl.value = prompt;
2795
+ this.agentTextareaEl.focus();
2796
+ }
2797
+ this.isFeedbacksDrawerOpen = false;
2798
+ this.syncUiStates();
2799
+ });
2800
+
2801
+ top.appendChild(idBadge);
2802
+ top.appendChild(investigateBtn);
2803
+
2804
+ const msgP = document.createElement("p");
2805
+ msgP.className = "cd-feedback-row-msg";
2806
+ msgP.textContent = item.message || "(Context drop without text)";
2807
+
2808
+ row.appendChild(top);
2809
+ row.appendChild(msgP);
2810
+ this.feedbacksListEl.appendChild(row);
2811
+ }
2812
+ }
2813
+
2814
+ private renderAgentStream(): void {
2815
+ if (!this.agentStreamEl) return;
2816
+ this.agentStreamEl.innerHTML = "";
2817
+
2818
+ if (this.agentMessages.length === 0 && !this.isAgentBusy) {
2819
+ const empty = document.createElement("div");
2820
+ empty.className = "cd-agent-empty";
2821
+
2822
+ const title = document.createElement("p");
2823
+ title.className = "cd-agent-empty-title";
2824
+ title.textContent = `Inspect & edit ${this.agentWorkspaceName} from the live DOM.`;
2825
+
2826
+ const desc = document.createElement("p");
2827
+ desc.className = "cd-agent-empty-desc";
2828
+ desc.textContent = `Connected MCP environments: ${this.agentMcpEnvironments.join(", ")}. File edits always stage an inline diff for your approval.`;
2829
+
2830
+ const starters = document.createElement("div");
2831
+ starters.className = "cd-starter-list";
2832
+
2833
+ const starterItems: Array<{ label: string; action: () => void }> = [
2834
+ {
2835
+ label: "Pin an element on this page & find its Rails template",
2836
+ action: () => {
2837
+ if (this.elementReferences.length === 0) {
2838
+ this.startPinSelection();
2839
+ } else if (this.agentTextareaEl) {
2840
+ this.agentTextareaEl.value =
2841
+ "Locate the Rails view/partial rendering the pinned element and explain how it is styled.";
2842
+ void this.handleAgentSubmit();
2843
+ }
2844
+ }
2845
+ },
2846
+ {
2847
+ label: "Triage open feedbacks across all environments",
2848
+ action: () => {
2849
+ if (this.agentTextareaEl) {
2850
+ this.agentTextareaEl.value =
2851
+ "List open ContextDrop feedbacks across all environments and summarize the highest-priority UI issues.";
2852
+ void this.handleAgentSubmit();
2853
+ }
2854
+ }
2855
+ },
2856
+ {
2857
+ label: "Inspect pinned element spacing & propose a clean CSS/ERB fix",
2858
+ action: () => {
2859
+ if (this.agentTextareaEl) {
2860
+ this.agentTextareaEl.value =
2861
+ "Inspect the pinned element in the workspace and stage a proposed file edit to polish its layout and accessibility.";
2862
+ this.agentTextareaEl.focus();
2863
+ }
2864
+ }
2865
+ }
2866
+ ];
2867
+
2868
+ for (const item of starterItems) {
2869
+ const btn = document.createElement("button");
2870
+ btn.type = "button";
2871
+ btn.className = "cd-starter-btn";
2872
+ const span = document.createElement("span");
2873
+ span.textContent = item.label;
2874
+ const arrow = document.createElement("span");
2875
+ arrow.innerHTML = ICON_CHEVRON_RIGHT;
2876
+ btn.appendChild(span);
2877
+ btn.appendChild(arrow);
2878
+ btn.addEventListener("click", item.action);
2879
+ starters.appendChild(btn);
2880
+ }
2881
+
2882
+ empty.appendChild(title);
2883
+ empty.appendChild(desc);
2884
+ empty.appendChild(starters);
2885
+ this.agentStreamEl.appendChild(empty);
2886
+ return;
2887
+ }
2888
+
2889
+ for (const msg of this.agentMessages) {
2890
+ const card = document.createElement("div");
2891
+ card.className = `cd-agent-msg is-${msg.role}`;
2892
+
2893
+ if (msg.role === "user") {
2894
+ if ((msg.elements && msg.elements.length > 0) || (msg.attachments && msg.attachments.length > 0)) {
2895
+ const pills = document.createElement("div");
2896
+ pills.className = "cd-chat-msg-pills";
2897
+ for (const el of msg.elements || []) {
2898
+ const pill = document.createElement("span");
2899
+ pill.className = "cd-chat-msg-pill";
2900
+ pill.textContent = el.selector;
2901
+ pills.appendChild(pill);
2902
+ }
2903
+ for (const att of msg.attachments || []) {
2904
+ const pill = document.createElement("span");
2905
+ pill.className = "cd-chat-msg-pill";
2906
+ pill.textContent = att.label;
2907
+ pills.appendChild(pill);
2908
+ }
2909
+ card.appendChild(pills);
2910
+ }
2911
+
2912
+ const textP = document.createElement("p");
2913
+ textP.className = "cd-chat-msg-text";
2914
+ textP.textContent = msg.content;
2915
+ card.appendChild(textP);
2916
+ } else {
2917
+ if (msg.toolCalls && msg.toolCalls.length > 0) {
2918
+ const traces = document.createElement("div");
2919
+ traces.className = "cd-tool-traces";
2920
+ for (const trace of msg.toolCalls) {
2921
+ const row = document.createElement("div");
2922
+ row.className = `cd-tool-trace${trace.status === "error" ? " is-error" : ""}`;
2923
+ const badge = document.createElement("span");
2924
+ badge.className = "cd-tool-trace-badge";
2925
+ badge.textContent = trace.name;
2926
+ const summary = document.createElement("span");
2927
+ summary.className = "cd-tool-trace-summary";
2928
+ summary.textContent = trace.summary;
2929
+ row.appendChild(badge);
2930
+ row.appendChild(summary);
2931
+ traces.appendChild(row);
2932
+ }
2933
+ card.appendChild(traces);
2934
+ }
2935
+
2936
+ if (msg.content) {
2937
+ const mdBody = document.createElement("div");
2938
+ mdBody.className = "cd-md-body";
2939
+ mdBody.innerHTML = renderSafeMarkdown(msg.content);
2940
+ card.appendChild(mdBody);
2941
+ }
2942
+
2943
+ if (msg.proposedEdits && msg.proposedEdits.length > 0) {
2944
+ for (const edit of msg.proposedEdits) {
2945
+ card.appendChild(this.buildDiffCardDom(edit));
2946
+ }
2947
+ }
2948
+ }
2949
+
2950
+ this.agentStreamEl.appendChild(card);
2951
+ }
2952
+
2953
+ if (this.isAgentBusy) {
2954
+ const thinking = document.createElement("div");
2955
+ thinking.className = "cd-agent-thinking";
2956
+ const lbl = document.createElement("span");
2957
+ lbl.className = "cd-thinking-label";
2958
+ lbl.textContent = "Inspecting workspace & DOM context...";
2959
+ const b1 = document.createElement("div");
2960
+ b1.className = "cd-skeleton-bar";
2961
+ const b2 = document.createElement("div");
2962
+ b2.className = "cd-skeleton-bar is-short";
2963
+ thinking.appendChild(lbl);
2964
+ thinking.appendChild(b1);
2965
+ thinking.appendChild(b2);
2966
+ this.agentStreamEl.appendChild(thinking);
2967
+ }
2968
+
2969
+ this.agentStreamEl.scrollTop = this.agentStreamEl.scrollHeight;
2970
+ }
2971
+
2972
+ private buildDiffCardDom(edit: ProposedFileEdit): HTMLDivElement {
2973
+ const card = document.createElement("div");
2974
+ card.className = "cd-diff-card";
2975
+ card.setAttribute("data-edit-id", edit.id);
2976
+
2977
+ const header = document.createElement("div");
2978
+ header.className = "cd-diff-card-header";
2979
+
2980
+ const pathGroup = document.createElement("div");
2981
+ pathGroup.className = "cd-diff-path-group";
2982
+ const iconSpan = document.createElement("span");
2983
+ iconSpan.innerHTML = ICON_FILE_CODE;
2984
+ const pathSpan = document.createElement("span");
2985
+ pathSpan.className = "cd-diff-path";
2986
+ pathSpan.textContent = edit.path;
2987
+ pathSpan.title = edit.path;
2988
+ pathGroup.appendChild(iconSpan);
2989
+ pathGroup.appendChild(pathSpan);
2990
+
2991
+ const stats = document.createElement("div");
2992
+ stats.className = "cd-diff-stats";
2993
+ const addSpan = document.createElement("span");
2994
+ addSpan.className = "cd-diff-stat-add";
2995
+ addSpan.textContent = `+${edit.added_lines}`;
2996
+ const delSpan = document.createElement("span");
2997
+ delSpan.className = "cd-diff-stat-del";
2998
+ delSpan.textContent = `-${edit.removed_lines}`;
2999
+ stats.appendChild(addSpan);
3000
+ stats.appendChild(delSpan);
3001
+
3002
+ header.appendChild(pathGroup);
3003
+ header.appendChild(stats);
3004
+ card.appendChild(header);
3005
+
3006
+ if (edit.summary) {
3007
+ const summary = document.createElement("div");
3008
+ summary.className = "cd-diff-summary";
3009
+ summary.textContent = edit.summary;
3010
+ card.appendChild(summary);
3011
+ }
3012
+
3013
+ card.appendChild(buildUnifiedDiffElement(document, edit.diff));
674
3014
 
675
- const actions = document.createElement("div");
676
- actions.className = "cd-toolbar-actions";
3015
+ const footer = document.createElement("div");
3016
+ footer.className = "cd-diff-footer";
677
3017
 
678
- if (this.config.features.element_selection) {
679
- const pickBtn = document.createElement("button");
680
- pickBtn.type = "button";
681
- pickBtn.className = "cd-btn";
682
- pickBtn.title = "Freeze & Pin element (⌥⇧P)";
683
- pickBtn.setAttribute("aria-label", "Pin HTML element as context (Option+Shift+P)");
684
- pickBtn.innerHTML = `${ICON_PIN}<span>Pin</span><kbd class="cd-kbd">⌥⇧P</kbd>`;
685
- pickBtn.addEventListener("click", () => this.startPinSelection());
686
- actions.appendChild(pickBtn);
3018
+ const statusPill = document.createElement("span");
3019
+ statusPill.className = `cd-diff-status-pill${edit.status === "applied" ? " is-applied" : edit.status === "rejected" ? " is-rejected" : ""}`;
3020
+ if (edit.status === "applied") {
3021
+ statusPill.innerHTML = `${ICON_CHECK}<span>Applied to workspace</span>`;
3022
+ } else if (edit.status === "rejected") {
3023
+ statusPill.textContent = "Rejected";
3024
+ } else if (edit.status === "reverted") {
3025
+ statusPill.textContent = "Reverted";
3026
+ } else {
3027
+ statusPill.textContent = "Staged · Awaiting approval";
687
3028
  }
3029
+ footer.appendChild(statusPill);
3030
+
3031
+ const btnGroup = document.createElement("div");
3032
+ btnGroup.className = "cd-diff-btn-group";
3033
+
3034
+ if (edit.status === "pending") {
3035
+ const rejectBtn = document.createElement("button");
3036
+ rejectBtn.type = "button";
3037
+ rejectBtn.className = "cd-btn";
3038
+ rejectBtn.textContent = "Reject";
3039
+ rejectBtn.addEventListener("click", () => {
3040
+ void this.handleEditDecision(edit, "reject");
3041
+ });
688
3042
 
689
- if (this.config.features.screenshot_capture) {
690
- const screenshotBtn = document.createElement("button");
691
- screenshotBtn.type = "button";
692
- screenshotBtn.className = "cd-btn";
693
- screenshotBtn.setAttribute("aria-label", "Capture viewport screenshot");
694
- screenshotBtn.innerHTML = `${ICON_CAMERA}<span>Screenshot</span>`;
695
- screenshotBtn.addEventListener("click", () => {
696
- void this.handleViewportScreenshot();
3043
+ const applyBtn = document.createElement("button");
3044
+ applyBtn.type = "button";
3045
+ applyBtn.className = "cd-btn cd-btn-apply";
3046
+ applyBtn.innerHTML = `${ICON_CHECK}<span>Apply Change</span>`;
3047
+ applyBtn.addEventListener("click", () => {
3048
+ void this.handleEditDecision(edit, "apply");
697
3049
  });
698
- actions.appendChild(screenshotBtn);
699
- }
700
3050
 
701
- const uploadBtn = document.createElement("button");
702
- uploadBtn.type = "button";
703
- uploadBtn.className = "cd-btn";
704
- uploadBtn.setAttribute("aria-label", "Upload image attachment");
705
- uploadBtn.innerHTML = `${ICON_IMAGE}<span>Image</span>`;
706
- uploadBtn.addEventListener("click", () => this.fileInputEl?.click());
707
- actions.appendChild(uploadBtn);
3051
+ btnGroup.appendChild(rejectBtn);
3052
+ btnGroup.appendChild(applyBtn);
3053
+ } else if (edit.status === "applied") {
3054
+ const revertBtn = document.createElement("button");
3055
+ revertBtn.type = "button";
3056
+ revertBtn.className = "cd-btn";
3057
+ revertBtn.innerHTML = `${ICON_UNDO}<span>Revert</span>`;
3058
+ revertBtn.addEventListener("click", () => {
3059
+ void this.handleEditDecision(edit, "revert");
3060
+ });
3061
+ btnGroup.appendChild(revertBtn);
3062
+ }
708
3063
 
709
- const submitBtn = document.createElement("button");
710
- submitBtn.type = "button";
711
- submitBtn.className = "cd-btn cd-btn-primary";
712
- submitBtn.setAttribute("aria-label", "Submit feedback");
713
- submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
714
- submitBtn.addEventListener("click", () => {
715
- void this.handleSubmit();
716
- });
717
- this.submitBtn = submitBtn;
3064
+ footer.appendChild(btnGroup);
3065
+ card.appendChild(footer);
3066
+ return card;
3067
+ }
718
3068
 
719
- toolbar.appendChild(actions);
720
- toolbar.appendChild(submitBtn);
721
- promptShell.appendChild(toolbar);
722
- composer.appendChild(promptShell);
3069
+ private async handleEditDecision(
3070
+ edit: ProposedFileEdit,
3071
+ action: "apply" | "reject" | "revert"
3072
+ ): Promise<void> {
3073
+ try {
3074
+ const res =
3075
+ action === "apply"
3076
+ ? await this.apiClient.applyEdit(edit.id)
3077
+ : action === "reject"
3078
+ ? await this.apiClient.rejectEdit(edit.id)
3079
+ : await this.apiClient.revertEdit(edit.id);
3080
+
3081
+ if (res?.edit) {
3082
+ edit.status = res.edit.status;
3083
+ }
3084
+ this.renderAgentStream();
3085
+ if (action === "apply") {
3086
+ this.showStatus(`Applied change to ${edit.path}. Reload page if needed.`, "success");
3087
+ } else if (action === "revert") {
3088
+ this.showStatus(`Reverted ${edit.path} to original contents.`, "success");
3089
+ }
3090
+ } catch (err) {
3091
+ const msg = err instanceof Error ? err.message : `Failed to ${action} edit.`;
3092
+ this.showStatus(msg, "error");
3093
+ }
3094
+ }
723
3095
 
724
- // 3. Freely Draggable Floating Pin Dock (visible when chatbox is closed, or draggable launcher)
725
- const pinDock = document.createElement("div");
726
- pinDock.className = "cd-pin-dock";
727
- this.pinDockEl = pinDock;
3096
+ public async handleAgentSubmit(): Promise<void> {
3097
+ if (this.isAgentBusy) return;
728
3098
 
729
- const dockGrip = document.createElement("span");
730
- dockGrip.className = "cd-pin-dock-grip";
731
- dockGrip.title = "Drag to float anywhere on screen";
732
- dockGrip.innerHTML = ICON_GRIP;
733
- this.attachDragHandle(dockGrip);
734
- pinDock.appendChild(dockGrip);
3099
+ const rawPrompt = (this.agentTextareaEl?.value || "").trim();
3100
+ if (
3101
+ rawPrompt.length === 0 &&
3102
+ this.elementReferences.length === 0 &&
3103
+ this.attachments.length === 0
3104
+ ) {
3105
+ this.showStatus("Enter a prompt or pin an element on the page first.", "error");
3106
+ return;
3107
+ }
735
3108
 
736
- if (this.config.features.element_selection) {
737
- const floatingPinBtn = document.createElement("button");
738
- floatingPinBtn.type = "button";
739
- floatingPinBtn.className = "cd-floating-pin-btn";
740
- floatingPinBtn.title = "Freeze & Pin element (⌥⇧P, or drag to move)";
741
- floatingPinBtn.setAttribute("aria-label", "Freeze & Pin element on page (Option+Shift+P)");
742
- floatingPinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>`;
743
- this.attachDragHandle(floatingPinBtn, () => this.startPinSelection());
744
- this.floatingPinBtn = floatingPinBtn;
745
- pinDock.appendChild(floatingPinBtn);
746
- }
747
-
748
- const trigger = document.createElement("button");
749
- trigger.type = "button";
750
- trigger.className = "cd-trigger";
751
- trigger.setAttribute("aria-label", "Open feedback composer");
752
- trigger.setAttribute("aria-expanded", String(this.isOpen));
753
- trigger.innerHTML = `${ICON_CHAT}<span>ContextDrop</span>`;
754
- this.attachDragHandle(trigger, () => this.toggleComposer());
755
- this.triggerBtn = trigger;
756
- pinDock.appendChild(trigger);
3109
+ const promptText =
3110
+ rawPrompt || "Inspect the pinned DOM element(s) in this Rails workspace and explain how they work.";
3111
+
3112
+ const attachedElements = [...this.elementReferences];
3113
+ const attachedMedia = this.attachments.map((att) => ({
3114
+ id: att.id,
3115
+ label: att.label,
3116
+ preview_url: att.preview_url,
3117
+ attachment_type: att.attachment_type
3118
+ }));
3119
+ const requestAttachments = this.attachments.map((att) => ({
3120
+ attachment_type: att.attachment_type,
3121
+ filename: att.filename,
3122
+ data_url: att.data_url
3123
+ }));
3124
+
3125
+ const now = new Date();
3126
+ const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
3127
+
3128
+ const userMsg: AgentChatMessage = {
3129
+ id: `msg_${Date.now()}_u`,
3130
+ role: "user",
3131
+ content: promptText,
3132
+ createdAt: timeLabel,
3133
+ elements: attachedElements,
3134
+ attachments: attachedMedia
3135
+ };
3136
+ this.agentMessages.push(userMsg);
757
3137
 
758
- root.appendChild(compactBar);
759
- root.appendChild(composer);
760
- root.appendChild(pinDock);
761
- this.shadow.appendChild(root);
3138
+ if (this.agentTextareaEl) {
3139
+ this.agentTextareaEl.value = "";
3140
+ }
3141
+ this.elementReferences = [];
3142
+ this.elementDomNodes.clear();
3143
+ this.attachments = [];
3144
+ this.picker?.hideExternalPreview();
3145
+ this.renderTray();
762
3146
 
3147
+ this.isAgentBusy = true;
3148
+ if (this.agentSendBtn) {
3149
+ this.agentSendBtn.disabled = true;
3150
+ this.agentSendBtn.innerHTML = `<span>Working...</span>`;
3151
+ }
3152
+ this.renderAgentStream();
763
3153
  this.syncUiStates();
3154
+
3155
+ try {
3156
+ const activeProv = this.getActiveProviderInfo();
3157
+ const res = await this.apiClient.sendAgentChat({
3158
+ messages: this.agentMessages.map((m) => ({ role: m.role, content: m.content })),
3159
+ page_url: typeof window !== "undefined" ? window.location.href : "/",
3160
+ element_references: attachedElements,
3161
+ attachments: requestAttachments,
3162
+ provider: activeProv.id,
3163
+ model: activeProv.model
3164
+ });
3165
+
3166
+ this.agentMessages.push({
3167
+ id: `msg_${Date.now()}_a`,
3168
+ role: "assistant",
3169
+ content: res.reply || "",
3170
+ createdAt: timeLabel,
3171
+ toolCalls: res.tool_calls || [],
3172
+ proposedEdits: res.proposed_edits || [],
3173
+ provider: res.provider,
3174
+ model: res.model
3175
+ });
3176
+ this.hideStatus();
3177
+ } catch (err) {
3178
+ const msg = err instanceof Error ? err.message : "Agent request failed.";
3179
+ if (/no api key|byok|api_key/i.test(msg)) {
3180
+ this.isByokDrawerOpen = true;
3181
+ }
3182
+ this.showStatus(msg, "error");
3183
+ } finally {
3184
+ this.isAgentBusy = false;
3185
+ if (this.agentSendBtn) {
3186
+ this.agentSendBtn.disabled = false;
3187
+ this.agentSendBtn.innerHTML = `${ICON_SEND}<span>Ask Agent</span>`;
3188
+ }
3189
+ this.renderAgentStream();
3190
+ this.syncUiStates();
3191
+ }
764
3192
  }
765
3193
 
766
3194
  private syncPinActiveIndicators(pickerActive: boolean): void {
767
- if (this.cornerPinBtn) {
768
- this.cornerPinBtn.classList.toggle("is-active", pickerActive);
769
- this.cornerPinBtn.setAttribute("aria-pressed", String(pickerActive));
770
- }
771
- if (this.floatingPinBtn) {
772
- this.floatingPinBtn.classList.toggle("is-active", pickerActive);
773
- this.floatingPinBtn.setAttribute("aria-pressed", String(pickerActive));
3195
+ for (const btn of [this.cornerPinBtn, this.sidebarPinBtn]) {
3196
+ if (btn) {
3197
+ btn.classList.toggle("is-active", pickerActive);
3198
+ btn.setAttribute("aria-pressed", String(pickerActive));
3199
+ }
774
3200
  }
775
3201
  if (this.compactPinBtn) {
3202
+ const smartMode = this.isSmartSelectionMode();
776
3203
  this.compactPinBtn.classList.toggle("is-active", pickerActive);
777
- this.compactPinBtn.innerHTML = pickerActive
778
- ? `${ICON_PIN}<span>Pinning</span>`
779
- : `${ICON_PIN}<span>Pin Element</span>`;
3204
+ if (smartMode) {
3205
+ this.compactPinBtn.title = "Highlight an area on the page";
3206
+ this.compactPinBtn.setAttribute("aria-label", "Toggle page highlight mode");
3207
+ this.compactPinBtn.innerHTML = pickerActive
3208
+ ? `${ICON_PIN}<span>Selecting</span>`
3209
+ : `${ICON_PIN}<span>Select area</span>`;
3210
+ } else {
3211
+ this.compactPinBtn.title = "Toggle Freeze & Pin (⌥⇧P)";
3212
+ this.compactPinBtn.setAttribute("aria-label", "Toggle element pin mode (Option+Shift+P)");
3213
+ this.compactPinBtn.innerHTML = pickerActive
3214
+ ? `${ICON_PIN}<span>Pinning</span>`
3215
+ : `${ICON_PIN}<span>Pin Element</span>`;
3216
+ }
780
3217
  }
781
3218
  }
782
3219
 
3220
+ private getVisibleContextCount(): number {
3221
+ if (!this.isSmartSelectionMode()) {
3222
+ return this.elementReferences.length + this.attachments.length;
3223
+ }
3224
+ const unlinkedAttachments = this.attachments.filter(
3225
+ (att) =>
3226
+ !(
3227
+ att.metadata?.auto_smart_context === true &&
3228
+ att.element_reference_ref &&
3229
+ this.elementReferences.some((el) => el.client_ref === att.element_reference_ref)
3230
+ )
3231
+ );
3232
+ return this.elementReferences.length + unlinkedAttachments.length;
3233
+ }
3234
+
783
3235
  private syncUiStates(): void {
784
3236
  const pickerActive = this.picker ? this.picker.isActive() : false;
785
- const totalContextCount = this.elementReferences.length + this.attachments.length;
3237
+ const totalContextCount = this.getVisibleContextCount();
3238
+ const agentMode = this.isAgentModeActive();
3239
+ const smartMode = this.isSmartSelectionMode();
3240
+
3241
+ const showAgentSidebar = this.isOpen && !this.isMinimized && agentMode;
3242
+ const showFeedbackComposer = this.isOpen && !this.isMinimized && !agentMode;
786
3243
 
787
3244
  if (this.composerEl) {
788
- this.composerEl.hidden = !this.isOpen || this.isMinimized;
3245
+ this.composerEl.hidden = !showFeedbackComposer;
3246
+ this.composerEl.classList.toggle("is-smart-mode", smartMode);
3247
+ }
3248
+ if (this.composerTitleEl) {
3249
+ this.composerTitleEl.textContent = smartMode ? "Send Feedback" : "ContextDrop";
3250
+ }
3251
+ if (this.composerMinBtn) {
3252
+ this.composerMinBtn.hidden = smartMode;
3253
+ }
3254
+ if (this.composerModeSwitchWrap) {
3255
+ this.composerModeSwitchWrap.hidden = !this.config.agent?.enabled;
789
3256
  }
3257
+ if (this.textareaEl && !this.customPlaceholderSet) {
3258
+ this.textareaEl.placeholder = smartMode
3259
+ ? DEFAULT_SMART_PLACEHOLDER
3260
+ : DEFAULT_VERBOSE_PLACEHOLDER;
3261
+ }
3262
+ if (this.composerToolbarPickBtn) {
3263
+ if (smartMode) {
3264
+ this.composerToolbarPickBtn.title = "Highlight an area on the page";
3265
+ this.composerToolbarPickBtn.setAttribute("aria-label", "Highlight an area on the page");
3266
+ this.composerToolbarPickBtn.innerHTML = `${ICON_PIN}<span>Select area</span>`;
3267
+ } else {
3268
+ this.composerToolbarPickBtn.title = "Freeze & Pin element (⌥⇧P)";
3269
+ this.composerToolbarPickBtn.setAttribute(
3270
+ "aria-label",
3271
+ "Pin HTML element as context (Option+Shift+P)"
3272
+ );
3273
+ this.composerToolbarPickBtn.innerHTML = `${ICON_PIN}<span>Pin</span><kbd class="cd-kbd">⌥⇧P</kbd>`;
3274
+ }
3275
+ }
3276
+ if (this.composerToolbarScreenshotBtn) {
3277
+ this.composerToolbarScreenshotBtn.hidden = smartMode;
3278
+ }
3279
+ if (this.composerToolbarUploadBtn) {
3280
+ this.composerToolbarUploadBtn.innerHTML = smartMode
3281
+ ? `${ICON_IMAGE}<span>Add image</span>`
3282
+ : `${ICON_IMAGE}<span>Image</span>`;
3283
+ }
3284
+ if (this.editBannerEl && this.editBannerInfoEl) {
3285
+ if (this.editingFeedbackId !== null) {
3286
+ this.editBannerEl.hidden = false;
3287
+ this.editBannerInfoEl.innerHTML = "";
3288
+ const iconSpan = document.createElement("span");
3289
+ iconSpan.innerHTML = ICON_EDIT;
3290
+ const labelSpan = document.createElement("span");
3291
+ labelSpan.textContent = smartMode ? "Editing your feedback" : "Editing feedback";
3292
+ this.editBannerInfoEl.appendChild(iconSpan);
3293
+ this.editBannerInfoEl.appendChild(labelSpan);
3294
+ if (!smartMode) {
3295
+ const idSpan = document.createElement("span");
3296
+ idSpan.className = "cd-edit-banner-id";
3297
+ idSpan.textContent = `#${this.editingFeedbackId}`;
3298
+ this.editBannerInfoEl.appendChild(idSpan);
3299
+ }
3300
+ } else {
3301
+ this.editBannerEl.hidden = true;
3302
+ }
3303
+ }
3304
+ if (this.submitBtn && !this.isSubmitting) {
3305
+ if (this.editingFeedbackId !== null) {
3306
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
3307
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
3308
+ } else {
3309
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
3310
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
3311
+ }
3312
+ }
3313
+
3314
+ if (this.agentSidebarEl) {
3315
+ this.agentSidebarEl.hidden = !showAgentSidebar;
3316
+ }
3317
+ if (this.sidebarEnvPillEl) {
3318
+ this.sidebarEnvPillEl.textContent = this.getShortEnvironmentSlug();
3319
+ }
3320
+ if (this.sidebarPushBtn) {
3321
+ this.sidebarPushBtn.classList.toggle("is-active", this.pushPageLayout);
3322
+ }
3323
+ if (this.byokDrawerEl) {
3324
+ this.byokDrawerEl.hidden = !this.isByokDrawerOpen;
3325
+ }
3326
+ if (this.keysToggleBtn) {
3327
+ this.keysToggleBtn.classList.toggle("is-active", this.isByokDrawerOpen);
3328
+ }
3329
+ if (this.feedbacksDrawerEl) {
3330
+ this.feedbacksDrawerEl.hidden = !this.isFeedbacksDrawerOpen;
3331
+ }
3332
+ if (this.feedbacksToggleBtn) {
3333
+ this.feedbacksToggleBtn.classList.toggle("is-active", this.isFeedbacksDrawerOpen);
3334
+ }
3335
+
3336
+ this.syncHostPagePushMargin(showAgentSidebar && this.pushPageLayout);
3337
+
790
3338
  if (this.compactBarEl) {
791
3339
  this.compactBarEl.hidden = !(this.isOpen && this.isMinimized);
792
- }
793
- if (this.pinDockEl) {
794
- this.pinDockEl.hidden = this.isOpen;
3340
+ this.compactBarEl.classList.toggle("is-smart-mode", smartMode);
795
3341
  }
796
3342
 
797
- if (this.triggerBtn) {
798
- this.triggerBtn.setAttribute("aria-expanded", String(this.isOpen && !this.isMinimized));
799
- const countBadge =
800
- totalContextCount > 0 ? `<span class="cd-count-pill">${totalContextCount}</span>` : "";
801
- this.triggerBtn.innerHTML = `${ICON_CHAT}<span>ContextDrop</span>${countBadge}`;
3343
+ if (this.bookCornerBtn) {
3344
+ this.bookCornerBtn.hidden = this.isOpen;
3345
+ this.bookCornerBtn.setAttribute("aria-expanded", String(this.isOpen && !this.isMinimized));
3346
+ this.bookCornerBtn.setAttribute(
3347
+ "aria-label",
3348
+ smartMode
3349
+ ? "Send feedback or drag corner to highlight part of the page"
3350
+ : "Open ContextDrop chatbox, or drag corner to pin an element on the page"
3351
+ );
3352
+ }
3353
+ if (this.bookCornerHintEl) {
3354
+ this.bookCornerHintEl.textContent = this.config.agent?.enabled
3355
+ ? "Open Agent · Drag to pin"
3356
+ : smartMode
3357
+ ? "Send feedback · Drag to highlight"
3358
+ : "Click to chat · Drag to pin";
3359
+ }
3360
+ if (this.bookCornerAgentDotEl) {
3361
+ this.bookCornerAgentDotEl.hidden = !this.config.agent?.enabled;
3362
+ }
3363
+ if (this.bookCornerCountEl) {
3364
+ this.bookCornerCountEl.hidden = totalContextCount === 0;
3365
+ this.bookCornerCountEl.textContent = String(totalContextCount);
802
3366
  }
803
3367
 
3368
+ const pinCountHtml =
3369
+ this.elementReferences.length > 0
3370
+ ? `<span class="cd-count-pill">${this.elementReferences.length}</span>`
3371
+ : "";
804
3372
  if (this.cornerPinBtn) {
805
- const pinCount =
806
- this.elementReferences.length > 0
807
- ? `<span class="cd-count-pill">${this.elementReferences.length}</span>`
808
- : "";
809
- this.cornerPinBtn.innerHTML = `${ICON_PIN}<span>Pin Element</span>${pinCount}`;
3373
+ if (smartMode) {
3374
+ this.cornerPinBtn.title = "Highlight an area on the page";
3375
+ this.cornerPinBtn.setAttribute("aria-label", "Highlight an area on the page");
3376
+ this.cornerPinBtn.innerHTML = `${ICON_PIN}<span>Select area</span>${pinCountHtml}`;
3377
+ } else {
3378
+ this.cornerPinBtn.title = "Freeze & Pin element (⌥⇧P)";
3379
+ this.cornerPinBtn.setAttribute(
3380
+ "aria-label",
3381
+ "Select DOM element on page (Option+Shift+P)"
3382
+ );
3383
+ this.cornerPinBtn.innerHTML = `${ICON_PIN}<span>Pin Element</span>${pinCountHtml}`;
3384
+ }
3385
+ }
3386
+ if (this.sidebarPinBtn) {
3387
+ this.sidebarPinBtn.innerHTML = `${ICON_PIN}<span>Pin</span>${pinCountHtml}`;
810
3388
  }
811
3389
 
812
3390
  this.syncPinActiveIndicators(pickerActive);
813
- this.renderCompactCoachBar(
814
- pickerActive,
815
- this.picker ? this.picker.getCandidateStack().length : 0
816
- );
3391
+ if (!this.isPeelDragging) {
3392
+ this.renderCompactCoachBar(
3393
+ pickerActive,
3394
+ this.picker ? this.picker.getCandidateStack().length : 0
3395
+ );
3396
+ }
817
3397
  }
818
3398
 
819
3399
  private renderCompactCoachBar(pickerActive: boolean, candidateCount: number = 0): void {
820
3400
  if (!this.compactStatusEl) return;
821
3401
  this.compactStatusEl.innerHTML = "";
822
3402
 
3403
+ const smartMode = this.isSmartSelectionMode();
823
3404
  const pinnedCount = this.elementReferences.length;
824
- const totalContextCount = pinnedCount + this.attachments.length;
3405
+ const totalContextCount = this.getVisibleContextCount();
825
3406
 
826
3407
  if (this.compactStepGroupEl) {
827
- this.compactStepGroupEl.hidden = !pickerActive;
3408
+ this.compactStepGroupEl.hidden = !pickerActive || smartMode;
828
3409
  }
829
3410
  if (this.compactLayerUpBtn) {
830
3411
  this.compactLayerUpBtn.disabled = candidateCount <= 1;
@@ -833,6 +3414,20 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
833
3414
  this.compactLayerDownBtn.disabled = candidateCount <= 1;
834
3415
  }
835
3416
 
3417
+ if (pickerActive && smartMode) {
3418
+ const coach = document.createElement("span");
3419
+ coach.className = "cd-compact-coach-text";
3420
+ coach.textContent = "Click any part of the page to highlight it";
3421
+ this.compactStatusEl.appendChild(coach);
3422
+
3423
+ if (this.compactDoneBtn) {
3424
+ this.compactDoneBtn.className = "cd-btn";
3425
+ this.compactDoneBtn.setAttribute("aria-label", "Cancel selection and return to feedback");
3426
+ this.compactDoneBtn.innerHTML = `<span>Cancel</span>`;
3427
+ }
3428
+ return;
3429
+ }
3430
+
836
3431
  if (pickerActive) {
837
3432
  if (pinnedCount === 0) {
838
3433
  const coach = document.createElement("span");
@@ -892,48 +3487,72 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
892
3487
  return;
893
3488
  }
894
3489
 
895
- // Minimized while not actively in Pin Mode
896
3490
  const summary = document.createElement("span");
897
3491
  summary.className = "cd-compact-coach-text";
898
3492
  summary.textContent =
899
3493
  totalContextCount > 0
900
3494
  ? `${totalContextCount} context item${totalContextCount > 1 ? "s" : ""} attached`
901
- : "Chatbox minimized";
3495
+ : this.isAgentModeActive()
3496
+ ? "Agent sidebar minimized"
3497
+ : "Chatbox minimized";
902
3498
  this.compactStatusEl.appendChild(summary);
903
3499
 
904
3500
  if (this.compactDoneBtn) {
905
3501
  this.compactDoneBtn.className = "cd-btn cd-btn-primary";
906
3502
  this.compactDoneBtn.setAttribute("aria-label", "Return to chatbox");
907
- this.compactDoneBtn.innerHTML = `${ICON_EXPAND}<span>Chat</span>`;
3503
+ this.compactDoneBtn.innerHTML = `${ICON_EXPAND}<span>${this.isAgentModeActive() ? "Agent" : "Chat"}</span>`;
908
3504
  }
909
3505
  }
910
3506
 
911
3507
  private renderChatThread(): void {
912
3508
  if (!this.chatThreadEl) return;
913
3509
  this.chatThreadEl.innerHTML = "";
3510
+ const smartMode = this.isSmartSelectionMode();
914
3511
 
915
3512
  if (this.sessionHistory.length === 0) {
916
- const emptyBox = document.createElement("div");
917
- emptyBox.className = "cd-chat-empty";
3513
+ if (smartMode && (this.elementReferences.length > 0 || this.attachments.length > 0)) {
3514
+ this.chatThreadEl.hidden = true;
3515
+ return;
3516
+ }
3517
+ this.chatThreadEl.hidden = false;
918
3518
 
919
- const p1 = document.createElement("p");
920
- p1.className = "cd-chat-empty-text";
921
- p1.textContent = "Drop context directly from this page.";
3519
+ const emptyBox = document.createElement("div");
3520
+ emptyBox.className = smartMode ? "cd-chat-empty is-smart" : "cd-chat-empty";
3521
+
3522
+ if (smartMode) {
3523
+ const hint = document.createElement("p");
3524
+ hint.className = "cd-chat-empty-hint";
3525
+ hint.textContent =
3526
+ "Drag the corner or select an area on the page, or write a quick note below.";
3527
+ emptyBox.appendChild(hint);
3528
+ } else {
3529
+ const p1 = document.createElement("p");
3530
+ p1.className = "cd-chat-empty-text";
3531
+ p1.textContent = "Drop context directly from this page.";
922
3532
 
923
- const p2 = document.createElement("p");
924
- p2.className = "cd-chat-empty-hint";
925
- p2.innerHTML =
926
- "Press <kbd class=\"cd-kbd\">⌥⇧P</kbd> anywhere or click Pin to freeze &amp; pin, scroll to cycle layers, and press <kbd class=\"cd-kbd\">Space</kbd> to pin instantly.";
3533
+ const p2 = document.createElement("p");
3534
+ p2.className = "cd-chat-empty-hint";
3535
+ p2.innerHTML =
3536
+ 'Drag the folded corner onto any element, or press <kbd class="cd-kbd">⌥⇧P</kbd> to freeze &amp; pin, scroll to cycle layers, and press <kbd class="cd-kbd">Space</kbd> to pin.';
927
3537
 
928
- emptyBox.appendChild(p1);
929
- emptyBox.appendChild(p2);
3538
+ emptyBox.appendChild(p1);
3539
+ emptyBox.appendChild(p2);
3540
+ }
930
3541
  this.chatThreadEl.appendChild(emptyBox);
931
3542
  return;
932
3543
  }
933
3544
 
3545
+ this.chatThreadEl.hidden = false;
3546
+
934
3547
  for (const entry of this.sessionHistory) {
3548
+ const entryIdStr = String(entry.id);
3549
+ const isEditingThis = this.editingFeedbackId === entryIdStr;
3550
+ const isConfirmingDelete = this.confirmingDeleteId === entryIdStr;
3551
+ const isDeletingThis = this.deletingFeedbackId === entryIdStr;
3552
+
935
3553
  const msgCard = document.createElement("div");
936
- msgCard.className = "cd-chat-msg";
3554
+ msgCard.className = isEditingThis ? "cd-chat-msg is-editing" : "cd-chat-msg";
3555
+ msgCard.setAttribute("data-feedback-id", entryIdStr);
937
3556
 
938
3557
  if (entry.elements.length > 0 || entry.attachments.length > 0) {
939
3558
  const pills = document.createElement("div");
@@ -941,17 +3560,22 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
941
3560
 
942
3561
  for (const el of entry.elements) {
943
3562
  const pill = document.createElement("span");
944
- pill.className = "cd-chat-msg-pill";
945
- pill.textContent = el.selector;
3563
+ pill.className = smartMode ? "cd-chat-msg-pill is-friendly" : "cd-chat-msg-pill";
3564
+ pill.textContent = smartMode ? this.getElementFriendlyLabel(el) : el.selector;
946
3565
  pills.appendChild(pill);
947
3566
  }
948
3567
  for (const att of entry.attachments) {
3568
+ if (smartMode && att.attachment_type === "screenshot" && entry.elements.length > 0) {
3569
+ continue;
3570
+ }
949
3571
  const pill = document.createElement("span");
950
- pill.className = "cd-chat-msg-pill";
3572
+ pill.className = smartMode ? "cd-chat-msg-pill is-friendly" : "cd-chat-msg-pill";
951
3573
  pill.textContent = att.label;
952
3574
  pills.appendChild(pill);
953
3575
  }
954
- msgCard.appendChild(pills);
3576
+ if (pills.childNodes.length > 0) {
3577
+ msgCard.appendChild(pills);
3578
+ }
955
3579
  }
956
3580
 
957
3581
  if (entry.message) {
@@ -963,14 +3587,102 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
963
3587
 
964
3588
  const meta = document.createElement("div");
965
3589
  meta.className = "cd-chat-msg-meta";
3590
+
3591
+ const metaInfo = document.createElement("div");
3592
+ metaInfo.className = "cd-chat-msg-meta-info";
3593
+
966
3594
  const idSpan = document.createElement("span");
967
- idSpan.textContent = `Dropped #${entry.id}`;
3595
+ const baseLabel = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
3596
+ idSpan.textContent = entry.isEdited ? `${baseLabel} · edited` : baseLabel;
3597
+
3598
+ const sepSpan = document.createElement("span");
3599
+ sepSpan.setAttribute("aria-hidden", "true");
3600
+ sepSpan.textContent = "·";
3601
+
968
3602
  const timeSpan = document.createElement("span");
969
3603
  timeSpan.textContent = entry.createdAt;
970
- meta.appendChild(idSpan);
971
- meta.appendChild(timeSpan);
3604
+
3605
+ metaInfo.appendChild(idSpan);
3606
+ metaInfo.appendChild(sepSpan);
3607
+ metaInfo.appendChild(timeSpan);
3608
+
3609
+ const actions = document.createElement("div");
3610
+ actions.className = "cd-chat-msg-actions";
3611
+
3612
+ const editBtn = document.createElement("button");
3613
+ editBtn.type = "button";
3614
+ editBtn.className = `cd-msg-action-btn${isEditingThis ? " is-active" : ""}`;
3615
+ editBtn.title = isEditingThis ? "Cancel editing" : "Edit feedback";
3616
+ editBtn.setAttribute("aria-label", "Edit feedback");
3617
+ editBtn.setAttribute("aria-pressed", String(isEditingThis));
3618
+ editBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
3619
+ editBtn.innerHTML = ICON_EDIT;
3620
+ editBtn.addEventListener("click", () => {
3621
+ if (this.editingFeedbackId === entryIdStr) {
3622
+ this.cancelEditingFeedback();
3623
+ } else {
3624
+ this.startEditingFeedback(entry.id);
3625
+ }
3626
+ });
3627
+
3628
+ const deleteBtn = document.createElement("button");
3629
+ deleteBtn.type = "button";
3630
+ deleteBtn.className = "cd-msg-action-btn is-danger";
3631
+ deleteBtn.title = "Delete feedback";
3632
+ deleteBtn.setAttribute("aria-label", "Delete feedback");
3633
+ deleteBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
3634
+ deleteBtn.innerHTML = ICON_TRASH;
3635
+ deleteBtn.addEventListener("click", () => {
3636
+ this.requestDeleteFeedback(entry.id);
3637
+ });
3638
+
3639
+ actions.appendChild(editBtn);
3640
+ actions.appendChild(deleteBtn);
3641
+
3642
+ meta.appendChild(metaInfo);
3643
+ meta.appendChild(actions);
972
3644
  msgCard.appendChild(meta);
973
3645
 
3646
+ if (isConfirmingDelete) {
3647
+ const confirmBar = document.createElement("div");
3648
+ confirmBar.className = "cd-msg-delete-confirm";
3649
+ confirmBar.setAttribute("role", "group");
3650
+ confirmBar.setAttribute("aria-label", "Confirm feedback deletion");
3651
+
3652
+ const confirmLabel = document.createElement("span");
3653
+ confirmLabel.className = "cd-msg-delete-label";
3654
+ confirmLabel.textContent = "Delete this feedback?";
3655
+
3656
+ const btnGroup = document.createElement("div");
3657
+ btnGroup.className = "cd-msg-delete-btns";
3658
+
3659
+ const cancelDeleteBtn = document.createElement("button");
3660
+ cancelDeleteBtn.type = "button";
3661
+ cancelDeleteBtn.className = "cd-btn cd-btn-xs";
3662
+ cancelDeleteBtn.setAttribute("aria-label", "Cancel delete");
3663
+ cancelDeleteBtn.disabled = isDeletingThis;
3664
+ cancelDeleteBtn.textContent = "Cancel";
3665
+ cancelDeleteBtn.addEventListener("click", () => {
3666
+ this.cancelDeleteFeedback();
3667
+ });
3668
+
3669
+ const confirmDeleteBtn = document.createElement("button");
3670
+ confirmDeleteBtn.type = "button";
3671
+ confirmDeleteBtn.className = "cd-btn cd-btn-xs cd-btn-danger";
3672
+ confirmDeleteBtn.setAttribute("aria-label", "Confirm delete feedback");
3673
+ confirmDeleteBtn.disabled = isDeletingThis;
3674
+ confirmDeleteBtn.textContent = isDeletingThis ? "Deleting..." : "Delete";
3675
+ confirmDeleteBtn.addEventListener("click", () => {
3676
+ void this.confirmDeleteFeedback(entry.id);
3677
+ });
3678
+
3679
+ btnGroup.appendChild(cancelDeleteBtn);
3680
+ btnGroup.appendChild(confirmDeleteBtn);
3681
+ confirmBar.appendChild(confirmLabel);
3682
+ confirmBar.appendChild(btnGroup);
3683
+ msgCard.appendChild(confirmBar);
3684
+ }
3685
+
974
3686
  this.chatThreadEl.appendChild(msgCard);
975
3687
  }
976
3688
 
@@ -978,10 +3690,125 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
978
3690
  }
979
3691
 
980
3692
  private renderTray(): void {
981
- if (!this.trayEl) return;
982
- this.trayEl.innerHTML = "";
3693
+ for (const targetTray of [this.trayEl, this.agentTrayEl]) {
3694
+ if (!targetTray) continue;
3695
+ this.populateTrayElement(targetTray);
3696
+ }
3697
+ if (this.sessionHistory.length === 0) {
3698
+ this.renderChatThread();
3699
+ }
3700
+ }
3701
+
3702
+ private populateTrayElement(trayContainer: HTMLDivElement): void {
3703
+ trayContainer.innerHTML = "";
3704
+ const smartTray = trayContainer === this.trayEl && this.isSmartSelectionMode();
3705
+
3706
+ if (smartTray) {
3707
+ const linkedShotIds = new Set<string>();
3708
+
3709
+ for (const elRef of this.elementReferences) {
3710
+ const domNode = this.elementDomNodes.get(elRef.client_ref);
3711
+ const friendlyLabel = this.getElementFriendlyLabel(elRef, domNode);
3712
+ const linkedShot = this.attachments.find(
3713
+ (att) => att.element_reference_ref === elRef.client_ref
3714
+ );
3715
+ if (linkedShot) {
3716
+ linkedShotIds.add(linkedShot.id);
3717
+ }
3718
+
3719
+ const card = document.createElement("div");
3720
+ card.className = "cd-smart-card";
3721
+ card.setAttribute("data-chip-type", "smart-context");
3722
+
3723
+ if (domNode) {
3724
+ card.addEventListener("mouseenter", () => this.picker?.showExternalPreview(domNode));
3725
+ card.addEventListener("mouseleave", () => this.picker?.hideExternalPreview());
3726
+ }
3727
+
3728
+ if (linkedShot?.preview_url) {
3729
+ const thumb = document.createElement("img");
3730
+ thumb.className = "cd-smart-card-thumb";
3731
+ thumb.src = linkedShot.preview_url;
3732
+ thumb.alt = friendlyLabel;
3733
+ card.appendChild(thumb);
3734
+ } else {
3735
+ const iconBadge = document.createElement("span");
3736
+ iconBadge.className = "cd-smart-card-icon";
3737
+ iconBadge.innerHTML = ICON_PIN;
3738
+ card.appendChild(iconBadge);
3739
+ }
3740
+
3741
+ const body = document.createElement("div");
3742
+ body.className = "cd-smart-card-body";
3743
+
3744
+ const title = document.createElement("span");
3745
+ title.className = "cd-smart-card-title";
3746
+ title.textContent = friendlyLabel;
3747
+
3748
+ const sub = document.createElement("span");
3749
+ sub.className = "cd-smart-card-sub";
3750
+ sub.textContent = linkedShot
3751
+ ? "Area & surrounding context captured"
3752
+ : "Highlighted on page";
3753
+
3754
+ body.appendChild(title);
3755
+ body.appendChild(sub);
3756
+ card.appendChild(body);
3757
+
3758
+ const removeBtn = document.createElement("button");
3759
+ removeBtn.type = "button";
3760
+ removeBtn.className = "cd-chip-remove";
3761
+ removeBtn.setAttribute("aria-label", `Remove ${friendlyLabel}`);
3762
+ removeBtn.innerHTML = ICON_CLOSE;
3763
+ removeBtn.addEventListener("click", () => this.removeElementReference(elRef.client_ref));
3764
+ card.appendChild(removeBtn);
3765
+
3766
+ trayContainer.appendChild(card);
3767
+ }
3768
+
3769
+ for (const att of this.attachments) {
3770
+ if (linkedShotIds.has(att.id)) continue;
3771
+
3772
+ const card = document.createElement("div");
3773
+ card.className = "cd-smart-card";
3774
+ card.setAttribute("data-chip-type", att.attachment_type);
3775
+
3776
+ if (att.preview_url) {
3777
+ const thumb = document.createElement("img");
3778
+ thumb.className = "cd-smart-card-thumb";
3779
+ thumb.src = att.preview_url;
3780
+ thumb.alt = att.label;
3781
+ card.appendChild(thumb);
3782
+ }
3783
+
3784
+ const body = document.createElement("div");
3785
+ body.className = "cd-smart-card-body";
3786
+
3787
+ const title = document.createElement("span");
3788
+ title.className = "cd-smart-card-title";
3789
+ title.textContent = att.label;
3790
+
3791
+ const sub = document.createElement("span");
3792
+ sub.className = "cd-smart-card-sub";
3793
+ sub.textContent = "Attached image";
3794
+
3795
+ body.appendChild(title);
3796
+ body.appendChild(sub);
3797
+ card.appendChild(body);
3798
+
3799
+ const removeBtn = document.createElement("button");
3800
+ removeBtn.type = "button";
3801
+ removeBtn.className = "cd-chip-remove";
3802
+ removeBtn.setAttribute("aria-label", `Remove ${att.label}`);
3803
+ removeBtn.innerHTML = ICON_CLOSE;
3804
+ removeBtn.addEventListener("click", () => this.removeAttachment(att.id));
3805
+ card.appendChild(removeBtn);
3806
+
3807
+ trayContainer.appendChild(card);
3808
+ }
3809
+ return;
3810
+ }
983
3811
 
984
- // Render ElementReference chips
985
3812
  for (const elRef of this.elementReferences) {
986
3813
  const chip = document.createElement("div");
987
3814
  chip.className = "cd-chip";
@@ -1005,10 +3832,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1005
3832
  chip.appendChild(badge);
1006
3833
  chip.appendChild(label);
1007
3834
 
1008
- if (
1009
- this.config.features.screenshot_capture &&
1010
- domNode
1011
- ) {
3835
+ if (this.config.features.screenshot_capture && domNode) {
1012
3836
  const snapBtn = document.createElement("button");
1013
3837
  snapBtn.type = "button";
1014
3838
  snapBtn.className = "cd-chip-action";
@@ -1029,10 +3853,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1029
3853
  removeBtn.addEventListener("click", () => this.removeElementReference(elRef.client_ref));
1030
3854
 
1031
3855
  chip.appendChild(removeBtn);
1032
- this.trayEl.appendChild(chip);
3856
+ trayContainer.appendChild(chip);
1033
3857
  }
1034
3858
 
1035
- // Render Attachment chips (uploaded images & screenshots)
1036
3859
  for (const att of this.attachments) {
1037
3860
  const chip = document.createElement("div");
1038
3861
  chip.className = "cd-chip";
@@ -1064,7 +3887,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1064
3887
  chip.appendChild(badge);
1065
3888
  chip.appendChild(label);
1066
3889
  chip.appendChild(removeBtn);
1067
- this.trayEl.appendChild(chip);
3890
+ trayContainer.appendChild(chip);
1068
3891
  }
1069
3892
  }
1070
3893
 
@@ -1190,8 +4013,69 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1190
4013
  }
1191
4014
  }
1192
4015
 
4016
+ private captureSmartSurroundingContext(
4017
+ element: Element,
4018
+ elementClientRef: string,
4019
+ friendlyLabel: string
4020
+ ): Promise<void> {
4021
+ const task = (async (): Promise<void> => {
4022
+ if (this.attachments.length >= this.config.limits.max_attachments) {
4023
+ return;
4024
+ }
4025
+ try {
4026
+ const result = await captureSurroundingContextScreenshot(
4027
+ element,
4028
+ this.config.features.smart_capture_padding ?? 84,
4029
+ this.config.privacy.excluded_selectors,
4030
+ elementClientRef
4031
+ );
4032
+ if (!this.elementReferences.some((ref) => ref.client_ref === elementClientRef)) {
4033
+ return;
4034
+ }
4035
+ this.attachments = this.attachments.filter(
4036
+ (att) =>
4037
+ !(
4038
+ att.element_reference_ref === elementClientRef &&
4039
+ att.metadata?.auto_smart_context === true
4040
+ )
4041
+ );
4042
+ this.attachments.push({
4043
+ id: `smartshot_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
4044
+ attachment_type: "screenshot",
4045
+ label: `Context around ${friendlyLabel}`,
4046
+ preview_url: result.dataUrl,
4047
+ blob: result.blob,
4048
+ data_url: result.dataUrl,
4049
+ filename: `context-${Date.now()}.png`,
4050
+ element_reference_ref: elementClientRef,
4051
+ metadata: {
4052
+ ...result.metadata,
4053
+ auto_smart_context: true,
4054
+ friendly_label: friendlyLabel
4055
+ }
4056
+ });
4057
+ this.renderTray();
4058
+ this.syncUiStates();
4059
+ } catch {
4060
+ // Non-fatal in headless or non-canvas environments; smart element card still renders
4061
+ }
4062
+ })();
4063
+
4064
+ this.pendingSmartCaptures.add(task);
4065
+ void task.finally(() => {
4066
+ this.pendingSmartCaptures.delete(task);
4067
+ });
4068
+ return task;
4069
+ }
4070
+
1193
4071
  public async handleSubmit(): Promise<void> {
1194
4072
  if (this.isSubmitting) return;
4073
+ const smartMode = this.isSmartSelectionMode();
4074
+ const editingId = this.editingFeedbackId;
4075
+
4076
+ if (this.pendingSmartCaptures.size > 0) {
4077
+ await Promise.allSettled(Array.from(this.pendingSmartCaptures));
4078
+ }
1195
4079
 
1196
4080
  const message = (this.textareaEl?.value || "").trim();
1197
4081
  if (
@@ -1199,37 +4083,132 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1199
4083
  this.attachments.length === 0 &&
1200
4084
  this.elementReferences.length === 0
1201
4085
  ) {
1202
- this.showStatus("Enter a note, pin an element, or attach a screenshot first.", "error");
4086
+ this.showStatus(
4087
+ smartMode
4088
+ ? "Write a short note or highlight part of the page first."
4089
+ : "Enter a note, pin an element, or attach a screenshot first.",
4090
+ "error"
4091
+ );
1203
4092
  return;
1204
4093
  }
1205
4094
 
1206
4095
  this.isSubmitting = true;
1207
4096
  if (this.submitBtn) {
1208
4097
  this.submitBtn.disabled = true;
1209
- this.submitBtn.innerHTML = `<span>Sending...</span>`;
4098
+ this.submitBtn.innerHTML =
4099
+ editingId !== null ? `<span>Saving...</span>` : `<span>Sending...</span>`;
1210
4100
  }
1211
4101
 
1212
4102
  try {
1213
- const submittedElements = [...this.elementReferences];
1214
- const submittedAttachments = this.attachments.map((att) => ({
4103
+ const submittedElements = structuredClone(this.elementReferences);
4104
+ const submittedAttachments: SessionFeedbackAttachmentItem[] = this.attachments.map((att) => ({
1215
4105
  id: att.id,
4106
+ server_id: att.existing_attachment_id,
1216
4107
  label: att.label,
1217
4108
  preview_url: att.preview_url,
1218
- attachment_type: att.attachment_type
4109
+ attachment_type: att.attachment_type,
4110
+ filename: att.filename,
4111
+ signed_blob_id: att.signed_blob_id,
4112
+ data_url: att.data_url,
4113
+ element_reference_ref: att.element_reference_ref || null,
4114
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
1219
4115
  }));
1220
4116
 
4117
+ const commonMetadata: Record<string, unknown> = {
4118
+ ...this.customMetadata,
4119
+ environment: this.config.environment,
4120
+ selection_mode: smartMode ? "smart" : "verbose",
4121
+ viewport: {
4122
+ width: typeof window !== "undefined" ? window.innerWidth : 0,
4123
+ height: typeof window !== "undefined" ? window.innerHeight : 0
4124
+ },
4125
+ locale: typeof navigator !== "undefined" ? navigator.language : "en"
4126
+ };
4127
+
4128
+ if (editingId !== null) {
4129
+ const existingIdx = this.sessionHistory.findIndex(
4130
+ (item) => String(item.id) === editingId
4131
+ );
4132
+ const existingEntry = existingIdx >= 0 ? this.sessionHistory[existingIdx] : undefined;
4133
+
4134
+ const updatePayload: FeedbackUpdatePayload = {
4135
+ message,
4136
+ metadata: commonMetadata,
4137
+ element_references: this.elementReferences,
4138
+ attachments: this.attachments.map((att) => {
4139
+ if (att.existing_attachment_id !== undefined && att.existing_attachment_id !== null) {
4140
+ return {
4141
+ existing_id: att.existing_attachment_id,
4142
+ attachment_type: att.attachment_type,
4143
+ element_reference_ref: att.element_reference_ref,
4144
+ metadata: att.metadata
4145
+ };
4146
+ }
4147
+ return {
4148
+ attachment_type: att.attachment_type,
4149
+ filename: att.filename,
4150
+ signed_blob_id: att.signed_blob_id,
4151
+ data_url: att.signed_blob_id ? undefined : att.data_url,
4152
+ element_reference_ref: att.element_reference_ref,
4153
+ metadata: att.metadata
4154
+ };
4155
+ })
4156
+ };
4157
+
4158
+ const updateRes = await this.apiClient.updateFeedback(
4159
+ existingEntry?.id ?? editingId,
4160
+ updatePayload,
4161
+ existingEntry?.ownershipToken
4162
+ );
4163
+
4164
+ const mergedPreviewStub: SessionFeedbackEntry = {
4165
+ id: existingEntry?.id ?? updateRes?.id ?? editingId,
4166
+ message:
4167
+ message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
4168
+ rawMessage: message,
4169
+ createdAt: existingEntry?.createdAt || this.formatTimestampLabel(updateRes?.created_at),
4170
+ rawCreatedAt: existingEntry?.rawCreatedAt || updateRes?.created_at,
4171
+ rawUpdatedAt: updateRes?.updated_at || new Date().toISOString(),
4172
+ isEdited: true,
4173
+ status: updateRes?.status || existingEntry?.status,
4174
+ ownershipToken:
4175
+ updateRes?.ownership_token ||
4176
+ updateRes?.feedback?.ownership_token ||
4177
+ existingEntry?.ownershipToken,
4178
+ elements: submittedElements,
4179
+ attachments: submittedAttachments
4180
+ };
4181
+
4182
+ const updatedEntry = updateRes?.feedback
4183
+ ? {
4184
+ ...this.mapOwnRecordToSessionEntry(updateRes.feedback, mergedPreviewStub),
4185
+ isEdited: true
4186
+ }
4187
+ : mergedPreviewStub;
4188
+
4189
+ if (existingIdx >= 0) {
4190
+ this.sessionHistory[existingIdx] = updatedEntry;
4191
+ } else {
4192
+ this.sessionHistory.push(updatedEntry);
4193
+ }
4194
+
4195
+ this.cancelEditingFeedback();
4196
+ this.showStatus(
4197
+ smartMode ? "Your feedback was updated." : "Feedback updated.",
4198
+ "success"
4199
+ );
4200
+ this.emitWidgetEvent("context-drop:update", {
4201
+ response: updateRes,
4202
+ payload: updatePayload
4203
+ });
4204
+ return;
4205
+ }
4206
+
1221
4207
  const payload: FeedbackSubmissionPayload = {
1222
4208
  message,
1223
4209
  page_url: typeof window !== "undefined" ? window.location.href : "/",
1224
4210
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
1225
- metadata: {
1226
- ...this.customMetadata,
1227
- viewport: {
1228
- width: typeof window !== "undefined" ? window.innerWidth : 0,
1229
- height: typeof window !== "undefined" ? window.innerHeight : 0
1230
- },
1231
- locale: typeof navigator !== "undefined" ? navigator.language : "en"
1232
- },
4211
+ metadata: commonMetadata,
1233
4212
  element_references: this.elementReferences,
1234
4213
  attachments: this.attachments.map((att) => ({
1235
4214
  attachment_type: att.attachment_type,
@@ -1245,13 +4224,26 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1245
4224
 
1246
4225
  const now = new Date();
1247
4226
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
1248
- this.sessionHistory.push({
4227
+ const localStub: SessionFeedbackEntry = {
1249
4228
  id: res?.id ?? this.sessionHistory.length + 1,
1250
- message: message || "(Context drop without text)",
4229
+ message:
4230
+ message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
4231
+ rawMessage: message,
1251
4232
  createdAt: timeLabel,
4233
+ rawCreatedAt: res?.created_at,
4234
+ rawUpdatedAt: res?.updated_at || res?.created_at,
4235
+ isEdited: false,
4236
+ status: res?.status,
4237
+ ownershipToken: res?.ownership_token || res?.feedback?.ownership_token,
1252
4238
  elements: submittedElements,
1253
4239
  attachments: submittedAttachments
1254
- });
4240
+ };
4241
+
4242
+ const createdEntry = res?.feedback
4243
+ ? this.mapOwnRecordToSessionEntry(res.feedback, localStub)
4244
+ : localStub;
4245
+
4246
+ this.sessionHistory.push(createdEntry);
1255
4247
 
1256
4248
  if (this.textareaEl) {
1257
4249
  this.textareaEl.value = "";
@@ -1263,24 +4255,56 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1263
4255
  this.renderTray();
1264
4256
  this.renderChatThread();
1265
4257
  this.syncUiStates();
1266
- this.showStatus("Context drop saved.", "success");
4258
+ this.showStatus(
4259
+ smartMode ? "Thanks! Your feedback was sent." : "Context drop saved.",
4260
+ "success"
4261
+ );
4262
+ this.emitWidgetEvent("context-drop:submit", {
4263
+ response: res,
4264
+ payload
4265
+ });
1267
4266
  } catch (err) {
1268
- const msg = err instanceof Error ? err.message : "Failed to submit feedback.";
4267
+ const msg =
4268
+ err instanceof Error
4269
+ ? err.message
4270
+ : editingId !== null
4271
+ ? "Failed to update feedback."
4272
+ : "Failed to submit feedback.";
1269
4273
  this.showStatus(msg, "error");
4274
+ this.emitWidgetEvent("context-drop:error", {
4275
+ error: msg
4276
+ });
1270
4277
  } finally {
1271
4278
  this.isSubmitting = false;
1272
4279
  if (this.submitBtn) {
1273
4280
  this.submitBtn.disabled = false;
1274
- this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
4281
+ if (this.editingFeedbackId !== null) {
4282
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
4283
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
4284
+ } else {
4285
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
4286
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
4287
+ }
4288
+ }
4289
+ this.renderChatThread();
4290
+ }
4291
+ }
4292
+
4293
+ private hideStatus(): void {
4294
+ for (const bar of [this.statusEl, this.agentStatusEl]) {
4295
+ if (bar) {
4296
+ bar.hidden = true;
1275
4297
  }
1276
4298
  }
1277
4299
  }
1278
4300
 
1279
4301
  private showStatus(text: string, kind: "error" | "success"): void {
1280
- if (!this.statusEl) return;
1281
- this.statusEl.textContent = text;
1282
- this.statusEl.className = `cd-status ${kind}`;
1283
- this.statusEl.hidden = false;
4302
+ for (const bar of [this.statusEl, this.agentStatusEl]) {
4303
+ if (!bar) continue;
4304
+ bar.textContent = text;
4305
+ bar.className = `cd-status ${kind}`;
4306
+ bar.hidden = false;
4307
+ }
1284
4308
  }
1285
4309
  }
1286
4310