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.
@@ -1,5 +1,5 @@
1
1
  import { MANDATORY_EXCLUDED_SELECTORS, describeSmartComponent } from "./sanitizer.js";
2
- import { ICON_CAMERA, ICON_CHECK, ICON_CHEVRON_DOWN, ICON_CHEVRON_RIGHT, ICON_CHEVRON_UP, ICON_CLOSE, ICON_CODE_PROMPT, ICON_EXPAND, ICON_FILE_CODE, ICON_GRIP, ICON_IMAGE, ICON_INBOX, ICON_KEY, ICON_MINIMIZE, ICON_PIN, ICON_PLUS, ICON_PUSH_LAYOUT, ICON_SCROLL_VERTICAL, ICON_SEND, ICON_SHIELD, ICON_SIDEBAR, ICON_SUN, ICON_MOON, ICON_UNDO } from "./icons.js";
2
+ import { ICON_CAMERA, ICON_CHECK, ICON_CHEVRON_DOWN, ICON_CHEVRON_RIGHT, ICON_CHEVRON_UP, ICON_CLOSE, ICON_CODE_PROMPT, ICON_EDIT, ICON_EXPAND, ICON_FILE_CODE, ICON_GRIP, ICON_IMAGE, ICON_INBOX, ICON_KEY, ICON_MINIMIZE, ICON_PIN, ICON_PLUS, ICON_PUSH_LAYOUT, ICON_SCROLL_VERTICAL, ICON_SEND, ICON_SHIELD, ICON_SIDEBAR, ICON_SUN, ICON_MOON, ICON_TRASH, ICON_UNDO } from "./icons.js";
3
3
  import { WIDGET_SHADOW_STYLES } from "./styles.js";
4
4
  import { ContextDropApiClient } from "./api-client.js";
5
5
  import { ElementPicker } from "./element-picker.js";
@@ -131,6 +131,12 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
131
131
  elementDomNodes = new Map();
132
132
  attachments = [];
133
133
  sessionHistory = [];
134
+ ownFeedbacksLoaded = false;
135
+ inFlightOwnFeedbacksPromise = null;
136
+ editingFeedbackId = null;
137
+ confirmingDeleteId = null;
138
+ deletingFeedbackId = null;
139
+ stashedDraftBeforeEdit = null;
134
140
  // Local Agent state
135
141
  agentStatusLoaded = false;
136
142
  agentWorkspaceName = "rails-app";
@@ -169,6 +175,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
169
175
  composerToolbarScreenshotBtn = null;
170
176
  composerToolbarUploadBtn = null;
171
177
  chatThreadEl = null;
178
+ editBannerEl = null;
179
+ editBannerInfoEl = null;
172
180
  textareaEl = null;
173
181
  trayEl = null;
174
182
  statusEl = null;
@@ -287,6 +295,22 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
287
295
  this.cancelActivePeelDrag();
288
296
  return;
289
297
  }
298
+ if (ev.key === "Escape" &&
299
+ !(this.picker && this.picker.isActive()) &&
300
+ this.isOpen &&
301
+ !this.isMinimized &&
302
+ !this.isAgentModeActive()) {
303
+ if (this.confirmingDeleteId !== null) {
304
+ ev.preventDefault();
305
+ this.cancelDeleteFeedback();
306
+ return;
307
+ }
308
+ if (this.editingFeedbackId !== null) {
309
+ ev.preventDefault();
310
+ this.cancelEditingFeedback();
311
+ return;
312
+ }
313
+ }
290
314
  // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
