-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
301 lines (266 loc) · 10.7 KB
/
background.js
File metadata and controls
301 lines (266 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// background.js — service worker
// Responsibilities:
// 1. Open side panel when toolbar icon clicked
// 2. Route messages between content.js <-> sidepanel.js
importScripts('platform-config.js', 'reporting-config.js');
// ── Open side panel on action click ──────────────────────────────────────────
chrome.action.onClicked.addListener(tab => {
chrome.sidePanel.open({ tabId: tab.id });
});
// ── Enable side panel for supported pages ─────────────────────────────────────
chrome.tabs.onUpdated.addListener((tabId, info, tab) => {
if (info.status !== 'complete') return;
const supported = cbvIsSupportedUrl(tab.url || '');
chrome.sidePanel.setOptions({
tabId,
enabled: supported,
path: 'sidepanel.html',
});
});
// ── Message routing ───────────────────────────────────────────────────────────
// content.js → background → sidepanel (content sends tree data / nav results)
// sidepanel → background → content (sidepanel sends nav commands)
// Keep track of UI ports (sidepanel/viewer) for a given tab
const uiPorts = new Map(); // tabId -> Set<port>
const reportedDiagnostics = new Map();
function getReportingConfig() {
return typeof cbvGetReportingConfig === 'function'
? cbvGetReportingConfig()
: { enabled: false };
}
function sanitizeText(value, limit = 240) {
return String(value || '').trim().replace(/\s+/g, ' ').slice(0, limit);
}
function sanitizeUrlForDiagnostics(input) {
try {
const parsed = new URL(String(input || ''));
const parts = parsed.pathname.split('/').filter(Boolean);
const first = parts[0] || '';
const second = parts[1] || '';
// Keep only route pattern, remove concrete identifiers/query/hash.
if (first === 'c') return `${parsed.origin}/c/:id`;
if (first === 'g') return `${parsed.origin}/g/:id`;
if (!first) return `${parsed.origin}/`;
if (second) return `${parsed.origin}/${first}/${second}`;
return `${parsed.origin}/${first}`;
} catch (_) {
return sanitizeText(input || '', 120);
}
}
function sanitizePageLabel(inputUrl, platform = '') {
const base = sanitizeText(platform || 'unknown', 24) || 'unknown';
try {
const path = new URL(String(inputUrl || '')).pathname || '/';
if (path.includes('/c/')) return `${base}:conversation`;
if (path.startsWith('/g/')) return `${base}:project`;
if (path.startsWith('/apps')) return `${base}:apps`;
return `${base}:page`;
} catch (_) {
return `${base}:page`;
}
}
function pruneReportedDiagnostics(now = Date.now()) {
const ttl = Number(getReportingConfig().dedupeWindowMs) || (30 * 60 * 1000);
for (const [key, ts] of reportedDiagnostics.entries()) {
if (now - ts > ttl) reportedDiagnostics.delete(key);
}
}
function buildReportKey(diagnostics) {
const broken = (diagnostics?.probe?.broken || []).join(',');
const url = (() => {
try {
const parsed = new URL(diagnostics?.url || '');
return `${parsed.origin}${parsed.pathname}`;
} catch (_) {
return sanitizeText(diagnostics?.url || '', 180);
}
})();
return [
sanitizeText(diagnostics?.platform, 24),
sanitizeText(diagnostics?.reason, 64),
broken,
url,
Number.isFinite(diagnostics?.turnCount) ? diagnostics.turnCount : 0,
].join('|');
}
function markDiagnosticSent(key) {
pruneReportedDiagnostics();
reportedDiagnostics.set(key, Date.now());
}
function wasDiagnosticRecentlySent(key) {
pruneReportedDiagnostics();
return reportedDiagnostics.has(key);
}
function sanitizeTurn(turn) {
return {
id: sanitizeText(turn?.id, 120),
turnIndex: Number.isFinite(turn?.turnIndex) ? turn.turnIndex : null,
branchIndex: Number.isFinite(turn?.branchIndex) ? turn.branchIndex : null,
role: sanitizeText(turn?.role, 24),
text: '',
};
}
function sanitizeDiagnostics(diagnostics) {
if (!diagnostics || typeof diagnostics !== 'object') return null;
return {
type: sanitizeText(diagnostics.type, 40) || 'selector-breakage',
reason: sanitizeText(diagnostics.reason, 80),
platform: sanitizeText(diagnostics.platform, 24),
platformLabel: sanitizeText(diagnostics.platformLabel, 40),
extensionVersion: sanitizeText(diagnostics.extensionVersion, 24),
selectorVersion: sanitizeText(diagnostics.selectorVersion, 40),
url: sanitizeUrlForDiagnostics(diagnostics.url),
ts: Number.isFinite(diagnostics.ts) ? diagnostics.ts : Date.now(),
turnCount: Number.isFinite(diagnostics.turnCount) ? diagnostics.turnCount : 0,
probe: {
platform: sanitizeText(diagnostics.probe?.platform, 24),
version: sanitizeText(diagnostics.probe?.version, 40),
ts: Number.isFinite(diagnostics.probe?.ts) ? diagnostics.probe.ts : null,
url: sanitizeUrlForDiagnostics(diagnostics.probe?.url),
hits: diagnostics.probe?.hits && typeof diagnostics.probe.hits === 'object' ? diagnostics.probe.hits : {},
broken: (Array.isArray(diagnostics.probe?.broken) ? diagnostics.probe.broken : []).map(item => sanitizeText(item, 60)),
},
extra: diagnostics.extra && typeof diagnostics.extra === 'object' ? diagnostics.extra : {},
activePath: (Array.isArray(diagnostics.activePath) ? diagnostics.activePath : []).slice(-4).map(sanitizeTurn),
visiblePath: (Array.isArray(diagnostics.visiblePath) ? diagnostics.visiblePath : []).slice(-4).map(sanitizeTurn),
domSummary: (Array.isArray(diagnostics.domSummary) ? diagnostics.domSummary : []).slice(0, 6).map(entry => ({
label: sanitizeText(entry?.label, 60),
count: Number.isFinite(entry?.count) ? entry.count : 0,
samples: (Array.isArray(entry?.samples) ? entry.samples : []).slice(0, 6).map(sample => ({
tag: sanitizeText(sample?.tag, 24),
testid: sanitizeText(sample?.testid, 80),
cls: sanitizeText(sample?.cls, 160),
text: '',
})),
})),
};
}
async function shouldAutoSendDiagnostics(diagnostics) {
const config = getReportingConfig();
if (!config.enabled || !config.endpoint) return false;
// Respect user consent stored by the side panel
try {
const result = await chrome.storage.local.get('cbv_consent');
const consent = result['cbv_consent'];
if (!consent?.decided || !consent?.autoSend) return false;
} catch (_) {
return false;
}
const platform = diagnostics?.platform || diagnostics?.probe?.platform;
if (platform !== 'chatgpt' && platform !== 'claude') return false;
const reason = diagnostics?.reason || '';
const broken = diagnostics?.probe?.broken || [];
return broken.length > 0 || reason === 'build_error' || reason === 'no_turns_detected' || reason === 'branch_navigation_warning';
}
async function postReport({ type, diagnostics, description = '', sender }) {
const config = getReportingConfig();
if (!config.enabled || !config.endpoint) return { ok: false, skipped: 'reporting_disabled' };
const sanitized = sanitizeDiagnostics(diagnostics);
if (!sanitized) return { ok: false, skipped: 'missing_diagnostics' };
const key = buildReportKey(sanitized);
if (type === 'auto_probe' && wasDiagnosticRecentlySent(key)) {
return { ok: true, deduped: true };
}
const controller = new AbortController();
const timeoutMs = Number(config.requestTimeoutMs) || 8000;
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(config.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CBV-Client': 'chrome-extension',
'X-CBV-Public-Key': config.publicKey || '',
},
body: JSON.stringify({
type,
source: 'chrome-extension',
client: 'chrome-extension',
publicKey: config.publicKey || '',
description: sanitizeText(description, 1500),
tabUrl: sanitizeUrlForDiagnostics(sender?.tab?.url || sanitized.url),
pageTitle: sanitizePageLabel(sender?.tab?.url || sanitized.url, sanitized.platform),
extensionVersion: sanitizeText(sanitized.extensionVersion, 24),
selectorVersion: sanitizeText(sanitized.selectorVersion, 40),
diagnostics: sanitized,
}),
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`Reporting endpoint failed: ${response.status}`);
}
if (type === 'auto_probe') markDiagnosticSent(key);
return { ok: true };
} finally {
clearTimeout(timer);
}
}
function addUiPort(tabId, port) {
if (!uiPorts.has(tabId)) uiPorts.set(tabId, new Set());
uiPorts.get(tabId).add(port);
}
function removeUiPort(tabId, port) {
const set = uiPorts.get(tabId);
if (!set) return;
set.delete(port);
if (!set.size) uiPorts.delete(tabId);
}
chrome.runtime.onConnect.addListener(port => {
if (port.name !== 'cbv-sidepanel' && port.name !== 'cbv-viewer') return;
// Figure out which tab this sidepanel belongs to
// (sidePanel port doesn't expose tabId directly — we ask the panel to send it)
let tabId = null;
port.onMessage.addListener(async msg => {
if (msg.type === 'REGISTER') {
if (tabId && tabId !== msg.tabId) removeUiPort(tabId, port);
tabId = msg.tabId;
if (tabId) addUiPort(tabId, port);
return;
}
// sidepanel → content: navigation / cancel commands
if ((msg.type === 'NAVIGATE' || msg.type === 'CANCEL') && tabId) {
chrome.tabs.sendMessage(tabId, msg).catch(() => {});
}
});
port.onDisconnect.addListener(() => {
if (tabId) removeUiPort(tabId, port);
});
});
// content.js → background → UI clients
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
const tabId = sender.tab?.id;
if (msg?.type === 'SUBMIT_REPORT') {
postReport({
type: msg.reportType === 'user_report' ? 'user_report' : 'auto_probe',
diagnostics: msg.diagnostics,
description: msg.description || '',
sender,
})
.then(result => sendResponse(result))
.catch(error => sendResponse({ ok: false, error: error.message }));
return true;
}
if (!tabId) return;
// Forward to all registered UIs for this tab
const ports = uiPorts.get(tabId);
if (ports) {
for (const port of ports) {
try { port.postMessage({ ...msg, tabId }); } catch (_) {}
}
}
if (msg?.type === 'PROBE_RESULT') {
shouldAutoSendDiagnostics(msg.diagnostics).then(should => {
if (!should) return;
postReport({
type: 'auto_probe',
diagnostics: msg.diagnostics,
sender,
}).catch(error => {
console.warn('CBV auto-report failed:', error);
});
});
}
// Always ACK
sendResponse({ ok: true });
return true;
});