context_drop 0.2.0 → 0.3.1

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 (40) 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 +1759 -105
  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 +99 -14
  8. data/app/controllers/context_drop/feedbacks_controller.rb +536 -17
  9. data/app/helpers/context_drop/dashboard_helper.rb +4 -0
  10. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  11. data/app/javascript/context_drop/__tests__/widget.test.ts +355 -1
  12. data/app/javascript/context_drop/api-client.ts +343 -22
  13. data/app/javascript/context_drop/element-picker.ts +1 -1
  14. data/app/javascript/context_drop/icons.ts +6 -0
  15. data/app/javascript/context_drop/screenshot.ts +1 -1
  16. data/app/javascript/context_drop/styles.ts +311 -0
  17. data/app/javascript/context_drop/types.ts +141 -6
  18. data/app/javascript/context_drop/widget.ts +1072 -35
  19. data/app/models/context_drop/attachment.rb +5 -0
  20. data/app/models/context_drop/comment.rb +50 -0
  21. data/app/models/context_drop/feedback.rb +81 -11
  22. data/app/services/context_drop/ownership_token.rb +114 -0
  23. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +14 -0
  24. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +169 -2
  25. data/app/views/layouts/context_drop/application.html.erb +131 -7
  26. data/config/routes.rb +16 -1
  27. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  28. data/db/migrate/20261116000001_create_context_drop_comments_and_update_statuses.rb +44 -0
  29. data/lib/context_drop/agent/orchestrator.rb +1 -1
  30. data/lib/context_drop/configuration.rb +26 -0
  31. data/lib/context_drop/mcp/dispatcher.rb +2 -1
  32. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +5 -3
  33. data/lib/context_drop/mcp/server.rb +1 -0
  34. data/lib/context_drop/mcp/tools/add_feedback_comment.rb +139 -0
  35. data/lib/context_drop/mcp/tools/get_feedback.rb +45 -6
  36. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +3 -0
  37. data/lib/context_drop/mcp/tools/list_feedbacks.rb +23 -3
  38. data/lib/context_drop/mcp/tools/update_feedback_status.rb +5 -3
  39. data/lib/context_drop/version.rb +1 -1
  40. metadata +7 -2
@@ -883,6 +883,9 @@
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>`;
888
+ const ICON_COMMENT = `<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="M13.5 10.2a1.3 1.3 0 0 1-1.3 1.3H5.4L2.5 14V3.8A1.3 1.3 0 0 1 3.8 2.5h8.4a1.3 1.3 0 0 1 1.3 1.3v6.4z"/></svg>`;
886
889
 
887
890
  // --- Module: markdown.ts ---
888
891
  /**
@@ -1160,6 +1163,47 @@
1160
1163
  border-color: #3b4252;
1161
1164
  }
1162
1165
 
1166
+ :host([data-cd-theme="dark"]) .cd-msg-action-btn:hover:not(:disabled),
1167
+ :host([data-theme="dark"]) .cd-msg-action-btn:hover:not(:disabled),
1168
+ .cd-composer[data-theme="dark"] .cd-msg-action-btn:hover:not(:disabled) {
1169
+ background: rgba(255, 255, 255, 0.09);
1170
+ color: var(--cd-ink);
1171
+ }
1172
+
1173
+ :host([data-cd-theme="dark"]) .cd-msg-action-btn.is-danger:hover:not(:disabled),
1174
+ :host([data-theme="dark"]) .cd-msg-action-btn.is-danger:hover:not(:disabled),
1175
+ .cd-composer[data-theme="dark"] .cd-msg-action-btn.is-danger:hover:not(:disabled) {
1176
+ background: var(--cd-danger-soft);
1177
+ color: #fca5a5;
1178
+ }
1179
+
1180
+ :host([data-cd-theme="dark"]) .cd-edit-banner-info,
1181
+ :host([data-theme="dark"]) .cd-edit-banner-info,
1182
+ .cd-composer[data-theme="dark"] .cd-edit-banner-info {
1183
+ color: var(--cd-ink);
1184
+ }
1185
+
1186
+ :host([data-cd-theme="dark"]) .cd-msg-delete-label,
1187
+ :host([data-theme="dark"]) .cd-msg-delete-label,
1188
+ .cd-composer[data-theme="dark"] .cd-msg-delete-label {
1189
+ color: #fca5a5;
1190
+ }
1191
+
1192
+ :host([data-cd-theme="dark"]) .cd-btn-danger,
1193
+ :host([data-theme="dark"]) .cd-btn-danger,
1194
+ .cd-composer[data-theme="dark"] .cd-btn-danger {
1195
+ background: #dc2626;
1196
+ border-color: #dc2626;
1197
+ color: #ffffff;
1198
+ }
1199
+
1200
+ :host([data-cd-theme="dark"]) .cd-btn-danger:hover:not(:disabled),
1201
+ :host([data-theme="dark"]) .cd-btn-danger:hover:not(:disabled),
1202
+ .cd-composer[data-theme="dark"] .cd-btn-danger:hover:not(:disabled) {
1203
+ background: #ef4444;
1204
+ border-color: #ef4444;
1205
+ }
1206
+
1163
1207
  *, *::before, *::after {
1164
1208
  box-sizing: border-box;
1165
1209
  }
@@ -2022,11 +2066,18 @@
2022
2066
  flex-direction: column;
2023
2067
  gap: 5px;
2024
2068
  align-self: flex-end;
2069
+ width: 92%;
2025
2070
  max-width: 92%;
2026
2071
  padding: 9px 11px;
2027
2072
  background: var(--cd-surface-elevated);
2028
2073
  border: 1px solid var(--cd-border);
2029
2074
  border-radius: 12px 12px 3px 12px;
2075
+ transition: border-color 0.14s var(--cd-ease), box-shadow 0.14s var(--cd-ease);
2076
+ }
2077
+
2078
+ .cd-chat-msg.is-editing {
2079
+ border-color: var(--cd-accent);
2080
+ box-shadow: 0 0 0 2px var(--cd-accent-soft);
2030
2081
  }
2031
2082
 
2032
2083
  .cd-chat-msg-text {
@@ -2047,6 +2098,83 @@
2047
2098
  font-variant-numeric: tabular-nums;
2048
2099
  }
2049
2100
 
2101
+ .cd-chat-msg-meta-info {
2102
+ display: inline-flex;
2103
+ align-items: center;
2104
+ gap: 6px;
2105
+ min-width: 0;
2106
+ flex-wrap: wrap;
2107
+ }
2108
+
2109
+ .cd-chat-msg-actions {
2110
+ display: inline-flex;
2111
+ align-items: center;
2112
+ gap: 2px;
2113
+ flex-shrink: 0;
2114
+ }
2115
+
2116
+ .cd-msg-action-btn {
2117
+ appearance: none;
2118
+ display: inline-flex;
2119
+ align-items: center;
2120
+ justify-content: center;
2121
+ width: 24px;
2122
+ height: 24px;
2123
+ padding: 0;
2124
+ border: 1px solid transparent;
2125
+ border-radius: 6px;
2126
+ background: transparent;
2127
+ color: var(--cd-ink-secondary);
2128
+ cursor: pointer;
2129
+ transition: background-color 0.12s ease, color 0.12s ease, border-color 0.12s ease;
2130
+ }
2131
+
2132
+ .cd-msg-action-btn:hover:not(:disabled) {
2133
+ background: rgba(17, 19, 24, 0.06);
2134
+ color: var(--cd-ink);
2135
+ }
2136
+
2137
+ .cd-msg-action-btn.is-active {
2138
+ background: var(--cd-accent-soft);
2139
+ color: var(--cd-accent-hover);
2140
+ border-color: rgba(29, 78, 216, 0.25);
2141
+ }
2142
+
2143
+ .cd-msg-action-btn.is-danger:hover:not(:disabled) {
2144
+ background: var(--cd-danger-soft);
2145
+ color: var(--cd-danger);
2146
+ }
2147
+
2148
+ .cd-msg-action-btn:disabled {
2149
+ opacity: 0.4;
2150
+ cursor: not-allowed;
2151
+ }
2152
+
2153
+ .cd-msg-delete-confirm {
2154
+ display: flex;
2155
+ align-items: center;
2156
+ justify-content: space-between;
2157
+ gap: 8px;
2158
+ margin-top: 2px;
2159
+ padding: 6px 8px;
2160
+ border-radius: 8px;
2161
+ background: var(--cd-danger-soft);
2162
+ border: 1px solid rgba(185, 28, 28, 0.24);
2163
+ }
2164
+
2165
+ .cd-msg-delete-label {
2166
+ font-size: 11.5px;
2167
+ font-weight: 600;
2168
+ color: var(--cd-danger);
2169
+ }
2170
+
2171
+ .cd-msg-delete-btns {
2172
+ display: inline-flex;
2173
+ align-items: center;
2174
+ gap: 5px;
2175
+ flex-shrink: 0;
2176
+ }
2177
+
2050
2178
  .cd-chat-msg-pills {
2051
2179
  display: flex;
2052
2180
  flex-wrap: wrap;
@@ -2069,6 +2197,136 @@
2069
2197
  font-weight: 500;
2070
2198
  }
2071
2199
 
2200
+ .cd-chat-msg.is-commenting {
2201
+ border-color: var(--cd-accent);
2202
+ box-shadow: 0 0 0 2px rgba(29, 78, 216, 0.12);
2203
+ }
2204
+
2205
+ .cd-msg-status-badge {
2206
+ display: inline-flex;
2207
+ align-items: center;
2208
+ padding: 1px 6px;
2209
+ border-radius: 999px;
2210
+ font-size: 10px;
2211
+ font-weight: 600;
2212
+ text-transform: capitalize;
2213
+ letter-spacing: 0.01em;
2214
+ border: 1px solid transparent;
2215
+ line-height: 1.4;
2216
+ }
2217
+
2218
+ .cd-msg-status-badge.is-new {
2219
+ background: #eff6ff;
2220
+ border-color: #bfdbfe;
2221
+ color: #1d4ed8;
2222
+ }
2223
+
2224
+ .cd-msg-status-badge.is-updated {
2225
+ background: #fffbeb;
2226
+ border-color: #fde68a;
2227
+ color: #b45309;
2228
+ }
2229
+
2230
+ .cd-msg-status-badge.is-fixed {
2231
+ background: #eef2ff;
2232
+ border-color: #c7d2fe;
2233
+ color: #4338ca;
2234
+ }
2235
+
2236
+ .cd-msg-status-badge.is-reviewed {
2237
+ background: #f0fdf4;
2238
+ border-color: #bbf7d0;
2239
+ color: #15803d;
2240
+ }
2241
+
2242
+ .cd-msg-status-badge.is-dismissed {
2243
+ background: #f8fafc;
2244
+ border-color: #e2e8f0;
2245
+ color: #64748b;
2246
+ }
2247
+
2248
+ .cd-review-btn {
2249
+ display: inline-flex;
2250
+ align-items: center;
2251
+ gap: 4px;
2252
+ padding: 2px 7px;
2253
+ border-radius: 5px;
2254
+ border: 1px solid #bbf7d0;
2255
+ background: #f0fdf4;
2256
+ color: #15803d;
2257
+ font-family: inherit;
2258
+ font-size: 10.5px;
2259
+ font-weight: 600;
2260
+ cursor: pointer;
2261
+ transition: background 0.12s ease, border-color 0.12s ease;
2262
+ }
2263
+
2264
+ .cd-review-btn:hover:not(:disabled) {
2265
+ background: #dcfce7;
2266
+ border-color: #86efac;
2267
+ }
2268
+
2269
+ .cd-review-btn:disabled {
2270
+ opacity: 0.5;
2271
+ cursor: default;
2272
+ }
2273
+
2274
+ .cd-comments-list {
2275
+ display: flex;
2276
+ flex-direction: column;
2277
+ gap: 6px;
2278
+ margin-top: 6px;
2279
+ padding-top: 6px;
2280
+ border-top: 1px dashed var(--cd-border-subtle);
2281
+ }
2282
+
2283
+ .cd-comment-item {
2284
+ background: var(--cd-surface-recessed);
2285
+ border: 1px solid var(--cd-border-subtle);
2286
+ border-radius: 6px;
2287
+ padding: 6px 8px;
2288
+ }
2289
+
2290
+ .cd-comment-header {
2291
+ display: flex;
2292
+ align-items: center;
2293
+ justify-content: space-between;
2294
+ gap: 6px;
2295
+ font-size: 10.5px;
2296
+ color: var(--cd-muted);
2297
+ margin-bottom: 2px;
2298
+ }
2299
+
2300
+ .cd-comment-author {
2301
+ font-weight: 600;
2302
+ color: var(--cd-ink);
2303
+ }
2304
+
2305
+ .cd-comment-body {
2306
+ margin: 0;
2307
+ font-size: 11.5px;
2308
+ line-height: 1.42;
2309
+ color: var(--cd-ink);
2310
+ white-space: pre-wrap;
2311
+ word-break: break-word;
2312
+ }
2313
+
2314
+ .cd-comment-images {
2315
+ display: flex;
2316
+ flex-wrap: wrap;
2317
+ gap: 5px;
2318
+ margin-top: 5px;
2319
+ }
2320
+
2321
+ .cd-comment-thumb {
2322
+ width: 48px;
2323
+ height: 48px;
2324
+ object-fit: cover;
2325
+ border-radius: 4px;
2326
+ border: 1px solid var(--cd-border);
2327
+ display: block;
2328
+ }
2329
+
2072
2330
  /* ==========================================================================
2073
2331
  4. LOCAL BYOK AGENTIC CODING SIDEBAR (.cd-agent-sidebar)
2074
2332
  ========================================================================== */
@@ -2931,6 +3189,42 @@
2931
3189
  border-top: 1px solid var(--cd-border);
2932
3190
  }
2933
3191
 
3192
+ .cd-edit-banner {
3193
+ display: flex;
3194
+ align-items: center;
3195
+ justify-content: space-between;
3196
+ gap: 8px;
3197
+ padding: 6px 12px;
3198
+ background: var(--cd-accent-soft);
3199
+ border-bottom: 1px solid var(--cd-border-subtle);
3200
+ font-size: 12px;
3201
+ color: var(--cd-ink);
3202
+ }
3203
+
3204
+ .cd-edit-banner[hidden] {
3205
+ display: none !important;
3206
+ }
3207
+
3208
+ .cd-edit-banner-info {
3209
+ display: inline-flex;
3210
+ align-items: center;
3211
+ gap: 6px;
3212
+ min-width: 0;
3213
+ font-weight: 600;
3214
+ color: var(--cd-accent-hover);
3215
+ }
3216
+
3217
+ .cd-edit-banner-info svg {
3218
+ color: var(--cd-accent-hover);
3219
+ flex-shrink: 0;
3220
+ }
3221
+
3222
+ .cd-edit-banner-id {
3223
+ font-family: var(--cd-mono);
3224
+ font-size: 11px;
3225
+ font-variant-numeric: tabular-nums;
3226
+ }
3227
+
2934
3228
  .cd-textarea {
2935
3229
  width: 100%;
2936
3230
  min-height: 68px;
@@ -3011,6 +3305,24 @@
3011
3305
  border-color: #252a34;
3012
3306
  }
3013
3307
 
3308
+ .cd-btn-xs {
3309
+ padding: 3px 8px;
3310
+ font-size: 11.5px;
3311
+ border-radius: 6px;
3312
+ }
3313
+
3314
+ .cd-btn-danger {
3315
+ background: var(--cd-danger);
3316
+ border-color: var(--cd-danger);
3317
+ color: #ffffff;
3318
+ font-weight: 600;
3319
+ }
3320
+
3321
+ .cd-btn-danger:hover:not(:disabled) {
3322
+ background: #991b1b;
3323
+ border-color: #991b1b;
3324
+ }
3325
+
3014
3326
  @media (max-width: 560px) {
3015
3327
  .cd-composer,
3016
3328
  .cd-compact-bar {
@@ -3038,6 +3350,8 @@
3038
3350
  .cd-corner-flap,
3039
3351
  .cd-drag-pin-head,
3040
3352
  .cd-composer,
3353
+ .cd-chat-msg,
3354
+ .cd-msg-action-btn,
3041
3355
  .cd-agent-sidebar,
3042
3356
  .cd-skeleton-bar {
3043
3357
  animation: none !important;
@@ -3047,13 +3361,72 @@
3047
3361
  `;
