Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): native spellcheck context menu in OK Desktop (#1846)
sarah7ad56cae6443
diff --git a/.changeset/spellcheck-context-menu.md b/.changeset/spellcheck-context-menu.mdnew file mode 100644index 000000000..e8a2dc400--- /dev/null+++ b/.changeset/spellcheck-context-menu.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Add a native right-click context menu in the OK Desktop editor (macOS). Right-clicking editable text now opens a native menu with Cut/Copy/Paste/Select All, and right-clicking a misspelled word adds spelling suggestions, "Add to Dictionary" (written to the macOS system dictionary), "Disable Spell Check", "Look Up", and "Search with Google" — matching the affordance every other Mac app offers. Spell check can be turned back on right from the editor ("Enable Spell Check" on any editable right-click) or from the new Edit ▸ "Check Spelling While Typing" menu item, and the on/off choice persists across relaunches. Previously, right-clicking a misspelled word did nothing.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex a8286f184..35ec62fdf 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -23,6 +23,22 @@ Open any doc from the sidebar. The body renders as WYSIWYG markdown with familiaA backslash command (`/`) opens an insert menu for headings, lists, code blocks, callouts, and the other content shapes the editor supports.+## Right-click menu and spell check++In the desktop app, right-clicking editable text opens a native context menu. Any editable field gets **Cut / Copy / Paste / Select All**; when there's a selection or a flagged word under the cursor, **Look Up** (the macOS dictionary panel) and **Search with Google** join it.++Spell checking uses the native macOS spellchecker (language follows your macOS settings), so misspelled words get the familiar red underline. Right-clicking a flagged word adds the spelling section:++| Item | Behavior |+| --- | --- |+| *Suggestions* | The spellchecker's corrections, one row each; pick one to replace the word. |+| **Add to Dictionary** | Teaches the macOS system dictionary the word — persistent, and shared with your other Mac apps (Safari, Notes). |+| **Disable Spell Check** | Turns spell checking off app-wide. The choice persists across relaunches. |++While spell check is off, right-clicking any editable text offers **Enable Spell Check**, and the menu bar carries the same toggle as **Edit ▸ Check Spelling While Typing** (see [Edit menu](#edit-menu)) — flip either to bring the squiggles back.++Surfaces with their own specialized right-click menus — asset and wiki-link chips, the [file sidebar](#right-click-context-menus), editor tabs — keep them; the editor menu never doubles up on top. In the web build the browser's own context menu fills this role.+## Edit with AISelect text in the WYSIWYG editor to hand that exact passage to an installed agent. The selection bubble menu shows an **Edit with AI** button alongside the formatting controls. Clicking it opens a popover with an instruction field and your installed-agent list (Claude, Codex, or Cursor). Type what you want done (the instruction is optional), pick an agent, and it opens with the project as its working directory and a prompt naming the doc, your instruction, and the selected passage.@@ -163,6 +179,14 @@ Below the project navigation items (Switch Project, Open Folder, Open Recent, CL**Switch Project…** moved to `Cmd+Shift+P`. The old `Cmd+Shift+N` binding now creates a new folder, matching macOS Finder, VS Code, and the broader convention.+### Edit menu++Alongside the standard Undo / Redo / Cut / Copy / Paste / Select All items:++| Item | Accelerator | Behavior |+| --- | --- | --- |+| **Check Spelling While Typing** | (none) | Checkbox reflecting whether spell check is on. Toggling applies app-wide and persists across relaunches — it's the same switch the editor right-click menu's Disable / Enable Spell Check rows flip (see [Right-click menu and spell check](#right-click-menu-and-spell-check)). |+### View menuBefore the existing Zoom and Toggle Fullscreen items, the View menu gets:diff --git a/packages/desktop/src/main/asset-menu.ts b/packages/desktop/src/main/asset-menu.tsindex d233004d2..5eb010ad6 100644--- a/packages/desktop/src/main/asset-menu.ts+++ b/packages/desktop/src/main/asset-menu.ts@@ -53,6 +53,7 @@ interface PopAssetMenuDeps {}export function popAssetMenu(deps: PopAssetMenuDeps, params: BuildAssetMenuTemplateParams): void {+ if (deps.window.isDestroyed()) return;const template = buildAssetMenuTemplate(params);deps.Menu.buildFromTemplate(template).popup({ window: deps.window });}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex a71400fb8..763d151d6 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -190,6 +190,8 @@ import { startFirstRunHandshake } from './share-handoff.ts';import { handleShellOpenExternal } from './shell-allowlist.ts';import { createShowGateRegistry, type ShowGateRegistry } from './show-gate.ts';import { reclaimProjectSkillsOnProjectOpen, reclaimUserSkillsOnLaunch } from './skill-reclaim.ts';+import { attachSpellcheckContextMenu } from './spellcheck-context-menu.ts';+import { popSpellcheckMenu } from './spellcheck-menu.ts';import {type AppState,addRecentProject,@@ -204,6 +206,7 @@ import {saveAppStateToDir,setLastUsedProjectParent,setProjectSessionState,+ setSpellCheckEnabled as setSpellCheckEnabledState,} from './state-store.ts';import { applyThemeApplied } from './theme-applied-handler.ts';import { applyThemeSource, isOkThemeSource } from './theme-handler.ts';@@ -357,6 +360,38 @@ export function getPendingSchemaIncompatibility(): SchemaIncompatibilityDiagnostexport function clearPendingSchemaIncompatibility(): void {pendingSchemaIncompatibility = null;}++function setSpellCheckEnabledAppWide(enabled: boolean): void {+ session.defaultSession.setSpellCheckerEnabled(enabled);+ appState = setSpellCheckEnabledState(appState, enabled);+ saveAppState(appState);+ refreshApplicationMenu();+}++function attachSpellcheckMenuToWindow(win: BrowserWindow): void {+ session.defaultSession.setSpellCheckerEnabled(appState.spellCheckEnabled);+ const openExternalSafely = handleShellOpenExternal({+ openExternal: (url) => shell.openExternal(url),+ });+ attachSpellcheckContextMenu(win.webContents, {+ isSpellCheckEnabled: () => appState.spellCheckEnabled,+ setSpellCheckEnabled: setSpellCheckEnabledAppWide,+ addToDictionary: (word) => {+ session.defaultSession.addWordToSpellCheckerDictionary(word);+ },+ openExternal: (url) => {+ void openExternalSafely(url).catch((err: unknown) => {+ getLogger('spellcheck-menu').warn(+ { err: err instanceof Error ? err.message : String(err), url },+ 'context-menu search openExternal failed',+ );+ });+ },+ popMenu: (input) => {+ popSpellcheckMenu({ Menu, window: win }, input);+ },+ });+}let navigatorWindow: BrowserWindowLike | null = null;let wm: WindowManager;const showGate: ShowGateRegistry = createShowGateRegistry({@@ -475,6 +510,7 @@ function ensureWindowManager() {e.preventDefault();});applyCascadePosition(win);+ attachSpellcheckMenuToWindow(win);return win as unknown as BrowserWindowLike;},forkUtility: (entry, args, opts) => {@@ -664,6 +700,7 @@ function openNavigator(pendingPayload?: ShareNavigatorPayload) {win.on('closed', () => {navigatorWindow = null;});+ attachSpellcheckMenuToWindow(win);return win as unknown as BrowserWindowLike;},rendererEntryPath: app.isPackaged@@ -1213,6 +1250,8 @@ async function runApplicationMenuRefresh(): Promise<void> {onToggleDocPanel: () => sendMenuActionToFocused('toggle-doc-panel'),onExpandAll: () => sendMenuActionToFocused('expand-all-tree'),onCollapseAll: () => sendMenuActionToFocused('collapse-all-tree'),+ spellCheckEnabled: appState.spellCheckEnabled,+ onToggleSpellCheck: () => setSpellCheckEnabledAppWide(!appState.spellCheckEnabled),});}diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.tsindex 93bff48fc..c01577091 100644--- a/packages/desktop/src/main/menu.ts+++ b/packages/desktop/src/main/menu.ts@@ -47,6 +47,8 @@ export interface MenuDeps {canCollapseAll?: boolean;onExpandAll?(): void;onCollapseAll?(): void;+ spellCheckEnabled?: boolean;+ onToggleSpellCheck?(): void;}export async function installApplicationMenu(deps: MenuDeps): Promise<void> {@@ -260,6 +262,14 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]{ role: 'copy' },{ role: 'paste' },{ role: 'selectAll' },+ { type: 'separator' },+ {+ label: 'Check Spelling While Typing',+ type: 'checkbox',+ checked: deps.spellCheckEnabled ?? true,+ enabled: deps.onToggleSpellCheck !== undefined,+ click: () => deps.onToggleSpellCheck?.(),+ },],},diff --git a/packages/desktop/src/main/spellcheck-context-menu.ts b/packages/desktop/src/main/spellcheck-context-menu.tsnew file mode 100644index 000000000..eba3a959b--- /dev/null+++ b/packages/desktop/src/main/spellcheck-context-menu.ts@@ -0,0 +1,61 @@+import type {+ BuildSpellcheckMenuTemplateParams,+ SpellcheckMenuActions,+ SpellcheckMenuParams,+} from './spellcheck-menu.ts';++export interface ContextMenuHandlerParams extends SpellcheckMenuParams {+ readonly isEditable: boolean;+}++export interface SpellcheckWebContents {+ on(+ event: 'context-menu',+ listener: (event: unknown, params: ContextMenuHandlerParams) => void,+ ): void;+ replaceMisspelling(text: string): void;+ showDefinitionForSelection(): void;+}++export interface SpellcheckContextMenuDeps {+ readonly isSpellCheckEnabled: () => boolean;+ readonly setSpellCheckEnabled: (enabled: boolean) => void;+ readonly addToDictionary: (word: string) => void;+ readonly openExternal: (url: string) => void;+ readonly popMenu: (input: BuildSpellcheckMenuTemplateParams) => void;+}++function googleSearchUrl(query: string): string {+ return `https://www.google.com/search?q=${encodeURIComponent(query)}`;+}++export function attachSpellcheckContextMenu(+ webContents: SpellcheckWebContents,+ deps: SpellcheckContextMenuDeps,+): void {+ webContents.on('context-menu', (_event, params) => {+ if (!params.isEditable) return;+ const actions: SpellcheckMenuActions = {+ replaceMisspelling: (suggestion) => {+ webContents.replaceMisspelling(suggestion);+ },+ addToDictionary: (word) => {+ deps.addToDictionary(word);+ },+ setSpellCheckEnabled: (enabled) => {+ deps.setSpellCheckEnabled(enabled);+ },+ lookUp: () => {+ webContents.showDefinitionForSelection();+ },+ search: (query) => {+ deps.openExternal(googleSearchUrl(query));+ },+ };+ deps.popMenu({+ params,+ spellCheckEnabled: deps.isSpellCheckEnabled(),+ actions,+ });+ });+}diff --git a/packages/desktop/src/main/spellcheck-menu.ts b/packages/desktop/src/main/spellcheck-menu.tsnew file mode 100644index 000000000..dd9fe08a3--- /dev/null+++ b/packages/desktop/src/main/spellcheck-menu.ts@@ -0,0 +1,111 @@+import type { BrowserWindow, EditFlags, Menu, MenuItemConstructorOptions } from 'electron';++export interface SpellcheckMenuParams {+ readonly misspelledWord: string;+ readonly dictionarySuggestions: readonly string[];+ readonly selectionText: string;+ readonly editFlags: Readonly<Pick<EditFlags, 'canCut' | 'canCopy' | 'canPaste' | 'canSelectAll'>>;+}++export interface SpellcheckMenuActions {+ readonly replaceMisspelling: (suggestion: string) => void;+ readonly addToDictionary: (word: string) => void;+ readonly setSpellCheckEnabled: (enabled: boolean) => void;+ readonly lookUp: () => void;+ readonly search: (query: string) => void;+}++export interface BuildSpellcheckMenuTemplateParams {+ readonly params: SpellcheckMenuParams;+ readonly spellCheckEnabled: boolean;+ readonly actions: SpellcheckMenuActions;+}++const LOOKUP_LABEL_MAX = 50;+const SEARCH_QUERY_MAX = 200;++export function buildSpellcheckMenuTemplate(+ input: BuildSpellcheckMenuTemplateParams,+): MenuItemConstructorOptions[] {+ const { params, spellCheckEnabled, actions } = input;+ const { misspelledWord, dictionarySuggestions, selectionText, editFlags } = params;++ const editSection: MenuItemConstructorOptions[] = [];+ if (editFlags.canCut) editSection.push({ role: 'cut' });+ if (editFlags.canCopy) editSection.push({ role: 'copy' });+ if (editFlags.canPaste) editSection.push({ role: 'paste' });+ if (editFlags.canSelectAll) editSection.push({ role: 'selectAll' });++ const spellSection: MenuItemConstructorOptions[] = [];+ if (misspelledWord && spellCheckEnabled) {+ for (const suggestion of dictionarySuggestions) {+ spellSection.push({+ label: suggestion,+ click: () => {+ actions.replaceMisspelling(suggestion);+ },+ });+ }+ spellSection.push({+ label: 'Add to Dictionary',+ click: () => {+ actions.addToDictionary(misspelledWord);+ },+ });+ spellSection.push({+ label: 'Disable Spell Check',+ click: () => {+ actions.setSpellCheckEnabled(false);+ },+ });+ } else if (!spellCheckEnabled) {+ spellSection.push({+ label: 'Enable Spell Check',+ click: () => {+ actions.setSpellCheckEnabled(true);+ },+ });+ }++ const word = selectionText || misspelledWord;+ const lookupSection: MenuItemConstructorOptions[] = [];+ if (word) {+ const labelWord =+ word.length > LOOKUP_LABEL_MAX ? `${word.slice(0, LOOKUP_LABEL_MAX).toWellFormed()}…` : word;+ const query = word.slice(0, SEARCH_QUERY_MAX).toWellFormed();+ lookupSection.push({+ label: `Look Up "${labelWord}"`,+ click: () => {+ actions.lookUp();+ },+ });+ lookupSection.push({+ label: 'Search with Google',+ click: () => {+ actions.search(query);+ },+ });+ }++ const template: MenuItemConstructorOptions[] = [];+ for (const section of [editSection, spellSection, lookupSection]) {+ if (section.length === 0) continue;+ if (template.length > 0) template.push({ type: 'separator' });+ template.push(...section);+ }+ return template;+}++interface PopSpellcheckMenuDeps {+ readonly Menu: Pick<typeof Menu, 'buildFromTemplate'>;+ readonly window: BrowserWindow;+}++export function popSpellcheckMenu(+ deps: PopSpellcheckMenuDeps,+ params: BuildSpellcheckMenuTemplateParams,+): void {+ if (deps.window.isDestroyed()) return;+ const template = buildSpellcheckMenuTemplate(params);+ deps.Menu.buildFromTemplate(template).popup({ window: deps.window });+}diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.tsindex 1d516d3cb..b28d6987a 100644--- a/packages/desktop/src/main/state-store.ts+++ b/packages/desktop/src/main/state-store.ts@@ -35,6 +35,7 @@ export interface AppState {schemaVersion: number;lastUsedProjectParent: string | null;pendingWindowRestore: string[] | null;+ spellCheckEnabled: boolean;}const RECENT_CAP = 20;@@ -52,6 +53,7 @@ export function emptyState(): AppState {schemaVersion: CURRENT_SCHEMA_VERSION,lastUsedProjectParent: null,pendingWindowRestore: null,+ spellCheckEnabled: true,};}@@ -59,6 +61,10 @@ export function setLastUsedProjectParent(state: AppState, parent: string): AppStreturn { ...state, lastUsedProjectParent: parent };}+export function setSpellCheckEnabled(state: AppState, enabled: boolean): AppState {+ return { ...state, spellCheckEnabled: enabled };+}+function emptyProjectSessionState(): ProjectSessionState {return {openTabs: [],@@ -303,6 +309,8 @@ export function parseAppState(raw: unknown): AppState | null {const pendingWindowRestore = Array.isArray(obj.pendingWindowRestore)? sanitizeStringArray(obj.pendingWindowRestore): null;+ const spellCheckEnabled =+ typeof obj.spellCheckEnabled === 'boolean' ? obj.spellCheckEnabled : true;return {recentProjects,lastOpenedProject,@@ -315,5 +323,6 @@ export function parseAppState(raw: unknown): AppState | null {schemaVersion,lastUsedProjectParent,pendingWindowRestore,+ spellCheckEnabled,};}diff --git a/packages/desktop/tests/main/asset-menu.test.ts b/packages/desktop/tests/main/asset-menu.test.tsindex 8690db581..5c1a4ab4d 100644--- a/packages/desktop/tests/main/asset-menu.test.ts+++ b/packages/desktop/tests/main/asset-menu.test.ts@@ -101,7 +101,7 @@ describe('popAssetMenu', () => {const popup = mock((_: unknown) => {});const menuInstance = { popup } as unknown as ReturnType<typeof Menu.buildFromTemplate>;const buildFromTemplate = mock((_: MenuItemConstructorOptions[]) => menuInstance);- const fakeWindow = { id: 42 } as unknown as BrowserWindow;+ const fakeWindow = { id: 42, isDestroyed: () => false } as unknown as BrowserWindow;popAssetMenu({@@ -122,4 +122,30 @@ describe('popAssetMenu', () => {expect(buildFromTemplate).toHaveBeenCalledTimes(1);expect(popup).toHaveBeenCalledWith({ window: fakeWindow });});++ test('destroyed window → no build, no popup (right-click racing window close)', () => {+ const popup = mock((_: unknown) => {});+ const menuInstance = { popup } as unknown as ReturnType<typeof Menu.buildFromTemplate>;+ const buildFromTemplate = mock((_: MenuItemConstructorOptions[]) => menuInstance);+ const fakeWindow = { id: 42, isDestroyed: () => true } as unknown as BrowserWindow;++ popAssetMenu(+ {+ Menu: { buildFromTemplate },+ window: fakeWindow,+ },+ {+ kind: 'asset',+ platform: 'darwin',+ actions: {+ reveal: () => {},+ openInDefault: () => {},+ copyLink: () => {},+ },+ },+ );++ expect(buildFromTemplate).not.toHaveBeenCalled();+ expect(popup).not.toHaveBeenCalled();+ });});diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.tsindex 53b0c5c16..45379c4f7 100644--- a/packages/desktop/tests/main/menu.test.ts+++ b/packages/desktop/tests/main/menu.test.ts@@ -823,3 +823,74 @@ describe('buildMenuTemplate — View → Show/Hide Sidebar', () => {expect(onToggleDocPanel2).toHaveBeenCalledTimes(1);});});++describe('buildMenuTemplate — Edit → Check Spelling While Typing', () => {+ function editSubmenu(deps: MenuDeps): MenuItemConstructorOptions[] {+ const edit = findByLabel(buildMenuTemplate(deps), 'Edit');+ const sub = edit?.submenu as MenuItemConstructorOptions[] | undefined;+ if (!sub) throw new Error('Edit submenu missing');+ return sub;+ }++ test('renders as a checkbox-type item, checked when spellCheckEnabled is true', () => {+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ spellCheckEnabled: true, onToggleSpellCheck: mock(() => {}) })),+ 'Check Spelling While Typing',+ );+ expect(item).toBeDefined();+ expect(item?.type).toBe('checkbox');+ expect(item?.checked).toBe(true);+ });++ test('renders unchecked when spellCheckEnabled is false', () => {+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ spellCheckEnabled: false, onToggleSpellCheck: mock(() => {}) })),+ 'Check Spelling While Typing',+ );+ expect(item?.checked).toBe(false);+ });++ test('defaults to checked when spellCheckEnabled dep is omitted (matches the on-by-default persistence default)', () => {+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ onToggleSpellCheck: mock(() => {}) })),+ 'Check Spelling While Typing',+ );+ expect(item?.checked).toBe(true);+ });++ test('ENABLED when onToggleSpellCheck handler is provided', () => {+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ onToggleSpellCheck: mock(() => {}) })),+ 'Check Spelling While Typing',+ );+ expect(item?.enabled).toBe(true);+ });++ test('DISABLED when onToggleSpellCheck handler is missing (unit-test default = unwired)', () => {+ const item = findByLabel(buildMenuTemplate(makeDeps()), 'Check Spelling While Typing');+ expect(item?.enabled).toBe(false);+ });++ test('click dispatches deps.onToggleSpellCheck', () => {+ const onToggleSpellCheck = mock(() => {});+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ onToggleSpellCheck })),+ 'Check Spelling While Typing',+ );+ (item?.click as (() => void) | undefined)?.();+ expect(onToggleSpellCheck).toHaveBeenCalledTimes(1);+ });++ test('click is a safe no-op when onToggleSpellCheck dep is omitted', () => {+ const item = findByLabel(buildMenuTemplate(makeDeps()), 'Check Spelling While Typing');+ expect(() => (item?.click as (() => void) | undefined)?.()).not.toThrow();+ });++ test('lives in the Edit submenu after the Select All role', () => {+ const sub = editSubmenu(makeDeps({ onToggleSpellCheck: mock(() => {}) }));+ const selectAllIdx = sub.findIndex((i) => i.role === 'selectAll');+ const spellIdx = sub.findIndex((i) => i.label === 'Check Spelling While Typing');+ expect(selectAllIdx).toBeGreaterThanOrEqual(0);+ expect(spellIdx).toBeGreaterThan(selectAllIdx);+ });+});diff --git a/packages/desktop/tests/main/spellcheck-context-menu.test.ts b/packages/desktop/tests/main/spellcheck-context-menu.test.tsnew file mode 100644index 000000000..f2b53aa88--- /dev/null+++ b/packages/desktop/tests/main/spellcheck-context-menu.test.ts@@ -0,0 +1,160 @@+import { describe, expect, mock, test } from 'bun:test';+import {+ attachSpellcheckContextMenu,+ type ContextMenuHandlerParams,+} from '../../src/main/spellcheck-context-menu.ts';+import type { BuildSpellcheckMenuTemplateParams } from '../../src/main/spellcheck-menu.ts';++const allEditFlags = {+ canCut: true,+ canCopy: true,+ canPaste: true,+ canSelectAll: true,+} as const;++function makeParams(overrides: Partial<ContextMenuHandlerParams> = {}): ContextMenuHandlerParams {+ return {+ isEditable: true,+ misspelledWord: '',+ dictionarySuggestions: [],+ selectionText: '',+ editFlags: allEditFlags,+ ...overrides,+ };+}++function makeWebContents() {+ let handler: ((event: unknown, params: ContextMenuHandlerParams) => void) | undefined;+ return {+ on: mock(+ (+ _event: 'context-menu',+ listener: (event: unknown, params: ContextMenuHandlerParams) => void,+ ) => {+ handler = listener;+ },+ ),+ replaceMisspelling: mock((_: string) => {}),+ showDefinitionForSelection: mock(() => {}),+ fire(params: ContextMenuHandlerParams) {+ if (!handler) throw new Error('no context-menu handler registered');+ handler({}, params);+ },+ };+}++function makeDeps(isSpellCheckEnabled: () => boolean = () => true) {+ return {+ isSpellCheckEnabled,+ setSpellCheckEnabled: mock((_: boolean) => {}),+ addToDictionary: mock((_: string) => {}),+ openExternal: mock((_: string) => {}),+ popMenu: mock((_: BuildSpellcheckMenuTemplateParams) => {}),+ };+}++describe('attachSpellcheckContextMenu — isEditable gate', () => {+ test('non-editable target pops no menu', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ attachSpellcheckContextMenu(wc, deps);+ wc.fire(makeParams({ isEditable: false }));+ expect(deps.popMenu).not.toHaveBeenCalled();+ });++ test('editable target pops the menu once', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ attachSpellcheckContextMenu(wc, deps);+ wc.fire(makeParams({ isEditable: true }));+ expect(deps.popMenu).toHaveBeenCalledTimes(1);+ });+});++describe('attachSpellcheckContextMenu — spellCheckEnabled flag', () => {+ test('reads the flag fresh on each right-click', () => {+ const wc = makeWebContents();+ const values = [true, false];+ const deps = makeDeps(() => values.shift() ?? true);+ attachSpellcheckContextMenu(wc, deps);+ wc.fire(makeParams());+ wc.fire(makeParams());+ const firstInput = deps.popMenu.mock.calls[0]?.[0];+ const secondInput = deps.popMenu.mock.calls[1]?.[0];+ expect(firstInput?.spellCheckEnabled).toBe(true);+ expect(secondInput?.spellCheckEnabled).toBe(false);+ });+});++describe('attachSpellcheckContextMenu — params forwarding', () => {+ test('popMenu receives the fired params object', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ attachSpellcheckContextMenu(wc, deps);+ const fired = makeParams({ misspelledWord: 'teh', selectionText: 'teh fox' });+ wc.fire(fired);+ expect(deps.popMenu.mock.calls[0]?.[0]?.params).toBe(fired);+ });+});++describe('attachSpellcheckContextMenu — action wiring', () => {+ function fireAndGetActions(+ wc: ReturnType<typeof makeWebContents>,+ deps: ReturnType<typeof makeDeps>,+ params: ContextMenuHandlerParams,+ ): BuildSpellcheckMenuTemplateParams['actions'] {+ attachSpellcheckContextMenu(wc, deps);+ wc.fire(params);+ const input = deps.popMenu.mock.calls[0]?.[0];+ if (!input) throw new Error('popMenu was not called');+ return input.actions;+ }++ test('replaceMisspelling routes to webContents.replaceMisspelling', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams({ misspelledWord: 'teh' }));+ actions.replaceMisspelling('the');+ expect(wc.replaceMisspelling).toHaveBeenCalledWith('the');+ });++ test('addToDictionary routes to the injected capability', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams({ misspelledWord: 'teh' }));+ actions.addToDictionary('teh');+ expect(deps.addToDictionary).toHaveBeenCalledWith('teh');+ });++ test('setSpellCheckEnabled routes to the injected capability', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams({ misspelledWord: 'teh' }));+ actions.setSpellCheckEnabled(false);+ expect(deps.setSpellCheckEnabled).toHaveBeenCalledWith(false);+ });++ test('lookUp routes to webContents.showDefinitionForSelection', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams({ selectionText: 'flow' }));+ actions.lookUp();+ expect(wc.showDefinitionForSelection).toHaveBeenCalledTimes(1);+ });++ test('search opens a Google query URL for the word', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams({ selectionText: 'flow' }));+ actions.search('flow');+ expect(deps.openExternal).toHaveBeenCalledWith('https://www.google.com/search?q=flow');+ });++ test('search percent-encodes the query', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams({ selectionText: 'a b&c' }));+ actions.search('a b&c');+ expect(deps.openExternal).toHaveBeenCalledWith('https://www.google.com/search?q=a%20b%26c');+ });+});diff --git a/packages/desktop/tests/main/spellcheck-menu.test.ts b/packages/desktop/tests/main/spellcheck-menu.test.tsnew file mode 100644index 000000000..891570c60--- /dev/null+++ b/packages/desktop/tests/main/spellcheck-menu.test.ts@@ -0,0 +1,307 @@+import { describe, expect, mock, test } from 'bun:test';+import type { BrowserWindow, Menu, MenuItemConstructorOptions } from 'electron';+import {+ type BuildSpellcheckMenuTemplateParams,+ buildSpellcheckMenuTemplate,+ popSpellcheckMenu,+ type SpellcheckMenuParams,+} from '../../src/main/spellcheck-menu.ts';++function makeActions() {+ return {+ replaceMisspelling: mock((_: string) => {}),+ addToDictionary: mock((_: string) => {}),+ setSpellCheckEnabled: mock((_: boolean) => {}),+ lookUp: mock(() => {}),+ search: mock((_: string) => {}),+ };+}++const allEditFlags = {+ canCut: true,+ canCopy: true,+ canPaste: true,+ canSelectAll: true,+} as const;++function makeParams(overrides: Partial<SpellcheckMenuParams> = {}): SpellcheckMenuParams {+ return {+ misspelledWord: '',+ dictionarySuggestions: [],+ selectionText: '',+ editFlags: allEditFlags,+ ...overrides,+ };+}++function build(+ params: SpellcheckMenuParams,+ spellCheckEnabled: boolean,+ actions: BuildSpellcheckMenuTemplateParams['actions'],+): MenuItemConstructorOptions[] {+ return buildSpellcheckMenuTemplate({ params, spellCheckEnabled, actions });+}++function shapeOf(template: MenuItemConstructorOptions[]): string[] {+ return template.map((e) => e.role ?? e.label ?? `[${e.type}]`);+}++describe('buildSpellcheckMenuTemplate — section composition', () => {+ test('editable text with no misspelling and no selection → edit roles only', () => {+ const template = build(makeParams(), true, makeActions());+ expect(shapeOf(template)).toEqual(['cut', 'copy', 'paste', 'selectAll']);+ });++ test('edit roles respect editFlags', () => {+ const params = makeParams({+ editFlags: { canCut: false, canCopy: true, canPaste: true, canSelectAll: false },+ });+ const template = build(params, true, makeActions());+ expect(shapeOf(template)).toEqual(['copy', 'paste']);+ });++ test('flagged word with checking on → suggestions, Add to Dictionary, Disable, Look Up, Search', () => {+ const params = makeParams({+ misspelledWord: 'teh',+ dictionarySuggestions: ['the', 'tech'],+ });+ const template = build(params, true, makeActions());+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ 'the',+ 'tech',+ 'Add to Dictionary',+ 'Disable Spell Check',+ '[separator]',+ 'Look Up "teh"',+ 'Search with Google',+ ]);+ });++ test('flagged word with zero suggestions → Add to Dictionary + Disable, no suggestion rows', () => {+ const params = makeParams({ misspelledWord: 'zzx', dictionarySuggestions: [] });+ const template = build(params, true, makeActions());+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ 'Add to Dictionary',+ 'Disable Spell Check',+ '[separator]',+ 'Look Up "zzx"',+ 'Search with Google',+ ]);+ });++ test('checking off → Enable spell check replaces the disable block', () => {+ const template = build(makeParams(), false, makeActions());+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ 'Enable Spell Check',+ ]);+ });++ test('flagged word with checking off → Enable row only, no suggestion rows', () => {+ const params = makeParams({ misspelledWord: 'teh', dictionarySuggestions: ['the', 'tech'] });+ const template = build(params, false, makeActions());+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ 'Enable Spell Check',+ '[separator]',+ 'Look Up "teh"',+ 'Search with Google',+ ]);+ });++ test('selection without a misspelling → Look Up and Search rows', () => {+ const params = makeParams({ selectionText: 'hello world' });+ const template = build(params, true, makeActions());+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ 'Look Up "hello world"',+ 'Search with Google',+ ]);+ });++ test('no rows at all → empty template (no dangling separators)', () => {+ const params = makeParams({+ editFlags: { canCut: false, canCopy: false, canPaste: false, canSelectAll: false },+ });+ const template = build(params, true, makeActions());+ expect(template).toHaveLength(0);+ });++ test('leading section absent → no leading separator', () => {+ const params = makeParams({+ misspelledWord: 'teh',+ dictionarySuggestions: ['the'],+ editFlags: { canCut: false, canCopy: false, canPaste: false, canSelectAll: false },+ });+ const template = build(params, true, makeActions());+ expect(template[0]?.type).not.toBe('separator');+ expect(shapeOf(template)).toEqual([+ 'the',+ 'Add to Dictionary',+ 'Disable Spell Check',+ '[separator]',+ 'Look Up "teh"',+ 'Search with Google',+ ]);+ });+});++describe('buildSpellcheckMenuTemplate — callback dispatch', () => {+ function clickRow(template: MenuItemConstructorOptions[], label: string) {+ const row = template.find((e) => e.label === label);+ if (!row?.click) throw new Error(`no clickable row labelled ${label}`);+ // biome-ignore lint/suspicious/noExplicitAny: test invokes the click callback+ (row.click as any)();+ }++ test('clicking a suggestion replaces with that exact suggestion', () => {+ const actions = makeActions();+ const params = makeParams({ misspelledWord: 'teh', dictionarySuggestions: ['the', 'tech'] });+ const template = build(params, true, actions);+ clickRow(template, 'tech');+ expect(actions.replaceMisspelling).toHaveBeenCalledTimes(1);+ expect(actions.replaceMisspelling).toHaveBeenCalledWith('tech');+ });++ test('Add to Dictionary adds the flagged word', () => {+ const actions = makeActions();+ const params = makeParams({ misspelledWord: 'teh', dictionarySuggestions: ['the'] });+ const template = build(params, true, actions);+ clickRow(template, 'Add to Dictionary');+ expect(actions.addToDictionary).toHaveBeenCalledWith('teh');+ });++ test('Disable spell check disables checking', () => {+ const actions = makeActions();+ const params = makeParams({ misspelledWord: 'teh', dictionarySuggestions: ['the'] });+ const template = build(params, true, actions);+ clickRow(template, 'Disable Spell Check');+ expect(actions.setSpellCheckEnabled).toHaveBeenCalledWith(false);+ });++ test('Enable spell check enables checking', () => {+ const actions = makeActions();+ const template = build(makeParams(), false, actions);+ clickRow(template, 'Enable Spell Check');+ expect(actions.setSpellCheckEnabled).toHaveBeenCalledWith(true);+ });++ test('Look Up fires lookUp; Search fires search with the word', () => {+ const actions = makeActions();+ const params = makeParams({ selectionText: 'flow' });+ const template = build(params, true, actions);+ clickRow(template, 'Look Up "flow"');+ clickRow(template, 'Search with Google');+ expect(actions.lookUp).toHaveBeenCalledTimes(1);+ expect(actions.search).toHaveBeenCalledWith('flow');+ });++ test('Search falls back to the flagged word when there is no selection', () => {+ const actions = makeActions();+ const params = makeParams({ misspelledWord: 'teh', dictionarySuggestions: ['the'] });+ const template = build(params, true, actions);+ clickRow(template, 'Search with Google');+ expect(actions.search).toHaveBeenCalledWith('teh');+ });++ test('selection takes precedence over the flagged word for Look Up and Search', () => {+ const actions = makeActions();+ const params = makeParams({+ misspelledWord: 'teh',+ dictionarySuggestions: ['the'],+ selectionText: 'teh quick fox',+ });+ const template = build(params, true, actions);+ expect(shapeOf(template)).toContain('Look Up "teh quick fox"');+ clickRow(template, 'Search with Google');+ expect(actions.search).toHaveBeenCalledWith('teh quick fox');+ });++ test('long selections are truncated in the Look Up label and capped in the search query', () => {+ const actions = makeActions();+ const template = build(makeParams({ selectionText: 'x'.repeat(500) }), true, actions);+ const lookUpRow = template.find((e) => e.label?.startsWith('Look Up'));+ expect(lookUpRow?.label).toBe(`Look Up "${'x'.repeat(50)}…"`);+ clickRow(template, 'Search with Google');+ expect(actions.search).toHaveBeenCalledWith('x'.repeat(200));+ });++ test('query truncation never splits a surrogate pair (encodeURIComponent-safe)', () => {+ const actions = makeActions();+ const template = build(makeParams({ selectionText: `${'x'.repeat(199)}😀` }), true, actions);+ clickRow(template, 'Search with Google');+ const query = actions.search.mock.calls[0]?.[0] ?? '';+ expect(() => encodeURIComponent(query)).not.toThrow();+ expect(query).toBe(`${'x'.repeat(199)}�`);+ });++ test('label truncation never splits a surrogate pair', () => {+ const actions = makeActions();+ const template = build(+ makeParams({ selectionText: `${'y'.repeat(49)}😀${'z'.repeat(10)}` }),+ true,+ actions,+ );+ const lookUpRow = template.find((e) => e.label?.startsWith('Look Up'));+ expect(lookUpRow?.label).toBe(`Look Up "${'y'.repeat(49)}�…"`);+ });+});++describe('popSpellcheckMenu', () => {+ function makeMenuFakes() {+ const popup = mock((_: unknown) => {});+ const menuInstance = { popup } as unknown as ReturnType<typeof Menu.buildFromTemplate>;+ const buildFromTemplate = mock((_: MenuItemConstructorOptions[]) => menuInstance);+ return { popup, buildFromTemplate };+ }++ test('builds the template from the given params + pops via injected Menu ctor', () => {+ const { popup, buildFromTemplate } = makeMenuFakes();+ const fakeWindow = { id: 7, isDestroyed: () => false } as unknown as BrowserWindow;++ popSpellcheckMenu(+ { Menu: { buildFromTemplate }, window: fakeWindow },+ { params: makeParams(), spellCheckEnabled: true, actions: makeActions() },+ );++ expect(buildFromTemplate).toHaveBeenCalledTimes(1);+ const built = buildFromTemplate.mock.calls[0]?.[0];+ expect(shapeOf(built ?? [])).toEqual(['cut', 'copy', 'paste', 'selectAll']);+ expect(popup).toHaveBeenCalledWith({ window: fakeWindow });+ });++ test('destroyed window → no build, no popup (right-click racing window close)', () => {+ const { popup, buildFromTemplate } = makeMenuFakes();+ const fakeWindow = { id: 7, isDestroyed: () => true } as unknown as BrowserWindow;++ popSpellcheckMenu(+ { Menu: { buildFromTemplate }, window: fakeWindow },+ { params: makeParams(), spellCheckEnabled: true, actions: makeActions() },+ );++ expect(buildFromTemplate).not.toHaveBeenCalled();+ expect(popup).not.toHaveBeenCalled();+ });+});diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.tsindex e33fe80f2..36716d078 100644--- a/packages/desktop/tests/main/state-store.test.ts+++ b/packages/desktop/tests/main/state-store.test.ts@@ -13,6 +13,7 @@ import {saveAppStateToDir,setLastUsedProjectParent,setProjectSessionState,+ setSpellCheckEnabled,} from '../../src/main/state-store.ts';describe('state-store (recent projects + LRU)', () => {@@ -471,3 +472,45 @@ describe('state-store (pendingWindowRestore — post-update window restore)', ()).toBeNull();});});++describe('state-store (spellCheckEnabled — app-wide spell-check toggle)', () => {+ test('defaults to true on a fresh state', () => {+ expect(emptyState().spellCheckEnabled).toBe(true);+ });++ test('setSpellCheckEnabled immutably updates the flag', () => {+ const original = emptyState();+ const disabled = setSpellCheckEnabled(original, false);+ expect(disabled.spellCheckEnabled).toBe(false);+ expect(disabled.recentProjects).toEqual([]);+ expect(disabled.schemaVersion).toBe(1);+ expect(original.spellCheckEnabled).toBe(true);+ });++ test('setSpellCheckEnabled can re-enable a disabled flag', () => {+ const reenabled = setSpellCheckEnabled(setSpellCheckEnabled(emptyState(), false), true);+ expect(reenabled.spellCheckEnabled).toBe(true);+ });++ test('parseAppState coerces a missing spellCheckEnabled to true (legacy state.json)', () => {+ const parsed = parseAppState({ recentProjects: [], lastOpenedProject: null });+ expect(parsed?.spellCheckEnabled).toBe(true);+ });++ test('parseAppState coerces a non-boolean spellCheckEnabled to true', () => {+ const parsed = parseAppState({ recentProjects: [], spellCheckEnabled: 'nope' });+ expect(parsed?.spellCheckEnabled).toBe(true);+ });++ test('parseAppState preserves an explicit false across a round-trip', () => {+ const state = setSpellCheckEnabled(emptyState(), false);+ const reparsed = parseAppState(JSON.parse(JSON.stringify(state)));+ expect(reparsed?.spellCheckEnabled).toBe(false);+ });++ test('parseAppState preserves an explicit true across a round-trip', () => {+ const state = setSpellCheckEnabled(emptyState(), true);+ const reparsed = parseAppState(JSON.parse(JSON.stringify(state)));+ expect(reparsed?.spellCheckEnabled).toBe(true);+ });+});