context_drop 0.2.0 → 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 (32) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +149 -12
  3. data/Rakefile +110 -1
  4. data/app/assets/javascripts/context_drop/context_drop.js +1230 -53
  5. data/app/controllers/context_drop/application_controller.rb +52 -3
  6. data/app/controllers/context_drop/configs_controller.rb +10 -1
  7. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  8. data/app/controllers/context_drop/feedbacks_controller.rb +383 -17
  9. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  10. data/app/javascript/context_drop/__tests__/widget.test.ts +355 -1
  11. data/app/javascript/context_drop/api-client.ts +306 -22
  12. data/app/javascript/context_drop/element-picker.ts +1 -1
  13. data/app/javascript/context_drop/icons.ts +4 -0
  14. data/app/javascript/context_drop/screenshot.ts +1 -1
  15. data/app/javascript/context_drop/styles.ts +181 -0
  16. data/app/javascript/context_drop/types.ts +96 -6
  17. data/app/javascript/context_drop/widget.ts +752 -29
  18. data/app/models/context_drop/feedback.rb +65 -8
  19. data/app/services/context_drop/ownership_token.rb +114 -0
  20. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +8 -0
  21. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +9 -0
  22. data/app/views/layouts/context_drop/application.html.erb +5 -0
  23. data/config/routes.rb +11 -0
  24. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  25. data/lib/context_drop/configuration.rb +26 -0
  26. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +3 -1
  27. data/lib/context_drop/mcp/tools/get_feedback.rb +16 -5
  28. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +3 -0
  29. data/lib/context_drop/mcp/tools/list_feedbacks.rb +22 -2
  30. data/lib/context_drop/mcp/tools/update_feedback_status.rb +3 -1
  31. data/lib/context_drop/version.rb +1 -1
  32. metadata +4 -2
@@ -2,11 +2,16 @@ import type {
2
2
  AgentChatMessage,
3
3
  AgentProviderInfo,
4
4
  AgentStatusResponse,
5
+ ContextDropApiClientOptions,
5
6
  CrossEnvFeedbackItem,
6
7
  ElementReferenceSnapshot,
7
8
  FeedbackSubmissionPayload,
9
+ FeedbackUpdatePayload,
10
+ OwnFeedbackRecord,
8
11
  PendingAttachmentItem,
9
12
  ProposedFileEdit,
13
+ SelectionMode,
14
+ SessionFeedbackAttachmentItem,
10
15
  SessionFeedbackEntry,
11
16
  WidgetConfig,
12
17
  WidgetPosition,
@@ -21,6 +26,7 @@ import {
21
26
  ICON_CHEVRON_UP,
22
27
  ICON_CLOSE,
23
28
  ICON_CODE_PROMPT,
29
+ ICON_EDIT,
24
30
  ICON_EXPAND,
25
31
  ICON_FILE_CODE,
26
32
  ICON_GRIP,
@@ -37,6 +43,7 @@ import {
37
43
  ICON_SIDEBAR,
38
44
  ICON_SUN,
39
45
  ICON_MOON,
46
+ ICON_TRASH,
40
47
  ICON_UNDO
41
48
  } from "./icons.ts";
42
49
  import { WIDGET_SHADOW_STYLES } from "./styles.ts";
@@ -144,12 +151,24 @@ const BaseHTMLElement: typeof HTMLElement =
144
151
 
145
152
  export class ContextDropWidgetElement extends BaseHTMLElement {
146
153
  public static get observedAttributes(): string[] {
147
- return ["data-position", "data-config", "data-theme", "data-cd-theme"];
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
+ ];
148
166
  }
149
167
 
150
168
  public shadow: ShadowRoot | null = null;
151
169
  private config: WidgetConfig = structuredClone(DEFAULT_CONFIG);
152
170
  private customMetadata: Record<string, unknown> = {};
171
+ private customHeaders: Record<string, string> = {};
153
172
  private apiClient: ContextDropApiClient = new ContextDropApiClient("/context_drop");
154
173
  private picker: ElementPicker | null = null;
155
174
 
@@ -173,6 +192,17 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
173
192
  private elementDomNodes: Map<string, Element> = new Map();
174
193
  private attachments: PendingAttachmentItem[] = [];
175
194
  private sessionHistory: SessionFeedbackEntry[] = [];
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;
176
206
 
177
207
  // Local Agent state
178
208
  private agentStatusLoaded: boolean = false;
@@ -215,6 +245,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
215
245
  private composerToolbarScreenshotBtn: HTMLButtonElement | null = null;
216
246
  private composerToolbarUploadBtn: HTMLButtonElement | null = null;
217
247
  private chatThreadEl: HTMLDivElement | null = null;
248
+ private editBannerEl: HTMLDivElement | null = null;
249
+ private editBannerInfoEl: HTMLSpanElement | null = null;
218
250
  private textareaEl: HTMLTextAreaElement | null = null;
219
251
  private trayEl: HTMLDivElement | null = null;
220
252
  private statusEl: HTMLDivElement | null = null;
@@ -226,7 +258,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
226
258
  private sidebarPinBtn: HTMLButtonElement | null = null;
227
259
  private sidebarEnvPillEl: HTMLSpanElement | null = null;
228
260
  private sidebarPushBtn: HTMLButtonElement | null = null;
229
- private providerPillBtn: HTMLButtonElement | null = null;
230
261
  private keyDotEl: HTMLSpanElement | null = null;
231
262
  private providerPillLabelEl: HTMLSpanElement | null = null;
232
263
  private keysToggleBtn: HTMLButtonElement | null = null;
@@ -260,6 +291,37 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
260
291
  this.applyTheme(newValue, false);
261
292
  } else if (name === "data-position" && newValue) {
262
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
+ }
263
325
  }
