Apply
Ignore
${
- s.type === "spelling"
+ s.type === "spelling" && s.original.trim()
? `
Add to dictionary `
: ""
}
@@ -911,8 +814,7 @@ export default defineContentScript({
if (!suggestion) return;
if (action === "apply") {
- applySuggestion(suggestion);
- updatePanelAfterChange();
+ if (applySuggestion(suggestion)) updatePanelAfterChange();
} else if (action === "ignore") {
ignoreSuggestion(suggestion);
updatePanelAfterChange();
@@ -969,7 +871,7 @@ export default defineContentScript({
function updatePanelAfterChange() {
if (currentSuggestions.length === 0) {
hideSuggestionPanel();
- showStatusButton("clean");
+ showStatusButton(reviewIncomplete ? "incomplete" : "clean");
} else {
// Re-render panel
hideSuggestionPanel();
@@ -989,59 +891,51 @@ export default defineContentScript({
}
}
- // Get character position rectangles
- function getCharacterRects(
- element: HTMLElement,
- startIndex: number,
- endIndex: number
- ): DOMRect[] {
- const tagName = element.tagName.toLowerCase();
-
- if (tagName === "textarea" || tagName === "input") {
- return getTextareaCharacterRects(
- element as HTMLTextAreaElement | HTMLInputElement,
- startIndex,
- endIndex
- );
- }
-
- // For contenteditable
- const range = document.createRange();
- let currentIndex = 0;
- let startNode: Text | null = null;
- let startOffset = 0;
- let endNode: Text | null = null;
- let endOffset = 0;
-
+ function mapEditorRanges(element: HTMLElement, text: string) {
+ const positions: Array<{ node: Text; offset: number } | undefined> = [];
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
+ const visibleRange = document.createRange();
+ let textIndex = 0;
let node: Text | null;
- while ((node = walker.nextNode() as Text)) {
- const nodeLength = node.length;
+ while ((node = walker.nextNode() as Text | null)) {
+ if (!node.parentElement || getComputedStyle(node.parentElement).visibility !== "visible") continue;
+ visibleRange.selectNodeContents(node);
+ if (!visibleRange.getClientRects().length) continue;
- if (!startNode && currentIndex + nodeLength > startIndex) {
- startNode = node;
- startOffset = startIndex - currentIndex;
+ for (let offset = 0; offset < node.length; offset++) {
+ const character = node.data[offset];
+ if (/\s/.test(character)) {
+ if (text[textIndex] !== character) continue;
+ } else {
+ // innerText includes line breaks between rendered blocks and around
.
+ while (/\s/.test(text[textIndex] ?? "")) textIndex++;
+ if (text[textIndex] !== character) return null;
+ }
+ positions[textIndex++] = { node, offset };
}
+ }
- if (!endNode && currentIndex + nodeLength >= endIndex) {
- endNode = node;
- endOffset = endIndex - currentIndex;
- break;
- }
+ if (text.slice(textIndex).trim()) return null;
- currentIndex += nodeLength;
- }
+ return (startIndex: number, endIndex: number) => {
+ const first = positions[startIndex];
+ const last = positions[endIndex - 1];
+ const range = document.createRange();
- if (!startNode || !endNode) return [];
+ if (startIndex === endIndex) {
+ if (first) range.setStart(first.node, first.offset);
+ else if (last) range.setStart(last.node, last.offset + 1);
+ else return null;
+ range.collapse(true);
+ } else {
+ if (!first || !last) return null;
+ range.setStart(first.node, first.offset);
+ range.setEnd(last.node, last.offset + 1);
+ }
- try {
- range.setStart(startNode, startOffset);
- range.setEnd(endNode, endOffset);
- return Array.from(range.getClientRects());
- } catch {
- return [];
- }
+ return range;
+ };
}
function getTextareaCharacterRects(
@@ -1058,18 +952,24 @@ export default defineContentScript({
position: absolute;
top: -9999px;
left: -9999px;
- white-space: pre-wrap;
- word-wrap: break-word;
+ white-space: ${element instanceof HTMLInputElement || element.wrap === "off" ? "pre" : "pre-wrap"};
+ overflow-wrap: break-word;
+ box-sizing: border-box;
overflow: hidden;
visibility: hidden;
font-family: ${computedStyle.fontFamily};
font-size: ${computedStyle.fontSize};
font-weight: ${computedStyle.fontWeight};
+ font-style: ${computedStyle.fontStyle};
+ text-align: ${computedStyle.textAlign};
+ direction: ${computedStyle.direction};
+ text-transform: ${computedStyle.textTransform};
+ word-spacing: ${computedStyle.wordSpacing};
+ tab-size: ${computedStyle.tabSize};
line-height: ${computedStyle.lineHeight};
letter-spacing: ${computedStyle.letterSpacing};
padding: ${computedStyle.padding};
- border: ${computedStyle.border};
- width: ${element.offsetWidth}px;
+ width: ${element.clientWidth}px;
`;
const before = document.createElement("span");
@@ -1086,24 +986,15 @@ export default defineContentScript({
mirror.appendChild(after);
document.body.appendChild(mirror);
- const markedRect = marked.getBoundingClientRect();
const mirrorRect = mirror.getBoundingClientRect();
-
- const relativeTop = markedRect.top - mirrorRect.top;
- const relativeLeft = markedRect.left - mirrorRect.left;
-
- const scrollTop = element.scrollTop || 0;
- const scrollLeft = element.scrollLeft || 0;
-
- const finalRect = new DOMRect(
- rect.left + relativeLeft - scrollLeft,
- rect.top + relativeTop - scrollTop,
- markedRect.width,
- markedRect.height
- );
-
- document.body.removeChild(mirror);
- return [finalRect];
+ const rects = Array.from(marked.getClientRects(), (part) => new DOMRect(
+ rect.left + element.clientLeft + part.left - mirrorRect.left - element.scrollLeft,
+ rect.top + element.clientTop + part.top - mirrorRect.top - element.scrollTop,
+ part.width,
+ part.height
+ ));
+ mirror.remove();
+ return rects;
}
// Inline popover (shown on underline click)
@@ -1144,10 +1035,10 @@ export default defineContentScript({
currentPopover.innerHTML = `
${escapeHtml(suggestion.explanation)}
@@ -1155,7 +1046,7 @@ export default defineContentScript({
Apply
Ignore
${
- suggestion.type === "spelling"
+ suggestion.type === "spelling" && suggestion.original.trim()
? '
+Dict '
: ""
}
@@ -1163,6 +1054,7 @@ export default defineContentScript({
`;
currentPopover.addEventListener("mousedown", (e) => {
+ e.preventDefault();
e.stopPropagation();
});
@@ -1174,9 +1066,10 @@ export default defineContentScript({
const action = target.dataset.action;
if (action === "apply") {
- applySuggestion(suggestion);
- hidePopover();
- updateStatusAfterChange();
+ if (applySuggestion(suggestion)) {
+ hidePopover();
+ updateStatusAfterChange();
+ }
} else if (action === "ignore") {
ignoreSuggestion(suggestion);
hidePopover();
@@ -1240,7 +1133,7 @@ export default defineContentScript({
function updateStatusAfterChange() {
if (currentSuggestions.length === 0) {
- showStatusButton("clean");
+ showStatusButton(reviewIncomplete ? "incomplete" : "clean");
} else {
showStatusButton("errors", currentSuggestions.length);
}
@@ -1253,34 +1146,77 @@ export default defineContentScript({
return div.innerHTML;
}
- function applySuggestion(suggestion: GrammarSuggestion) {
- if (!activeElement) return;
+ function applySuggestion(suggestion: GrammarSuggestion): boolean {
+ const element = activeElement;
+ if (!element) return false;
- const text = getTextFromElement(activeElement);
- const newText =
- text.substring(0, suggestion.startIndex) +
- suggestion.replacement +
- text.substring(suggestion.endIndex);
- setTextInElement(activeElement, newText);
-
- const lengthDiff =
- suggestion.replacement.length - suggestion.original.length;
- currentSuggestions = currentSuggestions
- .filter((s) => s.id !== suggestion.id)
- .map((s) => {
- if (s.startIndex > suggestion.endIndex) {
- return {
- ...s,
- startIndex: s.startIndex + lengthDiff,
- endIndex: s.endIndex + lengthDiff,
- };
- }
- return s;
- });
+ const { startIndex, endIndex, original, replacement } = suggestion;
+ const text = getTextFromElement(element);
+ if (text !== checkedText || text.slice(startIndex, endIndex) !== original) {
+ cleanup();
+ queueFieldCheck(element, true);
+ return false;
+ }
+
+ const newText = text.slice(0, startIndex) + replacement + text.slice(endIndex);
+ isApplyingSuggestion = true;
+ try {
+ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
+ setTextInElement(element, newText);
+ } else {
+ const range = mapEditorRanges(element, text)?.(startIndex, endIndex);
+ const selection = window.getSelection();
+ if (!element.isContentEditable || !range || !selection) return false;
+
+ const textNode = range.startContainer as Text;
+ const offset = range.startOffset;
+ const inputType = replacement ? "insertReplacementText" : "deleteContent";
+ const event = { inputType, data: replacement, bubbles: true, composed: true };
+ const targetRange = new StaticRange({
+ startContainer: range.startContainer,
+ startOffset: range.startOffset,
+ endContainer: range.endContainer,
+ endOffset: range.endOffset,
+ });
- browser.runtime
- .sendMessage({ type: "CORRECTION_APPLIED" })
- .catch(() => {});
+ element.focus();
+ if (!element.dispatchEvent(new InputEvent("beforeinput", {
+ ...event,
+ cancelable: true,
+ targetRanges: [targetRange],
+ }))) return false;
+ if (!element.contains(textNode) || getTextFromElement(element) !== text) return false;
+
+ if (range.startContainer === range.endContainer) {
+ textNode.replaceData(offset, range.endOffset - offset, replacement);
+ } else {
+ range.deleteContents();
+ textNode.insertData(offset, replacement);
+ }
+ selection.collapse(textNode, offset + replacement.length);
+ element.dispatchEvent(new InputEvent("input", event));
+ }
+ } finally {
+ isApplyingSuggestion = false;
+ }
+
+ const lengthDiff = replacement.length - original.length;
+ checkedText = getTextFromElement(element);
+ currentSuggestions = checkedText === newText
+ ? currentSuggestions.flatMap((item) => {
+ if (item.id === suggestion.id) return [];
+ if (item.endIndex <= startIndex) return [item];
+ if (item.startIndex < endIndex) return [];
+ return [{
+ ...item,
+ startIndex: item.startIndex + lengthDiff,
+ endIndex: item.endIndex + lengthDiff,
+ }];
+ })
+ : [];
+
+ browser.runtime.sendMessage({ type: "CORRECTION_APPLIED" }).catch(() => {});
+ return true;
}
function ignoreSuggestion(suggestion: GrammarSuggestion) {
@@ -1304,26 +1240,34 @@ export default defineContentScript({
const container = createOverlayContainer();
const shadow = container.shadowRoot!;
- shadow.querySelectorAll(".tc-underline").forEach((el) => el.remove());
+ for (const underline of underlineTargets.keys()) underline.remove();
+ underlineTargets.clear();
- if (!activeElement || currentSuggestions.length === 0) return;
+ const element = activeElement;
+ if (!element || currentSuggestions.length === 0) return;
+ const standardField = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;
+ const text = getTextFromElement(element);
+ if (text !== checkedText) return;
+ const editorRange = standardField ? null : mapEditorRanges(element, text);
currentSuggestions.forEach((suggestion) => {
- const rects = getCharacterRects(
- activeElement!,
- suggestion.startIndex,
- suggestion.endIndex
- );
+ const { startIndex, endIndex, original } = suggestion;
+ if (text.slice(startIndex, endIndex) !== original) return;
+
+ const rects = standardField
+ ? getTextareaCharacterRects(element, startIndex, endIndex)
+ : Array.from(editorRange?.(startIndex, endIndex)?.getClientRects() ?? []);
+ const insertion = startIndex === endIndex;
rects.forEach((rect) => {
- if (rect.width <= 0 || rect.height <= 0) return;
+ if (rect.height <= 0 || (!insertion && rect.width <= 0)) return;
const underline = document.createElement("div");
underline.className = "tc-underline";
underline.style.cssText = `
- left: ${rect.left}px;
+ left: ${insertion ? rect.left - 2 : rect.left}px;
top: ${rect.bottom - 2}px;
- width: ${Math.max(rect.width, 4)}px;
+ width: ${insertion ? 4 : Math.max(rect.width, 2)}px;
background: ${getSuggestionColor(suggestion.type)};
`;
@@ -1339,123 +1283,134 @@ export default defineContentScript({
});
shadow.appendChild(underline);
+ underlineTargets.set(underline, { suggestion, rect });
});
});
}
- // Event handlers
- function handleFocus(element: HTMLElement) {
- if (!settings.enabled || !isEditableElement(element)) return;
-
- activeElement = element;
-
- if (settings.checkMode === "realtime") {
- const text = getTextFromElement(element);
- if (text.length > 10) {
- debouncedCheck(text);
+ function handleSuggestionContextMenu(event: MouseEvent) {
+ const element = activeElement;
+ if (!element || underlineTargets.size === 0 || getTextFromElement(element) !== checkedText) return;
+
+ const path = event.composedPath();
+ const inEditor = path.includes(element);
+ const { clientX, clientY } = event;
+ for (const [underline, { suggestion, rect }] of underlineTargets) {
+ const horizontalPadding = suggestion.startIndex === suggestion.endIndex ? 4 : 0;
+ const overText = inEditor && clientX >= rect.left - horizontalPadding &&
+ clientX <= rect.right + horizontalPadding && clientY >= rect.top && clientY <= rect.bottom;
+ if (path.includes(underline) || overText) {
+ event.preventDefault();
+ event.stopPropagation();
+ showPopover(suggestion, rect);
+ return;
}
}
}
- function handleBlur() {
- setTimeout(() => {
- if (document.activeElement !== activeElement) {
- cleanup();
- activeElement = null;
- }
- }, 300);
- }
+ function queueFieldCheck(element: HTMLElement, force = false) {
+ if (!settings.enabled || (!force && settings.checkMode !== "realtime")) return;
- function handleInput(element: HTMLElement) {
- if (!settings.enabled || !isEditableElement(element)) return;
+ const text = getTextFromElement(element);
+ if (text.trim().length < minTextLength) {
+ cleanup();
+ return;
+ }
- activeElement = element;
- hideSuggestionPanel();
- hidePopover();
+ pendingFieldCheck = { element, text, force };
+ if (fieldCheckTimer !== null) clearTimeout(fieldCheckTimer);
+ fieldCheckTimer = null;
- if (settings.checkMode === "realtime") {
- const text = getTextFromElement(element);
- if (text.length > 10) {
- debouncedCheck(text);
- } else {
- cleanup();
- }
+ if (force) {
+ void runPendingFieldCheck();
+ } else {
+ fieldCheckTimer = setTimeout(() => {
+ fieldCheckTimer = null;
+ void runPendingFieldCheck();
+ }, settings.realtimeDelay);
}
}
- const debouncedCheck = debounce(async (text: string) => {
- if (isChecking || !activeElement) return;
- isChecking = true;
+ async function runPendingFieldCheck() {
+ if (isChecking || !pendingFieldCheck || !settings.enabled) return;
+
+ const { element, text, force } = pendingFieldCheck;
+ pendingFieldCheck = null;
+ const isCurrent = () => !ctx.isInvalid && settings.enabled &&
+ (force || settings.checkMode === "realtime") &&
+ activeElement === element && getTextFromElement(element) === text;
+ if (!isCurrent()) return;
+ isChecking = true;
showStatusButton("loading");
try {
- const result = await checkGrammarRequest(text);
- if (result && activeElement) {
+ const result = await checkGrammarRequest(text, force);
+ if (isCurrent()) {
+ checkedText = text;
+ reviewIncomplete = !!result.incomplete;
currentSuggestions = result.suggestions;
renderUnderlines();
-
- if (currentSuggestions.length > 0) {
- showStatusButton("errors", currentSuggestions.length);
- } else {
- showStatusButton("clean");
- }
+ const count = currentSuggestions.length;
+ showStatusButton(count ? "errors" : result.incomplete ? "incomplete" : "clean", count);
}
} catch (error) {
- console.error("Grammar check error:", error);
- hideStatusButton();
+ if (isCurrent()) {
+ showStatusButton("failed", 0, error instanceof Error ? error.message : "Could not check the text.");
+ }
} finally {
isChecking = false;
+ if (fieldCheckTimer === null) void runPendingFieldCheck();
}
- }, settings.realtimeDelay);
+ }
- // Message listener for keyboard shortcut
- browser.runtime.onMessage.addListener((message) => {
- if (message.type === "TRIGGER_CHECK") {
- if (googleDocsHandler.isGoogleDocs()) {
- googleDocsHandler.triggerManualCheck();
- } else if (activeElement) {
- const text = getTextFromElement(activeElement);
- if (text.length > 3) {
- showStatusButton("loading");
- checkGrammarRequest(text, true)
- .then((result) => {
- if (result) {
- currentSuggestions = result.suggestions;
- renderUnderlines();
- if (currentSuggestions.length > 0) {
- showStatusButton("errors", currentSuggestions.length);
- } else {
- showStatusButton("clean");
- }
- }
- })
- .catch(() => {
- hideStatusButton();
- });
- }
+ function handleFocus(element: HTMLElement) {
+ if (isApplyingSuggestion || !settings.enabled || !isEditableElement(element)) return;
+ if (activeElement !== element) cleanup();
+ activeElement = element;
+ queueFieldCheck(element);
+ }
+
+ function handleBlur() {
+ setTimeout(() => {
+ if (activeElement && !activeElement.contains(document.activeElement)) {
+ cleanup();
+ activeElement = null;
}
+ }, 300);
+ }
+
+ function handleInput(element: HTMLElement) {
+ if (isApplyingSuggestion || !settings.enabled || !isEditableElement(element)) return;
+ cleanup();
+ activeElement = element;
+ queueFieldCheck(element);
+ }
+
+ browser.runtime.onMessage.addListener((message) => {
+ if (message.type !== "TRIGGER_CHECK" || !settings.enabled) return;
+
+ if (googleDocsHandler.isGoogleDocs()) {
+ googleDocsHandler.triggerManualCheck();
+ } else if (activeElement) {
+ queueFieldCheck(activeElement, true);
}
});
- // Setup event listeners
- document.addEventListener(
- "focusin",
- (e) => {
- if (e.target instanceof HTMLElement) handleFocus(e.target);
- },
- true
- );
+ document.addEventListener("focusin", (event) => {
+ if (event.target instanceof HTMLElement) handleFocus(event.target);
+ }, true);
- document.addEventListener("focusout", () => handleBlur(), true);
+ document.addEventListener("focusout", handleBlur, true);
+ document.addEventListener("contextmenu", handleSuggestionContextMenu, true);
- document.addEventListener(
- "input",
- (e) => {
- if (e.target instanceof HTMLElement) handleInput(e.target);
- },
- true
- );
+ document.addEventListener("input", (event) => {
+ if (event.target instanceof HTMLElement) handleInput(event.target);
+ }, true);
+
+ if (!googleDocsHandler.isGoogleDocs() && document.activeElement instanceof HTMLElement) {
+ handleFocus(document.activeElement);
+ }
const handleScroll = debounce(() => {
if (activeElement && currentSuggestions.length > 0) {
@@ -1491,7 +1446,7 @@ export default defineContentScript({
);
ctx.onInvalidated(() => {
- textareaObserver.stop();
+ document.removeEventListener("contextmenu", handleSuggestionContextMenu, true);
googleDocsHandler.stop();
cleanup();
if (unwatchSettings) unwatchSettings();
diff --git a/src/entrypoints/options/App.tsx b/src/entrypoints/options/App.tsx
index fcbac99..a772631 100644
--- a/src/entrypoints/options/App.tsx
+++ b/src/entrypoints/options/App.tsx
@@ -1,7 +1,8 @@
import { useState, useEffect } from 'react';
+import type { CodexModel } from '@/lib/ai/codex';
import { settingsStorage, apiKeysStorage, dictionaryStorage, statsStorage } from '@/lib/storage';
import type { Settings, APIKeys, AIProvider } from '@/types';
-import { DEFAULT_SETTINGS, AVAILABLE_MODELS, SUPPORTED_LANGUAGES } from '@/types';
+import { DEFAULT_SETTINGS, AVAILABLE_MODELS, PROVIDER_NAMES, SUPPORTED_LANGUAGES } from '@/types';
import { Key, Settings as SettingsIcon, Book, BarChart3, Eye, EyeOff, Trash2, Save, CheckCircle } from 'lucide-react';
type TabType = 'api-keys' | 'settings' | 'dictionary' | 'stats';
@@ -40,7 +41,7 @@ export default function App() {
setTimeout(() => setSaveStatus('idle'), 2000);
}
- async function saveApiKey(provider: AIProvider, key: string) {
+ async function saveApiKey(provider: keyof APIKeys, key: string) {
const newKeys = { ...apiKeys, [provider]: key };
setApiKeys(newKeys);
setSaveStatus('saving');
@@ -146,9 +147,9 @@ function APIKeysTab({
apiKeys: APIKeys;
showKeys: Record
;
setShowKeys: (keys: Record) => void;
- saveApiKey: (provider: AIProvider, key: string) => void;
+ saveApiKey: (provider: keyof APIKeys, key: string) => void;
}) {
- const providers: { id: AIProvider; name: string; url: string }[] = [
+ const providers: { id: keyof APIKeys; name: string; url: string }[] = [
{ id: 'google', name: 'Google AI (Gemini)', url: 'https://aistudio.google.com/apikey' },
{ id: 'openai', name: 'OpenAI', url: 'https://platform.openai.com/api-keys' },
{ id: 'anthropic', name: 'Anthropic (Claude)', url: 'https://console.anthropic.com/settings/keys' },
@@ -159,7 +160,7 @@ function APIKeysTab({
How to get API keys
- You need at least one API key to use TextChecker. Your keys are stored securely in your browser
+ Codex uses your ChatGPT sign-in through the local bridge. For the providers below, enter an API key. Your keys are stored in your browser
and synced across your devices. They are never sent to any server except the AI provider.
@@ -216,19 +217,56 @@ function SettingsTab({
saveSettings: (settings: Settings) => void;
apiKeys: APIKeys;
}) {
- const providers: AIProvider[] = ['google', 'openai', 'anthropic'];
- const availableProviders = providers.filter((p) => apiKeys[p]);
+ const providers: AIProvider[] = ['google', 'openai', 'anthropic', 'codex'];
+ const [codexModels, setCodexModels] = useState([]);
+ const [codexStatus, setCodexStatus] = useState('');
+ const [loadingModels, setLoadingModels] = useState(false);
+ const [modelRefresh, setModelRefresh] = useState(0);
+ const isCodex = settings.provider === 'codex';
+
+ useEffect(() => {
+ if (!isCodex) return;
+
+ let active = true;
+ setLoadingModels(true);
+ setCodexStatus('Loading models from Codex…');
+
+ async function loadModels() {
+ try {
+ const response = await browser.runtime.sendMessage({ type: 'CODEX_MODELS' });
+ if (!response?.success || !Array.isArray(response.models)) {
+ throw new Error(response?.error || 'Update the local TextChecker bridge to load Codex models.');
+ }
+ if (active) {
+ setCodexModels(response.models);
+ setCodexStatus(response.models.length
+ ? 'Models loaded from your Codex session.'
+ : 'Codex returned no selectable models.');
+ }
+ } catch (error) {
+ if (active) {
+ setCodexStatus(error instanceof Error ? error.message : 'Could not load Codex models.');
+ }
+ } finally {
+ if (active) setLoadingModels(false);
+ }
+ }
+
+ void loadModels();
+ return () => { active = false; };
+ }, [isCodex, modelRefresh]);
+
+ const defaultCodexModel = codexModels.find((model) => model.isDefault);
+ const models = isCodex ? [
+ {
+ id: 'codex-default',
+ name: defaultCodexModel ? `Codex default (${defaultCodexModel.name})` : 'Codex default',
+ },
+ ...codexModels,
+ ] : AVAILABLE_MODELS[settings.provider];
return (
- {availableProviders.length === 0 && (
-
-
- Please add at least one API key in the "API Keys" tab to use TextChecker.
-
-
- )}
-
AI Provider
{
const provider = e.target.value as AIProvider;
const defaultModel = AVAILABLE_MODELS[provider][0].id;
- saveSettings({ ...settings, provider, model: defaultModel });
+ saveSettings({
+ ...settings,
+ provider,
+ model: defaultModel,
+ checkMode: provider === 'codex' ? 'ondemand' : settings.checkMode,
+ });
}}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{providers.map((p) => (
-
- {p.charAt(0).toUpperCase() + p.slice(1)} {!apiKeys[p] && '(no API key)'}
+
+ {PROVIDER_NAMES[p]} {p !== 'codex' && !apiKeys[p] && '(no API key)'}
))}
@@ -262,7 +305,10 @@ function SettingsTab({
}}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
- {AVAILABLE_MODELS[settings.provider].map((model) => (
+ {isCodex && settings.model !== 'custom' && !models.some((model) => model.id === settings.model) && (
+ {settings.model} (saved model)
+ )}
+ {models.map((model) => (
{model.name}
@@ -271,6 +317,20 @@ function SettingsTab({
+ {isCodex && (
+
+
setModelRefresh((count) => count + 1)}
+ disabled={loadingModels}
+ className="font-medium text-blue-700 underline disabled:opacity-50"
+ >
+ Refresh Codex models
+
+
{codexStatus}
+
+ )}
+
{settings.model === 'custom' && (
Custom Model ID
diff --git a/src/entrypoints/popup/App.tsx b/src/entrypoints/popup/App.tsx
index 3c5ee00..b142c6e 100644
--- a/src/entrypoints/popup/App.tsx
+++ b/src/entrypoints/popup/App.tsx
@@ -1,16 +1,17 @@
import { useState, useEffect } from 'react';
import { settingsStorage, statsStorage } from '@/lib/storage';
-import type { Settings, AIProvider, CheckMode } from '@/types';
-import { DEFAULT_SETTINGS } from '@/types';
+import type { Settings, APIKeys, CheckMode } from '@/types';
+import { DEFAULT_SETTINGS, PROVIDER_NAMES } from '@/types';
import { Settings as SettingsIcon, Power, Keyboard, Zap, AlertCircle, CheckCircle2 } from 'lucide-react';
export default function App() {
const [settings, setSettings] = useState
(DEFAULT_SETTINGS);
- const [hasApiKey, setHasApiKey] = useState>({
+ const [hasApiKey, setHasApiKey] = useState>({
google: false,
openai: false,
anthropic: false,
});
+ const [codexError, setCodexError] = useState('Could not check the Codex connection.');
const [stats, setStats] = useState({ checksPerformed: 0, errorsFound: 0, correctionsApplied: 0 });
const [loading, setLoading] = useState(true);
@@ -24,6 +25,10 @@ export default function App() {
if (response.success) {
setSettings(response.settings);
setHasApiKey(response.hasApiKey);
+ if (response.settings.provider === 'codex') {
+ const status = await browser.runtime.sendMessage({ type: 'CODEX_STATUS' });
+ setCodexError(status.success ? '' : status.error);
+ }
}
const loadedStats = await statsStorage.getValue();
setStats(loadedStats);
@@ -50,8 +55,8 @@ export default function App() {
browser.runtime.openOptionsPage();
}
- const hasAnyApiKey = hasApiKey.google || hasApiKey.openai || hasApiKey.anthropic;
- const providerName = settings.provider.charAt(0).toUpperCase() + settings.provider.slice(1);
+ const ready = settings.provider === 'codex' ? !codexError : hasApiKey[settings.provider];
+ const providerName = PROVIDER_NAMES[settings.provider];
if (loading) {
return (
@@ -83,12 +88,12 @@ export default function App() {
{/* Status */}
- {!hasAnyApiKey ? (
+ {!ready ? (
Setup Required
-
Add an API key to start checking grammar.
+
{settings.provider === 'codex' ? codexError : 'Add an API key or select Codex in Settings.'}
{/* Controls */}
- {hasAnyApiKey && (
+ {ready && (
{/* Enable/Disable Toggle */}
{
+ let response: CodexResponse;
+ try {
+ response = await browser.runtime.sendNativeMessage(HOST, request);
+ } catch {
+ throw new Error('Install or update the TextChecker Codex bridge for this browser.');
+ }
+
+ if (!response?.success) {
+ throw new Error(response?.error || 'The Codex bridge could not complete the request.');
+ }
+ return response;
+}
diff --git a/src/lib/ai/grammar-check.ts b/src/lib/ai/grammar-check.ts
index 249bb4a..d52620c 100644
--- a/src/lib/ai/grammar-check.ts
+++ b/src/lib/ai/grammar-check.ts
@@ -1,5 +1,7 @@
import { generateText } from 'ai';
import { getModel } from './providers';
+import { requestCodex } from './codex';
+import { splitSuggestion } from './suggestion-edits';
import { GRAMMAR_CHECK_SYSTEM_PROMPT, createGrammarCheckPrompt, REWRITE_SYSTEM_PROMPT, createRewritePrompt } from './prompts';
import type { AIProvider, GrammarSuggestion, GrammarCheckResult } from '@/types';
@@ -10,23 +12,51 @@ interface GrammarCheckOptions {
language: string;
}
+type AIGrammarSuggestion = Omit & { line: number };
+
interface AIGrammarResponse {
- suggestions: Array<{
- original: string;
- replacement: string;
- explanation: string;
- type: 'spelling' | 'grammar' | 'punctuation' | 'style';
- startIndex: number;
- endIndex: number;
- }>;
+ suggestions: AIGrammarSuggestion[];
detectedLanguage: string;
}
+function findUniqueFragment(text: string, original: string): number {
+ const index = text.indexOf(original);
+ return index >= 0 && text.indexOf(original, index + 1) === -1 ? index : -1;
+}
+
+function locateSuggestion(
+ suggestion: AIGrammarSuggestion,
+ text: string,
+ lines: string[],
+ lineStarts: number[],
+): Omit | null {
+ const { original, replacement, explanation, type, line } = suggestion;
+ if (typeof original !== 'string' || !original.trim() || original === replacement) return null;
+
+ const lineIndex = Number.isInteger(line) ? line - 1 : -1;
+ const lineText = lines[lineIndex];
+ const offset = lineText === undefined ? -1 : findUniqueFragment(lineText, original);
+ const startIndex = offset === -1 ? findUniqueFragment(text, original) : lineStarts[lineIndex] + offset;
+ const located = { original, replacement, explanation, type, startIndex, endIndex: startIndex + original.length };
+ return isValidSuggestion(located, text) ? located : null;
+}
+
+export function isValidSuggestion(
+ { original, replacement, startIndex, endIndex }: Pick,
+ text: string,
+): boolean {
+ return Number.isInteger(startIndex) && Number.isInteger(endIndex)
+ && startIndex >= 0 && startIndex <= endIndex && endIndex <= text.length
+ && typeof original === 'string' && typeof replacement === 'string'
+ && !/[\r\n]/.test(original) && !/[\r\n]/.test(replacement)
+ && text.slice(startIndex, endIndex) === original;
+}
+
export async function checkGrammar(
text: string,
options: GrammarCheckOptions
): Promise {
- const { provider, model: modelId, apiKey, language } = options;
+ const { language } = options;
if (!text.trim()) {
return {
@@ -38,51 +68,47 @@ export async function checkGrammar(
}
try {
- const model = getModel(provider, modelId, apiKey);
-
- const { text: responseText } = await generateText({
- model,
- system: GRAMMAR_CHECK_SYSTEM_PROMPT,
- prompt: createGrammarCheckPrompt(text, language),
- temperature: 0.1, // Low temperature for consistent results
+ const lines = text.split(/\r\n|\r|\n/);
+ let nextStart = 0;
+ const lineStarts = lines.map((line) => {
+ const start = nextStart;
+ const end = start + line.length;
+ nextStart = end + (text.startsWith('\r\n', end) ? 2 : 1);
+ return start;
});
+ const responseText = await generateWritingText(
+ options, GRAMMAR_CHECK_SYSTEM_PROMPT, createGrammarCheckPrompt(lines, language), 0.1,
+ );
// Parse the JSON response
const jsonMatch = responseText.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
- console.error('Failed to parse AI response:', responseText);
- return {
- suggestions: [],
- text,
- language: language === 'auto' ? 'en' : language,
- timestamp: Date.now(),
- };
+ throw new Error('The model did not return grammar suggestions in the expected format.');
}
const parsed: AIGrammarResponse = JSON.parse(jsonMatch[0]);
- // Validate and filter suggestions
- const validSuggestions: GrammarSuggestion[] = parsed.suggestions
- .filter((s) => {
- // Verify the original text matches the actual text at the specified position
- const actualText = text.substring(s.startIndex, s.endIndex);
- return actualText === s.original;
- })
- .map((s, index) => ({
- id: `suggestion-${Date.now()}-${index}`,
- original: s.original,
- replacement: s.replacement,
- explanation: s.explanation,
- type: s.type,
- startIndex: s.startIndex,
- endIndex: s.endIndex,
- }));
+ const timestamp = Date.now();
+ const located = parsed.suggestions.flatMap((suggestion) => {
+ const match = locateSuggestion(suggestion, text, lines, lineStarts);
+ return match ? [match] : [];
+ });
+ const edits = new Map>();
+ for (const suggestion of located.flatMap(splitSuggestion)) {
+ const key = JSON.stringify([suggestion.startIndex, suggestion.endIndex, suggestion.replacement]);
+ if (!edits.has(key)) edits.set(key, suggestion);
+ }
+ const validSuggestions = Array.from(edits.values(), (suggestion, index) => ({
+ ...suggestion,
+ id: `suggestion-${timestamp}-${index}`,
+ })).sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);
return {
suggestions: validSuggestions,
+ incomplete: located.length < parsed.suggestions.length,
text,
language: parsed.detectedLanguage || (language === 'auto' ? 'en' : language),
- timestamp: Date.now(),
+ timestamp,
};
} catch (error) {
console.error('Grammar check error:', error);
@@ -95,21 +121,14 @@ export async function rewriteText(
style: 'formal' | 'casual' | 'concise' | 'elaborate',
options: Omit
): Promise {
- const { provider, model: modelId, apiKey } = options;
-
if (!text.trim()) {
return text;
}
try {
- const model = getModel(provider, modelId, apiKey);
-
- const { text: rewrittenText } = await generateText({
- model,
- system: REWRITE_SYSTEM_PROMPT,
- prompt: createRewritePrompt(text, style),
- temperature: 0.7, // Higher temperature for creative rewriting
- });
+ const rewrittenText = await generateWritingText(
+ options, REWRITE_SYSTEM_PROMPT, createRewritePrompt(text, style), 0.7,
+ );
return rewrittenText.trim();
} catch (error) {
@@ -117,3 +136,21 @@ export async function rewriteText(
throw error;
}
}
+
+async function generateWritingText(
+ { provider, model, apiKey }: Omit,
+ system: string,
+ prompt: string,
+ temperature: number,
+): Promise {
+ if (provider === 'codex') {
+ const response = await requestCodex({ type: 'generate', model, instructions: system, prompt });
+ if (typeof response.text !== 'string') {
+ throw new Error('The Codex bridge returned an invalid response.');
+ }
+ return response.text;
+ }
+
+ const result = await generateText({ model: getModel(provider, model, apiKey), system, prompt, temperature });
+ return result.text;
+}
diff --git a/src/lib/ai/prompts.ts b/src/lib/ai/prompts.ts
index cb988b0..fe1da5b 100644
--- a/src/lib/ai/prompts.ts
+++ b/src/lib/ai/prompts.ts
@@ -2,11 +2,15 @@ export const GRAMMAR_CHECK_SYSTEM_PROMPT = `You are a professional grammar, spel
IMPORTANT RULES:
1. Only identify REAL errors - do not flag correct text
-2. Be precise with character positions - they must match exactly
+2. Copy the original fragment exactly and give its line number
3. Consider the context and language of the text
4. For each issue, provide a clear, helpful explanation
5. Respect regional variations (e.g., British vs American English)
6. Do not change the author's voice or style unless it's grammatically incorrect
+7. Read the surrounding lines before deciding whether text is incomplete. Evaluate words like "Si" in the context of the sentence they introduce.
+8. Keep each suggestion within one line. Never include or replace a line break.
+9. Check spelling and punctuation in every sentence, including short standalone sentences in longer texts. In Spanish, check required accents and opening and closing question or exclamation marks. For example, "Tienes mas tiempo para manana???" should be "¿Tienes más tiempo para mañana?".
+10. Return one suggestion per independent change. Select only the wrong word or punctuation. Include exactly enough neighboring text to locate a repeated fragment or a missing character. Keep that context identical in the replacement. For example, to add a missing comma after "Si pots" use "Si pots" → "Si pots,".
ISSUE TYPES:
- spelling: Misspelled words
@@ -22,8 +26,7 @@ Respond ONLY with valid JSON in this exact format:
"replacement": "corrected text",
"explanation": "brief explanation of the issue",
"type": "spelling|grammar|punctuation|style",
- "startIndex": 0,
- "endIndex": 10
+ "line": 1
}
],
"detectedLanguage": "en"
@@ -35,23 +38,22 @@ If no issues are found, return:
"detectedLanguage": "en"
}`;
-export function createGrammarCheckPrompt(text: string, language: string): string {
+export function createGrammarCheckPrompt(lines: string[], language: string): string {
const languageInstruction = language === 'auto'
? 'Detect the language automatically.'
: `The text is in ${language}. Check according to ${language} grammar rules.`;
+ const numberedText = lines.map((line, index) => `${index + 1} | ${line}`).join('\n');
+
return `${languageInstruction}
-Analyze the following text for grammar, spelling, punctuation, and style issues:
+Analyze the entire numbered text for grammar, spelling, punctuation, and style issues. The line number and bar are labels, separate from the text.
"""
-${text}
+${numberedText}
"""
-Remember:
-- startIndex and endIndex are 0-based character positions
-- "original" must be the EXACT text from the input at those positions
-- Only report genuine errors`;
+For each suggestion, copy the original fragment exactly and include its line number.`;
}
export const REWRITE_SYSTEM_PROMPT = `You are a professional writing assistant. Your task is to rewrite text while:
diff --git a/src/lib/ai/providers.ts b/src/lib/ai/providers.ts
index 5ece8fd..ece50b8 100644
--- a/src/lib/ai/providers.ts
+++ b/src/lib/ai/providers.ts
@@ -1,9 +1,9 @@
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { createOpenAI } from '@ai-sdk/openai';
import { createAnthropic } from '@ai-sdk/anthropic';
-import type { AIProvider } from '@/types';
+import type { APIKeys } from '@/types';
-export function createAIProvider(provider: AIProvider, apiKey: string) {
+export function createAIProvider(provider: keyof APIKeys, apiKey: string) {
switch (provider) {
case 'google':
return createGoogleGenerativeAI({ apiKey });
@@ -16,7 +16,7 @@ export function createAIProvider(provider: AIProvider, apiKey: string) {
}
}
-export function getModel(provider: AIProvider, modelId: string, apiKey: string) {
+export function getModel(provider: keyof APIKeys, modelId: string, apiKey: string) {
const aiProvider = createAIProvider(provider, apiKey);
switch (provider) {
diff --git a/src/lib/ai/suggestion-edits.ts b/src/lib/ai/suggestion-edits.ts
new file mode 100644
index 0000000..00afc3f
--- /dev/null
+++ b/src/lib/ai/suggestion-edits.ts
@@ -0,0 +1,93 @@
+import type { GrammarSuggestion } from '@/types';
+
+type LocatedSuggestion = Omit;
+const MAX_DIFF_CELLS = 100_000;
+const WORD_WITH_PUNCTUATION = /^([^\p{L}\p{M}\p{N}\s]*)([\p{L}\p{M}\p{N}]+)([^\p{L}\p{M}\p{N}\s]*)$/u;
+
+function tokenize(text: string) {
+ return [...text.matchAll(/[\p{L}\p{M}\p{N}]+|\s+|[^\p{L}\p{M}\p{N}\s]/gu)];
+}
+
+export function splitSuggestion(suggestion: LocatedSuggestion): LocatedSuggestion[] {
+ const { original, replacement, startIndex } = suggestion;
+ const before = tokenize(original);
+ const after = tokenize(replacement);
+ let start = 0;
+ let beforeEnd = before.length;
+ let afterEnd = after.length;
+ while (start < beforeEnd && start < afterEnd && before[start][0] === after[start][0]) {
+ start++;
+ }
+ while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1][0] === after[afterEnd - 1][0]) {
+ beforeEnd--;
+ afterEnd--;
+ }
+
+ const edits: LocatedSuggestion[] = [];
+ let beforeStart = start;
+ let afterStart = start;
+ function addFragment(left: number, oldText: string, newText: string) {
+ if (oldText === newText) return;
+ edits.push({
+ ...suggestion,
+ original: oldText,
+ replacement: newText,
+ startIndex: startIndex + left,
+ endIndex: startIndex + left + oldText.length,
+ });
+ }
+
+ function addEdit(beforeStop: number, afterStop: number) {
+ if (beforeStart === beforeStop && afterStart === afterStop) return;
+ const left = before[beforeStart]?.index ?? original.length;
+ const right = before[beforeStop]?.index ?? original.length;
+ const replacementStart = after[afterStart]?.index ?? replacement.length;
+ const replacementEnd = after[afterStop]?.index ?? replacement.length;
+
+ const oldText = original.slice(left, right);
+ const newText = replacement.slice(replacementStart, replacementEnd);
+ const oldParts = WORD_WITH_PUNCTUATION.exec(oldText);
+ const newParts = WORD_WITH_PUNCTUATION.exec(newText);
+
+ if (oldParts && newParts) {
+ // Keep an adjacent punctuation change separate from a word replacement.
+ addFragment(left, oldParts[1], newParts[1]);
+ addFragment(left + oldParts[1].length, oldParts[2], newParts[2]);
+ addFragment(left + oldParts[1].length + oldParts[2].length, oldParts[3], newParts[3]);
+ } else {
+ addFragment(left, oldText, newText);
+ }
+ }
+
+ const rows = beforeEnd - start + 1;
+ const columns = afterEnd - start + 1;
+ if (rows * columns <= MAX_DIFF_CELLS) {
+ // Unchanged tokens separate independently applicable edits.
+ const lengths = new Uint32Array(rows * columns);
+ for (let row = rows - 2; row >= 0; row--) {
+ for (let column = columns - 2; column >= 0; column--) {
+ const index = row * columns + column;
+ lengths[index] = before[start + row][0] === after[start + column][0]
+ ? 1 + lengths[index + columns + 1]
+ : Math.max(lengths[index + columns], lengths[index + 1]);
+ }
+ }
+
+ let row = 0;
+ let column = 0;
+ while (row < rows - 1 && column < columns - 1) {
+ const index = row * columns + column;
+ if (before[start + row][0] === after[start + column][0]) {
+ addEdit(start + row, start + column);
+ beforeStart = start + ++row;
+ afterStart = start + ++column;
+ } else if (lengths[index + columns] >= lengths[index + 1]) {
+ row++;
+ } else {
+ column++;
+ }
+ }
+ }
+ addEdit(beforeEnd, afterEnd);
+ return edits;
+}
diff --git a/src/types/index.ts b/src/types/index.ts
index ca62997..123a50c 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -1,4 +1,4 @@
-export type AIProvider = 'google' | 'openai' | 'anthropic';
+export type AIProvider = keyof APIKeys | 'codex';
export type CheckMode = 'realtime' | 'ondemand';
@@ -31,6 +31,7 @@ export interface GrammarSuggestion {
}
export interface GrammarCheckResult {
+ incomplete?: boolean;
suggestions: GrammarSuggestion[];
text: string;
language: string;
@@ -59,7 +60,15 @@ export const DEFAULT_SETTINGS: Settings = {
realtimeDelay: 500,
};
+export const PROVIDER_NAMES: Record = {
+ google: 'Google',
+ openai: 'OpenAI',
+ anthropic: 'Anthropic',
+ codex: 'Codex (ChatGPT subscription)',
+};
+
export const AVAILABLE_MODELS: Record = {
+ codex: [{ id: 'codex-default', name: 'Codex default' }],
google: [
{ id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash (Recommended)' },
{ id: 'gemini-2.5-flash-lite', name: 'Gemini 2.5 Flash Lite (Fastest)' },
diff --git a/wxt.config.ts b/wxt.config.ts
index 1814599..69f7c86 100644
--- a/wxt.config.ts
+++ b/wxt.config.ts
@@ -4,11 +4,16 @@ import react from '@vitejs/plugin-react';
export default defineConfig({
srcDir: 'src',
modules: ['@wxt-dev/module-react'],
- manifest: {
+ manifest: ({ browser }) => ({
+ ...(browser === 'firefox' ? {
+ browser_specific_settings: { gecko: { id: 'textchecker@codextde.github.io' } },
+ } : {
+ key: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxorixDZjYZ5KMeXo9E//ZKWqP9eDvK72LxZAy8qkaqnUpwLmnMsOChwsKljdqBbT6HL12l8Qs2F00+BLK6oGQ/E5unRwxTx19AIMVTBeG7TrcOedDxfCElyblU/2Zhmuqcp674+VJUf4IK5flDOJwUP9hiApZMqnWdRuj7qvuvlXPHIDWbyAOQu6amd04ExXCGHWLtwOVbtfz0/MZe+GqZGRzi0AHLEElFqUeU1OXETs0FnMkLnNFCj7dVsNXajRCuiYnBowECY1joE11Uw1MI1AS9mDfVXH23EEwWgYyu1MxwlR+a+UO3S0Lo9Iu85w6hlxMOJOEKiu4p6zv4odrwIDAQAB',
+ }),
name: 'TextChecker - AI Grammar Assistant',
description: 'Open-source AI-powered grammar, spelling, and style checker. Supports multiple AI providers.',
version: '1.0.0',
- permissions: ['storage', 'activeTab'],
+ permissions: ['storage', 'activeTab', 'nativeMessaging'],
host_permissions: [''],
action: {
default_title: 'TextChecker',
@@ -22,7 +27,7 @@ export default defineConfig({
description: 'Check grammar in current text field',
},
},
- },
+ }),
vite: () => ({
plugins: [react()],
}),