cjc0013 commited on
Commit
a41ef0a
·
verified ·
1 Parent(s): da60aa6

Upload 9 files

Browse files

UPDATED VERSION

GPTTrafficgateUPDATEDv3.1/background.js ADDED
@@ -0,0 +1,1035 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // background.js — orchestrator-owned notifications, retries, ledger, and global budget
2
+ // Updated: v3.2 big-pass freshness contract + detector telemetry + bounded orch events
3
+ // Patch: v3.2.1 signal compatibility (freshnessTs/detectedReply) + stronger freshness normalization
4
+ // Patch: v3.2.2 popup-only notifications (hard mute; background-enforced silent meta)
5
+ // Patch: v3.2.3 reliability fix (cooldown queues detected replies + Firefox notify availability hardening)
6
+ // Patch: v3.2.4 pulse-compat hardening (detectedReplyPulse + signal ts fallback + cooldown accounting)
7
+ // Patch: v3.2.5 queue/freshness hardening (pulse fallback detectedTs + queue age telemetry + depth normalization)
8
+ const api = (typeof browser !== 'undefined') ? browser : chrome;
9
+
10
+ const BUILD_META = Object.freeze({
11
+ channel: 'local-temp-addon',
12
+ buildTag: 'v3.2.5-orchestrated-freshness-pulse-compat-silent-popup-reliable-detected-queue-age',
13
+ buildTs: '2026-02-13T22:15:00Z',
14
+ contract: 'tgReplyDetected.v3'
15
+ });
16
+
17
+ const GPT_URLS = ['https://chat.openai.com/*', 'https://chatgpt.com/*'];
18
+ const GPT_HOST_RE = /^(chat\.openai\.com|chatgpt\.com)$/;
19
+
20
+ let cfg = { blockHistory: true, debug: false };
21
+ const intent = new Map(); // tabId -> bool
22
+ const allowUntil = new Map(); // tabId -> ms timestamp
23
+ let leaderTabId = null;
24
+
25
+ /* ---------------------------
26
+ * Orchestrator + health model
27
+ * -------------------------- */
28
+ const orch = {
29
+ peers: new Map(), // tabId -> { ts, visible, streaming, pressure, role, seq, lastSignalTs, lastDetectedTs, lastStreamEndTs, detectorMisses, freshKind }
30
+ limits: { maxVisibleStreamers: 1, maxTotalStreamers: 2 },
31
+ events: [], // bounded diagnostics ring
32
+ health: {
33
+ // traffic
34
+ signals: 0,
35
+ detected_received: 0,
36
+ detected_accepted: 0,
37
+ detected_dropped: 0,
38
+
39
+ // drop reasons
40
+ dropped_invalid_payload: 0,
41
+ dropped_duplicate: 0,
42
+ dropped_cooldown: 0,
43
+ dropped_notifications_unavailable: 0,
44
+
45
+ // notify lifecycle
46
+ enqueued: 0,
47
+ sent: 0,
48
+ failed: 0,
49
+ fallback: 0,
50
+
51
+ // freshness / contract fields
52
+ lastSignalTs: 0,
53
+ lastDetectedTs: 0,
54
+ lastAcceptedTs: 0,
55
+ lastOkTs: 0,
56
+ lastStreamEndTs: 0,
57
+
58
+ // extra diagnostics
59
+ lastEventId: '',
60
+ lastNotifyVia: '',
61
+ lastSeenFreshKind: '',
62
+ detectorMisses: 0,
63
+ lastSignalAgeMs: 0,
64
+ lastDetectedAgeMs: 0
65
+ }
66
+ };
67
+
68
+ const notifyState = {
69
+ requested: 0,
70
+ sent: 0,
71
+ failed: 0,
72
+ retried: 0,
73
+ fallback: 0,
74
+ suppressed: 0,
75
+ queueDepth: 0,
76
+ lastError: '',
77
+ lastNotifyAt: 0,
78
+ lastEventId: '',
79
+ lastNotifyVia: ''
80
+ };
81
+
82
+ const runtimeConfig = {
83
+ notifyCooldownMs: 7000,
84
+ detectDedupeMs: 45000,
85
+ queueTtlMs: 180000,
86
+ maxQueue: 200,
87
+ maxLedger: 300,
88
+ maxRetry: 1,
89
+ maxOrchEvents: 400,
90
+
91
+ // Hard policy: popup notifications only; never sound from background.
92
+ forceSilentNotifications: true
93
+ };
94
+
95
+ const recentEventIds = new Map(); // eventId -> ts
96
+ let notifyQueue = []; // {eventId,title,message,ts,retries,lastErr,source}
97
+ let notifyLedger = []; // compact notify history
98
+
99
+ function logDbg(...args) {
100
+ try {
101
+ if (cfg.debug) console.log('[TrafficGate BG]', ...args);
102
+ } catch {}
103
+ }
104
+
105
+ function ageMs(ts) {
106
+ if (!ts || !Number.isFinite(ts)) return null;
107
+ return Math.max(0, Date.now() - ts);
108
+ }
109
+
110
+ function updateHealthAges() {
111
+ orch.health.lastSignalAgeMs = ageMs(orch.health.lastSignalTs) || 0;
112
+ orch.health.lastDetectedAgeMs = ageMs(orch.health.lastDetectedTs) || 0;
113
+ }
114
+
115
+ function queueAges() {
116
+ if (!notifyQueue.length) return { oldestAgeMs: 0, newestAgeMs: 0 };
117
+ const now = Date.now();
118
+ const ages = notifyQueue
119
+ .map((q) => ageMs(Number(q?.ts || 0)) || 0)
120
+ .filter((n) => Number.isFinite(n) && n >= 0);
121
+ if (!ages.length) return { oldestAgeMs: 0, newestAgeMs: 0 };
122
+ return {
123
+ oldestAgeMs: Math.max(...ages),
124
+ newestAgeMs: Math.min(...ages)
125
+ };
126
+ }
127
+
128
+ function updateQueueDepth() {
129
+ notifyState.queueDepth = notifyQueue.length;
130
+ }
131
+
132
+ function recordOrchEvent(kind, data) {
133
+ try {
134
+ const evt = {
135
+ ts: Date.now(),
136
+ kind: String(kind || 'unknown'),
137
+ ...(data || {})
138
+ };
139
+ orch.events.push(evt);
140
+ if (orch.events.length > runtimeConfig.maxOrchEvents) {
141
+ orch.events.splice(0, orch.events.length - runtimeConfig.maxOrchEvents);
142
+ }
143
+ } catch {}
144
+ }
145
+
146
+ function logNotify(evt) {
147
+ try {
148
+ notifyLedger.push({ ts: Date.now(), ...evt });
149
+ if (notifyLedger.length > runtimeConfig.maxLedger) {
150
+ notifyLedger.splice(0, notifyLedger.length - runtimeConfig.maxLedger);
151
+ }
152
+ } catch {}
153
+ }
154
+
155
+ function pruneRecentEventIds() {
156
+ const now = Date.now();
157
+ for (const [id, ts] of recentEventIds.entries()) {
158
+ if ((now - ts) > runtimeConfig.detectDedupeMs) recentEventIds.delete(id);
159
+ }
160
+ }
161
+
162
+ function eventSeenRecently(eventId) {
163
+ pruneRecentEventIds();
164
+ if (!eventId) return false;
165
+ return recentEventIds.has(eventId);
166
+ }
167
+
168
+ function markEventSeen(eventId) {
169
+ if (!eventId) return;
170
+ recentEventIds.set(eventId, Date.now());
171
+ }
172
+
173
+ function prunePeers() {
174
+ const now = Date.now();
175
+ for (const [id, st] of orch.peers.entries()) {
176
+ if (!st || (now - (st.ts || 0)) > 30000) orch.peers.delete(id);
177
+ }
178
+ }
179
+
180
+ function computeGlobalBudget() {
181
+ prunePeers();
182
+ let total = 0;
183
+ let visible = 0;
184
+ for (const st of orch.peers.values()) {
185
+ if (st?.streaming) {
186
+ total += 1;
187
+ if (st.visible) visible += 1;
188
+ }
189
+ }
190
+ return {
191
+ totalStreamers: total,
192
+ visibleStreamers: visible,
193
+ followerHold: (visible > orch.limits.maxVisibleStreamers) || (total > orch.limits.maxTotalStreamers)
194
+ };
195
+ }
196
+
197
+ async function broadcastBudget() {
198
+ const budget = computeGlobalBudget();
199
+ try {
200
+ const tabs = await api.tabs.query({ url: GPT_URLS });
201
+ for (const t of (tabs || [])) {
202
+ if (typeof t.id === 'number') {
203
+ api.tabs.sendMessage(t.id, { type: 'tgGlobalBudget', budget }).catch(() => {});
204
+ }
205
+ }
206
+ } catch {}
207
+ }
208
+
209
+ setInterval(() => {
210
+ updateHealthAges();
211
+ broadcastBudget().catch(() => {});
212
+ }, 3000);
213
+
214
+ async function canUseNotifications() {
215
+ try {
216
+ // Reliability rule:
217
+ // If notifications API exists, attempt create() and handle failures there.
218
+ // Avoid permissions.contains false-negatives (seen in Firefox contexts).
219
+ return !!(api.notifications && api.notifications.create);
220
+ } catch {
221
+ return false;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Normalize/strip any sound-related fields carried in from upstream.
227
+ * Background stays popup-only.
228
+ */
229
+ function normalizeNotifyMeta(meta) {
230
+ const inMeta = (meta && typeof meta === 'object') ? meta : {};
231
+ const normalized = {
232
+ eventId: String(inMeta.eventId || ''),
233
+ via: String(inMeta.via || 'unknown'),
234
+ source: String(inMeta.source || 'unknown'),
235
+
236
+ // hard mute contract
237
+ silent: true,
238
+ sound: false,
239
+ playSound: false,
240
+ beep: false,
241
+ audio: false
242
+ };
243
+
244
+ if (!runtimeConfig.forceSilentNotifications) {
245
+ // reserved path if policy is changed later
246
+ normalized.silent = !!inMeta.silent;
247
+ normalized.sound = !!inMeta.sound;
248
+ normalized.playSound = !!inMeta.playSound;
249
+ normalized.beep = !!inMeta.beep;
250
+ normalized.audio = !!inMeta.audio;
251
+ }
252
+
253
+ return normalized;
254
+ }
255
+
256
+ async function sendUserNotification(title, message, meta) {
257
+ const now = Date.now();
258
+ const metaNorm = normalizeNotifyMeta(meta);
259
+
260
+ if ((now - notifyState.lastNotifyAt) < runtimeConfig.notifyCooldownMs) {
261
+ notifyState.suppressed += 1;
262
+ recordOrchEvent('notify_suppressed_cooldown', {
263
+ eventId: metaNorm.eventId || '',
264
+ via: metaNorm.via || '',
265
+ silent: !!metaNorm.silent
266
+ });
267
+ return { ok: false, reason: 'cooldown' };
268
+ }
269
+
270
+ const canNotify = await canUseNotifications();
271
+ if (!canNotify) {
272
+ notifyState.failed += 1;
273
+ notifyState.lastError = 'notifications_unavailable';
274
+ orch.health.dropped_notifications_unavailable += 1;
275
+ orch.health.lastNotifyVia = String(metaNorm.via || 'unknown');
276
+ recordOrchEvent('notify_unavailable', {
277
+ eventId: metaNorm.eventId || '',
278
+ via: metaNorm.via || '',
279
+ silent: !!metaNorm.silent
280
+ });
281
+ return { ok: false, reason: 'notifications_unavailable' };
282
+ }
283
+
284
+ try {
285
+ const t = String(title || 'ChatGPT');
286
+ const m = String(message || '');
287
+
288
+ const id = `tg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
289
+ await api.notifications.create(id, {
290
+ type: 'basic',
291
+ iconUrl:
292
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHUlEQVR4nKWTvUoDQRSGv5mQpI0Q6QWFrY2FhY2Nha2VhY2NrY2FrY2FjY2NjY2FhY2Nha2NhY2FjY2Nha2N7M7M7uQ9+8w3fOec8B0rA2j5fM7cR9G3fA2t4E7t8AqYQ6iJmB3C8L8mC6aKQ3v4C2n0Q4S6n3dD1hQWq0cQz8q0j1NQF3n3m0vNq4D+L7aB2r8mV1wA0x9k2xD7i4GgLxq2y0Xq4Qz6QmM3d8s9Fv3qkzqfI4nWQb6h9B9m5m2o1oH0H8f4x8B8u7Q6C2tJQmK6Y7n5xwC9m2m6y8g5QvQf4Qq7m9mR1Q8j4gX7aGJ9Rz3m2m2QxkP0Hk8W2n3y0D8k1m1m6rj8g3wTj7QAAAABJRU5ErkJggg==',
293
+ title: t,
294
+ message: m
295
+ });
296
+
297
+ notifyState.sent += 1;
298
+ notifyState.lastNotifyAt = now;
299
+ notifyState.lastEventId = String(metaNorm.eventId || '');
300
+ notifyState.lastNotifyVia = String(metaNorm.via || 'unknown');
301
+
302
+ orch.health.sent += 1;
303
+ orch.health.lastOkTs = now;
304
+ orch.health.lastEventId = String(metaNorm.eventId || '');
305
+ orch.health.lastNotifyVia = String(metaNorm.via || 'unknown');
306
+
307
+ recordOrchEvent('notify_sent', {
308
+ eventId: metaNorm.eventId || '',
309
+ via: metaNorm.via || '',
310
+ source: metaNorm.source || '',
311
+ silent: !!metaNorm.silent
312
+ });
313
+
314
+ return { ok: true, reason: 'sent', id };
315
+ } catch (e) {
316
+ notifyState.failed += 1;
317
+ notifyState.lastError = String(e?.message || e || 'notify_exception');
318
+
319
+ orch.health.failed += 1;
320
+ orch.health.lastEventId = String(metaNorm.eventId || '');
321
+ orch.health.lastNotifyVia = String(metaNorm.via || 'unknown');
322
+
323
+ recordOrchEvent('notify_fail', {
324
+ eventId: metaNorm.eventId || '',
325
+ via: metaNorm.via || '',
326
+ source: metaNorm.source || '',
327
+ err: notifyState.lastError,
328
+ silent: !!metaNorm.silent
329
+ });
330
+
331
+ return { ok: false, reason: 'exception' };
332
+ }
333
+ }
334
+
335
+ function enqueueNotify(item) {
336
+ notifyQueue.push(item);
337
+ if (notifyQueue.length > runtimeConfig.maxQueue) {
338
+ notifyQueue.splice(0, notifyQueue.length - runtimeConfig.maxQueue);
339
+ }
340
+ updateQueueDepth();
341
+ }
342
+
343
+ function normalizeReplyDetectionPayload(msg, tabId) {
344
+ const eventIdRaw = (msg && typeof msg.eventId === 'string') ? msg.eventId.trim() : '';
345
+ const sourceRaw = (msg && typeof msg.source === 'string') ? msg.source.trim() : '';
346
+ const titleRaw = (msg && typeof msg.title === 'string') ? msg.title.trim() : 'ChatGPT';
347
+ const messageRaw = (msg && typeof msg.message === 'string') ? msg.message.trim() : 'Reply ready in another tab';
348
+ const roleHintRaw = (msg && typeof msg.roleHint === 'string') ? msg.roleHint.trim() : '';
349
+
350
+ const detectedTs = Number(msg?.detectedTs || 0);
351
+ const streamEndTs = Number(msg?.streamEndTs || 0);
352
+
353
+ const normalized = {
354
+ eventId: eventIdRaw || `evt_${Date.now()}_${tabId || 'na'}_${Math.random().toString(36).slice(2, 6)}`,
355
+ source: sourceRaw || 'unknown',
356
+ title: titleRaw || 'ChatGPT',
357
+ message: messageRaw || 'Reply ready in another tab',
358
+ roleHint: roleHintRaw || '',
359
+ detectedTs: Number.isFinite(detectedTs) && detectedTs > 0 ? detectedTs : Date.now(),
360
+ streamEndTs: Number.isFinite(streamEndTs) && streamEndTs > 0 ? streamEndTs : 0
361
+ };
362
+
363
+ const valid =
364
+ typeof normalized.eventId === 'string' &&
365
+ normalized.eventId.length >= 6 &&
366
+ typeof normalized.title === 'string' &&
367
+ normalized.title.length > 0 &&
368
+ typeof normalized.message === 'string' &&
369
+ normalized.message.length > 0 &&
370
+ typeof normalized.source === 'string' &&
371
+ normalized.source.length > 0;
372
+
373
+ return { valid, normalized };
374
+ }
375
+
376
+ function normalizeFreshKind(msg) {
377
+ const fk = String(msg?.freshKind || msg?.freshnessKind || '').trim();
378
+ if (fk) return fk;
379
+ return 'heartbeat';
380
+ }
381
+
382
+ function hasDetectedPulse(msg) {
383
+ return msg?.detectedReply === true || msg?.detectedReplyPulse === true || msg?.pulseDetected === true;
384
+ }
385
+
386
+ function normalizeSignalTs(msg) {
387
+ const raw = Number(msg?.lastSignalTs || msg?.freshnessTs || 0);
388
+ if (Number.isFinite(raw) && raw > 0) return raw;
389
+ return Date.now();
390
+ }
391
+
392
+ function normalizeDetectedTs(msg) {
393
+ const d = Number(msg?.lastDetectedTs || 0);
394
+ if (Number.isFinite(d) && d > 0) return d;
395
+
396
+ const se = Number(msg?.lastStreamEndTs || 0);
397
+ if (Number.isFinite(se) && se > 0) return se;
398
+
399
+ return normalizeSignalTs(msg);
400
+ }
401
+
402
+ function absorbFreshnessFromSignal(msg) {
403
+ const msgSignalTs = normalizeSignalTs(msg);
404
+ const msgDetectedTs = Number(msg?.lastDetectedTs || 0);
405
+ const msgStreamEndTs = Number(msg?.lastStreamEndTs || 0);
406
+ const msgDetectorMisses = Number(msg?.detectorMisses || 0);
407
+ const msgFreshKind = normalizeFreshKind(msg);
408
+
409
+ orch.health.lastSignalTs = Math.max(orch.health.lastSignalTs || 0, msgSignalTs);
410
+
411
+ if (Number.isFinite(msgDetectedTs) && msgDetectedTs > 0) {
412
+ orch.health.lastDetectedTs = Math.max(orch.health.lastDetectedTs || 0, msgDetectedTs);
413
+ }
414
+ if (Number.isFinite(msgStreamEndTs) && msgStreamEndTs > 0) {
415
+ orch.health.lastStreamEndTs = Math.max(orch.health.lastStreamEndTs || 0, msgStreamEndTs);
416
+ }
417
+ if (Number.isFinite(msgDetectorMisses) && msgDetectorMisses >= 0) {
418
+ orch.health.detectorMisses = Math.max(orch.health.detectorMisses || 0, msgDetectorMisses);
419
+ }
420
+ if (msgFreshKind) {
421
+ orch.health.lastSeenFreshKind = msgFreshKind;
422
+ }
423
+
424
+ // optional pulse path from heartbeat producer
425
+ if (hasDetectedPulse(msg)) {
426
+ orch.health.detected_received += 1;
427
+ const pulseTs = normalizeDetectedTs(msg);
428
+ orch.health.lastDetectedTs = Math.max(orch.health.lastDetectedTs || 0, pulseTs || Date.now());
429
+ orch.health.lastAcceptedTs = Date.now();
430
+
431
+ if (notifyQueue.length > 0) {
432
+ const qa = queueAges();
433
+ recordOrchEvent('queue_detected_pulse', {
434
+ via: 'signal',
435
+ depth: notifyQueue.length,
436
+ oldestAgeMs: qa.oldestAgeMs,
437
+ newestAgeMs: qa.newestAgeMs,
438
+ freshKind: msgFreshKind || ''
439
+ });
440
+ }
441
+
442
+ recordOrchEvent('detected_pulse', {
443
+ via: 'signal',
444
+ freshKind: msgFreshKind || '',
445
+ detectorMisses: Number(msgDetectorMisses || 0),
446
+ pulseTs
447
+ });
448
+ }
449
+ }
450
+
451
+ async function handleReplyDetected(msg, tabId) {
452
+ orch.health.detected_received += 1;
453
+ orch.health.lastDetectedTs = Date.now();
454
+
455
+ recordOrchEvent('detected_received', {
456
+ tabId,
457
+ eventId: String(msg?.eventId || ''),
458
+ source: String(msg?.source || '')
459
+ });
460
+
461
+ const { valid, normalized } = normalizeReplyDetectionPayload(msg, tabId);
462
+
463
+ if (!valid) {
464
+ orch.health.detected_dropped += 1;
465
+ orch.health.dropped_invalid_payload += 1;
466
+
467
+ logNotify({ via: 'detected', ok: false, reason: 'invalid_payload', raw: String(msg?.eventId || '') });
468
+ recordOrchEvent('detected_invalid', { tabId, rawEventId: String(msg?.eventId || '') });
469
+
470
+ return { ok: false, dropped: 'invalid_payload', budget: computeGlobalBudget() };
471
+ }
472
+
473
+ orch.health.lastEventId = normalized.eventId;
474
+ orch.health.lastDetectedTs = normalized.detectedTs || Date.now();
475
+ if (normalized.streamEndTs) {
476
+ orch.health.lastStreamEndTs = Math.max(orch.health.lastStreamEndTs || 0, normalized.streamEndTs);
477
+ }
478
+
479
+ if (eventSeenRecently(normalized.eventId)) {
480
+ orch.health.detected_dropped += 1;
481
+ orch.health.dropped_duplicate += 1;
482
+
483
+ logNotify({ via: 'detected', eventId: normalized.eventId, ok: false, reason: 'duplicate' });
484
+ recordOrchEvent('detected_duplicate', { tabId, eventId: normalized.eventId });
485
+
486
+ return { ok: false, dropped: 'duplicate', eventId: normalized.eventId, budget: computeGlobalBudget() };
487
+ }
488
+
489
+ markEventSeen(normalized.eventId);
490
+
491
+ const sendRes = await sendUserNotification(normalized.title, normalized.message, normalizeNotifyMeta({
492
+ eventId: normalized.eventId,
493
+ via: 'detected',
494
+ source: normalized.source
495
+ }));
496
+
497
+ notifyState.requested += 1;
498
+ orch.health.lastAcceptedTs = Date.now();
499
+ orch.health.detected_accepted += 1;
500
+
501
+ if (sendRes.ok) {
502
+ logNotify({ via: 'detected', eventId: normalized.eventId, ok: true, reason: 'sent', source: normalized.source, silent: true });
503
+ return { ok: true, eventId: normalized.eventId, sent: true, budget: computeGlobalBudget() };
504
+ }
505
+
506
+ // Reliability change: do NOT drop detected events on cooldown.
507
+ // Queue them so completion notifications are eventually delivered.
508
+ if (sendRes.reason === 'cooldown') {
509
+ notifyState.fallback += 1;
510
+ orch.health.fallback += 1;
511
+ orch.health.detected_dropped += 1;
512
+ orch.health.dropped_cooldown += 1;
513
+
514
+ enqueueNotify({
515
+ eventId: normalized.eventId,
516
+ title: normalized.title,
517
+ message: normalized.message,
518
+ source: normalized.source,
519
+ ts: Date.now(),
520
+ retries: 0,
521
+ lastErr: 'cooldown'
522
+ });
523
+
524
+ orch.health.enqueued += 1;
525
+ const qa = queueAges();
526
+ logNotify({ via: 'detected', eventId: normalized.eventId, ok: false, reason: 'queued_cooldown', silent: true });
527
+ recordOrchEvent('detected_enqueued_cooldown', {
528
+ tabId,
529
+ eventId: normalized.eventId,
530
+ depth: notifyQueue.length,
531
+ oldestAgeMs: qa.oldestAgeMs,
532
+ newestAgeMs: qa.newestAgeMs
533
+ });
534
+
535
+ return { ok: false, queued: true, dropped: 'cooldown', eventId: normalized.eventId, budget: computeGlobalBudget() };
536
+ }
537
+
538
+ enqueueNotify({
539
+ eventId: normalized.eventId,
540
+ title: normalized.title,
541
+ message: normalized.message,
542
+ source: normalized.source,
543
+ ts: Date.now(),
544
+ retries: 0,
545
+ lastErr: sendRes.reason || 'unknown'
546
+ });
547
+
548
+ orch.health.enqueued += 1;
549
+ const qa = queueAges();
550
+ logNotify({ via: 'detected', eventId: normalized.eventId, ok: false, reason: 'queued', err: sendRes.reason || '', silent: true });
551
+ recordOrchEvent('detected_enqueued', {
552
+ tabId,
553
+ eventId: normalized.eventId,
554
+ err: sendRes.reason || '',
555
+ depth: notifyQueue.length,
556
+ oldestAgeMs: qa.oldestAgeMs,
557
+ newestAgeMs: qa.newestAgeMs
558
+ });
559
+
560
+ return { ok: false, queued: true, eventId: normalized.eventId, budget: computeGlobalBudget() };
561
+ }
562
+
563
+ async function drainNotifyQueue() {
564
+ const now = Date.now();
565
+ const keep = [];
566
+
567
+ for (const item of notifyQueue) {
568
+ if (!item || !item.title) continue;
569
+ if ((now - (item.ts || now)) > runtimeConfig.queueTtlMs) {
570
+ recordOrchEvent('queue_drop_ttl', { eventId: item?.eventId || '' });
571
+ continue;
572
+ }
573
+
574
+ const sendRes = await sendUserNotification(item.title, item.message || '', normalizeNotifyMeta({
575
+ eventId: item.eventId || '',
576
+ via: 'queue-drain',
577
+ source: item.source || ''
578
+ }));
579
+
580
+ if (sendRes.ok) {
581
+ logNotify({ via: 'queue-drain', eventId: item.eventId || '', ok: true, silent: true });
582
+ continue;
583
+ }
584
+
585
+ if ((item.retries || 0) < runtimeConfig.maxRetry) {
586
+ item.retries = (item.retries || 0) + 1;
587
+ item.lastErr = sendRes.reason || 'retry_failed';
588
+ notifyState.retried += 1;
589
+ keep.push(item);
590
+
591
+ logNotify({ via: 'queue-drain', eventId: item.eventId || '', ok: false, reason: 'retry', err: item.lastErr, silent: true });
592
+ recordOrchEvent('queue_retry', {
593
+ eventId: item.eventId || '',
594
+ retries: item.retries,
595
+ err: item.lastErr
596
+ });
597
+ } else {
598
+ notifyState.fallback += 1;
599
+ orch.health.fallback += 1;
600
+ logNotify({ via: 'queue-drain', eventId: item.eventId || '', ok: false, reason: 'fallback', err: sendRes.reason || '', silent: true });
601
+ recordOrchEvent('queue_drop_fallback', {
602
+ eventId: item.eventId || '',
603
+ err: sendRes.reason || ''
604
+ });
605
+ }
606
+ }
607
+
608
+ notifyQueue = keep.slice(-50);
609
+ updateQueueDepth();
610
+ }
611
+
612
+ setInterval(() => {
613
+ drainNotifyQueue().catch(() => {});
614
+ }, 15000);
615
+
616
+ function isGptUrl(url) {
617
+ try {
618
+ const u = new URL(url);
619
+ return GPT_HOST_RE.test(u.hostname);
620
+ } catch {
621
+ return false;
622
+ }
623
+ }
624
+
625
+ async function getActiveTabId() {
626
+ try {
627
+ const tabs = await api.tabs.query({ active: true, currentWindow: true });
628
+ if (!tabs || !tabs.length) return null;
629
+ const t = tabs[0];
630
+ if (t && typeof t.id === 'number' && isGptUrl(t.url || '')) return t.id;
631
+ } catch {}
632
+ return null;
633
+ }
634
+
635
+ async function setLeader(tabId) {
636
+ try {
637
+ const newLeader = (typeof tabId === 'number') ? tabId : await getActiveTabId();
638
+ if (newLeader === leaderTabId) return;
639
+
640
+ const oldLeader = leaderTabId;
641
+ leaderTabId = newLeader;
642
+
643
+ if (typeof oldLeader === 'number') {
644
+ api.tabs.sendMessage(oldLeader, { type: 'tgRole', role: 'follower' }).catch(() => {});
645
+ }
646
+ if (typeof leaderTabId === 'number') {
647
+ api.tabs.sendMessage(leaderTabId, { type: 'tgRole', role: 'leader' }).catch(() => {});
648
+ }
649
+ } catch {}
650
+ }
651
+
652
+ // Wake the event page periodically (Firefox MV2/MV3 mixed behavior resilience)
653
+ try {
654
+ api.alarms?.create('tg-ping', { periodInMinutes: 4 });
655
+ } catch {}
656
+
657
+ (async () => {
658
+ try {
659
+ const got = await api.storage.local.get({ blockHistory: true, debug: false });
660
+ cfg.blockHistory = !!got.blockHistory;
661
+ cfg.debug = !!got.debug;
662
+ } catch {}
663
+ await setLeader(null);
664
+ })();
665
+
666
+ api.storage.onChanged.addListener((changes, area) => {
667
+ if (area !== 'local') return;
668
+ if (changes.blockHistory) cfg.blockHistory = !!changes.blockHistory.newValue;
669
+ if (changes.debug) cfg.debug = !!changes.debug.newValue;
670
+ });
671
+
672
+ // Cleanup per-tab state
673
+ try {
674
+ api.tabs?.onRemoved?.addListener((tabId) => {
675
+ try { intent.delete(tabId); } catch {}
676
+ try { allowUntil.delete(tabId); } catch {}
677
+ try { orch.peers.delete(tabId); } catch {}
678
+ if (leaderTabId === tabId) {
679
+ leaderTabId = null;
680
+ setLeader(null);
681
+ }
682
+ });
683
+
684
+ api.tabs?.onUpdated?.addListener((tabId, changeInfo, tab) => {
685
+ try {
686
+ if (!changeInfo) return;
687
+
688
+ if (changeInfo.url && !isGptUrl(changeInfo.url)) {
689
+ intent.delete(tabId);
690
+ allowUntil.delete(tabId);
691
+ orch.peers.delete(tabId);
692
+ if (leaderTabId === tabId) {
693
+ leaderTabId = null;
694
+ setLeader(null);
695
+ }
696
+ }
697
+
698
+ if (tab && tab.active && isGptUrl(tab.url || changeInfo.url || '')) {
699
+ setLeader(tabId);
700
+ }
701
+ } catch {}
702
+ });
703
+
704
+ api.tabs?.onActivated?.addListener(async (info) => {
705
+ try {
706
+ const tab = await api.tabs.get(info.tabId);
707
+ if (tab && isGptUrl(tab.url || '')) await setLeader(info.tabId);
708
+ } catch {}
709
+ });
710
+ } catch {}
711
+
712
+ async function anyGptTabsOpen() {
713
+ try {
714
+ const tabs = await api.tabs.query({ url: GPT_URLS });
715
+ return !!(tabs && tabs.length);
716
+ } catch {
717
+ return false;
718
+ }
719
+ }
720
+
721
+ async function bgPingOnce(url) {
722
+ try {
723
+ const ctl = new AbortController();
724
+ const t = setTimeout(() => { try { ctl.abort(); } catch {} }, 6000);
725
+ const res = await fetch(url, {
726
+ method: 'GET',
727
+ cache: 'no-store',
728
+ credentials: 'include',
729
+ signal: ctl.signal
730
+ });
731
+ clearTimeout(t);
732
+ return !!res;
733
+ } catch {
734
+ return false;
735
+ }
736
+ }
737
+
738
+ try {
739
+ api.alarms?.onAlarm?.addListener(async (a) => {
740
+ if (!a || a.name !== 'tg-ping') return;
741
+ if (!(await anyGptTabsOpen())) return;
742
+
743
+ await bgPingOnce('https://chatgpt.com/api/auth/session');
744
+ await bgPingOnce('https://chat.openai.com/api/auth/session');
745
+ });
746
+ } catch {}
747
+
748
+ function hasPagination(u) {
749
+ try {
750
+ const q = u.searchParams;
751
+ if (q.has('cursor') || q.has('before')) return true;
752
+ if (q.has('offset') && Number(q.get('offset')) > 0) return true;
753
+ if (q.has('page') && Number(q.get('page')) > 1) return true;
754
+ const dir = (q.get('direction') || '').toLowerCase();
755
+ if (/back|prev|previous/.test(dir)) return true;
756
+ } catch {}
757
+ return false;
758
+ }
759
+
760
+ function isHistoryLoad(details) {
761
+ try {
762
+ const u = new URL(details.url);
763
+ if (!GPT_HOST_RE.test(u.hostname)) return false;
764
+ const method = (details.method || 'GET').toUpperCase();
765
+ if (method !== 'GET' && method !== 'POST') return false;
766
+
767
+ const p = u.pathname.toLowerCase();
768
+
769
+ if (/\/api\/auth\/session$/.test(p)) return false;
770
+ if (/\/backend-api\/models$/.test(p)) return false;
771
+
772
+ const looksHistoryPath = /(backend-api\/conversation|backend-api\/conversations|backend-api\/messages|\/history|\/messages|\/conversation|\/threads|\/graphql|\/gql|\/v1\/messages|\/v1\/threads)/.test(p);
773
+ if (!looksHistoryPath) return false;
774
+
775
+ return hasPagination(u);
776
+ } catch {
777
+ return false;
778
+ }
779
+ }
780
+
781
+ try {
782
+ api.webRequest?.onBeforeRequest.addListener(
783
+ (details) => {
784
+ try {
785
+ if (!cfg.blockHistory) return {};
786
+ if (details.type !== 'xmlhttprequest' && details.type !== 'fetch') return {};
787
+
788
+ const tabId = details.tabId;
789
+ const now = Date.now();
790
+ const okByTimer = (allowUntil.get(tabId) || 0) > now;
791
+ const okByIntent = !!intent.get(tabId);
792
+
793
+ if (!okByTimer && !okByIntent && isHistoryLoad(details)) {
794
+ if (cfg.debug) console.log('[TrafficGate] CANCEL', details.url);
795
+ return { cancel: true };
796
+ }
797
+ } catch (e) {
798
+ console.warn('[TrafficGate] onBeforeRequest', e);
799
+ }
800
+ return {};
801
+ },
802
+ { urls: ['https://chat.openai.com/*', 'https://chatgpt.com/*'] },
803
+ ['blocking', 'requestBody']
804
+ );
805
+ } catch {}
806
+
807
+ function makeHealthSnapshot() {
808
+ updateHealthAges();
809
+ const budget = computeGlobalBudget();
810
+ const qAges = queueAges();
811
+
812
+ const healthOut = {
813
+ ...orch.health,
814
+ // explicit freshness ages (for panel)
815
+ lastSignalAgeMs: ageMs(orch.health.lastSignalTs) || 0,
816
+ lastDetectedAgeMs: ageMs(orch.health.lastDetectedTs) || 0,
817
+ lastAcceptedAgeMs: ageMs(orch.health.lastAcceptedTs) || 0,
818
+ lastNotifyOkAgeMs: ageMs(orch.health.lastOkTs) || 0
819
+ };
820
+
821
+ return {
822
+ ok: true,
823
+ build: BUILD_META,
824
+ stats: { ...notifyState },
825
+ queue: notifyQueue.length,
826
+ queueOldestAgeMs: qAges.oldestAgeMs,
827
+ queueNewestAgeMs: qAges.newestAgeMs,
828
+ last: notifyLedger.slice(-20),
829
+ orchestration: {
830
+ health: healthOut,
831
+ budget,
832
+ peers: orch.peers.size
833
+ },
834
+ freshness: {
835
+ lastSignalAgo: healthOut.lastSignalAgeMs,
836
+ lastDetectedAgo: healthOut.lastDetectedAgeMs,
837
+ lastAcceptedAgo: healthOut.lastAcceptedAgeMs,
838
+ lastNotifyOkAgo: healthOut.lastNotifyOkAgeMs
839
+ }
840
+ };
841
+ }
842
+
843
+ function makeDiagnostics() {
844
+ return {
845
+ ok: true,
846
+ build: BUILD_META,
847
+ cfg: { ...cfg },
848
+ runtimeConfig: { ...runtimeConfig },
849
+ leaderTabId,
850
+ intentSize: intent.size,
851
+ allowUntilSize: allowUntil.size,
852
+ peerIds: Array.from(orch.peers.keys()).slice(-50),
853
+ recentEventIds: Array.from(recentEventIds.keys()).slice(-50),
854
+ queueDepth: notifyQueue.length,
855
+ ledgerTail: notifyLedger.slice(-40),
856
+ orchEventsTail: orch.events.slice(-80),
857
+ health: makeHealthSnapshot()
858
+ };
859
+ }
860
+
861
+ api.runtime.onMessage.addListener((msg, sender) => {
862
+ const tabId = sender?.tab?.id;
863
+ // non-tab commands allowed
864
+ const hasTab = typeof tabId === 'number';
865
+
866
+ try {
867
+ if (msg?.type === 'tgGetBuildInfo') {
868
+ return Promise.resolve({ ok: true, build: BUILD_META });
869
+ }
870
+
871
+ if (msg?.type === 'tgDiagnostics') {
872
+ return Promise.resolve(makeDiagnostics());
873
+ }
874
+
875
+ if (msg?.type === 'tgNotifyHealth') {
876
+ return Promise.resolve(makeHealthSnapshot());
877
+ }
878
+
879
+ if (msg?.type === 'tgGetOrchEvents') {
880
+ const lim = Math.max(1, Math.min(300, Number(msg?.limit || 80)));
881
+ return Promise.resolve({ ok: true, events: orch.events.slice(-lim), build: BUILD_META });
882
+ }
883
+
884
+ if (!hasTab) return;
885
+
886
+ if (msg?.type === 'historyIntent') {
887
+ intent.set(tabId, !!msg.value);
888
+ return;
889
+ }
890
+
891
+ if (msg?.type === 'toggleBlockHistory') {
892
+ cfg.blockHistory = !!msg.value;
893
+ api.storage.local.set({ blockHistory: cfg.blockHistory });
894
+ return;
895
+ }
896
+
897
+ if (msg?.type === 'requestStatus') {
898
+ const role = (leaderTabId === tabId) ? 'leader' : 'follower';
899
+ return Promise.resolve({
900
+ blockHistory: cfg.blockHistory,
901
+ intent: !!intent.get(tabId),
902
+ allowUntil: allowUntil.get(tabId) || 0,
903
+ role,
904
+ build: BUILD_META
905
+ });
906
+ }
907
+
908
+ if (msg?.type === 'allowHistoryForMs') {
909
+ const ms = Math.max(2000, Math.min(60000, Number(msg.ms) || 10000));
910
+ const until = Date.now() + ms;
911
+ allowUntil.set(tabId, until);
912
+ setTimeout(() => {
913
+ if ((allowUntil.get(tabId) || 0) <= Date.now()) allowUntil.delete(tabId);
914
+ }, ms + 250);
915
+ return Promise.resolve({ ok: true, until });
916
+ }
917
+
918
+ if (msg?.type === 'becomeLeader') {
919
+ setLeader(tabId);
920
+ return Promise.resolve({ ok: true });
921
+ }
922
+
923
+ if (msg?.type === 'tgSignal') {
924
+ orch.health.signals += 1;
925
+ orch.health.lastSignalTs = Date.now();
926
+
927
+ absorbFreshnessFromSignal(msg);
928
+ updateHealthAges();
929
+
930
+ const peer = {
931
+ ts: Date.now(),
932
+ visible: !!msg.visible,
933
+ streaming: !!msg.streaming,
934
+ pressure: Number(msg.pressure || 0),
935
+ role: String(msg.role || 'follower'),
936
+ seq: Number(msg.seq || 0),
937
+
938
+ lastSignalTs: normalizeSignalTs(msg),
939
+ lastDetectedTs: normalizeDetectedTs(msg),
940
+ lastStreamEndTs: Number(msg.lastStreamEndTs || 0),
941
+ detectorMisses: Number(msg.detectorMisses || 0),
942
+ freshKind: normalizeFreshKind(msg)
943
+ };
944
+
945
+ orch.peers.set(tabId, peer);
946
+
947
+ if (peer.detectorMisses > 0) {
948
+ orch.health.detectorMisses = Math.max(orch.health.detectorMisses || 0, peer.detectorMisses);
949
+ }
950
+ if (peer.lastStreamEndTs > 0) {
951
+ orch.health.lastStreamEndTs = Math.max(orch.health.lastStreamEndTs || 0, peer.lastStreamEndTs);
952
+ }
953
+ if (peer.lastDetectedTs > 0) {
954
+ orch.health.lastDetectedTs = Math.max(orch.health.lastDetectedTs || 0, peer.lastDetectedTs);
955
+ }
956
+ if (peer.freshKind) {
957
+ orch.health.lastSeenFreshKind = peer.freshKind;
958
+ }
959
+
960
+ recordOrchEvent('signal', {
961
+ tabId,
962
+ visible: peer.visible ? 1 : 0,
963
+ streaming: peer.streaming ? 1 : 0,
964
+ pressure: peer.pressure,
965
+ role: peer.role,
966
+ freshKind: peer.freshKind || '',
967
+ detectedTs: peer.lastDetectedTs || 0
968
+ });
969
+
970
+ const budget = computeGlobalBudget();
971
+ return Promise.resolve({ ok: true, budget });
972
+ }
973
+
974
+ if (msg?.type === 'tgReplyDetected') {
975
+ return handleReplyDetected(msg, tabId);
976
+ }
977
+
978
+ if (msg?.type === 'tgNotify') {
979
+ notifyState.requested += 1;
980
+ const title = String(msg?.title || 'ChatGPT');
981
+ const message = String(msg?.message || 'Reply ready in another tab');
982
+ const eventId = String(msg?.eventId || `manual_${Date.now()}`);
983
+
984
+ return sendUserNotification(title, message, normalizeNotifyMeta({
985
+ eventId,
986
+ via: 'notify',
987
+ source: 'manual_notify'
988
+ })).then((res) => {
989
+ if (!res.ok) {
990
+ enqueueNotify({
991
+ eventId,
992
+ title,
993
+ message,
994
+ source: 'manual_notify',
995
+ ts: Date.now(),
996
+ retries: 0,
997
+ lastErr: res.reason || 'send_failed'
998
+ });
999
+ }
1000
+ logNotify({ via: 'notify', eventId, ok: !!res.ok, reason: res.reason || '', silent: true });
1001
+ return { ok: !!res.ok, via: 'notify', reason: res.reason || '', stats: notifyState };
1002
+ });
1003
+ }
1004
+
1005
+ if (msg?.type === 'tgNotifyRetry') {
1006
+ notifyState.retried += 1;
1007
+ const title = String(msg?.title || 'ChatGPT');
1008
+ const message = String(msg?.message || 'Reply ready in another tab');
1009
+ const eventId = String(msg?.eventId || `retry_${Date.now()}`);
1010
+
1011
+ return sendUserNotification(title, message, normalizeNotifyMeta({
1012
+ eventId,
1013
+ via: 'retry',
1014
+ source: 'manual_retry'
1015
+ })).then((res) => {
1016
+ if (!res.ok) {
1017
+ enqueueNotify({
1018
+ eventId,
1019
+ title,
1020
+ message,
1021
+ source: 'manual_retry',
1022
+ ts: Date.now(),
1023
+ retries: 1,
1024
+ lastErr: res.reason || 'retry_failed'
1025
+ });
1026
+ }
1027
+ logNotify({ via: 'retry', eventId, ok: !!res.ok, reason: res.reason || '', silent: true });
1028
+ return { ok: !!res.ok, via: 'retry', reason: res.reason || '', stats: notifyState };
1029
+ });
1030
+ }
1031
+ } catch (e) {
1032
+ console.warn('[TrafficGate] bg onMessage error', e);
1033
+ return Promise.resolve({ ok: false, error: String(e?.message || e || 'unknown') });
1034
+ }
1035
+ });
GPTTrafficgateUPDATEDv3.1/content/autopilot.js ADDED
@@ -0,0 +1,1053 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // content/autopilot.js — autonomous adaptive controller (clean contract version)
2
+ // Scope: controller state + reply detection + tgSignal/tgReplyDetected + UI events only.
3
+ // No duplicate detector blocks, no global telemetry redefinition, no shadow symbol collisions.
4
+
5
+ (function () {
6
+ 'use strict';
7
+
8
+ const api = (typeof browser !== 'undefined') ? browser : chrome;
9
+
10
+ // Canonical notification audio policy for this module (popup yes, sound no)
11
+ const NOTIFY_SOUND_ENABLED = false;
12
+
13
+ // -------------------------
14
+ // Safe runtime messaging
15
+ // -------------------------
16
+ function sendMessageSafe(msg) {
17
+ return new Promise((resolve, reject) => {
18
+ try {
19
+ const maybe = api?.runtime?.sendMessage?.(msg);
20
+ if (maybe && typeof maybe.then === 'function') {
21
+ maybe.then(resolve).catch(reject);
22
+ return;
23
+ }
24
+ api.runtime.sendMessage(msg, (resp) => {
25
+ try {
26
+ const err = chrome?.runtime?.lastError;
27
+ if (err) reject(err);
28
+ else resolve(resp);
29
+ } catch {
30
+ resolve(resp);
31
+ }
32
+ });
33
+ } catch (e) {
34
+ reject(e);
35
+ }
36
+ });
37
+ }
38
+
39
+ const clamp = (n, min, max) => Math.max(min, Math.min(max, n));
40
+ const nowMs = () => Date.now();
41
+
42
+ function dispatchEventSafe(name, detail) {
43
+ try { window.dispatchEvent(new CustomEvent(name, { detail })); } catch {}
44
+ }
45
+
46
+ // -------------------------
47
+ // Shared core helpers (consume-only; no re-register)
48
+ // -------------------------
49
+ const tgCore = window.__tgCore || null;
50
+ const stableJsonDumps =
51
+ (tgCore && typeof tgCore.getCanonical === 'function' && tgCore.getCanonical('stable_json_dumps')) ||
52
+ ((value) => {
53
+ const seen = new WeakSet();
54
+ const walk = (v) => {
55
+ if (v === null || typeof v !== 'object') return v;
56
+ if (seen.has(v)) return '[Circular]';
57
+ seen.add(v);
58
+ if (Array.isArray(v)) return v.map(walk);
59
+ const out = {};
60
+ for (const k of Object.keys(v).sort()) out[k] = walk(v[k]);
61
+ return out;
62
+ };
63
+ return JSON.stringify(walk(value));
64
+ });
65
+
66
+ // -------------------------
67
+ // Controller state
68
+ // -------------------------
69
+ const TAB_ID = `${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
70
+ const COORD_CH = (window.BroadcastChannel ? new BroadcastChannel('tg_multi_tab_coord_v1') : null);
71
+
72
+ const cfg = {
73
+ role: 'follower',
74
+ leader: false,
75
+
76
+ profile: 'balanced',
77
+ pressure: 0,
78
+
79
+ // intent-driven locality
80
+ topPx: 160,
81
+ minTopPx: 80,
82
+
83
+ // adaptive baselines
84
+ baselinePressure: 28,
85
+ baselineLongtasks: 1,
86
+ baselineTurns: 55,
87
+ baselineLagMs: 40,
88
+ baselineSamples: 0,
89
+
90
+ // persistence cadence
91
+ lastPersistTs: 0,
92
+ lastProfileSwitchTs: 0,
93
+
94
+ // user activity
95
+ lastInputTs: Date.now(),
96
+
97
+ // hysteresis cooldown
98
+ coolDownUntil: 0
99
+ };
100
+
101
+ const stats = {
102
+ // low-level hooks emit to window.__tgTelemetry (defined elsewhere)
103
+ cancels: 0,
104
+ disconnects: 0,
105
+ longtasks: 0,
106
+ lastTurnCount: 0,
107
+ streamActive: false,
108
+ eventLoopLagMs: 0,
109
+ eventLoopLagHits: 0
110
+ };
111
+
112
+ const detector = {
113
+ lastBusy: false,
114
+ lastAssistantCount: 0,
115
+ lastDetectorEmitTs: 0,
116
+ detectorSeq: 0,
117
+ detectorMisses: 0,
118
+ lastDetectedTs: 0,
119
+ lastStreamStartTs: 0,
120
+ lastStreamEndTs: 0,
121
+
122
+ // selector hit telemetry
123
+ busyHits: {
124
+ explicit: 0,
125
+ buttonText: 0,
126
+ sendDisabled: 0,
127
+ fallback: 0
128
+ },
129
+
130
+ // stabilization fallback state
131
+ lastAssistantHash: '',
132
+ lastAssistantTextLen: 0,
133
+ lastAssistantChangeTs: 0,
134
+ lastStableCandidateTs: 0,
135
+ lastStableEmitTs: 0,
136
+ stabilizerArmed: false,
137
+
138
+ // forced flush guard
139
+ flushInFlight: false
140
+ };
141
+
142
+ const fresh = {
143
+ seq: 0,
144
+ lastSignalTs: 0,
145
+ lastDetectedTs: 0,
146
+ lastStreamEndTs: 0,
147
+ lastKind: 'boot'
148
+ };
149
+
150
+ let globalBudget = { totalStreamers: 0, visibleStreamers: 0, followerHold: false };
151
+ const peers = new Map(); // from BroadcastChannel
152
+
153
+ let replySeq = 0;
154
+ let pendingDetectedReplyPulse = false;
155
+ let lastReplySignalAtMs = 0;
156
+ let lastHeartbeatAtMs = 0;
157
+
158
+ const PROFILES = {
159
+ flow: { topPx: 120 },
160
+ balanced: { topPx: 160 },
161
+ hidden: { topPx: 100 },
162
+ recovery: { topPx: 90 }
163
+ };
164
+
165
+ const HYST = {
166
+ enterRecovery: 70,
167
+ exitRecovery: 42,
168
+ enterFlow: 55,
169
+ exitFlow: 62,
170
+ minSwitchGapMs: 6000,
171
+ recoveryCooldownMs: 120000
172
+ };
173
+
174
+ // stabilization fallback tuning
175
+ const STABILIZER = {
176
+ minChars: 24,
177
+ stableForMs: 900,
178
+ emitCooldownMs: 5500
179
+ };
180
+
181
+ // -------------------------
182
+ // Freshness / UI event emitters
183
+ // -------------------------
184
+ function emitFreshness(kind, extra) {
185
+ const k = String(kind || 'tick');
186
+ fresh.lastKind = k;
187
+
188
+ const payload = Object.assign({
189
+ kind: k,
190
+ ts: nowMs(),
191
+ tabId: TAB_ID,
192
+ visible: document.visibilityState === 'visible',
193
+ streamActive: !!stats.streamActive,
194
+ profile: cfg.profile,
195
+ pressure: Number(cfg.pressure || 0),
196
+ role: cfg.role,
197
+ seq: fresh.seq
198
+ }, extra || {});
199
+
200
+ dispatchEventSafe('tg:signal-freshness', payload);
201
+ }
202
+
203
+ function emitPerfProfile(reason) {
204
+ const localBudget = computeLocalBudget();
205
+
206
+ const bgTotal = Number(globalBudget?.totalStreamers || 0);
207
+ const bgVisible = Number(globalBudget?.visibleStreamers || 0);
208
+
209
+ const totalStreamers = bgTotal > 0 ? bgTotal : Number(localBudget.totalStreamers || 0);
210
+ const visibleStreamers = bgVisible > 0 ? bgVisible : Number(localBudget.visibleStreamers || 0);
211
+
212
+ const followerThrottle =
213
+ (typeof globalBudget?.followerHold === 'boolean')
214
+ ? !!(globalBudget.followerHold && cfg.role !== 'leader')
215
+ : !!(cfg.role !== 'leader' && (visibleStreamers > 1 || totalStreamers > 2));
216
+
217
+ const payload = {
218
+ profile: cfg.profile,
219
+ pressure: cfg.pressure,
220
+ role: cfg.role,
221
+ streamActive: !!stats.streamActive,
222
+ visible: document.visibilityState === 'visible',
223
+ followerThrottle,
224
+ totalStreamers,
225
+ visibleStreamers,
226
+ reason: String(reason || 'tick'),
227
+ ts: nowMs()
228
+ };
229
+ try { window.__tgPerfState = payload; } catch {}
230
+ dispatchEventSafe('tg:perf-profile', payload);
231
+ }
232
+
233
+ function emitReplyReadyLocal(detail) {
234
+ const d = Object.assign({}, detail || {});
235
+ if (!NOTIFY_SOUND_ENABLED) {
236
+ d.muteSound = true;
237
+ d.sound = false;
238
+ }
239
+ dispatchEventSafe('tg:reply-ready', d);
240
+ emitFreshness('reply_detected', {
241
+ eventId: d?.eventId || '',
242
+ reason: d?.source || 'unknown',
243
+ replySeq: d?.replySeq || 0
244
+ });
245
+ }
246
+
247
+ // -------------------------
248
+ // Telemetry ingestion (consume-only)
249
+ // -------------------------
250
+ function ingestTelemetryEvent(event, data) {
251
+ try {
252
+ if (event === 'historyCancel') stats.cancels += 1;
253
+ else if (event === 'disconnect') stats.disconnects += 1;
254
+ else if (event === 'turnCount' && typeof data?.count === 'number') stats.lastTurnCount = data.count;
255
+ else if (event === 'streamActive') {
256
+ const prev = !!stats.streamActive;
257
+ const next = !!data?.active;
258
+ stats.streamActive = next;
259
+
260
+ if (next && !prev) {
261
+ detector.lastStreamStartTs = nowMs();
262
+ emitFreshness('stream_transition', { transition: 'start', streamStartTs: detector.lastStreamStartTs });
263
+ } else if (prev && !next) {
264
+ detector.lastStreamEndTs = nowMs();
265
+ fresh.lastStreamEndTs = detector.lastStreamEndTs;
266
+ emitFreshness('stream_transition', { transition: 'end', streamEndTs: detector.lastStreamEndTs });
267
+ emitReplyFinished('stream-transition').catch(() => {});
268
+ }
269
+ }
270
+ } catch {}
271
+ }
272
+
273
+ // Consume events from net-guard/dom-softcap/keepalive via core bus if available
274
+ if (tgCore && typeof tgCore.on === 'function') {
275
+ try {
276
+ tgCore.on('tg:telemetry', (d) => ingestTelemetryEvent(d?.event, d?.data));
277
+ } catch {}
278
+ }
279
+
280
+ // Compatibility path: if an existing sink exists, wrap it instead of redefining global symbol.
281
+ try {
282
+ const existingSink = window.__tgTelemetry;
283
+ if (typeof existingSink === 'function' && !window.__tgTelemetryWrappedByAutopilot) {
284
+ window.__tgTelemetryWrappedByAutopilot = true;
285
+ window.__tgTelemetry = function wrappedTelemetry(event, data) {
286
+ try { ingestTelemetryEvent(event, data); } catch {}
287
+ try { return existingSink.apply(this, arguments); } catch { return undefined; }
288
+ };
289
+ }
290
+ } catch {}
291
+
292
+ // -------------------------
293
+ // Reply detection (single detector pipeline)
294
+ // -------------------------
295
+ function getAssistantTurnCount() {
296
+ try {
297
+ const a = document.querySelectorAll('[data-message-author-role="assistant"]').length;
298
+ const b = document.querySelectorAll('[data-testid^="conversation-turn-"]').length;
299
+ const c = document.querySelectorAll('article[data-testid*="conversation-turn"]').length;
300
+ return Math.max(a, b, c, 0);
301
+ } catch {
302
+ return 0;
303
+ }
304
+ }
305
+
306
+ function getLastAssistantText() {
307
+ try {
308
+ const nodes = document.querySelectorAll('[data-message-author-role="assistant"]');
309
+ if (!nodes || !nodes.length) return '';
310
+ const last = nodes[nodes.length - 1];
311
+ const txt = (last?.innerText || last?.textContent || '').replace(/\s+/g, ' ').trim();
312
+ return txt;
313
+ } catch {
314
+ return '';
315
+ }
316
+ }
317
+
318
+ function quickHash(s) {
319
+ // fast deterministic 32-bit hash string form
320
+ let h = 2166136261 >>> 0;
321
+ for (let i = 0; i < s.length; i++) {
322
+ h ^= s.charCodeAt(i);
323
+ h = Math.imul(h, 16777619);
324
+ }
325
+ return (h >>> 0).toString(16);
326
+ }
327
+
328
+ function detectDomBusy() {
329
+ try {
330
+ // 1) Explicit selectors (legacy + current variants)
331
+ const explicitSelectors = [
332
+ '[data-testid*="stop"]',
333
+ '[data-testid*="regenerate"]',
334
+ 'button[aria-label*="Stop"]',
335
+ 'button[aria-label*="Stop generating"]',
336
+ 'button[aria-label*="Stop streaming"]',
337
+ '[data-is-streaming="true"]',
338
+ '[aria-busy="true"]',
339
+ '.result-streaming',
340
+ '[class*="typing"]'
341
+ ];
342
+ const explicit = document.querySelectorAll(explicitSelectors.join(',')).length > 0;
343
+ if (explicit) {
344
+ detector.busyHits.explicit += 1;
345
+ return true;
346
+ }
347
+
348
+ // 2) Robust button text fallback
349
+ const btns = Array.from(document.querySelectorAll('button'));
350
+ for (const b of btns) {
351
+ const txt = (b.textContent || '').trim().toLowerCase();
352
+ const aria = (b.getAttribute('aria-label') || '').trim().toLowerCase();
353
+ const title = (b.getAttribute('title') || '').trim().toLowerCase();
354
+ const blob = `${txt} ${aria} ${title}`;
355
+
356
+ if (
357
+ blob.includes('stop generating') ||
358
+ blob.includes('stop streaming') ||
359
+ blob === 'stop' ||
360
+ blob.includes('thinking') ||
361
+ blob.includes('cancel')
362
+ ) {
363
+ detector.busyHits.buttonText += 1;
364
+ return true;
365
+ }
366
+ }
367
+
368
+ // 3) Composer/send-state heuristic
369
+ const sendBtn = document.querySelector('button[data-testid*="send"], form button[type="submit"]');
370
+ if (sendBtn && sendBtn.disabled) {
371
+ detector.busyHits.sendDisabled += 1;
372
+ return true;
373
+ }
374
+
375
+ return false;
376
+ } catch {
377
+ detector.busyHits.fallback += 1;
378
+ return !!stats.streamActive;
379
+ }
380
+ }
381
+
382
+ async function emitReplyFinished(source) {
383
+ const t = nowMs();
384
+ const minGapMs = 3500;
385
+
386
+ // hard dedupe
387
+ if ((t - lastReplySignalAtMs) < minGapMs) return;
388
+ if ((t - detector.lastDetectorEmitTs) < minGapMs) return;
389
+
390
+ detector.lastDetectorEmitTs = t;
391
+ detector.lastDetectedTs = t;
392
+ fresh.lastDetectedTs = t;
393
+ lastReplySignalAtMs = t;
394
+ pendingDetectedReplyPulse = true;
395
+
396
+ replySeq += 1;
397
+ detector.detectorSeq += 1;
398
+
399
+ const eventId = `reply_${TAB_ID}_${t}_${detector.detectorSeq}`;
400
+ const localDetail = {
401
+ tabId: TAB_ID,
402
+ replySeq,
403
+ source: source || 'unknown',
404
+ title: document.title || 'ChatGPT replied',
405
+ ts: t,
406
+ eventId
407
+ };
408
+
409
+ // UI/local path
410
+ emitReplyReadyLocal(localDetail);
411
+
412
+ // Background broker path (authoritative notify flow)
413
+ try {
414
+ const msg = {
415
+ type: 'tgReplyDetected',
416
+ eventId,
417
+ source: `autopilot:${source || 'unknown'}`,
418
+ detectedTs: t,
419
+ streamEndTs: detector.lastStreamEndTs || 0,
420
+ title: 'ChatGPT',
421
+ message: 'Reply finished in another tab',
422
+ roleHint: cfg.role || 'follower'
423
+ };
424
+ if (!NOTIFY_SOUND_ENABLED) {
425
+ msg.muteSound = true;
426
+ msg.sound = false;
427
+ msg.silent = true;
428
+ }
429
+ await sendMessageSafe(msg);
430
+ } catch {}
431
+
432
+ // Peer hint path
433
+ if (COORD_CH) {
434
+ try {
435
+ const peerMsg = {
436
+ type: 'reply-ready',
437
+ tabId: TAB_ID,
438
+ ts: t,
439
+ replySeq,
440
+ source: source || 'unknown',
441
+ eventId
442
+ };
443
+ if (!NOTIFY_SOUND_ENABLED) {
444
+ peerMsg.muteSound = true;
445
+ peerMsg.sound = false;
446
+ peerMsg.silent = true;
447
+ }
448
+ COORD_CH.postMessage(peerMsg);
449
+ } catch {}
450
+ }
451
+
452
+ // Flush detector freshness immediately so bg health/UI are not stale.
453
+ if (!detector.flushInFlight) {
454
+ detector.flushInFlight = true;
455
+ try { await sendSignal({ force: true }); } catch {}
456
+ detector.flushInFlight = false;
457
+ }
458
+ }
459
+
460
+ function evaluateStabilizedReply(busy, source) {
461
+ try {
462
+ const t = nowMs();
463
+ const txt = getLastAssistantText();
464
+ if (!txt || txt.length < STABILIZER.minChars) {
465
+ detector.stabilizerArmed = false;
466
+ return;
467
+ }
468
+
469
+ const h = quickHash(txt);
470
+ const changed = (h !== detector.lastAssistantHash) || (txt.length !== detector.lastAssistantTextLen);
471
+
472
+ if (changed) {
473
+ detector.lastAssistantHash = h;
474
+ detector.lastAssistantTextLen = txt.length;
475
+ detector.lastAssistantChangeTs = t;
476
+ detector.lastStableCandidateTs = t;
477
+ detector.stabilizerArmed = true;
478
+ return;
479
+ }
480
+
481
+ if (!detector.stabilizerArmed) return;
482
+ if (busy) return;
483
+
484
+ const stableFor = t - (detector.lastAssistantChangeTs || t);
485
+ const emitAgo = t - (detector.lastStableEmitTs || 0);
486
+
487
+ if (stableFor >= STABILIZER.stableForMs && emitAgo >= STABILIZER.emitCooldownMs) {
488
+ detector.lastStableEmitTs = t;
489
+ detector.stabilizerArmed = false;
490
+
491
+ emitFreshness('stabilized_candidate', {
492
+ source: source || 'stabilizer',
493
+ stableForMs: stableFor,
494
+ textLen: txt.length
495
+ });
496
+
497
+ emitReplyFinished(`${source || 'stabilizer'}-stable`).catch(() => {});
498
+ }
499
+ } catch {}
500
+ }
501
+
502
+ async function handleBusyEdge(nextBusy, source) {
503
+ const prevBusy = !!detector.lastBusy;
504
+ const nowBusy = !!nextBusy;
505
+ if (prevBusy === nowBusy) return;
506
+
507
+ detector.lastBusy = nowBusy;
508
+ stats.streamActive = nowBusy;
509
+
510
+ if (nowBusy) {
511
+ detector.lastStreamStartTs = nowMs();
512
+ emitFreshness('stream_transition', {
513
+ transition: 'start',
514
+ source: source || 'edge',
515
+ streamStartTs: detector.lastStreamStartTs
516
+ });
517
+ await sendSignal({ force: true });
518
+ return;
519
+ }
520
+
521
+ detector.lastStreamEndTs = nowMs();
522
+ fresh.lastStreamEndTs = detector.lastStreamEndTs;
523
+
524
+ emitFreshness('stream_transition', {
525
+ transition: 'end',
526
+ source: source || 'edge',
527
+ streamEndTs: detector.lastStreamEndTs
528
+ });
529
+
530
+ // Ensure detected state is stamped before final forced signal.
531
+ await emitReplyFinished(`${source || 'edge'}-end`);
532
+ await sendSignal({ force: true });
533
+ }
534
+
535
+ let replyObserver = null;
536
+ function startReplyObserver() {
537
+ if (replyObserver) return;
538
+ const root = document.querySelector('main') || document.body;
539
+ if (!root) return;
540
+
541
+ detector.lastBusy = detectDomBusy();
542
+ detector.lastAssistantCount = getAssistantTurnCount();
543
+ stats.streamActive = !!detector.lastBusy;
544
+
545
+ replyObserver = new MutationObserver(() => {
546
+ const busy = detectDomBusy();
547
+ const turns = getAssistantTurnCount();
548
+
549
+ // Busy edge handling (start/end)
550
+ handleBusyEdge(busy, 'dom-observer').catch(() => {});
551
+
552
+ // New assistant turn while idle
553
+ if (!busy && turns > detector.lastAssistantCount) {
554
+ emitReplyFinished('dom-turn-growth').catch(() => {});
555
+ }
556
+
557
+ // Content stabilization fallback
558
+ evaluateStabilizedReply(busy, 'dom-observer');
559
+
560
+ detector.lastBusy = busy;
561
+ stats.streamActive = !!busy;
562
+ detector.lastAssistantCount = turns;
563
+ });
564
+
565
+ replyObserver.observe(root, { childList: true, subtree: true, attributes: true });
566
+ }
567
+
568
+ // -------------------------
569
+ // Cross-tab coordination / budget
570
+ // -------------------------
571
+ function prunePeers() {
572
+ const t = nowMs();
573
+ for (const [k, v] of peers.entries()) {
574
+ if (!v || (t - (v.ts || 0)) > 15000) peers.delete(k);
575
+ }
576
+ }
577
+
578
+ function computeLocalBudget() {
579
+ prunePeers();
580
+
581
+ const selfVisible = (document.visibilityState === 'visible');
582
+ let selfStreaming = !!stats.streamActive;
583
+ try {
584
+ if (!selfStreaming) selfStreaming = !!detectDomBusy();
585
+ } catch {}
586
+
587
+ let total = selfStreaming ? 1 : 0;
588
+ let visible = (selfStreaming && selfVisible) ? 1 : 0;
589
+
590
+ for (const v of peers.values()) {
591
+ if (!v?.streaming) continue;
592
+ total += 1;
593
+ if (v.visible) visible += 1;
594
+ }
595
+
596
+ return {
597
+ totalStreamers: total,
598
+ visibleStreamers: visible
599
+ };
600
+ }
601
+
602
+ function computeExternalBusyScore() {
603
+ prunePeers();
604
+ let score = 0;
605
+ for (const v of peers.values()) {
606
+ if (v?.streaming) score += v.visible ? 18 : 9;
607
+ }
608
+ return clamp(score, 0, 45);
609
+ }
610
+
611
+ if (COORD_CH) {
612
+ try {
613
+ COORD_CH.onmessage = (ev) => {
614
+ const msg = ev?.data || null;
615
+ if (!msg || msg.tabId === TAB_ID) return;
616
+
617
+ if (msg.type === 'coord') {
618
+ peers.set(msg.tabId, {
619
+ ts: Number(msg.ts || nowMs()),
620
+ streaming: !!msg.streaming,
621
+ visible: !!msg.visible,
622
+ pressure: Number(msg.pressure || 0),
623
+ role: String(msg.role || 'follower')
624
+ });
625
+ } else if (msg.type === 'reply-ready') {
626
+ // UI fallback only; no re-detect logic
627
+ dispatchEventSafe('tg:reply-ready', msg);
628
+ emitFreshness('reply_detected', {
629
+ reason: `coord:${msg.source || 'peer'}`,
630
+ eventId: msg.eventId || ''
631
+ });
632
+ }
633
+ };
634
+ } catch {}
635
+ }
636
+
637
+ try {
638
+ api.runtime.onMessage.addListener((msg) => {
639
+ if (!msg) return;
640
+ if (msg.type === 'tgGlobalBudget') {
641
+ globalBudget = msg.budget || globalBudget;
642
+ } else if (msg.type === 'tgRole') {
643
+ cfg.role = String(msg.role || 'follower');
644
+ cfg.leader = (cfg.role === 'leader');
645
+ }
646
+ });
647
+ } catch {}
648
+
649
+ // -------------------------
650
+ // Pressure / profile logic
651
+ // -------------------------
652
+ function ewma(prev, next, alpha) {
653
+ return (prev * (1 - alpha)) + (next * alpha);
654
+ }
655
+
656
+ function computePressure() {
657
+ const visible = (document.visibilityState === 'visible');
658
+ const idleMs = nowMs() - cfg.lastInputTs;
659
+
660
+ const ltOver = Math.max(0, stats.longtasks - cfg.baselineLongtasks);
661
+ const turnOver = Math.max(0, stats.lastTurnCount - cfg.baselineTurns);
662
+ const lagOver = Math.max(0, stats.eventLoopLagMs - cfg.baselineLagMs);
663
+
664
+ let p = cfg.baselinePressure * 0.35;
665
+ p += clamp(ltOver * 9, 0, 45);
666
+ p += clamp(stats.disconnects * 8, 0, 24);
667
+ p += clamp(turnOver * 0.18, 0, 18);
668
+ p += clamp(lagOver * 0.16, 0, 20);
669
+ if (stats.streamActive) p += 14;
670
+ if (visible && idleMs < 20000) p += 8;
671
+ if (!visible) p -= 12;
672
+ if (stats.eventLoopLagHits >= 3) p += 10;
673
+ p += computeExternalBusyScore();
674
+
675
+ return clamp(Math.round(p), 0, 100);
676
+ }
677
+
678
+ function chooseProfile() {
679
+ const visible = (document.visibilityState === 'visible');
680
+ const idleMs = nowMs() - cfg.lastInputTs;
681
+ const inCooldown = (nowMs() < cfg.coolDownUntil);
682
+
683
+ if (!visible) return 'hidden';
684
+
685
+ if (cfg.profile === 'recovery') {
686
+ if (inCooldown || cfg.pressure > HYST.exitRecovery) return 'recovery';
687
+ }
688
+
689
+ if (cfg.pressure >= HYST.enterRecovery || stats.eventLoopLagHits >= 4) {
690
+ cfg.coolDownUntil = nowMs() + HYST.recoveryCooldownMs;
691
+ return 'recovery';
692
+ }
693
+
694
+ if (stats.streamActive || idleMs < 12000) {
695
+ if (cfg.pressure <= HYST.exitFlow) return 'flow';
696
+ return 'recovery';
697
+ }
698
+
699
+ if (cfg.profile === 'flow' && cfg.pressure <= HYST.enterFlow) return 'flow';
700
+ return 'balanced';
701
+ }
702
+
703
+ function applyProfile(next, reason) {
704
+ const t = nowMs();
705
+ if (next !== cfg.profile && (t - cfg.lastProfileSwitchTs) < HYST.minSwitchGapMs) return;
706
+
707
+ cfg.profile = next;
708
+ cfg.lastProfileSwitchTs = t;
709
+ cfg.topPx = clamp(Number(PROFILES[next]?.topPx || 160), cfg.minTopPx, 500);
710
+
711
+ emitPerfProfile(reason || 'profile');
712
+ }
713
+
714
+ function learnBaselines() {
715
+ if (document.visibilityState !== 'visible') return;
716
+ if (cfg.profile === 'recovery') return;
717
+
718
+ cfg.baselineSamples += 1;
719
+ cfg.baselineLongtasks = ewma(cfg.baselineLongtasks, stats.longtasks, 0.08);
720
+ cfg.baselineTurns = ewma(cfg.baselineTurns, stats.lastTurnCount || cfg.baselineTurns, 0.03);
721
+ cfg.baselineLagMs = ewma(cfg.baselineLagMs, stats.eventLoopLagMs || cfg.baselineLagMs, 0.06);
722
+ cfg.baselinePressure = ewma(cfg.baselinePressure, cfg.pressure, 0.04);
723
+ }
724
+
725
+ async function persistBaselinesMaybe() {
726
+ const t = nowMs();
727
+ if ((t - cfg.lastPersistTs) < 30000) return;
728
+ cfg.lastPersistTs = t;
729
+
730
+ try {
731
+ await api.storage.local.set({
732
+ tg_baseline_v1: {
733
+ pressure: cfg.baselinePressure,
734
+ longtasks: cfg.baselineLongtasks,
735
+ turns: cfg.baselineTurns,
736
+ lagMs: cfg.baselineLagMs,
737
+ samples: cfg.baselineSamples,
738
+ ts: t
739
+ }
740
+ });
741
+ } catch {}
742
+ }
743
+
744
+ async function loadBaselines() {
745
+ try {
746
+ const res = await api.storage.local.get(['tg_baseline_v1']);
747
+ const b = res?.tg_baseline_v1 || null;
748
+ if (b && typeof b === 'object') {
749
+ cfg.baselinePressure = clamp(Number(b.pressure) || cfg.baselinePressure, 8, 90);
750
+ cfg.baselineLongtasks = clamp(Number(b.longtasks) || cfg.baselineLongtasks, 0, 20);
751
+ cfg.baselineTurns = clamp(Number(b.turns) || cfg.baselineTurns, 10, 300);
752
+ cfg.baselineLagMs = clamp(Number(b.lagMs) || cfg.baselineLagMs, 5, 250);
753
+ cfg.baselineSamples = clamp(Number(b.samples) || 0, 0, 1000000);
754
+ }
755
+ } catch {}
756
+ }
757
+
758
+ // -------------------------
759
+ // Intent gating
760
+ // -------------------------
761
+ let lastScrollTop = 0;
762
+ let lastUpAt = 0;
763
+
764
+ async function updateIntent() {
765
+ if (document.visibilityState !== 'visible') return;
766
+
767
+ const sc = document.scrollingElement || document.documentElement;
768
+ const st = sc.scrollTop || 0;
769
+ const t = nowMs();
770
+
771
+ if (st < lastScrollTop - 2) lastUpAt = t;
772
+ lastScrollTop = st;
773
+
774
+ const nearTop = (st < cfg.topPx);
775
+ const recentUp = (t - lastUpAt) < 1500;
776
+ const allow = !!(nearTop || recentUp);
777
+
778
+ try { window.__chatTrafficGate?.setIntent?.(allow); } catch {}
779
+ try { await sendMessageSafe({ type: 'historyIntent', value: allow }); } catch {}
780
+ }
781
+
782
+ // -------------------------
783
+ // Heartbeat + tgSignal
784
+ // -------------------------
785
+ async function sendSignal(opts) {
786
+ const options = opts || {};
787
+ const force = !!options.force;
788
+
789
+ const t = nowMs();
790
+ if (!force && (t - lastHeartbeatAtMs) < 2500) return;
791
+ lastHeartbeatAtMs = t;
792
+
793
+ fresh.seq += 1;
794
+ fresh.lastSignalTs = t;
795
+
796
+ const pulse = pendingDetectedReplyPulse;
797
+ pendingDetectedReplyPulse = false;
798
+
799
+ // Robust streaming truth: telemetry first, DOM fallback
800
+ let effectiveStreaming = !!stats.streamActive;
801
+ try {
802
+ if (!effectiveStreaming) effectiveStreaming = !!detectDomBusy();
803
+ } catch {}
804
+ stats.streamActive = !!effectiveStreaming;
805
+
806
+ emitFreshness(force ? 'heartbeat_forced' : 'heartbeat', {
807
+ detectedReplyPulse: !!pulse,
808
+ detectorMisses: detector.detectorMisses,
809
+ lastDetectedTs: detector.lastDetectedTs || 0,
810
+ lastStreamEndTs: detector.lastStreamEndTs || 0,
811
+ busyHitExplicit: detector.busyHits.explicit || 0,
812
+ busyHitButtonText: detector.busyHits.buttonText || 0,
813
+ busyHitSendDisabled: detector.busyHits.sendDisabled || 0,
814
+ busyHitFallback: detector.busyHits.fallback || 0,
815
+ stabilizerArmed: !!detector.stabilizerArmed,
816
+ lastStableCandidateTs: detector.lastStableCandidateTs || 0,
817
+ lastStableEmitTs: detector.lastStableEmitTs || 0
818
+ });
819
+
820
+ try {
821
+ const resp = await sendMessageSafe({
822
+ type: 'tgSignal',
823
+ visible: document.visibilityState === 'visible',
824
+ streaming: !!effectiveStreaming,
825
+ pressure: Number(cfg.pressure || 0),
826
+ role: String(cfg.role || 'follower'),
827
+
828
+ // freshness contract fields
829
+ seq: fresh.seq,
830
+ lastSignalTs: t,
831
+ lastDetectedTs: detector.lastDetectedTs || 0,
832
+ lastStreamEndTs: detector.lastStreamEndTs || 0,
833
+ detectorMisses: detector.detectorMisses,
834
+ freshKind: fresh.lastKind,
835
+
836
+ // compatibility pulse fields for background freshness paths
837
+ detectedReply: !!pulse,
838
+ detectedReplyPulse: !!pulse,
839
+
840
+ // detector telemetry
841
+ busyHitExplicit: detector.busyHits.explicit || 0,
842
+ busyHitButtonText: detector.busyHits.buttonText || 0,
843
+ busyHitSendDisabled: detector.busyHits.sendDisabled || 0,
844
+ busyHitFallback: detector.busyHits.fallback || 0,
845
+ stabilizerArmed: !!detector.stabilizerArmed,
846
+ lastStableCandidateTs: detector.lastStableCandidateTs || 0,
847
+ lastStableEmitTs: detector.lastStableEmitTs || 0,
848
+ lastAssistantHash: detector.lastAssistantHash || '',
849
+ lastAssistantTextLen: detector.lastAssistantTextLen || 0
850
+ });
851
+
852
+ if (resp?.budget) globalBudget = resp.budget;
853
+ } catch {}
854
+ }
855
+
856
+ // -------------------------
857
+ // Event loop lag / long task observation
858
+ // -------------------------
859
+ let perfObs = null;
860
+ let lagTimer = null;
861
+
862
+ function startPerfObservers() {
863
+ if (!perfObs) {
864
+ try {
865
+ perfObs = new PerformanceObserver((list) => {
866
+ for (const e of list.getEntries()) {
867
+ if (e.duration >= 200) stats.longtasks += 1;
868
+ }
869
+ });
870
+ perfObs.observe({ entryTypes: ['longtask'] });
871
+ } catch { perfObs = null; }
872
+ }
873
+
874
+ if (!lagTimer) {
875
+ let last = performance.now();
876
+ lagTimer = setInterval(() => {
877
+ const n = performance.now();
878
+ const drift = Math.max(0, n - last - 1000);
879
+ last = n;
880
+
881
+ stats.eventLoopLagMs = Math.round(ewma(stats.eventLoopLagMs || 0, drift, 0.25));
882
+ if (drift > 220) stats.eventLoopLagHits += 1;
883
+ else stats.eventLoopLagHits = Math.max(0, stats.eventLoopLagHits - 1);
884
+ }, 1000);
885
+ }
886
+ }
887
+
888
+ function stopPerfObservers() {
889
+ try { perfObs?.disconnect?.(); } catch {}
890
+ perfObs = null;
891
+ if (lagTimer) clearInterval(lagTimer);
892
+ lagTimer = null;
893
+ }
894
+
895
+ // -------------------------
896
+ // Main control loop
897
+ // -------------------------
898
+ function decayCounters() {
899
+ stats.longtasks = Math.max(0, stats.longtasks - 1);
900
+ stats.cancels = Math.max(0, stats.cancels - 2);
901
+ stats.disconnects = Math.max(0, stats.disconnects - 1);
902
+ stats.eventLoopLagHits = Math.max(0, stats.eventLoopLagHits - 1);
903
+ }
904
+
905
+ async function controllerTick() {
906
+ cfg.pressure = computePressure();
907
+
908
+ const nextProfile = chooseProfile();
909
+ if (nextProfile !== cfg.profile) applyProfile(nextProfile, 'profile-switch');
910
+ else emitPerfProfile('tick');
911
+
912
+ await updateIntent();
913
+ await sendSignal();
914
+
915
+ learnBaselines();
916
+ decayCounters();
917
+ await persistBaselinesMaybe();
918
+
919
+ // publish lightweight coord (use same robust streaming truth)
920
+ if (COORD_CH) {
921
+ try {
922
+ let effectiveStreaming = !!stats.streamActive;
923
+ try {
924
+ if (!effectiveStreaming) effectiveStreaming = !!detectDomBusy();
925
+ } catch {}
926
+ stats.streamActive = !!effectiveStreaming;
927
+
928
+ COORD_CH.postMessage({
929
+ type: 'coord',
930
+ tabId: TAB_ID,
931
+ ts: nowMs(),
932
+ streaming: !!effectiveStreaming,
933
+ visible: (document.visibilityState === 'visible'),
934
+ pressure: cfg.pressure,
935
+ profile: cfg.profile,
936
+ role: cfg.role
937
+ });
938
+ } catch {}
939
+ }
940
+ }
941
+
942
+ // -------------------------
943
+ // Lifecycle
944
+ // -------------------------
945
+ let ctrlTimer = null;
946
+ let intentTimer = null;
947
+ let pollTimer = null;
948
+
949
+ function startLoops() {
950
+ if (!ctrlTimer) ctrlTimer = setInterval(() => { controllerTick().catch(() => {}); }, 5000);
951
+ if (!intentTimer) intentTimer = setInterval(() => { updateIntent().catch(() => {}); }, 2000);
952
+
953
+ // Secondary reply detector safety poll (single block only)
954
+ if (!pollTimer) {
955
+ pollTimer = setInterval(() => {
956
+ try {
957
+ const busy = detectDomBusy();
958
+ const turns = getAssistantTurnCount();
959
+
960
+ // Busy edge handling (start/end)
961
+ handleBusyEdge(busy, 'poll').catch(() => {});
962
+
963
+ if (!busy && turns > detector.lastAssistantCount) {
964
+ emitReplyFinished('poll-turn-growth').catch(() => {});
965
+ }
966
+
967
+ // Content stabilization fallback
968
+ evaluateStabilizedReply(busy, 'poll');
969
+
970
+ const missCondition =
971
+ detector.lastStreamEndTs > 0 &&
972
+ detector.lastDetectedTs < detector.lastStreamEndTs &&
973
+ (nowMs() - detector.lastStreamEndTs > 8000);
974
+
975
+ if (missCondition) {
976
+ detector.detectorMisses += 1;
977
+ emitFreshness('detector_miss', { detectorMisses: detector.detectorMisses });
978
+ emitReplyFinished('miss-recovery').catch(() => {});
979
+ }
980
+
981
+ detector.lastBusy = busy;
982
+ stats.streamActive = !!busy;
983
+ detector.lastAssistantCount = turns;
984
+ } catch {}
985
+ }, 1200);
986
+ }
987
+
988
+ startPerfObservers();
989
+ }
990
+
991
+ function stopLoops() {
992
+ if (ctrlTimer) clearInterval(ctrlTimer);
993
+ if (intentTimer) clearInterval(intentTimer);
994
+ if (pollTimer) clearInterval(pollTimer);
995
+ ctrlTimer = null;
996
+ intentTimer = null;
997
+ pollTimer = null;
998
+
999
+ stopPerfObservers();
1000
+
1001
+ // hidden mode still sends explicit no-intent once
1002
+ try { window.__chatTrafficGate?.setIntent?.(false); } catch {}
1003
+ sendMessageSafe({ type: 'historyIntent', value: false }).catch(() => {});
1004
+
1005
+ applyProfile('hidden', 'visibility-hidden');
1006
+ }
1007
+
1008
+ function markUserActive() { cfg.lastInputTs = nowMs(); }
1009
+ window.addEventListener('pointerdown', markUserActive, { passive: true, capture: true });
1010
+ window.addEventListener('keydown', markUserActive, { passive: true, capture: true });
1011
+
1012
+ document.addEventListener('visibilitychange', () => {
1013
+ if (document.visibilityState === 'visible') startLoops();
1014
+ else stopLoops();
1015
+ }, { passive: true });
1016
+
1017
+ // role discovery
1018
+ (async () => {
1019
+ try {
1020
+ const resp = await sendMessageSafe({ type: 'requestStatus' });
1021
+ if (resp?.role) {
1022
+ cfg.role = String(resp.role);
1023
+ cfg.leader = (cfg.role === 'leader');
1024
+ }
1025
+ } catch {}
1026
+ })();
1027
+
1028
+ // boot
1029
+ startReplyObserver();
1030
+ loadBaselines().finally(() => {
1031
+ if (document.visibilityState === 'visible') startLoops();
1032
+ else stopLoops();
1033
+
1034
+ // prime bg freshness state immediately on boot
1035
+ sendSignal({ force: true }).catch(() => {});
1036
+
1037
+ emitFreshness('boot', {
1038
+ baselineLoaded: true,
1039
+ visibility: document.visibilityState,
1040
+ tabId: TAB_ID
1041
+ });
1042
+
1043
+ // initial snapshot to UI panel
1044
+ try {
1045
+ const snap = stableJsonDumps({
1046
+ profile: cfg.profile,
1047
+ pressure: cfg.pressure,
1048
+ role: cfg.role
1049
+ });
1050
+ emitFreshness('boot_snapshot', { snapshot: snap });
1051
+ } catch {}
1052
+ });
1053
+ })();
GPTTrafficgateUPDATEDv3.1/content/core-utils.js ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (() => {
2
+ 'use strict';
3
+
4
+ const root = window;
5
+ const GUARD_KEY = '__tgCore_bootstrapped_v3';
6
+ const CORE_VERSION = '3.1.0';
7
+
8
+ const makeToken = () =>
9
+ `tg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
10
+
11
+ // Reinjection-safe: if already initialized, ensure compatibility shim exists and exit.
12
+ if (root[GUARD_KEY] && root.__tgCore) {
13
+ if (!root.__tgBus) {
14
+ root.__tgBus = Object.freeze({
15
+ emit: (name, detail) => { try { root.__tgCore.emitDom(name, detail); } catch {} },
16
+ on: (name, fn, opt) => {
17
+ try { return root.__tgCore.onDom(name, fn, opt || { passive: true }); } catch { return () => {}; }
18
+ }
19
+ });
20
+ }
21
+
22
+ // Signal reuse path for downstream modules that wait on core availability.
23
+ try {
24
+ root.__tgCore.emitDom('tg:core-reused', {
25
+ ts: Date.now(),
26
+ version: root.__tgCore?.version || CORE_VERSION,
27
+ reused: true
28
+ });
29
+ } catch {}
30
+ return;
31
+ }
32
+
33
+ const deepFreeze = (obj) => {
34
+ if (!obj || typeof obj !== 'object') return obj;
35
+ Object.freeze(obj);
36
+ for (const k of Object.getOwnPropertyNames(obj)) {
37
+ const v = obj[k];
38
+ if (v && typeof v === 'object' && !Object.isFrozen(v)) deepFreeze(v);
39
+ }
40
+ return obj;
41
+ };
42
+
43
+ if (!root.__tgCore) {
44
+ const canon = Object.create(null); // canonical helpers
45
+ const owners = Object.create(null); // helper owner map
46
+ const state = Object.create(null); // shared state
47
+ const listeners = new Map(); // internal event bus: event -> Set<fn>
48
+ const symbolOwners = Object.create(null); // claimed global symbols
49
+ const domForwardGuard = '__tgBusOrigin'; // recursion guard key in event detail
50
+
51
+ const bootTs = Date.now();
52
+ const instanceId = `core_${bootTs.toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
53
+
54
+ let debugEnabled = !!root.__TG_DEBUG;
55
+
56
+ const stableJsonDumps = (value) => {
57
+ const seen = new WeakSet();
58
+ const walk = (v) => {
59
+ if (v === null || typeof v !== 'object') {
60
+ if (typeof v === 'bigint') return `${String(v)}n`;
61
+ if (typeof v === 'function') return `[Function ${v.name || 'anonymous'}]`;
62
+ if (typeof v === 'symbol') return String(v);
63
+ return v;
64
+ }
65
+ if (seen.has(v)) return '[Circular]';
66
+ seen.add(v);
67
+
68
+ if (Array.isArray(v)) return v.map(walk);
69
+
70
+ const out = {};
71
+ for (const k of Object.keys(v).sort()) out[k] = walk(v[k]);
72
+ return out;
73
+ };
74
+ return JSON.stringify(walk(value));
75
+ };
76
+
77
+ const loadJson = (raw, fallback = null) => {
78
+ if (typeof raw !== 'string') return fallback;
79
+ try { return JSON.parse(raw); } catch { return fallback; }
80
+ };
81
+
82
+ /**
83
+ * registerCanonical(name, fn, owner, opts)
84
+ * opts:
85
+ * - allowSameOwnerOverride: boolean
86
+ * - allowExistingNoop: boolean (silently return existing)
87
+ */
88
+ const registerCanonical = (name, fn, owner = 'unknown', opts = null) => {
89
+ if (typeof name !== 'string' || !name.trim()) {
90
+ throw new TypeError('Canonical helper name must be a non-empty string');
91
+ }
92
+ if (typeof fn !== 'function') {
93
+ throw new TypeError(`Canonical helper ${name} must be a function`);
94
+ }
95
+
96
+ const key = name.trim();
97
+ const current = canon[key];
98
+ const currentOwner = owners[key];
99
+
100
+ if (current && current !== fn) {
101
+ const sameOwner = currentOwner === owner;
102
+ const allowSameOwnerOverride = !!opts?.allowSameOwnerOverride;
103
+ const allowExistingNoop = !!opts?.allowExistingNoop;
104
+
105
+ if (allowExistingNoop) return current;
106
+ if (sameOwner && allowSameOwnerOverride) {
107
+ canon[key] = fn;
108
+ owners[key] = owner;
109
+ return fn;
110
+ }
111
+
112
+ throw new Error(
113
+ `Duplicate canonical helper blocked: ${key} (owned by ${currentOwner}, attempted by ${owner})`
114
+ );
115
+ }
116
+
117
+ if (!current) {
118
+ canon[key] = fn;
119
+ owners[key] = owner;
120
+ }
121
+ return canon[key];
122
+ };
123
+
124
+ const blockDuplicateUtility = (name, owner = 'unknown') => {
125
+ const existingOwner = owners[name] || null;
126
+ if (existingOwner && existingOwner !== owner) {
127
+ throw new Error(
128
+ `Duplicate utility symbol blocked: ${name} (canonical owner: ${existingOwner}, attempted by ${owner})`
129
+ );
130
+ }
131
+ return true;
132
+ };
133
+
134
+ /**
135
+ * Explicit global-symbol claim system for low-level hooks that need singleton globals.
136
+ */
137
+ const claimGlobalSymbol = (name, owner = 'unknown', opts = null) => {
138
+ if (typeof name !== 'string' || !name.trim()) {
139
+ throw new TypeError('Global symbol name must be a non-empty string');
140
+ }
141
+ const key = name.trim();
142
+ const existing = symbolOwners[key];
143
+
144
+ if (!existing) {
145
+ symbolOwners[key] = owner;
146
+ return true;
147
+ }
148
+
149
+ if (existing === owner) return true;
150
+ if (opts?.allowTakeover === true) {
151
+ symbolOwners[key] = owner;
152
+ return true;
153
+ }
154
+
155
+ throw new Error(
156
+ `Global symbol already claimed: ${key} (owner: ${existing}, attempted by: ${owner})`
157
+ );
158
+ };
159
+
160
+ const releaseGlobalSymbol = (name, owner = 'unknown') => {
161
+ const key = String(name || '').trim();
162
+ if (!key) return false;
163
+ const existing = symbolOwners[key];
164
+ if (!existing) return false;
165
+ if (existing !== owner) return false;
166
+ delete symbolOwners[key];
167
+ return true;
168
+ };
169
+
170
+ const createPrivateName = (owner, localName) =>
171
+ `__tg_${String(owner).replace(/[^a-zA-Z0-9_]+/g, '_')}__${String(localName || '').replace(/[^a-zA-Z0-9_]+/g, '_')}`;
172
+
173
+ // Internal event bus
174
+ const emit = (event, detail = null) => {
175
+ const evt = String(event || '');
176
+ if (!evt) return 0;
177
+ const set = listeners.get(evt);
178
+ if (!set || set.size === 0) return 0;
179
+ let n = 0;
180
+ for (const fn of set) {
181
+ try { fn(detail); n++; } catch {}
182
+ }
183
+ return n;
184
+ };
185
+
186
+ const on = (event, fn, opts = null) => {
187
+ if (typeof fn !== 'function') throw new TypeError('listener must be a function');
188
+ const evt = String(event || '');
189
+ if (!evt) throw new TypeError('event must be a non-empty string');
190
+
191
+ let set = listeners.get(evt);
192
+ if (!set) {
193
+ set = new Set();
194
+ listeners.set(evt, set);
195
+ }
196
+
197
+ if (opts?.once) {
198
+ const onceWrapper = (detail) => {
199
+ try { fn(detail); } finally { try { off(evt, onceWrapper); } catch {} }
200
+ };
201
+ set.add(onceWrapper);
202
+ return () => off(evt, onceWrapper);
203
+ }
204
+
205
+ set.add(fn);
206
+ return () => off(evt, fn);
207
+ };
208
+
209
+ const off = (event, fn) => {
210
+ const evt = String(event || '');
211
+ if (!evt) return false;
212
+ const set = listeners.get(evt);
213
+ if (!set) return false;
214
+ const had = set.delete(fn);
215
+ if (set.size === 0) listeners.delete(evt);
216
+ return had;
217
+ };
218
+
219
+ // DOM bridge
220
+ const emitDom = (event, detail = null) => {
221
+ const evt = String(event || '');
222
+ if (!evt) return false;
223
+ try {
224
+ const token =
225
+ (detail && typeof detail === 'object' && detail.__tgEventToken)
226
+ ? detail.__tgEventToken
227
+ : makeToken();
228
+
229
+ const payload = (detail && typeof detail === 'object')
230
+ ? { ...detail, __tgEventToken: token, [domForwardGuard]: true }
231
+ : { value: detail, __tgEventToken: token, [domForwardGuard]: true };
232
+
233
+ window.dispatchEvent(new CustomEvent(evt, { detail: payload }));
234
+ return true;
235
+ } catch {
236
+ return false;
237
+ }
238
+ };
239
+
240
+ const onDom = (event, fn, opts = null) => {
241
+ const evt = String(event || '');
242
+ if (!evt || typeof fn !== 'function') return () => {};
243
+
244
+ const once = !!opts?.once;
245
+ const nativeOpts = {
246
+ passive: (opts?.passive !== false),
247
+ capture: !!opts?.capture,
248
+ once
249
+ };
250
+
251
+ const handler = (e) => {
252
+ try { fn(e?.detail ?? null, e); } catch {}
253
+ };
254
+
255
+ try {
256
+ window.addEventListener(evt, handler, nativeOpts);
257
+ return () => {
258
+ try { window.removeEventListener(evt, handler, nativeOpts); } catch {}
259
+ };
260
+ } catch {
261
+ return () => {};
262
+ }
263
+ };
264
+
265
+ // Internal + DOM one-shot emit
266
+ const emitBoth = (event, detail = null) => {
267
+ const payload = (detail && typeof detail === 'object')
268
+ ? { ...detail }
269
+ : { value: detail };
270
+
271
+ if (!payload.__tgEventToken) payload.__tgEventToken = makeToken();
272
+
273
+ const n = emit(event, payload);
274
+ emitDom(event, payload);
275
+ return n;
276
+ };
277
+
278
+ // Subscribe to internal + DOM; avoids duplicate callback when both fire in sequence
279
+ const onAny = (event, fn, opts = null) => {
280
+ if (typeof fn !== 'function') return () => {};
281
+ let lastToken = null;
282
+
283
+ const offInternal = on(event, (detail) => {
284
+ const tok = detail && typeof detail === 'object' ? detail.__tgEventToken : null;
285
+ if (tok && tok === lastToken) return;
286
+ lastToken = tok || null;
287
+ fn(detail);
288
+ });
289
+
290
+ const offDom = onDom(event, (detail) => {
291
+ const tok = detail && typeof detail === 'object' ? detail.__tgEventToken : null;
292
+ if (tok && tok === lastToken) return;
293
+ lastToken = tok || null;
294
+ fn(detail);
295
+ }, opts);
296
+
297
+ return () => { try { offInternal(); } catch {} try { offDom(); } catch {} };
298
+ };
299
+
300
+ const setState = (k, v) => { state[k] = v; return v; };
301
+ const getState = (k, fallback = null) => (Object.prototype.hasOwnProperty.call(state, k) ? state[k] : fallback);
302
+ const snapshotState = () => Object.assign({}, state);
303
+ const clearState = (k) => {
304
+ if (typeof k === 'undefined') {
305
+ for (const key of Object.keys(state)) delete state[key];
306
+ return true;
307
+ }
308
+ const key = String(k);
309
+ const had = Object.prototype.hasOwnProperty.call(state, key);
310
+ if (had) delete state[key];
311
+ return had;
312
+ };
313
+
314
+ const debug = (...args) => {
315
+ try { if (debugEnabled) console.debug('[tgCore]', ...args); } catch {}
316
+ };
317
+ const setDebug = (v) => { debugEnabled = !!v; return debugEnabled; };
318
+ const getDebug = () => !!debugEnabled;
319
+
320
+ // Canonical event names for downstream files
321
+ const EVENTS = deepFreeze({
322
+ PERF_PROFILE: 'tg:perf-profile',
323
+ SIGNAL_FRESHNESS: 'tg:signal-freshness',
324
+ REPLY_READY: 'tg:reply-ready',
325
+ WARMUP_STAGE: 'tg:warmup-stage',
326
+ NOTIFY_HEALTH: 'tg:notify-health',
327
+ CORE_READY: 'tg:core-ready',
328
+ CORE_REUSED: 'tg:core-reused'
329
+ });
330
+
331
+ const knownEventSet = new Set(Object.values(EVENTS));
332
+
333
+ const isKnownEventName = (name) => {
334
+ const s = String(name || '');
335
+ return knownEventSet.has(s);
336
+ };
337
+
338
+ const diagnostics = () => ({
339
+ version: CORE_VERSION,
340
+ bootTs,
341
+ instanceId,
342
+ canonicals: Object.keys(canon).sort(),
343
+ owners: Object.assign({}, owners),
344
+ claimedGlobals: Object.assign({}, symbolOwners),
345
+ stateKeys: Object.keys(state).sort(),
346
+ listeners: Array.from(listeners.entries()).map(([k, v]) => ({ event: k, count: v.size }))
347
+ });
348
+
349
+ registerCanonical('load_json', loadJson, 'core-utils');
350
+ registerCanonical('stable_json_dumps', stableJsonDumps, 'core-utils');
351
+
352
+ root.__tgCore = Object.freeze({
353
+ version: CORE_VERSION,
354
+ bootTs,
355
+ instanceId,
356
+
357
+ registerCanonical,
358
+ blockDuplicateUtility,
359
+ claimGlobalSymbol,
360
+ releaseGlobalSymbol,
361
+ createPrivateName,
362
+
363
+ getCanonical: (name) => canon[name] || null,
364
+ getOwner: (name) => owners[name] || null,
365
+ listCanonicals: () => Object.keys(canon).sort(),
366
+
367
+ emit,
368
+ on,
369
+ off,
370
+
371
+ emitDom,
372
+ onDom,
373
+ emitBoth,
374
+ onAny,
375
+
376
+ setState,
377
+ getState,
378
+ snapshotState,
379
+ clearState,
380
+
381
+ EVENTS,
382
+ isKnownEventName,
383
+
384
+ diagnostics,
385
+
386
+ debug,
387
+ setDebug,
388
+ getDebug
389
+ });
390
+ }
391
+
392
+ root.__tgCoreVersion = CORE_VERSION;
393
+ root[GUARD_KEY] = true;
394
+
395
+ // Compatibility shim: legacy users of __tgBus route through canonical core DOM bridge.
396
+ if (!root.__tgBus) {
397
+ root.__tgBus = Object.freeze({
398
+ emit: (name, detail) => { try { root.__tgCore.emitDom(name, detail); } catch {} },
399
+ on: (name, fn, opt) => {
400
+ try { return root.__tgCore.onDom(name, fn, opt || { passive: true }); } catch { return () => {}; }
401
+ }
402
+ });
403
+ }
404
+
405
+ // Boot signal for deterministic downstream initialization.
406
+ try {
407
+ root.__tgCore.emitDom('tg:core-ready', {
408
+ ts: Date.now(),
409
+ version: root.__tgCore?.version || CORE_VERSION,
410
+ instanceId: root.__tgCore?.instanceId || '',
411
+ bootTs: root.__tgCore?.bootTs || 0
412
+ });
413
+ } catch {}
414
+ })();
GPTTrafficgateUPDATEDv3.1/content/dom-softcap.js ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // content/dom-softcap.js — dynamic softcap per tab visibility (active vs background)
2
+ // Updated: canonical owner guard + fixed perf-profile contract + deterministic trim queue + state surface
3
+ // Patch: v2.1.0 reinjection-safe API, full lifecycle cleanup, generation-safe scheduling, richer diagnostics
4
+
5
+ (() => {
6
+ 'use strict';
7
+
8
+ const root = window;
9
+ const doc = document;
10
+ const OWNER = 'dom-softcap';
11
+ const VERSION = '2.1.0';
12
+ const GUARD_KEY = '__tgDomSoftcap_bootstrapped_v2';
13
+ const SYMBOL_NAME = 'tg-dom-softcap';
14
+ const SELECTOR_TURN = '[data-testid^="conversation-turn-"]';
15
+
16
+ if (root[GUARD_KEY] && root.__chatSoftCap) return;
17
+ if (root[GUARD_KEY] && !root.__chatSoftCap) {
18
+ // Bootstrapped marker exists without API; avoid duplicate init anyway.
19
+ return;
20
+ }
21
+ root[GUARD_KEY] = true;
22
+
23
+ const core = root.__tgCore || null;
24
+ const PERF_EVENT_NAME = String(core?.EVENTS?.PERF_PROFILE || 'tg:perf-profile');
25
+
26
+ try {
27
+ core?.claimGlobalSymbol?.(SYMBOL_NAME, OWNER, { allowTakeover: false });
28
+ } catch (e) {
29
+ try { if (root.__TG_DEBUG) console.warn('[dom-softcap] symbol claim blocked', e); } catch {}
30
+ return;
31
+ }
32
+
33
+ const tlog = (...args) => { try { root.__tgTelemetry?.apply(null, args); } catch {} };
34
+
35
+ const state = {
36
+ enabled: true,
37
+
38
+ // Effective knobs
39
+ keep: 60, // computed effective keep
40
+ keepActive: 45, // visible tab
41
+ keepHidden: 16, // hidden tab
42
+ keepDeepHidden: 10, // hidden long enough
43
+
44
+ deepHiddenAfterMs: 3 * 60 * 1000,
45
+ hiddenSince: null,
46
+
47
+ container: null,
48
+ observer: null,
49
+
50
+ firstDone: false,
51
+ dirty: true,
52
+
53
+ lastTrim: 0,
54
+ trimQueued: false,
55
+ trimBatch: 12,
56
+ minTrimGapMs: 300,
57
+ trimGen: 0, // generation counter to invalidate stale queued callbacks
58
+
59
+ // lifecycle
60
+ hbTimer: null,
61
+ scheduleTimer: null,
62
+ placeholderTimer: null,
63
+ offCorePerf: null,
64
+ offDomPerf: null,
65
+ offVisibility: null,
66
+
67
+ // diagnostics
68
+ trimOps: 0,
69
+ totalRemoved: 0,
70
+ lastTurnCount: 0,
71
+ placeholderRemoved: 0,
72
+ lastProfile: '',
73
+ startedAt: 0,
74
+ stoppedAt: 0
75
+ };
76
+
77
+ function publishState(extra) {
78
+ try {
79
+ root.__tgSoftcapState = Object.assign({
80
+ version: VERSION,
81
+ owner: OWNER,
82
+ enabled: !!state.enabled,
83
+ keep: Number(state.keep || 0),
84
+ keepActive: Number(state.keepActive || 0),
85
+ keepHidden: Number(state.keepHidden || 0),
86
+ keepDeepHidden: Number(state.keepDeepHidden || 0),
87
+ deepHiddenAfterMs: Number(state.deepHiddenAfterMs || 0),
88
+ hiddenSince: Number(state.hiddenSince || 0),
89
+ visibility: doc.visibilityState,
90
+ hasContainer: !!state.container,
91
+ hasObserver: !!state.observer,
92
+ dirty: !!state.dirty,
93
+ trimQueued: !!state.trimQueued,
94
+ trimGen: Number(state.trimGen || 0),
95
+ trimBatch: Number(state.trimBatch || 0),
96
+ minTrimGapMs: Number(state.minTrimGapMs || 0),
97
+ trimOps: Number(state.trimOps || 0),
98
+ totalRemoved: Number(state.totalRemoved || 0),
99
+ lastTurnCount: Number(state.lastTurnCount || 0),
100
+ lastTrimMs: Number(state.lastTrim || 0),
101
+ placeholderRemoved: Number(state.placeholderRemoved || 0),
102
+ scheduleTimerArmed: !!state.scheduleTimer,
103
+ hbTimerArmed: !!state.hbTimer,
104
+ placeholderTimerArmed: !!state.placeholderTimer,
105
+ lastProfile: String(state.lastProfile || ''),
106
+ startedAt: Number(state.startedAt || 0),
107
+ stoppedAt: Number(state.stoppedAt || 0)
108
+ }, extra || {});
109
+ } catch {}
110
+ }
111
+
112
+ function clampKeep(v, min, max) {
113
+ const n = Number(v);
114
+ if (!Number.isFinite(n)) return min;
115
+ return Math.max(min, Math.min(max, Math.floor(n)));
116
+ }
117
+
118
+ function applyMode() {
119
+ const vis = doc.visibilityState;
120
+ const now = Date.now();
121
+
122
+ if (vis === 'hidden') {
123
+ if (!state.hiddenSince) state.hiddenSince = now;
124
+ const deep = (now - state.hiddenSince) >= state.deepHiddenAfterMs;
125
+ state.keep = deep ? state.keepDeepHidden : state.keepHidden;
126
+ } else {
127
+ state.hiddenSince = null;
128
+ state.keep = state.keepActive;
129
+ }
130
+ }
131
+
132
+ function findContainer() {
133
+ const first = doc.querySelector(SELECTOR_TURN);
134
+ if (!first) return null;
135
+
136
+ let p = first.parentElement;
137
+ while (p && p !== doc.body) {
138
+ const kids = Array.from(p.children).filter((el) => el && el.nodeType === 1);
139
+ if (kids.length && kids.every((el) => el.matches(SELECTOR_TURN))) return p;
140
+ p = p.parentElement;
141
+ }
142
+
143
+ return first.parentElement || null;
144
+ }
145
+
146
+ function isPure(node) {
147
+ if (!node) return false;
148
+ const kids = Array.from(node.children).filter((el) => el && el.nodeType === 1);
149
+ return kids.length > 0 && kids.every((el) => el.matches(SELECTOR_TURN));
150
+ }
151
+
152
+ function nodes() {
153
+ if (!state.container) return [];
154
+ try {
155
+ return Array.from(state.container.querySelectorAll(SELECTOR_TURN));
156
+ } catch {
157
+ return [];
158
+ }
159
+ }
160
+
161
+ function doTrimWork() {
162
+ if (!state.enabled || !state.container) return;
163
+
164
+ applyMode();
165
+
166
+ const list = nodes();
167
+ const total = list.length;
168
+ state.lastTurnCount = total;
169
+
170
+ tlog('turnCount', { count: total, keep: state.keep, vis: doc.visibilityState });
171
+
172
+ const extra = total - state.keep;
173
+ if (extra > 0) {
174
+ const cutoff = total - state.keep;
175
+ const keepNodes = list.slice(cutoff);
176
+
177
+ let prevDisplay = '';
178
+ try {
179
+ prevDisplay = state.container.style.display;
180
+ state.container.style.display = 'none';
181
+ } catch {}
182
+
183
+ if (isPure(state.container)) {
184
+ try {
185
+ state.container.replaceChildren(...keepNodes);
186
+ } catch {
187
+ // fallback path if replaceChildren fails for any reason
188
+ for (let i = 0; i < cutoff; i++) {
189
+ try { list[i]?.remove(); } catch {}
190
+ }
191
+ }
192
+ } else {
193
+ // fallback for mixed container
194
+ for (let i = 0; i < cutoff; i++) {
195
+ try { list[i]?.remove(); } catch {}
196
+ }
197
+ }
198
+
199
+ try { state.container.style.display = prevDisplay; } catch {}
200
+ state.trimOps += 1;
201
+ state.totalRemoved += cutoff;
202
+
203
+ tlog('trim', { removed: cutoff, kept: state.keep });
204
+ }
205
+
206
+ state.lastTrim = Date.now();
207
+ state.dirty = false;
208
+ state.trimQueued = false;
209
+
210
+ // Preferred signal for early-shield to remove CSS shield
211
+ if (!state.firstDone) {
212
+ state.firstDone = true;
213
+ try { root.dispatchEvent(new Event('tg-unshield')); } catch {}
214
+ }
215
+
216
+ publishState();
217
+ }
218
+
219
+ function trimNowSafe() {
220
+ try { doTrimWork(); } catch {}
221
+ }
222
+
223
+ function clearScheduleTimer() {
224
+ if (state.scheduleTimer) {
225
+ try { clearTimeout(state.scheduleTimer); } catch {}
226
+ state.scheduleTimer = null;
227
+ }
228
+ }
229
+
230
+ function requestTrim(delayMs = 0) {
231
+ const now = Date.now();
232
+ const dt = now - (state.lastTrim || 0);
233
+
234
+ if (!state.enabled) {
235
+ state.trimQueued = false;
236
+ clearScheduleTimer();
237
+ publishState();
238
+ return;
239
+ }
240
+
241
+ if (state.trimQueued) return;
242
+
243
+ const effectiveDelay = Math.max(
244
+ Number(delayMs || 0),
245
+ dt < state.minTrimGapMs ? (state.minTrimGapMs - dt) : 0
246
+ );
247
+
248
+ state.trimQueued = true;
249
+ state.trimGen += 1;
250
+ const myGen = state.trimGen;
251
+
252
+ clearScheduleTimer();
253
+
254
+ state.scheduleTimer = setTimeout(() => {
255
+ state.scheduleTimer = null;
256
+
257
+ // stale callback guard
258
+ if (myGen !== state.trimGen) return;
259
+ if (!state.enabled) {
260
+ state.trimQueued = false;
261
+ publishState();
262
+ return;
263
+ }
264
+
265
+ try {
266
+ if ('requestIdleCallback' in root && typeof root.requestIdleCallback === 'function') {
267
+ root.requestIdleCallback(() => {
268
+ if (myGen !== state.trimGen) return;
269
+ trimNowSafe();
270
+ }, { timeout: 1200 });
271
+ } else {
272
+ trimNowSafe();
273
+ }
274
+ } catch {
275
+ trimNowSafe();
276
+ }
277
+ }, effectiveDelay);
278
+
279
+ publishState();
280
+ }
281
+
282
+ function bindContainerIfNeeded() {
283
+ const c = findContainer();
284
+ if (!c) return false;
285
+
286
+ if (state.container !== c) {
287
+ try { state.observer?.disconnect?.(); } catch {}
288
+
289
+ state.container = c;
290
+ state.dirty = true;
291
+
292
+ state.observer = new MutationObserver(() => {
293
+ if (!state.enabled) return;
294
+ state.dirty = true;
295
+ requestTrim(40);
296
+ });
297
+
298
+ try {
299
+ state.observer.observe(state.container, { childList: true });
300
+ } catch {}
301
+
302
+ requestTrim(80);
303
+ publishState({ rebound: true, reboundTs: Date.now() });
304
+ }
305
+
306
+ return true;
307
+ }
308
+
309
+ function heartbeat() {
310
+ if (!state.enabled) {
311
+ publishState();
312
+ return;
313
+ }
314
+ bindContainerIfNeeded();
315
+ if (state.dirty) requestTrim(80);
316
+ publishState();
317
+ }
318
+
319
+ function applySoftcapProfile(detail) {
320
+ const d = detail || {};
321
+ const profile = String(d.profile || '');
322
+
323
+ // If controller explicitly passes keep, trust it for active mode.
324
+ if (Number.isFinite(Number(d.keep))) {
325
+ state.keepActive = clampKeep(Number(d.keep), 20, 300);
326
+ }
327
+
328
+ // Optional explicit knobs from controller
329
+ if (Number.isFinite(Number(d.keepHidden))) {
330
+ state.keepHidden = clampKeep(Number(d.keepHidden), 8, 220);
331
+ }
332
+ if (Number.isFinite(Number(d.keepDeepHidden))) {
333
+ state.keepDeepHidden = clampKeep(Number(d.keepDeepHidden), 5, 120);
334
+ }
335
+ if (Number.isFinite(Number(d.deepHiddenAfterMs))) {
336
+ state.deepHiddenAfterMs = Math.max(10000, Math.floor(Number(d.deepHiddenAfterMs)));
337
+ }
338
+
339
+ // Contract compatibility signals
340
+ const streamFlag = (typeof d.streamActive === 'boolean')
341
+ ? d.streamActive
342
+ : (typeof d.streaming === 'boolean' ? d.streaming : null);
343
+ if (typeof streamFlag === 'boolean') {
344
+ // currently unused for trim logic, but captured for diagnostics/state surface if needed later
345
+ }
346
+
347
+ if (typeof d.visible === 'boolean') {
348
+ // hint only; visibilityState remains source of truth for mode
349
+ }
350
+
351
+ // Profile fallback mapping when explicit keep is absent
352
+ if (!Number.isFinite(Number(d.keep))) {
353
+ if (profile === 'hidden') {
354
+ state.keepActive = Math.min(state.keepActive, 16);
355
+ } else if (profile === 'recovery') {
356
+ state.keepActive = Math.min(state.keepActive, 28);
357
+ } else if (profile === 'flow') {
358
+ state.keepActive = clampKeep(state.keepActive, 36, 42);
359
+ } else if (profile === 'balanced') {
360
+ state.keepActive = Math.max(state.keepActive, 45);
361
+ }
362
+ }
363
+
364
+ state.lastProfile = profile || state.lastProfile || 'unknown';
365
+ state.dirty = true;
366
+ applyMode();
367
+ requestTrim(30);
368
+ publishState({ profileApplied: profile || 'unknown' });
369
+ }
370
+
371
+ function bindDomListeners() {
372
+ const onVis = () => {
373
+ applyMode();
374
+ state.dirty = true;
375
+ requestTrim(120);
376
+ };
377
+ doc.addEventListener('visibilitychange', onVis, { passive: true });
378
+ state.offVisibility = () => {
379
+ try { doc.removeEventListener('visibilitychange', onVis, { passive: true }); } catch {}
380
+ };
381
+
382
+ const onPerf = (ev) => {
383
+ try { applySoftcapProfile(ev?.detail || {}); } catch {}
384
+ };
385
+ root.addEventListener(PERF_EVENT_NAME, onPerf, { passive: true });
386
+ state.offDomPerf = () => {
387
+ try { root.removeEventListener(PERF_EVENT_NAME, onPerf, { passive: true }); } catch {}
388
+ };
389
+ }
390
+
391
+ function bindCoreListeners() {
392
+ try {
393
+ if (core?.on) {
394
+ state.offCorePerf = core.on(PERF_EVENT_NAME, (detail) => {
395
+ try { applySoftcapProfile(detail || {}); } catch {}
396
+ });
397
+ }
398
+ } catch {}
399
+ }
400
+
401
+ function setConfig(cfg) {
402
+ if (!cfg || typeof cfg !== 'object') return;
403
+
404
+ if (typeof cfg.enabled === 'boolean') state.enabled = cfg.enabled;
405
+ if (Number.isFinite(Number(cfg.keep))) state.keepActive = clampKeep(cfg.keep, 20, 300);
406
+ if (Number.isFinite(Number(cfg.keepHidden))) state.keepHidden = clampKeep(cfg.keepHidden, 8, 220);
407
+ if (Number.isFinite(Number(cfg.keepDeepHidden))) state.keepDeepHidden = clampKeep(cfg.keepDeepHidden, 5, 120);
408
+ if (Number.isFinite(Number(cfg.deepHiddenAfterMs))) state.deepHiddenAfterMs = Math.max(10000, Math.floor(Number(cfg.deepHiddenAfterMs)));
409
+ if (Number.isFinite(Number(cfg.minTrimGapMs))) state.minTrimGapMs = Math.max(50, Math.floor(Number(cfg.minTrimGapMs)));
410
+ if (Number.isFinite(Number(cfg.trimBatch))) state.trimBatch = Math.max(1, Math.floor(Number(cfg.trimBatch)));
411
+
412
+ state.dirty = true;
413
+ applyMode();
414
+ requestTrim(30);
415
+ publishState({ setConfig: true });
416
+ }
417
+
418
+ function diagnostics() {
419
+ return {
420
+ version: VERSION,
421
+ owner: OWNER,
422
+ enabled: !!state.enabled,
423
+ keep: {
424
+ effective: Number(state.keep || 0),
425
+ active: Number(state.keepActive || 0),
426
+ hidden: Number(state.keepHidden || 0),
427
+ deepHidden: Number(state.keepDeepHidden || 0),
428
+ deepHiddenAfterMs: Number(state.deepHiddenAfterMs || 0)
429
+ },
430
+ lifecycle: {
431
+ startedAt: Number(state.startedAt || 0),
432
+ stoppedAt: Number(state.stoppedAt || 0),
433
+ hbTimer: !!state.hbTimer,
434
+ scheduleTimer: !!state.scheduleTimer,
435
+ placeholderTimer: !!state.placeholderTimer
436
+ },
437
+ queue: {
438
+ dirty: !!state.dirty,
439
+ trimQueued: !!state.trimQueued,
440
+ trimGen: Number(state.trimGen || 0),
441
+ lastTrim: Number(state.lastTrim || 0),
442
+ minTrimGapMs: Number(state.minTrimGapMs || 0)
443
+ },
444
+ container: {
445
+ hasContainer: !!state.container,
446
+ hasObserver: !!state.observer,
447
+ lastTurnCount: Number(state.lastTurnCount || 0)
448
+ },
449
+ counters: {
450
+ trimOps: Number(state.trimOps || 0),
451
+ totalRemoved: Number(state.totalRemoved || 0),
452
+ placeholderRemoved: Number(state.placeholderRemoved || 0)
453
+ },
454
+ profile: String(state.lastProfile || '')
455
+ };
456
+ }
457
+
458
+ try {
459
+ Object.defineProperty(root, '__chatSoftCap', {
460
+ value: Object.freeze({
461
+ setConfig,
462
+ requestTrim: (delayMs = 0) => requestTrim(Number(delayMs || 0)),
463
+ diagnostics
464
+ }),
465
+ writable: false,
466
+ configurable: true,
467
+ enumerable: false
468
+ });
469
+ } catch {}
470
+
471
+ function startPlaceholderCleanup() {
472
+ if (state.placeholderTimer) return;
473
+ state.placeholderTimer = setInterval(() => {
474
+ try {
475
+ if (!state.enabled) return;
476
+ const ph = doc.querySelectorAll('.tg-recycle-placeholder');
477
+ if (ph.length > 800) {
478
+ const removeN = ph.length - 600;
479
+ for (let i = 0; i < removeN; i++) {
480
+ const n = ph[i];
481
+ if (n && n.parentNode) n.parentNode.removeChild(n);
482
+ }
483
+ state.placeholderRemoved += removeN;
484
+ publishState({ placeholderSweep: removeN });
485
+ }
486
+ } catch {}
487
+ }, 30000);
488
+ }
489
+
490
+ function stopPlaceholderCleanup() {
491
+ if (state.placeholderTimer) {
492
+ try { clearInterval(state.placeholderTimer); } catch {}
493
+ state.placeholderTimer = null;
494
+ }
495
+ }
496
+
497
+ function start() {
498
+ state.startedAt = Date.now();
499
+ bindDomListeners();
500
+ bindCoreListeners();
501
+
502
+ bindContainerIfNeeded();
503
+ applyMode();
504
+ requestTrim(160);
505
+
506
+ if (!state.hbTimer) {
507
+ state.hbTimer = setInterval(heartbeat, 2000);
508
+ }
509
+
510
+ startPlaceholderCleanup();
511
+ publishState({ startedAt: state.startedAt });
512
+ }
513
+
514
+ function teardown() {
515
+ state.stoppedAt = Date.now();
516
+
517
+ // invalidate queued trims
518
+ state.trimGen += 1;
519
+ state.trimQueued = false;
520
+
521
+ clearScheduleTimer();
522
+
523
+ try { if (state.hbTimer) clearInterval(state.hbTimer); } catch {}
524
+ state.hbTimer = null;
525
+
526
+ stopPlaceholderCleanup();
527
+
528
+ try { state.observer?.disconnect?.(); } catch {}
529
+ state.observer = null;
530
+ state.container = null;
531
+
532
+ try { state.offCorePerf?.(); } catch {}
533
+ state.offCorePerf = null;
534
+
535
+ try { state.offDomPerf?.(); } catch {}
536
+ state.offDomPerf = null;
537
+
538
+ try { state.offVisibility?.(); } catch {}
539
+ state.offVisibility = null;
540
+
541
+ publishState({ stoppedAt: state.stoppedAt, tornDown: true });
542
+ }
543
+
544
+ // Optional debug teardown
545
+ try {
546
+ Object.defineProperty(root, '__tgSoftcapTeardown', {
547
+ value: teardown,
548
+ writable: false,
549
+ configurable: true,
550
+ enumerable: false
551
+ });
552
+ } catch {}
553
+
554
+ if (doc.readyState === 'loading') {
555
+ doc.addEventListener('DOMContentLoaded', () => {
556
+ start();
557
+ }, { once: true });
558
+ } else {
559
+ start();
560
+ }
561
+ })();
GPTTrafficgateUPDATEDv3.1/content/early-shield.js ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // content/early-shield.js — document_start CSS shield (auto-unshields safely)
2
+ // Updated: canonical core integration + singleton guard + idempotent lifecycle
3
+ // Patch: v1.2.0 reinjection-safe API, stronger cleanup, core lifecycle compat, richer diagnostics
4
+
5
+ (() => {
6
+ 'use strict';
7
+
8
+ const root = window;
9
+ const doc = document;
10
+ const VERSION = '1.2.0';
11
+ const OWNER = 'early-shield';
12
+ const GUARD_KEY = '__tgEarlyShield_bootstrapped_v1';
13
+ const SYMBOL_NAME = 'tg-early-shield';
14
+
15
+ const EVENTS = Object.freeze({
16
+ UNSHIELD: 'tg-unshield',
17
+ READY: 'tg-early-shield-ready',
18
+ REMOVED: 'tg-early-shield-removed',
19
+ CORE_READY: 'tg:core-ready',
20
+ CORE_REUSED: 'tg:core-reused'
21
+ });
22
+
23
+ // Reinjection-safe short-circuit if already initialized.
24
+ if (root[GUARD_KEY] && root.__tgEarlyShield) {
25
+ try { root.__tgEarlyShield?.diagnostics?.(); } catch {}
26
+ return;
27
+ }
28
+ root[GUARD_KEY] = true;
29
+
30
+ const core = root.__tgCore || null;
31
+
32
+ // Try to claim symbol if canonical core exists.
33
+ try {
34
+ core?.claimGlobalSymbol?.(SYMBOL_NAME, OWNER, { allowTakeover: false });
35
+ } catch (e) {
36
+ // If symbol claim fails, exit to avoid collisions with another owner.
37
+ try { if (root.__TG_DEBUG) console.warn('[early-shield] symbol claim blocked', e); } catch {}
38
+ return;
39
+ }
40
+
41
+ const state = {
42
+ active: false,
43
+ removed: false,
44
+ appliedAt: 0,
45
+ removedAt: 0,
46
+ removedReason: '',
47
+ timeoutId: null,
48
+
49
+ offCoreUnshield: null,
50
+ offCoreReady: null,
51
+ offCoreReused: null,
52
+
53
+ offDomUnshield: null,
54
+ offDomReady: null,
55
+
56
+ lastError: ''
57
+ };
58
+
59
+ let styleEl = null;
60
+
61
+ const safeDispatch = (name, detail) => {
62
+ try { root.dispatchEvent(new CustomEvent(name, { detail })); } catch {}
63
+ };
64
+
65
+ const setStatus = (extra = null) => {
66
+ try {
67
+ root.__tgEarlyShieldStatus = Object.assign({
68
+ version: VERSION,
69
+ owner: OWNER,
70
+ active: !!state.active,
71
+ removed: !!state.removed,
72
+ appliedAt: state.appliedAt || 0,
73
+ removedAt: state.removedAt || 0,
74
+ removedReason: state.removedReason || '',
75
+ lastError: state.lastError || ''
76
+ }, extra || {});
77
+ } catch {}
78
+ };
79
+
80
+ const setErr = (e) => {
81
+ try { state.lastError = String(e?.message || e || ''); } catch {}
82
+ };
83
+
84
+ const resolveMountTarget = () => {
85
+ return doc.documentElement || doc.head || doc.body || doc;
86
+ };
87
+
88
+ const ensureShieldStyle = () => {
89
+ styleEl = doc.getElementById('tg-early-shield');
90
+ if (styleEl) return styleEl;
91
+
92
+ const el = doc.createElement('style');
93
+ el.id = 'tg-early-shield';
94
+ el.setAttribute('data-owner', OWNER);
95
+ el.textContent = `
96
+ html.tg-shield [data-testid^="conversation-turn-"] { display: none !important; }
97
+ html.tg-shield [data-testid="conversation-turns"] { visibility: hidden !important; }
98
+ `;
99
+ resolveMountTarget().appendChild(el);
100
+ styleEl = el;
101
+ return styleEl;
102
+ };
103
+
104
+ const applyShield = () => {
105
+ if (state.active || state.removed) return false;
106
+
107
+ try {
108
+ ensureShieldStyle();
109
+ doc.documentElement?.classList?.add('tg-shield');
110
+
111
+ state.active = true;
112
+ state.appliedAt = Date.now();
113
+
114
+ setStatus();
115
+ safeDispatch(EVENTS.READY, {
116
+ active: true,
117
+ ts: state.appliedAt,
118
+ version: VERSION,
119
+ owner: OWNER
120
+ });
121
+
122
+ return true;
123
+ } catch (e) {
124
+ setErr(e);
125
+ setStatus();
126
+ return false;
127
+ }
128
+ };
129
+
130
+ const clearTimer = () => {
131
+ try {
132
+ if (state.timeoutId) clearTimeout(state.timeoutId);
133
+ } catch {}
134
+ state.timeoutId = null;
135
+ };
136
+
137
+ const clearListeners = () => {
138
+ try { state.offCoreUnshield?.(); } catch {}
139
+ state.offCoreUnshield = null;
140
+
141
+ try { state.offCoreReady?.(); } catch {}
142
+ state.offCoreReady = null;
143
+
144
+ try { state.offCoreReused?.(); } catch {}
145
+ state.offCoreReused = null;
146
+
147
+ try { state.offDomUnshield?.(); } catch {}
148
+ state.offDomUnshield = null;
149
+
150
+ try { state.offDomReady?.(); } catch {}
151
+ state.offDomReady = null;
152
+ };
153
+
154
+ const detachStyle = () => {
155
+ try {
156
+ if (styleEl && styleEl.parentNode) {
157
+ styleEl.parentNode.removeChild(styleEl);
158
+ styleEl = null;
159
+ return;
160
+ }
161
+ } catch {}
162
+ try {
163
+ const el = doc.getElementById('tg-early-shield');
164
+ if (el && el.parentNode) el.parentNode.removeChild(el);
165
+ } catch {}
166
+ styleEl = null;
167
+ };
168
+
169
+ const removeShield = (reason = 'unknown') => {
170
+ if (state.removed) return false;
171
+ state.removed = true;
172
+
173
+ clearTimer();
174
+ clearListeners();
175
+
176
+ try { doc.documentElement?.classList?.remove('tg-shield'); } catch {}
177
+ detachStyle();
178
+
179
+ state.active = false;
180
+ state.removedAt = Date.now();
181
+ state.removedReason = String(reason || 'unknown');
182
+
183
+ setStatus();
184
+ safeDispatch(EVENTS.REMOVED, {
185
+ active: false,
186
+ ts: state.removedAt,
187
+ reason: state.removedReason,
188
+ version: VERSION,
189
+ owner: OWNER
190
+ });
191
+
192
+ return true;
193
+ };
194
+
195
+ const diagnostics = () => ({
196
+ version: VERSION,
197
+ owner: OWNER,
198
+ state: {
199
+ active: !!state.active,
200
+ removed: !!state.removed,
201
+ appliedAt: state.appliedAt || 0,
202
+ removedAt: state.removedAt || 0,
203
+ removedReason: state.removedReason || '',
204
+ timeoutArmed: !!state.timeoutId,
205
+ lastError: state.lastError || ''
206
+ },
207
+ listeners: {
208
+ domUnshield: !!state.offDomUnshield,
209
+ domReady: !!state.offDomReady,
210
+ coreUnshield: !!state.offCoreUnshield,
211
+ coreReady: !!state.offCoreReady,
212
+ coreReused: !!state.offCoreReused
213
+ },
214
+ stylePresent: !!doc.getElementById('tg-early-shield'),
215
+ classPresent: !!doc.documentElement?.classList?.contains('tg-shield')
216
+ });
217
+
218
+ const bindDomUnshield = () => {
219
+ const handler = () => { removeShield('event:tg-unshield'); };
220
+ root.addEventListener(EVENTS.UNSHIELD, handler, { once: true, passive: true });
221
+ state.offDomUnshield = () => {
222
+ try { root.removeEventListener(EVENTS.UNSHIELD, handler, { passive: true }); } catch {}
223
+ };
224
+ };
225
+
226
+ const bindDomReadyFallback = () => {
227
+ if (doc.readyState === 'loading') {
228
+ const onReady = () => { removeShield('domcontentloaded'); };
229
+ doc.addEventListener('DOMContentLoaded', onReady, { once: true, passive: true });
230
+ state.offDomReady = () => {
231
+ try { doc.removeEventListener('DOMContentLoaded', onReady, { passive: true }); } catch {}
232
+ };
233
+ } else {
234
+ state.offDomReady = null;
235
+ }
236
+ };
237
+
238
+ const bindCorePaths = () => {
239
+ try {
240
+ if (!core?.on) return;
241
+
242
+ state.offCoreUnshield = core.on(EVENTS.UNSHIELD, () => {
243
+ removeShield('core:tg-unshield');
244
+ });
245
+
246
+ // Core lifecycle compatibility: republish status when core lifecycle events occur.
247
+ state.offCoreReady = core.on(EVENTS.CORE_READY, () => {
248
+ setStatus({ coreLifecycle: 'ready', coreTs: Date.now() });
249
+ });
250
+
251
+ state.offCoreReused = core.on(EVENTS.CORE_REUSED, () => {
252
+ setStatus({ coreLifecycle: 'reused', coreTs: Date.now() });
253
+ });
254
+ } catch (e) {
255
+ setErr(e);
256
+ setStatus();
257
+ }
258
+ };
259
+
260
+ const boot = () => {
261
+ try {
262
+ applyShield();
263
+
264
+ // Safety valve: auto-unshield after 2.5s even if no trim/unshield fired
265
+ state.timeoutId = setTimeout(() => {
266
+ removeShield('timeout');
267
+ }, 2500);
268
+
269
+ bindDomUnshield();
270
+ bindCorePaths();
271
+ bindDomReadyFallback();
272
+
273
+ setStatus({ bootedAt: Date.now() });
274
+ } catch (e) {
275
+ // Hard fail-safe: never leave page permanently shielded
276
+ setErr(e);
277
+ removeShield('exception');
278
+ }
279
+ };
280
+
281
+ // Stable API for debug/ops and reinjection-safe control.
282
+ try {
283
+ Object.defineProperty(root, '__tgEarlyShield', {
284
+ value: Object.freeze({
285
+ version: VERSION,
286
+ owner: OWNER,
287
+ state: () => ({
288
+ active: !!state.active,
289
+ removed: !!state.removed,
290
+ appliedAt: state.appliedAt || 0,
291
+ removedAt: state.removedAt || 0,
292
+ removedReason: state.removedReason || ''
293
+ }),
294
+ apply: () => applyShield(),
295
+ remove: (reason) => removeShield(String(reason || 'manual')),
296
+ diagnostics
297
+ }),
298
+ writable: false,
299
+ configurable: true,
300
+ enumerable: false
301
+ });
302
+ } catch {}
303
+
304
+ boot();
305
+ })();
GPTTrafficgateUPDATEDv3.1/content/keepalive.js ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // content/keepalive.js — keep session warm; leader-only pinger; no auto-discard
2
+ // Upgraded: pressure-aware cadence, global-budget hold integration, hidden-tab conservative mode,
3
+ // and hard cap on cumulative keepalive work per minute.
4
+ // Patched: unified listeners, internal scan throttle, deterministic lifecycle, bounded state surface.
5
+
6
+ (function () {
7
+ 'use strict';
8
+
9
+ const root = window;
10
+ const doc = document;
11
+ const api = (typeof browser !== 'undefined') ? browser : chrome;
12
+ const tlog = (...args) => { try { root.__tgTelemetry?.apply(null, args); } catch {} };
13
+
14
+ const VERSION = '2.2.0';
15
+ const GUARD_KEY = '__tgKeepalive_bootstrapped_v2';
16
+
17
+ if (root[GUARD_KEY] && root.__chatKeepalive) return;
18
+ if (root[GUARD_KEY]) return;
19
+ root[GUARD_KEY] = true;
20
+
21
+ let __tgProfile = 'balanced';
22
+ let __tgPressure = 0;
23
+ let __tgFollowerThrottle = false;
24
+
25
+ let globalBudget = { totalStreamers: 0, visibleStreamers: 0, followerHold: false };
26
+
27
+ const state = {
28
+ enabled: true, // overall module on/off
29
+ pingEnabled: false, // leader-only pings by default
30
+ role: 'follower', // 'leader' | 'follower'
31
+ minutes: 7,
32
+ jitterPct: 0.18,
33
+ jitterSeed: Math.floor(Math.random() * 1000000),
34
+ autoReconnect: true,
35
+ allowReloads: false, // SAFE DEFAULT: off
36
+ lastReload: 0,
37
+ chosenPath: null,
38
+ chosenPathTs: 0,
39
+
40
+ // Stability guards
41
+ followerSuspendUntil: 0,
42
+ maxOpsPerMin: 10,
43
+ minuteBucket: Math.floor(Date.now() / 60000),
44
+ opsThisMinute: 0,
45
+
46
+ // Diagnostics
47
+ attempts: 0,
48
+ ok: 0,
49
+ fail: 0,
50
+ lastPingTs: 0,
51
+ lastPingOk: false,
52
+ lastPingPath: '',
53
+ lastPingMs: 0,
54
+ lastError: '',
55
+
56
+ // lifecycle
57
+ timer: null,
58
+ visListenerAdded: false,
59
+ msgListenerAdded: false,
60
+ moStarted: false,
61
+ onlineListenerAdded: false,
62
+ teardownAt: 0,
63
+
64
+ // scan throttle
65
+ lastDisconnectScan: 0,
66
+ disconnectScanMinMs: 1200
67
+ };
68
+
69
+ function publishState(extra = null) {
70
+ try {
71
+ root.__tgKeepaliveState = Object.assign({
72
+ version: VERSION,
73
+ enabled: !!state.enabled,
74
+ pingEnabled: !!state.pingEnabled,
75
+ role: state.role,
76
+ profile: __tgProfile,
77
+ pressure: Number(__tgPressure || 0),
78
+ followerThrottle: !!__tgFollowerThrottle,
79
+ followerHold: !!globalBudget?.followerHold,
80
+ minutes: Number(state.minutes || 0),
81
+ jitterPct: Number(state.jitterPct || 0),
82
+ attempts: Number(state.attempts || 0),
83
+ ok: Number(state.ok || 0),
84
+ fail: Number(state.fail || 0),
85
+ minuteBucket: Number(state.minuteBucket || 0),
86
+ opsThisMinute: Number(state.opsThisMinute || 0),
87
+ maxOpsPerMin: Number(state.maxOpsPerMin || 0),
88
+ chosenPath: state.chosenPath || '',
89
+ chosenPathTs: Number(state.chosenPathTs || 0),
90
+ lastPingTs: Number(state.lastPingTs || 0),
91
+ lastPingOk: !!state.lastPingOk,
92
+ lastPingPath: state.lastPingPath || '',
93
+ lastPingMs: Number(state.lastPingMs || 0),
94
+ lastError: state.lastError || '',
95
+ timerArmed: !!state.timer
96
+ }, extra || {});
97
+ } catch {}
98
+ }
99
+
100
+ function resetMinuteBucketIfNeeded() {
101
+ const m = Math.floor(Date.now() / 60000);
102
+ if (state.minuteBucket !== m) {
103
+ state.minuteBucket = m;
104
+ state.opsThisMinute = 0;
105
+ }
106
+ }
107
+
108
+ function canDoWorkNow() {
109
+ resetMinuteBucketIfNeeded();
110
+ return state.opsThisMinute < state.maxOpsPerMin;
111
+ }
112
+
113
+ function markWork() {
114
+ resetMinuteBucketIfNeeded();
115
+ state.opsThisMinute += 1;
116
+ }
117
+
118
+ function isFollowerHeld() {
119
+ if (state.role === 'leader') return false;
120
+ if (__tgFollowerThrottle) return true;
121
+ if (globalBudget?.followerHold) return true;
122
+ if (Date.now() < state.followerSuspendUntil) return true;
123
+ return false;
124
+ }
125
+
126
+ function dynamicBaseMinutes() {
127
+ let m = Math.max(2, Math.min(30, Number(state.minutes) || 7));
128
+ const p = Number(__tgPressure || 0);
129
+
130
+ if (doc.visibilityState !== 'visible') m = Math.max(m, 10);
131
+ if (isFollowerHeld()) m = Math.max(m, 14);
132
+ if (p >= 80) m = Math.max(m, 16);
133
+ else if (p >= 60) m = Math.max(m, 12);
134
+ else if (p >= 45) m = Math.max(m, 9);
135
+
136
+ if (__tgProfile === 'recovery') m = Math.max(m, 14);
137
+ if (__tgProfile === 'hidden') m = Math.max(m, 12);
138
+
139
+ return m;
140
+ }
141
+
142
+ function visible() { return doc.visibilityState === 'visible'; }
143
+
144
+ function notTyping() {
145
+ const ae = doc.activeElement;
146
+ return !(ae && (
147
+ ae.tagName === 'TEXTAREA' ||
148
+ (ae.tagName === 'INPUT' && /text|search|url|email|password/.test(ae.type || ''))
149
+ ));
150
+ }
151
+
152
+ function throttledTryClickRetry() {
153
+ const now = Date.now();
154
+ if ((now - state.lastDisconnectScan) < state.disconnectScanMinMs) return false;
155
+ state.lastDisconnectScan = now;
156
+ return tryClickRetry();
157
+ }
158
+
159
+ function tryClickRetry() {
160
+ const labels = ['reload', 'retry', 'try again', 'reconnect'];
161
+ const btns = Array.from(doc.querySelectorAll('button, a[role="button"]'));
162
+ for (const b of btns) {
163
+ const t = (b.textContent || '').trim().toLowerCase();
164
+ if (labels.some((L) => t.includes(L))) {
165
+ try { b.click(); } catch {}
166
+ tlog('retryClick');
167
+ return true;
168
+ }
169
+ }
170
+ return false;
171
+ }
172
+
173
+ function softReload() {
174
+ const now = Date.now();
175
+ if (now - state.lastReload < 30000) return;
176
+ if (!visible() || !notTyping()) return;
177
+ state.lastReload = now;
178
+ tlog('softReload');
179
+ location.reload();
180
+ }
181
+
182
+ function clearTimer() {
183
+ if (state.timer) {
184
+ try { clearInterval(state.timer); } catch {}
185
+ state.timer = null;
186
+ }
187
+ }
188
+
189
+ async function pickEndpoint() {
190
+ // cool down endpoint picking; don't spam probes
191
+ if (state.chosenPath && (Date.now() - state.chosenPathTs) < 5 * 60 * 1000) return state.chosenPath;
192
+
193
+ const candidates = [
194
+ '/api/auth/session',
195
+ '/backend-api/models',
196
+ '/backend-api/conversations?offset=0&limit=1',
197
+ '/favicon.ico',
198
+ '/'
199
+ ];
200
+
201
+ for (const path of candidates) {
202
+ try {
203
+ if (!canDoWorkNow()) break;
204
+ markWork();
205
+ if (await headOrGet(path)) {
206
+ state.chosenPath = path;
207
+ state.chosenPathTs = Date.now();
208
+ publishState();
209
+ return path;
210
+ }
211
+ } catch {}
212
+ }
213
+ state.chosenPath = state.chosenPath || '/';
214
+ state.chosenPathTs = Date.now();
215
+ publishState();
216
+ return state.chosenPath;
217
+ }
218
+
219
+ async function headOrGet(path) {
220
+ const url = new URL(path, location.origin).toString();
221
+
222
+ // Hidden + held followers should stay light.
223
+ if (doc.visibilityState !== 'visible' && isFollowerHeld()) {
224
+ try {
225
+ if ('sendBeacon' in navigator) {
226
+ const blob = new Blob([], { type: 'application/octet-stream' });
227
+ navigator.sendBeacon(url, blob);
228
+ return true;
229
+ }
230
+ } catch {}
231
+ return false;
232
+ }
233
+
234
+ try {
235
+ const ctl = new AbortController();
236
+ const t = setTimeout(() => ctl.abort(), 6000);
237
+ const res = await fetch(url, { method: 'HEAD', cache: 'no-store', credentials: 'include', keepalive: true, signal: ctl.signal });
238
+ clearTimeout(t);
239
+ return !!res && (res.ok || res.type === 'opaqueredirect');
240
+ } catch {}
241
+
242
+ try {
243
+ const ctl = new AbortController();
244
+ const t = setTimeout(() => ctl.abort(), 6000);
245
+ const res = await fetch(url, {
246
+ method: 'GET',
247
+ cache: 'no-store',
248
+ credentials: 'include',
249
+ keepalive: true,
250
+ signal: ctl.signal,
251
+ mode: 'same-origin'
252
+ });
253
+ clearTimeout(t);
254
+ return !!res && (res.ok || res.type === 'opaqueredirect');
255
+ } catch {}
256
+
257
+ try {
258
+ if (doc.visibilityState !== 'visible' && 'sendBeacon' in navigator) {
259
+ const blob = new Blob([], { type: 'application/octet-stream' });
260
+ navigator.sendBeacon(url, blob);
261
+ return true;
262
+ }
263
+ } catch {}
264
+
265
+ return false;
266
+ }
267
+
268
+ function schedule() {
269
+ clearTimer();
270
+
271
+ if (!state.enabled || !state.pingEnabled) {
272
+ publishState();
273
+ return;
274
+ }
275
+
276
+ // hard hold for followers
277
+ if (isFollowerHeld()) {
278
+ publishState({ held: true });
279
+ return;
280
+ }
281
+
282
+ const baseMin = dynamicBaseMinutes();
283
+ const jitterLow = Math.max(0.20, 0.25 - (state.jitterPct * 0.1));
284
+ const jitterHigh = Math.min(0.55, 0.35 + state.jitterPct);
285
+ const jitter = jitterLow + Math.random() * (jitterHigh - jitterLow);
286
+ const ms = Math.floor(baseMin * jitter * 60000);
287
+
288
+ state.timer = setInterval(() => { ping().catch(() => {}); }, ms);
289
+
290
+ if (!state.visListenerAdded) {
291
+ state.visListenerAdded = true;
292
+ const onVis = () => {
293
+ if (doc.visibilityState === 'visible') {
294
+ api.runtime.sendMessage({ type: 'becomeLeader' }).catch(() => {});
295
+ if (state.role !== 'leader') {
296
+ // temporary follow-mode ping until role catches up
297
+ state.pingEnabled = true;
298
+ }
299
+ schedule();
300
+ setTimeout(() => { ping().catch(() => {}); }, 1200);
301
+ } else {
302
+ if (state.role !== 'leader') {
303
+ state.pingEnabled = false;
304
+ }
305
+ schedule();
306
+ }
307
+ };
308
+ doc.addEventListener('visibilitychange', onVis, { passive: true });
309
+ state._onVis = onVis;
310
+ }
311
+
312
+ setTimeout(() => { ping().catch(() => {}); }, 2500);
313
+ publishState({ scheduledMs: ms, baseMin });
314
+ }
315
+
316
+ async function ping() {
317
+ if (!state.enabled || !state.pingEnabled) return;
318
+ if (isFollowerHeld()) return;
319
+ if (!canDoWorkNow()) return;
320
+
321
+ state.attempts += 1;
322
+ markWork();
323
+
324
+ if (!state.chosenPath) state.chosenPath = await pickEndpoint();
325
+
326
+ let ok = false;
327
+ const t0 = performance.now();
328
+ try {
329
+ ok = await headOrGet(state.chosenPath);
330
+ if (ok) state.ok += 1;
331
+ else state.fail += 1;
332
+
333
+ state.lastPingTs = Date.now();
334
+ state.lastPingOk = !!ok;
335
+ state.lastPingPath = state.chosenPath || '';
336
+ state.lastPingMs = Math.round(performance.now() - t0);
337
+
338
+ tlog('ping', {
339
+ role: state.role,
340
+ ok,
341
+ pressure: __tgPressure,
342
+ profile: __tgProfile,
343
+ held: isFollowerHeld(),
344
+ opsThisMinute: state.opsThisMinute
345
+ });
346
+ } catch (e) {
347
+ state.fail += 1;
348
+ state.lastError = String(e?.message || e || 'ping_error');
349
+ state.lastPingTs = Date.now();
350
+ state.lastPingOk = false;
351
+ state.lastPingPath = state.chosenPath || '';
352
+ state.lastPingMs = Math.round(performance.now() - t0);
353
+ }
354
+
355
+ publishState();
356
+ }
357
+
358
+ function attachRuntimeMessageListener() {
359
+ if (state.msgListenerAdded) return;
360
+ state.msgListenerAdded = true;
361
+
362
+ const handler = (msg) => {
363
+ if (!msg) return;
364
+
365
+ if (msg.type === 'tgGlobalBudget') {
366
+ globalBudget = msg.budget || globalBudget;
367
+
368
+ // budget-aware hold: hidden followers should stop pinging immediately
369
+ if (globalBudget?.followerHold && doc.visibilityState !== 'visible' && state.role !== 'leader') {
370
+ state.pingEnabled = false;
371
+ }
372
+ schedule();
373
+ publishState({ budgetUpdate: true });
374
+ return;
375
+ }
376
+
377
+ if (msg.type === 'tgRole') {
378
+ state.role = (msg.role === 'leader') ? 'leader' : 'follower';
379
+ state.pingEnabled = (state.role === 'leader');
380
+ schedule();
381
+ publishState({ roleUpdate: state.role });
382
+ }
383
+ };
384
+
385
+ try {
386
+ api.runtime.onMessage.addListener(handler);
387
+ state._onRuntime = handler;
388
+ } catch {}
389
+ }
390
+
391
+ function attachPerfListener() {
392
+ const onPerf = (ev) => {
393
+ try {
394
+ __tgProfile = ev?.detail?.profile || __tgProfile;
395
+ __tgPressure = Number(ev?.detail?.pressure || __tgPressure || 0);
396
+ __tgFollowerThrottle = !!ev?.detail?.followerThrottle;
397
+ schedule();
398
+ publishState({ perfUpdate: true });
399
+ } catch {}
400
+ };
401
+ root.addEventListener('tg:perf-profile', onPerf, { passive: true });
402
+ state._onPerf = onPerf;
403
+ }
404
+
405
+ function attachReconnectObservers() {
406
+ if (!state.moStarted) {
407
+ state.moStarted = true;
408
+ const kw = /(trying to reconnect|attempting to connect|reconnecting|network error|disconnected|lost connection)/i;
409
+ state._moErr = new MutationObserver((muts) => {
410
+ if (!state.autoReconnect) return;
411
+ for (const m of muts) {
412
+ for (const n of (m.addedNodes || [])) {
413
+ if (n.nodeType === 1) {
414
+ const txt = (n.textContent || '').slice(0, 4096);
415
+ if (kw.test(txt)) {
416
+ tlog('disconnect');
417
+ if (!throttledTryClickRetry() && state.allowReloads) {
418
+ setTimeout(() => softReload(), 2500);
419
+ }
420
+ return;
421
+ }
422
+ }
423
+ }
424
+ }
425
+ });
426
+ try {
427
+ state._moErr.observe(doc.documentElement || doc.body, { childList: true, subtree: true });
428
+ } catch {}
429
+ }
430
+
431
+ if (!state.onlineListenerAdded) {
432
+ state.onlineListenerAdded = true;
433
+ const onOnline = () => {
434
+ if (state.autoReconnect && state.allowReloads) {
435
+ setTimeout(() => { if (!throttledTryClickRetry()) softReload(); }, 1200);
436
+ }
437
+ };
438
+ root.addEventListener('online', onOnline, { passive: true });
439
+ state._onOnline = onOnline;
440
+ }
441
+ }
442
+
443
+ function exposeApi() {
444
+ Object.defineProperty(root, '__chatKeepalive', {
445
+ value: Object.freeze({
446
+ setEnabled(v) { state.enabled = !!v; schedule(); publishState(); },
447
+ setMinutes(m) {
448
+ m = Math.max(4, Math.min(30, Math.floor(m || state.minutes)));
449
+ state.minutes = m;
450
+ schedule();
451
+ publishState();
452
+ },
453
+ setJitterPct(v) {
454
+ const n = Number(v);
455
+ if (Number.isFinite(n)) state.jitterPct = Math.max(0, Math.min(0.5, n));
456
+ publishState();
457
+ },
458
+ setAutoReconnect(v) { state.autoReconnect = !!v; publishState(); },
459
+ setAllowReloads(v) { state.allowReloads = !!v; publishState(); },
460
+ setPingEnabled(v) { state.pingEnabled = !!v; schedule(); publishState(); },
461
+ setRole(r) {
462
+ state.role = (r === 'leader') ? 'leader' : 'follower';
463
+ state.pingEnabled = (state.role === 'leader');
464
+ schedule();
465
+ publishState();
466
+ },
467
+ reconnectNow() { throttledTryClickRetry() || (state.allowReloads && softReload()); },
468
+ getHealth() {
469
+ return {
470
+ role: state.role,
471
+ enabled: state.enabled,
472
+ pingEnabled: state.pingEnabled,
473
+ attempts: state.attempts,
474
+ ok: state.ok,
475
+ fail: state.fail,
476
+ opsThisMinute: state.opsThisMinute,
477
+ minuteBucket: state.minuteBucket,
478
+ profile: __tgProfile,
479
+ pressure: __tgPressure,
480
+ followerThrottle: __tgFollowerThrottle,
481
+ followerHold: !!globalBudget?.followerHold
482
+ };
483
+ }
484
+ }),
485
+ writable: false, configurable: true, enumerable: false
486
+ });
487
+ }
488
+
489
+ function exposeTeardown() {
490
+ Object.defineProperty(root, '__tgKeepaliveTeardown', {
491
+ value: () => {
492
+ try { clearTimer(); } catch {}
493
+
494
+ try {
495
+ if (state._onPerf) root.removeEventListener('tg:perf-profile', state._onPerf, { passive: true });
496
+ } catch {}
497
+ state._onPerf = null;
498
+
499
+ try {
500
+ if (state._onVis) doc.removeEventListener('visibilitychange', state._onVis, { passive: true });
501
+ } catch {}
502
+ state._onVis = null;
503
+
504
+ try {
505
+ if (state._onOnline) root.removeEventListener('online', state._onOnline, { passive: true });
506
+ } catch {}
507
+ state._onOnline = null;
508
+
509
+ try { state._moErr?.disconnect?.(); } catch {}
510
+ state._moErr = null;
511
+
512
+ state.teardownAt = Date.now();
513
+ publishState({ teardownAt: state.teardownAt });
514
+ },
515
+ writable: false,
516
+ configurable: true,
517
+ enumerable: false
518
+ });
519
+ }
520
+
521
+ (async () => {
522
+ exposeApi();
523
+ exposeTeardown();
524
+ attachPerfListener();
525
+ attachRuntimeMessageListener();
526
+ attachReconnectObservers();
527
+
528
+ try {
529
+ const got = await api.storage.local.get({
530
+ keepaliveEnabled: true,
531
+ keepaliveMinutes: 4,
532
+ autoReconnect: true,
533
+ allowReloads: false
534
+ });
535
+ state.enabled = !!got.keepaliveEnabled;
536
+ state.minutes = Number(got.keepaliveMinutes) || 4;
537
+ state.autoReconnect = !!got.autoReconnect;
538
+ state.allowReloads = !!got.allowReloads;
539
+ } catch {}
540
+
541
+ // Ask background who we are. If visible and background hasn't elected yet,
542
+ // briefly act as leader to keep the session warm until the role message arrives.
543
+ try {
544
+ const resp = await api.runtime.sendMessage({ type: 'requestStatus' });
545
+ if (resp?.role) {
546
+ state.role = resp.role;
547
+ state.pingEnabled = (resp.role === 'leader');
548
+ } else {
549
+ state.pingEnabled = (doc.visibilityState === 'visible');
550
+ }
551
+ } catch {
552
+ state.pingEnabled = (doc.visibilityState === 'visible');
553
+ }
554
+
555
+ // If visible, nudge background to elect us leader.
556
+ if (doc.visibilityState === 'visible') {
557
+ api.runtime.sendMessage({ type: 'becomeLeader' }).catch(() => {});
558
+ }
559
+
560
+ schedule();
561
+ publishState({ bootedAt: Date.now() });
562
+ })();
563
+ })();
GPTTrafficgateUPDATEDv3.1/content/net-guard.js ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // content/net-guard.js — document_start guard with SAFE JSON thinning + safer soft-block for list pagination
2
+ // Updated: canonical owner guard + unified fetch wrapper telemetry + clean event surface + bounded state
3
+ // Patch: v2.1.0 safer blocked-fetch semantics (no unintended retry), core-ready/reused compat, richer diagnostics
4
+ (() => {
5
+ 'use strict';
6
+
7
+ const root = window;
8
+ const doc = document;
9
+ const OWNER = 'net-guard';
10
+ const VERSION = '2.1.0';
11
+ const GUARD_KEY = '__tgNetGuard_bootstrapped_v2';
12
+ const SYMBOL_NAME = 'tg-net-guard';
13
+
14
+ if (root[GUARD_KEY]) return;
15
+ root[GUARD_KEY] = true;
16
+
17
+ const core = root.__tgCore || null;
18
+ try {
19
+ core?.claimGlobalSymbol?.(SYMBOL_NAME, OWNER, { allowTakeover: false });
20
+ } catch (e) {
21
+ try { if (root.__TG_DEBUG) console.warn('[net-guard] symbol claim blocked', e); } catch {}
22
+ return;
23
+ }
24
+
25
+ const HOSTS = /^(chat\.openai\.com|chatgpt\.com)$/;
26
+ const PATHS = /(backend-api\/conversation|backend-api\/conversations|backend-api\/messages|\/history|\/messages|\/conversation|\/threads|\/v1\/messages|\/v1\/threads)/i;
27
+
28
+ // Base tuning
29
+ const KEEP_BASE = 45;
30
+ const KEEP_LOW = 24;
31
+ const KEEP_MID = 34;
32
+ const PARSE_BUDGET_BASE_MS = 22;
33
+ const MIN_THIN_BYTES = 250 * 1024;
34
+
35
+ // Hard cap for cumulative background work/minute
36
+ const MAX_THINS_PER_MIN = 18;
37
+
38
+ // Soft-block only on *list-like* pagination endpoints where an empty page is safe.
39
+ const SOFT_BLOCK_LIST_PATHS = /(\/backend-api\/conversations\b|\/history\b|\/threads\b|\/v1\/threads\b)/i;
40
+
41
+ const api = (typeof browser !== 'undefined') ? browser : chrome;
42
+ const gate = { enabled: true, intent: false, allowUntil: 0 };
43
+
44
+ // Live perf/profile signal from autopilot
45
+ const perf = {
46
+ pressure: 0,
47
+ profile: 'balanced',
48
+ streamActive: false,
49
+ visible: doc.visibilityState === 'visible',
50
+ followerThrottle: false,
51
+ updatedAt: 0
52
+ };
53
+
54
+ const thinWindow = {
55
+ minute: Math.floor(Date.now() / 60000),
56
+ count: 0
57
+ };
58
+
59
+ const state = {
60
+ intervalId: null,
61
+ offCorePerf: null,
62
+ offCoreReady: null,
63
+ offCoreReused: null,
64
+
65
+ blocks: 0,
66
+ fetchBlocks: 0,
67
+ xhrBlocks: 0,
68
+ softBlocks: 0,
69
+ softBlockResponses: 0,
70
+ fetchAborts: 0,
71
+
72
+ thinApplied: 0,
73
+ thinSkipped: 0,
74
+ thinErrors: 0,
75
+
76
+ lastBlockUrl: '',
77
+ lastSlowFetchMs: 0,
78
+ lastError: '',
79
+ lastErrorTs: 0
80
+ };
81
+
82
+ const tlog = (...args) => { try { root.__tgTelemetry?.apply(null, args); } catch {} };
83
+
84
+ function setLastError(errLike) {
85
+ try {
86
+ state.lastError = String(errLike?.message || errLike || '');
87
+ state.lastErrorTs = Date.now();
88
+ } catch {}
89
+ }
90
+
91
+ function publishState(extra) {
92
+ try {
93
+ root.__tgNetGuardState = Object.assign({
94
+ version: VERSION,
95
+ owner: OWNER,
96
+ enabled: !!gate.enabled,
97
+ intent: !!gate.intent,
98
+ allowUntil: Number(gate.allowUntil || 0),
99
+
100
+ profile: String(perf.profile || 'balanced'),
101
+ pressure: Number(perf.pressure || 0),
102
+ streamActive: !!perf.streamActive,
103
+ visible: !!perf.visible,
104
+ followerThrottle: !!perf.followerThrottle,
105
+ updatedAt: Number(perf.updatedAt || 0),
106
+
107
+ thinMinute: thinWindow.minute,
108
+ thinMinuteCount: thinWindow.count,
109
+
110
+ blocks: state.blocks,
111
+ fetchBlocks: state.fetchBlocks,
112
+ xhrBlocks: state.xhrBlocks,
113
+ softBlocks: state.softBlocks,
114
+ softBlockResponses: state.softBlockResponses,
115
+ fetchAborts: state.fetchAborts,
116
+
117
+ thinApplied: state.thinApplied,
118
+ thinSkipped: state.thinSkipped,
119
+ thinErrors: state.thinErrors,
120
+
121
+ lastBlockUrl: state.lastBlockUrl || '',
122
+ lastSlowFetchMs: state.lastSlowFetchMs || 0,
123
+ lastError: state.lastError || '',
124
+ lastErrorTs: Number(state.lastErrorTs || 0)
125
+ }, extra || {});
126
+ } catch {}
127
+ }
128
+
129
+ function nowMinute() { return Math.floor(Date.now() / 60000); }
130
+
131
+ function bumpThinCounter() {
132
+ const m = nowMinute();
133
+ if (thinWindow.minute !== m) {
134
+ thinWindow.minute = m;
135
+ thinWindow.count = 0;
136
+ }
137
+ thinWindow.count += 1;
138
+ }
139
+
140
+ function canThinNow() {
141
+ const m = nowMinute();
142
+ if (thinWindow.minute !== m) {
143
+ thinWindow.minute = m;
144
+ thinWindow.count = 0;
145
+ }
146
+ return thinWindow.count < MAX_THINS_PER_MIN;
147
+ }
148
+
149
+ function parseBudgetMs() {
150
+ const p = Number(perf.pressure || 0);
151
+ if (p >= 80) return 10;
152
+ if (p >= 60) return 14;
153
+ if (p >= 45) return 18;
154
+ return PARSE_BUDGET_BASE_MS;
155
+ }
156
+
157
+ function dynamicKeep() {
158
+ const p = Number(perf.pressure || 0);
159
+ if (p >= 80) return KEEP_LOW;
160
+ if (p >= 55) return KEEP_MID;
161
+ return KEEP_BASE;
162
+ }
163
+
164
+ function overParseBudget(startTs) {
165
+ try { return (performance.now() - startTs) > parseBudgetMs(); } catch { return false; }
166
+ }
167
+
168
+ function shouldDeferHeavyWork() {
169
+ // Defer in hidden tabs when pressure/follower throttle is high.
170
+ if (doc.visibilityState === 'visible') return false;
171
+ if (perf.followerThrottle) return true;
172
+ if (Number(perf.pressure || 0) >= 55) return true;
173
+ return false;
174
+ }
175
+
176
+ async function syncGateStatus() {
177
+ try {
178
+ const r = await api.runtime.sendMessage({ type: 'requestStatus' });
179
+ if (r) {
180
+ gate.enabled = !!r.blockHistory;
181
+ gate.intent = !!r.intent;
182
+ gate.allowUntil = Number(r.allowUntil || 0);
183
+ publishState();
184
+ }
185
+ } catch (e) {
186
+ setLastError(e);
187
+ publishState();
188
+ }
189
+ }
190
+
191
+ (async () => {
192
+ try {
193
+ const s = await api.storage.local.get({ blockHistory: true });
194
+ gate.enabled = !!s.blockHistory;
195
+ } catch (e) {
196
+ setLastError(e);
197
+ }
198
+ await syncGateStatus();
199
+ publishState();
200
+ })();
201
+
202
+ // Keep gate in sync without hammering runtime messaging
203
+ state.intervalId = setInterval(() => { syncGateStatus().catch(() => {}); }, 12000);
204
+
205
+ function absorbPerfDetail(d) {
206
+ try {
207
+ perf.profile = String(d.profile || perf.profile || 'balanced');
208
+ perf.pressure = Number(d.pressure || perf.pressure || 0);
209
+ perf.streamActive = !!d.streamActive;
210
+ perf.visible = (typeof d.visible === 'boolean') ? d.visible : (doc.visibilityState === 'visible');
211
+ perf.followerThrottle = !!d.followerThrottle;
212
+ perf.updatedAt = Date.now();
213
+ publishState();
214
+ } catch (e) {
215
+ setLastError(e);
216
+ publishState();
217
+ }
218
+ }
219
+
220
+ root.addEventListener('tg:perf-profile', (ev) => {
221
+ absorbPerfDetail(ev?.detail || {});
222
+ }, { passive: true });
223
+
224
+ // Canonical bus path (if core exists)
225
+ try {
226
+ if (core?.on) {
227
+ state.offCorePerf = core.on('tg:perf-profile', (detail) => absorbPerfDetail(detail || {}));
228
+
229
+ // Core lifecycle compat: republish local state so downstream sees coherent snapshot.
230
+ state.offCoreReady = core.on('tg:core-ready', () => {
231
+ publishState({ coreLifecycle: 'ready', coreTs: Date.now() });
232
+ });
233
+
234
+ state.offCoreReused = core.on('tg:core-reused', () => {
235
+ publishState({ coreLifecycle: 'reused', coreTs: Date.now() });
236
+ });
237
+ }
238
+ } catch {}
239
+
240
+ Object.defineProperty(root, '__chatTrafficGate', {
241
+ value: {
242
+ setEnabled(v) { gate.enabled = !!v; publishState(); },
243
+ setIntent(v) { gate.intent = !!v; publishState(); },
244
+ allowForMs(ms) {
245
+ gate.allowUntil = Date.now() + Math.max(2000, Math.min(60000, Number(ms) || 10000));
246
+ publishState();
247
+ }
248
+ },
249
+ writable: false, configurable: false, enumerable: false
250
+ });
251
+
252
+ function hasPagination(u) {
253
+ try {
254
+ const q = u.searchParams;
255
+ if (q.has('cursor') || q.has('before')) return true;
256
+ if (q.has('offset') && Number(q.get('offset')) > 0) return true;
257
+ if (q.has('page') && Number(q.get('page')) > 1) return true;
258
+ const dir = (q.get('direction') || '').toLowerCase();
259
+ if (/back|prev|previous/.test(dir)) return true;
260
+ } catch {}
261
+ return false;
262
+ }
263
+
264
+ function looksHistory(url) {
265
+ try {
266
+ const u = (typeof url === 'string') ? new URL(url, location.href) : (url instanceof URL ? url : null);
267
+ if (!u) return false;
268
+ if (!HOSTS.test(u.hostname)) return false;
269
+ if (!PATHS.test(u.pathname)) return false;
270
+ return hasPagination(u);
271
+ } catch { return false; }
272
+ }
273
+
274
+ function shouldBlock(method, url) {
275
+ const now = Date.now();
276
+ return gate.enabled &&
277
+ (now < gate.allowUntil ? false : !gate.intent) &&
278
+ (method === 'GET' || method === 'POST') &&
279
+ looksHistory(url);
280
+ }
281
+
282
+ function isSoftBlockCandidate(url) {
283
+ try {
284
+ const u = new URL(url, location.href);
285
+ return SOFT_BLOCK_LIST_PATHS.test(u.pathname);
286
+ } catch { return false; }
287
+ }
288
+
289
+ function softBlockResponse() {
290
+ // Generic empty page response for list-like pagination endpoints.
291
+ const body = JSON.stringify({ items: [], has_more: false });
292
+ state.softBlockResponses += 1;
293
+ return new Response(body, {
294
+ status: 200,
295
+ headers: { 'content-type': 'application/json; charset=utf-8' }
296
+ });
297
+ }
298
+
299
+ function thinMappingWithAncestors(data, keepN) {
300
+ try {
301
+ const mapping = data?.mapping;
302
+ if (!mapping || typeof mapping !== 'object') return { data, changed: false };
303
+ const ids = Object.keys(mapping);
304
+ if (ids.length <= keepN + 10) return { data, changed: false };
305
+
306
+ const nodes = ids.map((id) => {
307
+ const n = mapping[id] || {};
308
+ const t = (n?.message?.create_time || n?.message?.create_time_ms || n?.create_time || 0);
309
+ return { id, t: Number(t) || 0 };
310
+ }).sort((a, b) => a.t - b.t);
311
+
312
+ const recent = nodes.slice(-keepN).map(x => x.id);
313
+ const keepSet = new Set(recent);
314
+
315
+ // Always keep current_node chain if present.
316
+ const cur = data?.current_node;
317
+ if (typeof cur === 'string' && cur in mapping) keepSet.add(cur);
318
+
319
+ // Pull ancestor chains for all kept nodes.
320
+ const addAncestors = (startId) => {
321
+ let id = startId;
322
+ let guard = 0;
323
+ while (id && guard++ < 500) {
324
+ const n = mapping[id];
325
+ if (!n) break;
326
+ const p = n.parent;
327
+ if (!p || typeof p !== 'string') break;
328
+ if (keepSet.has(p)) break;
329
+ keepSet.add(p);
330
+ id = p;
331
+ }
332
+ };
333
+
334
+ for (const id of Array.from(keepSet)) addAncestors(id);
335
+
336
+ // If there is an explicit root, keep it.
337
+ if (typeof data?.root === 'string' && data.root in mapping) keepSet.add(data.root);
338
+
339
+ const newMap = {};
340
+ for (const id of keepSet) if (id in mapping) newMap[id] = mapping[id];
341
+ data.mapping = newMap;
342
+ return { data, changed: true };
343
+ } catch {
344
+ return { data, changed: false };
345
+ }
346
+ }
347
+
348
+ async function thinIfNeeded(res) {
349
+ const startTs = performance.now();
350
+ try {
351
+ // Don’t spend heavy CPU while hidden under pressure/follower hold.
352
+ if (shouldDeferHeavyWork()) {
353
+ state.thinSkipped += 1;
354
+ publishState();
355
+ return res;
356
+ }
357
+
358
+ // Cumulative work guard
359
+ if (!canThinNow()) {
360
+ state.thinSkipped += 1;
361
+ publishState();
362
+ return res;
363
+ }
364
+
365
+ const ct = res.headers.get('content-type') || '';
366
+ if (!/application\/json|json/i.test(ct)) return res;
367
+
368
+ const clen = Number(res.headers.get('content-length') || 0);
369
+ if (clen > 0 && clen < MIN_THIN_BYTES) return res;
370
+
371
+ const clone = res.clone();
372
+
373
+ // Parse budget fail-open
374
+ if (overParseBudget(startTs)) {
375
+ state.thinSkipped += 1;
376
+ publishState();
377
+ return res;
378
+ }
379
+
380
+ const t0 = performance.now();
381
+ const data = await clone.json();
382
+ if (overParseBudget(t0)) {
383
+ state.thinSkipped += 1;
384
+ publishState();
385
+ return res;
386
+ }
387
+
388
+ if (overParseBudget(startTs)) {
389
+ state.thinSkipped += 1;
390
+ publishState();
391
+ return res;
392
+ }
393
+
394
+ let changed = false;
395
+ const KEEP = dynamicKeep();
396
+
397
+ if (Array.isArray(data?.messages) && data.messages.length > KEEP + 10) {
398
+ data.messages.sort((a, b) => (a.create_time || 0) - (b.create_time || 0));
399
+ data.messages = data.messages.slice(-KEEP);
400
+ changed = true;
401
+ } else if (data?.mapping && typeof data.mapping === 'object') {
402
+ const out = thinMappingWithAncestors(data, KEEP);
403
+ changed = changed || out.changed;
404
+ } else if (Array.isArray(data?.items) && data.items.length > KEEP + 10) {
405
+ data.items = data.items.slice(-KEEP);
406
+ changed = true;
407
+ }
408
+
409
+ if (!changed) return res;
410
+ if (overParseBudget(startTs)) {
411
+ state.thinSkipped += 1;
412
+ publishState();
413
+ return res; // fail-open late gate too
414
+ }
415
+
416
+ bumpThinCounter();
417
+ state.thinApplied += 1;
418
+
419
+ const headers = new Headers(res.headers);
420
+ try { headers.delete('content-length'); } catch {}
421
+ if (!headers.get('content-type')) headers.set('content-type', 'application/json; charset=utf-8');
422
+
423
+ const body = JSON.stringify(data);
424
+ publishState();
425
+ return new Response(body, { status: res.status, statusText: res.statusText, headers });
426
+ } catch (e) {
427
+ state.thinErrors += 1;
428
+ setLastError(e);
429
+ publishState();
430
+ // strict fail-open
431
+ return res;
432
+ }
433
+ }
434
+
435
+ function makeBlockedAbortError() {
436
+ const err = new DOMException('Blocked by Chat Traffic Gate', 'AbortError');
437
+ try { err.__tgBlocked = true; } catch {}
438
+ return err;
439
+ }
440
+
441
+ function isBlockedAbortError(e) {
442
+ if (!e) return false;
443
+ if (e.__tgBlocked === true) return true;
444
+ if (e.name === 'AbortError' && /Blocked by Chat Traffic Gate/i.test(String(e.message || ''))) return true;
445
+ return false;
446
+ }
447
+
448
+ function extractUrlFromFetchInput(input) {
449
+ try {
450
+ if (!input) return '';
451
+ if (typeof input === 'string') return input;
452
+ if (typeof URL !== 'undefined' && input instanceof URL) return input.href;
453
+ if (typeof input === 'object') {
454
+ if (typeof input.url === 'string') return input.url;
455
+ if (typeof input.href === 'string') return input.href;
456
+ }
457
+ } catch {}
458
+ try { return String(input); } catch { return ''; }
459
+ }
460
+
461
+ const _fetch = root.fetch;
462
+ if (typeof _fetch === 'function') {
463
+ root.fetch = async function patchedFetch(input, init) {
464
+ const fetchStart = performance.now();
465
+ const method = ((init && init.method) || 'GET').toUpperCase();
466
+ const url = extractUrlFromFetchInput(input);
467
+
468
+ try {
469
+ if (shouldBlock(method, url)) {
470
+ state.blocks += 1;
471
+ state.fetchBlocks += 1;
472
+ state.lastBlockUrl = String(url || '');
473
+ tlog('historyCancel');
474
+
475
+ // Prefer soft-block for list pagination: keeps UI calmer than an AbortError.
476
+ if (isSoftBlockCandidate(url)) {
477
+ state.softBlocks += 1;
478
+ publishState();
479
+ return softBlockResponse();
480
+ }
481
+
482
+ publishState();
483
+ throw makeBlockedAbortError();
484
+ }
485
+
486
+ const res = await _fetch.apply(this, arguments);
487
+
488
+ // Thin only paginated history responses (when allowed)
489
+ const out = looksHistory(url) ? await thinIfNeeded(res) : res;
490
+
491
+ const dt = performance.now() - fetchStart;
492
+ if (dt > 1200) {
493
+ state.lastSlowFetchMs = Math.round(dt);
494
+ try { root.__tgTelemetry && root.__tgTelemetry('slowFetch', { ms: state.lastSlowFetchMs }); } catch {}
495
+ publishState();
496
+ }
497
+
498
+ return out;
499
+ } catch (e) {
500
+ if (isBlockedAbortError(e)) {
501
+ state.fetchAborts += 1;
502
+ publishState();
503
+ throw e;
504
+ }
505
+
506
+ // Fail-open path for unexpected wrapper errors: attempt native fetch once.
507
+ try {
508
+ return await _fetch.apply(this, arguments);
509
+ } catch (nativeErr) {
510
+ setLastError(nativeErr || e);
511
+ publishState();
512
+ throw nativeErr;
513
+ }
514
+ }
515
+ };
516
+ }
517
+
518
+ const XHR = root.XMLHttpRequest;
519
+ if (XHR && XHR.prototype) {
520
+ const _open = XHR.prototype.open, _send = XHR.prototype.send;
521
+ XHR.prototype.open = function (method, url) {
522
+ try {
523
+ this.__tgMethod = String(method || 'GET').toUpperCase();
524
+ this.__tgURL = url;
525
+ } catch {}
526
+ return _open.apply(this, arguments);
527
+ };
528
+ XHR.prototype.send = function (body) {
529
+ try {
530
+ if (shouldBlock(this.__tgMethod, this.__tgURL)) {
531
+ state.blocks += 1;
532
+ state.xhrBlocks += 1;
533
+ state.lastBlockUrl = String(this.__tgURL || '');
534
+ try { this.abort(); } catch {}
535
+ try { this.dispatchEvent(new Event('error')); } catch {}
536
+ tlog('historyCancel');
537
+ publishState();
538
+ return;
539
+ }
540
+ } catch (e) {
541
+ setLastError(e);
542
+ publishState();
543
+ }
544
+ return _send.apply(this, arguments);
545
+ };
546
+ }
547
+
548
+ function diagnostics() {
549
+ return {
550
+ version: VERSION,
551
+ owner: OWNER,
552
+ gate: {
553
+ enabled: !!gate.enabled,
554
+ intent: !!gate.intent,
555
+ allowUntil: Number(gate.allowUntil || 0)
556
+ },
557
+ perf: {
558
+ profile: String(perf.profile || 'balanced'),
559
+ pressure: Number(perf.pressure || 0),
560
+ streamActive: !!perf.streamActive,
561
+ visible: !!perf.visible,
562
+ followerThrottle: !!perf.followerThrottle,
563
+ updatedAt: Number(perf.updatedAt || 0)
564
+ },
565
+ counters: {
566
+ blocks: state.blocks,
567
+ fetchBlocks: state.fetchBlocks,
568
+ xhrBlocks: state.xhrBlocks,
569
+ softBlocks: state.softBlocks,
570
+ softBlockResponses: state.softBlockResponses,
571
+ fetchAborts: state.fetchAborts,
572
+ thinApplied: state.thinApplied,
573
+ thinSkipped: state.thinSkipped,
574
+ thinErrors: state.thinErrors
575
+ },
576
+ last: {
577
+ lastBlockUrl: state.lastBlockUrl || '',
578
+ lastSlowFetchMs: state.lastSlowFetchMs || 0,
579
+ lastError: state.lastError || '',
580
+ lastErrorTs: Number(state.lastErrorTs || 0)
581
+ },
582
+ thinWindow: {
583
+ minute: thinWindow.minute,
584
+ count: thinWindow.count
585
+ }
586
+ };
587
+ }
588
+
589
+ function teardown() {
590
+ try { if (state.intervalId) clearInterval(state.intervalId); } catch {}
591
+ state.intervalId = null;
592
+ try { state.offCorePerf?.(); } catch {}
593
+ state.offCorePerf = null;
594
+ try { state.offCoreReady?.(); } catch {}
595
+ state.offCoreReady = null;
596
+ try { state.offCoreReused?.(); } catch {}
597
+ state.offCoreReused = null;
598
+ }
599
+
600
+ // Optional debug teardown hook
601
+ try {
602
+ Object.defineProperty(root, '__tgNetGuardTeardown', {
603
+ value: teardown,
604
+ writable: false,
605
+ configurable: true,
606
+ enumerable: false
607
+ });
608
+ } catch {}
609
+
610
+ // Optional debug diagnostics hook
611
+ try {
612
+ Object.defineProperty(root, '__tgNetGuardDiagnostics', {
613
+ value: diagnostics,
614
+ writable: false,
615
+ configurable: true,
616
+ enumerable: false
617
+ });
618
+ } catch {}
619
+
620
+ publishState({ bootedAt: Date.now() });
621
+ })();
GPTTrafficgateUPDATEDv3.1/content/traffic-ui.js ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function () {
2
+ 'use strict';
3
+
4
+ const api = (typeof browser !== 'undefined') ? browser : chrome;
5
+
6
+ const status = {
7
+ profile: 'balanced',
8
+ pressure: 0,
9
+ streamers: 0,
10
+ visibleStreamers: 0,
11
+ blockHistory: true,
12
+ allowUntil: 0,
13
+ role: 'follower',
14
+ followerThrottle: false
15
+ };
16
+
17
+ const health = {
18
+ sent: 0,
19
+ failed: 0,
20
+ retried: 0,
21
+ fallback: 0,
22
+ suppressed: 0,
23
+ queueDepth: 0,
24
+ queueOldestAgeMs: 0,
25
+ queueNewestAgeMs: 0,
26
+ lastOkTs: 0,
27
+ lastError: '',
28
+ role: 'follower',
29
+ signals: 0,
30
+ detected: 0,
31
+ enqueued: 0,
32
+
33
+ detectorMisses: 0,
34
+ lastStreamEndTs: 0,
35
+ lastEventId: '',
36
+ lastNotifyVia: '',
37
+ lastSignalAgeMs: 0,
38
+ lastDetectedAgeMs: 0,
39
+ lastSeenFreshKind: ''
40
+ };
41
+
42
+ const freshness = {
43
+ lastSignalTs: 0,
44
+ lastDetectedTs: 0,
45
+ lastNotifyTs: 0,
46
+ lastHealthTs: 0,
47
+ lastStreamEndTs: 0,
48
+ lastHeartbeatTs: 0,
49
+ heartbeatAgeMs: 0
50
+ };
51
+
52
+ const ui = {
53
+ paused: false,
54
+ hiddenPanel: false
55
+ };
56
+
57
+ const ledger = [];
58
+ let stale = false;
59
+ let pill, panel, stateChip, statsBox, eventsBox, gateBtn, allowBtn, testBtn, refreshBtn, togglePanelBtn, pauseBtn, clearBtn;
60
+
61
+ const STALE_SIGNAL_MS = 18000;
62
+ const STALE_HEALTH_MS = 20000;
63
+ const QUIET_DETECT_MS = 30000;
64
+
65
+ function mk(tag) { return document.createElement(tag); }
66
+
67
+ function ago(ts) {
68
+ if (!ts) return 'never';
69
+ const s = Math.max(0, Math.floor((Date.now() - ts) / 1000));
70
+ return s < 60 ? `${s}s ago` : `${Math.floor(s / 60)}m ago`;
71
+ }
72
+
73
+ function clamp(n, min, max) {
74
+ return Math.max(min, Math.min(max, n));
75
+ }
76
+
77
+ function pushEvt(txt) {
78
+ ledger.unshift(`[${new Date().toLocaleTimeString()}] ${txt}`);
79
+ if (ledger.length > 32) ledger.length = 32;
80
+ }
81
+
82
+ function logEvt(kind, msg, extra) {
83
+ const suffix = extra ? ` | ${extra}` : '';
84
+ pushEvt(`${kind}: ${msg}${suffix}`);
85
+ }
86
+
87
+ function deriveState() {
88
+ const now = Date.now();
89
+ const signalStale = freshness.lastSignalTs ? (now - freshness.lastSignalTs > STALE_SIGNAL_MS) : true;
90
+ const healthStale = freshness.lastHealthTs ? (now - freshness.lastHealthTs > STALE_HEALTH_MS) : true;
91
+ const detectStale = freshness.lastDetectedTs ? (now - freshness.lastDetectedTs > QUIET_DETECT_MS) : true;
92
+
93
+ if (stale || healthStale) return ['IDLE/STALE', '🟠'];
94
+
95
+ if (signalStale) return ['NO SIGNAL', '🟠'];
96
+
97
+ if ((health.failed || 0) >= Math.max(3, (health.sent || 0))) return ['NOTIFY FAILING', '🔴'];
98
+
99
+ if ((health.detectorMisses || 0) >= 2) return ['DETECTOR MISS', '🟡'];
100
+
101
+ if (detectStale && (status.streamers || 0) > 0) return ['DETECTOR QUIET', '🟡'];
102
+
103
+ if ((health.fallback || 0) > 0 || (health.retried || 0) > 0) return ['DEGRADED', '🟡'];
104
+
105
+ if (status.followerThrottle || (status.streamers || 0) > 1) return ['THROTTLED', '🟠'];
106
+
107
+ return ['OK', '🟢'];
108
+ }
109
+
110
+ function baseStyle(el, obj) { Object.assign(el.style, obj); }
111
+
112
+ function buttonStyle(btn) {
113
+ baseStyle(btn, {
114
+ background: '#2a2a2a',
115
+ color: '#fff',
116
+ border: '1px solid #444',
117
+ borderRadius: '8px',
118
+ padding: '4px 8px',
119
+ cursor: 'pointer'
120
+ });
121
+ }
122
+
123
+ function ensureUI() {
124
+ if (pill && document.contains(pill)) return;
125
+
126
+ pill = mk('div');
127
+ baseStyle(pill, {
128
+ position: 'fixed',
129
+ right: '10px',
130
+ bottom: '10px',
131
+ zIndex: '2147483647',
132
+ background: 'rgba(18,18,18,.92)',
133
+ color: '#fff',
134
+ border: '1px solid #2f2f2f',
135
+ borderRadius: '12px',
136
+ padding: '8px 10px',
137
+ fontSize: '12px',
138
+ fontFamily: 'ui-sans-serif,system-ui',
139
+ display: 'flex',
140
+ gap: '8px',
141
+ alignItems: 'center',
142
+ boxShadow: '0 8px 20px rgba(0,0,0,.38)'
143
+ });
144
+
145
+ stateChip = mk('span');
146
+ stateChip.textContent = '🟢 OK';
147
+
148
+ gateBtn = mk('button');
149
+ allowBtn = mk('button');
150
+ togglePanelBtn = mk('button');
151
+ pauseBtn = mk('button');
152
+
153
+ gateBtn.textContent = '🚦 On';
154
+ allowBtn.textContent = 'Allow 10s';
155
+ togglePanelBtn.textContent = 'Panel';
156
+ pauseBtn.textContent = 'Pause UI';
157
+
158
+ for (const b of [gateBtn, allowBtn, togglePanelBtn, pauseBtn]) buttonStyle(b);
159
+
160
+ gateBtn.onclick = async () => {
161
+ status.blockHistory = !status.blockHistory;
162
+ try { window.__chatTrafficGate?.setEnabled(status.blockHistory); } catch {}
163
+ try { await api.storage.local.set({ blockHistory: status.blockHistory }); } catch {}
164
+ try { await api.runtime.sendMessage({ type: 'toggleBlockHistory', value: status.blockHistory }); } catch {}
165
+ logEvt('gate', status.blockHistory ? 'on' : 'off');
166
+ render();
167
+ };
168
+
169
+ allowBtn.onclick = async () => {
170
+ const ms = 10000;
171
+ status.allowUntil = Date.now() + ms;
172
+ try { window.__chatTrafficGate?.allowForMs(ms); } catch {}
173
+ try { await api.runtime.sendMessage({ type: 'allowHistoryForMs', ms }); } catch {}
174
+ logEvt('gate', 'allow 10s');
175
+ render();
176
+ };
177
+
178
+ togglePanelBtn.onclick = () => {
179
+ ui.hiddenPanel = !ui.hiddenPanel;
180
+ panel.style.display = ui.hiddenPanel ? 'none' : 'block';
181
+ togglePanelBtn.textContent = ui.hiddenPanel ? 'Panel (off)' : 'Panel';
182
+ };
183
+
184
+ pauseBtn.onclick = () => {
185
+ ui.paused = !ui.paused;
186
+ pauseBtn.textContent = ui.paused ? 'Resume UI' : 'Pause UI';
187
+ logEvt('ui', ui.paused ? 'paused' : 'resumed');
188
+ render();
189
+ };
190
+
191
+ pill.append(stateChip, gateBtn, allowBtn, togglePanelBtn, pauseBtn);
192
+ document.documentElement.appendChild(pill);
193
+
194
+ panel = mk('div');
195
+ baseStyle(panel, {
196
+ position: 'fixed',
197
+ right: '10px',
198
+ bottom: '56px',
199
+ zIndex: '2147483647',
200
+ width: '390px',
201
+ maxHeight: '58vh',
202
+ overflow: 'auto',
203
+ background: 'rgba(10,10,10,.95)',
204
+ color: '#fff',
205
+ border: '1px solid #2d2d2d',
206
+ borderRadius: '12px',
207
+ padding: '10px',
208
+ fontSize: '12px',
209
+ fontFamily: 'ui-monospace,Consolas,monospace',
210
+ boxShadow: '0 10px 24px rgba(0,0,0,.45)'
211
+ });
212
+
213
+ const hdr = mk('div');
214
+ hdr.textContent = 'Traffic Gate Health';
215
+ baseStyle(hdr, {
216
+ fontWeight: '700',
217
+ marginBottom: '8px',
218
+ fontFamily: 'ui-sans-serif,system-ui'
219
+ });
220
+
221
+ statsBox = mk('pre');
222
+ eventsBox = mk('pre');
223
+ baseStyle(statsBox, { whiteSpace: 'pre-wrap', margin: '0 0 8px 0' });
224
+ baseStyle(eventsBox, { whiteSpace: 'pre-wrap', margin: '0' });
225
+
226
+ const row = mk('div');
227
+ baseStyle(row, { display: 'flex', gap: '8px', marginBottom: '8px', flexWrap: 'wrap' });
228
+
229
+ testBtn = mk('button');
230
+ refreshBtn = mk('button');
231
+ clearBtn = mk('button');
232
+
233
+ testBtn.textContent = 'Test notify';
234
+ refreshBtn.textContent = 'Refresh';
235
+ clearBtn.textContent = 'Clear events';
236
+
237
+ for (const b of [testBtn, refreshBtn, clearBtn]) buttonStyle(b);
238
+
239
+ testBtn.onclick = async () => {
240
+ const id = 'test_' + Date.now();
241
+ try {
242
+ const r = await api.runtime.sendMessage({
243
+ type: 'tgNotify',
244
+ eventId: id,
245
+ title: 'ChatGPT',
246
+ message: 'Manual test notify'
247
+ });
248
+ logEvt('notify', r && r.ok ? 'test ok' : 'test fail', id);
249
+ } catch {
250
+ logEvt('notify', 'test error');
251
+ }
252
+ await refreshHealth();
253
+ render();
254
+ };
255
+
256
+ refreshBtn.onclick = async () => {
257
+ await refreshHealth();
258
+ render();
259
+ };
260
+
261
+ clearBtn.onclick = () => {
262
+ ledger.length = 0;
263
+ logEvt('ui', 'events cleared');
264
+ render();
265
+ };
266
+
267
+ row.append(testBtn, refreshBtn, clearBtn);
268
+ panel.append(hdr, row, statsBox, eventsBox);
269
+ document.documentElement.appendChild(panel);
270
+ }
271
+
272
+ async function refreshHealth() {
273
+ try {
274
+ const r = await api.runtime.sendMessage({ type: 'tgNotifyHealth' });
275
+ freshness.lastHealthTs = Date.now();
276
+ stale = false;
277
+
278
+ if (r && r.stats) {
279
+ health.sent = Number(r.stats.sent || 0);
280
+ health.failed = Number(r.stats.failed || 0);
281
+ health.retried = Number(r.stats.retried || 0);
282
+ health.fallback = Number(r.stats.fallback || 0);
283
+ health.suppressed = Number(r.stats.suppressed || 0);
284
+ health.queueDepth = Number(r.queue || 0);
285
+ health.queueOldestAgeMs = Number(r.queueOldestAgeMs || health.queueOldestAgeMs || 0);
286
+ health.queueNewestAgeMs = Number(r.queueNewestAgeMs || health.queueNewestAgeMs || 0);
287
+ health.lastError = String(r.stats.lastError || health.lastError || '');
288
+ health.lastEventId = String(r.stats.lastEventId || health.lastEventId || '');
289
+ health.lastNotifyVia = String(r.stats.lastNotifyVia || health.lastNotifyVia || '');
290
+ }
291
+
292
+ // pull streamer budget directly from background snapshot (reliable even without recent perf events)
293
+ if (r?.orchestration?.budget) {
294
+ const b = r.orchestration.budget;
295
+ status.streamers = Number(b.totalStreamers || 0);
296
+ status.visibleStreamers = Number(b.visibleStreamers || 0);
297
+ status.followerThrottle = !!b.followerHold;
298
+ }
299
+
300
+ if (r?.orchestration?.health) {
301
+ const h = r.orchestration.health;
302
+ health.signals = Number(h.signals || 0);
303
+
304
+ // background schema uses detected_received / enqueued
305
+ health.detected = Number(h.detected_received || h.detected || 0);
306
+ health.enqueued = Number(h.enqueued || 0);
307
+
308
+ health.lastOkTs = Number(h.lastOkTs || 0);
309
+ health.detectorMisses = Number(h.detectorMisses || health.detectorMisses || 0);
310
+ health.lastSignalAgeMs = Number(h.lastSignalAgeMs || health.lastSignalAgeMs || 0);
311
+ health.lastDetectedAgeMs = Number(h.lastDetectedAgeMs || health.lastDetectedAgeMs || 0);
312
+ health.lastSeenFreshKind = String(h.lastSeenFreshKind || health.lastSeenFreshKind || '');
313
+
314
+ freshness.lastSignalTs = Number(h.lastSignalTs || freshness.lastSignalTs || 0);
315
+ freshness.lastDetectedTs = Number(h.lastDetectedTs || freshness.lastDetectedTs || 0);
316
+ freshness.lastStreamEndTs = Number(h.lastStreamEndTs || freshness.lastStreamEndTs || 0);
317
+ }
318
+
319
+ if (Array.isArray(r?.last)) {
320
+ for (const x of r.last.slice(-4)) {
321
+ const via = x?.via || 'evt';
322
+ const ok = x?.ok ? 'ok' : 'fail';
323
+ const eid = x?.eventId || '';
324
+ logEvt('last', `${via} ${ok}`, eid);
325
+ }
326
+ }
327
+ } catch {
328
+ stale = true;
329
+ logEvt('health', 'pull failed');
330
+ }
331
+ }
332
+
333
+ function render() {
334
+ ensureUI();
335
+ if (ui.paused) return;
336
+
337
+ const now = Date.now();
338
+ const inAllow = now < (status.allowUntil || 0);
339
+
340
+ freshness.heartbeatAgeMs = freshness.lastHeartbeatTs ? (now - freshness.lastHeartbeatTs) : 0;
341
+
342
+ gateBtn.textContent = status.blockHistory ? '🚦 On' : '🚦 Off';
343
+ allowBtn.textContent = inAllow ? `Allow ${Math.ceil((status.allowUntil - now) / 1000)}s` : 'Allow 10s';
344
+
345
+ const [txt, emoji] = deriveState();
346
+ stateChip.textContent = `${emoji} ${txt}`;
347
+ pill.title =
348
+ `profile:${status.profile} pressure:${Math.round(status.pressure || 0)} ` +
349
+ `streamers:${status.streamers || 0} visible:${status.visibleStreamers || 0} signals:${health.signals || 0} detected:${health.detected || 0}`;
350
+
351
+ statsBox.textContent =
352
+ `role: ${status.role}
353
+ profile: ${status.profile}
354
+ pressure: ${Math.round(status.pressure || 0)}
355
+ streamers(total/visible): ${status.streamers || 0}/${status.visibleStreamers || 0}
356
+ followerThrottle: ${status.followerThrottle ? 'yes' : 'no'}
357
+
358
+ notify sent/failed/retried: ${health.sent}/${health.failed}/${health.retried}
359
+ fallback/suppressed: ${health.fallback}/${health.suppressed}
360
+ queueDepth: ${health.queueDepth}
361
+ queueOldestAgeMs: ${health.queueOldestAgeMs || 0}
362
+ queueNewestAgeMs: ${health.queueNewestAgeMs || 0}
363
+ lastNotifyVia: ${health.lastNotifyVia || '-'}
364
+ lastEventId: ${health.lastEventId || '-'}
365
+
366
+ signals/detected/enqueued: ${health.signals}/${health.detected}/${health.enqueued}
367
+ detectorMisses: ${health.detectorMisses}
368
+ lastFreshKind: ${health.lastSeenFreshKind || '-'}
369
+ lastStreamEnd: ${ago(freshness.lastStreamEndTs)}
370
+ lastSignal: ${ago(freshness.lastSignalTs)}
371
+ lastDetected: ${ago(freshness.lastDetectedTs)}
372
+ lastNotifyOk: ${ago(health.lastOkTs)}
373
+ lastHealthPull: ${ago(freshness.lastHealthTs)}
374
+
375
+ signalAgeMs(bg): ${health.lastSignalAgeMs || 0}
376
+ detectedAgeMs(bg): ${health.lastDetectedAgeMs || 0}
377
+ heartbeatAgeMs(local): ${freshness.heartbeatAgeMs || 0}
378
+ lastError: ${health.lastError || '-'}`;
379
+
380
+ eventsBox.textContent = 'events:\n' + (ledger.length ? ledger.join('\n') : '(none)');
381
+ }
382
+
383
+ function bindEvents() {
384
+ window.addEventListener('tg:perf-profile', (ev) => {
385
+ const d = ev?.detail || {};
386
+ status.profile = d.profile || status.profile;
387
+ status.pressure = Number(d.pressure || status.pressure || 0);
388
+
389
+ // live profile events can carry budget hints
390
+ status.streamers = Number(d.totalStreamers || status.streamers || 0);
391
+ status.visibleStreamers = Number(d.visibleStreamers || status.visibleStreamers || 0);
392
+
393
+ status.role = d.role || status.role;
394
+ status.followerThrottle = !!d.followerThrottle;
395
+ freshness.lastSignalTs = Date.now();
396
+ logEvt('profile', `${status.profile} p=${Math.round(status.pressure || 0)} s=${status.streamers || 0}/${status.visibleStreamers || 0}`);
397
+ render();
398
+ }, { passive: true });
399
+
400
+ window.addEventListener('tg:reply-ready', (ev) => {
401
+ freshness.lastDetectedTs = Date.now();
402
+ health.detected = (health.detected || 0) + 1;
403
+ const d = ev?.detail || {};
404
+ logEvt('reply', `ready from ${d.tabId || 'tab'}`, `seq:${d.replySeq || '-'} id:${d.eventId || '-'}`);
405
+ render();
406
+ }, { passive: true });
407
+
408
+ // explicit freshness stream from autopilot
409
+ window.addEventListener('tg:signal-freshness', (ev) => {
410
+ const d = ev?.detail || {};
411
+ const kind = String(d.kind || 'tick');
412
+ health.lastSeenFreshKind = kind;
413
+
414
+ freshness.lastSignalTs = Number(d.ts || Date.now());
415
+ stale = false;
416
+
417
+ if (kind === 'heartbeat' || kind === 'heartbeat_forced') {
418
+ freshness.lastHeartbeatTs = Number(d.ts || Date.now());
419
+ }
420
+
421
+ if (kind === 'reply_detected') {
422
+ freshness.lastDetectedTs = Number(d.ts || Date.now());
423
+ health.detected = (health.detected || 0) + 1;
424
+ if (d.eventId) health.lastEventId = String(d.eventId);
425
+ }
426
+
427
+ if (kind === 'stream_transition' && d.streamEndTs) {
428
+ freshness.lastStreamEndTs = Number(d.streamEndTs || 0);
429
+ health.lastStreamEndTs = freshness.lastStreamEndTs;
430
+ }
431
+
432
+ if (kind === 'detector_miss') {
433
+ health.detectorMisses = Math.max(health.detectorMisses || 0, Number(d.detectorMisses || 0));
434
+ }
435
+
436
+ if (kind !== 'heartbeat') {
437
+ const compact = `k=${kind} p=${Math.round(Number(d.pressure || status.pressure || 0))} vis=${d.visible ? 1 : 0}`;
438
+ logEvt('fresh', compact);
439
+ }
440
+
441
+ render();
442
+ }, { passive: true });
443
+ }
444
+
445
+ function startStaleWatchdog() {
446
+ setInterval(() => {
447
+ const now = Date.now();
448
+ const healthTooOld = freshness.lastHealthTs && (now - freshness.lastHealthTs > STALE_HEALTH_MS);
449
+ const signalTooOld = freshness.lastSignalTs && (now - freshness.lastSignalTs > STALE_SIGNAL_MS);
450
+ stale = !!(healthTooOld || signalTooOld);
451
+ }, 2000);
452
+ }
453
+
454
+ async function init() {
455
+ ensureUI();
456
+ bindEvents();
457
+ startStaleWatchdog();
458
+
459
+ try {
460
+ const resp = await api.runtime.sendMessage({ type: 'requestStatus' });
461
+ if (resp) {
462
+ status.blockHistory = !!resp.blockHistory;
463
+ status.allowUntil = Number(resp.allowUntil || 0);
464
+ status.role = resp.role || status.role;
465
+ }
466
+ } catch {}
467
+
468
+ await refreshHealth();
469
+ render();
470
+
471
+ // health pull loop
472
+ setInterval(async () => {
473
+ await refreshHealth();
474
+ render();
475
+ }, 5000);
476
+
477
+ // ui countdown / age loop
478
+ setInterval(render, 1000);
479
+ }
480
+
481
+ if (document.readyState === 'loading') {
482
+ document.addEventListener('DOMContentLoaded', init, { once: true });
483
+ } else {
484
+ init();
485
+ }
486
+ })();
GPTTrafficgateUPDATEDv3.1/manifest.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "manifest_version": 2,
3
+ "name": "Chat Traffic Gate (ChatGPT) — AutoPilot v3.1 (Orchestrated Diagnostics)",
4
+ "version": "1.3.0",
5
+ "description": "Network history gate + cross-tab orchestrator + observable notification health panel.",
6
+ "author": "local",
7
+ "homepage_url": "https://chatgpt.com/",
8
+ "permissions": [
9
+ "storage",
10
+ "webRequest",
11
+ "alarms",
12
+ "tabs",
13
+ "notifications",
14
+ "https://chat.openai.com/*",
15
+ "https://chatgpt.com/*"
16
+ ],
17
+ "background": {
18
+ "scripts": [
19
+ "background.js"
20
+ ],
21
+ "persistent": false
22
+ },
23
+ "content_scripts": [
24
+ {
25
+ "matches": [
26
+ "https://chat.openai.com/*",
27
+ "https://chatgpt.com/*"
28
+ ],
29
+ "js": [
30
+ "content/core-utils.js",
31
+ "content/early-shield.js",
32
+ "content/net-guard.js"
33
+ ],
34
+ "run_at": "document_start",
35
+ "all_frames": false
36
+ },
37
+ {
38
+ "matches": [
39
+ "https://chat.openai.com/*",
40
+ "https://chatgpt.com/*"
41
+ ],
42
+ "js": [
43
+ "content/core-utils.js",
44
+ "content/dom-softcap.js",
45
+ "content/keepalive.js",
46
+ "content/autopilot.js",
47
+ "content/traffic-ui.js"
48
+ ],
49
+ "run_at": "document_idle",
50
+ "all_frames": false
51
+ }
52
+ ],
53
+ "browser_specific_settings": {
54
+ "gecko": {
55
+ "id": "chat-traffic-gate@local",
56
+ "strict_min_version": "109.0"
57
+ }
58
+ }
59
+ }