264
326
  }
265
327
 
@@ -300,6 +362,25 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
300
362
  return;
301
363
  }
302
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
+
303
384
  // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
304
385
  if (
305
386
  !this.isSmartSelectionMode() &&
@@ -414,6 +495,51 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
414
495
  return this.config;
415
496
  }
416
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
+
417
543
  public setWidgetConfig(partial: Partial<WidgetConfig>): void {
418
544
  const wasAgentEnabled = Boolean(this.config.agent?.enabled);
419
545
  if (
@@ -460,8 +586,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
460
586
  return;
461
587
  }
462
588
  this.surfaceMode = mode;
463
- if (mode === "agent" && this.isOpen) {
464
- void this.ensureAgentStatusLoaded();
589
+ if (this.isOpen) {
590
+ if (mode === "agent") {
591
+ void this.ensureAgentStatusLoaded();
592
+ } else if (!this.isMinimized) {
593
+ void this.ensureOwnFeedbacksLoaded();
594
+ }
465
595
  }
466
596
  this.renderTray();
467
597
  this.renderChatThread();
@@ -481,6 +611,301 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
481
611
  return [...this.sessionHistory];
482
612
  }
483
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
+
484
909
  public getAgentMessages(): AgentChatMessage[] {
485
910
  return [...this.agentMessages];
486
911
  }
@@ -514,16 +939,23 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
514
939
  }
515
940
 
516
941
  public openComposer(): void {
942
+ const wasOpen = this.isOpen && !this.isMinimized;
517
943
  this.isOpen = true;
518
944
  this.isMinimized = false;
519
945
  if (this.isAgentModeActive()) {
520
946
  void this.ensureAgentStatusLoaded();
947
+ } else {
948
+ void this.ensureOwnFeedbacksLoaded();
521
949
  }
522
950
  this.syncUiStates();
523
951
  this.focusActiveInput();
952
+ if (!wasOpen) {
953
+ this.emitWidgetEvent("context-drop:open", { open: true });
954
+ }
524
955
  }
525
956
 
526
957
  public closeComposer(): void {
958
+ const wasOpen = this.isOpen;
527
959
  this.isOpen = false;
528
960
  this.isMinimized = false;
529
961
  if (this.picker && this.picker.isActive()) {
@@ -531,6 +963,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
531
963
  }
532
964
  this.picker?.hideExternalPreview();
533
965
  this.syncUiStates();
966
+ if (wasOpen) {
967
+ this.emitWidgetEvent("context-drop:close", { open: false });
968
+ }
534
969
  }
