Skip to content

Commit bacc1e5

Browse files
committed
fix: prevent API key erasure on settings save and fix graph view unmount crash
1 parent 22316de commit bacc1e5

4 files changed

Lines changed: 72 additions & 16 deletions

File tree

AUDIT_LOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22

33
This log tracks all significant changes, updates, and versions in the PaperCache project.
44

5+
## 2026-06-27 (API Key Persistence & Graph View Fixes)
6+
**Change:** fix(ai): fix API key saving/clearing logic and macOS keychain credential updating; fix(graph): prevent `fg.graphData` crashes when opening or closing Graph View
7+
8+
**Details/Why:**
9+
1. **API Key Persistence**: When opening Settings, `apiKey` state initialized to empty string `''`. Clicking "Save Settings" after changing other preferences unintentionally took the `else` branch (`await window.electronAPI.setApiKey('')`), erasing existing keys from the OS keyring. Updated `saveSettings` to only save when `apiKey.trim()` is non-empty, and only clear when `!isApiKeySet`. Added an explicit "Clear Key" UI button next to the password input field when an API key is set.
10+
2. **Keyring Credential Updating**: In `src-tauri/src/commands/keychain.rs`, calling `set_password` on an existing keychain entry could fail on macOS. Updated `set_api_key` to delete any existing credential before setting the new password.
11+
3. **Graph View Crash Fixes**: Merged comprehensive defensive checks (`typeof fg.method === 'function'`) and ref caching into `GraphView.tsx` to prevent `fg.graphData is not a function` crashes when unmounting or toggling Graph View via `Cmd+G`.
12+
13+
**Files changed:** `src/Settings.tsx`, `src-tauri/src/commands/keychain.rs`, `src/GraphView.tsx`, `CHANGELOG.md`, `AUDIT_LOG.md`.
14+
15+
---
16+
517
## 2026-06-27 (Graph View Bugfix)
618
**Change:** fix(graph): prevent `e.graphData is not a function` crash on unmount and replace setInterval
719

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1212
- **Settings Bug Report & About Menu**: Added a "Submit a Bug Report" button under System settings linking directly to the GitHub issue creation form. Added a dedicated "About" section displaying the app logo, current version number, update checker, Ko-fi support link, and a thank you message.
1313

1414
### Fixed
15-
- **Graph View crash on navigation**: Fixed `e.graphData is not a function` TypeError when navigating to a note from the Graph View by adding defensive checks before invoking ref methods on component unmount and falling back to a ref cache. Also replaced `setInterval` with a chained `setTimeout` loop.
15+
- **API Key Persistence & Clearing**: Fixed an issue where clicking "Save Settings" without re-entering an API key unintentionally cleared existing keys from the OS keyring. Added an explicit "Clear Key" button and defensive trimming before saving credentials securely. Also improved macOS keyring replacement logic to prevent duplicate item errors.
16+
- **Graph View crash on navigation & toggle**: Fixed `fg.graphData is not a function` TypeError when navigating to notes or toggling Graph View (`Cmd+G`) by adding defensive checks before invoking ref methods on component unmount and falling back to a ref cache. Also replaced `setInterval` with a chained `setTimeout` loop.
1617
- **Windows Onboarding File Linking & Generation**: Fixed a bug on Windows where backslashes in generated note IDs caused internal `/file` links in `Welcome.md` to fail and create duplicate empty notes. Normalized note ID generation across Rust and TypeScript to consistently use forward slashes on all platforms, and ensured onboarding template files regenerate correctly on application updates.
1718
- **Window position/size now persists across restarts**: The window-state plugin's `on_window_ready` fires before the macOS display server is ready, causing `available_monitors()` to return empty and the saved position to be silently discarded. Fixed by deferring window-state restoration via a background thread + `run_on_main_thread` 300ms after `setup()` completes, bypassing the plugin's monitor-intersection check with a direct file read. Both the tray "Quit" and Settings "Quit" buttons now explicitly save window state before exit.
1819
- **Launch at Startup now registers as a proper Login Item**: Changed `MacosLauncher` from `LaunchAgent` to `AppleScript`, which registers PaperCache in System Settings > General > Login Items instead of creating a hidden `launchd` plist. Users can now see and manage the autostart entry directly from System Settings.

