Skip to content

feat: Codex provider, note-aware context, built-in slash commands + UX improvements#17

Merged
FBarrca merged 7 commits into
FBarrca:mainfrom
FelixIsaac:felix/codex-subscription-provider
May 23, 2026
Merged

feat: Codex provider, note-aware context, built-in slash commands + UX improvements#17
FBarrca merged 7 commits into
FBarrca:mainfrom
FelixIsaac:felix/codex-subscription-provider

Conversation

@FelixIsaac

@FelixIsaac FelixIsaac commented May 22, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Codex (ChatGPT subscription) provider — OAuth PKCE flow, auto token refresh, direct responses API, SSE parsing, labeled model dropdown
  • Note-aware context injection — note title, nearest H1-H3 heading, up to 3 surrounding paragraphs, YAML frontmatter fields (tags/type/status), document type detection (daily note / meeting / code / literature) — all injected into the system prompt
  • Selection scope auto-tuning — word → brief output, sentence → sentence, paragraph → paragraph; model is told to match input scope automatically
  • 8 built-in slash commands/fix /shorter /longer /formal /casual /bullets /summarize /continue — ship with the plugin, no setup needed; appear in autocomplete and settings
  • Command composition/fix /formal chains both transforms in one prompt
  • Default hotkeyCtrl+Shift+Space for "Show cursor tooltip"
  • Prompt wrapping — input field now wraps long text instead of scrolling horizontally; layout grows vertically
  • Retry button — regenerate with the same prompt after seeing a diff
  • Keybind hint — "↵ accept · Esc dismiss" shown after AI responds
  • Inline errors — error text shown inside the widget, not just a floating Notice
  • Persistent prompt history — saved to localStorage so history survives Obsidian restarts
  • Input/output edge cases — 60k char truncation, empty model guard, 429/403 error messages, port clash detection

Test plan

  • Select text → Ctrl+Shift+Space → type /fix → confirm grammar corrected
  • Type /fix /formal → both transforms applied
  • Long prompt → input wraps instead of scrolling
  • After diff appears → see "↵ accept · Esc dismiss" hint + retry button
  • Retry button → regenerates same prompt
  • Bad API key → error shown inside widget
  • Note with tags: frontmatter → AI response reflects tags
  • Select a single word → AI output matches word length
  • Select multiple paragraphs → AI output matches scope
  • Codex: sign in → call succeeds → sign out clears tokens

🤖 Generated with Claude Code

… dropdown

native fetch blocked by Obsidian CSP for external domains; requestUrl
bypasses it. Also adds Codex model dropdown with known models + custom
fallback, updates normalizeModel for gpt-5.5/5.4-mini/5.3-codex-spark.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented May 22, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Replace fetch with Obsidian.requestUrl for OAuth and Codex streaming, refine Codex model normalization and SSE parsing, add provider-gated Codex model UI and built-in slash commands, and append extracted document context to selection prompts.

Changes

Obsidian API Integration and Codex Client Updates

