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
@@ -4,20 +4,85 @@ import type {
4
4
  AgentKeysUpdatePayload,
5
5
  AgentKeysUpdateResponse,
6
6
  AgentStatusResponse,
7
+ ContextDropApiClientOptions,
7
8
  CrossEnvFeedbackListResponse,
9
+ FeedbackDeleteResponse,
8
10
  FeedbackSubmissionPayload,
9
11
  FeedbackSubmissionResponse,
12
+ FeedbackUpdatePayload,
13
+ FeedbackUpdateResponse,
14
+ OwnFeedbackListResponse,
10
15
  ProposedFileEdit,
11
16
  WidgetConfig
12
17
  } from "./types.ts";
13
18
 
19
+ const OWNERSHIP_STORAGE_KEY = "context_drop_ownership_tokens";
20
+ const MAX_STORED_OWNERSHIP_TOKENS = 50;
21
+
22
+ function getBrowserLocalStorage(): Storage | null {
23
+ try {
24
+ if (typeof window !== "undefined" && "localStorage" in window) {
25
+ const store = window.localStorage;
26
+ if (store && typeof store.getItem === "function" && typeof store.setItem === "function") {
27
+ return store;
28
+ }
29
+ }
30
+ } catch {
31
+ // Storage unavailable or restricted by browser privacy policy
32
+ }
33
+ return null;
34
+ }
35
+
14
36
  export class ContextDropApiClient {
15
37
  private baseUrl: string;
38
+ private credentials: RequestCredentials;
39
+ private customHeaders: Record<string, string>;
16
40
  private cachedCsrfToken: string | null = null;
41
+ private configFetched: boolean = false;
17
42
  private inFlightConfigPromise: Promise<WidgetConfig> | null = null;
43
+ private memoryOwnershipTokens: Map<string, string> = new Map();
18
44
 
19
- constructor(baseUrl: string = "/context_drop") {
45
+ constructor(baseUrl: string = "/context_drop", options: ContextDropApiClientOptions = {}) {
20
46
  this.baseUrl = baseUrl.replace(/\/+$/, "") || "/context_drop";
47
+ this.credentials = options.credentials || "same-origin";
48
+ this.customHeaders = options.headers ? { ...options.headers } : {};
49
+ }
50
+
51
+ public getBaseUrl(): string {
52
+ return this.baseUrl;
53
+ }
54
+
55
+ public setCredentials(credentials: RequestCredentials): void {
56
+ this.credentials = credentials;
57
+ }
58
+
59
+ public setHeaders(headers: Record<string, string>): void {
60
+ this.customHeaders = { ...headers };
61
+ }
62
+
63
+ private isCrossOriginEndpoint(): boolean {
64
+ if (!/^https?:\/\//i.test(this.baseUrl)) {
65
+ return false;
66
+ }
67
+ if (typeof window === "undefined" || !window.location || !window.location.origin) {
68
+ return true;
69
+ }
70
+ try {
71
+ return new URL(this.baseUrl, window.location.origin).origin !== window.location.origin;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ private mergeClientHeaders(base: Record<string, string>): Record<string, string> {
78
+ const merged: Record<string, string> = {
79
+ ...this.customHeaders,
80
+ ...base
81
+ };
82
+ if (this.isCrossOriginEndpoint()) {
83
+ merged["X-Context-Drop-Client"] = "1";
84
+ }
85
+ return merged;
21
86
  }
22
87
 
23
88
  public getCsrfToken(): string | null {
@@ -48,10 +113,10 @@ export class ContextDropApiClient {
48
113
  try {
49
114
  const response = await fetch(`${this.baseUrl}/config`, {
50
115
  method: "GET",
51
- credentials: "same-origin",
52
- headers: {
116
+ credentials: this.credentials,
117
+ headers: this.mergeClientHeaders({
53
118
  Accept: "application/json"
54
- }
119
+ })
55
120
  });
56
121
 
57
122
  if (!response.ok) {
@@ -59,6 +124,7 @@ export class ContextDropApiClient {
59
124
  }
60
125
 
61
126
  const config = (await response.json()) as WidgetConfig;
127
+ this.configFetched = true;
62
128
  if (config && typeof config.csrf_token === "string" && config.csrf_token.trim().length > 0) {
63
129
  this.cachedCsrfToken = config.csrf_token.trim();
64
130
  if (typeof document !== "undefined") {
@@ -86,6 +152,9 @@ export class ContextDropApiClient {
86
152
  if (this.cachedCsrfToken) {
87
153
  return this.cachedCsrfToken;
88
154
  }
155
+ if (this.configFetched) {
156
+ return null;
157
+ }
89
158
  }
90
159
 
91
160
  try {
@@ -130,7 +199,8 @@ export class ContextDropApiClient {
130
199
 
131
200
  const errorMessage = parsedError || rawText || "";
132
201
  const shouldRetryCsrf =
133
- this.isCsrfError(response.status, errorMessage) || (!csrfToken && response.status === 422);
202
+ this.isCsrfError(response.status, errorMessage) ||
203
+ (!csrfToken && !this.configFetched && response.status === 422);
134
204
 
135
205
  if (shouldRetryCsrf) {
136
206
  csrfToken = await this.resolveCsrfToken(true);
@@ -161,7 +231,7 @@ export class ContextDropApiClient {
161
231
  if (csrfToken) {
162
232
  headers["X-CSRF-Token"] = csrfToken;
163
233
  }
164
- return headers;
234
+ return this.mergeClientHeaders(headers);
165
235
  }
166
236
 
167
237
  public async uploadAttachment(file: Blob, filename: string): Promise<{ signed_blob_id: string }> {
@@ -178,8 +248,8 @@ export class ContextDropApiClient {
178
248
 
179
249
  return fetch(`${this.baseUrl}/attachments`, {
180
250
  method: "POST",
181
- credentials: "same-origin",
182
- headers,
251
+ credentials: this.credentials,
252
+ headers: this.mergeClientHeaders(headers),
183
253
  body: formData
184
254
  });
185
255
  };
@@ -187,25 +257,239 @@ export class ContextDropApiClient {
187
257
  return this.executeWithCsrfRetry(makeRequest, "Upload failed");
188
258
  }
189
259
 
260
+ private ownershipScopedKey(id: number | string): string {
261
+ return `${this.baseUrl}::${String(id)}`;
262
+ }
263
+
264
+ private readStoredTokenMap(): Record<string, string> {
265
+ const store = getBrowserLocalStorage();
266
+ if (!store) {
267
+ const out: Record<string, string> = {};
268
+ for (const [k, v] of this.memoryOwnershipTokens.entries()) {
269
+ out[k] = v;
270
+ }
271
+ return out;
272
+ }
273
+
274
+ try {
275
+ const raw = store.getItem(OWNERSHIP_STORAGE_KEY);
276
+ if (!raw) return {};
277
+ const parsed = JSON.parse(raw) as unknown;
278
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
279
+ return {};
280
+ }
281
+ const clean: Record<string, string> = {};
282
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
283
+ if (typeof v === "string" && v.trim().length > 0) {
284
+ clean[k] = v.trim();
285
+ }
286
+ }
287
+ return clean;
288
+ } catch {
289
+ return {};
290
+ }
291
+ }
292
+
293
+ private writeStoredTokenMap(map: Record<string, string>): void {
294
+ const entries = Object.entries(map);
295
+ const trimmedEntries =
296
+ entries.length > MAX_STORED_OWNERSHIP_TOKENS
297
+ ? entries.slice(entries.length - MAX_STORED_OWNERSHIP_TOKENS)
298
+ : entries;
299
+
300
+ this.memoryOwnershipTokens.clear();
301
+ const bounded: Record<string, string> = {};
302
+ for (const [k, v] of trimmedEntries) {
303
+ bounded[k] = v;
304
+ this.memoryOwnershipTokens.set(k, v);
305
+ }
306
+
307
+ const store = getBrowserLocalStorage();
308
+ if (store) {
309
+ try {
310
+ store.setItem(OWNERSHIP_STORAGE_KEY, JSON.stringify(bounded));
311
+ } catch {
312
+ // Non-fatal if storage quota exceeded
313
+ }
314
+ }
315
+ }
316
+
317
+ public getOwnershipToken(id: number | string): string | null {
318
+ const map = this.readStoredTokenMap();
319
+ const scoped = map[this.ownershipScopedKey(id)];
320
+ if (scoped) return scoped;
321
+ const plain = map[String(id)];
322
+ return plain || null;
323
+ }
324
+
325
+ public setOwnershipToken(id: number | string, token: string): void {
326
+ const trimmed = typeof token === "string" ? token.trim() : "";
327
+ if (!trimmed) return;
328
+ const map = this.readStoredTokenMap();
329
+ const key = this.ownershipScopedKey(id);
330
+ delete map[key];
331
+ map[key] = trimmed;
332
+ this.writeStoredTokenMap(map);
333
+ }
334
+
335
+ public removeOwnershipToken(id: number | string): void {
336
+ const map = this.readStoredTokenMap();
337
+ const scopedKey = this.ownershipScopedKey(id);
338
+ const plainKey = String(id);
339
+ if (!(scopedKey in map) && !(plainKey in map)) return;
340
+ delete map[scopedKey];
341
+ delete map[plainKey];
342
+ this.writeStoredTokenMap(map);
343
+ }
344
+
345
+ public getAllOwnershipTokens(): string[] {
346
+ const map = this.readStoredTokenMap();
347
+ const prefix = `${this.baseUrl}::`;
348
+ const tokens: string[] = [];
349
+ for (const [k, v] of Object.entries(map)) {
350
+ if ((k.startsWith(prefix) || !k.includes("::")) && v && !tokens.includes(v)) {
351
+ tokens.push(v);
352
+ }
353
+ }
354
+ return tokens;
355
+ }
356
+
357
+ public buildAttachmentPreviewUrl(
358
+ feedbackId: number | string,
359
+ attachmentId: number | string,
360
+ ownershipToken?: string | null
361
+ ): string {
362
+ const token = ownershipToken || this.getOwnershipToken(feedbackId);
363
+ const base = `${this.baseUrl}/feedback/${encodeURIComponent(String(feedbackId))}/attachments/${encodeURIComponent(String(attachmentId))}`;
364
+ return token ? `${base}?ownership_token=${encodeURIComponent(token)}` : base;
365
+ }
366
+
190
367
  public async submitFeedback(payload: FeedbackSubmissionPayload): Promise<FeedbackSubmissionResponse> {
191
368
  const makeRequest = async (csrfToken: string | null) =>
192
369
  fetch(`${this.baseUrl}/feedback`, {
193
370
  method: "POST",
194
- credentials: "same-origin",
371
+ credentials: this.credentials,
195
372
  headers: this.buildJsonHeaders(csrfToken),
196
373
  body: JSON.stringify({ feedback: payload })
197
374
  });
198
375
 
199
- return this.executeWithCsrfRetry(makeRequest, "Submission failed");
376
+ const response = await this.executeWithCsrfRetry<FeedbackSubmissionResponse>(
377
+ makeRequest,
378
+ "Submission failed"
379
+ );
380
+
381
+ const token = response?.ownership_token || response?.feedback?.ownership_token;
382
+ if (response?.id !== undefined && token) {
383
+ this.setOwnershipToken(response.id, token);
384
+ }
385
+ return response;
386
+ }
387
+
388
+ public async fetchOwnFeedbacks(limit: number = 30): Promise<OwnFeedbackListResponse> {
389
+ const headers: Record<string, string> = {
390
+ Accept: "application/json"
391
+ };
392
+ const tokens = this.getAllOwnershipTokens();
393
+ if (tokens.length > 0) {
394
+ headers["X-Context-Drop-Ownership-Tokens"] = tokens.join(",");
395
+ }
396
+
397
+ const qs = limit > 0 ? `?limit=${encodeURIComponent(String(limit))}` : "";
398
+ const response = await fetch(`${this.baseUrl}/feedback${qs}`, {
399
+ method: "GET",
400
+ credentials: this.credentials,
401
+ headers: this.mergeClientHeaders(headers)
402
+ });
403
+
404
+ if (!response.ok) {
405
+ const errBody = await response.json().catch(() => ({}));
406
+ throw new Error(
407
+ (errBody as { error?: string }).error || `Failed to load own feedbacks (${response.status})`
408
+ );
409
+ }
410
+
411
+ const parsed = (await response.json().catch(() => ({}))) as Partial<OwnFeedbackListResponse>;
412
+ const feedbacks = Array.isArray(parsed?.feedbacks) ? parsed.feedbacks : [];
413
+ for (const item of feedbacks) {
414
+ if (item && item.id !== undefined && typeof item.ownership_token === "string") {
415
+ this.setOwnershipToken(item.id, item.ownership_token);
416
+ }
417
+ }
418
+
419
+ return {
420
+ total_count: typeof parsed?.total_count === "number" ? parsed.total_count : feedbacks.length,
421
+ feedbacks
422
+ };
423
+ }
424
+
425
+ public async updateFeedback(
426
+ id: number | string,
427
+ payload: FeedbackUpdatePayload,
428
+ ownershipToken?: string | null
429
+ ): Promise<FeedbackUpdateResponse> {
430
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
431
+ const makeRequest = async (csrfToken: string | null) => {
432
+ const headers = this.buildJsonHeaders(csrfToken);
433
+ if (resolvedToken) {
434
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
435
+ }
436
+ const bodyPayload: Record<string, unknown> = { feedback: payload };
437
+ if (resolvedToken) {
438
+ bodyPayload.ownership_token = resolvedToken;
439
+ }
440
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
441
+ method: "PATCH",
442
+ credentials: this.credentials,
443
+ headers,
444
+ body: JSON.stringify(bodyPayload)
445
+ });
446
+ };
447
+
448
+ const response = await this.executeWithCsrfRetry<FeedbackUpdateResponse>(
449
+ makeRequest,
450
+ "Update failed"
451
+ );
452
+
453
+ const nextToken = response?.ownership_token || response?.feedback?.ownership_token;
454
+ if (response?.id !== undefined && nextToken) {
455
+ this.setOwnershipToken(response.id, nextToken);
456
+ }
457
+ return response;
458
+ }
459
+
460
+ public async deleteFeedback(
461
+ id: number | string,
462
+ ownershipToken?: string | null
463
+ ): Promise<FeedbackDeleteResponse> {
464
+ const resolvedToken = ownershipToken || this.getOwnershipToken(id);
465
+ const makeRequest = async (csrfToken: string | null) => {
466
+ const headers = this.buildJsonHeaders(csrfToken);
467
+ if (resolvedToken) {
468
+ headers["X-Context-Drop-Ownership-Token"] = resolvedToken;
469
+ }
470
+ return fetch(`${this.baseUrl}/feedback/${encodeURIComponent(String(id))}`, {
471
+ method: "DELETE",
472
+ credentials: this.credentials,
473
+ headers
474
+ });
475
+ };
476
+
477
+ const response = await this.executeWithCsrfRetry<FeedbackDeleteResponse>(
478
+ makeRequest,
479
+ "Delete failed"
480
+ );
481
+
482
+ this.removeOwnershipToken(id);
483
+ return response;
200
484
  }
201
485
 
202
486
  public async fetchAgentStatus(): Promise<AgentStatusResponse> {
203
487
  const response = await fetch(`${this.baseUrl}/agent/status`, {
204
488
  method: "GET",
205
- credentials: "same-origin",
206
- headers: {
489
+ credentials: this.credentials,
490
+ headers: this.mergeClientHeaders({
207
491
  Accept: "application/json"
208
- }
492
+ })
209
493
  });
210
494
 
211
495
  if (!response.ok) {
@@ -222,7 +506,7 @@ export class ContextDropApiClient {
222
506
  const makeRequest = async (csrfToken: string | null) =>
223
507
  fetch(`${this.baseUrl}/agent/keys`, {
224
508
  method: "POST",
225
- credentials: "same-origin",
509
+ credentials: this.credentials,
226
510
  headers: this.buildJsonHeaders(csrfToken),
227
511
  body: JSON.stringify(payload)
228
512
  });
@@ -234,7 +518,7 @@ export class ContextDropApiClient {
234
518
  const makeRequest = async (csrfToken: string | null) =>
235
519
  fetch(`${this.baseUrl}/agent/keys?provider=${encodeURIComponent(provider)}`, {
236
520
  method: "DELETE",
237
- credentials: "same-origin",
521
+ credentials: this.credentials,
238
522
  headers: this.buildJsonHeaders(csrfToken)
239
523
  });
240
524
 
@@ -248,10 +532,10 @@ export class ContextDropApiClient {
248
532
  const qs = `environment=${encodeURIComponent(environment)}&status=${encodeURIComponent(status)}`;
249
533
  const response = await fetch(`${this.baseUrl}/agent/feedbacks?${qs}`, {
250
534
  method: "GET",
251
- credentials: "same-origin",
252
- headers: {
535
+ credentials: this.credentials,
536
+ headers: this.mergeClientHeaders({
253
537
  Accept: "application/json"
254
- }
538
+ })
255
539
  });
256
540
 
257
541
  if (!response.ok) {
@@ -268,7 +552,7 @@ export class ContextDropApiClient {
268
552
  const makeRequest = async (csrfToken: string | null) =>
269
553
  fetch(`${this.baseUrl}/agent/chat`, {
270
554
  method: "POST",
271
- credentials: "same-origin",
555
+ credentials: this.credentials,
272
556
  headers: this.buildJsonHeaders(csrfToken),
273
557
  body: JSON.stringify(payload)
274
558
  });
@@ -280,7 +564,7 @@ export class ContextDropApiClient {
280
564
  const makeRequest = async (csrfToken: string | null) =>
281
565
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/apply`, {
282
566
  method: "POST",
283
- credentials: "same-origin",
567
+ credentials: this.credentials,
284
568
  headers: this.buildJsonHeaders(csrfToken)
285
569
  });
286
570
 
@@ -291,7 +575,7 @@ export class ContextDropApiClient {
291
575
  const makeRequest = async (csrfToken: string | null) =>
292
576
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/reject`, {
293
577
  method: "POST",
294
- credentials: "same-origin",
578
+ credentials: this.credentials,
295
579
  headers: this.buildJsonHeaders(csrfToken)
296
580
  });
297
581
 
@@ -302,7 +586,7 @@ export class ContextDropApiClient {
302
586
  const makeRequest = async (csrfToken: string | null) =>
303
587
  fetch(`${this.baseUrl}/agent/edits/${encodeURIComponent(editId)}/revert`, {
304
588
  method: "POST",
305
- credentials: "same-origin",
589
+ credentials: this.credentials,
306
590
  headers: this.buildJsonHeaders(csrfToken)
307
591
  });
308
592
 
@@ -1007,7 +1007,7 @@ export class ElementPicker {
1007
1007
  }
1008
1008
 
1009
1009
  private renderScrubbingHudContent(
1010
- currentCandidate: ElementCandidateInfo,
1010
+ _currentCandidate: ElementCandidateInfo,
1011
1011
  rect: { width: number; height: number }
1012
1012
  ): void {
1013
1013
  if (!this.hudEl) return;
@@ -59,3 +59,7 @@ export const ICON_SUN = `<svg viewBox="0 0 20 20" width="14" height="14" fill="n
59
59
 
60
60
  export 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>`;
61
61
 
62
+ export 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>`;
63
+
64
+ export 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>`;
65
+
@@ -118,7 +118,7 @@ export async function captureViewportScreenshot(
118
118
 
119
119
  // Paint page background
120
120
  const bodyBg =
121
- window.getComputedStyle && document.body
121
+ typeof window.getComputedStyle === "function" && document.body
122
122
  ? window.getComputedStyle(document.body).backgroundColor
123
123
  : "#ffffff";
124
124
  ctx.fillStyle = bodyBg && bodyBg !== "rgba(0, 0, 0, 0)" ? bodyBg : "#ffffff";