3048
3362
 
3049
3363
  // --- Module: api-client.ts ---
3364
+ const OWNERSHIP_STORAGE_KEY = "context_drop_ownership_tokens";
3365
+ const MAX_STORED_OWNERSHIP_TOKENS = 50;
3366
+
3367
+ function getBrowserLocalStorage() {
3368
+ try {
3369
+ if (typeof window !== "undefined" && "localStorage" in window) {
3370
+ const store = window.localStorage;
3371
+ if (store && typeof store.getItem === "function" && typeof store.setItem === "function") {
3372
+ return store;
3373
+ }
3374
+ }
3375
+ } catch {
3376
+ // Storage unavailable or restricted by browser privacy policy
3377
+ }
3378
+ return null;
3379
+ }
3050
3380
  class ContextDropApiClient {
3051
3381
  baseUrl ;
3382
+ credentials ;
3383
+ customHeaders ;
3052
3384
  cachedCsrfToken = null;
3385
+ configFetched = false;
3053
3386
  inFlightConfigPromise = null;
3387
+ memoryOwnershipTokens = new Map();
3054
3388
 
3055
- constructor(baseUrl = "/context_drop") {
3389
+ constructor(baseUrl = "/context_drop", options = {}) {
3056
3390
  this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
3391
+ this.credentials = options.credentials || "same-origin";
3392
+ this.customHeaders = options.headers ? { ...options.headers } : {};
3393
+ }
3394
+
3395
+ getBaseUrl() {
3396
+ return this.baseUrl;
3397
+ }
3398
+
3399
+ setCredentials(credentials ) {
3400
+ this.credentials = credentials;
3401
+ }
3402
+
3403
+ setHeaders(headers ) {
3404
+ this.customHeaders = { ...headers };
3405
+ }
3406
+
3407
+ isCrossOriginEndpoint() {
3408
+ if (!/^https?:\/\//i.test(this.baseUrl)) {
3409
+ return false;
3410
+ }
3411
+ if (typeof window === "undefined" || !window.location || !window.location.origin) {
3412
+ return true;
3413
+ }
3414
+ try {
3415
+ return new URL(this.baseUrl, window.location.origin).origin !== window.location.origin;
3416
+ } catch {
3417
+ return false;
3418
+ }
3419
+ }
3420
+
3421
+ mergeClientHeaders(base ) {
3422
+ const merged = {
3423
+ ...this.customHeaders,
3424
+ ...base
3425
+ };
3426
+ if (this.isCrossOriginEndpoint()) {
3427
+ merged["X-Context-Drop-Client"] = "1";
3428
+ }
3429
+ return merged;
3057
3430
  }
3058
3431
 
3059
3432
  getCsrfToken() {
@@ -3084,10 +3457,10 @@
3084
3457
  try {
3085
3458
  const response = await fetch(`${this.baseUrl}/config`, {
3086
3459
  method: "GET",
3087
- credentials: "same-origin",
3088
- headers: {
3460
+ credentials: this.credentials,
3461
+ headers: this.mergeClientHeaders({
3089
3462
  Accept: "application/json"
3090
- }
3463
+ })
3091
3464
  });
3092
3465
 
3093
3466
  if (!response.ok) {
@@ -3095,6 +3468,7 @@
3095
3468
  }
3096
3469
 
3097
3470
  const config = (await response.json()) ;
3471
+ this.configFetched = true;
3098
3472
  if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
3099
3473
  this.cachedCsrfToken = config.csrf_token.trim();
3100
3474
  if (typeof document !== "undefined") {
@@ -3122,6 +3496,9 @@
3122
3496
  if (this.cachedCsrfToken) {
3123
3497
  return this.cachedCsrfToken;
3124
3498
  }
3499
+ if (this.configFetched) {
3500
+ return null;
3501
+ }
3125
3502
  }
3126
3503
 
3127
3504
  try {
@@ -3166,7 +3543,8 @@
3166
3543
 
3167
3544
  const errorMessage = parsedError || rawText || "";
3168
3545
  const shouldRetryCsrf =
3169
- this.isCsrfError(response.status, errorMessage) || (!csrfToken && response.status === 422);
3546
+ this.isCsrfError(response.status, errorMessage) ||
3547
+ (!csrfToken && !this.configFetched && response.status === 422);
3170
3548
 
3171
3549
  if (shouldRetryCsrf) {
3172
3550
  csrfToken = await this.resolveCsrfToken(true);
@@ -3197,7 +3575,7 @@
3197
3575
  if (csrfToken) {
3198
3576
  headers["X-CSRF-Token"] = csrfToken;
3199
3577
  }
3200
- return headers;
3578
+ return this.mergeClientHeaders(headers);
3201
3579
  }
3202
3580
 
3203
3581
  async uploadAttachment(file , filename ) {
@@ -3214,8 +3592,8 @@
3214
3592
 
3215
3593
  return fetch(`${this.baseUrl}/attachments`, {
3216
3594
  method: "POST",
3217
- credentials: "same-origin",
3218
- headers,
3595
+ credentials: this.credentials,
3596
+ headers: this.mergeClientHeaders(headers),
3219
3597
  body: formData
3220
3598
  });
3221
3599
  };
@@ -3223,25 +3601,274 @@
3223
3601
  return this.executeWithCsrfRetry(makeRequest, "Upload failed");
3224
3602
  }
3225
3603
 
3604
+ ownershipScopedKey(id ) {
3605
+ return `${this.baseUrl}::${String(id)}`;
3606
+ }
3607
+
3608
+ readStoredTokenMap() {
3609
+ const store = getBrowserLocalStorage();
3610
+ if (!store) {
3611
+ const out = {};
3612
+ for (const [k, v] of this.memoryOwnershipTokens.entries()) {
3613
+ out[k] = v;
3614
+ }
3615
+ return out;
3616
+ }
3617
+
3618
+ try {
3619
+ const raw = store.getItem(OWNERSHIP_STORAGE_KEY);
3620
+ if (!raw) return {};
3621
+ const parsed = JSON.parse(raw) ;
3622
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
3623
+ return {};
3624
+ }
3625
+ const clean = {};
3626
+ for (const [k, v] of Object.entries(parsed )) {
3627
+ if (typeof v === "string" && v.trim().length > 0) {
3628
+ clean[k] = v.trim();
3629
+ }
3630
+ }
3631
+ return clean;
3632
+ } catch {
3633
+ return {};
3634
+ }
3635
+ }
3636
+
3637
+ writeStoredTokenMap(map ) {
3638
+ const entries = Object.entries(map);
3639
+ const trimmedEntries =
3640
+ entries.length > MAX_STORED_OWNERSHIP_TOKENS
3641
+ ? entries.slice(entries.length - MAX_STORED_OWNERSHIP_TOKENS)
3642
+ : entries;
3643
+
3644
+ this.memoryOwnershipTokens.clear();
3645
+ const bounded = {};
3646
+ for (const [k, v] of trimmedEntries) {
3647
+ bounded[k] = v;
3648
+ this.memoryOwnershipTokens.set(k, v);
3649
+ }
3650
+
3651
+ const store = getBrowserLocalStorage();
3652
+ if (store) {
3653
+ try {
3654
+ store.setItem(OWNERSHIP_STORAGE_KEY, JSON.stringify(bounded));
3655
+ } catch {
3656
+ // Non-fatal if storage quota exceeded
3657
+ }
3658
+ }
3659
+ }
3660
+
3661
+ getOwnershipToken(id ) {
3662
+ const map = this.readStoredTokenMap();
3663
+ const scoped = map[this.ownershipScopedKey(id)];
3664
+ if (scoped) return scoped;
3665
+ const plain = map[String(id)];
3666
+ return plain || null;
3667
+ }
3668
+
3669
+ setOwnershipToken(id , token ) {
3670
+ const trimmed = typeof token === "string" ? token.trim() : "";
3671
+ if (!trimmed) return;
3672
+ const map = this.readStoredTokenMap();
3673
+ const key = this.ownershipScopedKey(id);
3674
+ delete map[key];
3675
+ map[key] = trimmed;
3676
+ this.writeStoredTokenMap(map);
3677
+ }
3678
+
3679
+ removeOwnershipToken(id ) {
3680
+ const map = this.readStoredTokenMap();
3681
+ const scopedKey = this.ownershipScopedKey(id);
3682
+ const plainKey = String(id);
3683
+ if (!(scopedKey in map) && !(plainKey in map)) return;
3684
+ delete map[scopedKey];
3685
+ delete map[plainKey];
3686
+ this.writeStoredTokenMap(map);
3687
+ }
3688
+
3689
+ getAllOwnershipTokens() {
3690
+ const map = this.readStoredTokenMap();
3691
+ const prefix = `${this.baseUrl}::`;
3692
+ const tokens = [];
3693
+ for (const [k, v] of Object.entries(map)) {
3694
+ if ((k.startsWith(prefix) || !k.includes("::")) && v && !tokens.includes(v)) {
3695
+ tokens.push(v);
3696
+ }
3697
+ }
3698
+ return tokens;
3699
+ }
3700
+
3701
+ buildAttachmentPreviewUrl(
3702
+ feedbackId ,
3703
+ attachmentId ,
3704
+ ownershipToken
3705
+ ) {
3706
+ const token = ownershipToken || this.getOwnershipToken(feedbackId);
3707
+ const base = `${this.baseUrl}/feedback/${encodeURIComponent(String(feedbackId))}/attachments/${encodeURIComponent(String(attachmentId))}`;
3708
+ return token ? `${base}?ownership_token=${encodeURIComponent(token)}` : base;
3709
+ }
3710
+
3226
3711
  async submitFeedback(payload ) {
3227
3712
  const makeRequest = async (csrfToken ) =>
3228
3713
  fetch(`${this.baseUrl}/feedback`, {
3229
3714
  method: "POST",
3230
- credentials: "same-origin",
3715
+ credentials: this.credentials,
3231
3716
  headers: this.buildJsonHeaders(csrfToken),
3232
3717
  body: JSON.stringify({ feedback: payload })
3233
3718
  });
3234
3719
 
3235
- return this.executeWithCsrfRetry(makeRequest, "Submission failed");
3720
+ const response = await this.executeWithCsrfRetry (
3721
+ makeRequest,
3722
+ "Submission failed"
3723
+ );
3724
+
3725
+ const token = response?.ownership_token || response?.feedback?.ownership_token;
3726
+ if (response?.id !== undefined && token) {
3727
+ this.setOwnershipToken(response.id, token);
3728
+ }
3729
+ return response;
3730
+ }
3731
+
3732
+ async fetchOwnFeedbacks(limit = 30) {
3733
+ const headers = {
3734
+ Accept: "application/json"
3735
+ };
3736
+ const tokens = this.getAllOwnershipTokens();
3737
+ if (tokens.length > 0) {
3738
+ headers["X-Context-Drop-Ownership-Tokens"] = tokens.join(",");
3739
+ }
3740
+
3741
+ const qs = limit > 0 ? `?limit=${encodeURIComponent(String(limit))}` : "";
3742
+ const response = await fetch(`${this.baseUrl}/feedback${qs}`, {
3743
+ method: "GET",
3744
+ credentials: this.credentials,
3745
+ headers: this.mergeClientHeaders(headers)
3746
+ });
3747
+
3748
+ if (!response.ok) {
3749
+ const errBody = await response.json().catch(() => ({}));
3750
+ throw new Error(
3751
+ (errBody ).error || `Failed to load own feedbacks (${response.status})`
3752
+ );
3753
+ }
3754
+
3755
+ const parsed = (await response.json().catch(() => ({}))) ;
3756
+ const feedbacks = Array.isArray(parsed?.feedbacks) ? parsed.feedbacks : [];
3757
+ for (const item of feedbacks) {
3758
+ if (item && item.id !== undefined && typeof item.ownership_token === "string") {
3759
+ this.setOwnershipToken(item.id, item.ownership_token);
3760
+ }
3761
+ }
3762
+
3763
+ return {
3764
+ total_count: typeof parsed?.total_count === "number" ? parsed.total_count : feedbacks.length,
3765
+ feedbacks
3766
+ };
3767
+ }
3768
+
3769
+ async updateFeedback(
3770
+ id ,
3771
+ payload ,
3772
+ ownershipToken
3773
+ ) {
3774
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
3775
+ const makeRequest = async (csrfToken ) => {
3776
+ const headers = this.buildJsonHeaders(csrfToken);
3777
+ if (resolvedToken) {
3778
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
3779
+ }
3780
+ const bodyPayload = { feedback: payload };
3781
+ if (resolvedToken) {
3782
+ bodyPayload.ownership_token = resolvedToken;
3783
+ }
3784
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
3785
+ method: "PATCH",
3786
+ credentials: this.credentials,
3787
+ headers,
3788
+ body: JSON.stringify(bodyPayload)
3789
+ });
3790
+ };
3791
+
3792
+ const response = await this.executeWithCsrfRetry (
3793
+ makeRequest,
3794
+ "Update failed"
3795
+ );
3796
+
3797
+ const nextToken = response?.ownership_token || response?.feedback?.ownership_token;
3798
+ if (response?.id !== undefined && nextToken) {
3799
+ this.setOwnershipToken(response.id, nextToken);
3800
+ }
3801
+ return response;
3802
+ }
3803
+
3804
+ async createComment(
3805
+ id ,
3806
+ payload ,
3807
+ ownershipToken
3808
+ ) {
3809
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
3810
+ const makeRequest = async (csrfToken ) => {
3811
+ const headers = this.buildJsonHeaders(csrfToken);
3812
+ if (resolvedToken) {
3813
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
3814
+ }
3815
+ const bodyPayload = { comment: payload };
3816
+ if (resolvedToken) {
3817
+ bodyPayload.ownership_token = resolvedToken;
3818
+ }
3819
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}/comments`, {
3820
+ method: "POST",
3821
+ credentials: this.credentials,
3822
+ headers,
3823
+ body: JSON.stringify(bodyPayload)
3824
+ });
3825
+ };
3826
+
3827
+ const response = await this.executeWithCsrfRetry (
3828
+ makeRequest,
3829
+ "Comment failed"
3830
+ );
3831
+
3832
+ const nextToken = response?.feedback?.ownership_token;
3833
+ if (response?.feedback?.id !== undefined && nextToken) {
3834
+ this.setOwnershipToken(response.feedback.id, nextToken);
3835
+ }
3836
+ return response;
3837
+ }
3838
+
3839
+ async deleteFeedback(
3840
+ id ,
3841
+ ownershipToken
3842
+ ) {
3843
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
3844
+ const makeRequest = async (csrfToken ) => {
3845
+ const headers = this.buildJsonHeaders(csrfToken);
3846
+ if (resolvedToken) {
3847
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
3848
+ }
3849
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
3850
+ method: "DELETE",
3851
+ credentials: this.credentials,
3852
+ headers
3853
+ });
3854
+ };
3855
+
3856
+ const response = await this.executeWithCsrfRetry (
3857
+ makeRequest,
3858
+ "Delete failed"
3859
+ );
3860
+
3861
+ this.removeOwnershipToken(id);
3862
+ return response;
3236
3863
  }
3237
3864
 
3238
3865
  async fetchAgentStatus() {
3239
3866
  const response = await fetch(`${this.baseUrl}/agent/status`, {
3240
3867
  method: "GET",
3241
- credentials: "same-origin",
3242
- headers: {
3868
+ credentials: this.credentials,
3869
+ headers: this.mergeClientHeaders({
3243
3870
  Accept: "application/json"
3244
- }
3871
+ })
3245
3872
  });
3246
3873
 
3247
3874
  if (!response.ok) {
@@ -3258,7 +3885,7 @@
3258
3885
  const makeRequest = async (csrfToken ) =>
3259
3886
  fetch(`${this.baseUrl}/agent/keys`, {
3260
3887
  method: "POST",
3261
- credentials: "same-origin",
3888
+ credentials: this.credentials,
3262
3889
  headers: this.buildJsonHeaders(csrfToken),
3263
3890
  body: JSON.stringify(payload)
3264
3891
  });
@@ -3270,7 +3897,7 @@
3270
3897
  const makeRequest = async (csrfToken ) =>
3271
3898
  fetch(`${this.baseUrl}/agent/keys?provider=${encodeURIComponent(provider)}`, {
3272
3899
  method: "DELETE",
3273
- credentials: "same-origin",
3900
+ credentials: this.credentials,
3274
3901
  headers: this.buildJsonHeaders(csrfToken)
3275
3902
  });
3276
3903
 
@@ -3284,10 +3911,10 @@
3284
3911
  const qs = `environment=${encodeURIComponent(environment)}&status=${encodeURIComponent(status)}`;
3285
3912
  const response = await fetch(`${this.baseUrl}/agent/feedbacks?${qs}`, {
3286
3913
  method: "GET",
3287
- credentials: "same-origin",
3288
- headers: {
3914
+ credentials: this.credentials,
3915
+ headers: this.mergeClientHeaders({
3289
3916
  Accept: "application/json"
3290
- }
3917
+ })
3291
3918
  });
3292
3919
 
3293
3920
  if (!response.ok) {
@@ -3304,7 +3931,7 @@
3304
3931
  const makeRequest = async (csrfToken ) =>
3305
3932
  fetch(`${this.baseUrl}/agent/chat`, {
3306
3933
  method: "POST",
3307
- credentials: "same-origin",
3934
+ credentials: this.credentials,
3308
3935
  headers: this.buildJsonHeaders(csrfToken),
3309
3936
  body: JSON.stringify(payload)
3310
3937
  });
@@ -3316,7 +3943,7 @@
3316
3943
  const makeRequest = async (csrfToken ) =>
3317
3944
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/apply`, {
3318
3945
  method: "POST",
3319
- credentials: "same-origin",
3946
+ credentials: this.credentials,
3320
3947
  headers: this.buildJsonHeaders(csrfToken)
3321
3948
  });
3322
3949
 
@@ -3327,7 +3954,7 @@
3327
3954
  const makeRequest = async (csrfToken ) =>
3328
3955
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/reject`, {
3329
3956
  method: "POST",
3330
- credentials: "same-origin",
3957
+ credentials: this.credentials,
3331
3958
  headers: this.buildJsonHeaders(csrfToken)
3332
3959
  });
3333
3960
 
@@ -3338,7 +3965,7 @@
3338
3965
  const makeRequest = async (csrfToken ) =>
3339
3966
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/revert`, {
3340
3967
  method: "POST",
3341
- credentials: "same-origin",
3968
+ credentials: this.credentials,
3342
3969
  headers: this.buildJsonHeaders(csrfToken)
3343
3970
  });
