sanity-plugin-seo-copilot 0.2.7 → 0.2.11

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.
package/package.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "name": "sanity-plugin-seo-copilot",
3
- "version": "0.2.7",
3
+ "version": "0.2.11",
4
4
  "description": "AI-powered SEO writing assistant for Sanity Studio",
5
- "keywords": ["sanity", "sanity-plugin", "seo", "copilot"],
5
+ "keywords": [
6
+ "sanity",
7
+ "sanity-plugin",
8
+ "seo",
9
+ "copilot"
10
+ ],
6
11
  "license": "UNLICENSED",
7
12
  "author": "MJH Life Sciences",
8
13
  "exports": {
@@ -231,20 +231,22 @@ export function ChatPanel({ messages, isStreaming, sendMessage, clearChat, docum
231
231
  {messages.length > 0 && (
232
232
  <button
233
233
  onClick={clearChat}
234
- onMouseEnter={() => setClearHovered(true)}
234
+ onMouseEnter={() => !isStreaming && setClearHovered(true)}
235
235
  onMouseLeave={() => setClearHovered(false)}
236
236
  title="Clear conversation"
237
237
  aria-label="Clear conversation"
238
+ disabled={isStreaming}
238
239
  style={{
239
240
  background: "none",
240
241
  border: "none",
241
- cursor: "pointer",
242
+ cursor: isStreaming ? "not-allowed" : "pointer",
242
243
  padding: 4,
243
244
  display: "flex",
244
245
  alignItems: "center",
245
- color: clearHovered ? "#ef4444" : "#9ca3af",
246
+ color: isStreaming ? "#d1d5db" : clearHovered ? "#ef4444" : "#9ca3af",
246
247
  transition: "color 150ms",
247
248
  flexShrink: 0,
249
+ opacity: isStreaming ? 0.4 : 1,
248
250
  }}
249
251
  >
250
252
  <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">
@@ -19,6 +19,11 @@ export function FeedbackButton({ suggestionType, suggestionText, documentId, pub
19
19
  const [submitted, setSubmitted] = useState(false);
20
20
  const popupRef = useRef<HTMLDivElement>(null);
21
21
  const inputRef = useRef<HTMLInputElement>(null);
22
+ const submitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
23
+
24
+ useEffect(() => {
25
+ return () => { if (submitTimerRef.current) clearTimeout(submitTimerRef.current); };
26
+ }, []);
22
27
 
23
28
  // Close popup on outside click
24
29
  useEffect(() => {
@@ -90,7 +95,7 @@ export function FeedbackButton({ suggestionType, suggestionText, documentId, pub
90
95
  } catch { /* silent */ }
91
96
  }
92
97
  setSubmitted(true);
93
- setTimeout(() => {
98
+ submitTimerRef.current = setTimeout(() => {
94
99
  setShowReasonPopup(false);
95
100
  setReason("");
96
101
  }, 1000);
@@ -113,12 +113,14 @@ function buildSuggestedKeywords(
113
113
  const lowerText = documentText.toLowerCase();
114
114
 
115
115
  for (const kw of supporting) {
116
+ if (kw == null || typeof kw.term !== "string") continue;
116
117
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
117
118
  const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
118
119
  merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: livePlacement });
119
120
  }
120
121
 
121
122
  for (const kw of missing) {
123
+ if (kw == null || typeof kw.term !== "string") continue;
122
124
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
123
125
  const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
124
126
  merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: livePlacement });
@@ -450,8 +452,9 @@ function SecondaryKeywordSelector({
450
452
  };
451
453
 
452
454
  // The selected secondary may be a custom term not present in `options` - append it
453
- // so the radio still shows as selected.
454
- const opts = selectedTerm && !options.some((o) => o.term === selectedTerm)
455
+ // so the radio still shows as selected. Case-insensitive check so a filtered-out
456
+ // primary (removed via lowercase comparison) is not re-added here.
457
+ const opts = selectedTerm && !options.some((o) => o.term.toLowerCase() === selectedTerm.toLowerCase())
455
458
  ? [...options, { term: selectedTerm, volume: null }]
456
459
  : options;
457
460
 
@@ -564,8 +567,8 @@ function computePlacementClient(term: string, content: string, fields?: Document
564
567
  const lower = term.toLowerCase();
565
568
  return {
566
569
  inBody: content.toLowerCase().includes(lower),
567
- inTitle: fields?.title?.toLowerCase().includes(lower) ?? false,
568
- inMetaDescription: fields?.metaDescription?.toLowerCase().includes(lower) ?? false,
570
+ inTitle: typeof fields?.title === 'string' ? fields.title.toLowerCase().includes(lower) : false,
571
+ inMetaDescription: typeof fields?.metaDescription === 'string' ? fields.metaDescription.toLowerCase().includes(lower) : false,
569
572
  inImages: fields?.imageNames?.some((name: string) => name.toLowerCase().includes(lower)) ?? false,
570
573
  inUrl: fields?.slug?.toLowerCase().includes(lower) ?? false,
571
574
  };
@@ -649,7 +652,9 @@ function SuggestedKeywordsCard({
649
652
  const res = await fetch(`${apiUrl}/api/seo-copilot/keyword-help`, {
650
653
  method: "POST",
651
654
  headers: { "Content-Type": "application/json" },
652
- body: JSON.stringify({ keyword: term, content: text, publication, previousSuggestions }),
655
+ // Clip to 5,000 chars: the backend only reads the first 4,000 anyway, so sending
656
+ // the full article needlessly bloats the request on long pieces.
657
+ body: JSON.stringify({ keyword: term, content: text.slice(0, 5000), publication, previousSuggestions }),
653
658
  });
654
659
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
655
660
  const data = await res.json();
@@ -1063,9 +1068,12 @@ export function KeywordPanel({
1063
1068
  // Auto-update selected term when analysis refreshes (unless user manually picked a different one)
1064
1069
  useEffect(() => {
1065
1070
  if (defaultSelectedTerm && defaultSelectedTerm !== prevDefaultRef.current) {
1066
- // Only auto-update if user's current selection was the old default (they haven't overridden)
1067
- setSelectedPrimaryTerm((prev) => prev === prevDefaultRef.current ? defaultSelectedTerm : prev);
1071
+ // Only auto-update if the user's current selection was the old default (no manual override).
1072
+ // Snapshot the old ref value BEFORE mutating it - the setState updater is queued and runs
1073
+ // after this effect body, so it must compare against the old default, not the new one.
1074
+ const oldDefault = prevDefaultRef.current;
1068
1075
  prevDefaultRef.current = defaultSelectedTerm;
1076
+ setSelectedPrimaryTerm((prev) => (prev === oldDefault ? defaultSelectedTerm : prev));
1069
1077
  }
1070
1078
  }, [defaultSelectedTerm]);
1071
1079
 
@@ -1122,17 +1130,19 @@ export function KeywordPanel({
1122
1130
  ? selectedPrimaryTerm
1123
1131
  : candidates[0]?.term ?? "";
1124
1132
 
1125
- // Secondary options = the same candidate pool as primary, plus the suggested
1126
- // supporting keywords (deduped). The primary term is intentionally NOT removed -
1127
- // both selectors draw from one shared pool.
1133
+ // Secondary options = same candidate pool as primary + supporting keywords, deduped,
1134
+ // with the currently-active primary filtered out so editors can't pick the same keyword twice.
1135
+ const activeTermLower = activeTerm.toLowerCase();
1128
1136
  const secondaryOptions: { term: string; volume: number | null }[] = [];
1129
1137
  const seenSecondary = new Set<string>();
1130
1138
  for (const c of candidates) {
1131
1139
  const key = c.term.toLowerCase();
1140
+ if (key === activeTermLower) continue;
1132
1141
  if (!seenSecondary.has(key)) { seenSecondary.add(key); secondaryOptions.push({ term: c.term, volume: c.volume }); }
1133
1142
  }
1134
1143
  for (const kw of suggestedKeywords) {
1135
1144
  const key = kw.term.toLowerCase();
1145
+ if (key === activeTermLower) continue;
1136
1146
  if (!seenSecondary.has(key)) { seenSecondary.add(key); secondaryOptions.push({ term: kw.term, volume: kw.volume }); }
1137
1147
  }
1138
1148
 
@@ -1,108 +1,108 @@
1
- import { MJH_BLUE } from "./styles";
2
-
3
- // Small (i) button that lives in the panel header next to the pop-out control. The
4
- // first-run popup collapses into this; clicking it re-opens the popup.
5
- export function OnboardingInfoButton({ onClick }: { onClick: () => void }) {
6
- return (
7
- <button
8
- onClick={(e) => { e.stopPropagation(); onClick(); }}
9
- onMouseDown={(e) => e.stopPropagation()}
10
- style={{
11
- background: "rgba(0,93,172,0.08)",
12
- border: "none",
13
- borderRadius: "50%",
14
- width: 20,
15
- height: 20,
16
- cursor: "pointer",
17
- padding: 0,
18
- display: "flex",
19
- alignItems: "center",
20
- justifyContent: "center",
21
- color: MJH_BLUE,
22
- flexShrink: 0,
23
- }}
24
- title="How SEO Copilot works"
25
- aria-label="How SEO Copilot works"
26
- >
27
- <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
28
- <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clipRule="evenodd" />
29
- </svg>
30
- </button>
31
- );
32
- }
33
-
34
- // First-run onboarding popup. Amorphous MJH-blue glass. Clicking anywhere on the
35
- // dimmed backdrop, the X, or "Got it" dismisses it (fades out to the info icon).
36
- export function OnboardingCard({ onDismiss, closing }: { onDismiss: () => void; closing: boolean }) {
37
- return (
38
- <>
39
- {/* Click-anywhere backdrop - very light so it doesn't feel like a hard modal. */}
40
- <div
41
- onClick={onDismiss}
42
- style={{
43
- position: "absolute",
44
- inset: 0,
45
- zIndex: 60,
46
- background: "transparent",
47
- cursor: "pointer",
48
- }}
49
- />
50
- <div
51
- onClick={(e) => e.stopPropagation()}
52
- style={{
53
- position: "absolute",
54
- top: 50,
55
- right: 10,
56
- left: 10,
57
- maxWidth: 320,
58
- marginLeft: "auto",
59
- zIndex: 61,
60
- borderRadius: 18,
61
- padding: "14px 16px 16px",
62
- // Amorphous blue glass
63
- background: "linear-gradient(155deg, rgba(0,93,172,0.16), rgba(0,93,172,0.08))",
64
- backdropFilter: "blur(20px) saturate(170%)",
65
- WebkitBackdropFilter: "blur(20px) saturate(170%)",
66
- boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.55), inset 1.5px 2px 1px -1px rgba(255,255,255,0.9), 0 10px 30px rgba(0,93,172,0.22), 0 2px 8px rgba(0,0,0,0.12)",
67
- animation: `${closing ? "onboard-out" : "onboard-in"} ${closing ? 180 : 240}ms ease-out forwards`,
68
- }}
69
- >
70
- <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 6 }}>
71
- <span style={{ fontSize: 13, fontWeight: 800, color: "#00468a", letterSpacing: "-0.01em" }}>
72
- Welcome to SEO Copilot
73
- </span>
74
- <button
75
- onClick={onDismiss}
76
- style={{ background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#00468a", opacity: 0.7 }}
77
- title="Dismiss"
78
- aria-label="Dismiss"
79
- >
80
- <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">
81
- <path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
82
- </svg>
83
- </button>
84
- </div>
85
- <div style={{ fontSize: 11.5, color: "#13335a", lineHeight: 1.6 }}>
86
- Start on the <strong>Keywords</strong> tab. Choose one <strong>Primary</strong> keyword (required) and, optionally, one <strong>Secondary</strong> keyword. Copilot then optimizes the whole article - title, meta, URL, headings, and images - toward both.
87
- </div>
88
- <button
89
- onClick={onDismiss}
90
- style={{
91
- marginTop: 12,
92
- width: "100%",
93
- padding: "7px 12px",
94
- fontSize: 11.5,
95
- fontWeight: 700,
96
- color: "#ffffff",
97
- background: MJH_BLUE,
98
- border: "none",
99
- borderRadius: 8,
100
- cursor: "pointer",
101
- }}
102
- >
103
- Got it
104
- </button>
105
- </div>
106
- </>
107
- );
108
- }
1
+ import { MJH_BLUE } from "./styles";
2
+
3
+ // Small (i) button that lives in the panel header next to the pop-out control. The
4
+ // first-run popup collapses into this; clicking it re-opens the popup.
5
+ export function OnboardingInfoButton({ onClick }: { onClick: () => void }) {
6
+ return (
7
+ <button
8
+ onClick={(e) => { e.stopPropagation(); onClick(); }}
9
+ onMouseDown={(e) => e.stopPropagation()}
10
+ style={{
11
+ background: "rgba(0,93,172,0.08)",
12
+ border: "none",
13
+ borderRadius: "50%",
14
+ width: 20,
15
+ height: 20,
16
+ cursor: "pointer",
17
+ padding: 0,
18
+ display: "flex",
19
+ alignItems: "center",
20
+ justifyContent: "center",
21
+ color: MJH_BLUE,
22
+ flexShrink: 0,
23
+ }}
24
+ title="How SEO Copilot works"
25
+ aria-label="How SEO Copilot works"
26
+ >
27
+ <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
28
+ <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clipRule="evenodd" />
29
+ </svg>
30
+ </button>
31
+ );
32
+ }
33
+
34
+ // First-run onboarding popup. Amorphous MJH-blue glass. Clicking anywhere on the
35
+ // dimmed backdrop, the X, or "Got it" dismisses it (fades out to the info icon).
36
+ export function OnboardingCard({ onDismiss, closing }: { onDismiss: () => void; closing: boolean }) {
37
+ return (
38
+ <>
39
+ {/* Click-anywhere backdrop - very light so it doesn't feel like a hard modal. */}
40
+ <div
41
+ onClick={onDismiss}
42
+ style={{
43
+ position: "absolute",
44
+ inset: 0,
45
+ zIndex: 60,
46
+ background: "transparent",
47
+ cursor: "pointer",
48
+ }}
49
+ />
50
+ <div
51
+ onClick={(e) => e.stopPropagation()}
52
+ style={{
53
+ position: "absolute",
54
+ top: 50,
55
+ right: 10,
56
+ left: 10,
57
+ maxWidth: 320,
58
+ marginLeft: "auto",
59
+ zIndex: 61,
60
+ borderRadius: 18,
61
+ padding: "14px 16px 16px",
62
+ // Amorphous blue glass
63
+ background: "linear-gradient(155deg, rgba(0,93,172,0.16), rgba(0,93,172,0.08))",
64
+ backdropFilter: "blur(20px) saturate(170%)",
65
+ WebkitBackdropFilter: "blur(20px) saturate(170%)",
66
+ boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.55), inset 1.5px 2px 1px -1px rgba(255,255,255,0.9), 0 10px 30px rgba(0,93,172,0.22), 0 2px 8px rgba(0,0,0,0.12)",
67
+ animation: `${closing ? "onboard-out" : "onboard-in"} ${closing ? 200 : 240}ms ease-out forwards`,
68
+ }}
69
+ >
70
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 6 }}>
71
+ <span style={{ fontSize: 13, fontWeight: 800, color: "#00468a", letterSpacing: "-0.01em" }}>
72
+ Welcome to SEO Copilot
73
+ </span>
74
+ <button
75
+ onClick={onDismiss}
76
+ style={{ background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#00468a", opacity: 1 }}
77
+ title="Dismiss"
78
+ aria-label="Dismiss"
79
+ >
80
+ <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">
81
+ <path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
82
+ </svg>
83
+ </button>
84
+ </div>
85
+ <div style={{ fontSize: 11.5, color: "#13335a", lineHeight: 1.6 }}>
86
+ Start on the <strong>Keywords</strong> tab. Choose one <strong>Primary</strong> keyword (required) and, optionally, one <strong>Secondary</strong> keyword. Copilot then optimizes its recommendations toward both.
87
+ </div>
88
+ <button
89
+ onClick={onDismiss}
90
+ style={{
91
+ marginTop: 12,
92
+ width: "100%",
93
+ padding: "7px 12px",
94
+ fontSize: 11.5,
95
+ fontWeight: 700,
96
+ color: "#ffffff",
97
+ background: MJH_BLUE,
98
+ border: "none",
99
+ borderRadius: 8,
100
+ cursor: "pointer",
101
+ }}
102
+ >
103
+ Got it
104
+ </button>
105
+ </div>
106
+ </>
107
+ );
108
+ }
@@ -196,6 +196,7 @@ function PanelContent({
196
196
  const [popupMode, setPopupMode] = useState<"hidden" | "auto" | "persistent">("hidden");
197
197
  const [popupClosing, setPopupClosing] = useState(false);
198
198
  const onboardTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
199
+ const onboardFadeRef = useRef<ReturnType<typeof setTimeout> | null>(null);
199
200
 
200
201
  useEffect(() => {
201
202
  let onboarded = false;
@@ -208,10 +209,13 @@ function PanelContent({
208
209
  onboardTimerRef.current = setTimeout(() => {
209
210
  // Auto-fade to the (i) icon. Does NOT mark onboarded.
210
211
  setPopupClosing(true);
211
- setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 180);
212
- }, 5000);
212
+ onboardFadeRef.current = setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 180);
213
+ }, 8000);
213
214
  }
214
- return () => { if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current); };
215
+ return () => {
216
+ if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
217
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
218
+ };
215
219
  // Re-run only when the site changes.
216
220
  // eslint-disable-next-line react-hooks/exhaustive-deps
217
221
  }, [onboardKey, onboardSessionKey]);
@@ -222,13 +226,15 @@ function PanelContent({
222
226
 
223
227
  const dismissPopup = useCallback(() => {
224
228
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
229
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
225
230
  markOnboarded();
226
231
  setPopupClosing(true);
227
- setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 180);
232
+ onboardFadeRef.current = setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 180);
228
233
  }, [markOnboarded]);
229
234
 
230
235
  const openPopupPersistent = useCallback(() => {
231
236
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
237
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
232
238
  markOnboarded();
233
239
  setPopupClosing(false);
234
240
  setPopupMode("persistent");
@@ -238,7 +244,9 @@ function PanelContent({
238
244
  const handleTabChange = useCallback((id: TabId) => {
239
245
  markOnboarded();
240
246
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
241
- setPopupMode((m) => (m === "hidden" ? m : "hidden"));
247
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
248
+ setPopupClosing(true);
249
+ onboardFadeRef.current = setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 120);
242
250
  onActiveTabChange(id);
243
251
  }, [markOnboarded, onActiveTabChange]);
244
252
 
@@ -676,6 +684,8 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
676
684
  );
677
685
  const dragOffset = useRef<{ dx: number; dy: number } | null>(null);
678
686
  const resizeStart = useRef<{ startX: number; startY: number; startW: number; startH: number } | null>(null);
687
+ const activeDragCleanupRef = useRef<(() => void) | null>(null);
688
+ const activeResizeCleanupRef = useRef<(() => void) | null>(null);
679
689
 
680
690
  const { text, isLoading: docLoading, documentFields, documentId, documentType } = useDocumentContent();
681
691
  const { apiUrl } = useConfig();
@@ -749,6 +759,14 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
749
759
  // Effective primary (matches PanelContent's resolution)
750
760
  const effectivePrimary = selectedPrimary || keywordAnalysisState.analysis?.primaryKeyword?.term || "";
751
761
 
762
+ // Clear the secondary keyword if the user promotes it to primary - otherwise both
763
+ // slots hold the same term and all secondary-coverage audits produce false positives.
764
+ useEffect(() => {
765
+ if (selectedSecondary && effectivePrimary && selectedSecondary.toLowerCase() === effectivePrimary.toLowerCase()) {
766
+ setSelectedSecondary("");
767
+ }
768
+ }, [effectivePrimary, selectedSecondary, setSelectedSecondary]);
769
+
752
770
  // Build keyword panel data (consumed by chat). Lifted here so chat hook lives at top level.
753
771
  const keywordPanelData = useMemo(() => {
754
772
  const analysis = keywordAnalysisState.analysis;
@@ -779,6 +797,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
779
797
  const [isCSLoading, setIsCSLoading] = useState(false);
780
798
  const [csError, setCsError] = useState<string | null>(null);
781
799
  const aeoOpVersionRef = useRef(0);
800
+ const csAbortRef = useRef<AbortController | null>(null);
782
801
  // Only reset *transient* state on doc change. Persisted state is reloaded automatically
783
802
  // by usePersistentState when its key changes.
784
803
  const didInitAeoRef = useRef(false);
@@ -797,7 +816,11 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
797
816
  setIsCSLoading(true);
798
817
  setCsError(null);
799
818
  try {
800
- const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication);
819
+ csAbortRef.current?.abort(); const csController = new AbortController(); csAbortRef.current = csController;
820
+ const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication, csController.signal);
821
+ // This call was superseded by a newer one (e.g. rapid re-click). Bail silently so the
822
+ // aborted call's empty result does not flash a false "No suggestions returned" error.
823
+ if (csController.signal.aborted) return;
801
824
  if (aeoOpVersionRef.current !== myVersion) return;
802
825
  if (
803
826
  data.keyTakeaways.length === 0 &&
@@ -825,6 +848,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
825
848
  // The article text at the moment we last fetched - used to flag stale suggestions.
826
849
  const [linkingFetchedText, setLinkingFetchedText] = useState("");
827
850
  const linkingVersionRef = useRef(0);
851
+ const linkingAbortRef = useRef<AbortController | null>(null);
828
852
  const didInitLinkingRef = useRef(false);
829
853
  // Tracks the keyword signature we last fetched for, so the auto-fetch effect can skip
830
854
  // re-fetching when persisted suggestions already cover the current doc. Declared here
@@ -859,14 +883,19 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
859
883
  setIsLinkingLoading(true);
860
884
  setLinkingError(null);
861
885
  try {
886
+ linkingAbortRef.current?.abort(); const linkingController = new AbortController(); linkingAbortRef.current = linkingController;
862
887
  const suggestions = await fetchLinkingSuggestions(
863
888
  apiUrl,
864
889
  text,
865
890
  effectivePrimary,
866
891
  supportingKeywordsForLinking,
867
892
  documentId,
868
- effectivePublication
893
+ effectivePublication,
894
+ linkingController.signal
869
895
  );
896
+ // Superseded by a newer fetch (e.g. rapid re-click). Bail before the aborted call's
897
+ // empty result overwrites the good persisted suggestions.
898
+ if (linkingController.signal.aborted) return;
870
899
  if (linkingVersionRef.current !== myVersion) return;
871
900
  setLinkingSuggestions(suggestions);
872
901
  setLinkingFetchedText(text);
@@ -947,6 +976,16 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
947
976
  setIsLinkCheckLoading(false);
948
977
  }, [apiUrl, documentFields?.bodyLinks, setHasRunLinkCheck, setLinkCheckResults]);
949
978
 
979
+ // Cleanup any active drag/resize listeners if the component unmounts mid-gesture.
980
+ useEffect(() => {
981
+ return () => {
982
+ activeDragCleanupRef.current?.();
983
+ activeResizeCleanupRef.current?.();
984
+ csAbortRef.current?.abort();
985
+ linkingAbortRef.current?.abort();
986
+ };
987
+ }, []);
988
+
950
989
  const handleDragStart = useCallback(
951
990
  (e: React.MouseEvent) => {
952
991
  dragOffset.current = {
@@ -962,6 +1001,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
962
1001
  });
963
1002
  };
964
1003
  const onMouseUp = () => {
1004
+ activeDragCleanupRef.current = null;
965
1005
  dragOffset.current = null;
966
1006
  window.removeEventListener("mousemove", onMouseMove);
967
1007
  window.removeEventListener("mouseup", onMouseUp);
@@ -972,6 +1012,12 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
972
1012
  document.body.style.userSelect = "none";
973
1013
  window.addEventListener("mousemove", onMouseMove);
974
1014
  window.addEventListener("mouseup", onMouseUp);
1015
+ activeDragCleanupRef.current = () => {
1016
+ window.removeEventListener("mousemove", onMouseMove);
1017
+ window.removeEventListener("mouseup", onMouseUp);
1018
+ document.body.style.cursor = "";
1019
+ document.body.style.userSelect = "";
1020
+ };
975
1021
  },
976
1022
  [floatPos]
977
1023
  );
@@ -990,6 +1036,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
990
1036
  setFloatSize({ width: newW, height: newH });
991
1037
  };
992
1038
  const onMouseUp = () => {
1039
+ activeResizeCleanupRef.current = null;
993
1040
  resizeStart.current = null;
994
1041
  document.body.style.cursor = "";
995
1042
  document.body.style.userSelect = "";
@@ -998,6 +1045,12 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
998
1045
  };
999
1046
  window.addEventListener("mousemove", onMouseMove);
1000
1047
  window.addEventListener("mouseup", onMouseUp);
1048
+ activeResizeCleanupRef.current = () => {
1049
+ window.removeEventListener("mousemove", onMouseMove);
1050
+ window.removeEventListener("mouseup", onMouseUp);
1051
+ document.body.style.cursor = "";
1052
+ document.body.style.userSelect = "";
1053
+ };
1001
1054
  },
1002
1055
  [floatSize]
1003
1056
  );
@@ -65,6 +65,10 @@ export function ShimmerLoader({
65
65
  style.dataset.seoCopilotKeyframes = "1";
66
66
  style.innerHTML = KEYFRAMES;
67
67
  document.head.appendChild(style);
68
+ return () => {
69
+ try { document.head.removeChild(style); } catch { /* already removed */ }
70
+ keyframesInjected = false;
71
+ };
68
72
  }
69
73
  }, []);
70
74
 
@@ -185,6 +185,9 @@ export function TabBar({ tabs, activeTab, onTabChange }: TabBarProps) {
185
185
  const duration = Math.min(560, Math.max(280, Math.round(250 + dist * 0.6)));
186
186
  return { ...next, ready: true, duration };
187
187
  });
188
+ return () => {
189
+ if (clickTimerRef.current) clearTimeout(clickTimerRef.current);
190
+ };
188
191
  }, [activeTab, signature]);
189
192
 
190
193
  // Re-measure when the bar resizes (panel resize -> tabs may reflow / wrap).
@@ -1,4 +1,4 @@
1
- import { useMemo, useState } from "react";
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
2
  import { LoadingBars } from "../SEOCopilotPanel";
3
3
  import { FeedbackButton } from "../FeedbackButton";
4
4
  import { analyzeGEO } from "../../lib/geoAnalysis";
@@ -67,11 +67,13 @@ function SectionHeader({ label, iconColor, ai }: { label: string; iconColor: str
67
67
 
68
68
  function CopyButton({ text }: { text: string }) {
69
69
  const [copied, setCopied] = useState(false);
70
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
71
+ useEffect(() => { return () => { if (copyTimerRef.current) clearTimeout(copyTimerRef.current); }; }, []);
70
72
  const handleCopy = async () => {
71
73
  try {
72
74
  await navigator.clipboard.writeText(text);
73
75
  setCopied(true);
74
- setTimeout(() => setCopied(false), 1500);
76
+ copyTimerRef.current = setTimeout(() => setCopied(false), 1500);
75
77
  } catch {
76
78
  // silent
77
79
  }