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.
@@ -883,6 +883,8 @@
883
883
  const ICON_PUSH_LAYOUT = `<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="2.5" width="12" height="11" rx="1.8"/><line x1="9.5" y1="2.5" x2="9.5" y2="13.5"/><polyline points="6.5 6.2 4.7 8 6.5 9.8"/></svg>`;
884
884
  const ICON_SUN = `<svg viewBox="0 0 20 20" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="10" cy="10" r="3.75"/><line x1="10" y1="2" x2="10" y2="4"/><line x1="10" y1="16" x2="10" y2="18"/><line x1="2" y1="10" x2="4" y2="10"/><line x1="16" y1="10" x2="18" y2="10"/><line x1="4.34" y1="4.34" x2="5.75" y2="5.75"/><line x1="14.25" y1="14.25" x2="15.66" y2="15.66"/><line x1="4.34" y1="15.66" x2="5.75" y2="14.25"/><line x1="14.25" y1="5.75" x2="15.66" y2="4.34"/></svg>`;
885
885
  const ICON_MOON = `<svg viewBox="0 0 20 20" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17.2 12.8A7.5 7.5 0 0 1 7.2 2.8a7.5 7.5 0 1 0 10 10z"/></svg>`;
886
+ const ICON_EDIT = `<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11.2 2.5a1.5 1.5 0 0 1 2.1 2.1L5.8 12.1 2.7 13l.9-3.1 7.6-7.4z"/></svg>`;
887
+ const ICON_TRASH = `<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.8 4.5h10.4"/><path d="M6.2 4.5V3.2a.9.9 0 0 1 .9-.9h1.8a.9.9 0 0 1 .9.9v1.3"/><path d="M4.2 4.5l.6 8.3a1.2 1.2 0 0 0 1.2 1.1h4a1.2 1.2 0 0 0 1.2-1.1l.6-8.3"/></svg>`;
886
888
 
887
889
  // --- Module: markdown.ts ---