3344
3971
 
@@ -3450,7 +4077,7 @@
3450
4077
 
3451
4078
  // Paint page background
3452
4079
  const bodyBg =
3453
- window.getComputedStyle && document.body
4080
+ typeof window.getComputedStyle === "function" && document.body
3454
4081
  ? window.getComputedStyle(document.body).backgroundColor
3455
4082
  : "#ffffff";
3456
4083
  ctx.fillStyle = bodyBg && bodyBg !== "rgba(0, 0, 0, 0)" ? bodyBg : "#ffffff";
@@ -4605,7 +5232,7 @@
4605
5232
  }
4606
5233
 
4607
5234
  renderScrubbingHudContent(
4608
- currentCandidate ,
5235
+ _currentCandidate ,
4609
5236
  rect
4610
5237
  ) {
4611
5238
  if (!this.hudEl) return;
@@ -5321,12 +5948,24 @@
5321
5948
  : (class {} );
5322
5949
  class ContextDropWidgetElement extends BaseHTMLElement {
5323
5950
  static get observedAttributes() {
5324
- return ["data-position", "data-config", "data-theme", "data-cd-theme"];
5951
+ return [
5952
+ "data-endpoint",
5953
+ "data-position",
5954
+ "data-placeholder",
5955
+ "data-config",
5956
+ "data-metadata",
5957
+ "data-credentials",
5958
+ "data-selection-mode",
5959
+ "data-environment",
5960
+ "data-theme",
5961
+ "data-cd-theme"
5962
+ ];
5325
5963
  }
5326
5964
 
5327
5965
  shadow = null;
5328
5966
  config = structuredClone(DEFAULT_CONFIG);
5329
5967
  customMetadata = {};
5968
+ customHeaders = {};
5330
5969
  apiClient = new ContextDropApiClient("/context_drop");
5331
5970
  picker = null;
5332
5971
 
@@ -5350,6 +5989,19 @@
5350
5989
  elementDomNodes = new Map();
5351
5990
  attachments = [];
5352
5991
  sessionHistory = [];
5992
+ ownFeedbacksLoaded = false;
5993
+ inFlightOwnFeedbacksPromise = null;
5994
+ editingFeedbackId = null;
5995
+ commentingFeedbackId = null;
5996
+ reviewingFeedbackId = null;
5997
+ confirmingDeleteId = null;
5998
+ deletingFeedbackId = null;
5999
+ stashedDraftBeforeEdit
6000
+
6001
+
6002
+
6003
+
6004
+ = null;
5353
6005
 
5354
6006
  // Local Agent state
5355
6007
  agentStatusLoaded = false;
@@ -5392,6 +6044,8 @@
5392
6044
  composerToolbarScreenshotBtn = null;
5393
6045
  composerToolbarUploadBtn = null;
5394
6046
  chatThreadEl = null;
6047
+ editBannerEl = null;
6048
+ editBannerInfoEl = null;
5395
6049
  textareaEl = null;
5396
6050
  trayEl = null;
5397
6051
  statusEl = null;
@@ -5403,7 +6057,6 @@
5403
6057
  sidebarPinBtn = null;
5404
6058
  sidebarEnvPillEl = null;
5405
6059
  sidebarPushBtn = null;
5406
- providerPillBtn = null;
5407
6060
  keyDotEl = null;
5408
6061
  providerPillLabelEl = null;
5409
6062
  keysToggleBtn = null;
@@ -5437,6 +6090,37 @@
5437
6090
  this.applyTheme(newValue, false);
5438
6091
  } else if (name === "data-position" && newValue) {
5439
6092
  this.setCornerPosition(newValue );
6093
+ } else if (name === "data-endpoint" && newValue && this.shadow) {
6094
+ this.setEndpoint(newValue);
6095
+ } else if (name === "data-credentials" && newValue && this.shadow) {
6096
+ if (newValue === "same-origin" || newValue === "include" || newValue === "omit") {
6097
+ this.apiClient.setCredentials(newValue);
6098
+ }
6099
+ } else if (name === "data-placeholder" && newValue && this.shadow) {
6100
+ this.setWidgetConfig({ placeholder: newValue });
6101
+ } else if (name === "data-metadata" && this.shadow) {
6102
+ if (newValue) {
6103
+ try {
6104
+ this.customMetadata = JSON.parse(newValue) ;
6105
+ } catch {
6106
+ this.customMetadata = {};
6107
+ }
6108
+ } else {
6109
+ this.customMetadata = {};
6110
+ }
6111
+ } else if (name === "data-selection-mode" && newValue && this.shadow) {
6112
+ if (newValue === "smart" || newValue === "verbose") {
6113
+ this.setWidgetConfig({ features: { ...this.config.features, selection_mode: newValue } });
6114
+ }
6115
+ } else if (name === "data-environment" && newValue && this.shadow) {
6116
+ this.setWidgetConfig({ environment: newValue });
6117
+ } else if (name === "data-config" && newValue && this.shadow) {
6118
+ try {
6119
+ const parsed = JSON.parse(newValue) ;
6120
+ this.setWidgetConfig(parsed);
6121
+ } catch {
6122
+ // Ignore malformed JSON
6123
+ }
5440
6124
  }
5441
6125
  }