291
315
  if (!this.isSmartSelectionMode() &&
292
316
  ev.altKey &&
@@ -384,6 +408,8 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
384
408
  "same-origin";
385
409
  const resolvedHeaders = options.headers || this.customHeaders;
386
410
  this.customHeaders = { ...resolvedHeaders };
411
+ this.ownFeedbacksLoaded = false;
412
+ this.inFlightOwnFeedbacksPromise = null;
387
413
  this.apiClient = new ContextDropApiClient(endpoint || "/context_drop", {
388
414
  credentials: resolvedCredentials,
389
415
  headers: this.customHeaders
@@ -457,8 +483,13 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
457
483
  return;
458
484
  }
459
485
  this.surfaceMode = mode;
460
- if (mode === "agent" && this.isOpen) {
461
- void this.ensureAgentStatusLoaded();
486
+ if (this.isOpen) {
487
+ if (mode === "agent") {
488
+ void this.ensureAgentStatusLoaded();
489
+ }
490
+ else if (!this.isMinimized) {
491
+ void this.ensureOwnFeedbacksLoaded();
492
+ }
462
493
  }
463
494
  this.renderTray();
464
495
  this.renderChatThread();
@@ -474,6 +505,267 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
474
505
  getSessionHistory() {
475
506
  return [...this.sessionHistory];
476
507
  }
508
+ getEditingFeedbackId() {
509
+ return this.editingFeedbackId;
510
+ }
511
+ formatTimestampLabel(isoOrLabel) {
512
+ if (isoOrLabel && /^\d{2}:\d{2}$/.test(isoOrLabel.trim())) {
513
+ return isoOrLabel.trim();
514
+ }
515
+ const parsed = isoOrLabel ? new Date(isoOrLabel) : new Date();
516
+ const valid = Number.isNaN(parsed.getTime()) ? new Date() : parsed;
517
+ return `${String(valid.getHours()).padStart(2, "0")}:${String(valid.getMinutes()).padStart(2, "0")}`;
518
+ }
519
+ mapOwnRecordToSessionEntry(record, existingEntry) {
520
+ const smartMode = this.isSmartSelectionMode();
521
+ const rawMessage = typeof record.message === "string" ? record.message : "";
522
+ const displayMessage = rawMessage || (smartMode ? "(Highlighted page area)" : "(Context drop without text)");
523
+ const token = record.ownership_token ||
524
+ existingEntry?.ownershipToken ||
525
+ this.apiClient.getOwnershipToken(record.id) ||
526
+ undefined;
527
+ const isEdited = Boolean(record.created_at && record.updated_at && record.updated_at !== record.created_at);
528
+ const serverAttachments = Array.isArray(record.attachments) ? record.attachments : [];
529
+ const mappedAttachments = serverAttachments.map((att, idx) => {
530
+ const existingAtt = existingEntry?.attachments.find((a) => (a.server_id !== undefined && String(a.server_id) === String(att.id)) ||
531
+ (a.server_id === undefined &&
532
+ idx < (existingEntry?.attachments.length || 0) &&
533
+ existingEntry?.attachments[idx]?.filename === att.filename));
534
+ const previewUrl = existingAtt?.preview_url &&
535
+ (existingAtt.preview_url.startsWith("data:") || existingAtt.preview_url.startsWith("blob:"))
536
+ ? existingAtt.preview_url
537
+ : this.apiClient.buildAttachmentPreviewUrl(record.id, att.id, token);
538
+ const meta = att.metadata && typeof att.metadata === "object" && !Array.isArray(att.metadata)
539
+ ? { ...att.metadata }
540
+ : existingAtt?.metadata
541
+ ? { ...existingAtt.metadata }
542
+ : {};
543
+ let label = existingAtt?.label || "";
544
+ if (!label) {
545
+ if (meta.auto_smart_context === true && typeof meta.friendly_label === "string") {
546
+ label = `Context around ${meta.friendly_label}`;
547
+ }
548
+ else if (att.filename) {
549
+ label = att.filename;
550
+ }
551
+ else {
552
+ label = att.attachment_type === "screenshot" ? "Screenshot" : "Attached image";
553
+ }
554
+ }
555
+ return {
556
+ id: existingAtt?.id || `srv_att_${record.id}_${att.id}`,
557
+ server_id: att.id,
558
+ label,
559
+ preview_url: previewUrl,
560
+ attachment_type: att.attachment_type === "screenshot" ? "screenshot" : "image",
561
+ filename: att.filename,
562
+ element_reference_ref: att.element_reference_ref ?? existingAtt?.element_reference_ref ?? null,
563
+ metadata: meta
564
+ };
565
+ });
566
+ const elements = Array.isArray(record.element_references)
567
+ ? structuredClone(record.element_references)
568
+ : existingEntry?.elements
569
+ ? structuredClone(existingEntry.elements)
570
+ : [];
571
+ return {
572
+ id: record.id,
573
+ message: displayMessage,
574
+ rawMessage,
575
+ createdAt: this.formatTimestampLabel(record.created_at || existingEntry?.rawCreatedAt),
576
+ rawCreatedAt: record.created_at,
577
+ rawUpdatedAt: record.updated_at,
578
+ isEdited: isEdited || Boolean(existingEntry?.isEdited),
579
+ status: record.status,
580
+ ownershipToken: token,
581
+ elements,
582
+ attachments: mappedAttachments
583
+ };
584
+ }
585
+ async refreshOwnFeedbacks() {
586
+ if (typeof fetch !== "function") {
587
+ return [...this.sessionHistory];
588
+ }
589
+ if (this.inFlightOwnFeedbacksPromise) {
590
+ return this.inFlightOwnFeedbacksPromise;
591
+ }
592
+ this.inFlightOwnFeedbacksPromise = (async () => {
593
+ try {
594
+ const res = await this.apiClient.fetchOwnFeedbacks();
595
+ this.ownFeedbacksLoaded = true;
596
+ const records = Array.isArray(res?.feedbacks) ? res.feedbacks : [];
597
+ if (records.length === 0) {
598
+ return [...this.sessionHistory];
599
+ }
600
+ const existingById = new Map();
601
+ for (const entry of this.sessionHistory) {
602
+ existingById.set(String(entry.id), entry);
603
+ }
604
+ const chronologicalServerRecords = [...records].reverse();
605
+ const serverIds = new Set();
606
+ const merged = [];
607
+ for (const record of chronologicalServerRecords) {
608
+ if (!record || record.id === undefined || record.id === null)
609
+ continue;
610
+ const idKey = String(record.id);
611
+ serverIds.add(idKey);
612
+ merged.push(this.mapOwnRecordToSessionEntry(record, existingById.get(idKey)));
613
+ }
614
+ for (const localEntry of this.sessionHistory) {
615
+ if (!serverIds.has(String(localEntry.id))) {
616
+ merged.push(localEntry);
617
+ }
618
+ }
619
+ this.sessionHistory = merged;
620
+ this.renderChatThread();
621
+ this.syncUiStates();
622
+ }
623
+ catch {
624
+ // Non-fatal when offline or using minimal synthetic endpoints
625
+ }
626
+ finally {
627
+ this.inFlightOwnFeedbacksPromise = null;
628
+ }
629
+ return [...this.sessionHistory];
630
+ })();
631
+ return this.inFlightOwnFeedbacksPromise;
632
+ }
633
+ async ensureOwnFeedbacksLoaded() {
634
+ if (this.ownFeedbacksLoaded)
635
+ return;
636
+ await this.refreshOwnFeedbacks();
637
+ }
638
+ startEditingFeedback(feedbackId) {
639
+ const targetKey = String(feedbackId);
640
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
641
+ if (!entry)
642
+ return false;
643
+ this.confirmingDeleteId = null;
644
+ this.hideStatus();
645
+ if (this.editingFeedbackId === null) {
646
+ this.stashedDraftBeforeEdit = {
647
+ message: this.textareaEl?.value || "",
648
+ elementReferences: [...this.elementReferences],
649
+ elementDomNodes: new Map(this.elementDomNodes),
650
+ attachments: [...this.attachments]
651
+ };
652
+ }
653
+ this.editingFeedbackId = targetKey;
654
+ if (this.textareaEl) {
655
+ this.textareaEl.value = entry.rawMessage !== undefined ? entry.rawMessage : entry.message;
656
+ }
657
+ this.elementReferences = structuredClone(entry.elements);
658
+ this.elementDomNodes.clear();
659
+ if (typeof document !== "undefined" && typeof document.querySelector === "function") {
660
+ for (const elRef of this.elementReferences) {
661
+ if (!elRef.selector)
662
+ continue;
663
+ try {
664
+ const liveNode = document.querySelector(elRef.selector);
665
+ if (liveNode) {
666
+ this.elementDomNodes.set(elRef.client_ref, liveNode);
667
+ }
668
+ }
669
+ catch {
670
+ // Ignore invalid or complex selectors not resolvable on current page
671
+ }
672
+ }
673
+ }
674
+ this.attachments = entry.attachments.map((att) => ({
675
+ id: att.id,
676
+ existing_attachment_id: att.server_id,
677
+ attachment_type: att.attachment_type,
678
+ label: att.label,
679
+ preview_url: att.preview_url,
680
+ signed_blob_id: att.signed_blob_id,
681
+ data_url: att.data_url,
682
+ filename: att.filename || att.label || "attachment.png",
683
+ element_reference_ref: att.element_reference_ref || undefined,
684
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
685
+ }));
686
+ this.picker?.refreshPinnedMarkers();
687
+ this.renderTray();
688
+ this.renderChatThread();
689
+ this.syncUiStates();
690
+ this.textareaEl?.focus();
691
+ return true;
692
+ }
693
+ cancelEditingFeedback() {
694
+ if (this.editingFeedbackId === null)
695
+ return;
696
+ this.editingFeedbackId = null;
697
+ if (this.stashedDraftBeforeEdit) {
698
+ if (this.textareaEl) {
699
+ this.textareaEl.value = this.stashedDraftBeforeEdit.message;
700
+ }
701
+ this.elementReferences = this.stashedDraftBeforeEdit.elementReferences;
702
+ this.elementDomNodes = this.stashedDraftBeforeEdit.elementDomNodes;
703
+ this.attachments = this.stashedDraftBeforeEdit.attachments;
704
+ this.stashedDraftBeforeEdit = null;
705
+ }
706
+ else {
707
+ if (this.textareaEl) {
708
+ this.textareaEl.value = "";
709
+ }
710
+ this.elementReferences = [];
711
+ this.elementDomNodes.clear();
712
+ this.attachments = [];
713
+ }
714
+ this.picker?.hideExternalPreview();
715
+ this.picker?.refreshPinnedMarkers();
716
+ this.renderTray();
717
+ this.renderChatThread();
718
+ this.syncUiStates();
719
+ }
720
+ requestDeleteFeedback(feedbackId) {
721
+ const targetKey = String(feedbackId);
722
+ if (!this.sessionHistory.some((item) => String(item.id) === targetKey))
723
+ return;
724
+ this.confirmingDeleteId = this.confirmingDeleteId === targetKey ? null : targetKey;
725
+ this.renderChatThread();
726
+ }
727
+ cancelDeleteFeedback() {
728
+ if (this.confirmingDeleteId === null)
729
+ return;
730
+ this.confirmingDeleteId = null;
731
+ this.renderChatThread();
732
+ }
733
+ async confirmDeleteFeedback(feedbackId) {
734
+ if (this.deletingFeedbackId !== null)
735
+ return;
736
+ const targetKey = String(feedbackId);
737
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
738
+ if (!entry)
739
+ return;
740
+ this.deletingFeedbackId = targetKey;
741
+ this.renderChatThread();
742
+ try {
743
+ const res = await this.apiClient.deleteFeedback(entry.id, entry.ownershipToken);
744
+ if (this.editingFeedbackId === targetKey) {
745
+ this.cancelEditingFeedback();
746
+ }
747
+ this.sessionHistory = this.sessionHistory.filter((item) => String(item.id) !== targetKey);
748
+ this.confirmingDeleteId = null;
749
+ this.deletingFeedbackId = null;
750
+ this.renderChatThread();
751
+ this.renderTray();
752
+ this.syncUiStates();
753
+ this.showStatus(this.isSmartSelectionMode() ? "Your feedback was deleted." : "Feedback deleted.", "success");
754
+ this.emitWidgetEvent("context-drop:delete", {
755
+ response: res,
756
+ id: entry.id
757
+ });
758
+ }
759
+ catch (err) {
760
+ this.deletingFeedbackId = null;
761
+ this.renderChatThread();
762
+ const msg = err instanceof Error ? err.message : "Failed to delete feedback.";
763
+ this.showStatus(msg, "error");
764
+ this.emitWidgetEvent("context-drop:error", {
765
+ error: msg
766
+ });
767
+ }
768
+ }
477
769
  getAgentMessages() {
478
770
  return [...this.agentMessages];
479
771
  }
@@ -509,6 +801,9 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
509
801
  if (this.isAgentModeActive()) {
510
802
  void this.ensureAgentStatusLoaded();
511
803
  }
804
+ else {
805
+ void this.ensureOwnFeedbacksLoaded();
806
+ }
512
807
  this.syncUiStates();
513
808
  this.focusActiveInput();
514
809
  if (!wasOpen) {
@@ -1405,6 +1700,24 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1405
1700
  composer.appendChild(fileInput);
1406
1701
  const promptShell = document.createElement("div");
1407
1702
  promptShell.className = "cd-prompt-shell";
1703
+ const editBanner = document.createElement("div");
1704
+ editBanner.className = "cd-edit-banner";
1705
+ editBanner.hidden = true;
1706
+ const editBannerInfo = document.createElement("span");
1707
+ editBannerInfo.className = "cd-edit-banner-info";
1708
+ this.editBannerInfoEl = editBannerInfo;
1709
+ editBanner.appendChild(editBannerInfo);
1710
+ const cancelEditBtn = document.createElement("button");
1711
+ cancelEditBtn.type = "button";
1712
+ cancelEditBtn.className = "cd-btn cd-btn-xs";
1713
+ cancelEditBtn.setAttribute("aria-label", "Cancel editing feedback");
1714
+ cancelEditBtn.textContent = "Cancel";
1715
+ cancelEditBtn.addEventListener("click", () => {
1716
+ this.cancelEditingFeedback();
1717
+ });
1718
+ editBanner.appendChild(cancelEditBtn);
1719
+ this.editBannerEl = editBanner;
1720
+ promptShell.appendChild(editBanner);
1408
1721
  const textarea = document.createElement("textarea");
1409
1722
  textarea.className = "cd-textarea";
1410
1723
  textarea.placeholder = this.config.placeholder;
@@ -1415,8 +1728,18 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
1415
1728
  void this.handleSubmit();
1416
1729
  }
1417
1730
  else if (ev.key === "Escape") {
1731
+ if (ev.defaultPrevented)
1732
+ return;
1418
1733
  ev.preventDefault();
1419
- this.closeComposer();
1734
+ if (this.confirmingDeleteId !== null) {
1735
+ this.cancelDeleteFeedback();
1736
+ }
1737
+ else if (this.editingFeedbackId !== null) {
1738
+ this.cancelEditingFeedback();
1739
+ }
1740
+ else {
1741
+ this.closeComposer();
1742
+ }
1420
1743
  }
1421
1744
  });
1422
1745
  textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
@@ -2551,6 +2874,37 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
2551
2874
  ? `${ICON_IMAGE}<span>Add image</span>`
2552
2875
  : `${ICON_IMAGE}<span>Image</span>`;
2553
2876
  }
