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
@@ -307,4 +307,259 @@ describe("ContextDropApiClient CSRF handling & lazy bootstrap", () => {
307
307
  assert.equal(fetchCalls[2].url, "/context_drop/config");
308
308
  assert.equal(fetchCalls[3].url, "/context_drop/attachments");
309
309
  });
310
+
311
+ it("avoids redundant /config calls when Next.js backend returns csrf_token: null and sends X-Context-Drop-Client cross-origin", async () => {
312
+ mockMetaContent = null;
313
+ mockFetchHandler = async (url: string, _options: RequestInit) => {
314
+ if (url.endsWith("/config")) {
315
+ return new Response(
316
+ JSON.stringify({
317
+ enabled: true,
318
+ position: "bottom_right",
319
+ csrf_token: null
320
+ }),
321
+ { status: 200, headers: { "Content-Type": "application/json" } }
322
+ );
323
+ }
324
+ return new Response(JSON.stringify({ id: 9, status: "new" }), {
325
+ status: 201,
326
+ headers: { "Content-Type": "application/json" }
327
+ });
328
+ };
329
+
330
+ const client = new ContextDropApiClient("https://api.acme.com/api/context-drop", {
331
+ credentials: "include",
332
+ headers: { "X-Tenant-Id": "acme" }
333
+ });
334
+
335
+ await client.submitFeedback({
336
+ message: "First Next.js feedback",
337
+ page_url: "https://app.acme.com/home",
338
+ user_agent: "test-agent",
339
+ metadata: {},
340
+ element_references: [],
341
+ attachments: []
342
+ });
343
+
344
+ await client.submitFeedback({
345
+ message: "Second Next.js feedback",
346
+ page_url: "https://app.acme.com/home",
347
+ user_agent: "test-agent",
348
+ metadata: {},
349
+ element_references: [],
350
+ attachments: []
351
+ });
352
+
353
+ // Only 1 /config bootstrap call + 2 /feedback calls (no redundant /config before second submit)
354
+ assert.equal(fetchCalls.length, 3);
355
+ assert.equal(fetchCalls[0].url, "https://api.acme.com/api/context-drop/config");
356
+ assert.equal(fetchCalls[1].url, "https://api.acme.com/api/context-drop/feedback");
357
+ assert.equal(fetchCalls[2].url, "https://api.acme.com/api/context-drop/feedback");
358
+ assert.equal(fetchCalls[1].options.credentials, "include");
359
+ const sentHeaders = fetchCalls[1].options.headers as Record<string, string>;
360
+ assert.equal(sentHeaders["X-Context-Drop-Client"], "1");
361
+ assert.equal(sentHeaders["X-Tenant-Id"], "acme");
362
+ });
363
+ });
364
+
365
+ describe("ContextDropApiClient own feedback sync, update, soft-delete & ownership tokens", () => {
366
+ const originalDocument = globalThis.document;
367
+ const originalWindow = (globalThis as Record<string, unknown>).window;
368
+ const originalFetch = globalThis.fetch;
369
+
370
+ let fetchCalls: Array<{ url: string; options: RequestInit }> = [];
371
+ let mockFetchHandler: (url: string, options: RequestInit) => Promise<Response>;
372
+
373
+ beforeEach(() => {
374
+ fetchCalls = [];
375
+ (globalThis as unknown as { document: unknown }).document = {
376
+ querySelector: (selector: string) =>
377
+ selector === 'meta[name="csrf-token"]'
378
+ ? {
379
+ getAttribute: (name: string) => (name === "content" ? "csrf-tok-1" : null),
380
+ setAttribute: () => {}
381
+ }
382
+ : null
383
+ };
384
+
385
+ mockFetchHandler = async () =>
386
+ new Response(JSON.stringify({ ok: true }), {
387
+ status: 200,
388
+ headers: { "Content-Type": "application/json" }
389
+ });
390
+
391
+ globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
392
+ const url = typeof input === "string" ? input : input.toString();
393
+ const options = init || {};
394
+ fetchCalls.push({ url, options });
395
+ return mockFetchHandler(url, options);
396
+ };
397
+ });
398
+
399
+ afterEach(() => {
400
+ (globalThis as unknown as { document: unknown }).document = originalDocument;
401
+ if (originalWindow === undefined) {
402
+ delete (globalThis as Record<string, unknown>).window;
403
+ } else {
404
+ (globalThis as Record<string, unknown>).window = originalWindow;
405
+ }
406
+ globalThis.fetch = originalFetch;
407
+ });
408
+
409
+ it("persists ownership_token in window.localStorage and falls back cleanly to memory when unavailable", async () => {
410
+ const storeData = new Map<string, string>();
411
+ (globalThis as Record<string, unknown>).window = {
412
+ location: { origin: "http://localhost:3000" },
413
+ localStorage: {
414
+ getItem: (k: string) => storeData.get(k) ?? null,
415
+ setItem: (k: string, v: string) => {
416
+ storeData.set(k, v);
417
+ },
418
+ removeItem: (k: string) => {
419
+ storeData.delete(k);
420
+ }
421
+ }
422
+ };
423
+
424
+ mockFetchHandler = async () =>
425
+ new Response(
426
+ JSON.stringify({
427
+ id: 77,
428
+ status: "new",
429
+ ownership_token: "77.nonce1.sig1",
430
+ created_at: "2026-11-13T00:00:00Z"
431
+ }),
432
+ { status: 201, headers: { "Content-Type": "application/json" } }
433
+ );
434
+
435
+ const clientWithStorage = new ContextDropApiClient("/context_drop");
436
+ await clientWithStorage.submitFeedback({
437
+ message: "Stored token test",
438
+ page_url: "http://localhost:3000/app",
439
+ user_agent: "node-test",
440
+ metadata: {},
441
+ element_references: [],
442
+ attachments: []
443
+ });
444
+
445
+ assert.equal(clientWithStorage.getOwnershipToken(77), "77.nonce1.sig1");
446
+ assert.ok(storeData.get("context_drop_ownership_tokens")?.includes("77.nonce1.sig1"));
447
+
448
+ // Second client sharing localStorage reads persisted token across page reloads
449
+ const reloadedClient = new ContextDropApiClient("/context_drop");
450
+ assert.equal(reloadedClient.getOwnershipToken(77), "77.nonce1.sig1");
451
+ assert.equal(
452
+ reloadedClient.buildAttachmentPreviewUrl(77, 9),
453
+ "/context_drop/feedback/77/attachments/9?ownership_token=77.nonce1.sig1"
454
+ );
455
+
456
+ // Without window.localStorage, falls back to in-memory map
457
+ delete (globalThis as Record<string, unknown>).window;
458
+ const memoryClient = new ContextDropApiClient("/context_drop");
459
+ memoryClient.setOwnershipToken(88, "88.nonce2.sig2");
460
+ assert.equal(memoryClient.getOwnershipToken(88), "88.nonce2.sig2");
461
+ assert.equal(
462
+ memoryClient.buildAttachmentPreviewUrl(99, 3),
463
+ "/context_drop/feedback/99/attachments/3"
464
+ );
465
+ });
466
+
467
+ it("sends X-Context-Drop-Ownership-Tokens in fetchOwnFeedbacks, retries CSRF on updateFeedback, and clears token on deleteFeedback", async () => {
468
+ delete (globalThis as Record<string, unknown>).window;
469
+ const client = new ContextDropApiClient("/context_drop");
470
+ client.setOwnershipToken(12, "12.n1.s1");
471
+
472
+ let patchAttempts = 0;
473
+ mockFetchHandler = async (url: string, options: RequestInit) => {
474
+ const method = (options.method || "GET").toUpperCase();
475
+ if (url.startsWith("/context_drop/feedback?") && method === "GET") {
476
+ return new Response(
477
+ JSON.stringify({
478
+ total_count: 1,
479
+ feedbacks: [
480
+ {
481
+ id: 12,
482
+ status: "new",
483
+ message: "Existing feedback",
484
+ page_url: "http://localhost:3000/orders",
485
+ created_at: "2026-11-13T01:00:00Z",
486
+ updated_at: "2026-11-13T01:00:00Z",
487
+ ownership_token: "12.n1.rotated",
488
+ element_references: [],
489
+ attachments: []
490
+ }
491
+ ]
492
+ }),
493
+ { status: 200, headers: { "Content-Type": "application/json" } }
494
+ );
495
+ }
496
+
497
+ if (url.endsWith("/config") && method === "GET") {
498
+ return new Response(
499
+ JSON.stringify({ enabled: true, csrf_token: "fresh-csrf-2" }),
500
+ { status: 200, headers: { "Content-Type": "application/json" } }
501
+ );
502
+ }
503
+
504
+ if (url === "/context_drop/feedback/12" && method === "PATCH") {
505
+ patchAttempts += 1;
506
+ if (patchAttempts === 1) {
507
+ return new Response(
508
+ JSON.stringify({ error: "Invalid CSRF authenticity token" }),
509
+ { status: 422, headers: { "Content-Type": "application/json" } }
510
+ );
511
+ }
512
+ return new Response(
513
+ JSON.stringify({
514
+ id: 12,
515
+ status: "new",
516
+ attachments_count: 0,
517
+ element_references_count: 1,
518
+ ownership_token: "12.n1.rotated",
519
+ updated_at: "2026-11-13T02:00:00Z"
520
+ }),
521
+ { status: 200, headers: { "Content-Type": "application/json" } }
522
+ );
523
+ }
524
+
525
+ if (url === "/context_drop/feedback/12" && method === "DELETE") {
526
+ return new Response(
527
+ JSON.stringify({
528
+ id: 12,
529
+ deleted: true,
530
+ deleted_at: "2026-11-13T03:00:00Z"
531
+ }),
532
+ { status: 200, headers: { "Content-Type": "application/json" } }
533
+ );
534
+ }
535
+
536
+ throw new Error(`Unexpected request: ${method} ${url}`);
537
+ };
538
+
539
+ const own = await client.fetchOwnFeedbacks(20);
540
+ assert.equal(own.total_count, 1);
541
+ assert.equal(
542
+ (fetchCalls[0].options.headers as Record<string, string>)["X-Context-Drop-Ownership-Tokens"],
543
+ "12.n1.s1"
544
+ );
545
+ assert.equal(client.getOwnershipToken(12), "12.n1.rotated");
546
+
547
+ const updated = await client.updateFeedback(12, {
548
+ message: "Edited feedback text",
549
+ element_references: [],
550
+ attachments: []
551
+ });
552
+ assert.equal(updated.id, 12);
553
+ assert.equal(patchAttempts, 2);
554
+ const patchHeaders = fetchCalls[3].options.headers as Record<string, string>;
555
+ assert.equal(patchHeaders["X-Context-Drop-Ownership-Token"], "12.n1.rotated");
556
+ const patchBody = JSON.parse(String(fetchCalls[3].options.body)) as Record<string, unknown>;
557
+ assert.equal(patchBody.ownership_token, "12.n1.rotated");
558
+
559
+ const deleted = await client.deleteFeedback(12);
560
+ assert.equal(deleted.deleted, true);
561
+ const deleteHeaders = fetchCalls[4].options.headers as Record<string, string>;
562
+ assert.equal(deleteHeaders["X-Context-Drop-Ownership-Token"], "12.n1.rotated");
563
+ assert.equal(client.getOwnershipToken(12), null);
564
+ });
310
565
  });