5442
6126
 
@@ -5477,6 +6161,25 @@
5477
6161
  return;
5478
6162
  }
5479
6163
 
6164
+ if (
6165
+ ev.key === "Escape" &&
6166
+ !(this.picker && this.picker.isActive()) &&
6167
+ this.isOpen &&
6168
+ !this.isMinimized &&
6169
+ !this.isAgentModeActive()
6170
+ ) {
6171
+ if (this.confirmingDeleteId !== null) {
6172
+ ev.preventDefault();
6173
+ this.cancelDeleteFeedback();
6174
+ return;
6175
+ }
6176
+ if (this.editingFeedbackId !== null) {
6177
+ ev.preventDefault();
6178
+ this.cancelEditingFeedback();
6179
+ return;
6180
+ }
6181
+ }
6182
+
5480
6183
  // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
5481
6184
  if (
5482
6185
  !this.isSmartSelectionMode() &&
@@ -5581,81 +6284,547 @@
5581
6284
  this.picker?.hideExternalPreview();
5582
6285
  this.syncHostPagePushMargin(false);
5583
6286
 
5584
- if (typeof window !== "undefined") {
5585
- window.removeEventListener("mousemove", this.boundTrackPointer, { capture: true });
5586
- window.removeEventListener("keydown", this.boundGlobalKeyDown, { capture: true });
5587
- }
6287
+ if (typeof window !== "undefined") {
6288
+ window.removeEventListener("mousemove", this.boundTrackPointer, { capture: true });
6289
+ window.removeEventListener("keydown", this.boundGlobalKeyDown, { capture: true });
6290
+ }
6291
+ }
6292
+
6293
+ getConfig() {
6294
+ return this.config;
6295
+ }
6296
+
6297
+ setEndpoint(endpoint , options = {}) {
6298
+ const resolvedCredentials =
6299
+ options.credentials ||
6300
+ (this.getAttribute("data-credentials") ) ||
6301
+ "same-origin";
6302
+ const resolvedHeaders = options.headers || this.customHeaders;
6303
+ this.customHeaders = { ...resolvedHeaders };
6304
+ this.ownFeedbacksLoaded = false;
6305
+ this.inFlightOwnFeedbacksPromise = null;
6306
+ this.apiClient = new ContextDropApiClient(endpoint || "/context_drop", {
6307
+ credentials: resolvedCredentials,
6308
+ headers: this.customHeaders
6309
+ });
6310
+ }
6311
+
6312
+ setHeaders(headers ) {
6313
+ this.customHeaders = { ...headers };
6314
+ this.apiClient.setHeaders(this.customHeaders);
6315
+ }
6316
+
6317
+ setCredentials(credentials ) {
6318
+ this.apiClient.setCredentials(credentials);
6319
+ }
6320
+
6321
+ setCustomMetadata(metadata ) {
6322
+ this.customMetadata = { ...metadata };
6323
+ }
6324
+
6325
+ emitWidgetEvent(name , detail ) {
6326
+ if (typeof CustomEvent !== "function" || typeof this.dispatchEvent !== "function") {
6327
+ return;
6328
+ }
6329
+ try {
6330
+ this.dispatchEvent(
6331
+ new CustomEvent(name, {
6332
+ bubbles: true,
6333
+ composed: true,
6334
+ detail
6335
+ })
6336
+ );
6337
+ } catch {
6338
+ // Non-fatal in synthetic DOM environments
6339
+ }
6340
+ }
6341
+
6342
+ setWidgetConfig(partial ) {
6343
+ const wasAgentEnabled = Boolean(this.config.agent?.enabled);
6344
+ if (
6345
+ typeof partial.placeholder === "string" &&
6346
+ partial.placeholder !== DEFAULT_VERBOSE_PLACEHOLDER &&
6347
+ partial.placeholder !== DEFAULT_SMART_PLACEHOLDER
6348
+ ) {
6349
+ this.customPlaceholderSet = true;
6350
+ }
6351
+ this.config = {
6352
+ ...this.config,
6353
+ ...partial,
6354
+ agent: { ...(this.config.agent || { enabled: false }), ...(partial.agent || {}) },
6355
+ features: { ...this.config.features, ...(partial.features || {}) },
6356
+ limits: { ...this.config.limits, ...(partial.limits || {}) },
6357
+ privacy: { ...this.config.privacy, ...(partial.privacy || {}) }
6358
+ };
6359
+ if (partial.csrf_token) {
6360
+ this.apiClient.setCsrfToken(partial.csrf_token);
6361
+ }
6362
+ if (partial.position) {
6363
+ this.setCornerPosition(partial.position);
6364
+ }
6365
+ const nowAgentEnabled = Boolean(this.config.agent?.enabled);
6366
+ if (nowAgentEnabled && !wasAgentEnabled) {
6367
+ this.surfaceMode = "agent";
6368
+ if (this.isOpen) {
6369
+ void this.ensureAgentStatusLoaded();
6370
+ }
6371
+ } else if (!nowAgentEnabled) {
6372
+ this.surfaceMode = "feedback";
6373
+ }
6374
+ this.renderTray();
6375
+ this.renderChatThread();
6376
+ this.syncUiStates();
6377
+ }
6378
+
6379
+ getSurfaceMode() {
6380
+ return this.isAgentModeActive() ? "agent" : "feedback";
6381
+ }
6382
+
6383
+ setSurfaceMode(mode ) {
6384
+ if (mode === "agent" && !this.config.agent?.enabled) {
6385
+ return;
6386
+ }
6387
+ this.surfaceMode = mode;
6388
+ if (this.isOpen) {
6389
+ if (mode === "agent") {
6390
+ void this.ensureAgentStatusLoaded();
6391
+ } else if (!this.isMinimized) {
6392
+ void this.ensureOwnFeedbacksLoaded();
6393
+ }
6394
+ }
6395
+ this.renderTray();
6396
+ this.renderChatThread();
6397
+ this.syncUiStates();
6398
+ this.focusActiveInput();
6399
+ }
6400
+
6401
+ getElementReferences() {
6402
+ return [...this.elementReferences];
6403
+ }
6404
+
6405
+ getAttachments() {
6406
+ return [...this.attachments];
6407
+ }
6408
+
6409
+ getSessionHistory() {
6410
+ return [...this.sessionHistory];
6411
+ }
6412
+
6413
+ getEditingFeedbackId() {
6414
+ return this.editingFeedbackId;
6415
+ }
6416
+
6417
+ formatTimestampLabel(isoOrLabel ) {
6418
+ if (isoOrLabel && /^\d{2}:\d{2}$/.test(isoOrLabel.trim())) {
6419
+ return isoOrLabel.trim();
6420
+ }
6421
+ const parsed = isoOrLabel ? new Date(isoOrLabel) : new Date();
6422
+ const valid = Number.isNaN(parsed.getTime()) ? new Date() : parsed;
6423
+ return `${String(valid.getHours()).padStart(2, "0")}:${String(valid.getMinutes()).padStart(2, "0")}`;
6424
+ }
6425
+
6426
+ mapOwnRecordToSessionEntry(
6427
+ record ,
6428
+ existingEntry
6429
+ ) {
6430
+ const smartMode = this.isSmartSelectionMode();
6431
+ const rawMessage = typeof record.message === "string" ? record.message : "";
6432
+ const displayMessage =
6433
+ rawMessage || (smartMode ? "(Highlighted page area)" : "(Context drop without text)");
6434
+ const token =
6435
+ record.ownership_token ||
6436
+ existingEntry?.ownershipToken ||
6437
+ this.apiClient.getOwnershipToken(record.id) ||
6438
+ undefined;
6439
+ const isEdited = Boolean(
6440
+ record.created_at && record.updated_at && record.updated_at !== record.created_at
6441
+ );
6442
+
6443
+ const serverAttachments = Array.isArray(record.attachments) ? record.attachments : [];
6444
+ const mappedAttachments = serverAttachments.map((att, idx) => {
6445
+ const existingAtt = existingEntry?.attachments.find(
6446
+ (a) =>
6447
+ (a.server_id !== undefined && String(a.server_id) === String(att.id)) ||
6448
+ (a.server_id === undefined &&
6449
+ idx < (existingEntry?.attachments.length || 0) &&
6450
+ existingEntry?.attachments[idx]?.filename === att.filename)
6451
+ );
6452
+
6453
+ const previewUrl =
6454
+ existingAtt?.preview_url &&
6455
+ (existingAtt.preview_url.startsWith("data:") || existingAtt.preview_url.startsWith("blob:"))
6456
+ ? existingAtt.preview_url
6457
+ : this.apiClient.buildAttachmentPreviewUrl(record.id, att.id, token);
6458
+
6459
+ const meta =
6460
+ att.metadata && typeof att.metadata === "object" && !Array.isArray(att.metadata)
6461
+ ? { ...att.metadata }
6462
+ : existingAtt?.metadata
6463
+ ? { ...existingAtt.metadata }
6464
+ : {};
6465
+
6466
+ let label = existingAtt?.label || "";
6467
+ if (!label) {
6468
+ if (meta.auto_smart_context === true && typeof meta.friendly_label === "string") {
6469
+ label = `Context around ${meta.friendly_label}`;
6470
+ } else if (att.filename) {
6471
+ label = att.filename;
6472
+ } else {
6473
+ label = att.attachment_type === "screenshot" ? "Screenshot" : "Attached image";
6474
+ }
6475
+ }
6476
+
6477
+ return {
6478
+ id: existingAtt?.id || `srv_att_${record.id}_${att.id}`,
6479
+ server_id: att.id,
6480
+ label,
6481
+ preview_url: previewUrl,
6482
+ attachment_type: att.attachment_type === "screenshot" ? "screenshot" : "image",
6483
+ filename: att.filename,
6484
+ element_reference_ref: att.element_reference_ref ?? existingAtt?.element_reference_ref ?? null,
6485
+ metadata: meta
6486
+ };
6487
+ });
6488
+
6489
+ const elements = Array.isArray(record.element_references)
6490
+ ? structuredClone(record.element_references)
6491
+ : existingEntry?.elements
6492
+ ? structuredClone(existingEntry.elements)
6493
+ : [];
6494
+
6495
+ const mappedComments = Array.isArray(record.comments)
6496
+ ? record.comments.map((c) => ({
6497
+ id: c.id,
6498
+ author_label: c.author_label || "You",
6499
+ author_type: c.author_type ?? null,
6500
+ body: c.body ?? null,
6501
+ createdAt: this.formatTimestampLabel(c.created_at),
6502
+ rawCreatedAt: c.created_at,
6503
+ attachments: Array.isArray(c.attachments)
6504
+ ? c.attachments.map((att) => ({
6505
+ id: `srv-catt-${att.id}`,
6506
+ server_id: att.id,
6507
+ label: att.filename || "image.png",
6508
+ preview_url: this.apiClient.buildAttachmentPreviewUrl(record.id, att.id, token),
6509
+ attachment_type: att.attachment_type || "image",
6510
+ filename: att.filename,
6511
+ metadata: att.metadata || {}
6512
+ }))
6513
+ : []
6514
+ }))
6515
+ : existingEntry?.comments
6516
+ ? structuredClone(existingEntry.comments)
6517
+ : [];
6518
+
6519
+ return {
6520
+ id: record.id,
6521
+ message: displayMessage,
6522
+ rawMessage,
6523
+ createdAt: this.formatTimestampLabel(record.created_at || existingEntry?.rawCreatedAt),
6524
+ rawCreatedAt: record.created_at,
6525
+ rawUpdatedAt: record.updated_at,
6526
+ isEdited: isEdited || Boolean(existingEntry?.isEdited),
6527
+ status: record.status,
6528
+ ownershipToken: token,
6529
+ elements,
6530
+ attachments: mappedAttachments,
6531
+ comments: mappedComments
6532
+ };
6533
+ }
6534
+
6535
+ async refreshOwnFeedbacks() {
6536
+ if (typeof fetch !== "function") {
6537
+ return [...this.sessionHistory];
6538
+ }
6539
+ if (this.inFlightOwnFeedbacksPromise) {
6540
+ return this.inFlightOwnFeedbacksPromise;
6541
+ }
6542
+
6543
+ this.inFlightOwnFeedbacksPromise = (async () => {
6544
+ try {
6545
+ const res = await this.apiClient.fetchOwnFeedbacks();
6546
+ this.ownFeedbacksLoaded = true;
6547
+ const records = Array.isArray(res?.feedbacks) ? res.feedbacks : [];
6548
+ if (records.length === 0) {
6549
+ return [...this.sessionHistory];
6550
+ }
6551
+
6552
+ const existingById = new Map ();
6553
+ for (const entry of this.sessionHistory) {
6554
+ existingById.set(String(entry.id), entry);
6555
+ }
6556
+
6557
+ const chronologicalServerRecords = [...records].reverse();
6558
+ const serverIds = new Set ();
6559
+ const merged = [];
6560
+
6561
+ for (const record of chronologicalServerRecords) {
6562
+ if (!record || record.id === undefined || record.id === null) continue;
6563
+ const idKey = String(record.id);
6564
+ serverIds.add(idKey);
6565
+ merged.push(this.mapOwnRecordToSessionEntry(record, existingById.get(idKey)));
6566
+ }
6567
+
6568
+ for (const localEntry of this.sessionHistory) {
6569
+ if (!serverIds.has(String(localEntry.id))) {
6570
+ merged.push(localEntry);
6571
+ }
6572
+ }
6573
+
6574
+ this.sessionHistory = merged;
6575
+ this.renderChatThread();
6576
+ this.syncUiStates();
6577
+ } catch {
6578
+ // Non-fatal when offline or using minimal synthetic endpoints
6579
+ } finally {
6580
+ this.inFlightOwnFeedbacksPromise = null;
6581
+ }
6582
+ return [...this.sessionHistory];
6583
+ })();
6584
+
6585
+ return this.inFlightOwnFeedbacksPromise;
5588
6586
  }