2877
+ if (this.editBannerEl && this.editBannerInfoEl) {
2878
+ if (this.editingFeedbackId !== null) {
2879
+ this.editBannerEl.hidden = false;
2880
+ this.editBannerInfoEl.innerHTML = "";
2881
+ const iconSpan = document.createElement("span");
2882
+ iconSpan.innerHTML = ICON_EDIT;
2883
+ const labelSpan = document.createElement("span");
2884
+ labelSpan.textContent = smartMode ? "Editing your feedback" : "Editing feedback";
2885
+ this.editBannerInfoEl.appendChild(iconSpan);
2886
+ this.editBannerInfoEl.appendChild(labelSpan);
2887
+ if (!smartMode) {
2888
+ const idSpan = document.createElement("span");
2889
+ idSpan.className = "cd-edit-banner-id";
2890
+ idSpan.textContent = `#${this.editingFeedbackId}`;
2891
+ this.editBannerInfoEl.appendChild(idSpan);
2892
+ }
2893
+ }
2894
+ else {
2895
+ this.editBannerEl.hidden = true;
2896
+ }
2897
+ }
2898
+ if (this.submitBtn && !this.isSubmitting) {
2899
+ if (this.editingFeedbackId !== null) {
2900
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
2901
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
2902
+ }
2903
+ else {
2904
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
2905
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
2906
+ }
2907
+ }
2554
2908
  if (this.agentSidebarEl) {
2555
2909
  this.agentSidebarEl.hidden = !showAgentSidebar;
2556
2910
  }