535
970
 
536
971
  public toggleComposer(): void {
@@ -791,7 +1226,15 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
791
1226
 
792
1227
  private readDataAttributes(): void {
793
1228
  const endpoint = this.getAttribute("data-endpoint") || "/context_drop";
794
- 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
+ });
795
1238
 
796
1239
  const rawConfig = this.getAttribute("data-config");
797
1240
  if (rawConfig) {
@@ -847,6 +1290,16 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
847
1290
  if (themeOverride === "dark" || themeOverride === "light") {
848
1291
  this.currentTheme = themeOverride;
849
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
+ }
850
1303
  }
851
1304
 
852
1305
  private detectViewportSnapCorner(
@@ -1508,6 +1961,27 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1508
1961
  const promptShell = document.createElement("div");
1509
1962
  promptShell.className = "cd-prompt-shell";
1510
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
+
1511
1985
  const textarea = document.createElement("textarea");
1512
1986
  textarea.className = "cd-textarea";
1513
1987
  textarea.placeholder = this.config.placeholder;
@@ -1517,8 +1991,15 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1517
1991
  ev.preventDefault();
1518
1992
  void this.handleSubmit();
1519
1993
  } else if (ev.key === "Escape") {
1994
+ if (ev.defaultPrevented) return;
1520
1995
  ev.preventDefault();
1521
- 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
+ }
1522
2003
  }
1523
2004
  });
1524
2005
  textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
@@ -1746,7 +2227,6 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1746
2227
  providerPill.appendChild(keyDot);
1747
2228
  providerPill.appendChild(providerLabel);
1748
2229
  providerPill.addEventListener("click", () => this.toggleByokDrawer());
1749
- this.providerPillBtn = providerPill;
1750
2230
 
1751
2231
  const subbarRight = document.createElement("div");
1752
2232
  subbarRight.className = "cd-subbar-right";
@@ -2801,6 +3281,35 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
2801
3281
  ? `${ICON_IMAGE}<span>Add image</span>`
2802
3282
  : `${ICON_IMAGE}<span>Image</span>`;
2803
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
+ }
2804
3313
 