src-tauri/src/commands/keychain.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@ const SERVICE_NAME: &str = "com.variablethe.papercache";
1212
pub fn set_api_key(key: String) -> Result<bool, String> {
1313
let entry = Entry::new(SERVICE_NAME, "openai_api_key")
1414
.map_err(|e| format!("Failed to access keyring: {}", e))?;
15-
if key.is_empty() {
16-
entry.delete_credential().ok();
15+
let trimmed = key.trim();
16+
if trimmed.is_empty() {
17+
let _ = entry.delete_credential();
1718
return Ok(true);
1819
}
20+
let _ = entry.delete_credential();
1921
entry
20-
.set_password(&key)
22+
.set_password(trimmed)
2123
.map_err(|e| format!("Failed to set API key: {}", e))?;
2224
Ok(true)
2325
}

src/Settings.tsx

Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -88,13 +88,26 @@ export default function Settings({ onClose }: { onClose?: () => void }) {
8888
localStorage.setItem(SETTINGS_KEYS.API_MODEL, apiModel)
8989
localStorage.setItem(SETTINGS_KEYS.AI_SYSTEM_PROMPT, aiSystemPrompt)
9090

91-
if (apiKey) {
92-
const success = await window.electronAPI.setApiKey(apiKey)
93-
if (!success) {
94-
alert('Failed to save API key securely. Check console.')
91+
if (apiKey.trim()) {
92+
try {
93+
const success = await window.electronAPI.setApiKey(apiKey.trim())
94+
if (success) {
95+
setIsApiKeySet(true)
96+
} else {
97+
alert('Failed to save API key securely. Check console.')
98+
}
99+
} catch (err) {
100+
// eslint-disable-next-line no-console
101+
console.error('Failed to save API key:', err)
102+
alert(`Failed to save API key securely: ${err}`)
103+
}
104+
} else if (!isApiKeySet) {
105+
try {
106+
await window.electronAPI.setApiKey('') // clear key
107+
} catch (err) {
108+
// eslint-disable-next-line no-console
109+
console.error('Failed to clear API key:', err)
95110
}
96-
} else {
97-
await window.electronAPI.setApiKey('') // clear key
98111
}
99112

100113
useSettingsStore.getState().setSettings({
@@ -167,12 +180,40 @@ export default function Settings({ onClose }: { onClose?: () => void }) {
167180
<h3>AI Configuration</h3>
168181
<div className="setting-group">
169182
<label>API Key {isApiKeySet ? '✅ (Set)' : ''}</label>
170-
<input
171-
type="password"
172-
value={apiKey}
173-
onChange={(e) => setApiKey(e.target.value)}
174-
placeholder={isApiKeySet ? 'Enter new key to replace existing' : 'sk-...'}
175-
/>
183+
<div style={{ display: 'flex', gap: '8px' }}>
184+
<input
185+
type="password"
186+
value={apiKey}
187+
onChange={(e) => setApiKey(e.target.value)}
188+
placeholder={isApiKeySet ? 'Enter new key to replace existing' : 'sk-...'}
189+
style={{ flex: 1 }}
190+
/>
191+
{isApiKeySet && (
192+
<button
193+
type="button"
194+
onClick={async () => {
195+
try {
196+
await window.electronAPI.setApiKey('')
197+
setIsApiKeySet(false)
198+
setApiKey('')
199+
} catch (err) {
200+
// eslint-disable-next-line no-console
201+
console.error('Failed to clear key:', err)
202+
}
203+
}}
204+
style={{
205+
padding: '6px 12px',
206+
borderRadius: '4px',
207+
background: 'var(--bg-secondary)',
208+
color: 'var(--text-primary)',
209+
border: '1px solid var(--border-color)',
210+
cursor: 'pointer',
211+
}}
212+
>
213+
Clear Key
214+
</button>
215+
)}
216+
</div>
176217
</div>
177218

178219
<div className="setting-group">

0 commit comments

Comments
 (0)