Layer / File(s) Summary
Auth & Codex client network migration
src/codex-auth.ts, src/codex-client.ts
Import requestUrl and replace fetch with requestUrl({ url, ... , throw: false }) for token exchange, token refresh, and Codex API streaming; add explicit non-2xx checks via res.status, adapt parsing to res.json/res.text, add input truncation, and update SSE parsing entry points.
Editor context + selection flow
src/api.ts
Add extractNoteContext(selectionText) to gather nearby headings/paragraphs and append a "Document context" block to the system prompt used by callSelection/handleEditorUpdate.
Provider-gated model selection & built-in commands
src/settings.ts, src/modules/commands/*
When provider === "codex" show a Codex model dropdown with recommended options and a "Custom…" mode plus a custom-model ID field and warning; add and export BUILT_IN_COMMANDS, include built-ins in autocompletion/highlighter, and include built-ins in parseCommand matching.
Command hotkey
src/main.ts
Register Ctrl+Shift+Space as the hotkey for show-cursor-tooltip command.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • FBarrca/obsidian-inlineAI#16: Both PRs modify the same Codex implementation files; prior work added Codex provider code that this PR migrates and extends.

Poem

🐰 I hopped from fetch to requestUrl bright,
Tokens refreshed and streams read by night,
Mini and five-point-five models now play,
Dropdowns and slash-commands guide my way,
I nibble context, then hop — code feels light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the three main features: Codex provider integration, note-aware context injection, and built-in slash commands with UX improvements.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/codex-auth.ts (2)

1-205: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Prettier check is currently blocking this file.

CI reports formatting issues here; please run Prettier and commit the result to unblock merge.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/codex-auth.ts` around lines 1 - 205, The file src/codex-auth.ts fails CI
Prettier formatting; run Prettier on that file and commit the formatted result.
Specifically, reformat the whole file (including functions generatePKCE,
randomState, decodeJWT, extractAccountId, exchangeCode, refreshCodexToken,
getValidCodexToken, startCodexOAuthFlow) using your project's Prettier config
(or npm/yarn prettier --write) so spacing, semicolons, and line breaks match CI
expectations, then stage and push the updated file.

60-78: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Harden both OAuth token flows in src/codex-auth.ts against transport failures and non-JSON responses.

  • requestUrl(..., throw: false) doesn’t cover transport/network errors; add a try/catch around the requestUrl call in both exchangeCode (lines ~60-78) and refreshCodexToken (lines ~91-107).
  • Both flows read res.json and assume a valid payload; handle empty/invalid JSON (e.g., guard/try-catch around res.json or parse via res.text) and validate the expected types before using access_token, refresh_token, and expires_in.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/codex-auth.ts` around lines 60 - 78, The OAuth flows in exchangeCode and
refreshCodexToken must be hardened: wrap the requestUrl call in each function in
a try/catch to handle transport/network errors and return null (or appropriate
failure) on exception, and do not rely directly on res.json; instead read/parse
the response safely (e.g., get res.text and JSON.parse in a try/catch or guard
res.json access) and validate types for access_token, refresh_token, and
expires_in before using them—if parsing fails or required fields are
missing/incorrect types, return null and log/handle the error. Ensure you update
both exchangeCode and refreshCodexToken to follow the same pattern and reference
TOKEN_URL, CLIENT_ID, REDIRECT_URI, access_token, refresh_token, and expires_in
when validating.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/codex-client.ts`:
- Around line 22-33: The normalizeModel function currently maps any string
containing "codex" to "gpt-5.1-codex", which silently rewrites arbitrary custom
Codex IDs (e.g., "gpt-5.6-codex"); update normalizeModel to stop using the broad
m.includes("codex") rule: remove or narrow the clause that returns
"gpt-5.1-codex" for any m.includes("codex") and instead only map explicit legacy
aliases (exact matches like "codex" or previously supported short IDs) or
specific known tokens (e.g., "codex-max", "codex-mini") already handled, letting
unknown codex-branded IDs fall through to the final return so custom model IDs
are preserved.

In `@src/settings.ts`:
- Around line 147-158: When the dropdown value is changed to "custom" the code
currently only calls this.display(), so this.plugin.settings.model remains the
previous value and the UI snaps back; update the onChange handler inside the
Setting(...).addDropdown callback (the handler that compares value !== "custom")
to also set this.plugin.settings.model = "custom" and await this.saveSettings()
before calling this.display(), ensuring the "custom" selection is persisted
(references: Setting, addDropdown, CODEX_MODELS, dropdownValue,
this.plugin.settings.model, saveSettings, display).

---

Outside diff comments:
In `@src/codex-auth.ts`:
- Around line 1-205: The file src/codex-auth.ts fails CI Prettier formatting;
run Prettier on that file and commit the formatted result. Specifically,
reformat the whole file (including functions generatePKCE, randomState,
decodeJWT, extractAccountId, exchangeCode, refreshCodexToken,
getValidCodexToken, startCodexOAuthFlow) using your project's Prettier config
(or npm/yarn prettier --write) so spacing, semicolons, and line breaks match CI
expectations, then stage and push the updated file.
- Around line 60-78: The OAuth flows in exchangeCode and refreshCodexToken must
be hardened: wrap the requestUrl call in each function in a try/catch to handle
transport/network errors and return null (or appropriate failure) on exception,
and do not rely directly on res.json; instead read/parse the response safely
(e.g., get res.text and JSON.parse in a try/catch or guard res.json access) and
validate types for access_token, refresh_token, and expires_in before using
them—if parsing fails or required fields are missing/incorrect types, return
null and log/handle the error. Ensure you update both exchangeCode and
refreshCodexToken to follow the same pattern and reference TOKEN_URL, CLIENT_ID,
REDIRECT_URI, access_token, refresh_token, and expires_in when validating.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2e8186c5-54c8-4668-82e2-2f062de90337

📥 Commits

Reviewing files that changed from the base of the PR and between 5f21d0b and b389c59.

📒 Files selected for processing (3)
  • src/codex-auth.ts
  • src/codex-client.ts
  • src/settings.ts

Comment thread src/codex-client.ts
Comment thread src/settings.ts
response.output_text.delta has delta as plain string not object; fix
parseSseText to handle it. Also fix custom model dropdown — selecting
Custom now sets model to "" so isCustom triggers correctly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/settings.ts (1)

1-395: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Run Prettier on this file before merge.

CI is failing formatting for this file. Please run Prettier and commit the result (pipeline already flags this exact file).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/settings.ts` around lines 1 - 395, The file fails CI formatting; run the
project's Prettier formatter on this file and commit the changes — e.g., run
your repo's format script or `npx prettier --write src/settings.ts` — then
re-run CI. Focus on formatting changes only (no logic edits) in symbols like
DEFAULT_SETTINGS, InlineAISettingsTab, saveSettings and display so the file
meets the project's Prettier rules before merging.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/settings.ts`:
- Around line 1-395: The file fails CI formatting; run the project's Prettier
formatter on this file and commit the changes — e.g., run your repo's format
script or `npx prettier --write src/settings.ts` — then re-run CI. Focus on
formatting changes only (no logic edits) in symbols like DEFAULT_SETTINGS,
InlineAISettingsTab, saveSettings and display so the file meets the project's
Prettier rules before merging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b01a430e-05f0-4251-a241-b5b39b400e4b

📥 Commits

Reviewing files that changed from the base of the PR and between b389c59 and 1024c37.

📒 Files selected for processing (2)
  • src/codex-client.ts
  • src/settings.ts

FelixIsaac and others added 4 commits May 23, 2026 06:33
…eset, token warning

- pre-check port 1455 before OAuth flow to catch clashes early
- 403: friendly message suggesting gpt-5.4-mini fallback
- 429: "subscription limit reached" instead of raw error
- add response.output_text.done SSE path for reasoning-only responses
- reset model to gpt-5.4-mini when switching to Codex provider
- 10s notice on session expiry prompting user to re-sign-in in settings
- warn user tokens stored in plaintext data.json when signed in

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- model dropdown shows description for each option
- custom model field shows validation warning when empty
- guard against empty model before API call
- truncate inputs >60k chars with notice
- trim whitespace from output; clearer error for reasoning-only responses
- auto-reset model to gpt-5.4-mini when switching to Codex provider

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@FelixIsaac FelixIsaac changed the title fix: Codex CSP fetch fix + model dropdown feat: Codex provider, note-aware context, built-in slash commands + UX improvements May 23, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/settings.ts (1)

225-239: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Preserve custom model value when toggling between dropdown options.

When the user switches from a predefined model to "Custom…", then to another predefined model, and back to "Custom…" again, their previously-entered custom model ID is lost (Line 234 always clears model to ""). This forces the user to re-enter their custom model ID.

💾 Suggested fix to preserve the last custom model

Maintain a separate field (e.g., lastCustomModel) or only clear model when switching from a predefined value to "custom" for the first time:

 				.addDropdown((dd) => {
 					CODEX_MODELS.forEach((m) => dd.addOption(m.value, m.label));
 					dd.setValue(dropdownValue).onChange(async (value) => {
-						this.plugin.settings.model =
-							value === "custom" ? "" : value;
+						if (value === "custom") {
+							// Only clear if currently on a predefined model
+							const wasPredefined = CODEX_MODELS.some(
+								m => m.value === this.plugin.settings.model && m.value !== "custom"
+							);
+							if (wasPredefined) {
+								this.plugin.settings.model = "";
+							}
+							// Otherwise keep the current custom value
+						} else {
+							this.plugin.settings.model = value;
+						}
 						await this.saveSettings();
 						this.display();
 					});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/settings.ts` around lines 225 - 239, The dropdown currently clears
this.plugin.settings.model to "" whenever the user selects "custom", which loses
any previously-entered custom ID; modify the handler in the Setting.addDropdown
callback (where CODEX_MODELS are added and dd.setValue(...).onChange(...)) to
preserve the last custom value instead of unconditionally setting model = "";
implement either a new field this.plugin.settings.lastCustomModel that you
update when the user edits a custom model and restore into
this.plugin.settings.model when "custom" is reselected, or only clear model the
very first time switching to "custom" (checking previous value) so subsequent
toggles restore the stored custom value; ensure you still call await
this.saveSettings() and this.display() after updating settings.
♻️ Duplicate comments (1)
src/codex-client.ts (1)

35-36: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve custom Codex model IDs instead of coercing them to gpt-5.1-codex.

Line 35 still rewrites any model containing "codex", so custom IDs (for example, gpt-5.6-codex) cannot pass through unchanged.

💡 Proposed fix
-	if (m.includes("gpt-5.1-codex") || m.includes("codex"))
+	if (m.includes("gpt-5.1-codex") || m === "codex")
		return "gpt-5.1-codex";
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/codex-client.ts` around lines 35 - 36, The current mapping forcibly
rewrites any model string containing "codex" to "gpt-5.1-codex", which discards
custom Codex model IDs; update the logic in src/codex-client.ts where the
variable `m` is checked so that if `m` contains "codex" you return `m` unchanged
(or only coerce when `m` exactly equals a legacy alias), thereby preserving
custom IDs like "gpt-5.6-codex" instead of always returning "gpt-5.1-codex".
🧹 Nitpick comments (1)
src/settings.ts (1)

76-100: ⚡ Quick win

Extract model IDs to avoid duplication.

CODEX_MODEL_IDS defined here duplicates the model IDs from the CODEX_MODELS array at lines 167-212. If a model is added or removed from one list but not the other, they'll drift out of sync.

♻️ Refactor to derive IDs from CODEX_MODELS

Move CODEX_MODELS definition outside the display method (e.g., as a class constant or module-level constant), then derive the IDs:

+const CODEX_MODELS: {
+	value: string;
+	label: string;
+	desc: string;
+}[] = [
+	{
+		value: "gpt-5.5",
+		label: "GPT-5.5",
+		desc: "Most capable — best for complex rewrites and reasoning",
+	},
+	// ... rest of models
+];
+
+const CODEX_MODEL_IDS = CODEX_MODELS
+	.filter(m => m.value !== "custom")
+	.map(m => m.value);

 export class InlineAISettingsTab extends PluginSettingTab {
 	// ...
 	display(): void {
 		// ...
 		.onChange(async (value) => {
-			const CODEX_MODEL_IDS = [
-				"gpt-5.5",
-				"gpt-5.4-mini",
-				"gpt-5.3-codex-spark",
-				"gpt-5.2-codex",
-				"gpt-5.1-codex",
-				"gpt-5.1-codex-max",
-				"codex-mini-latest",
-			];
 			this.plugin.settings.provider = value as
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/settings.ts` around lines 76 - 100, The CODEX_MODEL_IDS array is
duplicated and can drift from CODEX_MODELS; refactor by moving CODEX_MODELS to
module-level or a class constant (e.g., export/const CODEX_MODELS) and replace
the local CODEX_MODEL_IDS usage with a derived ID list (e.g., CODEX_MODELS.map(m
=> m.id)) where the switch-to-codex logic lives (the block referencing
this.plugin.settings.provider and checking value === "codex" and
CODEX_MODEL_IDS.includes(this.plugin.settings.model)), so the model-reset logic
uses the single source of truth for model IDs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/api.ts`:
- Around line 331-342: Replace the fragile doc.indexOf-based search with the
actual editor selection range: use the provided selection range start/end (e.g.,
selectionRange.start and selectionRange.end or the editor's
selectionStart/selectionEnd variables) to compute selectionStart and
selectionEnd, then derive before = doc.slice(0, selectionStart) and after =
doc.slice(selectionEnd); keep the existing fallback to docBeforeCursor or
cursor-based slicing only if the explicit selection range is missing or invalid.
Ensure you update references that currently use selectionStart, selectionText
and cursor so they rely on the canonical selection indices.

---

Outside diff comments:
In `@src/settings.ts`:
- Around line 225-239: The dropdown currently clears this.plugin.settings.model
to "" whenever the user selects "custom", which loses any previously-entered
custom ID; modify the handler in the Setting.addDropdown callback (where
CODEX_MODELS are added and dd.setValue(...).onChange(...)) to preserve the last
custom value instead of unconditionally setting model = ""; implement either a
new field this.plugin.settings.lastCustomModel that you update when the user
edits a custom model and restore into this.plugin.settings.model when "custom"
is reselected, or only clear model the very first time switching to "custom"
(checking previous value) so subsequent toggles restore the stored custom value;
ensure you still call await this.saveSettings() and this.display() after
updating settings.

---

Duplicate comments:
In `@src/codex-client.ts`:
- Around line 35-36: The current mapping forcibly rewrites any model string
containing "codex" to "gpt-5.1-codex", which discards custom Codex model IDs;
update the logic in src/codex-client.ts where the variable `m` is checked so
that if `m` contains "codex" you return `m` unchanged (or only coerce when `m`
exactly equals a legacy alias), thereby preserving custom IDs like
"gpt-5.6-codex" instead of always returning "gpt-5.1-codex".

---

Nitpick comments:
In `@src/settings.ts`:
- Around line 76-100: The CODEX_MODEL_IDS array is duplicated and can drift from
CODEX_MODELS; refactor by moving CODEX_MODELS to module-level or a class
constant (e.g., export/const CODEX_MODELS) and replace the local CODEX_MODEL_IDS
usage with a derived ID list (e.g., CODEX_MODELS.map(m => m.id)) where the
switch-to-codex logic lives (the block referencing this.plugin.settings.provider
and checking value === "codex" and
CODEX_MODEL_IDS.includes(this.plugin.settings.model)), so the model-reset logic
uses the single source of truth for model IDs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0cb5ce40-1321-495f-927e-f103af4a9e6c

📥 Commits

Reviewing files that changed from the base of the PR and between 1024c37 and 05dc259.

📒 Files selected for processing (7)
  • src/api.ts
  • src/codex-auth.ts
  • src/codex-client.ts
  • src/main.ts
  • src/modules/commands/parser.ts
  • src/modules/commands/source.ts
  • src/settings.ts

Comment thread src/api.ts
Comment on lines +331 to +342
const selectionStart = doc.indexOf(
selectionText,
Math.max(0, cursor - selectionText.length - 200),
);
const before =
selectionStart > 0
? doc.slice(0, selectionStart)
: docBeforeCursor;
const after =
selectionStart >= 0
? doc.slice(selectionStart + selectionText.length)
: doc.slice(cursor);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use the actual editor selection range for context slicing.

Line 331 can resolve the wrong occurrence when selected text repeats, which may attach unrelated context to the model prompt.

💡 Proposed fix
-			const selectionStart = doc.indexOf(
-				selectionText,
-				Math.max(0, cursor - selectionText.length - 200),
-			);
-			const before =
-				selectionStart > 0
-					? doc.slice(0, selectionStart)
-					: docBeforeCursor;
-			const after =
-				selectionStart >= 0
-					? doc.slice(selectionStart + selectionText.length)
-					: doc.slice(cursor);
+			const sel = cm.state.selection.main;
+			const selectionStart = sel.from;
+			const selectionEnd = sel.to;
+			const before = doc.slice(0, selectionStart);
+			const after = doc.slice(selectionEnd);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/api.ts` around lines 331 - 342, Replace the fragile doc.indexOf-based
search with the actual editor selection range: use the provided selection range
start/end (e.g., selectionRange.start and selectionRange.end or the editor's
selectionStart/selectionEnd variables) to compute selectionStart and
selectionEnd, then derive before = doc.slice(0, selectionStart) and after =
doc.slice(selectionEnd); keep the existing fallback to docBeforeCursor or
cursor-based slicing only if the explicit selection range is missing or invalid.
Ensure you update references that currently use selectionStart, selectionText
and cursor so they rely on the canonical selection indices.

@FBarrca FBarrca merged commit 053119e into FBarrca:main May 23, 2026
2 checks passed
@FBarrca

FBarrca commented May 30, 2026

Copy link
Copy Markdown
Owner

Just added a new release with your changes! 1.2.7

It features your provider but I made some improvements;
Moved the storage to the Keychain as to make it more secure and less likely for users to leak.
Also made it so the onboarding also works on mobile by using the device code method.

Let me know what you think!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants