context_drop 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +149 -12
  3. data/Rakefile +110 -1
  4. data/app/assets/javascripts/context_drop/context_drop.js +1230 -53
  5. data/app/controllers/context_drop/application_controller.rb +52 -3
  6. data/app/controllers/context_drop/configs_controller.rb +10 -1
  7. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  8. data/app/controllers/context_drop/feedbacks_controller.rb +383 -17
  9. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  10. data/app/javascript/context_drop/__tests__/widget.test.ts +355 -1
  11. data/app/javascript/context_drop/api-client.ts +306 -22
  12. data/app/javascript/context_drop/element-picker.ts +1 -1
  13. data/app/javascript/context_drop/icons.ts +4 -0
  14. data/app/javascript/context_drop/screenshot.ts +1 -1
  15. data/app/javascript/context_drop/styles.ts +181 -0
  16. data/app/javascript/context_drop/types.ts +96 -6
  17. data/app/javascript/context_drop/widget.ts +752 -29
  18. data/app/models/context_drop/feedback.rb +65 -8
  19. data/app/services/context_drop/ownership_token.rb +114 -0
  20. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +8 -0
  21. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +9 -0
  22. data/app/views/layouts/context_drop/application.html.erb +5 -0
  23. data/config/routes.rb +11 -0
  24. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  25. data/lib/context_drop/configuration.rb +26 -0
  26. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +3 -1
  27. data/lib/context_drop/mcp/tools/get_feedback.rb +16 -5
  28. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +3 -0
  29. data/lib/context_drop/mcp/tools/list_feedbacks.rb +22 -2
  30. data/lib/context_drop/mcp/tools/update_feedback_status.rb +3 -1
  31. data/lib/context_drop/version.rb +1 -1
  32. metadata +4 -2
@@ -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,13 +3230,72 @@
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 ;
3251
+ credentials ;
3252
+ customHeaders ;
3052
3253
  cachedCsrfToken = null;
3254
+ configFetched = false;
3053
3255
  inFlightConfigPromise = null;
3256
+ memoryOwnershipTokens = new Map();
3054
3257
 