@@ -384,6 +384,7 @@ class MockUiEvent {
384
384
  public readonly deltaY: number;
385
385
  public readonly deltaMode: number;
386
386
  public readonly key: string;
387
+ public readonly code: string;
387
388
  public readonly shiftKey: boolean;
388
389
  public readonly altKey: boolean;
389
390
  public readonly ctrlKey: boolean;
@@ -496,6 +497,8 @@ class MockDomElement {
496
497
  public autocomplete: string = "";
497
498
  public multiple: boolean = false;
498
499
  public accept: string = "";
500
+ public src: string = "";
501
+ public alt: string = "";
499
502
  public scrollTop: number = 0;
500
503
  public scrollHeight: number = 0;
501
504
  private rawHtml: string = "";
@@ -1548,7 +1551,7 @@ describe("ContextDrop v0.2 Book-Corner Peel-to-Pin & Agentic Sidebar", () => {
1548
1551
 
1549
1552
  it("defaults sidebar width to 560px for full container item layout without crowding", async () => {
1550
1553
  await withMountedWidget(
1551
- async ({ widget, shadowRoot, mockHtml }) => {
1554
+ async ({ shadowRoot, mockHtml }) => {
1552
1555
  const sidebar = shadowRoot.querySelector(".cd-agent-sidebar");
1553
1556
  const bookCorner = shadowRoot.querySelector(".cd-book-corner");
1554
1557
  assert.ok(sidebar && bookCorner);
@@ -1609,4 +1612,355 @@ describe("ContextDrop v0.2 Book-Corner Peel-to-Pin & Agentic Sidebar", () => {
1609
1612
  }
1610
1613
  );
1611
1614
  });
1615
+
1616
+ it("loads own feedbacks on open, edits message + context inline with draft restoration, and emits context-drop:update", async () => {
1617
+ const g = globalThis as Record<string, unknown>;
1618
+ const prevFetch = g.fetch;
1619
+ const apiCalls: Array<{ url: string; method: string; headers: Record<string, string>; body?: unknown }> = [];
1620
+
1621
+ g.fetch = async (input: string | URL, init?: RequestInit) => {
1622
+ const url = String(input);
1623
+ const method = (init?.method || "GET").toUpperCase();
1624
+ const headers = (init?.headers as Record<string, string>) || {};
1625
+ const body =
1626
+ typeof init?.body === "string" && init.body.length > 0 ? JSON.parse(init.body) : undefined;
1627
+ apiCalls.push({ url, method, headers, body });
1628
+
1629
+ if (url.includes("/feedback?") && method === "GET") {
1630
+ return new Response(
1631
+ JSON.stringify({
1632
+ total_count: 1,
1633
+ feedbacks: [
1634
+ {
1635
+ id: 501,
1636
+ status: "new",
1637
+ message: "Initial checkout button misalignment",
1638
+ page_url: "http://localhost:3000/orders",
1639
+ created_at: "2026-11-13T04:00:00Z",
1640
+ updated_at: "2026-11-13T04:00:00Z",
1641
+ ownership_token: "501.nonceA.sigA",
1642
+ element_references: [
1643
+ {
1644
+ id: 11,
1645
+ client_ref: "el_orig_1",
1646
+ tag_name: "button",
1647
+ selector: "#submit-order",
1648
+ dom_path: "body > button#submit-order",
1649
+ text_content: "Submit Order",
1650
+ bounding_rect: { x: 20, y: 40, width: 160, height: 42 }
1651
+ }
1652
+ ],
1653
+ attachments: [
1654
+ {
1655
+ id: 91,
1656
+ attachment_type: "screenshot",
1657
+ filename: "orig-shot.png",
1658
+ content_type: "image/png",
1659
+ byte_size: 1200,
1660
+ element_reference_id: 11,
1661
+ element_client_ref: "el_orig_1",
1662
+ preview_url: "/context_drop/feedback/501/attachments/91",
1663
+ metadata: { capture_type: "element" }
1664
+ }
1665
+ ]
1666
+ }
1667
+ ]
1668
+ }),
1669
+ { status: 200, headers: { "Content-Type": "application/json" } }
1670
+ );
1671
+ }
1672
+
1673
+ if (url.endsWith("/feedback/501") && method === "PATCH") {
1674
+ return new Response(
1675
+ JSON.stringify({
1676
+ id: 501,
1677
+ status: "new",
1678
+ attachments_count: 1,
1679
+ element_references_count: 2,
1680
+ ownership_token: "501.nonceA.sigA",
1681
+ updated_at: "2026-11-13T04:05:00Z",
1682
+ feedback: {
1683
+ id: 501,
1684
+ status: "new",
1685
+ message: "Updated: button + coupon field misaligned on Safari",
1686
+ page_url: "http://localhost:3000/orders",
1687
+ created_at: "2026-11-13T04:00:00Z",
1688
+ updated_at: "2026-11-13T04:05:00Z",
1689
+ ownership_token: "501.nonceA.sigA",
1690
+ element_references: [
1691
+ {
1692
+ id: 12,
1693
+ client_ref: "el_orig_1",
1694
+ tag_name: "button",
1695
+ selector: "#submit-order",
1696
+ dom_path: "body > button#submit-order"
1697
+ },
1698
+ {
1699
+ id: 13,
1700
+ client_ref: "el_added_2",
1701
+ tag_name: "input",
1702
+ selector: "#coupon-code",
1703
+ dom_path: "body > input#coupon-code"
1704
+ }
1705
+ ],
1706
+ attachments: [
1707
+ {
1708
+ id: 91,
1709
+ attachment_type: "screenshot",
1710
+ filename: "orig-shot.png",
1711
+ content_type: "image/png",
1712
+ byte_size: 1200,
1713
+ element_reference_id: 12,
1714
+ element_client_ref: "el_orig_1",
1715
+ preview_url: "/context_drop/feedback/501/attachments/91"
1716
+ }
1717
+ ]
1718
+ }
1719
+ }),
1720
+ { status: 200, headers: { "Content-Type": "application/json" } }
1721
+ );
1722
+ }
1723
+
1724
+ throw new Error(`Unexpected fetch ${method} ${url}`);
1725
+ };
1726
+
1727
+ try {
1728
+ await withMountedWidget(
1729
+ async ({ widget, shadowRoot, mockBody, mockWindow }) => {
1730
+ const updateEvents: unknown[] = [];
1731
+ widget.addEventListener("context-drop:update", (ev: unknown) => {
1732
+ updateEvents.push((ev as { detail?: unknown }).detail);
1733
+ });
1734
+
1735
+ // Open composer -> triggers lazy GET /feedback sync
1736
+ widget.openComposer();
1737
+ await new Promise((r) => setTimeout(r, 15));
1738
+
1739
+ const chatThread = shadowRoot.querySelector(".cd-chat-thread");
1740
+ const editBanner = shadowRoot.querySelector(".cd-edit-banner");
1741
+ const textarea = shadowRoot.querySelector("[aria-label='Feedback description']");
1742
+ const tray = shadowRoot.querySelector(".cd-tray");
1743
+ assert.ok(chatThread && editBanner && textarea && tray);
1744
+ assert.equal(chatThread.hidden, false);
1745
+ assert.equal(editBanner.hidden, true);
1746
+
1747
+ const msgCard = chatThread.querySelector(".cd-chat-msg");
1748
+ assert.ok(msgCard, "Synced own feedback card is rendered in composer thread");
1749
+
1750
+ // Type an unsent draft before clicking Edit so draft restoration can be verified
1751
+ textarea.value = "Unsent new draft note";
1752
+ textarea.dispatchEvent(new MockUiEvent("input"));
1753
+
1754
+ const editBtn = msgCard.querySelector("[aria-label='Edit feedback']");
1755
+ assert.ok(editBtn);
1756
+ editBtn.dispatchEvent(new MockUiEvent("click"));
1757
+
1758
+ assert.equal(editBanner.hidden, false);
1759
+ assert.equal(textarea.value, "Initial checkout button misalignment");
1760
+ assert.equal(widget.getElementReferences().length, 1);
1761
+ assert.equal(widget.getElementReferences()[0].selector, "#submit-order");
1762
+ assert.equal(widget.getAttachments().length, 1);
1763
+ assert.equal(widget.getAttachments()[0].existing_attachment_id, 91);
1764
+
1765
+ const saveBtn = shadowRoot.querySelector("[aria-label='Save feedback changes']");
1766
+ assert.ok(saveBtn, "Submit button switches aria-label to Save feedback changes");
1767
+
1768
+ // Pressing Escape while editing cancels edit and restores the unsent draft!
1769
+ mockWindow.dispatchEvent(new MockUiEvent("keydown", { key: "Escape" }));
1770
+ assert.equal(editBanner.hidden, true);
1771
+ assert.equal(textarea.value, "Unsent new draft note");
1772
+ assert.equal(widget.getElementReferences().length, 0);
1773
+ assert.equal(widget.getAttachments().length, 0);
1774
+
1775
+ // Re-enter edit mode on #501, pin an additional element, edit text, and click Save
1776
+ const editBtnAgain = shadowRoot.querySelector("[aria-label='Edit feedback']");
1777
+ assert.ok(editBtnAgain);
1778
+ editBtnAgain.dispatchEvent(new MockUiEvent("click"));
1779
+
1780
+ const couponInput = new MockDomElement("input");
1781
+ couponInput.setAttribute("id", "coupon-code");
1782
+ couponInput.setRect({ left: 30, top: 90, width: 200, height: 36 });
1783
+ mockBody.appendChild(couponInput);
1784
+ widget.addElementReference({
1785
+ client_ref: "el_added_2",
1786
+ tag_name: "input",
1787
+ selector: "#coupon-code",
1788
+ dom_path: "body > input#coupon-code",
1789
+ text_content: null,
1790
+ attributes_snapshot: { id: "coupon-code" },
1791
+ bounding_rect: { x: 30, y: 90, width: 200, height: 36 },
1792
+ viewport: { width: 1280, height: 800 },
1793
+ metadata: {},
1794
+ captured_at: "2026-11-13T04:04:00Z"
1795
+ });
1796
+
1797
+ textarea.value = "Updated: button + coupon field misaligned on Safari";
1798
+ textarea.dispatchEvent(new MockUiEvent("input"));
1799
+
1800
+ const activeSaveBtn = shadowRoot.querySelector("[aria-label='Save feedback changes']");
1801
+ assert.ok(activeSaveBtn);
1802
+ activeSaveBtn.dispatchEvent(new MockUiEvent("click"));
1803
+ await new Promise((r) => setTimeout(r, 15));
1804
+
1805
+ const patchCall = apiCalls.find((c) => c.method === "PATCH");
1806
+ assert.ok(patchCall, "PATCH /feedback/501 was sent");
1807
+ assert.equal(patchCall.headers["X-Context-Drop-Ownership-Token"], "501.nonceA.sigA");
1808
+ const patchPayload = (patchCall.body as { feedback: Record<string, unknown> }).feedback;
1809
+ assert.equal(patchPayload.message, "Updated: button + coupon field misaligned on Safari");
1810
+ assert.equal((patchPayload.element_references as unknown[]).length, 2);
1811
+ const sentAtts = patchPayload.attachments as Array<Record<string, unknown>>;
1812
+ assert.equal(sentAtts.length, 1);
1813
+ assert.equal(sentAtts[0].existing_id, 91);
1814
+
1815
+ // Edit mode exited, unsent draft restored, card updated with · edited indicator, event emitted
1816
+ assert.equal(editBanner.hidden, true);
1817
+ assert.equal(textarea.value, "Unsent new draft note");
1818
+ assert.equal(updateEvents.length, 1);
1819
+ const updatedMetaInfo = shadowRoot.querySelector(".cd-chat-msg-meta-info");
1820
+ assert.ok(
1821
+ updatedMetaInfo &&
1822
+ updatedMetaInfo.childNodes.some((n) => n.textContent.includes("edited"))
1823
+ );
1824
+ },
1825
+ {
1826
+ "data-config": JSON.stringify({
1827
+ enabled: true,
1828
+ environment: "staging",
1829
+ position: "bottom_right",
1830
+ csrf_token: "test_csrf_999",
1831
+ agent: { enabled: false }
1832
+ })
1833
+ }
1834
+ );
1835
+ } finally {
1836
+ if (prevFetch === undefined) {
1837
+ delete g.fetch;
1838
+ } else {
1839
+ g.fetch = prevFetch;
1840
+ }
1841
+ }
1842
+ });
1843
+
1844
+ it("soft-deletes own feedback via inline confirmation bar in smart mode without modals and emits context-drop:delete", async () => {
1845
+ const g = globalThis as Record<string, unknown>;
1846
+ const prevFetch = g.fetch;
1847
+ const apiCalls: Array<{ url: string; method: string; headers: Record<string, string> }> = [];
1848
+
1849
+ g.fetch = async (input: string | URL, init?: RequestInit) => {
1850
+ const url = String(input);
1851
+ const method = (init?.method || "GET").toUpperCase();
1852
+ const headers = (init?.headers as Record<string, string>) || {};
1853
+ apiCalls.push({ url, method, headers });
1854
+
1855
+ if (url.includes("/feedback?") && method === "GET") {
1856
+ return new Response(
1857
+ JSON.stringify({
1858
+ total_count: 1,
1859
+ feedbacks: [
1860
+ {
1861
+ id: 808,
1862
+ status: "new",
1863
+ message: "Accidental duplicate report",
1864
+ page_url: "http://localhost:3000/orders",
1865
+ created_at: "2026-11-13T05:00:00Z",
1866
+ updated_at: "2026-11-13T05:00:00Z",
1867
+ ownership_token: "808.nonceB.sigB",
1868
+ element_references: [],
1869
+ attachments: []
1870
+ }
1871
+ ]
1872
+ }),
1873
+ { status: 200, headers: { "Content-Type": "application/json" } }
1874
+ );
1875
+ }
1876
+
1877
+ if (url.endsWith("/feedback/808") && method === "DELETE") {
1878
+ return new Response(
1879
+ JSON.stringify({
1880
+ id: 808,
1881
+ deleted: true,
1882
+ deleted_at: "2026-11-13T05:01:00Z"
1883
+ }),
1884
+ { status: 200, headers: { "Content-Type": "application/json" } }
1885
+ );
1886
+ }
1887
+
1888
+ throw new Error(`Unexpected fetch ${method} ${url}`);
1889
+ };
1890
+
1891
+ try {
1892
+ await withMountedWidget(
1893
+ async ({ widget, shadowRoot }) => {
1894
+ const deleteEvents: unknown[] = [];
1895
+ widget.addEventListener("context-drop:delete", (ev: unknown) => {
1896
+ deleteEvents.push((ev as { detail?: unknown }).detail);
1897
+ });
1898
+
1899
+ widget.openComposer();
1900
+ await new Promise((r) => setTimeout(r, 15));
1901
+
1902
+ const chatThread = shadowRoot.querySelector(".cd-chat-thread");
1903
+ const editBanner = shadowRoot.querySelector(".cd-edit-banner");
1904
+ assert.ok(chatThread && editBanner);
1905
+ assert.equal(chatThread.hidden, false);
1906
+
1907
+ // Start editing #808 first, then trigger Delete to verify deleting cancels active edit cleanly
1908
+ const editBtn = chatThread.querySelector("[aria-label='Edit feedback']");
1909
+ assert.ok(editBtn);
1910
+ editBtn.dispatchEvent(new MockUiEvent("click"));
1911
+ assert.equal(editBanner.hidden, false);
1912
+
1913
+ const deleteBtn = chatThread.querySelector("[aria-label='Delete feedback']");
1914
+ assert.ok(deleteBtn);
1915
+ deleteBtn.dispatchEvent(new MockUiEvent("click"));
1916
+
1917
+ // Inline confirmation bar appears (no browser confirm / modal)
1918
+ let confirmBar = chatThread.querySelector(".cd-msg-delete-confirm");
1919
+ assert.ok(confirmBar, "Inline delete confirmation bar renders inside feedback card");
1920
+
1921
+ // Clicking Cancel dismisses inline confirmation without calling DELETE
1922
+ const cancelDelBtn = confirmBar.querySelector("[aria-label='Cancel delete']");
1923
+ assert.ok(cancelDelBtn);
1924
+ cancelDelBtn.dispatchEvent(new MockUiEvent("click"));
1925
+ assert.equal(chatThread.querySelector(".cd-msg-delete-confirm"), null);
1926
+ assert.equal(apiCalls.some((c) => c.method === "DELETE"), false);
1927
+
1928
+ // Click Delete again, then Confirm delete feedback
1929
+ const deleteBtnAgain = chatThread.querySelector("[aria-label='Delete feedback']");
1930
+ assert.ok(deleteBtnAgain);
1931
+ deleteBtnAgain.dispatchEvent(new MockUiEvent("click"));
1932
+
1933
+ confirmBar = chatThread.querySelector(".cd-msg-delete-confirm");
1934
+ assert.ok(confirmBar);
1935
+ const confirmDelBtn = confirmBar.querySelector("[aria-label='Confirm delete feedback']");
1936
+ assert.ok(confirmDelBtn);
1937
+ confirmDelBtn.dispatchEvent(new MockUiEvent("click"));
1938
+ await new Promise((r) => setTimeout(r, 15));
1939
+
1940
+ const delCall = apiCalls.find((c) => c.method === "DELETE");
1941
+ assert.ok(delCall, "DELETE /feedback/808 was sent");
1942
+ assert.equal(delCall.headers["X-Context-Drop-Ownership-Token"], "808.nonceB.sigB");
1943
+ assert.equal(editBanner.hidden, true, "Active edit banner closes when edited feedback is deleted");
1944
+ assert.equal(chatThread.querySelector(".cd-chat-msg"), null, "Deleted card is removed from thread");
1945
+ assert.ok(chatThread.querySelector(".cd-chat-empty"), "Empty state prompt renders cleanly after delete");
1946
+ assert.equal(deleteEvents.length, 1);
1947
+ },
1948
+ {
1949
+ "data-config": JSON.stringify({
1950
+ enabled: true,
1951
+ environment: "production",
1952
+ position: "bottom_right",
1953
+ csrf_token: "prod_csrf_123",
1954
+ agent: { enabled: false }
1955
+ })
1956
+ }
1957
+ );
1958
+ } finally {
1959
+ if (prevFetch === undefined) {
1960
+ delete g.fetch;
1961
+ } else {
1962
+ g.fetch = prevFetch;
1963
+ }
1964
+ }
1965
+ });
1612
1966
  });