@@ -2751,8 +3105,13 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
2751
3105
  }
2752
3106
  this.chatThreadEl.hidden = false;
2753
3107
  for (const entry of this.sessionHistory) {
3108
+ const entryIdStr = String(entry.id);
3109
+ const isEditingThis = this.editingFeedbackId === entryIdStr;
3110
+ const isConfirmingDelete = this.confirmingDeleteId === entryIdStr;
3111
+ const isDeletingThis = this.deletingFeedbackId === entryIdStr;
2754
3112
  const msgCard = document.createElement("div");
2755
- msgCard.className = "cd-chat-msg";
3113
+ msgCard.className = isEditingThis ? "cd-chat-msg is-editing" : "cd-chat-msg";
3114
+ msgCard.setAttribute("data-feedback-id", entryIdStr);
2756
3115
  if (entry.elements.length > 0 || entry.attachments.length > 0) {
2757
3116
  const pills = document.createElement("div");
2758
3117
  pills.className = "cd-chat-msg-pills";
@@ -2783,13 +3142,86 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
2783
3142
  }
2784
3143
  const meta = document.createElement("div");
2785
3144
  meta.className = "cd-chat-msg-meta";
3145
+ const metaInfo = document.createElement("div");
3146
+ metaInfo.className = "cd-chat-msg-meta-info";
2786
3147
  const idSpan = document.createElement("span");
2787
- idSpan.textContent = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
3148
+ const baseLabel = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
3149
+ idSpan.textContent = entry.isEdited ? `${baseLabel} · edited` : baseLabel;
3150
+ const sepSpan = document.createElement("span");
3151
+ sepSpan.setAttribute("aria-hidden", "true");
3152
+ sepSpan.textContent = "·";
2788
3153
  const timeSpan = document.createElement("span");
2789
3154
  timeSpan.textContent = entry.createdAt;
2790
- meta.appendChild(idSpan);
2791
- meta.appendChild(timeSpan);
3155
+ metaInfo.appendChild(idSpan);
3156
+ metaInfo.appendChild(sepSpan);
3157
+ metaInfo.appendChild(timeSpan);
3158
+ const actions = document.createElement("div");
3159
+ actions.className = "cd-chat-msg-actions";
3160
+ const editBtn = document.createElement("button");
3161
+ editBtn.type = "button";
3162
+ editBtn.className = `cd-msg-action-btn${isEditingThis ? " is-active" : ""}`;
3163
+ editBtn.title = isEditingThis ? "Cancel editing" : "Edit feedback";
3164
+ editBtn.setAttribute("aria-label", "Edit feedback");
3165
+ editBtn.setAttribute("aria-pressed", String(isEditingThis));
3166
+ editBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
3167
+ editBtn.innerHTML = ICON_EDIT;
3168
+ editBtn.addEventListener("click", () => {
3169
+ if (this.editingFeedbackId === entryIdStr) {
3170
+ this.cancelEditingFeedback();
3171
+ }
3172
+ else {
3173
+ this.startEditingFeedback(entry.id);
3174
+ }
3175
+ });
3176
+ const deleteBtn = document.createElement("button");
3177
+ deleteBtn.type = "button";
3178
+ deleteBtn.className = "cd-msg-action-btn is-danger";
3179
+ deleteBtn.title = "Delete feedback";
3180
+ deleteBtn.setAttribute("aria-label", "Delete feedback");
3181
+ deleteBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
3182
+ deleteBtn.innerHTML = ICON_TRASH;
3183
+ deleteBtn.addEventListener("click", () => {
3184
+ this.requestDeleteFeedback(entry.id);
3185
+ });
3186
+ actions.appendChild(editBtn);
3187
+ actions.appendChild(deleteBtn);
3188
+ meta.appendChild(metaInfo);
3189
+ meta.appendChild(actions);
2792
3190
  msgCard.appendChild(meta);
3191
+ if (isConfirmingDelete) {
3192
+ const confirmBar = document.createElement("div");
3193
+ confirmBar.className = "cd-msg-delete-confirm";
3194
+ confirmBar.setAttribute("role", "group");
3195
+ confirmBar.setAttribute("aria-label", "Confirm feedback deletion");
3196
+ const confirmLabel = document.createElement("span");
3197
+ confirmLabel.className = "cd-msg-delete-label";
3198
+ confirmLabel.textContent = "Delete this feedback?";
3199
+ const btnGroup = document.createElement("div");
3200
+ btnGroup.className = "cd-msg-delete-btns";
3201
+ const cancelDeleteBtn = document.createElement("button");
3202
+ cancelDeleteBtn.type = "button";
3203
+ cancelDeleteBtn.className = "cd-btn cd-btn-xs";
3204
+ cancelDeleteBtn.setAttribute("aria-label", "Cancel delete");
3205
+ cancelDeleteBtn.disabled = isDeletingThis;
3206
+ cancelDeleteBtn.textContent = "Cancel";
3207
+ cancelDeleteBtn.addEventListener("click", () => {
3208
+ this.cancelDeleteFeedback();
3209
+ });
3210
+ const confirmDeleteBtn = document.createElement("button");
3211
+ confirmDeleteBtn.type = "button";
3212
+ confirmDeleteBtn.className = "cd-btn cd-btn-xs cd-btn-danger";
3213
+ confirmDeleteBtn.setAttribute("aria-label", "Confirm delete feedback");
3214
+ confirmDeleteBtn.disabled = isDeletingThis;
3215
+ confirmDeleteBtn.textContent = isDeletingThis ? "Deleting..." : "Delete";
3216
+ confirmDeleteBtn.addEventListener("click", () => {
3217
+ void this.confirmDeleteFeedback(entry.id);
3218
+ });
3219
+ btnGroup.appendChild(cancelDeleteBtn);
3220
+ btnGroup.appendChild(confirmDeleteBtn);
3221
+ confirmBar.appendChild(confirmLabel);
3222
+ confirmBar.appendChild(btnGroup);
3223
+ msgCard.appendChild(confirmBar);
3224
+ }
2793
3225
  this.chatThreadEl.appendChild(msgCard);
2794
3226
  }