3055
- constructor(baseUrl = "/context_drop") {
3258
+ constructor(baseUrl = "/context_drop", options = {}) {
3056
3259
  this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
3260
+ this.credentials = options.credentials || "same-origin";
3261
+ this.customHeaders = options.headers ? { ...options.headers } : {};
3262
+ }
3263
+
3264
+ getBaseUrl() {
3265
+ return this.baseUrl;
3266
+ }
3267
+
3268
+ setCredentials(credentials ) {
3269
+ this.credentials = credentials;
3270
+ }
3271
+
3272
+ setHeaders(headers ) {
3273
+ this.customHeaders = { ...headers };
3274
+ }
3275
+
3276
+ isCrossOriginEndpoint() {
3277
+ if (!/^https?:\/\//i.test(this.baseUrl)) {
3278
+ return false;
3279
+ }
3280
+ if (typeof window === "undefined" || !window.location || !window.location.origin) {
3281
+ return true;
3282
+ }
3283
+ try {
3284
+ return new URL(this.baseUrl, window.location.origin).origin !== window.location.origin;
3285
+ } catch {
3286
+ return false;
3287
+ }
3288
+ }
3289
+
3290
+ mergeClientHeaders(base ) {
3291
+ const merged = {
3292
+ ...this.customHeaders,
3293
+ ...base
3294
+ };
3295
+ if (this.isCrossOriginEndpoint()) {
3296
+ merged["X-Context-Drop-Client"] = "1";
3297
+ }
3298
+ return merged;
3057
3299
  }
3058
3300
 
3059
3301
  getCsrfToken() {
@@ -3084,10 +3326,10 @@
3084
3326
  try {
3085
3327
  const response = await fetch(`${this.baseUrl}/config`, {
3086
3328
  method: "GET",
3087
- credentials: "same-origin",
3088
- headers: {
3329
+ credentials: this.credentials,
3330
+ headers: this.mergeClientHeaders({
3089
3331
  Accept: "application/json"
3090
- }
3332
+ })
3091
3333
  });
3092
3334
 
3093
3335
  if (!response.ok) {
@@ -3095,6 +3337,7 @@
3095
3337
  }
3096
3338
 
3097
3339
  const config = (await response.json()) ;
3340
+ this.configFetched = true;
3098
3341
  if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
3099
3342
  this.cachedCsrfToken = config.csrf_token.trim();
3100
3343
  if (typeof document !== "undefined") {
@@ -3122,6 +3365,9 @@
3122
3365
  if (this.cachedCsrfToken) {
3123
3366
  return this.cachedCsrfToken;
3124
3367
  }
3368
+ if (this.configFetched) {
3369
+ return null;
3370
+ }
3125
3371
  }
3126
3372
 
3127
3373
  try {
@@ -3166,7 +3412,8 @@
3166
3412
 
3167
3413
  const errorMessage = parsedError || rawText || "";
3168
3414
  const shouldRetryCsrf =
3169
- this.isCsrfError(response.status, errorMessage) || (!csrfToken && response.status === 422);
3415
+ this.isCsrfError(response.status, errorMessage) ||
3416
+ (!csrfToken && !this.configFetched && response.status === 422);
3170
3417
 
3171
3418
  if (shouldRetryCsrf) {
3172
3419
  csrfToken = await this.resolveCsrfToken(true);
@@ -3197,7 +3444,7 @@
3197
3444
  if (csrfToken) {
3198
3445
  headers["X-CSRF-Token"] = csrfToken;
3199
3446
  }
3200
- return headers;
3447
+ return this.mergeClientHeaders(headers);
3201
3448
  }
3202
3449
 
3203
3450
  async uploadAttachment(file , filename ) {
@@ -3214,8 +3461,8 @@
3214
3461
 
3215
3462
  return fetch(`${this.baseUrl}/attachments`, {
3216
3463
  method: "POST",
3217
- credentials: "same-origin",
3218
- headers,
3464
+ credentials: this.credentials,
3465
+ headers: this.mergeClientHeaders(headers),
3219
3466
  body: formData
3220
3467
  });
3221
3468
  };
@@ -3223,25 +3470,239 @@
3223
3470
  return this.executeWithCsrfRetry(makeRequest, "Upload failed");
3224
3471
  }
3225
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
+
3226
3580
  async submitFeedback(payload ) {
3227
3581
  const makeRequest = async (csrfToken ) =>
3228
3582
  fetch(`${this.baseUrl}/feedback`, {
3229
3583
  method: "POST",
3230
- credentials: "same-origin",
3584
+ credentials: this.credentials,
3231
3585
  headers: this.buildJsonHeaders(csrfToken),
3232
3586
  body: JSON.stringify({ feedback: payload })
3233
3587
  });
3234
3588
 
3235
- 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;
3236
3697
  }
3237
3698
 
3238
3699
  async fetchAgentStatus() {
3239
3700
  const response = await fetch(`${this.baseUrl}/agent/status`, {
3240
3701
  method: "GET",
3241
- credentials: "same-origin",
3242
- headers: {
3702
+ credentials: this.credentials,
3703
+ headers: this.mergeClientHeaders({
3243
3704
  Accept: "application/json"
3244
- }
3705
+ })
3245
3706
  });
3246
3707
 
3247
3708
  if (!response.ok) {
@@ -3258,7 +3719,7 @@
3258
3719
  const makeRequest = async (csrfToken ) =>
3259
3720
  fetch(`${this.baseUrl}/agent/keys`, {
3260
3721
  method: "POST",
3261
- credentials: "same-origin",
3722
+ credentials: this.credentials,
3262
3723
  headers: this.buildJsonHeaders(csrfToken),
3263
3724
  body: JSON.stringify(payload)
3264
3725
  });
@@ -3270,7 +3731,7 @@
3270
3731
  const makeRequest = async (csrfToken ) =>
3271
3732
  fetch(`${this.baseUrl}/agent/keys?provider=${encodeURIComponent(provider)}`, {
3272
3733
  method: "DELETE",
3273
- credentials: "same-origin",
3734
+ credentials: this.credentials,
3274
3735
  headers: this.buildJsonHeaders(csrfToken)
3275
3736
  });
3276
3737
 
@@ -3284,10 +3745,10 @@
3284
3745
  const qs = `environment=${encodeURIComponent(environment)}&status=${encodeURIComponent(status)}`;
3285
3746
  const response = await fetch(`${this.baseUrl}/agent/feedbacks?${qs}`, {
3286
3747
  method: "GET",
3287
- credentials: "same-origin",
3288
- headers: {
3748
+ credentials: this.credentials,
3749
+ headers: this.mergeClientHeaders({
3289
3750
  Accept: "application/json"
3290
- }
3751
+ })
3291
3752
  });
3292
3753
 
3293
3754
  if (!response.ok) {
@@ -3304,7 +3765,7 @@
3304
3765
  const makeRequest = async (csrfToken ) =>
3305
3766
  fetch(`${this.baseUrl}/agent/chat`, {
3306
3767
  method: "POST",
3307
- credentials: "same-origin",
3768
+ credentials: this.credentials,
3308
3769
  headers: this.buildJsonHeaders(csrfToken),
3309
3770
  body: JSON.stringify(payload)
3310
3771
  });
@@ -3316,7 +3777,7 @@
3316
3777
  const makeRequest = async (csrfToken ) =>
3317
3778
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/apply`, {
3318
3779
  method: "POST",
3319
- credentials: "same-origin",
3780
+ credentials: this.credentials,
3320
3781
  headers: this.buildJsonHeaders(csrfToken)
3321
3782
  });
3322
3783
 
@@ -3327,7 +3788,7 @@
3327
3788
  const makeRequest = async (csrfToken ) =>
3328
3789
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/reject`, {
3329
3790
  method: "POST",
3330
- credentials: "same-origin",
3791
+ credentials: this.credentials,
3331
3792
  headers: this.buildJsonHeaders(csrfToken)
3332
3793
  });
3333
3794
 
@@ -3338,7 +3799,7 @@
3338
3799
  const makeRequest = async (csrfToken ) =>
3339
3800
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/revert`, {
3340
3801
  method: "POST",
3341
- credentials: "same-origin",
3802
+ credentials: this.credentials,
3342
3803
  headers: this.buildJsonHeaders(csrfToken)
3343
3804
  });
3344
3805
 
@@ -3450,7 +3911,7 @@
3450
3911
 
3451
3912
  // Paint page background
3452
3913
  const bodyBg =
3453
- window.getComputedStyle && document.body
3914
+ typeof window.getComputedStyle === "function" && document.body
3454
3915
  ? window.getComputedStyle(document.body).backgroundColor
3455
3916
  : "#ffffff";
3456
3917
  ctx.fillStyle = bodyBg && bodyBg !== "rgba(0, 0, 0, 0)" ? bodyBg : "#ffffff";
@@ -4605,7 +5066,7 @@
4605
5066
  }
4606
5067
 
4607
5068
  renderScrubbingHudContent(
4608
- currentCandidate ,
5069
+ _currentCandidate ,
4609
5070
  rect
4610
5071
  ) {
4611
5072
  if (!this.hudEl) return;
@@ -5321,12 +5782,24 @@
5321
5782
  : (class {} );
5322
5783
  class ContextDropWidgetElement extends BaseHTMLElement {
5323
5784
  static get observedAttributes() {
5324
- return ["data-position", "data-config", "data-theme", "data-cd-theme"];
5785
+ return [
5786
+ "data-endpoint",
5787
+ "data-position",
5788
+ "data-placeholder",
5789
+ "data-config",
5790
+ "data-metadata",
5791
+ "data-credentials",
5792
+ "data-selection-mode",
5793
+ "data-environment",
5794
+ "data-theme",
5795
+ "data-cd-theme"
5796
+ ];
5325
5797
  }
5326
5798
 
5327
5799
  shadow = null;
5328
5800
  config = structuredClone(DEFAULT_CONFIG);
5329
5801
  customMetadata = {};
5802
+ customHeaders = {};
5330
5803
  apiClient = new ContextDropApiClient("/context_drop");
5331
5804
  picker = null;
5332
5805
 
@@ -5350,6 +5823,17 @@
5350
5823
  elementDomNodes = new Map();
5351
5824
  attachments = [];
5352
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;
5353
5837
 
5354
5838
  // Local Agent state
5355
5839
  agentStatusLoaded = false;
@@ -5392,6 +5876,8 @@
5392
5876
  composerToolbarScreenshotBtn = null;
5393
5877
  composerToolbarUploadBtn = null;
5394
5878
  chatThreadEl = null;
5879
+ editBannerEl = null;
5880
+ editBannerInfoEl = null;
5395
5881
  textareaEl = null;
5396
5882
  trayEl = null;
5397
5883
  statusEl = null;
@@ -5403,7 +5889,6 @@
5403
5889
  sidebarPinBtn = null;
5404
5890
  sidebarEnvPillEl = null;
5405
5891
  sidebarPushBtn = null;
5406
- providerPillBtn = null;
5407
5892
  keyDotEl = null;
5408
5893
  providerPillLabelEl = null;
5409
5894
  keysToggleBtn = null;
@@ -5437,6 +5922,37 @@
5437
5922
  this.applyTheme(newValue, false);
5438
5923
  } else if (name === "data-position" && newValue) {
5439
5924
  this.setCornerPosition(newValue );
5925
+ } else if (name === "data-endpoint" && newValue && this.shadow) {
5926
+ this.setEndpoint(newValue);
5927
+ } else if (name === "data-credentials" && newValue && this.shadow) {
5928
+ if (newValue === "same-origin" || newValue === "include" || newValue === "omit") {
5929
+ this.apiClient.setCredentials(newValue);
5930
+ }
5931
+ } else if (name === "data-placeholder" && newValue && this.shadow) {
5932
+ this.setWidgetConfig({ placeholder: newValue });
5933
+ } else if (name === "data-metadata" && this.shadow) {
5934
+ if (newValue) {
5935
+ try {
5936
+ this.customMetadata = JSON.parse(newValue) ;
5937
+ } catch {
5938
+ this.customMetadata = {};
5939
+ }
5940
+ } else {
5941
+ this.customMetadata = {};
5942
+ }
5943
+ } else if (name === "data-selection-mode" && newValue && this.shadow) {
5944
+ if (newValue === "smart" || newValue === "verbose") {
5945
+ this.setWidgetConfig({ features: { ...this.config.features, selection_mode: newValue } });
5946
+ }
5947
+ } else if (name === "data-environment" && newValue && this.shadow) {
5948
+ this.setWidgetConfig({ environment: newValue });
5949
+ } else if (name === "data-config" && newValue && this.shadow) {
5950
+ try {
5951
+ const parsed = JSON.parse(newValue) ;
5952
+ this.setWidgetConfig(parsed);
5953
+ } catch {
5954
+ // Ignore malformed JSON
5955
+ }
5440
5956
  }
5441
5957
  }
5442
5958
 
@@ -5477,6 +5993,25 @@
5477
5993
  return;
5478
5994
  }
5479
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
+
5480
6015
  // Alt+Shift+P / Option+Shift+P toggles Freeze & Pin mode in technical/verbose environments
5481
6016
  if (
5482
6017
  !this.isSmartSelectionMode() &&
@@ -5591,6 +6126,51 @@
5591
6126
  return this.config;
5592
6127
  }
5593
6128
 
6129
+ setEndpoint(endpoint , options = {}) {
6130
+ const resolvedCredentials =
6131
+ options.credentials ||
6132
+ (this.getAttribute("data-credentials") ) ||
6133
+ "same-origin";
6134
+ const resolvedHeaders = options.headers || this.customHeaders;
6135
+ this.customHeaders = { ...resolvedHeaders };
6136
+ this.ownFeedbacksLoaded = false;
6137
+ this.inFlightOwnFeedbacksPromise = null;
6138
+ this.apiClient = new ContextDropApiClient(endpoint || "/context_drop", {
6139
+ credentials: resolvedCredentials,
6140
+ headers: this.customHeaders
6141
+ });
6142
+ }
6143
+
6144
+ setHeaders(headers ) {
6145
+ this.customHeaders = { ...headers };
6146
+ this.apiClient.setHeaders(this.customHeaders);
6147
+ }
6148
+
6149
+ setCredentials(credentials ) {
6150
+ this.apiClient.setCredentials(credentials);
6151
+ }
6152
+
6153
+ setCustomMetadata(metadata ) {
6154
+ this.customMetadata = { ...metadata };
6155
+ }
6156
+
6157
+ emitWidgetEvent(name , detail ) {
6158
+ if (typeof CustomEvent !== "function" || typeof this.dispatchEvent !== "function") {
6159
+ return;
6160
+ }
6161
+ try {
6162
+ this.dispatchEvent(
6163
+ new CustomEvent(name, {
6164
+ bubbles: true,
6165
+ composed: true,
6166
+ detail
6167
+ })
6168
+ );
6169
+ } catch {
6170
+ // Non-fatal in synthetic DOM environments
6171
+ }
6172
+ }
6173
+
5594
6174
  setWidgetConfig(partial ) {
5595
6175
  const wasAgentEnabled = Boolean(this.config.agent?.enabled);
5596
6176
  if (
@@ -5637,8 +6217,12 @@
5637
6217
  return;
5638
6218
  }
5639
6219
  this.surfaceMode = mode;
5640
- if (mode === "agent" && this.isOpen) {
5641
- 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
+ }
5642
6226
  }
5643
6227
  this.renderTray();
5644
6228
  this.renderChatThread();
@@ -5658,6 +6242,301 @@
5658
6242
  return [...this.sessionHistory];
5659
6243
  }
5660
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
+
5661
6540
  getAgentMessages() {
5662
6541
  return [...this.agentMessages];
5663
6542
  }
@@ -5691,16 +6570,23 @@
5691
6570
  }
5692
6571
 
5693
6572
  openComposer() {
6573
+ const wasOpen = this.isOpen && !this.isMinimized;
5694
6574
  this.isOpen = true;
5695
6575
  this.isMinimized = false;
5696
6576
  if (this.isAgentModeActive()) {
5697
6577
  void this.ensureAgentStatusLoaded();
6578
+ } else {
6579
+ void this.ensureOwnFeedbacksLoaded();
5698
6580
  }
5699
6581
  this.syncUiStates();
5700
6582
  this.focusActiveInput();
6583
+ if (!wasOpen) {
6584
+ this.emitWidgetEvent("context-drop:open", { open: true });
6585
+ }
5701
6586
  }
5702
6587
 
5703
6588
  closeComposer() {
6589
+ const wasOpen = this.isOpen;
5704
6590
  this.isOpen = false;
5705
6591
  this.isMinimized = false;
5706
6592
  if (this.picker && this.picker.isActive()) {
@@ -5708,6 +6594,9 @@
5708
6594
  }
5709
6595
  this.picker?.hideExternalPreview();
5710
6596
  this.syncUiStates();
6597
+ if (wasOpen) {
6598
+ this.emitWidgetEvent("context-drop:close", { open: false });
6599
+ }
5711
6600
  }
5712
6601
 
5713
6602
  toggleComposer() {
@@ -5968,7 +6857,15 @@
5968
6857
 
5969
6858
  readDataAttributes() {
5970
6859
  const endpoint = this.getAttribute("data-endpoint") || "/context_drop";
5971
- this.apiClient = new ContextDropApiClient(endpoint);
6860
+ const rawCredentials = this.getAttribute("data-credentials");
6861
+ const credentials =
6862
+ rawCredentials === "include" || rawCredentials === "omit" || rawCredentials === "same-origin"
6863
+ ? rawCredentials
6864
+ : "same-origin";
6865
+ this.apiClient = new ContextDropApiClient(endpoint, {
6866
+ credentials,
6867
+ headers: this.customHeaders
6868
+ });
5972
6869
 
5973
6870
  const rawConfig = this.getAttribute("data-config");
5974
6871
  if (rawConfig) {
@@ -6024,6 +6921,16 @@
6024
6921
  if (themeOverride === "dark" || themeOverride === "light") {
6025
6922
  this.currentTheme = themeOverride;
6026
6923
  }
6924
+
6925
+ const selectionModeOverride = this.getAttribute("data-selection-mode") ;
6926
+ if (selectionModeOverride === "smart" || selectionModeOverride === "verbose") {
6927
+ this.config.features.selection_mode = selectionModeOverride;
6928
+ }
6929
+
6930
+ const envOverride = this.getAttribute("data-environment");
6931
+ if (envOverride && envOverride.trim().length > 0) {
6932
+ this.config.environment = envOverride.trim();
6933
+ }
6027
6934
  }
6028
6935
 
6029
6936
  detectViewportSnapCorner(
@@ -6685,6 +7592,27 @@
6685
7592
  const promptShell = document.createElement("div");
6686
7593
  promptShell.className = "cd-prompt-shell";
6687
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
+
6688
7616
  const textarea = document.createElement("textarea");
6689
7617
  textarea.className = "cd-textarea";
6690
7618
  textarea.placeholder = this.config.placeholder;
@@ -6694,8 +7622,15 @@
6694
7622
  ev.preventDefault();
6695
7623
  void this.handleSubmit();
6696
7624
  } else if (ev.key === "Escape") {
7625
+ if (ev.defaultPrevented) return;
6697
7626
  ev.preventDefault();
6698
- 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
+ }
6699
7634
  }
6700
7635
  });
6701
7636
  textarea.addEventListener("paste", (ev) => this.handlePaste(ev));
@@ -6923,7 +7858,6 @@
6923
7858
  providerPill.appendChild(keyDot);
6924
7859
  providerPill.appendChild(providerLabel);
6925
7860
  providerPill.addEventListener("click", () => this.toggleByokDrawer());
6926
- this.providerPillBtn = providerPill;
6927
7861
 
6928
7862
  const subbarRight = document.createElement("div");
6929
7863
  subbarRight.className = "cd-subbar-right";
@@ -7978,6 +8912,35 @@
7978
8912
  ? `${ICON_IMAGE}<span>Add image</span>`
7979
8913
  : `${ICON_IMAGE}<span>Image</span>`;
7980
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
+ }
7981
8944
 
7982
8945
  if (this.agentSidebarEl) {
7983
8946
  this.agentSidebarEl.hidden = !showAgentSidebar;
@@ -8213,8 +9176,14 @@
8213
9176
  this.chatThreadEl.hidden = false;
8214
9177
 
8215
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
+
8216
9184
  const msgCard = document.createElement("div");
8217
- msgCard.className = "cd-chat-msg";
9185
+ msgCard.className = isEditingThis ? "cd-chat-msg is-editing" : "cd-chat-msg";
9186
+ msgCard.setAttribute("data-feedback-id", entryIdStr);
8218
9187
 
8219
9188
  if (entry.elements.length > 0 || entry.attachments.length > 0) {
8220
9189
  const pills = document.createElement("div");
@@ -8249,14 +9218,102 @@
8249
9218
 
8250
9219
  const meta = document.createElement("div");
8251
9220
  meta.className = "cd-chat-msg-meta";
9221
+
9222
+ const metaInfo = document.createElement("div");
9223
+ metaInfo.className = "cd-chat-msg-meta-info";
9224
+
8252
9225
  const idSpan = document.createElement("span");
8253
- 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
+
8254
9233
  const timeSpan = document.createElement("span");
8255
9234
  timeSpan.textContent = entry.createdAt;
8256
- meta.appendChild(idSpan);
8257
- 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);
8258
9275
  msgCard.appendChild(meta);
8259
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
+
8260
9317
  this.chatThreadEl.appendChild(msgCard);
8261
9318
  }
8262
9319
 
@@ -8645,6 +9702,7 @@
8645
9702
  async handleSubmit() {
8646
9703
  if (this.isSubmitting) return;
8647
9704
  const smartMode = this.isSmartSelectionMode();
9705
+ const editingId = this.editingFeedbackId;
8648
9706
 
8649
9707
  if (this.pendingSmartCaptures.size > 0) {
8650
9708
  await Promise.allSettled(Array.from(this.pendingSmartCaptures));
@@ -8668,32 +9726,120 @@
8668
9726
  this.isSubmitting = true;
8669
9727
  if (this.submitBtn) {
8670
9728
  this.submitBtn.disabled = true;
8671
- this.submitBtn.innerHTML = `<span>Sending...</span>`;
9729
+ this.submitBtn.innerHTML =
9730
+ editingId !== null ? `<span>Saving...</span>` : `<span>Sending...</span>`;
8672
9731
  }
8673
9732
 
8674
9733
  try {
8675
- const submittedElements = [...this.elementReferences];
8676
- const submittedAttachments = this.attachments.map((att) => ({
9734
+ const submittedElements = structuredClone(this.elementReferences);
9735
+ const submittedAttachments = this.attachments.map((att) => ({
8677
9736
  id: att.id,
9737
+ server_id: att.existing_attachment_id,
8678
9738
  label: att.label,
8679
9739
  preview_url: att.preview_url,
8680
- 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) : {}
8681
9746
  }));
8682
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
+
8683
9838
  const payload = {
8684
9839
  message,
8685
9840
  page_url: typeof window !== "undefined" ? window.location.href : "/",
8686
9841
  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
- },
9842
+ metadata: commonMetadata,
8697
9843
  element_references: this.elementReferences,
8698
9844
  attachments: this.attachments.map((att) => ({
8699
9845
  attachment_type: att.attachment_type,
@@ -8709,14 +9855,26 @@
8709
9855
 
8710
9856
  const now = new Date();
8711
9857
  const timeLabel = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
8712
- this.sessionHistory.push({
9858
+ const localStub = {
8713
9859
  id: res?.id ?? this.sessionHistory.length + 1,
8714
9860
  message:
8715
9861
  message || (smartMode ? "(Highlighted page area)" : "(Context drop without text)"),
9862
+ rawMessage: message,
8716
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,
8717
9869
  elements: submittedElements,
8718
9870
  attachments: submittedAttachments
8719
- });
9871
+ };
9872
+
9873
+ const createdEntry = res?.feedback
9874
+ ? this.mapOwnRecordToSessionEntry(res.feedback, localStub)
9875
+ : localStub;
9876
+
9877
+ this.sessionHistory.push(createdEntry);
8720
9878
 
8721
9879
  if (this.textareaEl) {
8722
9880
  this.textareaEl.value = "";
@@ -8732,15 +9890,34 @@
8732
9890
  smartMode ? "Thanks! Your feedback was sent." : "Context drop saved.",
8733
9891
  "success"
8734
9892
  );
9893
+ this.emitWidgetEvent("context-drop:submit", {
9894
+ response: res,
9895
+ payload
9896
+ });
8735
9897
  } catch (err) {
8736
- 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.";
8737
9904
  this.showStatus(msg, "error");
9905
+ this.emitWidgetEvent("context-drop:error", {
9906
+ error: msg
9907
+ });
8738
9908
  } finally {
8739
9909
  this.isSubmitting = false;
8740
9910
  if (this.submitBtn) {
8741
9911
  this.submitBtn.disabled = false;
8742
- 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
+ }
8743
9919
  }
9920
+ this.renderChatThread();
8744
9921
  }
8745
9922
  }
8746
9923