2805
3314
  if (this.agentSidebarEl) {
2806
3315
  this.agentSidebarEl.hidden = !showAgentSidebar;
@@ -3036,8 +3545,14 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3036
3545
  this.chatThreadEl.hidden = false;
3037
3546
 
3038
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
+
3039
3553
  const msgCard = document.createElement("div");
3040
- msgCard.className = "cd-chat-msg";
3554
+ msgCard.className = isEditingThis ? "cd-chat-msg is-editing" : "cd-chat-msg";
3555
+ msgCard.setAttribute("data-feedback-id", entryIdStr);
3041
3556
 
3042
3557
  if (entry.elements.length > 0 || entry.attachments.length > 0) {
3043
3558
  const pills = document.createElement("div");
@@ -3072,14 +3587,102 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3072
3587
 
3073
3588
  const meta = document.createElement("div");
3074
3589
  meta.className = "cd-chat-msg-meta";
3590
+
3591
+ const metaInfo = document.createElement("div");
3592
+ metaInfo.className = "cd-chat-msg-meta-info";
3593
+
3075
3594
  const idSpan = document.createElement("span");
3076
- idSpan.textContent = smartMode ? "Feedback sent" : `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
+
3077
3602
  const timeSpan = document.createElement("span");
3078
3603
  timeSpan.textContent = entry.createdAt;
3079
- meta.appendChild(idSpan);
3080
- 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);
3081
3644
  msgCard.appendChild(meta);
3082
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
+
3083
3686
  this.chatThreadEl.appendChild(msgCard);
3084
3687
  }
3085
3688
 
@@ -3468,6 +4071,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3468
4071
  public async handleSubmit(): Promise<void> {
3469
4072
  if (this.isSubmitting) return;
3470
4073
  const smartMode = this.isSmartSelectionMode();
4074
+ const editingId = this.editingFeedbackId;
3471
4075
 
3472
4076
  if (this.pendingSmartCaptures.size > 0) {
3473
4077
  await Promise.allSettled(Array.from(this.pendingSmartCaptures));
@@ -3491,32 +4095,120 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3491
4095
  this.isSubmitting = true;
3492
4096
  if (this.submitBtn) {
3493
4097
  this.submitBtn.disabled = true;
3494
- this.submitBtn.innerHTML = `<span>Sending...</span>`;
4098
+ this.submitBtn.innerHTML =
4099
+ editingId !== null ? `<span>Saving...</span>` : `<span>Sending...</span>`;
3495
4100
  }
3496
4101
 
3497
4102
  try {
3498
- const submittedElements = [...this.elementReferences];
3499
- const submittedAttachments = this.attachments.map((att) => ({
4103
+ const submittedElements = structuredClone(this.elementReferences);
4104
+ const submittedAttachments: SessionFeedbackAttachmentItem[] = this.attachments.map((att) => ({
3500
4105
  id: att.id,
4106
+ server_id: att.existing_attachment_id,
3501
4107
  label: att.label,
3502
4108
  preview_url: att.preview_url,
3503
- 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) : {}
3504
4115
  }));
3505
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
+
3506
4207
  const payload: FeedbackSubmissionPayload = {
3507
4208
  message,
3508
4209
  page_url: typeof window !== "undefined" ? window.location.href : "/",
3509
4210
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
3510
- metadata: {
3511
- ...this.customMetadata,
3512
- environment: this.config.environment,
3513
- selection_mode: smartMode ? "smart" : "verbose",
3514
- viewport: {
3515
- width: typeof window !== "undefined" ? window.innerWidth : 0,
3516
- height: typeof window !== "undefined" ? window.innerHeight : 0
3517
- },
3518
- locale: typeof navigator !== "undefined" ? navigator.language : "en"
3519
- },
4211
+ metadata: commonMetadata,
3520
4212
  element_references: this.elementReferences,
3521
4213
  attachments: this.attachments.map((att) => ({
3522
4214
  attachment_type: att.attachment_type,
@@ -3532,14 +4224,26 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3532
4224
 
3533
4225
  const now = new Date();
3534
4226
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
3535
- this.sessionHistory.push({
4227
+ const localStub: SessionFeedbackEntry = {
3536
4228
  id: res?.id ?? this.sessionHistory.length + 1,
3537
4229
  message:
3538
4230
  message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
4231
+ rawMessage: message,
3539
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,
3540
4238
  elements: submittedElements,
3541
4239
  attachments: submittedAttachments
3542
- });
4240
+ };
4241
+
4242
+ const createdEntry = res?.feedback
4243
+ ? this.mapOwnRecordToSessionEntry(res.feedback, localStub)
4244
+ : localStub;
4245
+
4246
+ this.sessionHistory.push(createdEntry);
3543
4247
 
3544
4248
  if (this.textareaEl) {
3545
4249
  this.textareaEl.value = "";
@@ -3555,15 +4259,34 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3555
4259
  smartMode ? "Thanks! Your feedback was sent." : "Context drop saved.",
3556
4260
  "success"
3557
4261
  );
4262
+ this.emitWidgetEvent("context-drop:submit", {
4263
+ response: res,
4264
+ payload
4265
+ });
3558
4266
  } catch (err) {
3559
- 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.";
3560
4273
  this.showStatus(msg, "error");
4274
+ this.emitWidgetEvent("context-drop:error", {
4275
+ error: msg
4276
+ });
3561
4277
  } finally {
3562
4278
  this.isSubmitting = false;
3563
4279
  if (this.submitBtn) {
3564
4280
  this.submitBtn.disabled = false;
3565
- 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
+ }
3566
4288
  }
4289
+ this.renderChatThread();
3567
4290
  }
3568
4291
  }
3569
4292