2795
3227
  this.chatThreadEl.scrollTop = this.chatThreadEl.scrollHeight;
@@ -3113,6 +3545,7 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3113
3545
  if (this.isSubmitting)
3114
3546
  return;
3115
3547
  const smartMode = this.isSmartSelectionMode();
3548
+ const editingId = this.editingFeedbackId;
3116
3549
  if (this.pendingSmartCaptures.size > 0) {
3117
3550
  await Promise.allSettled(Array.from(this.pendingSmartCaptures));
3118
3551
  }
@@ -3128,30 +3561,100 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3128
3561
  this.isSubmitting = true;
3129
3562
  if (this.submitBtn) {
3130
3563
  this.submitBtn.disabled = true;
3131
- this.submitBtn.innerHTML = `<span>Sending...</span>`;
3564
+ this.submitBtn.innerHTML =
3565
+ editingId !== null ? `<span>Saving...</span>` : `<span>Sending...</span>`;
3132
3566
  }
3133
3567
  try {
3134
- const submittedElements = [...this.elementReferences];
3568
+ const submittedElements = structuredClone(this.elementReferences);
3135
3569
  const submittedAttachments = this.attachments.map((att) => ({
3136
3570
  id: att.id,
3571
+ server_id: att.existing_attachment_id,
3137
3572
  label: att.label,
3138
3573
  preview_url: att.preview_url,
3139
- attachment_type: att.attachment_type
3574
+ attachment_type: att.attachment_type,
3575
+ filename: att.filename,
3576
+ signed_blob_id: att.signed_blob_id,
3577
+ data_url: att.data_url,
3578
+ element_reference_ref: att.element_reference_ref || null,
3579
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
3140
3580
  }));
3581
+ const commonMetadata = {
3582
+ ...this.customMetadata,
3583
+ environment: this.config.environment,
3584
+ selection_mode: smartMode ? "smart" : "verbose",
3585
+ viewport: {
3586
+ width: typeof window !== "undefined" ? window.innerWidth : 0,
3587
+ height: typeof window !== "undefined" ? window.innerHeight : 0
3588
+ },
3589
+ locale: typeof navigator !== "undefined" ? navigator.language : "en"
3590
+ };
3591
+ if (editingId !== null) {
3592
+ const existingIdx = this.sessionHistory.findIndex((item) => String(item.id) === editingId);
3593
+ const existingEntry = existingIdx >= 0 ? this.sessionHistory[existingIdx] : undefined;
3594
+ const updatePayload = {
3595
+ message,
3596
+ metadata: commonMetadata,
3597
+ element_references: this.elementReferences,
3598
+ attachments: this.attachments.map((att) => {
3599
+ if (att.existing_attachment_id !== undefined && att.existing_attachment_id !== null) {
3600
+ return {
3601
+ existing_id: att.existing_attachment_id,
3602
+ attachment_type: att.attachment_type,
3603
+ element_reference_ref: att.element_reference_ref,
3604
+ metadata: att.metadata
3605
+ };
3606
+ }
3607
+ return {
3608
+ attachment_type: att.attachment_type,
3609
+ filename: att.filename,
3610
+ signed_blob_id: att.signed_blob_id,
3611
+ data_url: att.signed_blob_id ? undefined : att.data_url,
3612
+ element_reference_ref: att.element_reference_ref,
3613
+ metadata: att.metadata
3614
+ };
3615
+ })
3616
+ };
3617
+ const updateRes = await this.apiClient.updateFeedback(existingEntry?.id ?? editingId, updatePayload, existingEntry?.ownershipToken);
3618
+ const mergedPreviewStub = {
3619
+ id: existingEntry?.id ?? updateRes?.id ?? editingId,
3620
+ message: message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
3621
+ rawMessage: message,
3622
+ createdAt: existingEntry?.createdAt || this.formatTimestampLabel(updateRes?.created_at),
3623
+ rawCreatedAt: existingEntry?.rawCreatedAt || updateRes?.created_at,
3624
+ rawUpdatedAt: updateRes?.updated_at || new Date().toISOString(),
3625
+ isEdited: true,
3626
+ status: updateRes?.status || existingEntry?.status,
3627
+ ownershipToken: updateRes?.ownership_token ||
3628
+ updateRes?.feedback?.ownership_token ||
3629
+ existingEntry?.ownershipToken,
3630
+ elements: submittedElements,
3631
+ attachments: submittedAttachments
3632
+ };
3633
+ const updatedEntry = updateRes?.feedback
3634
+ ? {
3635
+ ...this.mapOwnRecordToSessionEntry(updateRes.feedback, mergedPreviewStub),
3636
+ isEdited: true
3637
+ }
3638
+ : mergedPreviewStub;
3639
+ if (existingIdx >= 0) {
3640
+ this.sessionHistory[existingIdx] = updatedEntry;
3641
+ }
3642
+ else {
3643
+ this.sessionHistory.push(updatedEntry);
3644
+ }
3645
+ this.cancelEditingFeedback();
3646
+ this.showStatus(smartMode ? "Your feedback was updated." : "Feedback updated.", "success");
3647
+ this.emitWidgetEvent("context-drop:update", {
3648
+ response: updateRes,
3649
+ payload: updatePayload
3650
+ });
3651
+ return;
3652
+ }
3141
3653
  const payload = {
3142
3654
  message,
3143
3655
  page_url: typeof window !== "undefined" ? window.location.href : "/",
3144
3656
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
3145
- metadata: {
3146
- ...this.customMetadata,
3147
- environment: this.config.environment,
3148
- selection_mode: smartMode ? "smart" : "verbose",
3149
- viewport: {
3150
- width: typeof window !== "undefined" ? window.innerWidth : 0,
3151
- height: typeof window !== "undefined" ? window.innerHeight : 0
3152
- },
3153
- locale: typeof navigator !== "undefined" ? navigator.language : "en"
3154
- },
3657
+ metadata: commonMetadata,
3155
3658
  element_references: this.elementReferences,
3156
3659
  attachments: this.attachments.map((att) => ({
3157
3660
  attachment_type: att.attachment_type,
@@ -3165,13 +3668,23 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3165
3668
  const res = await this.apiClient.submitFeedback(payload);
3166
3669
  const now = new Date();
3167
3670
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
3168
- this.sessionHistory.push({
3671
+ const localStub = {
3169
3672
  id: res?.id ?? this.sessionHistory.length + 1,
3170
3673
  message: message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
3674
+ rawMessage: message,
3171
3675
  createdAt: timeLabel,
3676
+ rawCreatedAt: res?.created_at,
3677
+ rawUpdatedAt: res?.updated_at || res?.created_at,
3678
+ isEdited: false,
3679
+ status: res?.status,
3680
+ ownershipToken: res?.ownership_token || res?.feedback?.ownership_token,
3172
3681
  elements: submittedElements,
3173
3682
  attachments: submittedAttachments
3174
- });
3683
+ };
3684
+ const createdEntry = res?.feedback
3685
+ ? this.mapOwnRecordToSessionEntry(res.feedback, localStub)
3686
+ : localStub;
3687
+ this.sessionHistory.push(createdEntry);
3175
3688
  if (this.textareaEl) {
3176
3689
  this.textareaEl.value = "";
3177
3690
  }
@@ -3189,7 +3702,11 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3189
3702
  });
3190
3703
  }
3191
3704
  catch (err) {
3192
- const msg = err instanceof Error ? err.message : "Failed to submit feedback.";
3705
+ const msg = err instanceof Error
3706
+ ? err.message
3707
+ : editingId !== null
3708
+ ? "Failed to update feedback."
3709
+ : "Failed to submit feedback.";
3193
3710
  this.showStatus(msg, "error");
3194
3711
  this.emitWidgetEvent("context-drop:error", {
3195
3712
  error: msg
@@ -3199,8 +3716,16 @@ export class ContextDropWidgetElement extends BaseHTMLElement {
3199
3716
  this.isSubmitting = false;
3200
3717
  if (this.submitBtn) {
3201
3718
  this.submitBtn.disabled = false;
3202
- this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
3719
+ if (this.editingFeedbackId !== null) {
3720
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
3721
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
3722
+ }
3723
+ else {
3724
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
3725
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
3726
+ }
3203
3727
  }
3728
+ this.renderChatThread();
3204
3729
  }
3205
3730
  }
3206
3731
  hideStatus() {