5589
6587
 
5590
- getConfig() {
5591
- return this.config;
6588
+ async ensureOwnFeedbacksLoaded() {
6589
+ if (this.ownFeedbacksLoaded) return;
6590
+ await this.refreshOwnFeedbacks();
5592
6591
  }
5593
6592
 
5594
- setWidgetConfig(partial ) {
5595
- const wasAgentEnabled = Boolean(this.config.agent?.enabled);
5596
- if (
5597
- typeof partial.placeholder === "string" &&
5598
- partial.placeholder !== DEFAULT_VERBOSE_PLACEHOLDER &&
5599
- partial.placeholder !== DEFAULT_SMART_PLACEHOLDER
5600
- ) {
5601
- this.customPlaceholderSet = true;
6593
+ startEditingFeedback(feedbackId ) {
6594
+ const targetKey = String(feedbackId);
6595
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
6596
+ if (!entry) return false;
6597
+
6598
+ if (this.commentingFeedbackId !== null) {
6599
+ this.cancelCommentingFeedback();
5602
6600
  }
5603
- this.config = {
5604
- ...this.config,
5605
- ...partial,
5606
- agent: { ...(this.config.agent || { enabled: false }), ...(partial.agent || {}) },
5607
- features: { ...this.config.features, ...(partial.features || {}) },
5608
- limits: { ...this.config.limits, ...(partial.limits || {}) },
5609
- privacy: { ...this.config.privacy, ...(partial.privacy || {}) }
5610
- };
5611
- if (partial.csrf_token) {
5612
- this.apiClient.setCsrfToken(partial.csrf_token);
6601
+ this.confirmingDeleteId = null;
6602
+ this.hideStatus();
6603
+
6604
+ if (this.editingFeedbackId === null && this.commentingFeedbackId === null) {
6605
+ this.stashedDraftBeforeEdit = {
6606
+ message: this.textareaEl?.value || "",
6607
+ elementReferences: [...this.elementReferences],
6608
+ elementDomNodes: new Map(this.elementDomNodes),
6609
+ attachments: [...this.attachments]
6610
+ };
5613
6611
  }
5614
- if (partial.position) {
5615
- this.setCornerPosition(partial.position);
6612
+
6613
+ this.editingFeedbackId = targetKey;
6614
+
6615
+ if (this.textareaEl) {
6616
+ this.textareaEl.value = entry.rawMessage !== undefined ? entry.rawMessage : entry.message;
5616
6617
  }
5617
- const nowAgentEnabled = Boolean(this.config.agent?.enabled);
5618
- if (nowAgentEnabled && !wasAgentEnabled) {
5619
- this.surfaceMode = "agent";
5620
- if (this.isOpen) {
5621
- void this.ensureAgentStatusLoaded();
6618
+
6619
+ this.elementReferences = structuredClone(entry.elements);
6620
+ this.elementDomNodes.clear();
6621
+ if (typeof document !== "undefined" && typeof document.querySelector === "function") {
6622
+ for (const elRef of this.elementReferences) {
6623
+ if (!elRef.selector) continue;
6624
+ try {
6625
+ const liveNode = document.querySelector(elRef.selector);
6626
+ if (liveNode) {
6627
+ this.elementDomNodes.set(elRef.client_ref, liveNode);
6628
+ }
6629
+ } catch {
6630
+ // Ignore invalid or complex selectors not resolvable on current page
6631
+ }
5622
6632
  }
5623
- } else if (!nowAgentEnabled) {
5624
- this.surfaceMode = "feedback";
5625
6633
  }
6634
+
6635
+ this.attachments = entry.attachments.map((att) => ({
6636
+ id: att.id,
6637
+ existing_attachment_id: att.server_id,
6638
+ attachment_type: att.attachment_type,
6639
+ label: att.label,
6640
+ preview_url: att.preview_url,
6641
+ signed_blob_id: att.signed_blob_id,
6642
+ data_url: att.data_url,
6643
+ filename: att.filename || att.label || "attachment.png",
6644
+ element_reference_ref: att.element_reference_ref || undefined,
6645
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
6646
+ }));
6647
+
6648
+ this.picker?.refreshPinnedMarkers();
5626
6649
  this.renderTray();
5627
6650
  this.renderChatThread();
5628
6651
  this.syncUiStates();
6652
+ this.textareaEl?.focus();
6653
+ return true;
5629
6654
  }
5630
6655
 
5631
- getSurfaceMode() {
5632
- return this.isAgentModeActive() ? "agent" : "feedback";
6656
+ cancelEditingFeedback() {
6657
+ if (this.editingFeedbackId === null) return;
6658
+ this.editingFeedbackId = null;
6659
+
6660
+ if (this.stashedDraftBeforeEdit) {
6661
+ if (this.textareaEl) {
6662
+ this.textareaEl.value = this.stashedDraftBeforeEdit.message;
6663
+ }
6664
+ this.elementReferences = this.stashedDraftBeforeEdit.elementReferences;
6665
+ this.elementDomNodes = this.stashedDraftBeforeEdit.elementDomNodes;
6666
+ this.attachments = this.stashedDraftBeforeEdit.attachments;
6667
+ this.stashedDraftBeforeEdit = null;
6668
+ } else {
6669
+ if (this.textareaEl) {
6670
+ this.textareaEl.value = "";
6671
+ }
6672
+ this.elementReferences = [];
6673
+ this.elementDomNodes.clear();
6674
+ this.attachments = [];
6675
+ }
6676
+
6677
+ this.picker?.hideExternalPreview();
6678
+ this.picker?.refreshPinnedMarkers();
6679
+ this.renderTray();
6680
+ this.renderChatThread();
6681
+ this.syncUiStates();
5633
6682
  }
5634
6683
 
5635
- setSurfaceMode(mode ) {
5636
- if (mode === "agent" && !this.config.agent?.enabled) {
5637
- return;
6684
+ startCommentingFeedback(feedbackId ) {
6685
+ const targetKey = String(feedbackId);
6686
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
6687
+ if (!entry) return false;
6688
+
6689
+ if (this.editingFeedbackId !== null) {
6690
+ this.cancelEditingFeedback();
5638
6691
  }
5639
- this.surfaceMode = mode;
5640
- if (mode === "agent" && this.isOpen) {
5641
- void this.ensureAgentStatusLoaded();
6692
+ this.confirmingDeleteId = null;
6693
+ this.hideStatus();
6694
+
6695
+ if (this.commentingFeedbackId === null && this.editingFeedbackId === null) {
6696
+ this.stashedDraftBeforeEdit = {
6697
+ message: this.textareaEl?.value || "",
6698
+ elementReferences: [...this.elementReferences],
6699
+ elementDomNodes: new Map(this.elementDomNodes),
6700
+ attachments: [...this.attachments]
6701
+ };
6702
+ }
6703
+
6704
+ this.commentingFeedbackId = targetKey;
6705
+ if (this.textareaEl) {
6706
+ this.textareaEl.value = "";
5642
6707
  }
6708
+ this.elementReferences = [];
6709
+ this.elementDomNodes.clear();
6710
+ this.attachments = [];
6711
+
6712
+ this.picker?.hideExternalPreview();
6713
+ this.picker?.refreshPinnedMarkers();
5643
6714
  this.renderTray();
5644
6715
  this.renderChatThread();
5645
6716
  this.syncUiStates();
5646
- this.focusActiveInput();
6717
+ this.textareaEl?.focus();
6718
+ return true;
5647
6719
  }
5648
6720
 
5649
- getElementReferences() {
5650
- return [...this.elementReferences];
6721
+ cancelCommentingFeedback() {
6722
+ if (this.commentingFeedbackId === null) return;
6723
+ this.commentingFeedbackId = null;
6724
+
6725
+ if (this.stashedDraftBeforeEdit) {
6726
+ if (this.textareaEl) {
6727
+ this.textareaEl.value = this.stashedDraftBeforeEdit.message;
6728
+ }
6729
+ this.elementReferences = this.stashedDraftBeforeEdit.elementReferences;
6730
+ this.elementDomNodes = this.stashedDraftBeforeEdit.elementDomNodes;
6731
+ this.attachments = this.stashedDraftBeforeEdit.attachments;
6732
+ this.stashedDraftBeforeEdit = null;
6733
+ } else {
6734
+ if (this.textareaEl) {
6735
+ this.textareaEl.value = "";
6736
+ }
6737
+ this.elementReferences = [];
6738
+ this.elementDomNodes.clear();
6739
+ this.attachments = [];
6740
+ }
6741
+
6742
+ this.renderTray();
6743
+ this.renderChatThread();
6744
+ this.syncUiStates();
5651
6745
  }
5652
6746
 
5653
- getAttachments() {
5654
- return [...this.attachments];
6747
+ async markFeedbackReviewed(feedbackId ) {
6748
+ if (this.reviewingFeedbackId !== null || this.isSubmitting) return;
6749
+ const targetKey = String(feedbackId);
6750
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
6751
+ if (!entry) return;
6752
+
6753
+ this.reviewingFeedbackId = targetKey;
6754
+ this.renderChatThread();
6755
+
6756
+ try {
6757
+ const res = await this.apiClient.updateFeedback(
6758
+ entry.id,
6759
+ { status: "reviewed" },
6760
+ entry.ownershipToken
6761
+ );
6762
+ entry.status = res?.status || "reviewed";
6763
+ if (res?.ownership_token) {
6764
+ entry.ownershipToken = res.ownership_token;
6765
+ }
6766
+ this.reviewingFeedbackId = null;
6767
+ this.renderChatThread();
6768
+ this.showStatus("Fix marked as reviewed.", "success");
6769
+ this.emitWidgetEvent("context-drop:update", { response: res, id: entry.id });
6770
+ } catch (err) {
6771
+ this.reviewingFeedbackId = null;
6772
+ this.renderChatThread();
6773
+ const msg = err instanceof Error ? err.message : "Failed to mark feedback as reviewed.";
6774
+ this.showStatus(msg, "error");
6775
+ }
5655
6776
  }
5656
6777
 
5657
- getSessionHistory() {
5658
- return [...this.sessionHistory];
6778
+ requestDeleteFeedback(feedbackId ) {
6779
+ const targetKey = String(feedbackId);
6780
+ if (!this.sessionHistory.some((item) => String(item.id) === targetKey)) return;
6781
+ this.confirmingDeleteId = this.confirmingDeleteId === targetKey ? null : targetKey;
6782
+ this.renderChatThread();
6783
+ }
6784
+
6785
+ cancelDeleteFeedback() {
6786
+ if (this.confirmingDeleteId === null) return;
6787
+ this.confirmingDeleteId = null;
6788
+ this.renderChatThread();
6789
+ }
6790
+
6791
+ async confirmDeleteFeedback(feedbackId ) {
6792
+ if (this.deletingFeedbackId !== null) return;
6793
+ const targetKey = String(feedbackId);
6794
+ const entry = this.sessionHistory.find((item) => String(item.id) === targetKey);
6795
+ if (!entry) return;
6796
+
6797
+ this.deletingFeedbackId = targetKey;
6798
+ this.renderChatThread();
6799
+
6800
+ try {
6801
+ const res = await this.apiClient.deleteFeedback(entry.id, entry.ownershipToken);
6802
+ if (this.editingFeedbackId === targetKey) {
6803
+ this.cancelEditingFeedback();
6804
+ }
6805
+ this.sessionHistory = this.sessionHistory.filter((item) => String(item.id) !== targetKey);
6806
+ this.confirmingDeleteId = null;
6807
+ this.deletingFeedbackId = null;
6808
+ this.renderChatThread();
6809
+ this.renderTray();
6810
+ this.syncUiStates();
6811
+ this.showStatus(
6812
+ this.isSmartSelectionMode() ? "Your feedback was deleted." : "Feedback deleted.",
6813
+ "success"
6814
+ );
6815
+ this.emitWidgetEvent("context-drop:delete", {
6816
+ response: res,
6817
+ id: entry.id
6818
+ });
6819
+ } catch (err) {
6820
+ this.deletingFeedbackId = null;
6821
+ this.renderChatThread();
6822
+ const msg = err instanceof Error ? err.message : "Failed to delete feedback.";
6823
+ this.showStatus(msg, "error");
6824
+ this.emitWidgetEvent("context-drop:error", {
6825
+ error: msg
6826
+ });
6827
+ }
5659
6828
  }
5660
6829
 
5661
6830
  getAgentMessages() {
@@ -5691,16 +6860,23 @@
5691
6860
  }
5692
6861
 
5693
6862
  openComposer() {
6863
+ const wasOpen = this.isOpen && !this.isMinimized;
5694
6864
  this.isOpen = true;
5695
6865
  this.isMinimized = false;
5696
6866
  if (this.isAgentModeActive()) {
5697
6867
  void this.ensureAgentStatusLoaded();
6868
+ } else {
6869
+ void this.ensureOwnFeedbacksLoaded();
5698
6870
  }
5699
6871
  this.syncUiStates();
5700
6872
  this.focusActiveInput();
6873
+ if (!wasOpen) {
6874
+ this.emitWidgetEvent("context-drop:open", { open: true });
6875
+ }
5701
6876
  }
5702
6877
 
5703
6878
  closeComposer() {
6879
+ const wasOpen = this.isOpen;
5704
6880
  this.isOpen = false;
5705
6881
  this.isMinimized = false;
5706
6882
  if (this.picker && this.picker.isActive()) {
@@ -5708,6 +6884,9 @@
5708
6884
  }
5709
6885
  this.picker?.hideExternalPreview();
5710
6886
  this.syncUiStates();
6887
+ if (wasOpen) {
6888
+ this.emitWidgetEvent("context-drop:close", { open: false });
6889
+ }
5711
6890
  }
5712
6891
 
5713
6892
  toggleComposer() {
@@ -5968,7 +7147,15 @@
5968
7147
 
5969
7148
  readDataAttributes() {
5970
7149
  const endpoint = this.getAttribute("data-endpoint") || "/context_drop";
5971
- this.apiClient = new ContextDropApiClient(endpoint);
7150
+ const rawCredentials = this.getAttribute("data-credentials");
7151
+ const credentials =
7152
+ rawCredentials === "include" || rawCredentials === "omit" || rawCredentials === "same-origin"
7153
+ ? rawCredentials
7154
+ : "same-origin";
7155
+ this.apiClient = new ContextDropApiClient(endpoint, {
7156
+ credentials,
7157
+ headers: this.customHeaders
7158
+ });
5972
7159
 
5973
7160
  const rawConfig = this.getAttribute("data-config");
5974
7161
  if (rawConfig) {
@@ -6024,6 +7211,16 @@
6024
7211
  if (themeOverride === "dark" || themeOverride === "light") {
6025
7212
  this.currentTheme = themeOverride;
6026
7213
  }
7214
+
7215
+ const selectionModeOverride = this.getAttribute("data-selection-mode") ;
7216
+ if (selectionModeOverride === "smart" || selectionModeOverride === "verbose") {
7217
+ this.config.features.selection_mode = selectionModeOverride;
7218
+ }
7219
+
7220
+ const envOverride = this.getAttribute("data-environment");
7221
+ if (envOverride && envOverride.trim().length > 0) {
7222
+ this.config.environment = envOverride.trim();
7223
+ }
6027
7224
  }
6028
7225
 
6029
7226
  detectViewportSnapCorner(
@@ -6685,6 +7882,31 @@
6685
7882
  const promptShell = document.createElement("div");
6686
7883
  promptShell.className = "cd-prompt-shell";
6687
7884
 
7885
+ const editBanner = document.createElement("div");
7886
+ editBanner.className = "cd-edit-banner";
7887
+ editBanner.hidden = true;
7888
+
7889
+ const editBannerInfo = document.createElement("span");
7890
+ editBannerInfo.className = "cd-edit-banner-info";
7891
+ this.editBannerInfoEl = editBannerInfo;
7892
+ editBanner.appendChild(editBannerInfo);
7893
+
7894
+ const cancelEditBtn = document.createElement("button");
7895
+ cancelEditBtn.type = "button";
7896
+ cancelEditBtn.className = "cd-btn cd-btn-xs";
7897
+ cancelEditBtn.setAttribute("aria-label", "Cancel editing feedback");
7898
+ cancelEditBtn.textContent = "Cancel";
7899
+ cancelEditBtn.addEventListener("click", () => {
7900
+ if (this.commentingFeedbackId !== null) {
7901
+ this.cancelCommentingFeedback();
7902
+ } else {
7903
+ this.cancelEditingFeedback();
7904
+ }
7905
+ });
7906
+ editBanner.appendChild(cancelEditBtn);
7907
+ this.editBannerEl = editBanner;
7908
+ promptShell.appendChild(editBanner);
7909
+
6688
7910
  const textarea = document.createElement("textarea");
6689
7911
  textarea.className = "cd-textarea";
6690
7912
  textarea.placeholder = this.config.placeholder;
@@ -6694,8 +7916,17 @@
6694
7916
  ev.preventDefault();
6695
7917
  void this.handleSubmit();
6696
7918
  } else if (ev.key === "Escape") {
7919
+ if (ev.defaultPrevented) return;
6697
7920
  ev.preventDefault();
6698
- this.closeComposer();
7921
+ if (this.confirmingDeleteId !== null) {
7922
+ this.cancelDeleteFeedback();
7923
+ } else if (this.commentingFeedbackId !== null) {
7924
+ this.cancelCommentingFeedback();
7925
+ } else if (this.editingFeedbackId !== null) {
7926
+ this.cancelEditingFeedback();
7927
+ } else {
7928
+ this.closeComposer();
7929
+ }
6699
7930
  }
6700
7931
  });
6701
7932
  textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
@@ -6923,7 +8154,6 @@
6923
8154
  providerPill.appendChild(keyDot);
6924
8155
  providerPill.appendChild(providerLabel);
6925
8156
  providerPill.addEventListener("click", () => this.toggleByokDrawer());
6926
- this.providerPillBtn = providerPill;
6927
8157
 
6928
8158
  const subbarRight = document.createElement("div");
6929
8159
  subbarRight.className = "cd-subbar-right";
@@ -7951,12 +9181,21 @@
7951
9181
  if (this.composerModeSwitchWrap) {
7952
9182
  this.composerModeSwitchWrap.hidden = !this.config.agent?.enabled;
7953
9183
  }
7954
- if (this.textareaEl && !this.customPlaceholderSet) {
7955
- this.textareaEl.placeholder = smartMode
7956
- ? DEFAULT_SMART_PLACEHOLDER
7957
- : DEFAULT_VERBOSE_PLACEHOLDER;
9184
+ const isCommenting = this.commentingFeedbackId !== null;
9185
+ if (this.textareaEl) {
9186
+ if (isCommenting) {
9187
+ this.textareaEl.placeholder = "Write a comment... (attach or paste images below)";
9188
+ } else if (!this.customPlaceholderSet) {
9189
+ this.textareaEl.placeholder = smartMode
9190
+ ? DEFAULT_SMART_PLACEHOLDER
9191
+ : DEFAULT_VERBOSE_PLACEHOLDER;
9192
+ }
9193
+ }
9194
+ if (this.cornerPinBtn) {
9195
+ this.cornerPinBtn.hidden = isCommenting;
7958
9196
  }
7959
9197
  if (this.composerToolbarPickBtn) {
9198
+ this.composerToolbarPickBtn.hidden = isCommenting;
7960
9199
  if (smartMode) {
7961
9200
  this.composerToolbarPickBtn.title = "Highlight an area on the page";
7962
9201
  this.composerToolbarPickBtn.setAttribute("aria-label", "Highlight an area on the page");
@@ -7971,13 +9210,60 @@
7971
9210
  }
7972
9211
  }
7973
9212
  if (this.composerToolbarScreenshotBtn) {
7974
- this.composerToolbarScreenshotBtn.hidden = smartMode;
9213
+ this.composerToolbarScreenshotBtn.hidden = smartMode && !isCommenting;
7975
9214
  }
7976
9215
  if (this.composerToolbarUploadBtn) {
7977
9216
  this.composerToolbarUploadBtn.innerHTML = smartMode
7978
9217
  ? `${ICON_IMAGE}<span>Add image</span>`
7979
9218
  : `${ICON_IMAGE}<span>Image</span>`;
7980
9219
  }
9220
+ if (this.editBannerEl && this.editBannerInfoEl) {
9221
+ if (this.editingFeedbackId !== null) {
9222
+ this.editBannerEl.hidden = false;
9223
+ this.editBannerInfoEl.innerHTML = "";
9224
+ const iconSpan = document.createElement("span");
9225
+ iconSpan.innerHTML = ICON_EDIT;
9226
+ const labelSpan = document.createElement("span");
9227
+ labelSpan.textContent = smartMode ? "Editing your feedback" : "Editing feedback";
9228
+ this.editBannerInfoEl.appendChild(iconSpan);
9229
+ this.editBannerInfoEl.appendChild(labelSpan);
9230
+ if (!smartMode) {
9231
+ const idSpan = document.createElement("span");
9232
+ idSpan.className = "cd-edit-banner-id";
9233
+ idSpan.textContent = `#${this.editingFeedbackId}`;
9234
+ this.editBannerInfoEl.appendChild(idSpan);
9235
+ }
9236
+ } else if (this.commentingFeedbackId !== null) {
9237
+ this.editBannerEl.hidden = false;
9238
+ this.editBannerInfoEl.innerHTML = "";
9239
+ const iconSpan = document.createElement("span");
9240
+ iconSpan.innerHTML = ICON_COMMENT;
9241
+ const labelSpan = document.createElement("span");
9242
+ labelSpan.textContent = smartMode ? "Commenting on feedback" : "Commenting on";
9243
+ this.editBannerInfoEl.appendChild(iconSpan);
9244
+ this.editBannerInfoEl.appendChild(labelSpan);
9245
+ if (!smartMode) {
9246
+ const idSpan = document.createElement("span");
9247
+ idSpan.className = "cd-edit-banner-id";
9248
+ idSpan.textContent = `#${this.commentingFeedbackId}`;
9249
+ this.editBannerInfoEl.appendChild(idSpan);
9250
+ }
9251
+ } else {
9252
+ this.editBannerEl.hidden = true;
9253
+ }
9254
+ }
9255
+ if (this.submitBtn && !this.isSubmitting) {
9256
+ if (this.editingFeedbackId !== null) {
9257
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
9258
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
9259
+ } else if (this.commentingFeedbackId !== null) {
9260
+ this.submitBtn.setAttribute("aria-label", "Submit comment");
9261
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Comment</span>`;
9262
+ } else {
9263
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
9264
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
9265
+ }
9266
+ }
7981
9267
 
7982
9268
  if (this.agentSidebarEl) {
7983
9269
  this.agentSidebarEl.hidden = !showAgentSidebar;
@@ -8213,8 +9499,21 @@
8213
9499
  this.chatThreadEl.hidden = false;
8214
9500
 
8215
9501
  for (const entry of this.sessionHistory) {
9502
+ const entryIdStr = String(entry.id);
9503
+ const isEditingThis = this.editingFeedbackId === entryIdStr;
9504
+ const isCommentingThis = this.commentingFeedbackId === entryIdStr;
9505
+ const isReviewingThis = this.reviewingFeedbackId === entryIdStr;
9506
+ const isConfirmingDelete = this.confirmingDeleteId === entryIdStr;
9507
+ const isDeletingThis = this.deletingFeedbackId === entryIdStr;
9508
+ const statusName = entry.status || "new";
9509
+
8216
9510
  const msgCard = document.createElement("div");
8217
- msgCard.className = "cd-chat-msg";
9511
+ msgCard.className = isEditingThis
9512
+ ? "cd-chat-msg is-editing"
9513
+ : isCommentingThis
9514
+ ? "cd-chat-msg is-commenting"
9515
+ : "cd-chat-msg";
9516
+ msgCard.setAttribute("data-feedback-id", entryIdStr);
8218
9517
 
8219
9518
  if (entry.elements.length > 0 || entry.attachments.length > 0) {
8220
9519
  const pills = document.createElement("div");
@@ -8247,16 +9546,192 @@
8247
9546
  msgCard.appendChild(textP);
8248
9547
  }
8249
9548
 
9549
+ if (entry.comments && entry.comments.length > 0) {
9550
+ const commentsList = document.createElement("div");
9551
+ commentsList.className = "cd-comments-list";
9552
+ for (const comment of entry.comments) {
9553
+ const cItem = document.createElement("div");
9554
+ cItem.className = "cd-comment-item";
9555
+
9556
+ const cHeader = document.createElement("div");
9557
+ cHeader.className = "cd-comment-header";
9558
+ const cAuthor = document.createElement("span");
9559
+ cAuthor.className = "cd-comment-author";
9560
+ cAuthor.textContent = comment.author_label || "You";
9561
+ const cTime = document.createElement("span");
9562
+ cTime.textContent = comment.createdAt;
9563
+ cHeader.appendChild(cAuthor);
9564
+ cHeader.appendChild(cTime);
9565
+ cItem.appendChild(cHeader);
9566
+
9567
+ if (comment.body) {
9568
+ const cBody = document.createElement("p");
9569
+ cBody.className = "cd-comment-body";
9570
+ cBody.textContent = comment.body;
9571
+ cItem.appendChild(cBody);
9572
+ }
9573
+
9574
+ if (comment.attachments && comment.attachments.length > 0) {
9575
+ const cImgs = document.createElement("div");
9576
+ cImgs.className = "cd-comment-images";
9577
+ for (const att of comment.attachments) {
9578
+ if (att.preview_url) {
9579
+ const imgLink = document.createElement("a");
9580
+ imgLink.href = att.preview_url;
9581
+ imgLink.target = "_blank";
9582
+ imgLink.rel = "noopener noreferrer";
9583
+ const img = document.createElement("img");
9584
+ img.src = att.preview_url;
9585
+ img.alt = att.label || "Comment image";
9586
+ img.className = "cd-comment-thumb";
9587
+ imgLink.appendChild(img);
9588
+ cImgs.appendChild(imgLink);
9589
+ }
9590
+ }
9591
+ if (cImgs.childNodes.length > 0) {
9592
+ cItem.appendChild(cImgs);
9593
+ }
9594
+ }
9595
+
9596
+ commentsList.appendChild(cItem);
9597
+ }
9598
+ msgCard.appendChild(commentsList);
9599
+ }
9600
+
8250
9601
  const meta = document.createElement("div");
8251
9602
  meta.className = "cd-chat-msg-meta";
9603
+
9604
+ const metaInfo = document.createElement("div");
9605
+ metaInfo.className = "cd-chat-msg-meta-info";
9606
+
9607
+ const statusBadge = document.createElement("span");
9608
+ statusBadge.className = `cd-msg-status-badge is-${statusName}`;
9609
+ statusBadge.textContent = statusName;
9610
+
8252
9611
  const idSpan = document.createElement("span");
8253
- idSpan.textContent = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
9612
+ const baseLabel = smartMode ? "Feedback sent" : `Dropped #${entry.id}`;
9613
+ idSpan.textContent = entry.isEdited ? `${baseLabel} · edited` : baseLabel;
9614
+
9615
+ const sepSpan = document.createElement("span");
9616
+ sepSpan.setAttribute("aria-hidden", "true");
9617
+ sepSpan.textContent = "·";
9618
+
8254
9619
  const timeSpan = document.createElement("span");
8255
9620
  timeSpan.textContent = entry.createdAt;
8256
- meta.appendChild(idSpan);
8257
- meta.appendChild(timeSpan);
9621
+
9622
+ metaInfo.appendChild(statusBadge);
9623
+ metaInfo.appendChild(idSpan);
9624
+ metaInfo.appendChild(sepSpan);
9625
+ metaInfo.appendChild(timeSpan);
9626
+
9627
+ const actions = document.createElement("div");
9628
+ actions.className = "cd-chat-msg-actions";
9629
+
9630
+ if (statusName === "fixed") {
9631
+ const reviewBtn = document.createElement("button");
9632
+ reviewBtn.type = "button";
9633
+ reviewBtn.className = "cd-review-btn";
9634
+ reviewBtn.title = "Confirm fix was tested and reviewed";
9635
+ reviewBtn.setAttribute("aria-label", "Mark fix as reviewed");
9636
+ reviewBtn.disabled = isReviewingThis || this.isSubmitting || this.deletingFeedbackId !== null;
9637
+ reviewBtn.innerHTML = `${ICON_CHECK}<span>${isReviewingThis ? "Saving..." : "Mark Reviewed"}</span>`;
9638
+ reviewBtn.addEventListener("click", () => {
9639
+ void this.markFeedbackReviewed(entry.id);
9640
+ });
9641
+ actions.appendChild(reviewBtn);
9642
+ }
9643
+
9644
+ const commentBtn = document.createElement("button");
9645
+ commentBtn.type = "button";
9646
+ commentBtn.className = `cd-msg-action-btn${isCommentingThis ? " is-active" : ""}`;
9647
+ commentBtn.title = isCommentingThis ? "Cancel comment" : "Add comment";
9648
+ commentBtn.setAttribute("aria-label", "Add comment");
9649
+ commentBtn.setAttribute("aria-pressed", String(isCommentingThis));
9650
+ commentBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
9651
+ commentBtn.innerHTML = ICON_COMMENT;
9652
+ commentBtn.addEventListener("click", () => {
9653
+ if (this.commentingFeedbackId === entryIdStr) {
9654
+ this.cancelCommentingFeedback();
9655
+ } else {
9656
+ this.startCommentingFeedback(entry.id);
9657
+ }
9658
+ });
9659
+
9660
+ const editBtn = document.createElement("button");
9661
+ editBtn.type = "button";
9662
+ editBtn.className = `cd-msg-action-btn${isEditingThis ? " is-active" : ""}`;
9663
+ editBtn.title = isEditingThis ? "Cancel editing" : "Edit feedback";
9664
+ editBtn.setAttribute("aria-label", "Edit feedback");
9665
+ editBtn.setAttribute("aria-pressed", String(isEditingThis));
9666
+ editBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
9667
+ editBtn.innerHTML = ICON_EDIT;
9668
+ editBtn.addEventListener("click", () => {
9669
+ if (this.editingFeedbackId === entryIdStr) {
9670
+ this.cancelEditingFeedback();
9671
+ } else {
9672
+ this.startEditingFeedback(entry.id);
9673
+ }
9674
+ });
9675
+
9676
+ const deleteBtn = document.createElement("button");
9677
+ deleteBtn.type = "button";
9678
+ deleteBtn.className = "cd-msg-action-btn is-danger";
9679
+ deleteBtn.title = "Delete feedback";
9680
+ deleteBtn.setAttribute("aria-label", "Delete feedback");
9681
+ deleteBtn.disabled = this.isSubmitting || this.deletingFeedbackId !== null;
9682
+ deleteBtn.innerHTML = ICON_TRASH;
9683
+ deleteBtn.addEventListener("click", () => {
9684
+ this.requestDeleteFeedback(entry.id);
9685
+ });
9686
+
9687
+ actions.appendChild(commentBtn);
9688
+ actions.appendChild(editBtn);
9689
+ actions.appendChild(deleteBtn);
9690
+
9691
+ meta.appendChild(metaInfo);
9692
+ meta.appendChild(actions);
8258
9693
  msgCard.appendChild(meta);
8259
9694
 
9695
+ if (isConfirmingDelete) {
9696
+ const confirmBar = document.createElement("div");
9697
+ confirmBar.className = "cd-msg-delete-confirm";
9698
+ confirmBar.setAttribute("role", "group");
9699
+ confirmBar.setAttribute("aria-label", "Confirm feedback deletion");
9700
+
9701
+ const confirmLabel = document.createElement("span");
9702
+ confirmLabel.className = "cd-msg-delete-label";
9703
+ confirmLabel.textContent = "Delete this feedback?";
9704
+
9705
+ const btnGroup = document.createElement("div");
9706
+ btnGroup.className = "cd-msg-delete-btns";
9707
+
9708
+ const cancelDeleteBtn = document.createElement("button");
9709
+ cancelDeleteBtn.type = "button";
9710
+ cancelDeleteBtn.className = "cd-btn cd-btn-xs";
9711
+ cancelDeleteBtn.setAttribute("aria-label", "Cancel delete");
9712
+ cancelDeleteBtn.disabled = isDeletingThis;
9713
+ cancelDeleteBtn.textContent = "Cancel";
9714
+ cancelDeleteBtn.addEventListener("click", () => {
9715
+ this.cancelDeleteFeedback();
9716
+ });
9717
+
9718
+ const confirmDeleteBtn = document.createElement("button");
9719
+ confirmDeleteBtn.type = "button";
9720
+ confirmDeleteBtn.className = "cd-btn cd-btn-xs cd-btn-danger";
9721
+ confirmDeleteBtn.setAttribute("aria-label", "Confirm delete feedback");
9722
+ confirmDeleteBtn.disabled = isDeletingThis;
9723
+ confirmDeleteBtn.textContent = isDeletingThis ? "Deleting..." : "Delete";
9724
+ confirmDeleteBtn.addEventListener("click", () => {
9725
+ void this.confirmDeleteFeedback(entry.id);
9726
+ });
9727
+
9728
+ btnGroup.appendChild(cancelDeleteBtn);
9729
+ btnGroup.appendChild(confirmDeleteBtn);
9730
+ confirmBar.appendChild(confirmLabel);
9731
+ confirmBar.appendChild(btnGroup);
9732
+ msgCard.appendChild(confirmBar);
9733
+ }
9734
+
8260
9735
  this.chatThreadEl.appendChild(msgCard);
8261
9736
  }
8262
9737
 
@@ -8645,13 +10120,20 @@
8645
10120
  async handleSubmit() {
8646
10121
  if (this.isSubmitting) return;
8647
10122
  const smartMode = this.isSmartSelectionMode();
10123
+ const editingId = this.editingFeedbackId;
10124
+ const commentingId = this.commentingFeedbackId;
8648
10125
 
8649
10126
  if (this.pendingSmartCaptures.size > 0) {
8650
10127
  await Promise.allSettled(Array.from(this.pendingSmartCaptures));
8651
10128
  }
8652
10129
 
8653
10130
  const message = (this.textareaEl?.value || "").trim();
8654
- if (
10131
+ if (commentingId !== null) {
10132
+ if (message.length === 0 && this.attachments.length === 0) {
10133
+ this.showStatus("Write a comment or attach an image first.", "error");
10134
+ return;
10135
+ }
10136
+ } else if (
8655
10137
  message.length === 0 &&
8656
10138
  this.attachments.length === 0 &&
8657
10139
  this.elementReferences.length === 0
@@ -8668,32 +10150,173 @@
8668
10150
  this.isSubmitting = true;
8669
10151
  if (this.submitBtn) {
8670
10152
  this.submitBtn.disabled = true;
8671
- this.submitBtn.innerHTML = `<span>Sending...</span>`;
10153
+ this.submitBtn.innerHTML =
10154
+ editingId !== null
10155
+ ? `<span>Saving...</span>`
10156
+ : commentingId !== null
10157
+ ? `<span>Posting...</span>`
10158
+ : `<span>Sending...</span>`;
8672
10159
  }
8673
10160
 
8674
10161
  try {
8675
- const submittedElements = [...this.elementReferences];
8676
- const submittedAttachments = this.attachments.map((att) => ({
10162
+ const submittedElements = structuredClone(this.elementReferences);
10163
+ const submittedAttachments = this.attachments.map((att) => ({
8677
10164
  id: att.id,
10165
+ server_id: att.existing_attachment_id,
8678
10166
  label: att.label,
8679
10167
  preview_url: att.preview_url,
8680
- attachment_type: att.attachment_type
10168
+ attachment_type: att.attachment_type,
10169
+ filename: att.filename,
10170
+ signed_blob_id: att.signed_blob_id,
10171
+ data_url: att.data_url,
10172
+ element_reference_ref: att.element_reference_ref || null,
10173
+ metadata: att.metadata ? structuredClone(att.metadata) : {}
8681
10174
  }));
8682
10175
 
10176
+ const commonMetadata = {
10177
+ ...this.customMetadata,
10178
+ environment: this.config.environment,
10179
+ selection_mode: smartMode ? "smart" : "verbose",
10180
+ viewport: {
10181
+ width: typeof window !== "undefined" ? window.innerWidth : 0,
10182
+ height: typeof window !== "undefined" ? window.innerHeight : 0
10183
+ },
10184
+ locale: typeof navigator !== "undefined" ? navigator.language : "en"
10185
+ };
10186
+
10187
+ if (commentingId !== null) {
10188
+ const existingIdx = this.sessionHistory.findIndex(
10189
+ (item) => String(item.id) === commentingId
10190
+ );
10191
+ const existingEntry = existingIdx >= 0 ? this.sessionHistory[existingIdx] : undefined;
10192
+
10193
+ const commentPayload = {
10194
+ body: message,
10195
+ attachments: this.attachments.map((att) => ({
10196
+ attachment_type: att.attachment_type,
10197
+ filename: att.filename,
10198
+ signed_blob_id: att.signed_blob_id,
10199
+ data_url: att.signed_blob_id ? undefined : att.data_url,
10200
+ metadata: att.metadata
10201
+ }))
10202
+ };
10203
+
10204
+ const commentRes = await this.apiClient.createComment(
10205
+ existingEntry?.id ?? commentingId,
10206
+ commentPayload,
10207
+ existingEntry?.ownershipToken
10208
+ );
10209
+
10210
+ if (commentRes?.feedback) {
10211
+ const updatedEntry = this.mapOwnRecordToSessionEntry(commentRes.feedback, existingEntry);
10212
+ if (existingIdx >= 0) {
10213
+ this.sessionHistory[existingIdx] = updatedEntry;
10214
+ }
10215
+ } else if (existingEntry) {
10216
+ existingEntry.status = commentRes?.status || "updated";
10217
+ if (!existingEntry.comments) existingEntry.comments = [];
10218
+ existingEntry.comments.push({
10219
+ id: commentRes?.id ?? Date.now(),
10220
+ author_label: commentRes?.comment?.author_label || "You",
10221
+ body: message || null,
10222
+ createdAt: this.formatTimestampLabel(commentRes?.created_at),
10223
+ attachments: submittedAttachments
10224
+ });
10225
+ }
10226
+
10227
+ this.cancelCommentingFeedback();
10228
+ this.showStatus("Comment added.", "success");
10229
+ this.emitWidgetEvent("context-drop:comment", {
10230
+ response: commentRes,
10231
+ payload: commentPayload
10232
+ });
10233
+ return;
10234
+ }
10235
+
10236
+ if (editingId !== null) {
10237
+ const existingIdx = this.sessionHistory.findIndex(
10238
+ (item) => String(item.id) === editingId
10239
+ );
10240
+ const existingEntry = existingIdx >= 0 ? this.sessionHistory[existingIdx] : undefined;
10241
+
10242
+ const updatePayload = {
10243
+ message,
10244
+ metadata: commonMetadata,
10245
+ element_references: this.elementReferences,
10246
+ attachments: this.attachments.map((att) => {
10247
+ if (att.existing_attachment_id !== undefined && att.existing_attachment_id !== null) {
10248
+ return {
10249
+ existing_id: att.existing_attachment_id,
10250
+ attachment_type: att.attachment_type,
10251
+ element_reference_ref: att.element_reference_ref,
10252
+ metadata: att.metadata
10253
+ };
10254
+ }
10255
+ return {
10256
+ attachment_type: att.attachment_type,
10257
+ filename: att.filename,
10258
+ signed_blob_id: att.signed_blob_id,
10259
+ data_url: att.signed_blob_id ? undefined : att.data_url,
10260
+ element_reference_ref: att.element_reference_ref,
10261
+ metadata: att.metadata
10262
+ };
10263
+ })
10264
+ };
10265
+
10266
+ const updateRes = await this.apiClient.updateFeedback(
10267
+ existingEntry?.id ?? editingId,
10268
+ updatePayload,
10269
+ existingEntry?.ownershipToken
10270
+ );
10271
+
10272
+ const mergedPreviewStub = {
10273
+ id: existingEntry?.id ?? updateRes?.id ?? editingId,
10274
+ message:
10275
+ message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
10276
+ rawMessage: message,
10277
+ createdAt: existingEntry?.createdAt || this.formatTimestampLabel(updateRes?.created_at),
10278
+ rawCreatedAt: existingEntry?.rawCreatedAt || updateRes?.created_at,
10279
+ rawUpdatedAt: updateRes?.updated_at || new Date().toISOString(),
10280
+ isEdited: true,
10281
+ status: updateRes?.status || existingEntry?.status,
10282
+ ownershipToken:
10283
+ updateRes?.ownership_token ||
10284
+ updateRes?.feedback?.ownership_token ||
10285
+ existingEntry?.ownershipToken,
10286
+ elements: submittedElements,
10287
+ attachments: submittedAttachments
10288
+ };
10289
+
10290
+ const updatedEntry = updateRes?.feedback
10291
+ ? {
10292
+ ...this.mapOwnRecordToSessionEntry(updateRes.feedback, mergedPreviewStub),
10293
+ isEdited: true
10294
+ }
10295
+ : mergedPreviewStub;
10296
+
10297
+ if (existingIdx >= 0) {
10298
+ this.sessionHistory[existingIdx] = updatedEntry;
10299
+ } else {
10300
+ this.sessionHistory.push(updatedEntry);
10301
+ }
10302
+
10303
+ this.cancelEditingFeedback();
10304
+ this.showStatus(
10305
+ smartMode ? "Your feedback was updated." : "Feedback updated.",
10306
+ "success"
10307
+ );
10308
+ this.emitWidgetEvent("context-drop:update", {
10309
+ response: updateRes,
10310
+ payload: updatePayload
10311
+ });
10312
+ return;
10313
+ }
10314
+
8683
10315
  const payload = {
8684
10316
  message,
8685
10317
  page_url: typeof window !== "undefined" ? window.location.href : "/",
8686
10318
  user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
8687
- metadata: {
8688
- ...this.customMetadata,
8689
- environment: this.config.environment,
8690
- selection_mode: smartMode ? "smart" : "verbose",
8691
- viewport: {
8692
- width: typeof window !== "undefined" ? window.innerWidth : 0,
8693
- height: typeof window !== "undefined" ? window.innerHeight : 0
8694
- },
8695
- locale: typeof navigator !== "undefined" ? navigator.language : "en"
8696
- },
10319
+ metadata: commonMetadata,
8697
10320
  element_references: this.elementReferences,
8698
10321
  attachments: this.attachments.map((att) => ({
8699
10322
  attachment_type: att.attachment_type,
@@ -8709,14 +10332,26 @@
8709
10332
 
8710
10333
  const now = new Date();
8711
10334
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
8712
- this.sessionHistory.push({
10335
+ const localStub = {
8713
10336
  id: res?.id ?? this.sessionHistory.length + 1,
8714
10337
  message:
8715
10338
  message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
10339
+ rawMessage: message,
8716
10340
  createdAt: timeLabel,
10341
+ rawCreatedAt: res?.created_at,
10342
+ rawUpdatedAt: res?.updated_at || res?.created_at,
10343
+ isEdited: false,
10344
+ status: res?.status,
10345
+ ownershipToken: res?.ownership_token || res?.feedback?.ownership_token,
8717
10346
  elements: submittedElements,
8718
10347
  attachments: submittedAttachments
8719
- });
10348
+ };
10349
+
10350
+ const createdEntry = res?.feedback
10351
+ ? this.mapOwnRecordToSessionEntry(res.feedback, localStub)
10352
+ : localStub;
10353
+
10354
+ this.sessionHistory.push(createdEntry);
8720
10355
 
8721
10356
  if (this.textareaEl) {
8722
10357
  this.textareaEl.value = "";
@@ -8732,15 +10367,34 @@
8732
10367
  smartMode ? "Thanks! Your feedback was sent." : "Context drop saved.",
8733
10368
  "success"
8734
10369
  );
10370
+ this.emitWidgetEvent("context-drop:submit", {
10371
+ response: res,
10372
+ payload
10373
+ });
8735
10374
  } catch (err) {
8736
- const msg = err instanceof Error ? err.message : "Failed to submit feedback.";
10375
+ const msg =
10376
+ err instanceof Error
10377
+ ? err.message
10378
+ : editingId !== null
10379
+ ? "Failed to update feedback."
10380
+ : "Failed to submit feedback.";
8737
10381
  this.showStatus(msg, "error");
10382
+ this.emitWidgetEvent("context-drop:error", {
10383
+ error: msg
10384
+ });
8738
10385
  } finally {
8739
10386
  this.isSubmitting = false;
8740
10387
  if (this.submitBtn) {
8741
10388
  this.submitBtn.disabled = false;
8742
- this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
10389
+ if (this.editingFeedbackId !== null) {
10390
+ this.submitBtn.setAttribute("aria-label", "Save feedback changes");
10391
+ this.submitBtn.innerHTML = `${ICON_CHECK}<span>Save</span>`;
10392
+ } else {
10393
+ this.submitBtn.setAttribute("aria-label", "Submit feedback");
10394
+ this.submitBtn.innerHTML = `${ICON_SEND}<span>Send</span>`;
10395
+ }
8743
10396
  }
10397
+ this.renderChatThread();
8744
10398
  }
8745
10399
  }
8746
10400