888
890
  /**
@@ -1160,6 +1162,47 @@
1160
1162
  border-color: #3b4252;
1161
1163
  }
1162
1164
 
1165
+ :host([data-cd-theme="dark"]) .cd-msg-action-btn:hover:not(:disabled),
1166
+ :host([data-theme="dark"]) .cd-msg-action-btn:hover:not(:disabled),
1167
+ .cd-composer[data-theme="dark"] .cd-msg-action-btn:hover:not(:disabled) {
1168
+ background: rgba(255, 255, 255, 0.09);
1169
+ color: var(--cd-ink);
1170
+ }
1171
+
1172
+ :host([data-cd-theme="dark"]) .cd-msg-action-btn.is-danger:hover:not(:disabled),
1173
+ :host([data-theme="dark"]) .cd-msg-action-btn.is-danger:hover:not(:disabled),
1174
+ .cd-composer[data-theme="dark"] .cd-msg-action-btn.is-danger:hover:not(:disabled) {
1175
+ background: var(--cd-danger-soft);
1176
+ color: #fca5a5;
1177
+ }
1178
+
1179
+ :host([data-cd-theme="dark"]) .cd-edit-banner-info,
1180
+ :host([data-theme="dark"]) .cd-edit-banner-info,
1181
+ .cd-composer[data-theme="dark"] .cd-edit-banner-info {
1182
+ color: var(--cd-ink);
1183
+ }
1184
+
1185
+ :host([data-cd-theme="dark"]) .cd-msg-delete-label,
1186
+ :host([data-theme="dark"]) .cd-msg-delete-label,
1187
+ .cd-composer[data-theme="dark"] .cd-msg-delete-label {
1188
+ color: #fca5a5;
1189
+ }
1190
+
1191
+ :host([data-cd-theme="dark"]) .cd-btn-danger,
1192
+ :host([data-theme="dark"]) .cd-btn-danger,
1193
+ .cd-composer[data-theme="dark"] .cd-btn-danger {
1194
+ background: #dc2626;
1195
+ border-color: #dc2626;
1196
+ color: #ffffff;
1197
+ }
1198
+
1199
+ :host([data-cd-theme="dark"]) .cd-btn-danger:hover:not(:disabled),
1200
+ :host([data-theme="dark"]) .cd-btn-danger:hover:not(:disabled),
1201
+ .cd-composer[data-theme="dark"] .cd-btn-danger:hover:not(:disabled) {
1202
+ background: #ef4444;
1203
+ border-color: #ef4444;
1204
+ }
1205
+
1163
1206
  *, *::before, *::after {
1164
1207
  box-sizing: border-box;
1165
1208
  }
@@ -2022,11 +2065,18 @@
2022
2065
  flex-direction: column;
2023
2066
  gap: 5px;
2024
2067
  align-self: flex-end;
2068
+ width: 92%;
2025
2069
  max-width: 92%;
2026
2070
  padding: 9px 11px;
2027
2071
  background: var(--cd-surface-elevated);
2028
2072
  border: 1px solid var(--cd-border);
2029
2073
  border-radius: 12px 12px 3px 12px;
2074
+ transition: border-color 0.14s var(--cd-ease), box-shadow 0.14s var(--cd-ease);
2075
+ }
2076
+
2077
+ .cd-chat-msg.is-editing {
2078
+ border-color: var(--cd-accent);
2079
+ box-shadow: 0 0 0 2px var(--cd-accent-soft);
2030
2080
  }
2031
2081
 
2032
2082
  .cd-chat-msg-text {
@@ -2047,6 +2097,83 @@
2047
2097
  font-variant-numeric: tabular-nums;
2048
2098
  }
2049
2099
 
2100
+ .cd-chat-msg-meta-info {
2101
+ display: inline-flex;
2102
+ align-items: center;
2103
+ gap: 6px;
2104
+ min-width: 0;
2105
+ flex-wrap: wrap;
2106
+ }
2107
+
2108
+ .cd-chat-msg-actions {
2109
+ display: inline-flex;
2110
+ align-items: center;
2111
+ gap: 2px;
2112
+ flex-shrink: 0;
2113
+ }
2114
+
2115
+ .cd-msg-action-btn {
2116
+ appearance: none;
2117
+ display: inline-flex;
2118
+ align-items: center;
2119
+ justify-content: center;
2120
+ width: 24px;
2121
+ height: 24px;
2122
+ padding: 0;
2123
+ border: 1px solid transparent;
2124
+ border-radius: 6px;
2125
+ background: transparent;
2126
+ color: var(--cd-ink-secondary);
2127
+ cursor: pointer;
2128
+ transition: background-color 0.12s ease, color 0.12s ease, border-color 0.12s ease;
2129
+ }
2130
+
2131
+ .cd-msg-action-btn:hover:not(:disabled) {
2132
+ background: rgba(17, 19, 24, 0.06);
2133
+ color: var(--cd-ink);
2134
+ }
2135
+
2136
+ .cd-msg-action-btn.is-active {
2137
+ background: var(--cd-accent-soft);
2138
+ color: var(--cd-accent-hover);
2139
+ border-color: rgba(29, 78, 216, 0.25);
2140
+ }
2141
+
2142
+ .cd-msg-action-btn.is-danger:hover:not(:disabled) {
2143
+ background: var(--cd-danger-soft);
2144
+ color: var(--cd-danger);
2145
+ }
2146
+
2147
+ .cd-msg-action-btn:disabled {
2148
+ opacity: 0.4;
2149
+ cursor: not-allowed;
2150
+ }
2151
+
2152
+ .cd-msg-delete-confirm {
2153
+ display: flex;
2154
+ align-items: center;
2155
+ justify-content: space-between;
2156
+ gap: 8px;
2157
+ margin-top: 2px;
2158
+ padding: 6px 8px;
2159
+ border-radius: 8px;
2160
+ background: var(--cd-danger-soft);
2161
+ border: 1px solid rgba(185, 28, 28, 0.24);
2162
+ }
2163
+
2164
+ .cd-msg-delete-label {
2165
+ font-size: 11.5px;
2166
+ font-weight: 600;
2167
+ color: var(--cd-danger);
2168
+ }
2169
+
2170
+ .cd-msg-delete-btns {
2171
+ display: inline-flex;
2172
+ align-items: center;
2173
+ gap: 5px;
2174
+ flex-shrink: 0;
2175
+ }
2176
+
2050
2177
  .cd-chat-msg-pills {
2051
2178
  display: flex;
2052
2179
  flex-wrap: wrap;
@@ -2931,6 +3058,42 @@
2931
3058
  border-top: 1px solid var(--cd-border);
2932
3059
  }
2933
3060
 
3061
+ .cd-edit-banner {
3062
+ display: flex;
3063
+ align-items: center;
3064
+ justify-content: space-between;
3065
+ gap: 8px;
3066
+ padding: 6px 12px;
3067
+ background: var(--cd-accent-soft);
3068
+ border-bottom: 1px solid var(--cd-border-subtle);
3069
+ font-size: 12px;
3070
+ color: var(--cd-ink);
3071
+ }
3072
+
3073
+ .cd-edit-banner[hidden] {
3074
+ display: none !important;
3075
+ }
3076
+
3077
+ .cd-edit-banner-info {
3078
+ display: inline-flex;
3079
+ align-items: center;
3080
+ gap: 6px;
3081
+ min-width: 0;
3082
+ font-weight: 600;
3083
+ color: var(--cd-accent-hover);
3084
+ }
3085
+
3086
+ .cd-edit-banner-info svg {
3087
+ color: var(--cd-accent-hover);
3088
+ flex-shrink: 0;
3089
+ }
3090
+
3091
+ .cd-edit-banner-id {
3092
+ font-family: var(--cd-mono);
3093
+ font-size: 11px;
3094
+ font-variant-numeric: tabular-nums;
3095
+ }
3096
+
2934
3097
  .cd-textarea {
2935
3098
  width: 100%;
2936
3099
  min-height: 68px;
@@ -3011,6 +3174,24 @@
3011
3174
  border-color: #252a34;
3012
3175
  }
3013
3176
 
3177
+ .cd-btn-xs {
3178
+ padding: 3px 8px;
3179
+ font-size: 11.5px;
3180
+ border-radius: 6px;
3181
+ }
3182
+
3183
+ .cd-btn-danger {
3184
+ background: var(--cd-danger);
3185
+ border-color: var(--cd-danger);
3186
+ color: #ffffff;
3187
+ font-weight: 600;
3188
+ }
3189
+
3190
+ .cd-btn-danger:hover:not(:disabled) {
3191
+ background: #991b1b;
3192
+ border-color: #991b1b;
3193
+ }
3194
+
3014
3195
  @media (max-width: 560px) {
3015
3196
  .cd-composer,
3016
3197
  .cd-compact-bar {
@@ -3038,6 +3219,8 @@
3038
3219
  .cd-corner-flap,
3039
3220
  .cd-drag-pin-head,
3040
3221
  .cd-composer,
3222
+ .cd-chat-msg,
3223
+ .cd-msg-action-btn,
3041
3224
  .cd-agent-sidebar,
3042
3225
  .cd-skeleton-bar {
3043
3226
  animation: none !important;
@@ -3047,6 +3230,22 @@
3047
3230
  `;
3048
3231
 
3049
3232
  // --- Module: api-client.ts ---
3233
+ const OWNERSHIP_STORAGE_KEY = "context_drop_ownership_tokens";
3234
+ const MAX_STORED_OWNERSHIP_TOKENS = 50;
3235
+
3236
+ function getBrowserLocalStorage() {
3237
+ try {
3238
+ if (typeof window !== "undefined" && "localStorage" in window) {
3239
+ const store = window.localStorage;
3240
+ if (store && typeof store.getItem === "function" && typeof store.setItem === "function") {
3241
+ return store;
3242
+ }
3243
+ }
3244
+ } catch {
3245
+ // Storage unavailable or restricted by browser privacy policy
3246
+ }
3247
+ return null;
3248
+ }
3050
3249
  class ContextDropApiClient {
3051
3250
  baseUrl ;
3052
3251
  credentials ;
@@ -3054,6 +3253,7 @@
3054
3253
  cachedCsrfToken = null;
3055
3254
  configFetched = false;
3056
3255
  inFlightConfigPromise = null;
3256
+ memoryOwnershipTokens = new Map();
3057
3257
 
3058
3258
  constructor(baseUrl = "/context_drop", options = {}) {
3059
3259
  this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
@@ -3270,6 +3470,113 @@
3270
3470
  return this.executeWithCsrfRetry(makeRequest, "Upload failed");
3271
3471
  }
3272
3472
 
3473
+ ownershipScopedKey(id ) {
3474
+ return `${this.baseUrl}::${String(id)}`;
3475
+ }
3476
+
3477
+ readStoredTokenMap() {
3478
+ const store = getBrowserLocalStorage();
3479
+ if (!store) {
3480
+ const out = {};
3481
+ for (const [k, v] of this.memoryOwnershipTokens.entries()) {
3482
+ out[k] = v;
3483
+ }
3484
+ return out;
3485
+ }
3486
+
3487
+ try {
3488
+ const raw = store.getItem(OWNERSHIP_STORAGE_KEY);
3489
+ if (!raw) return {};
3490
+ const parsed = JSON.parse(raw) ;
3491
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
3492
+ return {};
3493
+ }
3494
+ const clean = {};
3495
+ for (const [k, v] of Object.entries(parsed )) {
3496
+ if (typeof v === "string" && v.trim().length > 0) {
3497
+ clean[k] = v.trim();
3498
+ }
3499
+ }
3500
+ return clean;
3501
+ } catch {
3502
+ return {};
3503
+ }
3504
+ }
3505
+
3506
+ writeStoredTokenMap(map ) {
3507
+ const entries = Object.entries(map);
3508
+ const trimmedEntries =
3509
+ entries.length > MAX_STORED_OWNERSHIP_TOKENS
3510
+ ? entries.slice(entries.length - MAX_STORED_OWNERSHIP_TOKENS)
3511
+ : entries;
3512
+
3513
+ this.memoryOwnershipTokens.clear();
3514
+ const bounded = {};
3515
+ for (const [k, v] of trimmedEntries) {
3516
+ bounded[k] = v;
3517
+ this.memoryOwnershipTokens.set(k, v);
3518
+ }
3519
+
3520
+ const store = getBrowserLocalStorage();
3521
+ if (store) {
3522
+ try {
3523
+ store.setItem(OWNERSHIP_STORAGE_KEY, JSON.stringify(bounded));
3524
+ } catch {
3525
+ // Non-fatal if storage quota exceeded
3526
+ }
3527
+ }
3528
+ }
3529
+
3530
+ getOwnershipToken(id ) {
3531
+ const map = this.readStoredTokenMap();
3532
+ const scoped = map[this.ownershipScopedKey(id)];
3533
+ if (scoped) return scoped;
3534
+ const plain = map[String(id)];
3535
+ return plain || null;
3536
+ }
3537
+
3538
+ setOwnershipToken(id , token ) {
3539
+ const trimmed = typeof token === "string" ? token.trim() : "";
3540
+ if (!trimmed) return;
3541
+ const map = this.readStoredTokenMap();
3542
+ const key = this.ownershipScopedKey(id);
3543
+ delete map[key];
3544
+ map[key] = trimmed;
3545
+ this.writeStoredTokenMap(map);
3546
+ }
3547
+
3548
+ removeOwnershipToken(id ) {
3549
+ const map = this.readStoredTokenMap();
3550
+ const scopedKey = this.ownershipScopedKey(id);
3551
+ const plainKey = String(id);
3552
+ if (!(scopedKey in map) && !(plainKey in map)) return;
3553
+ delete map[scopedKey];
3554
+ delete map[plainKey];
3555
+ this.writeStoredTokenMap(map);
3556
+ }
3557
+
3558
+ getAllOwnershipTokens() {
3559
+ const map = this.readStoredTokenMap();
3560
+ const prefix = `${this.baseUrl}::`;
3561
+ const tokens = [];
3562
+ for (const [k, v] of Object.entries(map)) {
3563
+ if ((k.startsWith(prefix) || !k.includes("::")) && v && !tokens.includes(v)) {
3564
+ tokens.push(v);
3565
+ }
3566
+ }
3567
+ return tokens;
3568
+ }
3569
+
3570
+ buildAttachmentPreviewUrl(
3571
+ feedbackId ,
3572
+ attachmentId ,
3573
+ ownershipToken
3574
+ ) {
3575
+ const token = ownershipToken || this.getOwnershipToken(feedbackId);
3576
+ const base = `${this.baseUrl}/feedback/${encodeURIComponent(String(feedbackId))}/attachments/${encodeURIComponent(String(attachmentId))}`;
3577
+ return token ? `${base}?ownership_token=${encodeURIComponent(token)}` : base;
3578
+ }
3579
+
3273
3580
  async submitFeedback(payload ) {
3274
3581
  const makeRequest = async (csrfToken ) =>
3275
3582
  fetch(`${this.baseUrl}/feedback`, {
@@ -3279,7 +3586,114 @@
3279
3586
  body: JSON.stringify({ feedback: payload })
3280
3587
  });
3281
3588
 
3282
- return this.executeWithCsrfRetry(makeRequest, "Submission failed");
3589
+ const response = await this.executeWithCsrfRetry (
3590
+ makeRequest,
3591
+ "Submission failed"
3592
+ );
3593
+
3594
+ const token = response?.ownership_token || response?.feedback?.ownership_token;
3595
+ if (response?.id !== undefined && token) {
3596
+ this.setOwnershipToken(response.id, token);
3597
+ }
3598
+ return response;
3599
+ }
3600
+
3601
+ async fetchOwnFeedbacks(limit = 30) {
3602
+ const headers = {
3603
+ Accept: "application/json"
3604
+ };
3605
+ const tokens = this.getAllOwnershipTokens();
3606
+ if (tokens.length > 0) {
3607
+ headers["X-Context-Drop-Ownership-Tokens"] = tokens.join(",");
3608
+ }
3609
+
3610
+ const qs = limit > 0 ? `?limit=${encodeURIComponent(String(limit))}` : "";
3611
+ const response = await fetch(`${this.baseUrl}/feedback${qs}`, {
3612
+ method: "GET",
3613
+ credentials: this.credentials,
3614
+ headers: this.mergeClientHeaders(headers)
3615
+ });
3616
+
3617
+ if (!response.ok) {
3618
+ const errBody = await response.json().catch(() => ({}));
3619
+ throw new Error(
3620
+ (errBody ).error || `Failed to load own feedbacks (${response.status})`
3621
+ );
3622
+ }
3623
+
3624
+ const parsed = (await response.json().catch(() => ({}))) ;
3625
+ const feedbacks = Array.isArray(parsed?.feedbacks) ? parsed.feedbacks : [];
3626
+ for (const item of feedbacks) {
3627
+ if (item && item.id !== undefined && typeof item.ownership_token === "string") {
3628
+ this.setOwnershipToken(item.id, item.ownership_token);
3629
+ }
3630
+ }
3631
+
3632
+ return {
3633
+ total_count: typeof parsed?.total_count === "number" ? parsed.total_count : feedbacks.length,
3634
+ feedbacks
3635
+ };
3636
+ }
3637
+
3638
+ async updateFeedback(
3639
+ id ,
3640
+ payload ,
3641
+ ownershipToken
3642
+ ) {
3643
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
3644
+ const makeRequest = async (csrfToken ) => {
3645
+ const headers = this.buildJsonHeaders(csrfToken);
3646
+ if (resolvedToken) {
3647
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
3648
+ }
3649
+ const bodyPayload = { feedback: payload };
3650
+ if (resolvedToken) {
3651
+ bodyPayload.ownership_token = resolvedToken;
3652
+ }
3653
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
3654
+ method: "PATCH",
3655
+ credentials: this.credentials,
3656
+ headers,
3657
+ body: JSON.stringify(bodyPayload)
3658
+ });
3659
+ };
3660
+
3661
+ const response = await this.executeWithCsrfRetry (
3662
+ makeRequest,
3663
+ "Update failed"
3664
+ );
3665
+
3666
+ const nextToken = response?.ownership_token || response?.feedback?.ownership_token;
3667
+ if (response?.id !== undefined && nextToken) {
3668
+ this.setOwnershipToken(response.id, nextToken);
3669
+ }
3670
+ return response;
3671
+ }
3672
+
3673
+ async deleteFeedback(
3674
+ id ,
3675
+ ownershipToken
3676
+ ) {
3677
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
3678
+ const makeRequest = async (csrfToken ) => {
3679
+ const headers = this.buildJsonHeaders(csrfToken);
3680
+ if (resolvedToken) {
3681
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
3682
+ }
3683
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
3684
+ method: "DELETE",
3685
+ credentials: this.credentials,
3686
+ headers
3687
+ });
3688
+ };
3689
+
3690
+ const response = await this.executeWithCsrfRetry (
3691
+ makeRequest,
3692
+ "Delete failed"
3693
+ );
3694
+
3695
+ this.removeOwnershipToken(id);
3696
+ return response;
3283
3697
  }
3284
3698
 
3285
3699
  async fetchAgentStatus() {
@@ -5409,6 +5823,17 @@
5409
5823
  elementDomNodes = new Map();
5410
5824
  attachments = [];
5411
5825
  sessionHistory = [];
5826
+ ownFeedbacksLoaded = false;
5827
+ inFlightOwnFeedbacksPromise = null;
5828
+ editingFeedbackId = null;
5829
+ confirmingDeleteId = null;
5830
+ deletingFeedbackId = null;
5831
+ stashedDraftBeforeEdit
5832
+
5833
+
5834
+
5835
+
5836
+ = null;
5412
5837
 
5413
5838
  // Local Agent state
5414
5839
  agentStatusLoaded = false;
@@ -5451,6 +5876,8 @@
5451
5876
  composerToolbarScreenshotBtn = null;
5452
5877
  composerToolbarUploadBtn = null;
5453
5878
  chatThreadEl = null;
5879
+ editBannerEl = null;
5880
+ editBannerInfoEl = null;
5454
5881
  textareaEl = null;
5455
5882
  trayEl = null;
5456
5883
  statusEl = null;
@@ -5566,6 +5993,25 @@
5566
5993
  return;
5567
5994
  }
5568
5995
 
5996
+ if (
5997
+ ev.key === "Escape" &&
5998
+ !(this.picker && this.picker.isActive()) &&
5999
+ this.isOpen &&
6000
+ !this.isMinimized &&
6001
+ !this.isAgentModeActive()
6002
+ ) {
6003
+ if (this.confirmingDeleteId !== null) {
6004
+ ev.preventDefault();
6005
+ this.cancelDeleteFeedback();
6006
+ return;
6007
+ }
6008
+ if (this.editingFeedbackId !== null) {
6009
+ ev.preventDefault();
6010
+ this.cancelEditingFeedback();
6011
+ return;
6012
+ }
6013
+ }
6014
+
5569
6015
  // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
5570
6016
  if (
5571
6017
  !this.isSmartSelectionMode() &&
@@ -5687,6 +6133,8 @@
5687
6133
  "same-origin";
5688
6134
  const resolvedHeaders = options.headers || this.customHeaders;
5689
6135
  this.customHeaders = { ...resolvedHeaders };
6136
+ this.ownFeedbacksLoaded = false;
6137
+ this.inFlightOwnFeedbacksPromise = null;
5690
6138
  this.apiClient = new ContextDropApiClient(endpoint || "/context_drop", {
5691
6139
  credentials: resolvedCredentials,
5692
6140
  headers: this.customHeaders
@@ -5769,8 +6217,12 @@
5769
6217
  return;
5770
6218
  }
5771
6219
  this.surfaceMode = mode;
5772
- if (mode === "agent" && this.isOpen) {
5773
- void this.ensureAgentStatusLoaded();
6220
+ if (this.isOpen) {
6221
+ if (mode === "agent") {
6222
+ void this.ensureAgentStatusLoaded();
6223
+ } else if (!this.isMinimized) {
6224
+ void this.ensureOwnFeedbacksLoaded();
6225
+ }
5774
6226
  }
5775
6227
  this.renderTray();
5776
6228
  this.renderChatThread();
@@ -5790,6 +6242,301 @@
5790
6242
  return [...this.sessionHistory];
5791
6243
  }
5792
6244
 
6245
+ getEditingFeedbackId() {
6246
+ return this.editingFeedbackId;
6247
+ }
6248
+
6249
+ formatTimestampLabel(isoOrLabel ) {
6250
+ if (isoOrLabel && /^\d{2}:\d{2}$/.test(isoOrLabel.trim())) {
6251
+ return isoOrLabel.trim();
6252
+ }
6253
+ const parsed = isoOrLabel ? new Date(isoOrLabel) : new Date();
6254
+ const valid = Number.isNaN(parsed.getTime()) ? new Date() : parsed;
6255
+ return `${String(valid.getHours()).padStart(2, "0")}:${String(valid.getMinutes()).padStart(2, "0")}`;
6256
+ }
6257
+
6258
+ mapOwnRecordToSessionEntry(
6259
+ record ,
6260
+ existingEntry
6261
+ ) {
6262
+ const smartMode = this.isSmartSelectionMode();
6263
+ const rawMessage = typeof record.message === "string" ? record.message : "";
6264
+ const displayMessage =
6265
+ rawMessage || (smartMode ? "(Highlighted page area)" : "(Context drop without text)");
6266
+ const token =
6267
+ record.ownership_token ||
6268
+ existingEntry?.ownershipToken ||
6269
+ this.apiClient.getOwnershipToken(record.id) ||
6270
+ undefined;
6271
+ const isEdited = Boolean(
6272
+ record.created_at && record.updated_at && record.updated_at !== record.created_at
6273
+ );
6274
+
6275
+ const serverAttachments = Array.isArray(record.attachments) ? record.attachments : [];
6276
+ const mappedAttachments = serverAttachments.map((att, idx) => {
6277
+ const existingAtt = existingEntry?.attachments.find(
6278
+ (a) =>
6279
+ (a.server_id !== undefined && String(a.server_id) === String(att.id)) ||
6280
+ (a.server_id === undefined &&
6281
+ idx < (existingEntry?.attachments.length || 0) &&
6282
+ existingEntry?.attachments[idx]?.filename === att.filename)
6283
+ );
6284
+
6285
+ const previewUrl =
6286
+ existingAtt?.preview_url &&
6287
+ (existingAtt.preview_url.startsWith("data:") || existingAtt.preview_url.startsWith("blob:"))
6288
+ ? existingAtt.preview_url
6289
+ : this.apiClient.buildAttachmentPreviewUrl(record.id, att.id, token);
6290
+
6291
+ const meta =
6292
+ att.metadata && typeof att.metadata === "object" && !Array.isArray(att.metadata)
6293
+ ? { ...att.metadata }
6294
+ : existingAtt?.metadata
6295
+ ? { ...existingAtt.metadata }
6296
+ : {};
6297
+
6298
+ let label = existingAtt?.label || "";
6299
+ if (!label) {
6300
+ if (meta.auto_smart_context === true && typeof meta.friendly_label === "string") {
6301
+ label = `Context around ${meta.friendly_label}`;
6302
+ } else if (att.filename) {
6303
+ label = att.filename;
6304
+ } else {
6305
+ label = att.attachment_type === "screenshot" ? "Screenshot" : "Attached image";
6306
+ }
6307
+ }
6308
+
6309
+ return {
6310
+ id: existingAtt?.id || `srv_att_${record.id}_${att.id}`,
6311
+ server_id: att.id,
6312
+ label,
6313
+ preview_url: previewUrl,
6314
+ attachment_type: att.attachment_type === "screenshot" ? "screenshot" : "image",
6315
+ filename: att.filename,
6316
+ element_reference_ref: att.element_reference_ref ?? existingAtt?.element_reference_ref ?? null,
6317
+ metadata: meta
6318
+ };
6319
+ });
6320
+
6321
+ const elements = Array.isArray(record.element_references)
6322
+ ? structuredClone(record.element_references)
6323
+ : existingEntry?.elements
6324
+ ? structuredClone(existingEntry.elements)
6325
+ : [];
6326
+
6327
+ return {
6328
+ id: record.id,
6329
+ message: displayMessage,
6330
+ rawMessage,
6331
+ createdAt: this.formatTimestampLabel(record.created_at || existingEntry?.rawCreatedAt),
6332
+ rawCreatedAt: record.created_at,
6333
+ rawUpdatedAt: record.updated_at,
6334
+ isEdited: isEdited || Boolean(existingEntry?.isEdited),
6335
+ status: record.status,
6336
+ ownershipToken: token,
6337
+ elements,
6338
+ attachments: mappedAttachments
6339
+ };
6340
+ }
6341
+
6342
+ async refreshOwnFeedbacks() {
6343
+ if (typeof fetch !== "function") {
6344
+ return [...this.sessionHistory];
6345
+ }
6346
+ if (this.inFlightOwnFeedbacksPromise) {
6347
+ return this.inFlightOwnFeedbacksPromise;
6348
+ }
6349
+
6350
+ this.inFlightOwnFeedbacksPromise = (async () => {
6351
+ try {
6352
+ const res = await this.apiClient.fetchOwnFeedbacks();
6353
+ this.ownFeedbacksLoaded = true;
6354
+ const records = Array.isArray(res?.feedbacks) ? res.feedbacks : [];
6355
+ if (records.length === 0) {
6356
+ return [...this.sessionHistory];
6357
+ }
6358
+
6359
+ const existingById = new Map ();
6360
+ for (const entry of this.sessionHistory) {
6361
+ existingById.set(String(entry.id), entry);
6362
+ }
6363
+
6364
+ const chronologicalServerRecords = [...records].reverse();
6365
+ const serverIds = new Set ();
6366
+ const merged = [];
6367
+
6368
+ for (const record of chronologicalServerRecords) {
6369
+ if (!record || record.id === undefined || record.id === null) continue;
6370
+ const idKey = String(record.id);
6371
+ serverIds.add(idKey);
6372
+ merged.push(this.mapOwnRecordToSessionEntry(record, existingById.get(idKey)));
6373
+ }
6374
+
6375
+ for (const localEntry of this.sessionHistory) {
6376
+ if (!serverIds.has(String(localEntry.id))) {
6377
+ merged.push(localEntry);
6378
+ }
6379
+ }
6380
+
6381
+ this.sessionHistory = merged;
6382
+ this.renderChatThread();
6383
+ this.syncUiStates();
6384
+ } catch {
6385
+ // Non-fatal when offline or using minimal synthetic endpoints
6386
+ } finally {
6387
+ this.inFlightOwnFeedbacksPromise = null;
6388
+ }
6389
+ return [...this.sessionHistory];
6390
+ })();
6391
+
6392
+ return this.inFlightOwnFeedbacksPromise;
6393
+ }
6394
+
6395
+ async ensureOwnFeedbacksLoaded() {
6396
+ if (this.ownFeedbacksLoaded) return;
6397
+ await this.refreshOwnFeedbacks();
6398
+ }
6399
+
6400
+ startEditingFeedback(feedbackId ) {
6401
+ const targetKey = String(feedbackId);
6402
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
6403
+ if (!entry) return false;
6404
+
6405
+ this.confirmingDeleteId = null;
6406
+ this.hideStatus();
6407
+
6408
+ if (this.editingFeedbackId === null) {
6409
+ this.stashedDraftBeforeEdit = {
6410
+ message: this.textareaEl?.value || "",
6411
+ elementReferences: [...this.elementReferences],
6412
+ elementDomNodes: new Map(this.elementDomNodes),
6413
+ attachments: [...this.attachments]
6414
+ };
6415
+ }
6416
+
6417
+ this.editingFeedbackId = targetKey;
6418
+
6419
+ if (this.textareaEl) {
6420
+ this.textareaEl.value = entry.rawMessage !== undefined ? entry.rawMessage : entry.message;
6421
+ }
6422
+
6423
+ this.elementReferences = structuredClone(entry.elements);
6424
+ this.elementDomNodes.clear();
6425
+ if (typeof document !== "undefined" && typeof document.querySelector === "function") {
6426
+ for (const elRef of this.elementReferences) {
6427
+ if (!elRef.selector) continue;
6428
+ try {
6429
+ const liveNode = document.querySelector(elRef.selector);
6430
+ if (liveNode) {
6431
+ this.elementDomNodes.set(elRef.client_ref, liveNode);
6432
+ }
6433
+ } catch {
6434
+ // Ignore invalid or complex selectors not resolvable on current page
6435
+ }
6436
+ }
6437
+ }
6438
+
6439
+ this.attachments = entry.attachments.map((att) => ({
6440
+ id: att.id,
6441
+ existing_attachment_id: att.server_id,
6442
+ attachment_type: att.attachment_type,
6443
+ label: att.label,
6444
+ preview_url: att.preview_url,
6445
+ signed_blob_id: att.signed_blob_id,
6446
+ data_url: att.data_url,
6447
+ filename: att.filename || att.label || "attachment.png",
6448
+ element_reference_ref: att.element_reference_ref || undefined,
6449
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
6450
+ }));
6451
+
6452
+ this.picker?.refreshPinnedMarkers();
6453
+ this.renderTray();
6454
+ this.renderChatThread();
6455
+ this.syncUiStates();
6456
+ this.textareaEl?.focus();
6457
+ return true;
6458
+ }
6459
+
6460
+ cancelEditingFeedback() {
6461
+ if (this.editingFeedbackId === null) return;
6462
+ this.editingFeedbackId = null;
6463
+
6464
+ if (this.stashedDraftBeforeEdit) {
6465
+ if (this.textareaEl) {
6466
+ this.textareaEl.value = this.stashedDraftBeforeEdit.message;
6467
+ }
6468
+ this.elementReferences = this.stashedDraftBeforeEdit.elementReferences;
6469
+ this.elementDomNodes = this.stashedDraftBeforeEdit.elementDomNodes;
6470
+ this.attachments = this.stashedDraftBeforeEdit.attachments;
6471
+ this.stashedDraftBeforeEdit = null;
6472
+ } else {
6473
+ if (this.textareaEl) {
6474
+ this.textareaEl.value = "";
6475
+ }
6476
+ this.elementReferences = [];
6477
+ this.elementDomNodes.clear();
6478
+ this.attachments = [];
6479
+ }
6480
+
6481
+ this.picker?.hideExternalPreview();
6482
+ this.picker?.refreshPinnedMarkers();
6483
+ this.renderTray();
6484
+ this.renderChatThread();
6485
+ this.syncUiStates();
6486
+ }
6487
+
6488
+ requestDeleteFeedback(feedbackId ) {
6489
+ const targetKey = String(feedbackId);
6490
+ if (!this.sessionHistory.some((item) => String(item.id) === targetKey)) return;
6491
+ this.confirmingDeleteId = this.confirmingDeleteId === targetKey ? null : targetKey;
6492
+ this.renderChatThread();
6493
+ }
6494
+
6495
+ cancelDeleteFeedback() {
6496
+ if (this.confirmingDeleteId === null) return;
6497
+ this.confirmingDeleteId = null;
6498
+ this.renderChatThread();
6499
+ }
6500
+
6501
+ async confirmDeleteFeedback(feedbackId ) {
6502
+ if (this.deletingFeedbackId !== null) return;
6503
+ const targetKey = String(feedbackId);
6504
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
6505
+ if (!entry) return;
6506
+
6507
+ this.deletingFeedbackId = targetKey;
6508
+ this.renderChatThread();
6509
+
6510
+ try {
6511
+ const res = await this.apiClient.deleteFeedback(entry.id, entry.ownershipToken);
6512
+ if (this.editingFeedbackId === targetKey) {
6513
+ this.cancelEditingFeedback();
6514
+ }
6515
+ this.sessionHistory = this.sessionHistory.filter((item) => String(item.id) !== targetKey);
6516
+ this.confirmingDeleteId = null;
6517
+ this.deletingFeedbackId = null;
6518
+ this.renderChatThread();
6519
+ this.renderTray();
6520
+ this.syncUiStates();
6521
+ this.showStatus(
6522
+ this.isSmartSelectionMode() ? "Your feedback was deleted." : "Feedback deleted.",
6523
+ "success"
6524
+ );
6525
+ this.emitWidgetEvent("context-drop:delete", {
6526
+ response: res,
6527
+ id: entry.id
6528
+ });
6529
+ } catch (err) {
6530
+ this.deletingFeedbackId = null;
6531
+ this.renderChatThread();
6532
+ const msg = err instanceof Error ? err.message : "Failed to delete feedback.";
6533
+ this.showStatus(msg, "error");
6534
+ this.emitWidgetEvent("context-drop:error", {
6535
+ error: msg
6536
+ });
6537
+ }
6538
+ }
6539
+
5793
6540
  getAgentMessages() {
5794
6541
  return [...this.agentMessages];
5795
6542
  }
@@ -5828,6 +6575,8 @@
5828
6575
  this.isMinimized = false;
5829
6576
  if (this.isAgentModeActive()) {
5830
6577
  void this.ensureAgentStatusLoaded();
6578
+ } else {
6579
+ void this.ensureOwnFeedbacksLoaded();
5831
6580
  }
5832
6581
  this.syncUiStates();
5833
6582
  this.focusActiveInput();
@@ -6843,6 +7592,27 @@
6843
7592
  const promptShell = document.createElement("div");
6844
7593
  promptShell.className = "cd-prompt-shell";
6845
7594
 
7595
+ const editBanner = document.createElement("div");
7596
+ editBanner.className = "cd-edit-banner";
7597
+ editBanner.hidden = true;
7598
+
7599
+ const editBannerInfo = document.createElement("span");
7600
+ editBannerInfo.className = "cd-edit-banner-info";
7601
+ this.editBannerInfoEl = editBannerInfo;
7602
+ editBanner.appendChild(editBannerInfo);
7603
+
7604
+ const cancelEditBtn = document.createElement("button");
7605
+ cancelEditBtn.type = "button";
7606
+ cancelEditBtn.className = "cd-btn cd-btn-xs";
7607
+ cancelEditBtn.setAttribute("aria-label", "Cancel editing feedback");
7608
+ cancelEditBtn.textContent = "Cancel";
7609
+ cancelEditBtn.addEventListener("click", () => {
7610
+ this.cancelEditingFeedback();
7611
+ });
7612
+ editBanner.appendChild(cancelEditBtn);
7613
+ this.editBannerEl = editBanner;
7614
+ promptShell.appendChild(editBanner);
7615
+
6846
7616
  const textarea = document.createElement("textarea");
6847
7617
  textarea.className = "cd-textarea";
6848
7618
  textarea.placeholder = this.config.placeholder;
@@ -6852,8 +7622,15 @@
6852
7622
  ev.preventDefault();
6853
7623
  void this.handleSubmit();
6854
7624
  } else if (ev.key === "Escape") {
7625
+ if (ev.defaultPrevented) return;
6855
7626
  ev.preventDefault();
6856
- this.closeComposer();
7627
+ if (this.confirmingDeleteId !== null) {
7628
+ this.cancelDeleteFeedback();
7629
+ } else if (this.editingFeedbackId !== null) {
7630
+ this.cancelEditingFeedback();
7631
+ } else {
7632
+ this.closeComposer();
7633
+ }
6857
7634
  }
6858
7635
  });
6859
7636
  textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
@@ -8135,6 +8912,35 @@
8135
8912
  ? `${ICON_IMAGE}<span>Add image</span>`
8136
8913
  : `${ICON_IMAGE}<span>Image</span>`;
8137
8914
  }
8915
+ if (this.editBannerEl && this.editBannerInfoEl) {
8916
+ if (this.editingFeedbackId !== null) {
8917
+ this.editBannerEl.hidden = false;
8918
+ this.editBannerInfoEl.innerHTML = "";
8919
+ const iconSpan = document.createElement("span");
8920
+ iconSpan.innerHTML = ICON_EDIT;
8921
+ const labelSpan = document.createElement("span");
8922
+ labelSpan.textContent = smartMode ? "Editing your feedback" : "Editing feedback";
8923
+ this.editBannerInfoEl.appendChild(iconSpan);
8924
+ this.editBannerInfoEl.appendChild(labelSpan);
8925
+ if (!smartMode) {
8926
+ const idSpan = document.createElement("span");
8927
+ idSpan.className = "cd-edit-banner-id";
8928
+ idSpan.textContent = `#${this.editingFeedbackId}`;
8929
+ this.editBannerInfoEl.appendChild(idSpan);
8930
+ }
8931
+ } else {
8932
+ this.editBannerEl.hidden = true;
8933
+ }
8934
+ }
8935
+ if (this.submitBtn && !this.isSubmitting) {
8936
+ if (this.editingFeedbackId !== null) {
8937
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
8938
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
8939
+ } else {
8940
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
8941
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
8942
+ }
8943
+ }
8138
8944
 
8139
8945
  if (this.agentSidebarEl) {
8140
8946
  this.agentSidebarEl.hidden = !showAgentSidebar;
@@ -8370,8 +9176,14 @@
8370
9176
  this.chatThreadEl.hidden = false;
8371
9177
 
8372
9178
  for (const entry of this.sessionHistory) {
9179
+ const entryIdStr = String(entry.id);
9180
+ const isEditingThis = this.editingFeedbackId === entryIdStr;
9181
+ const isConfirmingDelete = this.confirmingDeleteId === entryIdStr;
9182
+ const isDeletingThis = this.deletingFeedbackId === entryIdStr;
9183
+
8373
9184
  const msgCard = document.createElement("div");
8374
- msgCard.className = "cd-chat-msg";
9185
+ msgCard.className = isEditingThis ? "cd-chat-msg is-editing" : "cd-chat-msg";
9186
+ msgCard.setAttribute("data-feedback-id", entryIdStr);
8375
9187
 
8376
9188
  if (entry.elements.length > 0 || entry.attachments.length > 0) {
8377
9189
  const pills = document.createElement("div");
@@ -8406,14 +9218,102 @@
8406
9218
 
8407
9219
  const meta = document.createElement("div");
8408
9220
  meta.className = "cd-chat-msg-meta";
9221
+
9222
+ const metaInfo = document.createElement("div");
9223
+ metaInfo.className = "cd-chat-msg-meta-info";
9224
+
8409
9225
  const idSpan = document.createElement("span");
8410
- idSpan.textContent = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
9226
+ const baseLabel = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
9227
+ idSpan.textContent = entry.isEdited ? `${baseLabel} · edited` : baseLabel;
9228
+
9229
+ const sepSpan = document.createElement("span");
9230
+ sepSpan.setAttribute("aria-hidden", "true");
9231
+ sepSpan.textContent = "·";
9232
+
8411
9233
  const timeSpan = document.createElement("span");
8412
9234
  timeSpan.textContent = entry.createdAt;
8413
- meta.appendChild(idSpan);
8414
- meta.appendChild(timeSpan);
9235
+
9236
+ metaInfo.appendChild(idSpan);
9237
+ metaInfo.appendChild(sepSpan);
9238
+ metaInfo.appendChild(timeSpan);
9239
+
9240
+ const actions = document.createElement("div");
9241
+ actions.className = "cd-chat-msg-actions";
9242
+
9243
+ const editBtn = document.createElement("button");
9244
+ editBtn.type = "button";
9245
+ editBtn.className = `cd-msg-action-btn${isEditingThis ? " is-active" : ""}`;
9246
+ editBtn.title = isEditingThis ? "Cancel editing" : "Edit feedback";
9247
+ editBtn.setAttribute("aria-label", "Edit feedback");
9248
+ editBtn.setAttribute("aria-pressed", String(isEditingThis));
9249
+ editBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
9250
+ editBtn.innerHTML = ICON_EDIT;
9251
+ editBtn.addEventListener("click", () => {
9252
+ if (this.editingFeedbackId === entryIdStr) {
9253
+ this.cancelEditingFeedback();
9254
+ } else {
9255
+ this.startEditingFeedback(entry.id);
9256
+ }
9257
+ });
9258
+
9259
+ const deleteBtn = document.createElement("button");
9260
+ deleteBtn.type = "button";
9261
+ deleteBtn.className = "cd-msg-action-btn is-danger";
9262
+ deleteBtn.title = "Delete feedback";
9263
+ deleteBtn.setAttribute("aria-label", "Delete feedback");
9264
+ deleteBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
9265
+ deleteBtn.innerHTML = ICON_TRASH;
9266
+ deleteBtn.addEventListener("click", () => {
9267
+ this.requestDeleteFeedback(entry.id);
9268
+ });
9269
+
9270
+ actions.appendChild(editBtn);
9271
+ actions.appendChild(deleteBtn);
9272
+
9273
+ meta.appendChild(metaInfo);
9274
+ meta.appendChild(actions);
8415
9275
  msgCard.appendChild(meta);
8416
9276
 
9277
+ if (isConfirmingDelete) {
9278
+ const confirmBar = document.createElement("div");
9279
+ confirmBar.className = "cd-msg-delete-confirm";
9280
+ confirmBar.setAttribute("role", "group");
9281
+ confirmBar.setAttribute("aria-label", "Confirm feedback deletion");
9282
+
9283
+ const confirmLabel = document.createElement("span");
9284
+ confirmLabel.className = "cd-msg-delete-label";
9285
+ confirmLabel.textContent = "Delete this feedback?";
9286
+
9287
+ const btnGroup = document.createElement("div");
9288
+ btnGroup.className = "cd-msg-delete-btns";
9289
+
9290
+ const cancelDeleteBtn = document.createElement("button");
9291
+ cancelDeleteBtn.type = "button";
9292
+ cancelDeleteBtn.className = "cd-btn cd-btn-xs";
9293
+ cancelDeleteBtn.setAttribute("aria-label", "Cancel delete");
9294
+ cancelDeleteBtn.disabled = isDeletingThis;
9295
+ cancelDeleteBtn.textContent = "Cancel";
9296
+ cancelDeleteBtn.addEventListener("click", () => {
9297
+ this.cancelDeleteFeedback();
9298
+ });
9299
+
9300
+ const confirmDeleteBtn = document.createElement("button");
9301
+ confirmDeleteBtn.type = "button";
9302
+ confirmDeleteBtn.className = "cd-btn cd-btn-xs cd-btn-danger";
9303
+ confirmDeleteBtn.setAttribute("aria-label", "Confirm delete feedback");
9304
+ confirmDeleteBtn.disabled = isDeletingThis;
9305
+ confirmDeleteBtn.textContent = isDeletingThis ? "Deleting..." : "Delete";
9306
+ confirmDeleteBtn.addEventListener("click", () => {
9307
+ void this.confirmDeleteFeedback(entry.id);
9308
+ });
9309
+
9310
+ btnGroup.appendChild(cancelDeleteBtn);
9311
+ btnGroup.appendChild(confirmDeleteBtn);
9312
+ confirmBar.appendChild(confirmLabel);
9313
+ confirmBar.appendChild(btnGroup);
9314
+ msgCard.appendChild(confirmBar);
9315
+ }
9316
+
8417
9317
  this.chatThreadEl.appendChild(msgCard);
8418
9318
  }
8419
9319
 
@@ -8802,6 +9702,7 @@
8802
9702
  async handleSubmit() {
8803
9703
  if (this.isSubmitting) return;
8804
9704
  const smartMode = this.isSmartSelectionMode();
9705
+ const editingId = this.editingFeedbackId;
8805
9706
 
8806
9707
  if (this.pendingSmartCaptures.size > 0) {
8807
9708
  await Promise.allSettled(Array.from(this.pendingSmartCaptures));
@@ -8825,32 +9726,120 @@
8825
9726
  this.isSubmitting = true;
8826
9727
  if (this.submitBtn) {
8827
9728
  this.submitBtn.disabled = true;
8828
- this.submitBtn.innerHTML = `<span>Sending...</span>`;
9729
+ this.submitBtn.innerHTML =
9730
+ editingId !== null ? `<span>Saving...</span>` : `<span>Sending...</span>`;
8829
9731
  }
8830
9732
 
8831
9733
  try {
8832
- const submittedElements = [...this.elementReferences];
8833
- const submittedAttachments = this.attachments.map((att) => ({
9734
+ const submittedElements = structuredClone(this.elementReferences);
9735
+ const submittedAttachments = this.attachments.map((att) => ({
8834
9736
  id: att.id,
9737
+ server_id: att.existing_attachment_id,
8835
9738
  label: att.label,
8836
9739
  preview_url: att.preview_url,
8837
- attachment_type: att.attachment_type
9740
+ attachment_type: att.attachment_type,
9741
+ filename: att.filename,
9742
+ signed_blob_id: att.signed_blob_id,
9743
+ data_url: att.data_url,
9744
+ element_reference_ref: att.element_reference_ref || null,
9745
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
8838
9746
  }));
8839
9747
 
9748
+ const commonMetadata = {
9749
+ ...this.customMetadata,
9750
+ environment: this.config.environment,
9751
+ selection_mode: smartMode ? "smart" : "verbose",
9752
+ viewport: {
9753
+ width: typeof window !== "undefined" ? window.innerWidth : 0,
9754
+ height: typeof window !== "undefined" ? window.innerHeight : 0
9755
+ },
9756
+ locale: typeof navigator !== "undefined" ? navigator.language : "en"
9757
+ };
9758
+
9759
+ if (editingId !== null) {
9760
+ const existingIdx = this.sessionHistory.findIndex(
9761
+ (item) => String(item.id) === editingId
9762
+ );
9763
+ const existingEntry = existingIdx >= 0 ? this.sessionHistory[existingIdx] : undefined;
9764
+
9765
+ const updatePayload = {
9766
+ message,
9767
+ metadata: commonMetadata,
9768
+ element_references: this.elementReferences,
9769
+ attachments: this.attachments.map((att) => {
9770
+ if (att.existing_attachment_id !== undefined && att.existing_attachment_id !== null) {
9771
+ return {
9772
+ existing_id: att.existing_attachment_id,
9773
+ attachment_type: att.attachment_type,
9774
+ element_reference_ref: att.element_reference_ref,
9775
+ metadata: att.metadata
9776
+ };
9777
+ }
9778
+ return {
9779
+ attachment_type: att.attachment_type,
9780
+ filename: att.filename,
9781
+ signed_blob_id: att.signed_blob_id,
9782
+ data_url: att.signed_blob_id ? undefined : att.data_url,
9783
+ element_reference_ref: att.element_reference_ref,
9784
+ metadata: att.metadata
9785
+ };
9786
+ })
9787
+ };
9788
+
9789
+ const updateRes = await this.apiClient.updateFeedback(
9790
+ existingEntry?.id ?? editingId,
9791
+ updatePayload,
9792
+ existingEntry?.ownershipToken
9793
+ );
9794
+
9795
+ const mergedPreviewStub = {
9796
+ id: existingEntry?.id ?? updateRes?.id ?? editingId,
9797
+ message:
9798
+ message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
9799
+ rawMessage: message,
9800
+ createdAt: existingEntry?.createdAt || this.formatTimestampLabel(updateRes?.created_at),
9801
+ rawCreatedAt: existingEntry?.rawCreatedAt || updateRes?.created_at,
9802
+ rawUpdatedAt: updateRes?.updated_at || new Date().toISOString(),
9803
+ isEdited: true,
9804
+ status: updateRes?.status || existingEntry?.status,
9805
+ ownershipToken:
9806
+ updateRes?.ownership_token ||
9807
+ updateRes?.feedback?.ownership_token ||
9808
+ existingEntry?.ownershipToken,
9809
+ elements: submittedElements,
9810
+ attachments: submittedAttachments
9811
+ };
9812
+
9813
+ const updatedEntry = updateRes?.feedback
9814
+ ? {
9815
+ ...this.mapOwnRecordToSessionEntry(updateRes.feedback, mergedPreviewStub),
9816
+ isEdited: true
9817
+ }
9818
+ : mergedPreviewStub;
9819
+
9820
+ if (existingIdx >= 0) {
9821
+ this.sessionHistory[existingIdx] = updatedEntry;
9822
+ } else {
9823
+ this.sessionHistory.push(updatedEntry);
9824
+ }
9825
+
9826
+ this.cancelEditingFeedback();
9827
+ this.showStatus(
9828
+ smartMode ? "Your feedback was updated." : "Feedback updated.",
9829
+ "success"
9830
+ );
9831
+ this.emitWidgetEvent("context-drop:update", {
9832
+ response: updateRes,
9833
+ payload: updatePayload
9834
+ });
9835
+ return;
9836
+ }
9837
+
8840
9838
  const payload = {
8841
9839
  message,
8842
9840
  page_url: typeof window !== "undefined" ? window.location.href : "/",
8843
9841
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
8844
- metadata: {
8845
- ...this.customMetadata,
8846
- environment: this.config.environment,
8847
- selection_mode: smartMode ? "smart" : "verbose",
8848
- viewport: {
8849
- width: typeof window !== "undefined" ? window.innerWidth : 0,
8850
- height: typeof window !== "undefined" ? window.innerHeight : 0
8851
- },
8852
- locale: typeof navigator !== "undefined" ? navigator.language : "en"
8853
- },
9842
+ metadata: commonMetadata,
8854
9843
  element_references: this.elementReferences,
8855
9844
  attachments: this.attachments.map((att) => ({
8856
9845
  attachment_type: att.attachment_type,
@@ -8866,14 +9855,26 @@
8866
9855
 
8867
9856
  const now = new Date();
8868
9857
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
8869
- this.sessionHistory.push({
9858
+ const localStub = {
8870
9859
  id: res?.id ?? this.sessionHistory.length + 1,
8871
9860
  message:
8872
9861
  message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
9862
+ rawMessage: message,
8873
9863
  createdAt: timeLabel,
9864
+ rawCreatedAt: res?.created_at,
9865
+ rawUpdatedAt: res?.updated_at || res?.created_at,
9866
+ isEdited: false,
9867
+ status: res?.status,
9868
+ ownershipToken: res?.ownership_token || res?.feedback?.ownership_token,
8874
9869
  elements: submittedElements,
8875
9870
  attachments: submittedAttachments
8876
- });
9871
+ };
9872
+
9873
+ const createdEntry = res?.feedback
9874
+ ? this.mapOwnRecordToSessionEntry(res.feedback, localStub)
9875
+ : localStub;
9876
+
9877
+ this.sessionHistory.push(createdEntry);
8877
9878
 
8878
9879
  if (this.textareaEl) {
8879
9880
  this.textareaEl.value = "";
@@ -8894,7 +9895,12 @@
8894
9895
  payload
8895
9896
  });
8896
9897
  } catch (err) {
8897
- const msg = err instanceof Error ? err.message : "Failed to submit feedback.";
9898
+ const msg =
9899
+ err instanceof Error
9900
+ ? err.message
9901
+ : editingId !== null
9902
+ ? "Failed to update feedback."
9903
+ : "Failed to submit feedback.";
8898
9904
  this.showStatus(msg, "error");
8899
9905
  this.emitWidgetEvent("context-drop:error", {
8900
9906
  error: msg
@@ -8903,8 +9909,15 @@
8903
9909
  this.isSubmitting = false;
8904
9910
  if (this.submitBtn) {
8905
9911
  this.submitBtn.disabled = false;
8906
- this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
9912
+ if (this.editingFeedbackId !== null) {
9913
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
9914
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
9915
+ } else {
9916
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
9917
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
9918
+ }
8907
9919
  }
9920
+ this.renderChatThread();
8908
9921
  }
8909
9922
  }
8910
9923