ChatGPT Business arayüzünde Sohbet, Çalışma/Codex ve Otonom Ajanlar aynı yerde görünmesine rağmen kullanım limitleri aynı değil. Özellikle ortak kota fark edilmeden tüketilebildiği için küçük bir Tampermonkey paneli hazırladım.
Ne yapıyor?
- Normal Sohbet ile ortak kota kullanan işleri ayırıyor.
- Çalışma, Codex ve Otonom Ajanları tek başlık altında 🤖 ORTAK KOTA olarak gösteriyor.
- Ortak kotanın 5 saatlik ve haftalık kalan yüzdesini gösteriyor.
- Kota sıfırlanmasına kalan süreyi takip ediyor.
- Varsa tam sıfırlama hakkını ve son kullanım tarihini gösteriyor.
- Verileri otomatik olarak yaklaşık 5 dakikada bir yeniliyor; ayrıca Şimdi güncelle düğmesi var.
- Kota bittiğinde veya azaldığında uyarı verebiliyor.
- 🆓 HIZLI
- ⚪ ORTA
- 🟡 YÜKSEK
- 🟢 ÇOK YÜKSEK
- 🧠 PRO
Panel açıldığında, uygun durumda 🟢 Çok Yükseğe geç düğmesi de bulunuyor.
Sol sohbet listesi
Ortak kota kullandığı daha önce tespit edilen Çalışma/Codex konuşmaları sol menüde otomatik olarak işaretleniyor:
- Turuncu arka plan
- Turuncu sol çizgi
- 🤖 simgesi
Kullanım mantığı
Normal Sohbet → Ortak Codex/Çalışma kotasından bağımsız.
🤖 ORTAK KOTA → Çalışma, Codex ve Otonom Ajanlar tarafından ortak kullanılan limit.
Bu ayrım özellikle ekip hesabında önemli; otonom ajanlar veya başka kullanıcıların çalışmaları ortak haftalık kotayı tüketebiliyor.
Kurulum
- Tarayıcıya Tampermonkey kurun.
- Yeni bir kullanıcı betiği oluşturun.
- Varsayılan kodu silin.
- Aşağıdaki betiğin tamamını yapıştırıp kaydedin.
- Ekleti ayarınca Tempermonkey için Kullanıcı komut dosyalarına izin ver seçili olduğuna emin olun.
- ChatGPT sayfasını yenileyin.
Not: ChatGPT arayüzü zaman zaman değiştiği için mod/model algılama kısmı gelecekte güncelleme gerektirebilir. Betik yalnızca tarayıcı tarafında çalışır ve ChatGPT arayüzünde gösterilen kullanım bilgilerini okumaya çalışır.
Güncel sürüm: v1.5.8
// ==UserScript==
// @name ChatGPT Limit Takip Paneli
// @namespace https://chatgpt.com/
// @version 1.5.8
// @description ChatGPT Çalışma kotasını izler; Sohbet/Çalışma modunu güçlü arayüz ipuçlarıyla ayırt eder ve 5 dakikada bir günceller.
// @author İbrahim Metin Çiriş için
// @match https://chatgpt.com/*
// @run-at document-idle
// @grant GM_notification
// ==/UserScript==
(function () {
'use strict';
const PANEL_ID = 'chatgpt-limit-takip-paneli';
const STORAGE_KEY = 'chatgpt-limit-takip-v1';
const ALERT_KEY = 'chatgpt-limit-takip-alerts-v1';
const POSITION_KEY = 'chatgpt-limit-takip-position-v1';
const THREAD_MODE_KEY = 'chatgpt-limit-thread-modes-v1';
const MODE_ALERT_KEY = 'chatgpt-limit-takip-mode-alert-v1';
const SCAN_INTERVAL_MS = 4000;
const BACKGROUND_REFRESH_MS = 5 * 60 * 1000;
const USAGE_URL = 'https://chatgpt.com/codex/settings/usage';
const FRAME_ID = 'chatgpt-limit-takip-usage-frame';
const IS_EMBEDDED = window.top !== window.self;
let nextBackgroundRefreshAt = Date.now() + BACKGROUND_REFRESH_MS;
let usageFrame = null;
let lastMode = null;
const emptyState = () => ({
fiveHour: { remaining: null, reset: '', resetAt: null },
weekly: { remaining: null, reset: '', resetAt: null },
resetRight: { available: false, type: '', expires: '' },
updatedAt: null,
});
function loadState() {
try {
return { ...emptyState(), ...JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') };
} catch {
return emptyState();
}
}
function saveState(state) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
function visiblePageText() {
const roots = [...document.querySelectorAll('[role="dialog"], main')];
const source = roots.length ? roots : [document.body];
return source
.filter((el) => el && el.id !== PANEL_ID)
.map((el) => el.innerText || '')
.join('n')
.replace(/u00a0/g, ' ');
}
function linesOf(text) {
return text.split(/n+/).map((line) => line.trim()).filter(Boolean);
}
function parseRemaining(block) {
const joined = block.join(' ');
const tr = joined.match(/%(d{1,3}(?:[.,]d+)?)s*kald[ıi]/i);
const en = joined.match(/(d{1,3}(?:[.,]d+)?)s*%s*(?:remaining|left)/i);
const value = tr?.[1] ?? en?.[1];
return value == null ? null : Math.max(0, Math.min(100, Number(value.replace(',', '.'))));
}
function hasResetTime(text) {
if (!text) return false;
return /bd{1,2}:d{2}b/.test(text) || /bd+s*(?:dk|dakika|dak|sa|saat|gün|hafta|minute(?:s)?|min|hour(?:s)?|day(?:s)?|week(?:s)?)b/i.test(text);
}
function validReset(text) {
return hasResetTime(text) ? text : '';
}
function parseReset(block) {
for (let i = 0; i < block.length; i += 1) {
if (/(?:sonras+yenilenecek|yenilenecek|resets?s+in|resets+at)/i.test(block[i])) {
const line = block[i];
if (hasResetTime(line)) return line;
if (i > 0 && hasResetTime(block[i - 1])) return `${block[i - 1]} ${line}`;
return '';
}
}
return '';
}
function parseLimit(lines, headingPattern) {
const index = lines.findIndex((line) => headingPattern.test(line));
if (index < 0) return null;
const block = lines.slice(index, index + 12);
const remaining = parseRemaining(block);
if (remaining == null) return null;
return { remaining, reset: parseReset(block) };
}
function parsePage() {
const lines = linesOf(visiblePageText());
const state = loadState();
const fiveHour = parseLimit(lines, /^(?:5s*saatliks*limit|5[- ]hour(?:s+limit)?)/i);
const weekly = parseLimit(lines, /^(?:haftalıks*limit|weekly(?:s+limit)?)/i);
const rightsIndex = lines.findIndex((line) => /(?:kullanıms+limitis+yenilemes+hakları|usages+limits+reset)/i.test(line));
let resetRight = null;
if (rightsIndex >= 0) {
const block = lines.slice(rightsIndex, rightsIndex + 14);
const type = block.find((line) => /(?:tams+sıfırlama|fulls+reset)/i.test(line)) || '';
const expires = block.find((line) => /(?:bitişs+zamanı|expires?)/i.test(line)) || '';
resetRight = { available: Boolean(type || expires), type, expires };
}
if (!fiveHour && !weekly && !resetRight) return state;
const next = {
fiveHour: fiveHour ? { ...state.fiveHour, ...fiveHour } : state.fiveHour,
weekly: weekly ? { ...state.weekly, ...weekly } : state.weekly,
resetRight: resetRight || state.resetRight,
updatedAt: new Date().toISOString(),
};
saveState(next);
maybeNotify(next);
return next;
}
function colorFor(value) {
if (value == null) return '#94a3b8';
if (value < 20) return '#ef4444';
if (value < 40) return '#f59e0b';
if (value < 70) return '#38bdf8';
return '#22c55e';
}
function normalizeUiText(value) {
return String(value || '')
.replace(/u00a0/g, ' ')
.replace(/s+/g, ' ')
.trim()
.toLocaleLowerCase('tr-TR');
}
function modeFromText(text) {
const t = normalizeUiText(text);
if (/^(çalışma|work)$/.test(t)) return 'work';
if (/^(sohbet|chat)$/.test(t)) return 'chat';
return null;
}
function detectCurrentMode() {
// ÖNEMLİ:
// Sohbet geçmişinin tamamını taramıyoruz. Aksi halde kullanıcı bu konuşmada
// "Usage limits exceeded..." veya "Çalışma" kelimelerini konuştuğunda normal
// sohbet yanlışlıkla ortak-kota modu sanılabiliyor.
const url = `${location.pathname} ${location.search} ${location.hash}`.toLowerCase();
// 1) URL'de açık ve güvenilir ajan/çalışma işareti varsa.
if (/(?:^|[/?#&=_-])(?:workspace-agent|agent-mode|work-mode)(?:$|[/?#&=_-])/.test(url)) {
return { mode: 'work', source: 'url' };
}
// 2) Composer: "İstediğin konu üstünde çalış" kesin Çalışma sinyalidir.
const composerNodes = document.querySelectorAll(
'textarea,input,[contenteditable="true"],[data-placeholder],[aria-label]'
);
let hasChatComposer = false;
for (const el of composerNodes) {
if (el.closest?.(`#${PANEL_ID}`)) continue;
const hint = normalizeUiText([
el.getAttribute?.('placeholder'),
el.getAttribute?.('data-placeholder'),
el.getAttribute?.('aria-label')
].filter(Boolean).join(' '));
if (!hint) continue;
if (/istediğin konu üstünde çalış|istedigin konu ustunde calis|work on anything|work on a task/.test(hint)) {
return { mode: 'work', source: 'composer-work' };
}
if (/chatgpt['’]?ye sor|ask chatgpt|message chatgpt/.test(hint)) {
hasChatComposer = true;
}
}
// 3) Ajan hata mesajını yalnızca SON ve KISA asistan mesajıysa kabul et.
// Böylece eski mesajlarda bu cümleyi konuşmuş olmamız yanlış pozitif üretmez.
const assistantMessages = [...document.querySelectorAll('[data-message-author-role="assistant"]')];
const lastAssistant = assistantMessages.at(-1);
if (lastAssistant) {
const lastText = normalizeUiText(lastAssistant.innerText || lastAssistant.textContent || '');
if (
lastText.length <= 220 &&
/^usage limits exceeded[.! ]*not running this agent[.! ]*$/.test(lastText)
) {
return { mode: 'work', source: 'last-agent-error' };
}
}
const composer = composerElement();
const composerRect = composer?.getBoundingClientRect?.();
// 4) Composer yakınındaki, mesaj balonu DIŞINDAKİ sistem uyarıları.
// Eski konuşma metinlerini değil, yalnız aktif alt arayüzü tarar.
const signalNodes = document.querySelectorAll(
'[role="alert"],[role="status"],main div,main p,main span'
);
for (const el of signalNodes) {
if (!isActuallyVisible(el) || el.closest?.(`#${PANEL_ID}`)) continue;
if (el.closest?.('[data-message-author-role]')) continue;
const rect = el.getBoundingClientRect();
if (composerRect) {
const nearComposer = rect.bottom >= composerRect.top - 330 && rect.top <= composerRect.bottom + 40;
if (!nearComposer) continue;
}
const t = normalizeUiText(el.innerText || el.textContent || '');
if (!t || t.length > 260) continue;
if (
/şimdilik çalışma kullanım hakkınız kalmadı|simdilik calisma kullanim hakkiniz kalmadi/.test(t) ||
/çalışma alanının kredileri tükendi|calisma alaninin kredileri tukendi/.test(t) ||
/usage limits exceeded[.! ]*not running this agent/.test(t)
) {
return { mode: 'work', source: 'near-composer-system' };
}
}
// 5) Üst breadcrumb/header'daki "... · Çalışma" işareti.
// Yalnız ekranın üst şeridini okuyoruz; sohbet geçmişini değil.
const topNodes = document.querySelectorAll(
'header *,[role="banner"] *,main h1,main h2,main h3,main button,main [role="button"],main div,main span'
);
for (const el of topNodes) {
if (!isActuallyVisible(el) || el.closest?.(`#${PANEL_ID}`)) continue;
if (el.closest?.('[data-message-author-role]')) continue;
const rect = el.getBoundingClientRect();
if (rect.top < -5 || rect.top > 115) continue;
const t = normalizeUiText(el.innerText || el.textContent || '');
if (!t || t.length > 180) continue;
if (/[·•]s*çalışma(?:s|$)|[·•]s*work(?:s|$)/.test(t)) {
return { mode: 'work', source: 'top-breadcrumb' };
}
}
// 6) Aktif/işaretli Sohbet-Çalışma kontrolleri.
const activeSelectors = [
'[role="tab"][aria-selected="true"]',
'[aria-pressed="true"]',
'[data-state="active"]',
'[aria-current="page"]',
'[aria-current="true"]'
];
for (const selector of activeSelectors) {
for (const el of document.querySelectorAll(selector)) {
if (el.closest?.(`#${PANEL_ID}`)) continue;
const mode = modeFromText(el.innerText || el.textContent || el.getAttribute?.('aria-label'));
if (mode) return { mode, source: 'active-ui' };
}
}
// 7) Ajan kartı: composer'ın hemen üstünde, mesaj balonu dışında kısa bir ajan adı
// varsa ve aynı ad sol menüde Otonom Ajanlar bölümünde görünüyorsa ortak kota say.
if (composerRect) {
const sidebarCandidates = [...document.querySelectorAll('aside a,aside button,nav a,nav button,a,button')]
.filter((el) => {
if (!isActuallyVisible(el) || el.closest?.(`#${PANEL_ID}`)) return false;
const r = el.getBoundingClientRect();
return r.left < 340 && r.width > 40 && r.width < 320;
})
.map((el) => normalizeUiText(el.innerText || el.textContent || ''))
.filter((t) => t && t.length >= 4 && t.length <= 90 && !/ajanlara göz at|browse agents/.test(t));
if (sidebarCandidates.length) {
const nearComposerLabels = [...document.querySelectorAll('main div,main span,main p,main button')]
.filter((el) => {
if (!isActuallyVisible(el) || el.closest?.(`#${PANEL_ID}`)) return false;
if (el.closest?.('[data-message-author-role]')) return false;
const r = el.getBoundingClientRect();
return r.left > 300 &&
r.bottom >= composerRect.top - 120 &&
r.top <= composerRect.top + 20;
})
.map((el) => normalizeUiText(el.innerText || el.textContent || ''))
.filter((t) => t && t.length >= 4 && t.length <= 90);
if (nearComposerLabels.some((label) => sidebarCandidates.includes(label))) {
return { mode: 'work', source: 'agent-card' };
}
}
}
// 8) "ChatGPT'ye sor" ancak bütün ortak-kota kontrollerinden SONRA Sohbet sayılır.
if (hasChatComposer) {
return { mode: 'chat', source: 'composer-chat' };
}
return { mode: 'unknown', source: 'unknown' };
}
function loadThreadModes() {
try {
const parsed = JSON.parse(localStorage.getItem(THREAD_MODE_KEY) || '{}');
return parsed && typeof parsed === 'object' ? parsed : {};
} catch {
return {};
}
}
function saveThreadModes(map) {
try {
localStorage.setItem(THREAD_MODE_KEY, JSON.stringify(map));
} catch { /* localStorage doluysa sessizce geç. */ }
}
function canonicalThreadKey(href = location.href) {
try {
const u = new URL(href, location.origin);
const path = u.pathname.replace(//+$/, '') || '/';
// ChatGPT sohbet sayfalarında genellikle /c/<id> kullanılır.
// Arayüz başka bir sohbet rotası kullanırsa, benzersiz ve uzun son segmenti de kabul et.
if (/^/c/[^/]+$/i.test(path)) return path;
const parts = path.split('/').filter(Boolean);
const last = parts.at(-1) || '';
if (last.length >= 20 && !/^(settings|usage|library|projects|gpts?)$/i.test(last)) {
return path;
}
} catch {}
return '';
}
function rememberCurrentThreadMode(detectedMode) {
const key = canonicalThreadKey();
if (!key || !detectedMode || !['chat', 'work'].includes(detectedMode.mode)) return;
const map = loadThreadModes();
const nextMode = detectedMode.mode;
// Çalışma/ajan olarak kesin algılanmış bir konuşmayı kalıcı biçimde işaretle.
// Normal sohbet olarak kesin algılanırsa daha önceki yanlış işareti temizle.
if (nextMode === 'work') {
map[key] = { mode: 'work', seenAt: Date.now() };
} else if (nextMode === 'chat' && map[key]?.mode === 'work') {
// Yanlış pozitifleri kendi kendine düzeltebilmek için sohbet tespitinde kaldır.
delete map[key];
}
saveThreadModes(map);
}
function sidebarConversationLinks() {
return [...document.querySelectorAll('a[href]')].filter((a) => {
if (a.closest?.(`#${PANEL_ID}`) || !isActuallyVisible(a)) return false;
const r = a.getBoundingClientRect();
if (r.left > 340 || r.width < 80 || r.height < 18) return false;
return Boolean(canonicalThreadKey(a.href));
});
}
function directWorkHintForSidebarLink(link) {
const t = normalizeUiText([
link.innerText,
link.textContent,
link.getAttribute('aria-label'),
link.getAttribute('title'),
link.getAttribute('data-testid')
].filter(Boolean).join(' '));
const href = String(link.href || '').toLowerCase();
return (
/(?:^|s)(?:çalışma|calisma|work|codex)(?:s|$)/.test(t) ||
/(?:workspace-agent|agent-mode|work-mode|codex)/.test(href)
);
}
function styleSidebarThreads() {
const map = loadThreadModes();
for (const link of sidebarConversationLinks()) {
const key = canonicalThreadKey(link.href);
if (!key) continue;
// DOM içinde doğrudan bir Çalışma/Codex ipucu varsa ziyaret edilmeden de işaretle.
if (directWorkHintForSidebarLink(link)) {
map[key] = { mode: 'work', seenAt: Date.now() };
}
const isWork = map[key]?.mode === 'work';
link.classList.toggle('clt-sidebar-work-thread', isWork);
if (isWork) {
link.setAttribute('data-clt-work-thread', '1');
if (!link.getAttribute('title')?.includes('Ortak kota')) {
const oldTitle = link.getAttribute('title') || '';
link.setAttribute('title', `${oldTitle ? `${oldTitle} — ` : ''}🤖 Ortak kota kullanan konuşma`);
}
} else {
link.classList.remove('clt-sidebar-work-thread');
link.removeAttribute('data-clt-work-thread');
}
}
saveThreadModes(map);
}
function effectiveWorkStatus(state) {
const five = state.fiveHour?.remaining;
const week = state.weekly?.remaining;
const known = [five, week].filter((v) => v != null);
if (!known.length) return { level: 'unknown', label: 'Kota okunmadı', color: '#94a3b8' };
// Work kullanılabilirliği iki pencereden daha kısıtlı olana bağlıdır.
const effective = Math.min(...known);
if (effective <= 0) return { level: 'blocked', label: 'KOTA YOK', color: '#ef4444' };
if (effective <= 10) return { level: 'critical', label: 'KOTA ÇOK AZ', color: '#ef4444' };
if (effective <= 20) return { level: 'low', label: 'KOTA AZ', color: '#f59e0b' };
return { level: 'ok', label: 'Kota uygun', color: '#22c55e' };
}
function effortFromText(value) {
const t = normalizeUiText(value);
if (!t) return null;
// Önce daha özgül ifadeler. "Çok Yüksek", "Yüksek"ten önce kontrol edilmeli.
if (/(?:^|s)(?:çoks*yüksek|verys*high|xhigh|maximum)(?:s|$)/.test(t)) {
return { key: 'veryhigh', label: 'ÇOK YÜKSEK', emoji: '🟢' };
}
if (/(?:^|s)pro(?:s|$)/.test(t) || /gpt[- ]?5(?:[.,]d+)?s*pro/.test(t)) {
return { key: 'pro', label: 'PRO!', emoji: '🧠' };
}
if (/(?:^|s)(?:orta|medium)(?:s|$)/.test(t)) {
return { key: 'medium', label: 'ORTA', emoji: '⚪' };
}
if (/(?:^|s)(?:yüksek|high)(?:s|$)/.test(t)) {
return { key: 'high', label: 'YÜKSEK', emoji: '🟡' };
}
if (/(?:^|s)(?:hızlı|fast)(?:s|$)/.test(t)) {
return { key: 'fast', label: 'HIZLI', emoji: '🆓' };
}
return null;
}
function isActuallyVisible(el) {
if (!el || el.closest?.(`#${PANEL_ID}`)) return false;
const style = getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
const rect = el.getBoundingClientRect();
return rect.width > 2 && rect.height > 2 && rect.bottom >= 0 && rect.top <= innerHeight;
}
function elementUiText(el) {
return [
el?.innerText,
el?.textContent,
el?.getAttribute?.('aria-label'),
el?.getAttribute?.('title'),
el?.getAttribute?.('data-testid')
].filter(Boolean).join(' ');
}
function composerElement() {
const candidates = [...document.querySelectorAll(
'textarea,[contenteditable="true"],[data-placeholder]'
)].filter(isActuallyVisible);
return candidates.find((el) => {
const hint = normalizeUiText([
el.getAttribute?.('placeholder'),
el.getAttribute?.('data-placeholder'),
el.getAttribute?.('aria-label')
].filter(Boolean).join(' '));
return /chatgpt['’]?ye sor|ask chatgpt|message chatgpt|istediğin konu üstünde çalış|istedigin konu ustunde calis|work on anything|work on a task/.test(hint);
}) || candidates[0] || null;
}
function effortControlCandidates() {
const composer = composerElement();
const roots = [];
if (composer) {
let node = composer;
for (let i = 0; node && i < 7; i += 1, node = node.parentElement) roots.push(node);
const form = composer.closest('form');
if (form) roots.unshift(form);
}
const seen = new Set();
const out = [];
const add = (el, baseScore = 0) => {
if (!el || seen.has(el) || !isActuallyVisible(el)) return;
seen.add(el);
const effort = effortFromText(elementUiText(el));
if (!effort) return;
const rect = el.getBoundingClientRect();
let score = baseScore;
if (el.matches('[aria-haspopup="menu"],[aria-haspopup="listbox"],[role="combobox"]')) score += 80;
if (el.matches('button,[role="button"]')) score += 35;
if (/gpt|5[.,]d|sol|terra|reason|akıl|model/i.test(elementUiText(el))) score += 25;
if (effort.key !== 'fast') score += 18; // ayrı Fast düğmesi ile akıl yürütme seçicisi çakışırsa akıl düzeyini tercih et.
if (rect.top > innerHeight * .55) score += 20; // mesaj kutusuna yakın alt kontroller.
out.push({ el, effort, score });
};
roots.forEach((root, idx) => {
root.querySelectorAll?.(
'button,[role="button"],[role="combobox"],[aria-haspopup="menu"],[aria-haspopup="listbox"]'
).forEach((el) => add(el, 120 - idx * 8));
});
// Arayüz yapısı değişirse, yalnız görünür etkileşimli kontrolleri yedek olarak tara.
document.querySelectorAll(
'button,[role="button"],[role="combobox"],[aria-haspopup="menu"],[aria-haspopup="listbox"]'
).forEach((el) => add(el, 0));
return out.sort((a, b) => b.score - a.score);
}
function detectChatEffort() {
// Eski sürüm bütün sayfa yazısını tarıyordu; geçmiş mesajlardaki veya menüdeki
// "Çok Yüksek" sözü yanlış pozitif üretebiliyordu. Artık yalnız aktif UI kontrolünü okuyor.
const candidates = effortControlCandidates();
if (candidates.length) return { ...candidates[0].effort, source: 'active-control' };
// Açık bir seçenek menüsünde aktif/işaretli öğe varsa onu kullan.
const selected = [...document.querySelectorAll(
'[role="menuitem"][aria-checked="true"],[role="option"][aria-selected="true"],[data-state="checked"]'
)].filter(isActuallyVisible);
for (const el of selected) {
const effort = effortFromText(elementUiText(el));
if (effort) return { ...effort, source: 'selected-option' };
}
return { key: 'unknown', label: 'SOHBET', emoji: '💬', source: 'unknown' };
}
function clickableAncestor(el) {
if (!el) return null;
return el.closest?.(
'button,[role="button"],[role="menuitem"],[role="menuitemradio"],[role="option"],[data-radix-collection-item],[tabindex]'
) || el;
}
function dispatchClick(el) {
if (!el) return;
try { el.focus?.({ preventScroll: true }); } catch {}
try { el.click(); } catch {}
}
function findEffortControlForClick() {
const current = detectChatEffort();
const candidates = effortControlCandidates()
.filter((c) => current.key === 'unknown' || c.effort.key === current.key);
if (!candidates.length) return effortControlCandidates()[0]?.el || null;
return candidates
.sort((a, b) => {
const score = (item) => {
const el = item.el;
const txt = normalizeUiText(elementUiText(el));
let s = item.score || 0;
if (el.matches?.('[aria-haspopup="menu"],[aria-haspopup="listbox"],[role="combobox"]')) s += 150;
if (el.matches?.('button,[role="button"]')) s += 70;
if (txt.length <= 45) s += 40;
if (/gpt|5[.,]d|sol|terra|orta|medium|yüksek|high|pro/i.test(txt)) s += 30;
return s;
};
return score(b) - score(a);
})[0].el;
}
function findVeryHighOption() {
// Menü öğesinin kendisi span/div olabiliyor; bu yüzden önce görünür kısa metinleri
// bulup sonra en yakın tıklanabilir atasına çıkıyoruz.
const all = [...document.querySelectorAll('body *')]
.filter((el) => isActuallyVisible(el) && !el.closest?.(`#${PANEL_ID}`))
.map((el) => ({
el,
text: normalizeUiText(el.innerText || el.textContent || '')
}))
.filter(({ text }) =>
text &&
text.length <= 80 &&
/^(?:🟢s*)?(?:çoks*yüksek|verys*high|xhigh|maximum)(?:s+.*)?$/.test(text)
)
.map(({ el, text }) => ({ el: clickableAncestor(el), text }))
.filter(({ el }) => el && isActuallyVisible(el));
const unique = [];
const seen = new Set();
for (const item of all) {
if (seen.has(item.el)) continue;
seen.add(item.el);
unique.push(item);
}
unique.sort((a, b) => {
const score = (item) => {
const el = item.el;
let s = 0;
if (el.closest?.('[role="menu"],[role="listbox"],[data-state="open"]')) s += 200;
if (el.matches?.('[role="menuitem"],[role="menuitemradio"],[role="option"]')) s += 120;
if (el.matches?.('button,[role="button"]')) s += 60;
const r = el.getBoundingClientRect();
if (r.top > 100 && r.bottom < innerHeight - 20) s += 20;
return s;
};
return score(b) - score(a);
});
return unique[0]?.el || null;
}
function findReasoningSubmenuControl() {
const candidates = [...document.querySelectorAll(
'[role="menuitem"],[role="menuitemradio"],[role="option"],button,[role="button"]'
)]
.filter((el) => isActuallyVisible(el) && !el.closest?.(`#${PANEL_ID}`))
.map((el) => ({ el, text: normalizeUiText(elementUiText(el)) }))
.filter(({ text }) =>
text &&
text.length <= 90 &&
/akıl yürütme|akil yurutme|reasoning|düşünme düzeyi|dusunme duzeyi|effort/.test(text)
);
return candidates[0]?.el || null;
}
async function waitForVeryHighOption(rounds = 14, delay = 120) {
for (let i = 0; i < rounds; i += 1) {
const option = findVeryHighOption();
if (option) return option;
await new Promise((resolve) => setTimeout(resolve, delay));
}
return null;
}
async function switchToVeryHigh(button) {
if (!button) return;
button.disabled = true;
button.textContent = 'Seçiliyor…';
const current = detectChatEffort();
if (current.key === 'veryhigh') {
button.textContent = 'Zaten Çok Yüksek ✓';
setTimeout(() => {
if (button.isConnected) button.disabled = false;
}, 1000);
return;
}
const control = findEffortControlForClick();
if (!control) {
button.textContent = 'Seçici bulunamadı';
setTimeout(() => {
if (button.isConnected) {
button.disabled = false;
button.textContent = '🟢 Çok Yükseğe geç';
}
}, 1600);
return;
}
// 1. deneme: aktif Orta/Yüksek/Pro kontrolünü aç.
dispatchClick(control);
let option = await waitForVeryHighOption();
// Bazı arayüz sürümlerinde önce "Akıl yürütme" alt menüsüne giriliyor.
if (!option) {
const submenu = findReasoningSubmenuControl();
if (submenu) {
dispatchClick(submenu);
option = await waitForVeryHighOption(10, 120);
}
}
// İlk click React/Radix tarafından yutulduysa ikinci kez gerçek pointer/mouse olayları.
if (!option) {
try {
control.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true, cancelable: true, pointerType: 'mouse', button: 0
}));
control.dispatchEvent(new MouseEvent('mousedown', {
bubbles: true, cancelable: true, button: 0
}));
control.dispatchEvent(new PointerEvent('pointerup', {
bubbles: true, cancelable: true, pointerType: 'mouse', button: 0
}));
control.dispatchEvent(new MouseEvent('mouseup', {
bubbles: true, cancelable: true, button: 0
}));
control.dispatchEvent(new MouseEvent('click', {
bubbles: true, cancelable: true, button: 0
}));
} catch {
dispatchClick(control);
}
option = await waitForVeryHighOption(12, 120);
}
if (!option) {
button.textContent = 'Menü açılamadı — elle seçin';
setTimeout(() => {
if (button.isConnected) {
button.disabled = false;
button.textContent = '🟢 Çok Yükseğe geç';
}
}, 2200);
return;
}
dispatchClick(option);
// Seçimin gerçekten değiştiğini doğrula.
let success = false;
for (let i = 0; i < 12; i += 1) {
await new Promise((resolve) => setTimeout(resolve, 140));
if (detectChatEffort().key === 'veryhigh') {
success = true;
break;
}
}
button.textContent = success ? 'Çok Yüksek seçildi ✓' : 'Seçim doğrulanamadı';
setTimeout(() => update(), 500);
}
function chatModeBadge() {
const effort = detectChatEffort();
const cls = effort.key === 'pro'
? 'clt-chat-pro'
: effort.key === 'fast'
? 'clt-chat-fast'
: effort.key === 'veryhigh'
? 'clt-chat-veryhigh'
: effort.key === 'high'
? 'clt-chat-high'
: effort.key === 'medium'
? 'clt-chat-medium'
: 'clt-mode-chat';
const title = effort.key === 'pro'
? 'Pro aktif. Sonraki mesaj da Pro olarak gider; işiniz bittiyse Çok Yükseğe dönün.'
: effort.key === 'fast'
? 'Hızlı sohbet modu.'
: effort.key === 'veryhigh'
? 'Çok Yüksek: standart ciddi sohbet kullanımınız.'
: effort.key === 'high'
? 'Yüksek seçili. İsterseniz panelden Çok Yükseğe geçebilirsiniz.'
: effort.key === 'medium'
? 'Orta seçili. İsterseniz panelden Çok Yükseğe geçebilirsiniz.'
: 'Sohbet modu aktif; seçili akıl yürütme düzeyi kesin okunamadı.';
return `<span class="clt-mode-badge ${cls}" title="${escapeHtml(title)}"><b>${effort.emoji} ${effort.label}</b></span>`;
}
function modeBadge(state) {
const detected = detectCurrentMode();
const workStatus = effectiveWorkStatus(state);
if (detected.mode === 'work') {
const text = workStatus.level === 'blocked' ? '🤖 ORTAK KOTA • YOK' : '🤖 ORTAK KOTA';
return `<span class="clt-mode-badge clt-mode-work" title="Çalışma, Codex ve otonom ajanlar aynı ortak kotayı tüketir."><i></i><b>${text}</b></span>`;
}
if (detected.mode === 'chat') {
return chatModeBadge();
}
return `<span class="clt-mode-badge clt-mode-unknown" title="Normal Sohbet / ortak kota modu arayüzden kesin belirlenemedi."><i></i><b>MOD ?</b></span>`;
}
function modeSummary(state) {
const detected = detectCurrentMode();
const workStatus = effectiveWorkStatus(state);
if (detected.mode === 'work') {
if (workStatus.level === 'blocked') {
return `<div class="clt-mode-card clt-mode-card-danger"><b>🤖 Ortak kota tükenmiş</b><div>Çalışma, Codex ve otonom ajanlar aynı ortak havuzu kullanır. Bu sayfa ajan/Çalışma olarak algılandı; normal Sohbet etkilenmez.</div></div>`;
}
if (workStatus.level === 'critical' || workStatus.level === 'low') {
return `<div class="clt-mode-card clt-mode-card-warn"><b>🤖 Ortak kota — ${workStatus.label.toLocaleLowerCase('tr-TR')}</b><div>Bu sayfa Çalışma/Codex/otonom ajan ortak kotasını tüketir.</div></div>`;
}
return `<div class="clt-mode-card clt-mode-card-work"><b>🤖 Ortak kota kullanılıyor</b><div>Bu sayfa Çalışma/Codex/otonom ajan ortak kotasını tüketir.</div></div>`;
}
if (detected.mode === 'chat') {
const effort = detectChatEffort();
if (effort.key === 'pro') {
return `<div class="clt-mode-card clt-mode-card-danger"><b>🧠 PRO aktif</b><div>Sonraki mesaj da Pro olarak gider. İşiniz bittiyse aşağıdaki tuşla Çok Yükseğe dönün.</div></div>`;
}
if (effort.key === 'fast') {
return `<div class="clt-mode-card clt-mode-card-chat"><b>🆓 Hızlı sohbet</b><div>Basit ve hızlı işler için uygun. Ortak kota bu ekranda gizlenmiştir.</div></div>`;
}
if (effort.key === 'veryhigh') {
return `<div class="clt-mode-card clt-mode-card-chat"><b>🟢 Çok Yüksek</b><div>Standart ciddi sohbet kullanımınız. Seçim aktif kontrol üzerinden anlık okunuyor.</div></div>`;
}
if (effort.key === 'high') {
return `<div class="clt-mode-card clt-mode-card-warn"><b>🟡 Yüksek seçili</b><div>Standart tercihiniz Çok Yüksek ise aşağıdaki tuşla tek tıkla geçebilirsiniz.</div></div>`;
}
if (effort.key === 'medium') {
return `<div class="clt-mode-card"><b>⚪ Orta seçili</b><div>Standart tercihiniz Çok Yüksek ise aşağıdaki tuşla tek tıkla geçebilirsiniz.</div></div>`;
}
return `<div class="clt-mode-card"><b>💬 Sohbet — düzey okunamadı</b><div>Yanlış bilgi göstermemek için tahmin edilmiyor. Aşağıdaki tuş Çok Yüksek seçimini deneyebilir.</div></div>`;
}
return `<div class="clt-mode-card"><b>Mod kesin belirlenemedi</b><div>Okunan kota Çalışma/Codex/otonom ajan ortak kotasıdır; normal Sohbet bundan bağımsızdır.</div></div>`;
}
function maybeNotifyWorkMode(state) {
const detected = detectCurrentMode();
const status = effectiveWorkStatus(state);
const modeChangedToWork = detected.mode === 'work' && lastMode !== 'work';
lastMode = detected.mode;
if (!modeChangedToWork) return;
let key = '';
let text = '';
if (status.level === 'blocked') {
key = 'work-blocked';
text = '🤖 Ortak kota kullanılıyor; haftalık/5 saatlik Codex kotasının kullanılabilir kısmı kalmamış. Normal Sohbet etkilenmez.';
} else if (status.level === 'critical' || status.level === 'low') {
key = 'work-low';
text = '🤖 Ortak kota kullanılıyor ve Codex ortak kotası düşük.';
}
if (!key || typeof GM_notification !== 'function') return;
// Aynı durum için 30 dakikada birden sık sistem bildirimi verme.
let sent = {};
try { sent = JSON.parse(localStorage.getItem(MODE_ALERT_KEY) || '{}'); } catch { sent = {}; }
const now = Date.now();
if (now - Number(sent[key] || 0) < 30 * 60 * 1000) return;
GM_notification({ title: 'ChatGPT ortak kota uyarısı', text, timeout: 9000 });
sent[key] = now;
localStorage.setItem(MODE_ALERT_KEY, JSON.stringify(sent));
}
function percentText(value) {
if (value == null) return 'Henüz okunmadı';
return `%${String(value).replace('.', ',')} kaldı`;
}
function resetAtMillis(windowData) {
const direct = windowData?.reset_at ?? windowData?.resetAt;
if (direct != null) {
if (typeof direct === 'number') return direct < 1e12 ? direct * 1000 : direct;
const parsed = Date.parse(direct);
if (!Number.isNaN(parsed)) return parsed;
}
const after = Number(windowData?.reset_after_seconds ?? windowData?.resetAfterSeconds);
return Number.isFinite(after) ? Date.now() + after * 1000 : null;
}
function normalizeUsageWindow(windowData) {
if (!windowData) return null;
const used = Number(windowData.used_percent ?? windowData.usedPercent);
if (!Number.isFinite(used)) return null;
return {
remaining: Math.max(0, Math.min(100, Math.round((100 - used) * 10) / 10)),
reset: '',
resetAt: resetAtMillis(windowData),
windowSeconds: Number(windowData.limit_window_seconds ?? windowData.limitWindowSeconds) || 0,
};
}
async function fetchUsageData() {
try {
const response = await fetch('/backend-api/wham/usage', {
method: 'GET',
credentials: 'include',
headers: { Accept: 'application/json' },
cache: 'no-store',
});
if (!response.ok) return false;
const data = await response.json();
const rateLimit = data.rate_limit ?? data.rateLimit ?? data.rate_limits ?? data.rateLimits;
const windows = [
rateLimit?.primary_window ?? rateLimit?.primaryWindow,
rateLimit?.secondary_window ?? rateLimit?.secondaryWindow,
].map(normalizeUsageWindow).filter(Boolean).sort((a, b) => a.windowSeconds - b.windowSeconds);
if (!windows.length) return false;
const state = loadState();
if (windows[0]) state.fiveHour = { ...state.fiveHour, ...windows[0] };
if (windows[1]) state.weekly = { ...state.weekly, ...windows[1] };
state.updatedAt = new Date().toISOString();
saveState(state);
maybeNotify(state);
return true;
} catch {
return false;
}
}
function formatLimitCountdown(milliseconds) {
const totalMinutes = Math.max(0, Math.ceil(milliseconds / 60000));
const days = Math.floor(totalMinutes / 1440);
const hours = Math.floor((totalMinutes % 1440) / 60);
const minutes = totalMinutes % 60;
if (days > 0) return `${days} gün ${hours} sa`;
if (hours > 0) return `${hours} sa ${minutes} dk`;
return `${minutes} dk`;
}
function limitDetail(label, item) {
const value = item?.remaining;
const width = value == null ? 0 : value;
const reset = validReset(item?.reset);
const hasResetAt = item?.resetAt != null;
const resetAt = hasResetAt ? Number(item.resetAt) : NaN;
const remainingTime = Number.isFinite(resetAt) ? Math.max(0, resetAt - Date.now()) : null;
const resetInfo = remainingTime != null
? `<div class="clt-reset-line">Sıfırlanmaya kalan: <strong class="clt-limit-countdown" data-reset-at="${resetAt}">${formatLimitCountdown(remainingTime)}</strong></div>`
: reset ? `<div class="clt-reset-line">Sıfırlanma: ${escapeHtml(reset)}</div>` : '';
return `
<div class="clt-limit">
<div class="clt-limit-head"><span>${label}</span><strong>${percentText(value)}</strong></div>
<div class="clt-meter"><div class="clt-meter-fill" style="width:${width}%;background:${colorFor(value)}"></div></div>
${resetInfo}
</div>`;
}
function formatCountdown(milliseconds) {
const seconds = Math.max(0, Math.ceil(milliseconds / 1000));
const minutes = Math.floor(seconds / 60);
return `${minutes}:${String(seconds % 60).padStart(2, '0')}`;
}
function updateRefreshProgress() {
const panel = document.getElementById(PANEL_ID);
if (!panel) return;
const remaining = Math.max(0, nextBackgroundRefreshAt - Date.now());
const ratio = Math.max(0, Math.min(100, (remaining / BACKGROUND_REFRESH_MS) * 100));
const bar = panel.querySelector('.clt-refresh-fill');
const time = panel.querySelector('.clt-refresh-time');
if (bar) bar.style.width = `${ratio}%`;
if (time) time.textContent = formatCountdown(remaining);
panel.querySelectorAll('.clt-limit-countdown[data-reset-at]').forEach((element) => {
const resetAt = Number(element.dataset.resetAt);
if (Number.isFinite(resetAt)) element.textContent = formatLimitCountdown(resetAt - Date.now());
});
}
function badge(label, item) {
const value = item?.remaining;
const shown = value == null ? '–' : value === 100 ? '✓' : String(value).replace('.', ',');
const reset = validReset(item?.reset);
const title = reset ? `${label}: ${shown} — ${reset}` : `${label}: ${shown}`;
return `<span class="clt-badge" title="${escapeHtml(title)}"><i style="background:${colorFor(value)}"></i><b>${label}</b>${shown}</span>`;
}
function escapeHtml(value) {
return String(value || '').replace(/[&<>"']/g, (ch) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[ch]));
}
function formatUpdated(iso) {
if (!iso) return 'Kullanım ekranı henüz okunmadı';
return `Son okuma: ${new Intl.DateTimeFormat('tr-TR', {
day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'
}).format(new Date(iso))}`;
}
function applySavedPosition(panel) {
try {
const saved = JSON.parse(localStorage.getItem(POSITION_KEY) || 'null');
if (!saved || !Number.isFinite(saved.left) || !Number.isFinite(saved.top)) return;
panel.style.left = `${Math.max(4, Math.min(window.innerWidth - 90, saved.left))}px`;
panel.style.top = `${Math.max(4, Math.min(window.innerHeight - 30, saved.top))}px`;
panel.style.bottom = 'auto';
} catch { /* Varsayılan konumu kullan. */ }
}
function makeDraggable(panel) {
const handle = panel.querySelector('.clt-mini');
let drag = null;
handle.addEventListener('pointerdown', (event) => {
if (event.button !== 0) return;
const rect = panel.getBoundingClientRect();
drag = { x: event.clientX, y: event.clientY, left: rect.left, top: rect.top, moved: false };
handle.setPointerCapture(event.pointerId);
});
handle.addEventListener('pointermove', (event) => {
if (!drag) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
if (Math.abs(dx) + Math.abs(dy) < 4) return;
drag.moved = true;
const left = Math.max(4, Math.min(window.innerWidth - panel.offsetWidth - 4, drag.left + dx));
const top = Math.max(4, Math.min(window.innerHeight - panel.offsetHeight - 4, drag.top + dy));
panel.style.left = `${left}px`;
panel.style.top = `${top}px`;
panel.style.bottom = 'auto';
});
handle.addEventListener('pointerup', (event) => {
if (!drag) return;
handle.releasePointerCapture(event.pointerId);
if (drag.moved) {
const rect = panel.getBoundingClientRect();
localStorage.setItem(POSITION_KEY, JSON.stringify({ left: rect.left, top: rect.top }));
panel.dataset.justDragged = '1';
setTimeout(() => { delete panel.dataset.justDragged; }, 100);
}
drag = null;
});
}
async function manualRefresh(button) {
button.disabled = true;
button.textContent = 'Güncelleniyor…';
nextBackgroundRefreshAt = Date.now() + BACKGROUND_REFRESH_MS;
const fetched = await fetchUsageData();
if (usageFrame) usageFrame.src = usageUrl();
render(loadState());
const currentButton = document.querySelector(`#${PANEL_ID} .clt-refresh-button`);
if (currentButton) {
currentButton.textContent = fetched ? 'Güncellendi ✓' : 'Sayfa okunuyor…';
setTimeout(() => {
const latestButton = document.querySelector(`#${PANEL_ID} .clt-refresh-button`);
if (latestButton) {
latestButton.disabled = false;
latestButton.textContent = 'Şimdi güncelle';
}
}, 1300);
}
}
function render(state) {
let panel = document.getElementById(PANEL_ID);
if (!panel) {
panel = document.createElement('aside');
panel.id = PANEL_ID;
panel.innerHTML = `
<style>
#${PANEL_ID}{position:fixed;left:12px;bottom:12px;z-index:2147483646;color:#263244;font:11px/1.25 system-ui,-apple-system,Segoe UI,sans-serif}
#${PANEL_ID} .clt-mini{display:flex;gap:4px;padding:3px;background:rgba(255,255,255,.96);border:1px solid #d8dee8;border-radius:9px;box-shadow:0 4px 14px rgba(15,23,42,.16);backdrop-filter:blur(10px);cursor:grab;user-select:none;touch-action:none}
#${PANEL_ID} .clt-mini:active{cursor:grabbing}
#${PANEL_ID} .clt-badge{display:flex;align-items:center;gap:3px;min-width:37px;height:18px;padding:0 5px 0 4px;border-radius:6px;background:#eef2f7;color:#263244;font-variant-numeric:tabular-nums}
#${PANEL_ID} .clt-badge i{width:6px;height:6px;border-radius:50%;box-shadow:0 0 7px currentColor}
#${PANEL_ID} .clt-badge b{font-size:9px;color:#64748b;font-weight:700}
#${PANEL_ID} .clt-mode-badge{display:flex;align-items:center;gap:4px;height:18px;padding:0 6px;border-radius:6px;font-size:8px;font-weight:800;letter-spacing:.2px;white-space:nowrap}
#${PANEL_ID} .clt-mode-badge i{width:6px;height:6px;border-radius:50%}
#${PANEL_ID} .clt-mode-chat{background:#ecfdf5;color:#047857;border:1px solid #a7f3d0}
#${PANEL_ID} .clt-chat-veryhigh{background:#ecfdf5;color:#047857;border:1px solid #86efac}
#${PANEL_ID} .clt-chat-fast{background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe}
#${PANEL_ID} .clt-chat-medium{background:#f8fafc;color:#475569;border:1px solid #cbd5e1}
#${PANEL_ID} .clt-chat-high{background:#fffbeb;color:#a16207;border:1px solid #fde68a}
#${PANEL_ID} .clt-chat-pro{background:#fff1f2;color:#be123c;border:1px solid #fda4af;box-shadow:0 0 0 2px rgba(225,29,72,.08)}
#${PANEL_ID} .clt-mode-chat i{background:#10b981;box-shadow:0 0 7px #10b981}
#${PANEL_ID} .clt-mode-work{background:#fff7ed;color:#c2410c;border:1px solid #fed7aa}
#${PANEL_ID} .clt-mode-work i{background:#f97316;box-shadow:0 0 7px #f97316}
#${PANEL_ID} .clt-mode-unknown{background:#f8fafc;color:#64748b;border:1px solid #e2e8f0}
#${PANEL_ID} .clt-mode-unknown i{background:#94a3b8}
#${PANEL_ID}.clt-work-active .clt-mini{border-color:#fb923c;box-shadow:0 4px 16px rgba(249,115,22,.28)}
#${PANEL_ID}.clt-work-blocked .clt-mini{border-color:#ef4444;box-shadow:0 4px 18px rgba(239,68,68,.34)}
#${PANEL_ID} .clt-detail{display:none;position:absolute;left:0;bottom:31px;width:260px;padding:11px;color:#263244;background:rgba(255,255,255,.98);border:1px solid #d8dee8;border-radius:11px;box-shadow:0 10px 30px rgba(15,23,42,.2)}
#${PANEL_ID}.clt-open .clt-detail{display:block}
#${PANEL_ID} .clt-limit+.clt-limit{margin-top:11px}
#${PANEL_ID} .clt-limit-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:5px}
#${PANEL_ID} .clt-limit-head span{font-weight:650}
#${PANEL_ID} .clt-limit-head strong{font-size:11px;color:#172033;white-space:nowrap}
#${PANEL_ID} .clt-meter,#${PANEL_ID} .clt-refresh-track{height:6px;background:#e5eaf1;border-radius:99px;overflow:hidden}
#${PANEL_ID} .clt-meter-fill,#${PANEL_ID} .clt-refresh-fill{height:100%;border-radius:99px;transition:width .7s linear}
#${PANEL_ID} .clt-reset-line{margin-top:4px;color:#64748b;font-size:10px}
#${PANEL_ID} .clt-reset-card{margin-top:11px;padding:8px 9px;background:#f1f5f9;border:1px solid #e2e8f0;border-radius:8px;color:#475569;font-size:10px;line-height:1.35}
#${PANEL_ID} .clt-reset-card b{display:block;margin-bottom:3px;color:#172033;font-size:11px}
#${PANEL_ID} .clt-reset-card div+div{margin-top:3px}
#${PANEL_ID} .clt-mode-card{margin:0 0 11px;padding:8px 9px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;color:#475569;font-size:10px;line-height:1.35}
#${PANEL_ID} .clt-mode-card b{display:block;margin-bottom:3px;color:#172033;font-size:11px}
#${PANEL_ID} .clt-mode-card-chat{background:#ecfdf5;border-color:#a7f3d0}
#${PANEL_ID} .clt-mode-card-work{background:#fff7ed;border-color:#fed7aa}
#${PANEL_ID} .clt-mode-card-warn{background:#fffbeb;border-color:#fde68a}
#${PANEL_ID} .clt-mode-card-danger{background:#fef2f2;border-color:#fecaca}
#${PANEL_ID} .clt-mode-card-danger b{color:#b91c1c}
#${PANEL_ID} .clt-refresh-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:10px 0 5px;color:#64748b;font-size:9px}
#${PANEL_ID} .clt-refresh-fill{width:100%;background:#94a3b8}
#${PANEL_ID} .clt-refresh-button{border:1px solid #cbd5e1;border-radius:6px;background:#fff;color:#334155;padding:3px 7px;font:600 9px/1.2 system-ui,-apple-system,Segoe UI,sans-serif;cursor:pointer}
#${PANEL_ID} .clt-refresh-button:hover{background:#f1f5f9;border-color:#94a3b8}
#${PANEL_ID} .clt-refresh-button:disabled{cursor:wait;opacity:.65}
a.clt-sidebar-work-thread{background:rgba(249,115,22,.10)!important;box-shadow:inset 3px 0 0 #f97316!important;border-radius:8px!important}
a.clt-sidebar-work-thread::after{content:"🤖";margin-left:auto;padding-left:6px;font-size:10px;opacity:.88}
#${PANEL_ID} .clt-effort-action{margin:0 0 10px}
#${PANEL_ID} .clt-effort-button{width:100%;border:1px solid #86efac;border-radius:8px;background:#ecfdf5;color:#047857;padding:7px 9px;font:750 10px/1.2 system-ui,-apple-system,Segoe UI,sans-serif;cursor:pointer}
#${PANEL_ID} .clt-effort-button:hover{background:#dcfce7;border-color:#4ade80}
#${PANEL_ID} .clt-effort-button:disabled{cursor:wait;opacity:.7}
</style>
<div class="clt-detail"></div>
<div class="clt-mini"></div>`;
document.documentElement.appendChild(panel);
applySavedPosition(panel);
makeDraggable(panel);
panel.querySelector('.clt-mini').addEventListener('click', () => {
if (panel.dataset.justDragged) return;
panel.classList.toggle('clt-open');
});
}
const detectedMode = detectCurrentMode();
const workStatus = effectiveWorkStatus(state);
panel.classList.toggle('clt-work-active', detectedMode.mode === 'work');
panel.classList.toggle('clt-work-blocked', detectedMode.mode === 'work' && workStatus.level === 'blocked');
panel.querySelector('.clt-mini').innerHTML = detectedMode.mode === 'work'
? `${modeBadge(state)}${badge('5s', state.fiveHour)}${badge('7g', state.weekly)}`
: `${modeBadge(state)}`;
const rightExpiry = String(state.resetRight?.expires || '').replace(/^(?:Bitiş zamanı|Expires?(?: at)?)s*/i, '').trim();
const right = state.resetRight?.available ? `
<div class="clt-reset-card">
<b>Tam sıfırlama hakkı mevcut</b>
<div>Kullanıldığında 5 saatlik ve haftalık limit birlikte yenilenir.</div>
${rightExpiry ? `<div>Bu hak <strong>${escapeHtml(rightExpiry)}</strong> tarihine kadar kullanılabilir.</div>` : ''}
</div>` : '';
const codexDetails = detectedMode.mode === 'work' ? `
${limitDetail('5 saatlik ortak kota', state.fiveHour)}
${limitDetail('Haftalık ortak kota', state.weekly)}
${right}
` : '';
const currentEffort = detectedMode.mode === 'chat' ? detectChatEffort() : null;
const effortAction = detectedMode.mode === 'chat' && currentEffort?.key !== 'veryhigh'
? `<div class="clt-effort-action"><button class="clt-effort-button" type="button">🟢 Çok Yükseğe geç</button></div>`
: '';
panel.querySelector('.clt-detail').innerHTML = `
${modeSummary(state)}
${effortAction}
${codexDetails}
<div class="clt-refresh-head"><span>Otomatik kontrol: <span class="clt-refresh-time">5:00</span></span><button class="clt-refresh-button" type="button">Şimdi güncelle</button></div>
<div class="clt-refresh-track"><div class="clt-refresh-fill"></div></div>`;
const effortButton = panel.querySelector('.clt-effort-button');
if (effortButton) {
effortButton.addEventListener('click', (event) => {
event.stopPropagation();
switchToVeryHigh(event.currentTarget);
});
}
panel.querySelector('.clt-refresh-button').addEventListener('click', (event) => {
event.stopPropagation();
manualRefresh(event.currentTarget);
});
updateRefreshProgress();
maybeNotifyWorkMode(state);
}
function maybeNotify(state) {
let sent = {};
try { sent = JSON.parse(localStorage.getItem(ALERT_KEY) || '{}'); } catch { sent = {}; }
const weekKey = state.updatedAt?.slice(0, 10) || 'unknown';
const alerts = [
{ id: `weekly-${weekKey}`, value: state.weekly?.remaining, threshold: 20, text: `Haftalık ortak kota %${state.weekly?.remaining} kaldı.` },
{ id: `five-${weekKey}`, value: state.fiveHour?.remaining, threshold: 15, text: `5 saatlik ortak kota %${state.fiveHour?.remaining} kaldı.` },
];
for (const alert of alerts) {
if (alert.value != null && alert.value <= alert.threshold && !sent[alert.id]) {
if (typeof GM_notification === 'function') {
GM_notification({ title: 'ChatGPT limit uyarısı', text: alert.text, timeout: 7000 });
}
sent[alert.id] = true;
}
}
localStorage.setItem(ALERT_KEY, JSON.stringify(sent));
}
let lastChatEffortKey = null;
function maybeWarnProSelection() {
const detected = detectCurrentMode();
if (detected.mode !== 'chat') {
lastChatEffortKey = null;
return;
}
const effort = detectChatEffort();
if (effort.key === 'pro' && lastChatEffortKey !== 'pro') {
if (typeof GM_notification === 'function') {
GM_notification({
title: 'Pro aktif',
text: 'Sonraki mesaj Pro olarak gider. Tek soruluk kullanım bittiyse Çok Yüksek veya Hızlıya dönün.',
timeout: 7000
});
}
}
lastChatEffortKey = effort.key;
}
function update() {
const state = parsePage();
const detectedMode = detectCurrentMode();
rememberCurrentThreadMode(detectedMode);
render(state);
styleSidebarThreads();
maybeWarnProSelection();
}
function usageUrl() {
const url = new URL(USAGE_URL);
url.searchParams.set('limit_takip_refresh', String(Date.now()));
return url.href;
}
function setupSidebarWatcher() {
let pending = null;
const observer = new MutationObserver(() => {
if (pending) clearTimeout(pending);
pending = setTimeout(() => {
styleSidebarThreads();
}, 180);
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
setTimeout(styleSidebarThreads, 1200);
}
function setupBackgroundUsagePage() {
let frame = document.getElementById(FRAME_ID);
if (!frame) {
frame = document.createElement('iframe');
frame.id = FRAME_ID;
frame.title = 'ChatGPT kullanım bilgisi';
frame.tabIndex = -1;
frame.setAttribute('aria-hidden', 'true');
frame.style.cssText = 'position:fixed;left:-10000px;bottom:0;width:900px;height:700px;opacity:0;pointer-events:none;border:0;z-index:-1';
nextBackgroundRefreshAt = Date.now() + BACKGROUND_REFRESH_MS;
frame.src = usageUrl();
document.documentElement.appendChild(frame);
}
usageFrame = frame;
fetchUsageData();
setInterval(() => {
nextBackgroundRefreshAt = Date.now() + BACKGROUND_REFRESH_MS;
fetchUsageData();
frame.src = usageUrl();
}, BACKGROUND_REFRESH_MS);
}
if (IS_EMBEDDED) {
setTimeout(parsePage, 1500);
setInterval(parsePage, SCAN_INTERVAL_MS);
return;
}
update();
setupBackgroundUsagePage();
setupSidebarWatcher();
setInterval(update, SCAN_INTERVAL_MS);
setInterval(updateRefreshProgress, 1000);
})();