Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Add "By meaning" semantic search to the Cmd+K omnibar (#1727)

mike-inkeep77a56fbc6cbd
diff --git a/.changeset/embeddings-key-tail.md b/.changeset/embeddings-key-tail.md
new file mode 100644
index 000000000..3868dea75
--- /dev/null
+++ b/.changeset/embeddings-key-tail.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Show a redacted tail of the stored embeddings key in Settings
+
+The "API key set" panel in Settings now shows the last four characters of the stored key (the rest masked) so you can tell at a glance which key is configured. The key is still never returned in full: the status endpoint exposes only the redacted tail, and only when the key is long enough that four characters are a negligible fraction.
diff --git a/.changeset/omnibar-semantic-search.md b/.changeset/omnibar-semantic-search.md
new file mode 100644
index 000000000..16d68a348
--- /dev/null
+++ b/.changeset/omnibar-semantic-search.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Add semantic ("by meaning") search to the Cmd+K omnibar.
+
+When semantic search is set up for a project (enabled plus an embeddings API key), the omnibar shows a "By meaning" filter pill beside "By tag". Clicking it opens an exclusive mode where typing stays instant and local; pressing Enter fires one vector search through the existing `/api/search` semantic fusion, the same engine the MCP `search` tool uses. Results are sticky: editing the query after a search keeps the prior results (dimmed) and offers a one-key re-fire, so a stray keystroke never costs the expensive result set. Escape exits the mode before closing the palette. When semantic search is not set up the pill is hidden and the omnibar is unchanged.
+
+Omnibar-initiated semantic searches now carry a `source` tag so their cost can be counted apart from the MCP tool's.
diff --git a/.changeset/omnibar-semantic-ux.md b/.changeset/omnibar-semantic-ux.md
new file mode 100644
index 000000000..60cbee6b2
--- /dev/null
+++ b/.changeset/omnibar-semantic-ux.md
@@ -0,0 +1,8 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Omnibar "By meaning" UX: carry typed text into the mode, and show indexing progress
+
+- Switching to "By meaning" (clicking the pill) now keeps whatever you already typed as the semantic query instead of clearing it — only a `tag:` filter prefix is dropped. The typed text becomes the pending search you can fire with Enter.
+- The "By meaning" view now shows an indexing banner with live coverage ("Indexing your pages — N of M ready. Results may be incomplete.") while the corpus is still embedding. The first by-meaning search lazily kicks off that background index, and the banner ticks up as it progresses, so it is clear when results may not yet be complete.
diff --git a/.changeset/secrets-file-read-self-heal.md b/.changeset/secrets-file-read-self-heal.md
new file mode 100644
index 000000000..885f92046
--- /dev/null
+++ b/.changeset/secrets-file-read-self-heal.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Tighten loose permissions on the embeddings secrets file when reading it
+
+The embeddings API key in `~/.ok/secrets.yml` was re-secured to 0600 only on write. A file left group/other-readable (an older build before chmod-on-write, an external tool, or a hand-edit) could stay world-readable indefinitely, since the key is read on every search but rewritten rarely or never. Reads now self-heal: a secrets file with a mode looser than owner-only is tightened to 0600 the moment it is read, with a one-time warning. Best-effort and never throws, so it stays safe on the search read path.
+
+The store also reads a key stored under the previous field name as a fallback, so a key written by an earlier build keeps working after the field was renamed to `OPENAI_API_KEY`; the next time the key is set, it is rewritten under the current name (one-shot and self-clearing).
diff --git a/.changeset/semantic-search-similarity-floor.md b/.changeset/semantic-search-similarity-floor.md
new file mode 100644
index 000000000..c701158f4
--- /dev/null
+++ b/.changeset/semantic-search-similarity-floor.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Make semantic search retrieval rank-based so synonym queries return matches
+
+Semantic ("by meaning") search returned nothing for synonym queries: "cybersecurity" missed a page about hacking, "kid" missed a page about a child. The cause was an absolute cosine floor of 0.35 applied before ranking. text-embedding-3-small produces a compressed similarity band for short keyword queries against whole-document embeddings (correct hits commonly score 0.13 to 0.29), so the floor discarded every candidate and search fell back to pure keyword matching, which a synonym cannot satisfy.
+
+An absolute threshold is the wrong mechanism here: the right value is model-specific, and on a compressed scale a weak-but-real hit and weak noise overlap (a correct hit scored 0.147 while an unrelated query scored 0.151), so no threshold separates them. Retrieval is now rank-based: the closest pages by cosine are returned and ranked, with no absolute cutoff by default. The omnibar bounds the "By meaning" list by a result count (the same cap as keyword search) rather than a score, since nearest-neighbor search always has a closest match. An optional per-project hard cutoff remains via search.semantic.similarityFloor for anyone who knows their provider's cosine scale and wants to suppress weak matches.
+
+This affects both the MCP search tool and the omnibar "By meaning" mode.
diff --git a/packages/app/package.json b/packages/app/package.json
index faf575a2b..de32f72b7 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -5,7 +5,7 @@
"private": true,
"type": "module",
"scripts": {
- "predev": "turbo run build --filter=@inkeep/open-knowledge-core --filter=@inkeep/open-knowledge-server && sh scripts/i18n-compile-unless-skipped.sh",
+ "predev": "turbo run build --filter=@inkeep/open-knowledge-core --filter=@inkeep/open-knowledge-server && bun run i18n:compile",
"dev": "vite",
"build": "bun run i18n:compile && tsc --noEmit && vite build",
"typecheck": "tsc --noEmit",
@@ -25,7 +25,7 @@
"measure:fuzz": "bash scripts/measure-fuzz.sh",
"measure:stress": "bash scripts/measure-stress.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/init-load-byte-stable.e2e.ts tests/stress/single-file-ephemeral.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/init-load-byte-stable.e2e.ts tests/stress/single-file-ephemeral.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
@@ -50,7 +50,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "2.7 MB",
+ "limit": "2.75 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index 3f9821388..680a7b724 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -11,13 +11,16 @@ import {
FolderPlus,
Hash,
LayoutGrid,
+ Loader2,
Network,
Package,
Plus,
Settings,
+ Sparkles,
} from 'lucide-react';
import {
type Dispatch,
+ type KeyboardEvent as ReactKeyboardEvent,
type SetStateAction,
useDeferredValue,
useEffect,
@@ -37,11 +40,13 @@ import {
buildWorkspaceEntries,
fetchWorkspaceSearchEntries,
matchesCommandQuery,
+ SEMANTIC_RESULT_LIMIT,
searchWorkspaceEntries,
splitTextByQueryMatches,
type WorkspaceEntry,
type WorkspaceSearchEntry,
} from '@/components/command-palette-search';
+import { computeSemanticModeView } from '@/components/command-palette-semantic';
import {
fetchDocsForTag,
fetchTagsList,
@@ -67,6 +72,7 @@ import {
import { useDocumentContext } from '@/editor/DocumentContext';
import type { TagSummaryEntry } from '@/editor/extensions/tag-suggestion';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
+import { useSemanticSearchStatus } from '@/hooks/use-semantic-search-status';
import type { OkDesktopBridge, RecentProjectEntry } from '@/lib/desktop-bridge-types';
import { hashFromDocName } from '@/lib/doc-hash';
import { runWithToast as runWithToastBase } from '@/lib/error-state';
@@ -111,10 +117,12 @@ function NavigationItem({
entry,
query = '',
onSelect,
+ disabled = false,
}: {
entry: WorkspaceEntry | WorkspaceSearchEntry | OmnibarRecentEntry;
query?: string;
onSelect: () => void;
+ disabled?: boolean;
}) {
const Icon = entry.kind === 'folder' ? FolderOpen : FileText;
const title =
@@ -125,6 +133,7 @@ function NavigationItem({
<CommandItem
value={`${entry.kind} ${entry.path}`}
onSelect={onSelect}
+ disabled={disabled}
data-testid={`command-palette-nav-${entry.kind}-${entry.path}`}
className="items-start"
>
@@ -188,6 +197,12 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
const [searchStatus, setSearchStatus] = useState<'idle' | 'loading' | 'success' | 'error'>(
'idle',
);
+ const [isSemanticMode, setIsSemanticMode] = useState(false);
+ const [semanticResults, setSemanticResults] = useState<WorkspaceSearchEntry[]>([]);
+ const [semanticFiredQuery, setSemanticFiredQuery] = useState<string | null>(null);
+ const [semanticStatus, setSemanticStatus] = useState<'idle' | 'loading' | 'success' | 'error'>(
+ 'idle',
+ );
const [projectRecents, setProjectRecents] = useState<RecentProjectEntry[]>([]);
const [recentNavigation, setRecentNavigation] = useState<OmnibarRecentEntry[]>([]);
const [createDialogKind, setCreateDialogKind] = useState<'file' | 'folder' | null>(null);
@@ -204,11 +219,28 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
const tagsListFetchedRef = useRef(false);
const listRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
+ const semanticAbortRef = useRef<AbortController | null>(null);
+ const semanticTimerRef = useRef<number | null>(null);
const { activeDocName, activeTarget } = useDocumentContext();
const { pages, pageTitles, pageMeta, folderPaths } = usePageList();
const workspace = useWorkspace();
const { states: installStates, refresh: refreshInstallStates } = useInstalledAgents();
const { dispatch: dispatchHandoff } = useHandoffDispatch();
+ const { status: semanticCapability, refresh: refreshSemanticStatus } = useSemanticSearchStatus({
+ enabled: open,
+ });
+ const semanticCapable =
+ (semanticCapability?.enabled ?? false) && (semanticCapability?.keyPresent ?? false);
+ const semanticIndexedCount = semanticCapability?.embedded ?? 0;
+ const semanticTotalCount = semanticCapability?.total ?? 0;
+ const semanticIndexing =
+ semanticCapable && semanticTotalCount > 0 && semanticIndexedCount < semanticTotalCount;
+ // biome-ignore lint/correctness/useExhaustiveDependencies: refreshSemanticStatus is behaviorally stable; re-arm only on the gating booleans.
+ useEffect(() => {
+ if (!open || !isSemanticMode || !semanticIndexing) return;
+ const id = window.setInterval(() => refreshSemanticStatus(), 2500);
+ return () => window.clearInterval(id);
+ }, [open, isSemanticMode, semanticIndexing]);
const handoffInput = buildHandoffInput({ docName: activeDocName, workspace });
const workspaceEntries = buildWorkspaceEntries(pages, folderPaths, pageTitles, pageMeta);
@@ -257,6 +289,16 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
tagsListFetchedRef.current = false;
setTagDocs([]);
setTagDocsStatus('idle');
+ setIsSemanticMode(false);
+ semanticAbortRef.current?.abort();
+ semanticAbortRef.current = null;
+ if (semanticTimerRef.current !== null) {
+ window.clearTimeout(semanticTimerRef.current);
+ semanticTimerRef.current = null;
+ }
+ setSemanticResults([]);
+ setSemanticFiredQuery(null);
+ setSemanticStatus('idle');
}, [open, bridge, refreshInstallStates, t]);
useEffect(() => {
@@ -265,10 +307,24 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
}, [query]);
const knownTagNames = new Set(tagsList.map((tag) => tag.name));
- const paletteMode = parseTagPaletteQuery(deferredQuery, knownTagNames);
+ const paletteMode = isSemanticMode
+ ? ({ kind: 'normal', query: deferredQuery } as const)
+ : parseTagPaletteQuery(deferredQuery, knownTagNames);
const isTagMode = paletteMode.kind !== 'normal';
+ const inExclusiveMode = isTagMode || isSemanticMode;
const tagListQuery = paletteMode.kind === 'tag-list' ? paletteMode.query : '';
const tagDocsName = paletteMode.kind === 'tag-docs' ? paletteMode.tagName : '';
+ const semanticQueryText = query.trim();
+ const semanticView = isSemanticMode
+ ? computeSemanticModeView({
+ query: semanticQueryText,
+ firedQuery: semanticFiredQuery,
+ status: semanticStatus,
+ resultCount: semanticResults.length,
+ })
+ : null;
+ const semanticSubmitQuery = semanticView?.submit?.query ?? '';
+ const semanticResultsLabel = semanticView?.results.forQuery ?? '';
useEffect(() => {
if (!open || !isTagMode) return;
@@ -321,7 +377,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
}, [open, tagDocsTarget]);
useEffect(() => {
- if (!open || !trimmedDeferredQuery || isTagMode) {
+ if (!open || !trimmedDeferredQuery || inExclusiveMode) {
setSearchResults([]);
setSearchStatus('idle');
return;
@@ -354,7 +410,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
window.clearTimeout(timeout);
controller.abort();
};
- }, [open, trimmedDeferredQuery, isTagMode]);
+ }, [open, trimmedDeferredQuery, inExclusiveMode]);
const runAction = (fn: () => Promise<void> | void, fallback = t`Command failed.`) => {
onOpenChange(false);
@@ -381,25 +437,28 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
}
const showRecentNavigation =
- !isTagMode && trimmedDeferredQuery === '' && visibleRecents.length > 0;
+ !inExclusiveMode && trimmedDeferredQuery === '' && visibleRecents.length > 0;
const visibleSearchResults = computeVisibleSearchResults({
searchResults,
fallbackSearchResults,
searchStatus,
});
- const showNavigation = !isTagMode && visibleSearchResults.length > 0;
+ const showNavigation = !inExclusiveMode && visibleSearchResults.length > 0;
const showSearchLoading =
- !isTagMode && trimmedDeferredQuery !== '' && searchStatus === 'loading' && !showNavigation;
+ !inExclusiveMode &&
+ trimmedDeferredQuery !== '' &&
+ searchStatus === 'loading' &&
+ !showNavigation;
const showCreateFile =
- !isTagMode && matchesCommandQuery(t`New file`, deferredQuery, ['create file']);
+ !inExclusiveMode && matchesCommandQuery(t`New file`, deferredQuery, ['create file']);
const showCreateFolder =
- !isTagMode && matchesCommandQuery(t`New folder`, deferredQuery, ['create folder']);
+ !inExclusiveMode && matchesCommandQuery(t`New folder`, deferredQuery, ['create folder']);
const showGraphCommand =
- !isTagMode &&
+ !inExclusiveMode &&
activeDocName !== null &&
matchesCommandQuery(t`Open graph`, deferredQuery, ['graph panel network']);
const showInitializeStarterPack =
- !isTagMode &&
+ !inExclusiveMode &&
matchesCommandQuery(t`Initialize starter pack`, deferredQuery, [
'scaffold',
'seed',
@@ -407,30 +466,30 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
'starter',
]);
const showCreateProject =
- !isTagMode &&
+ !inExclusiveMode &&
bridge !== null &&
matchesCommandQuery(t`New project`, deferredQuery, ['create new project scaffold']);
const showProjectOpenFolder =
- !isTagMode &&
+ !inExclusiveMode &&
bridge !== null &&
matchesCommandQuery(t`Open folder on disk`, deferredQuery, ['project']);
const showProjectSwitch =
- !isTagMode &&
+ !inExclusiveMode &&
!singleFile &&
bridge !== null &&
matchesCommandQuery(t`Switch Project`, deferredQuery, ['switch project navigator projects']);
const showSettings =
- !isTagMode &&
+ !inExclusiveMode &&
!singleFile &&
matchesCommandQuery(t`Settings`, deferredQuery, ['preferences config']);
const showInstallClaudeDesktop =
SHOW_INSTALL_SKILL &&
- !isTagMode &&
+ !inExclusiveMode &&
matchesCommandQuery(t`Install for Claude Chat & Cowork (Desktop App)`, deferredQuery, [
'claude desktop install cowork',
]);
const showProjectRecents =
- !isTagMode &&
+ !inExclusiveMode &&
bridge !== null &&
switchableProjects.length > 0 &&
(trimmedDeferredQuery === '' ||
@@ -439,7 +498,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
));
const isEmbedded = useIsEmbedded();
const showAgentGroup =
- !isTagMode &&
+ !inExclusiveMode &&
!isEmbedded &&
handoffInput !== null &&
(trimmedDeferredQuery === '' ||
@@ -459,7 +518,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
paletteMode.kind === 'tag-docs' && tagDocsStatus === 'success' && tagDocs.length === 0;
const hasAnyResults =
- isTagMode ||
+ inExclusiveMode ||
showRecentNavigation ||
showNavigation ||
showSearchLoading ||
@@ -479,6 +538,90 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
setQuery(`${TAG_QUERY_PREFIX}${tagName}`);
}
+ function resetSemanticState() {
+ semanticAbortRef.current?.abort();
+ semanticAbortRef.current = null;
+ if (semanticTimerRef.current !== null) {
+ window.clearTimeout(semanticTimerRef.current);
+ semanticTimerRef.current = null;
+ }
+ setSemanticResults([]);
+ setSemanticFiredQuery(null);
+ setSemanticStatus('idle');
+ }
+
+ function enterSemanticMode() {
+ setIsSemanticMode(true);
+ if (query.startsWith(TAG_QUERY_PREFIX)) setQuery(query.slice(TAG_QUERY_PREFIX.length));
+ resetSemanticState();
+ inputRef.current?.focus();
+ }
+
+ function exitSemanticMode() {
+ setIsSemanticMode(false);
+ setQuery('');
+ resetSemanticState();
+ inputRef.current?.focus();
+ }
+
+ function fireSemanticSearch(raw: string) {
+ const q = raw.trim();
+ if (!q) return;
+ semanticAbortRef.current?.abort();
+ if (semanticTimerRef.current !== null) window.clearTimeout(semanticTimerRef.current);
+ const controller = new AbortController();
+ semanticAbortRef.current = controller;
+ setSemanticStatus('loading');
+ let timedOut = false;
+ const timeout = window.setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ setSemanticStatus('error');
+ }, COMMAND_PALETTE_SEARCH_TIMEOUT_MS);
+ semanticTimerRef.current = timeout;
+ void fetchWorkspaceSearchEntries(q, {
+ signal: controller.signal,
+ semantic: true,
+ limit: SEMANTIC_RESULT_LIMIT,
+ })
+ .then((results) => {
+ clearThisFire(timeout, controller);
+ setSemanticResults(results);
+ setSemanticFiredQuery(q);
+ setSemanticStatus('success');
+ })
+ .catch((error: unknown) => {
+ clearThisFire(timeout, controller);
+ if (error instanceof Error && error.name === 'AbortError' && !timedOut) return;
+ console.debug('[semantic-search] fire failed', { timedOut, error });
+ setSemanticStatus('error');
+ });
+ }
+
+ function clearThisFire(timeout: number, controller: AbortController) {
+ window.clearTimeout(timeout);
+ if (semanticTimerRef.current === timeout) semanticTimerRef.current = null;
+ if (semanticAbortRef.current === controller) semanticAbortRef.current = null;
+ }
+
+ function onSemanticInputKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {
+ if (!isSemanticMode || e.key !== 'Enter') return;
+ if (semanticView?.submit) {
+ e.preventDefault();
+ e.stopPropagation();
+ fireSemanticSearch(semanticView.submit.query);
+ } else if (semanticStatus === 'loading') {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }
+
+ function onPaletteEscapeKeyDown(e: KeyboardEvent) {
+ if (!isSemanticMode) return;
+ e.preventDefault();
+ exitSemanticMode();
+ }
+
return (
<>
<CommandDialog
@@ -492,12 +635,16 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
className:
'[&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4',
}}
+ onEscapeKeyDown={onPaletteEscapeKeyDown}
>
<CommandInput
ref={inputRef}
value={query}
onValueChange={setQuery}
- placeholder={t`Search files, folders, or commands`}
+ onKeyDown={onSemanticInputKeyDown}
+ placeholder={
+ isSemanticMode ? t`Search by meaning` : t`Search files, folders, or commands`
+ }
/>
{/* Filter-pills row — Slack-style. Always visible so the
available filters are discoverable without typing a magic
@@ -507,6 +654,10 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
<button
type="button"
onClick={() => {
+ if (isSemanticMode) {
+ setIsSemanticMode(false);
+ resetSemanticState();
+ }
setQuery(isTagMode ? '' : TAG_QUERY_PREFIX);
inputRef.current?.focus();
}}
@@ -525,8 +676,130 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
<Trans>By tag</Trans>
</span>
</button>
+ {/* Shown only when semantic search is set up for this project (enabled
+ + key). Enters an exclusive "by meaning" mode — a deliberate-submit
+ vector search, distinct from the per-keystroke lexical filters. */}
+ {semanticCapable ? (
+ <button
+ type="button"
+ onClick={() => (isSemanticMode ? exitSemanticMode() : enterSemanticMode())}
+ data-testid="command-palette-filter-semantic"
+ data-active={isSemanticMode}
+ aria-pressed={isSemanticMode}
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors',
+ isSemanticMode
+ ? 'border-primary/30 bg-primary/10 text-primary'
+ : 'border-border bg-transparent text-muted-foreground hover:bg-accent hover:text-accent-foreground',
+ )}
+ >
+ <Sparkles className="size-3.5" />
+ <span>
+ <Trans>By meaning</Trans>
+ </span>
+ </button>
+ ) : null}
</div>
<CommandList ref={listRef} className="subtle-scrollbar">
+ {isSemanticMode && semanticView ? (
+ <>
+ {/* Coverage banner — the first by-meaning search lazily kicks off the
+ background embed, so the corpus may be partly (or not yet) indexed.
+ Surface it so the user knows results may be incomplete; the count
+ ticks up via the poll above. */}
+ {semanticIndexing ? (
+ <div
+ className="flex items-center gap-2 px-3 py-2 text-muted-foreground text-xs"
+ role="status"
+ aria-live="polite"
+ data-testid="command-palette-semantic-indexing"
+ >
+ <Loader2 className="size-3.5 animate-spin" />
+ <Trans>
+ Indexing your pages — {semanticIndexedCount} of {semanticTotalCount} ready.
+ Results may be incomplete.
+ </Trans>
+ </div>
+ ) : null}
+
+ {/* Submit / retry row — the action ↵ performs while the query is
+ dirty or after an error. Rendered first so it is the default
+ highlight; the input's keydown makes ↵ deterministic regardless. */}
+ {semanticView.submit ? (
+ <CommandGroup>
+ <CommandItem
+ value="semantic-submit"
+ onSelect={() => fireSemanticSearch(semanticSubmitQuery)}
+ data-testid="command-palette-semantic-submit"
+ >
+ {semanticView.submit.kind === 'retry' ? (
+ <span className="flex items-center gap-2 text-amber-700 dark:text-amber-400">
+ <Sparkles />
+ <Trans>Couldn't reach the embeddings provider — press ↵ to retry</Trans>
+ </span>
+ ) : (
+ <>
+ <Sparkles />
+ <span className="min-w-0 flex-1 truncate">
+ <Trans>Search "{semanticSubmitQuery}" by meaning</Trans>
+ </span>
+ <CommandShortcut>↵</CommandShortcut>
+ </>
+ )}
+ </CommandItem>
+ </CommandGroup>
+ ) : null}
+
+ {semanticView.notice === 'empty' ? (
+ <CommandEmpty data-testid="command-palette-semantic-empty">
+ <Trans>Type a query, then press ↵ to search your pages by meaning.</Trans>
+ </CommandEmpty>
+ ) : null}
+ {semanticView.notice === 'searching' ? (
+ <div
+ className="flex items-center justify-center gap-2 py-6 text-muted-foreground text-sm"
+ role="status"
+ aria-live="polite"
+ data-testid="command-palette-semantic-searching"
+ >
+ <Loader2 className="size-4 animate-spin" />
+ <Trans>Searching by meaning</Trans>
+ </div>
+ ) : null}
+ {semanticView.notice === 'no-results' ? (
+ <CommandEmpty data-testid="command-palette-semantic-no-results">
+ <Trans>No pages matched "{semanticQueryText}" by meaning.</Trans>
+ </CommandEmpty>
+ ) : null}
+
+ {/* Held (sticky) results in the server's fusion order — no omnibar
+ fuzzy/recency re-ranking. Dimmed + labeled with the query they
+ were fetched for while the typed query has moved past them. */}
+ {semanticView.results.show ? (
+ <CommandGroup
+ heading={
+ semanticView.results.dimmed
+ ? t`Showing results for "${semanticResultsLabel}"`
+ : t`By meaning`
+ }
+ >
+ <div
+ data-testid="command-palette-semantic-results"
+ data-dimmed={semanticView.results.dimmed}
+ >
+ {semanticResults.map((entry) => (
+ <NavigationItem
+ key={makeOmnibarRecentKey(entry.kind, entry.path)}
+ entry={entry}
+ disabled={semanticView.results.dimmed}
+ onSelect={() => navigateToEntry(entry)}
+ />
+ ))}
+ </div>
+ </CommandGroup>
+ ) : null}
+ </>
+ ) : null}
{showSearchLoading && !showNavigation ? (
<CommandEmpty>
<Trans>Searching</Trans>
diff --git a/packages/app/src/components/command-palette-search.test.ts b/packages/app/src/components/command-palette-search.test.ts
index a15788943..61ff4f285 100644
--- a/packages/app/src/components/command-palette-search.test.ts
+++ b/packages/app/src/components/command-palette-search.test.ts
@@ -127,6 +127,7 @@ describe('fetchWorkspaceSearchEntries', () => {
intent: 'full_text',
scopes: ['page', 'folder', 'content'],
limit: 30,
+ source: 'omnibar',
});
expect(results).toEqual([
{
@@ -140,4 +141,23 @@ describe('fetchWorkspaceSearchEntries', () => {
{ kind: 'folder', path: 'docs', name: 'docs', title: 'docs', score: 12 },
]);
});
+
+ test('semantic submit adds semantic:true (keeps full_text + scopes + source:omnibar)', async () => {
+ let requestBody: unknown = null;
+ globalThis.fetch = (async (_input, init) => {
+ requestBody = JSON.parse(String(init?.body));
+ return new Response(JSON.stringify({ results: [] }), { status: 200 });
+ }) as typeof fetch;
+
+ await fetchWorkspaceSearchEntries('auth retries', { semantic: true });
+
+ expect(requestBody).toEqual({
+ query: 'auth retries',
+ intent: 'full_text',
+ scopes: ['page', 'folder', 'content'],
+ limit: 30,
+ source: 'omnibar',
+ semantic: true,
+ });
+ });
});
diff --git a/packages/app/src/components/command-palette-search.ts b/packages/app/src/components/command-palette-search.ts
index a46501b85..304086188 100644
--- a/packages/app/src/components/command-palette-search.ts
+++ b/packages/app/src/components/command-palette-search.ts
@@ -37,6 +37,7 @@ interface WorkspaceEntrySearchCorpus {
export const EMPTY_QUERY_NAV_LIMIT = 20;
const MATCH_QUERY_NAV_LIMIT = 50;
const API_SEARCH_LIMIT = 30;
+export const SEMANTIC_RESULT_LIMIT = 30;
let cachedEntriesFingerprint = '';
let cachedEntrySearchCorpus: WorkspaceEntrySearchCorpus | null = null;
@@ -206,7 +207,7 @@ function toWorkspaceSearchEntry(
export async function fetchWorkspaceSearchEntries(
query: string,
- options: { signal?: AbortSignal; limit?: number } = {},
+ options: { signal?: AbortSignal; limit?: number; semantic?: boolean } = {},
): Promise<WorkspaceSearchEntry[]> {
const normalizedQuery = query.trim();
if (!normalizedQuery) return [];
@@ -219,6 +220,8 @@ export async function fetchWorkspaceSearchEntries(
intent: 'full_text',
scopes: ['page', 'folder', 'content'],
limit: options.limit ?? API_SEARCH_LIMIT,
+ source: 'omnibar',
+ ...(options.semantic ? { semantic: true } : {}),
}),
signal: options.signal,
});
diff --git a/packages/app/src/components/command-palette-semantic.test.ts b/packages/app/src/components/command-palette-semantic.test.ts
new file mode 100644
index 000000000..6e7b7ba71
--- /dev/null
+++ b/packages/app/src/components/command-palette-semantic.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, test } from 'bun:test';
+import { computeSemanticModeView, type SemanticModeState } from './command-palette-semantic';
+
+function view(over: Partial<SemanticModeState>) {
+ return computeSemanticModeView({
+ query: '',
+ firedQuery: null,
+ status: 'idle',
+ resultCount: 0,
+ ...over,
+ });
+}
+
+describe('computeSemanticModeView', () => {
+ test('just entered, empty query: prompts to type, no submit, no results', () => {
+ expect(view({})).toEqual({
+ submit: null,
+ results: { show: false, dimmed: false, forQuery: null },
+ notice: 'empty',
+ });
+ });
+
+ test('query typed, nothing fired: offers a search submit (Enter fires)', () => {
+ expect(view({ query: 'auth retries' })).toEqual({
+ submit: { kind: 'search', query: 'auth retries' },
+ results: { show: false, dimmed: false, forQuery: null },
+ notice: null,
+ });
+ });
+
+ test('loading the first fire: spinner, no submit, no results', () => {
+ expect(view({ query: 'auth retries', status: 'loading' })).toEqual({
+ submit: null,
+ results: { show: false, dimmed: false, forQuery: null },
+ notice: 'searching',
+ });
+ });
+
+ test('loading a re-fire: prior results stay, dimmed + labeled, spinner', () => {
+ expect(
+ view({ query: 'auth retries', firedQuery: 'sessions', status: 'loading', resultCount: 5 }),
+ ).toEqual({
+ submit: null,
+ results: { show: true, dimmed: true, forQuery: 'sessions' },
+ notice: 'searching',
+ });
+ });
+
+ test('clean success (query matches fired): results lead, no submit, Enter opens', () => {
+ expect(
+ view({
+ query: 'auth retries',
+ firedQuery: 'auth retries',
+ status: 'success',
+ resultCount: 7,
+ }),
+ ).toEqual({
+ submit: null,
+ results: { show: true, dimmed: false, forQuery: 'auth retries' },
+ notice: null,
+ });
+ });
+
+ test('clean success with zero matches: no-match notice, no submit', () => {
+ expect(
+ view({
+ query: 'auth retries',
+ firedQuery: 'auth retries',
+ status: 'success',
+ resultCount: 0,
+ }),
+ ).toEqual({
+ submit: null,
+ results: { show: false, dimmed: false, forQuery: null },
+ notice: 'no-results',
+ });
+ });
+
+ test('dirty after success: submit row leads (Enter re-fires), prior results dimmed + labeled', () => {
+ expect(
+ view({
+ query: 'token refresh',
+ firedQuery: 'auth retries',
+ status: 'success',
+ resultCount: 7,
+ }),
+ ).toEqual({
+ submit: { kind: 'search', query: 'token refresh' },
+ results: { show: true, dimmed: true, forQuery: 'auth retries' },
+ notice: null,
+ });
+ });
+
+ test('error on the first fire: a retry row (Enter retries), no held results', () => {
+ expect(view({ query: 'auth retries', status: 'error' })).toEqual({
+ submit: { kind: 'retry', query: 'auth retries' },
+ results: { show: false, dimmed: false, forQuery: null },
+ notice: null,
+ });
+ });
+
+ test('error on a re-fire: retry row + prior results retained, dimmed + labeled', () => {
+ expect(
+ view({ query: 'token refresh', firedQuery: 'auth retries', status: 'error', resultCount: 7 }),
+ ).toEqual({
+ submit: { kind: 'retry', query: 'token refresh' },
+ results: { show: true, dimmed: true, forQuery: 'auth retries' },
+ notice: null,
+ });
+ });
+
+ test('clearing the query after a fire keeps the held results dimmed, no submit', () => {
+ expect(
+ view({ query: '', firedQuery: 'auth retries', status: 'success', resultCount: 7 }),
+ ).toEqual({
+ submit: null,
+ results: { show: true, dimmed: true, forQuery: 'auth retries' },
+ notice: null,
+ });
+ });
+
+ test('clearing the query DURING a re-fire keeps the held results dimmed, spinner showing', () => {
+ expect(
+ view({ query: '', firedQuery: 'auth retries', status: 'loading', resultCount: 7 }),
+ ).toEqual({
+ submit: null,
+ results: { show: true, dimmed: true, forQuery: 'auth retries' },
+ notice: 'searching',
+ });
+ });
+
+ test('clearing the query after an error keeps the held results dimmed, no retry row', () => {
+ expect(
+ view({ query: '', firedQuery: 'auth retries', status: 'error', resultCount: 7 }),
+ ).toEqual({
+ submit: null,
+ results: { show: true, dimmed: true, forQuery: 'auth retries' },
+ notice: null,
+ });
+ });
+});
diff --git a/packages/app/src/components/command-palette-semantic.ts b/packages/app/src/components/command-palette-semantic.ts
new file mode 100644
index 000000000..0f36bef25
--- /dev/null
+++ b/packages/app/src/components/command-palette-semantic.ts
@@ -0,0 +1,43 @@
+export interface SemanticModeState {
+ query: string;
+ firedQuery: string | null;
+ status: 'idle' | 'loading' | 'success' | 'error';
+ resultCount: number;
+}
+
+type SemanticSubmit = { kind: 'search'; query: string } | { kind: 'retry'; query: string } | null;
+
+export interface SemanticModeView {
+ submit: SemanticSubmit;
+ results: { show: boolean; dimmed: boolean; forQuery: string | null };
+ notice: 'empty' | 'searching' | 'no-results' | null;
+}
+
+export function computeSemanticModeView(state: SemanticModeState): SemanticModeView {
+ const { query, firedQuery, status, resultCount } = state;
+ const hasResults = resultCount > 0;
+ const dirty = query !== '' && query !== firedQuery;
+ const dimmed = hasResults && (status === 'loading' || query !== firedQuery);
+
+ let submit: SemanticSubmit = null;
+ if (status === 'error' && query !== '') {
+ submit = { kind: 'retry', query };
+ } else if (dirty && status !== 'loading') {
+ submit = { kind: 'search', query };
+ }
+
+ let notice: SemanticModeView['notice'] = null;
+ if (status === 'loading') {
+ notice = 'searching';
+ } else if (query === '' && !hasResults) {
+ notice = 'empty';
+ } else if (status === 'success' && !dirty && !hasResults) {
+ notice = 'no-results';
+ }
+
+ return {
+ submit,
+ results: { show: hasResults, dimmed, forQuery: hasResults ? firedQuery : null },
+ notice,
+ };
+}
diff --git a/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx b/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx
index 15f1b0910..1f0bd7cd4 100644
--- a/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx
+++ b/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx
@@ -25,6 +25,7 @@ function statusOf(over: Partial<SemanticIndexStatus>): SemanticIndexStatus {
enabled: false,
keyPresent: false,
keySource: null,
+ keyHint: null,
ready: false,
capable: false,
embedded: 0,
@@ -127,6 +128,25 @@ describe('EmbeddingsKeySection', () => {
expect(rec.clearCalls).toBe(1);
});
+ test('key present: shows the redacted tail (keyHint), never the full key', async () => {
+ const { transport } = makeTransport();
+ mockStatus = statusOf({ keyPresent: true, keySource: 'file', keyHint: 'a1b2' });
+ render(<EmbeddingsKeySection transport={transport} />);
+
+ const hint = await screen.findByTestId('settings-embeddings-key-hint');
+ expect(hint.textContent).toContain('a1b2');
+ expect(hint.textContent?.length).toBeLessThan(20);
+ });
+
+ test('key present without a hint: the set state still renders (no tail line)', async () => {
+ const { transport } = makeTransport();
+ mockStatus = statusOf({ keyPresent: true, keySource: 'file', keyHint: null });
+ render(<EmbeddingsKeySection transport={transport} />);
+
+ expect(await screen.findByTestId('settings-embeddings-key-set')).toBeDefined();
+ expect(screen.queryByTestId('settings-embeddings-key-hint')).toBeNull();
+ });
+
test('clear failure surfaces the error', async () => {
const user = userEvent.setup();
const rec = makeTransport({
diff --git a/packages/app/src/components/settings/EmbeddingsKeySection.tsx b/packages/app/src/components/settings/EmbeddingsKeySection.tsx
index 9b5c39348..a2da1dec4 100644
--- a/packages/app/src/components/settings/EmbeddingsKeySection.tsx
+++ b/packages/app/src/components/settings/EmbeddingsKeySection.tsx
@@ -18,6 +18,7 @@ export function EmbeddingsKeySection({ transport }: { transport?: EmbeddingsKeyT
const keyPresent = status?.keyPresent ?? false;
const keySource = status?.keySource ?? null;
+ const keyHint = status?.keyHint ?? null;
async function onSave() {
const key = keyInput.trim();
@@ -56,8 +57,13 @@ export function EmbeddingsKeySection({ transport }: { transport?: EmbeddingsKeyT
</h3>
<p className="text-sm text-muted-foreground">
<Trans>
- The API key semantic search uses to embed your content. Stored once for this machine and
- shared across all projects. Turn the feature on per project in This project → Search.
+ Your OpenAI API key, used only to create embeddings of your content for semantic search.
+ Stored once for this machine in{' '}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs">
+ ~/.ok/secrets.yml
+ </code>{' '}
+ (readable only by your user account) and shared across all projects. Turn the feature on
+ per project in This project → Search.
</Trans>
</p>
</div>
@@ -81,9 +87,19 @@ export function EmbeddingsKeySection({ transport }: { transport?: EmbeddingsKeyT
data-testid="settings-embeddings-key-set"
>
<div className="min-w-0">
- <div className="text-sm font-medium">
+ <div className="mb-1.5 text-sm font-medium">
<Trans>API key set</Trans>
</div>
+ {keyHint ? (
+ <p
+ className="truncate font-mono text-muted-foreground text-xs"
+ title={t`Key ending in ${keyHint}`}
+ data-testid="settings-embeddings-key-hint"
+ >
+ <span aria-hidden="true">••••••••</span>
+ {keyHint}
+ </p>
+ ) : null}
<p className="text-muted-foreground text-1sm">
<Trans>Stored on this machine.</Trans>
</p>
@@ -99,8 +115,11 @@ export function EmbeddingsKeySection({ transport }: { transport?: EmbeddingsKeyT
</div>
) : null}
- <div className="space-y-2">
- <label htmlFor="settings-embeddings-key-input" className="text-sm font-medium">
+ <div>
+ <label
+ htmlFor="settings-embeddings-key-input"
+ className="mb-2 block text-sm font-medium"
+ >
{keyPresent ? <Trans>Replace key</Trans> : <Trans>Add a key</Trans>}
</label>
<div className="flex items-center gap-2">
diff --git a/packages/app/src/components/ui/command.tsx b/packages/app/src/components/ui/command.tsx
index 2e3820991..824632e1d 100644
--- a/packages/app/src/components/ui/command.tsx
+++ b/packages/app/src/components/ui/command.tsx
@@ -23,6 +23,7 @@ interface CommandDialogProps extends ComponentProps<typeof Dialog> {
className?: string;
showCloseButton?: boolean;
commandProps?: ComponentProps<typeof CommandPrimitive>;
+ onEscapeKeyDown?: ComponentProps<typeof DialogContent>['onEscapeKeyDown'];
}
function CommandDialog({
@@ -32,6 +33,7 @@ function CommandDialog({
className,
showCloseButton = true,
commandProps,
+ onEscapeKeyDown,
...props
}: CommandDialogProps) {
const { className: commandClassName, ...restCommandProps } = commandProps ?? {};
@@ -40,6 +42,7 @@ function CommandDialog({
<DialogContent
className={cn('top-[12vh] translate-y-0 overflow-hidden p-0', className)}
showCloseButton={showCloseButton}
+ onEscapeKeyDown={onEscapeKeyDown}
>
{/* Inside DialogContent so Radix wires aria within its portal (cf. SettingsDialogShell) */}
<DialogTitle className="sr-only">{title}</DialogTitle>
diff --git a/packages/app/src/hooks/use-semantic-search-status.ts b/packages/app/src/hooks/use-semantic-search-status.ts
index 54d86935a..ce3795da2 100644
--- a/packages/app/src/hooks/use-semantic-search-status.ts
+++ b/packages/app/src/hooks/use-semantic-search-status.ts
@@ -21,26 +21,31 @@ interface UseSemanticSearchStatusResult {
refresh: () => void;
}
-export function useSemanticSearchStatus(): UseSemanticSearchStatusResult {
+export function useSemanticSearchStatus(
+ options: { enabled?: boolean } = {},
+): UseSemanticSearchStatusResult {
+ const enabled = options.enabled ?? true;
const [status, setStatus] = useState<SemanticIndexStatus | null>(null);
function refresh() {
+ if (!enabled) return;
void fetchSemanticStatus().then((next) => {
if (next) setStatus(next);
});
}
- // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is intentionally stable (defined in component scope)
+ // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is stable in component scope; re-run only when `enabled` flips on.
useEffect(() => {
refresh();
- }, []);
+ }, [enabled]);
- // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is intentionally stable (defined in component scope)
+ // biome-ignore lint/correctness/useExhaustiveDependencies: refresh is stable in component scope.
useEffect(() => {
+ if (!enabled) return;
return subscribeToDocumentsChanged((channels) => {
if (channels.includes('files')) refresh();
});
- }, []);
+ }, [enabled]);
return { status, refresh };
}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 2d9b163f6..fee575191 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -344,6 +344,7 @@
"9npOH9": ["Open file"],
"9o1bIV": [["behind"], " behind"],
"9oE4C3": ["Browse your repos:"],
+ "9tJX8r": ["By meaning"],
"9zb2WA": ["Connecting"],
"A1taO8": ["Search"],
"A5CYnd": ["Broken link"],
@@ -496,7 +497,11 @@
"FCxvG5": ["First item"],
"FEr96N": ["Theme"],
"FF5rwn": ["Connect Open Knowledge to other tools you use."],
+ "FNTx6u": ["Search \"", ["semanticSubmitQuery"], "\" by meaning"],
"FOGD7m": ["Create something great."],
+ "FOyCTr": [
+ "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."
+ ],
"FRYB1Q": ["/api/config returned a malformed body"],
"FTUGgh": ["Enter a repository URL or owner/repo"],
"FUMerq": ["Could not enable sync: ", ["detail"]],
@@ -772,6 +777,7 @@
"P6lAT3": ["Folder target: ", ["linkTitle"], ". Click to open the overview."],
"P8yDjG": ["Name can’t be empty, \".\", \"..\", or contain / or \\"],
"PB4upl": ["Find previous match"],
+ "PBwmDJ": ["Searching by meaning"],
"PKLY-1": ["Opening..."],
"PMyJ9C": ["No edit session yet"],
"PQCdtv": ["\"", ["docName"], "\" doesn't exist."],
@@ -795,6 +801,7 @@
"QR5SP1": ["created template"],
"QWks14": ["A short line shown under the name in the template list."],
"QcpeeE": ["Navigate to ", ["docName"]],
+ "QlxHAH": ["Showing results for \"", ["semanticResultsLabel"], "\""],
"QqBQu1": ["Label <0>(visible link text)</0>"],
"QyioBP": ["Move up"],
"R0cyYB": [
@@ -921,9 +928,6 @@
"Vlc75q": ["Keep file deleted"],
"VuxVSP": ["Start source completion"],
"VvS_k_": ["Config sharing is now local-only."],
- "Vz1amp": [
- "The API key semantic search uses to embed your content. Stored once for this machine and shared across all projects. Turn the feature on per project in This project → Search."
- ],
"W-ntoW": ["heading-slug"],
"W1qRuM": ["This document is already active in the editor. Use Open to collapse the graph."],
"W5A0Ly": ["An unexpected error occurred."],
@@ -987,6 +991,7 @@
"XtRoxT": ["Page ", ["pageNumber"]],
"XvPJaT": ["Diff layout"],
"Xv_ijG": ["https://github.com/owner/repo or owner/repo"],
+ "Xw_maT": ["Type a query, then press ↵ to search your pages by meaning."],
"XyOUTJ": ["Exit merge"],
"Y-Urt2": ["Block math equation rendered with KaTeX from a LaTeX source string."],
"Y8ViJx": ["A newer version may have been deployed since this tab opened."],
@@ -1368,6 +1373,13 @@
{ "one": ["Show ", "#", " auto-save"], "other": ["Show ", "#", " auto-saves"] }
]
],
+ "kCNU4q": [
+ "Indexing your pages — ",
+ ["semanticIndexedCount"],
+ " of ",
+ ["semanticTotalCount"],
+ " ready. Results may be incomplete."
+ ],
"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],
"kDuh1E": ["Path resolves outside the project"],
"kFLlsI": ["Insert a footnote reference + matching definition stub."],
@@ -1544,6 +1556,7 @@
" · ",
["tabCount", "plural", { "one": ["#", " tab"], "other": ["#", " tabs"] }]
],
+ "qEIFZu": ["Key ending in ", ["keyHint"]],
"qEue6Q": [" or "],
"qNOgUu": ["Edits at the source land here — no copy-paste drift."],
"qRZh7J": ["Let Tab leave the source editor instead of indenting."],
@@ -1577,6 +1590,7 @@
["repoName"],
"</0>."
],
+ "rBc32v": ["Couldn't reach the embeddings provider — press ↵ to retry"],
"rFw02Q": ["Uploading ", ["keyName"]],
"rJVoVX": ["Source find results"],
"rQAQus": ["Couldn't save template: ", ["error"]],
@@ -1772,6 +1786,7 @@
"yEJ-sl": [
"The preview blocks resources that don't meet its security rules (for example plain http:// URLs, or code that uses eval). The content above may render incompletely."
],
+ "yFyZMJ": ["No pages matched \"", ["semanticQueryText"], "\" by meaning."],
"yHikCO": ["Open CodeMirror's go-to-line prompt."],
"yKu_3Y": ["Restore"],
"yLq4w4": ["Separator"],
@@ -1827,6 +1842,7 @@
["pickedRelative"],
"</1> because it contains a <2>.git</2> folder (one .ok/ per git repo). <3>Content directory</3> defaults to <4>.</4> (the whole repo); type a sub-folder to narrow it."
],
+ "zXj1rA": ["Search by meaning"],
"zZ_I5K": ["Open project menu"],
"zaXlhf": [
"The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 496bd32fe..93cae5d6e 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -842,6 +842,10 @@ msgstr "Bullet list"
msgid "Bullet List"
msgstr "Bullet List"
+#: src/components/CommandPalette.tsx
+msgid "By meaning"
+msgstr "By meaning"
+
#: src/components/CommandPalette.tsx
msgid "By tag"
msgstr "By tag"
@@ -1502,6 +1506,10 @@ msgstr "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or
msgid "Couldn't reach GitHub. Try again?"
msgstr "Couldn't reach GitHub. Try again?"
+#: src/components/CommandPalette.tsx
+msgid "Couldn't reach the embeddings provider — press ↵ to retry"
+msgstr "Couldn't reach the embeddings provider — press ↵ to retry"
+
#: src/editor/bubble-menu/EditWithAiBubbleButton.tsx
msgid "Couldn't read the selection — please try again."
msgstr "Couldn't read the selection — please try again."
@@ -2672,6 +2680,10 @@ msgstr "Indented blockquote for citations."
msgid "Indexed {embedded} of {total} pages."
msgstr "Indexed {embedded} of {total} pages."
+#: src/components/CommandPalette.tsx
+msgid "Indexing your pages — {semanticIndexedCount} of {semanticTotalCount} ready. Results may be incomplete."
+msgstr "Indexing your pages — {semanticIndexedCount} of {semanticTotalCount} ready. Results may be incomplete."
+
#: src/components/FrontmatterRow.tsx
msgid "inherited"
msgstr "inherited"
@@ -2831,6 +2843,10 @@ msgstr "Keep file deleted"
msgid "Keep my version"
msgstr "Keep my version"
+#: src/components/settings/EmbeddingsKeySection.tsx
+msgid "Key ending in {keyHint}"
+msgstr "Key ending in {keyHint}"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Keyboard shortcuts available in the editor and workspace."
msgstr "Keyboard shortcuts available in the editor and workspace."
@@ -3465,6 +3481,10 @@ msgstr "No pages found for \"{trimmedQuery}\""
msgid "No pages link here yet."
msgstr "No pages link here yet."
+#: src/components/CommandPalette.tsx
+msgid "No pages matched \"{semanticQueryText}\" by meaning."
+msgstr "No pages matched \"{semanticQueryText}\" by meaning."
+
#: src/components/settings/OkignoreSection.tsx
msgid "No patterns yet. Type a folder or file name below to start hiding files."
msgstr "No patterns yet. Type a folder or file name below to start hiding files."
@@ -4662,10 +4682,18 @@ msgstr "Scope: "
msgid "Search"
msgstr "Search"
+#: src/components/CommandPalette.tsx
+msgid "Search \"{semanticSubmitQuery}\" by meaning"
+msgstr "Search \"{semanticSubmitQuery}\" by meaning"
+
#: src/components/EditorHeader.tsx
msgid "Search ({searchShortcut})"
msgstr "Search ({searchShortcut})"
+#: src/components/CommandPalette.tsx
+msgid "Search by meaning"
+msgstr "Search by meaning"
+
#: src/components/PageHeaderWidgets.tsx
msgid "Search emoji"
msgstr "Search emoji"
@@ -4706,6 +4734,10 @@ msgstr "Search templates"
msgid "Searching"
msgstr "Searching"
+#: src/components/CommandPalette.tsx
+msgid "Searching by meaning"
+msgstr "Searching by meaning"
+
#: src/editor/slash-command/items.tsx
msgid "Second item"
msgstr "Second item"
@@ -4954,6 +4986,10 @@ msgstr "Show thumbnails"
msgid "Showing first {truncatedShownCount} items — use search to find others"
msgstr "Showing first {truncatedShownCount} items — use search to find others"
+#: src/components/CommandPalette.tsx
+msgid "Showing results for \"{semanticResultsLabel}\""
+msgstr "Showing results for \"{semanticResultsLabel}\""
+
#. placeholder {0}: items.length
#: src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx
msgid "Showing top {0} headings — keep typing to narrow"
@@ -5316,10 +5352,6 @@ msgstr "That folder isn't an Open Knowledge project yet. Initialize it and open?
msgid "The {targetNoun} could not be opened — try navigating to it manually."
msgstr "The {targetNoun} could not be opened — try navigating to it manually."
-#: src/components/settings/EmbeddingsKeySection.tsx
-msgid "The API key semantic search uses to embed your content. Stored once for this machine and shared across all projects. Turn the feature on per project in This project → Search."
-msgstr "The API key semantic search uses to embed your content. Stored once for this machine and shared across all projects. Turn the feature on per project in This project → Search."
-
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"
msgstr "The Claude Desktop App didn't open the file. Is it installed? ({msg})"
@@ -5579,6 +5611,10 @@ msgstr "Two-page (even)"
msgid "Two-page (odd)"
msgstr "Two-page (odd)"
+#: src/components/CommandPalette.tsx
+msgid "Type a query, then press ↵ to search your pages by meaning."
+msgstr "Type a query, then press ↵ to search your pages by meaning."
+
#: src/editor/components/CodePreviewEditModal.tsx
msgid "Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."
msgstr "Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."
@@ -5958,6 +5994,10 @@ msgstr "Your GitHub token is missing required scopes. Try signing in again."
msgid "Your knowledge base is now on GitHub at <0>{ownerLogin}/{repoName}</0>."
msgstr "Your knowledge base is now on GitHub at <0>{ownerLogin}/{repoName}</0>."
+#: src/components/settings/EmbeddingsKeySection.tsx
+msgid "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."
+msgstr "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."
+
#: src/components/CloneDialog.tsx
msgid "Your repositories"
msgstr "Your repositories"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index ab0de2ed6..b34499b5f 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -344,6 +344,7 @@
"9npOH9": ["Ōƥēń ƒĩĺē"],
"9o1bIV": [["behind"], " ƀēĥĩńď"],
"9oE4C3": ["ßŕōŵśē ŷōũŕ ŕēƥōś:"],
+ "9tJX8r": ["ßŷ ḿēàńĩńĝ"],
"9zb2WA": ["Ćōńńēćţĩńĝ"],
"A1taO8": ["Śēàŕćĥ"],
"A5CYnd": ["ßŕōķēń ĺĩńķ"],
@@ -496,7 +497,11 @@
"FCxvG5": ["Ƒĩŕśţ ĩţēḿ"],
"FEr96N": ["Ţĥēḿē"],
"FF5rwn": ["Ćōńńēćţ Ōƥēń Ķńōŵĺēďĝē ţō ōţĥēŕ ţōōĺś ŷōũ ũśē."],
+ "FNTx6u": ["Śēàŕćĥ \"", ["semanticSubmitQuery"], "\" ƀŷ ḿēàńĩńĝ"],
"FOGD7m": ["Ćŕēàţē śōḿēţĥĩńĝ ĝŕēàţ."],
+ "FOyCTr": [
+ "Ŷōũŕ ŌƥēńÀĨ ÀƤĨ ķēŷ, ũśēď ōńĺŷ ţō ćŕēàţē ēḿƀēďďĩńĝś ōƒ ŷōũŕ ćōńţēńţ ƒōŕ śēḿàńţĩć śēàŕćĥ. Śţōŕēď ōńćē ƒōŕ ţĥĩś ḿàćĥĩńē ĩń <0>~/.ōķ/śēćŕēţś.ŷḿĺ</0> (ŕēàďàƀĺē ōńĺŷ ƀŷ ŷōũŕ ũśēŕ àććōũńţ) àńď śĥàŕēď àćŕōśś àĺĺ ƥŕōĴēćţś. Ţũŕń ţĥē ƒēàţũŕē ōń ƥēŕ ƥŕōĴēćţ ĩń Ţĥĩś ƥŕōĴēćţ → Śēàŕćĥ."
+ ],
"FRYB1Q": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď à ḿàĺƒōŕḿēď ƀōďŷ"],
"FTUGgh": ["Ēńţēŕ à ŕēƥōśĩţōŕŷ ŨŔĹ ōŕ ōŵńēŕ/ŕēƥō"],
"FUMerq": ["Ćōũĺď ńōţ ēńàƀĺē śŷńć: ", ["detail"]],
@@ -772,6 +777,7 @@
"P6lAT3": ["Ƒōĺďēŕ ţàŕĝēţ: ", ["linkTitle"], ". Ćĺĩćķ ţō ōƥēń ţĥē ōvēŕvĩēŵ."],
"P8yDjG": ["Ńàḿē ćàń’ţ ƀē ēḿƥţŷ, \".\", \"..\", ōŕ ćōńţàĩń / ōŕ \\"],
"PB4upl": ["Ƒĩńď ƥŕēvĩōũś ḿàţćĥ"],
+ "PBwmDJ": ["Śēàŕćĥĩńĝ ƀŷ ḿēàńĩńĝ"],
"PKLY-1": ["Ōƥēńĩńĝ..."],
"PMyJ9C": ["Ńō ēďĩţ śēśśĩōń ŷēţ"],
"PQCdtv": ["\"", ["docName"], "\" ďōēśń'ţ ēxĩśţ."],
@@ -795,6 +801,7 @@
"QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],
"QWks14": ["À śĥōŕţ ĺĩńē śĥōŵń ũńďēŕ ţĥē ńàḿē ĩń ţĥē ţēḿƥĺàţē ĺĩśţ."],
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
+ "QlxHAH": ["Śĥōŵĩńĝ ŕēśũĺţś ƒōŕ \"", ["semanticResultsLabel"], "\""],
"QqBQu1": ["Ĺàƀēĺ <0>(vĩśĩƀĺē ĺĩńķ ţēxţ)</0>"],
"QyioBP": ["Ḿōvē ũƥ"],
"R0cyYB": [
@@ -921,9 +928,6 @@
"Vlc75q": ["Ķēēƥ ƒĩĺē ďēĺēţēď"],
"VuxVSP": ["Śţàŕţ śōũŕćē ćōḿƥĺēţĩōń"],
"VvS_k_": ["Ćōńƒĩĝ śĥàŕĩńĝ ĩś ńōŵ ĺōćàĺ-ōńĺŷ."],
- "Vz1amp": [
- "Ţĥē ÀƤĨ ķēŷ śēḿàńţĩć śēàŕćĥ ũśēś ţō ēḿƀēď ŷōũŕ ćōńţēńţ. Śţōŕēď ōńćē ƒōŕ ţĥĩś ḿàćĥĩńē àńď śĥàŕēď àćŕōśś àĺĺ ƥŕōĴēćţś. Ţũŕń ţĥē ƒēàţũŕē ōń ƥēŕ ƥŕōĴēćţ ĩń Ţĥĩś ƥŕōĴēćţ → Śēàŕćĥ."
- ],
"W-ntoW": ["ĥēàďĩńĝ-śĺũĝ"],
"W1qRuM": ["Ţĥĩś ďōćũḿēńţ ĩś àĺŕēàďŷ àćţĩvē ĩń ţĥē ēďĩţōŕ. Ũśē Ōƥēń ţō ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"W5A0Ly": ["Àń ũńēxƥēćţēď ēŕŕōŕ ōććũŕŕēď."],
@@ -987,6 +991,7 @@
"XtRoxT": ["Ƥàĝē ", ["pageNumber"]],
"XvPJaT": ["Ďĩƒƒ ĺàŷōũţ"],
"Xv_ijG": ["ĥţţƥś://ĝĩţĥũƀ.ćōḿ/ōŵńēŕ/ŕēƥō ōŕ ōŵńēŕ/ŕēƥō"],
+ "Xw_maT": ["Ţŷƥē à ǫũēŕŷ, ţĥēń ƥŕēśś ↵ ţō śēàŕćĥ ŷōũŕ ƥàĝēś ƀŷ ḿēàńĩńĝ."],
"XyOUTJ": ["Ēxĩţ ḿēŕĝē"],
"Y-Urt2": ["ßĺōćķ ḿàţĥ ēǫũàţĩōń ŕēńďēŕēď ŵĩţĥ ĶàŢēX ƒŕōḿ à ĹàŢēX śōũŕćē śţŕĩńĝ."],
"Y8ViJx": ["À ńēŵēŕ vēŕśĩōń ḿàŷ ĥàvē ƀēēń ďēƥĺōŷēď śĩńćē ţĥĩś ţàƀ ōƥēńēď."],
@@ -1368,6 +1373,13 @@
{ "one": ["Śĥōŵ ", "#", " àũţō-śàvē"], "other": ["Śĥōŵ ", "#", " àũţō-śàvēś"] }
]
],
+ "kCNU4q": [
+ "Ĩńďēxĩńĝ ŷōũŕ ƥàĝēś — ",
+ ["semanticIndexedCount"],
+ " ōƒ ",
+ ["semanticTotalCount"],
+ " ŕēàďŷ. Ŕēśũĺţś ḿàŷ ƀē ĩńćōḿƥĺēţē."
+ ],
"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],
"kDuh1E": ["Ƥàţĥ ŕēśōĺvēś ōũţśĩďē ţĥē ƥŕōĴēćţ"],
"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],
@@ -1544,6 +1556,7 @@
" · ",
["tabCount", "plural", { "one": ["#", " ţàƀ"], "other": ["#", " ţàƀś"] }]
],
+ "qEIFZu": ["Ķēŷ ēńďĩńĝ ĩń ", ["keyHint"]],
"qEue6Q": [" ōŕ "],
"qNOgUu": ["Ēďĩţś àţ ţĥē śōũŕćē ĺàńď ĥēŕē — ńō ćōƥŷ-ƥàśţē ďŕĩƒţ."],
"qRZh7J": ["Ĺēţ Ţàƀ ĺēàvē ţĥē śōũŕćē ēďĩţōŕ ĩńśţēàď ōƒ ĩńďēńţĩńĝ."],
@@ -1577,6 +1590,7 @@
["repoName"],
"</0>."
],
+ "rBc32v": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ — ƥŕēśś ↵ ţō ŕēţŕŷ"],
"rFw02Q": ["Ũƥĺōàďĩńĝ ", ["keyName"]],
"rJVoVX": ["Śōũŕćē ƒĩńď ŕēśũĺţś"],
"rQAQus": ["Ćōũĺďń'ţ śàvē ţēḿƥĺàţē: ", ["error"]],
@@ -1772,6 +1786,7 @@
"yEJ-sl": [
"Ţĥē ƥŕēvĩēŵ ƀĺōćķś ŕēśōũŕćēś ţĥàţ ďōń'ţ ḿēēţ ĩţś śēćũŕĩţŷ ŕũĺēś (ƒōŕ ēxàḿƥĺē ƥĺàĩń ĥţţƥ:// ŨŔĹś, ōŕ ćōďē ţĥàţ ũśēś ēvàĺ). Ţĥē ćōńţēńţ àƀōvē ḿàŷ ŕēńďēŕ ĩńćōḿƥĺēţēĺŷ."
],
+ "yFyZMJ": ["Ńō ƥàĝēś ḿàţćĥēď \"", ["semanticQueryText"], "\" ƀŷ ḿēàńĩńĝ."],
"yHikCO": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĝō-ţō-ĺĩńē ƥŕōḿƥţ."],
"yKu_3Y": ["Ŕēśţōŕē"],
"yLq4w4": ["Śēƥàŕàţōŕ"],
@@ -1827,6 +1842,7 @@
["pickedRelative"],
"</1> ƀēćàũśē ĩţ ćōńţàĩńś à <2>.ĝĩţ</2> ƒōĺďēŕ (ōńē .ōķ/ ƥēŕ ĝĩţ ŕēƥō). <3>Ćōńţēńţ ďĩŕēćţōŕŷ</3> ďēƒàũĺţś ţō <4>.</4> (ţĥē ŵĥōĺē ŕēƥō); ţŷƥē à śũƀ-ƒōĺďēŕ ţō ńàŕŕōŵ ĩţ."
],
+ "zXj1rA": ["Śēàŕćĥ ƀŷ ḿēàńĩńĝ"],
"zZ_I5K": ["Ōƥēń ƥŕōĴēćţ ḿēńũ"],
"zaXlhf": [
"Ţĥē ƥŕōƥēŕţĩēś ƀĺōćķ àţ ţĥē ţōƥ ōƒ ţĥĩś ďōć ĥàś à ƒōŕḿàţţĩńĝ ēŕŕōŕ. Śŵĩţćĥ ţō śōũŕćē ḿōďē ţō ƒĩx ĩţ."
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 2397597cd..c1147879e 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -837,6 +837,10 @@ msgstr ""
msgid "Bullet List"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "By meaning"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "By tag"
msgstr ""
@@ -1497,6 +1501,10 @@ msgstr ""
msgid "Couldn't reach GitHub. Try again?"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Couldn't reach the embeddings provider — press ↵ to retry"
+msgstr ""
+
#: src/editor/bubble-menu/EditWithAiBubbleButton.tsx
msgid "Couldn't read the selection — please try again."
msgstr ""
@@ -2667,6 +2675,10 @@ msgstr ""
msgid "Indexed {embedded} of {total} pages."
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Indexing your pages — {semanticIndexedCount} of {semanticTotalCount} ready. Results may be incomplete."
+msgstr ""
+
#: src/components/FrontmatterRow.tsx
msgid "inherited"
msgstr ""
@@ -2826,6 +2838,10 @@ msgstr ""
msgid "Keep my version"
msgstr ""
+#: src/components/settings/EmbeddingsKeySection.tsx
+msgid "Key ending in {keyHint}"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Keyboard shortcuts available in the editor and workspace."
msgstr ""
@@ -3460,6 +3476,10 @@ msgstr ""
msgid "No pages link here yet."
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "No pages matched \"{semanticQueryText}\" by meaning."
+msgstr ""
+
#: src/components/settings/OkignoreSection.tsx
msgid "No patterns yet. Type a folder or file name below to start hiding files."
msgstr ""
@@ -4657,10 +4677,18 @@ msgstr ""
msgid "Search"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Search \"{semanticSubmitQuery}\" by meaning"
+msgstr ""
+
#: src/components/EditorHeader.tsx
msgid "Search ({searchShortcut})"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Search by meaning"
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
msgid "Search emoji"
msgstr ""
@@ -4701,6 +4729,10 @@ msgstr ""
msgid "Searching"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Searching by meaning"
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Second item"
msgstr ""
@@ -4949,6 +4981,10 @@ msgstr ""
msgid "Showing first {truncatedShownCount} items — use search to find others"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Showing results for \"{semanticResultsLabel}\""
+msgstr ""
+
#. placeholder {0}: items.length
#: src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx
msgid "Showing top {0} headings — keep typing to narrow"
@@ -5311,10 +5347,6 @@ msgstr ""
msgid "The {targetNoun} could not be opened — try navigating to it manually."
msgstr ""
-#: src/components/settings/EmbeddingsKeySection.tsx
-msgid "The API key semantic search uses to embed your content. Stored once for this machine and shared across all projects. Turn the feature on per project in This project → Search."
-msgstr ""
-
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"
msgstr ""
@@ -5574,6 +5606,10 @@ msgstr ""
msgid "Two-page (odd)"
msgstr ""
+#: src/components/CommandPalette.tsx
+msgid "Type a query, then press ↵ to search your pages by meaning."
+msgstr ""
+
#: src/editor/components/CodePreviewEditModal.tsx
msgid "Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."
msgstr ""
@@ -5953,6 +5989,10 @@ msgstr ""
msgid "Your knowledge base is now on GitHub at <0>{ownerLogin}/{repoName}</0>."
msgstr ""
+#: src/components/settings/EmbeddingsKeySection.tsx
+msgid "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Your repositories"
msgstr ""
diff --git a/packages/app/tests/stress/command-palette-semantic.e2e.ts b/packages/app/tests/stress/command-palette-semantic.e2e.ts
new file mode 100644
index 000000000..e4a7c942b
--- /dev/null
+++ b/packages/app/tests/stress/command-palette-semantic.e2e.ts
@@ -0,0 +1,243 @@
+import type { Page } from '@playwright/test';
+import { expect, test } from './_helpers';
+
+const DESKTOP_VIEWPORT = { width: 1440, height: 900 } as const;
+
+const cmdkRoot = (page: Page) => page.locator('[cmdk-root]');
+const cmdkInput = (page: Page) => page.locator('[data-slot="command-input"]');
+const semanticPill = (page: Page) =>
+ page.locator('[data-testid="command-palette-filter-semantic"]');
+const tagPill = (page: Page) => page.locator('[data-testid="command-palette-filter-tag"]');
+const submitRow = (page: Page) => page.locator('[data-testid="command-palette-semantic-submit"]');
+const emptyNotice = (page: Page) => page.locator('[data-testid="command-palette-semantic-empty"]');
+const resultsGroup = (page: Page) =>
+ page.locator('[data-testid="command-palette-semantic-results"]');
+const indexingBanner = (page: Page) =>
+ page.locator('[data-testid="command-palette-semantic-indexing"]');
+
+const CAPABLE_STATUS = {
+ enabled: true,
+ keyPresent: true,
+ keySource: 'file',
+ keyHint: 'a1b2', // redacted last-4, matching the real /api/semantic-status shape
+ ready: true,
+ capable: true,
+ embedded: 3,
+ total: 3,
+} as const;
+
+async function fakeCapability(page: Page) {
+ await page.route('**/api/semantic-status', async (route) => {
+ await route.fulfill({ json: CAPABLE_STATUS });
+ });
+}
+
+async function openPalette(page: Page) {
+ await page.keyboard.press('ControlOrMeta+k');
+ await expect(cmdkRoot(page)).toBeVisible({ timeout: 2_000 });
+}
+
+test.describe('command-palette semantic mode — gate, pill, submit, sticky, escape', () => {
+ test('pill is hidden when semantic search is not set up (byte-identical gate)', async ({
+ page,
+ api,
+ }) => {
+ await api.seedDocs([{ name: 's001', markdown: '# s001\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s001');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ const statusResolved = page.waitForResponse((r) => r.url().includes('/api/semantic-status'), {
+ timeout: 15_000,
+ });
+ await openPalette(page);
+ await statusResolved;
+ await expect(tagPill(page)).toBeVisible();
+ await expect(semanticPill(page)).toHaveCount(0);
+ });
+
+ test('with capability the pill enters an exclusive mode showing the type-to-search prompt', async ({
+ page,
+ api,
+ }) => {
+ await fakeCapability(page);
+ await api.seedDocs([{ name: 's002', markdown: '# s002\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s002');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+
+ await expect(semanticPill(page)).toBeVisible();
+ await semanticPill(page).click();
+
+ await expect(semanticPill(page)).toHaveAttribute('aria-pressed', 'true');
+ await expect(cmdkInput(page)).toHaveAttribute('placeholder', 'Search by meaning');
+ await expect(emptyNotice(page)).toBeVisible();
+ });
+
+ test('typing never fires; Enter fires ONE /api/search with semantic:true + source:omnibar', async ({
+ page,
+ api,
+ }) => {
+ await fakeCapability(page);
+ const searchBodies: Array<Record<string, unknown>> = [];
+ await page.route('**/api/search', async (route) => {
+ searchBodies.push(route.request().postDataJSON() as Record<string, unknown>);
+ await route.fulfill({
+ json: {
+ results: [
+ {
+ kind: 'page',
+ path: 'session-token-refresh',
+ title: 'Session Token Refresh',
+ score: 9,
+ signals: { vector: 0.82 },
+ },
+ ],
+ },
+ });
+ });
+ await api.seedDocs([{ name: 's003', markdown: '# s003\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s003');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+ await semanticPill(page).click();
+
+ await page.keyboard.type('auth retries');
+ await expect(submitRow(page)).toBeVisible();
+ expect(searchBodies.length).toBe(0);
+
+ await page.keyboard.press('Enter');
+ await expect(resultsGroup(page)).toBeVisible({ timeout: 5_000 });
+ await expect(resultsGroup(page).getByText('Session Token Refresh')).toBeVisible();
+ expect(searchBodies.length).toBe(1);
+ expect(searchBodies[0]).toMatchObject({
+ semantic: true,
+ source: 'omnibar',
+ intent: 'full_text',
+ query: 'auth retries',
+ limit: 30,
+ });
+ });
+
+ test('editing after a fire holds the results (disabled + dimmed), arms the submit row, and re-fires on ↵', async ({
+ page,
+ api,
+ }) => {
+ await fakeCapability(page);
+ const searchBodies: Array<Record<string, unknown>> = [];
+ await page.route('**/api/search', async (route) => {
+ searchBodies.push(route.request().postDataJSON() as Record<string, unknown>);
+ await route.fulfill({
+ json: {
+ results: [
+ {
+ kind: 'page',
+ path: 'session-token-refresh',
+ title: 'Session Token Refresh',
+ score: 9,
+ },
+ ],
+ },
+ });
+ });
+ await api.seedDocs([{ name: 's004', markdown: '# s004\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s004');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+ await semanticPill(page).click();
+ await page.keyboard.type('auth');
+ await page.keyboard.press('Enter');
+
+ const resultRow = page.locator(
+ '[data-testid="command-palette-nav-file-session-token-refresh"]',
+ );
+ await expect(resultsGroup(page)).toBeVisible({ timeout: 5_000 });
+ await expect(resultsGroup(page)).toHaveAttribute('data-dimmed', 'false');
+ await expect(resultRow).toHaveAttribute('aria-disabled', 'false');
+ await expect(submitRow(page)).toHaveCount(0);
+ expect(searchBodies.length).toBe(1);
+
+ await page.keyboard.type(' retries');
+ await expect(submitRow(page)).toBeVisible();
+ await expect(submitRow(page)).toHaveAttribute('data-selected', 'true');
+ await expect(resultsGroup(page)).toHaveAttribute('data-dimmed', 'true');
+ await expect(resultRow).toHaveAttribute('aria-disabled', 'true');
+
+ await page.keyboard.press('Enter');
+ await expect.poll(() => searchBodies.length).toBe(2);
+ expect(searchBodies[1]).toMatchObject({
+ semantic: true,
+ source: 'omnibar',
+ query: 'auth retries',
+ });
+ });
+
+ test('Escape exits semantic mode first (palette stays open); a second Escape closes it', async ({
+ page,
+ api,
+ }) => {
+ await fakeCapability(page);
+ await api.seedDocs([{ name: 's005', markdown: '# s005\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s005');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+ await semanticPill(page).click();
+ await expect(semanticPill(page)).toHaveAttribute('aria-pressed', 'true');
+
+ await page.keyboard.press('Escape');
+ await expect(cmdkRoot(page)).toBeVisible();
+ await expect(semanticPill(page)).toHaveAttribute('aria-pressed', 'false');
+
+ await page.keyboard.press('Escape');
+ await expect(cmdkRoot(page)).toBeHidden({ timeout: 2_000 });
+ });
+
+ test('typed text carries into "By meaning" mode when the pill is clicked (not cleared)', async ({
+ page,
+ api,
+ }) => {
+ await fakeCapability(page);
+ await api.seedDocs([{ name: 's006', markdown: '# s006\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s006');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+ await page.keyboard.type('auth retries');
+ await semanticPill(page).click();
+ await expect(semanticPill(page)).toHaveAttribute('aria-pressed', 'true');
+ await expect(cmdkInput(page)).toHaveValue('auth retries');
+ await expect(submitRow(page)).toBeVisible();
+ });
+
+ test('shows an indexing banner with coverage while the corpus is not fully embedded', async ({
+ page,
+ api,
+ }) => {
+ await page.route('**/api/semantic-status', async (route) => {
+ await route.fulfill({ json: { ...CAPABLE_STATUS, embedded: 1, total: 4 } });
+ });
+ await api.seedDocs([{ name: 's007', markdown: '# s007\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s007');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+ await semanticPill(page).click();
+ await expect(indexingBanner(page)).toBeVisible();
+ await expect(indexingBanner(page)).toContainText('1 of 4');
+ });
+
+ test('no indexing banner when the corpus is fully embedded', async ({ page, api }) => {
+ await fakeCapability(page);
+ await api.seedDocs([{ name: 's008', markdown: '# s008\n\nBody.' }]);
+ await page.setViewportSize(DESKTOP_VIEWPORT);
+ await page.goto('/#/s008');
+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });
+ await openPalette(page);
+ await semanticPill(page).click();
+ await expect(emptyNotice(page)).toBeVisible(); // in semantic mode...
+ await expect(indexingBanner(page)).toBeHidden(); // ...but fully indexed, no banner
+ });
+});
diff --git a/packages/cli/src/commands/embeddings/index.ts b/packages/cli/src/commands/embeddings/index.ts
index 68c0ea80a..4f99133d1 100644
--- a/packages/cli/src/commands/embeddings/index.ts
+++ b/packages/cli/src/commands/embeddings/index.ts
@@ -23,7 +23,7 @@ async function readKey(): Promise<string> {
for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
return Buffer.concat(chunks).toString('utf-8').trim();
}
- return (await password({ message: 'Enter embeddings API key:' })).trim();
+ return (await password({ message: 'Enter OpenAI embeddings API key:' })).trim();
}
function readSemanticConfig(projectDir: string) {
@@ -57,7 +57,7 @@ async function fetchLiveCoverage(
function setKeyCommand(): Command {
return new Command('set-key')
- .description('Store the embeddings provider API key in ~/.ok/secrets.yml')
+ .description('Store your OpenAI embeddings API key in ~/.ok/secrets.yml')
.action(async () => {
const key = await readKey();
if (!key) {
@@ -67,7 +67,7 @@ function setKeyCommand(): Command {
}
await createEmbeddingsSecretStore().set(key);
process.stderr.write(
- '✓ Embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).\n' +
+ '✓ OpenAI embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).\n' +
'Now enable it per project — the easiest path is OK Desktop → Settings → This\n' +
'project → Search (a toggle with an egress-confirmation prompt), or run\n' +
'`ok embeddings enable` in the project folder.\n',
@@ -77,14 +77,14 @@ function setKeyCommand(): Command {
function clearKeyCommand(): Command {
return new Command('clear-key')
- .description('Remove the stored embeddings provider API key')
+ .description('Remove your stored OpenAI embeddings API key')
.action(async () => {
const { touched } = await clearEmbeddingsKeyFromAllBackends();
if (touched.length === 0) {
- process.stderr.write('No stored embeddings key found.\n');
+ process.stderr.write('No stored OpenAI embeddings key found.\n');
return;
}
- process.stderr.write(`✓ Embeddings API key cleared (${touched.join(', ')}).\n`);
+ process.stderr.write(`✓ OpenAI embeddings API key cleared (${touched.join(', ')}).\n`);
});
}
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index f0af373ee..91104d217 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -167,6 +167,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'search.semantic.dimensions',
'search.semantic.enabled',
'search.semantic.model',
+ 'search.semantic.similarityFloor',
]);
});
});
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index e39ed04ac..cce465fe6 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -230,6 +230,18 @@ export const ConfigSchema = z.looseObject({
"Optional output vector dimensions. Omit to use the model's native size (1536 for text-embedding-3-small). Set a smaller value (text-embedding-3 supports e.g. 512 / 1024) to shrink the on-disk cache, trading a little retrieval quality. Changing it re-embeds the corpus.",
})
.optional(),
+ similarityFloor: z
+ .number()
+ .min(0)
+ .max(1)
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description:
+ 'Optional hard cutoff: drop any "by meaning" match whose cosine similarity is below this value. Off by default (0) because retrieval is rank-based (the closest pages are returned regardless of absolute score) and the right cutoff is model-specific. Set it only to suppress weak matches for a specific provider/model whose cosine scale you know. Most setups should leave it unset and rely on the result-count cap.',
+ })
+ .optional(),
})
.default({
enabled: false,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index ba8715e79..7588e41c8 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -653,6 +653,7 @@ export {
SearchResultEntrySchema,
type SearchSemanticStatus,
SearchSemanticStatusSchema,
+ type SearchSource,
type SearchSuccess,
SearchSuccessSchema,
type SeedApplyRequest,
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index e9a7b208a..d79a20478 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -162,10 +162,13 @@ export const SearchRequestSchema = z
scope: z.string().optional(),
limit: z.number().int().nonnegative().optional(),
semantic: z.boolean().optional(),
+ source: z.enum(['omnibar', 'mcp', 'http']).optional(),
})
.loose() satisfies StandardSchemaV1;
export type SearchRequest = z.infer<typeof SearchRequestSchema>;
+export type SearchSource = NonNullable<SearchRequest['source']>;
+
export const SearchResultEntrySchema = z
.object({
kind: z.enum(['page', 'folder', 'content']),
@@ -195,6 +198,7 @@ export const SemanticIndexStatusSchema = z
enabled: z.boolean(),
keyPresent: z.boolean(),
keySource: z.enum(['file', 'env']).nullable(),
+ keyHint: z.string().nullable(),
ready: z.boolean(),
capable: z.boolean(),
embedded: z.number().int().nonnegative(),
diff --git a/packages/core/src/search/workspace-search.semantic.test.ts b/packages/core/src/search/workspace-search.semantic.test.ts
index a1bda667d..c2b83b4a5 100644
--- a/packages/core/src/search/workspace-search.semantic.test.ts
+++ b/packages/core/src/search/workspace-search.semantic.test.ts
@@ -57,7 +57,7 @@ describe('semantic ranking — candidate source + brackets-outer/RRF-body', () =
]);
const withSemantic = searchWorkspaceCorpus(corpus, 'auth retries', {
intent: 'full_text',
- semantic: { scores },
+ semantic: { scores, similarityFloor: 0.5 },
});
expect(ids(withSemantic)).toEqual(['guides/credential-rotation']);
expect(withSemantic[0].signals.vector).toBeCloseTo(0.82, 5);
@@ -66,10 +66,10 @@ describe('semantic ranking — candidate source + brackets-outer/RRF-body', () =
test('similarityFloor keeps a low-cosine vector-only doc out of the candidate pool', () => {
const docs = [page('recipes/sourdough', 'Sourdough', 'a recipe for sourdough bread')];
const corpus = createWorkspaceSearchCorpus(docs);
- const scores = new Map([['page:recipes/sourdough', 0.2]]); // below default floor 0.35
+ const scores = new Map([['page:recipes/sourdough', 0.2]]);
const results = searchWorkspaceCorpus(corpus, 'auth retries', {
intent: 'full_text',
- semantic: { scores },
+ semantic: { scores, similarityFloor: 0.5 },
});
expect(results.length).toBe(0);
});
@@ -101,7 +101,7 @@ describe('semantic ranking — candidate source + brackets-outer/RRF-body', () =
const scores = new Map([['page:auth/login', 0.2]]);
const results = searchWorkspaceCorpus(corpus, 'login', {
intent: 'full_text',
- semantic: { scores },
+ semantic: { scores, similarityFloor: 0.5 },
});
expect(results.length).toBe(1);
expect('vector' in results[0].signals).toBe(false);
@@ -124,7 +124,7 @@ describe('semantic ranking — candidate source + brackets-outer/RRF-body', () =
]);
const fused = searchWorkspaceCorpus(corpus, 'telemetry', {
intent: 'full_text',
- semantic: { scores },
+ semantic: { scores, similarityFloor: 0.5 },
});
expect(fused[0].document.path).toBe(bm25Second);
expect(fused[1].document.path).toBe(bm25Top);
@@ -143,4 +143,25 @@ describe('semantic ranking — candidate source + brackets-outer/RRF-body', () =
expect(results.length).toBe(2);
expect(ids(results).sort()).toEqual(['v/doc-0', 'v/doc-1']);
});
+
+ test('the default is rank-based: low cosines are admitted (no absolute cutoff), ordered by similarity', () => {
+ const docs = [
+ page('characters/edward', 'Edward', 'the crew hacker who breaks into networked systems'),
+ page('music/soundtrack', 'Soundtrack', 'jazz and blues from the series'),
+ ];
+ const corpus = createWorkspaceSearchCorpus(docs);
+ const noSemantic = searchWorkspaceCorpus(corpus, 'cybersecurity', { intent: 'full_text' });
+ expect(noSemantic.length).toBe(0); // zero token overlap — vector-only retrievable
+ const scores = new Map([
+ ['page:characters/edward', 0.13],
+ ['page:music/soundtrack', 0.08],
+ ]);
+ const results = searchWorkspaceCorpus(corpus, 'cybersecurity', {
+ intent: 'full_text',
+ semantic: { scores },
+ });
+ expect(ids(results)).toEqual(['characters/edward', 'music/soundtrack']);
+ expect(results[0].signals.vector).toBeCloseTo(0.13, 5);
+ expect(results[1].signals.vector).toBeCloseTo(0.08, 5);
+ });
});
diff --git a/packages/core/src/search/workspace-search.ts b/packages/core/src/search/workspace-search.ts
index 748d83673..5a93ff6ec 100644
--- a/packages/core/src/search/workspace-search.ts
+++ b/packages/core/src/search/workspace-search.ts
@@ -49,7 +49,7 @@ export const MAX_WORKSPACE_SEARCH_LIMIT = 100;
export const DEFAULT_RRF_K = 60;
export const DEFAULT_VECTOR_CANDIDATE_LIMIT = 64;
-export const DEFAULT_VECTOR_SIMILARITY_FLOOR = 0.35;
+export const DEFAULT_VECTOR_SIMILARITY_FLOOR = 0;
const WORKSPACE_SEARCH_SCHEMA = {
id: 'string',
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 3a1861eab..11181c1c9 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -126,6 +126,7 @@ import {
SaveVersionSuccessSchema,
SearchRequestSchema,
type SearchSemanticStatus,
+ type SearchSource,
type SearchSuccess,
SearchSuccessSchema,
SeedApplyRequestSchema,
@@ -1576,6 +1577,7 @@ export interface ApiExtensionOptions {
recentlyRemovedDocs?: RecentlyRemovedDocs;
serializeDoc?: (docName: string) => string | null;
semanticSearch?: SemanticSearchService;
+ getSemanticSimilarityFloor?: () => number | undefined;
embeddingsSecretsFile?: string;
}
@@ -1658,6 +1660,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
recentlyRemovedDocs,
serializeDoc,
semanticSearch,
+ getSemanticSimilarityFloor,
embeddingsSecretsFile,
ephemeral = false,
} = options;
@@ -9850,6 +9853,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return undefined;
}
+ function parseSearchSource(value: unknown): SearchSource {
+ return value === 'omnibar' || value === 'mcp' || value === 'http' ? value : 'http';
+ }
+
interface SemanticResolution {
input?: WorkspaceSemanticInput;
status?: SearchSemanticStatus;
@@ -9877,7 +9884,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const startedAt = performance.now();
const scores = await semanticSearch.queryScores(query, corpus.documents);
queryEmbedMs = performance.now() - startedAt;
- if (scores && scores.size > 0) input = { scores };
+ if (scores && scores.size > 0) {
+ const similarityFloor = getSemanticSimilarityFloor?.();
+ input = similarityFloor !== undefined ? { scores, similarityFloor } : { scores };
+ }
}
const status = semanticSearch.getStatus();
@@ -9924,6 +9934,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
scopes: WorkspaceSearchScope[] | undefined;
limit: number | undefined;
semanticParam: boolean | undefined;
+ source: SearchSource;
}): Promise<SearchSuccess> {
const startedAt = performance.now();
const corpus = await getWorkspaceSearchCorpus();
@@ -9958,6 +9969,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
: 'no_match';
recordSemanticQuery({
outcome,
+ source: params.source,
capable: semantic.capable,
embedded: semantic.status.coverage.embedded,
total: semantic.pageTotal,
@@ -10079,6 +10091,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
url.searchParams.get('scope') ?? url.searchParams.get('scopes'),
);
const semanticParam = parseSemanticParam(url.searchParams.get('semantic'));
+ const source = parseSearchSource(url.searchParams.get('source'));
const limitNum = limit === null ? undefined : Number(limit);
if (query.length > 200) {
@@ -10098,6 +10111,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
scopes,
limit: limitNum,
semanticParam,
+ source,
});
successResponse(res, 200, SearchSuccessSchema, body, { handler: 'search-get' });
} catch (e) {
@@ -10121,6 +10135,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const scopes = parseSearchScopes(body.scopes ?? body.scope);
const limit = typeof body.limit === 'number' ? body.limit : undefined;
const semanticParam = parseSemanticParam(body.semantic);
+ const source = parseSearchSource(body.source);
if (query.length > 200) {
errorResponse(
@@ -10139,6 +10154,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
scopes,
limit,
semanticParam,
+ source,
});
successResponse(res, 200, SearchSuccessSchema, responseBody, { handler: 'search-post' });
} catch (e) {
@@ -10883,12 +10899,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
embedded = status.embeddedCount;
}
const storedKey = await new FileEmbeddingsBackend(embeddingsSecretsFile).get();
- const keySource: 'file' | 'env' | null = storedKey
- ? 'file'
- : process.env[EMBEDDINGS_API_KEY_ENV]
- ? 'env'
- : null;
+ const envKey = process.env[EMBEDDINGS_API_KEY_ENV] ?? null;
+ const keySource: 'file' | 'env' | null = storedKey ? 'file' : envKey ? 'env' : null;
const keyPresent = keySource !== null;
+ const resolvedKey = storedKey ?? envKey;
+ const keyHint = resolvedKey && resolvedKey.length >= 8 ? resolvedKey.slice(-4) : null;
let total = 0;
for (const [docName] of getFileIndex()) {
if (!isSystemDoc(docName) && !isConfigDoc(docName) && !isHiddenDocName(docName)) {
@@ -10899,7 +10914,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
200,
SemanticIndexStatusSchema,
- { enabled, keyPresent, keySource, ready, capable, embedded, total },
+ { enabled, keyPresent, keySource, keyHint, ready, capable, embedded, total },
{ handler: 'semantic-status', extraHeaders: { 'Cache-Control': 'no-store' } },
);
} catch (e) {
diff --git a/packages/server/src/api-search-semantic-factory.test.ts b/packages/server/src/api-search-semantic-factory.test.ts
index acce49607..e0eea2224 100644
--- a/packages/server/src/api-search-semantic-factory.test.ts
+++ b/packages/server/src/api-search-semantic-factory.test.ts
@@ -116,7 +116,11 @@ beforeAll(async () => {
'search:\n semantic:\n enabled: true\n',
'utf-8',
);
- writeFileSync(join(tmpDir, '.ok', 'secrets.yml'), 'embeddings: sk-test-factory-key\n', 'utf-8');
+ writeFileSync(
+ join(tmpDir, '.ok', 'secrets.yml'),
+ 'OPENAI_API_KEY: sk-test-factory-key\n',
+ 'utf-8',
+ );
const shadowRepo = await initShadowRepo(tmpDir);
const embedder = createConceptEmbedder({ concepts: CONCEPTS });
@@ -178,6 +182,7 @@ describe('createServer boot — flag-ON semantic search (factory glue)', () => {
enabled: boolean;
keyPresent: boolean;
keySource: string | null;
+ keyHint: string | null;
ready: boolean;
capable: boolean;
embedded: number;
@@ -186,16 +191,18 @@ describe('createServer boot — flag-ON semantic search (factory glue)', () => {
expect(status.enabled).toBe(true);
expect(status.keyPresent).toBe(true);
expect(status.keySource).toBe('file');
+ expect(status.keyHint).toBe('-key');
expect(status.ready).toBe(true);
expect(status.capable).toBe(true);
expect(status.total).toBe(SERVED_PAGE_COUNT);
expect(status.embedded).toBe(SERVED_PAGE_COUNT);
});
- test('the omnibar call shape stays lexical through the same booted server', async () => {
+ test('the omnibar per-keystroke call shape stays lexical through the same booted server', async () => {
const { results, semantic } = await searchViaServer(server, {
query: 'auth retries',
intent: 'full_text',
+ source: 'omnibar',
});
for (const r of results ?? []) expect('vector' in r.signals).toBe(false);
expect(results?.find((r) => r.path === 'guides/credential-rotation')).toBeUndefined();
@@ -271,6 +278,63 @@ describe('createServer boot — project-local scope enforcement (egress safety)'
});
});
+describe('createServer boot — similarityFloor config reaches core ranking', () => {
+ test('a high project-local similarityFloor gates out a vector-only match the default would surface', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-sem-floor-'));
+ try {
+ writeFileSync(
+ join(dir, 'rotation.md'),
+ '# Credential Rotation\n\nThe credential rotation flow re-issues secrets when they expire.\n',
+ 'utf-8',
+ );
+ mkdirSync(join(dir, '.ok', 'local'), { recursive: true });
+ writeFileSync(
+ join(dir, '.ok', 'local', 'config.yml'),
+ 'search:\n semantic:\n enabled: true\n similarityFloor: 0.999\n',
+ 'utf-8',
+ );
+ writeFileSync(join(dir, '.ok', 'secrets.yml'), 'OPENAI_API_KEY: sk-test\n', 'utf-8');
+ const shadowRepo = await initShadowRepo(dir);
+ const srv = createServer({
+ contentDir: dir,
+ projectDir: dir,
+ quiet: true,
+ debounce: 60_000,
+ gitEnabled: false,
+ shadowRepo,
+ skipStateManifestCheck: true,
+ destroyTimeoutMs: 500,
+ configHomedirOverride: dir,
+ embedderLoader: () => Promise.resolve(createConceptEmbedder({ concepts: CONCEPTS })),
+ });
+ await srv.ready;
+ try {
+ const deadline = Date.now() + 20_000;
+ let result: SearchBody | undefined;
+ do {
+ result = await searchViaServer(srv, {
+ query: 'auth retries',
+ intent: 'full_text',
+ semantic: true,
+ });
+ if ((result.semantic?.coverage.embedded ?? 0) >= 1) break;
+ await new Promise((r) => setTimeout(r, 25));
+ } while (Date.now() < deadline);
+
+ expect(result?.semantic?.capable).toBe(true);
+ expect(result?.semantic?.coverage.embedded).toBe(1); // the doc embedded
+ expect(result?.results?.find((r) => r.path === 'rotation')).toBeUndefined();
+ for (const r of result?.results ?? []) expect('vector' in r.signals).toBe(false);
+ expect(result?.semantic?.applied).toBe(false);
+ } finally {
+ await srv.destroy();
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 30_000);
+});
+
describe('createServer boot — embeddings key set/clear handlers (Account control)', () => {
test('set-key writes the secrets file, status flips keyPresent, clear-key removes it', async () => {
const dir = mkdtempSync(join(tmpdir(), 'ok-sem-setkey-'));
diff --git a/packages/server/src/api-search-semantic.test.ts b/packages/server/src/api-search-semantic.test.ts
index f60fcb8cf..d1459d475 100644
--- a/packages/server/src/api-search-semantic.test.ts
+++ b/packages/server/src/api-search-semantic.test.ts
@@ -171,7 +171,7 @@ describe('POST /api/search — semantic (opt-in)', () => {
}
});
- test('the omnibar call shape (no semantic field) stays lexical and byte-identical', async () => {
+ test('the omnibar deliberate "by meaning" submit (semantic + source) fuses vector', async () => {
const dir = seed();
try {
const fileIndex = buildFileIndex(dir);
@@ -179,7 +179,25 @@ describe('POST /api/search — semantic (opt-in)', () => {
const { results, semantic } = await searchPost(
dir,
fileIndex,
- { query: 'auth retries', intent: 'full_text' },
+ { query: 'auth retries', intent: 'full_text', semantic: true, source: 'omnibar' },
+ service,
+ );
+ expect(results?.find((r) => r.path === 'guides/credential-rotation')).toBeDefined();
+ expect(semantic?.applied).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('the omnibar per-keystroke call (no semantic field) stays lexical and byte-identical', async () => {
+ const dir = seed();
+ try {
+ const fileIndex = buildFileIndex(dir);
+ const service = await makeService(fileIndex, { enabled: true });
+ const { results, semantic } = await searchPost(
+ dir,
+ fileIndex,
+ { query: 'auth retries', intent: 'full_text', source: 'omnibar' },
service,
);
expect(results?.find((r) => r.path === 'guides/credential-rotation')).toBeUndefined();
diff --git a/packages/server/src/embeddings/embeddings-telemetry.test.ts b/packages/server/src/embeddings/embeddings-telemetry.test.ts
index ca91f3946..419093780 100644
--- a/packages/server/src/embeddings/embeddings-telemetry.test.ts
+++ b/packages/server/src/embeddings/embeddings-telemetry.test.ts
@@ -17,6 +17,7 @@ describe('embeddings telemetry', () => {
recordEmbeddingRequestDuration('document', 123.4);
recordSemanticQuery({
outcome: 'applied',
+ source: 'mcp',
capable: true,
embedded: 5,
total: 40,
@@ -25,12 +26,22 @@ describe('embeddings telemetry', () => {
});
recordSemanticQuery({
outcome: 'incapable',
+ source: 'omnibar',
capable: false,
embedded: 0,
total: 0,
queryEmbedMs: null,
vectorContributors: 0,
});
+ recordSemanticQuery({
+ outcome: 'no_match',
+ source: 'http',
+ capable: true,
+ embedded: 3,
+ total: 9,
+ queryEmbedMs: 12,
+ vectorContributors: 0,
+ });
__resetEmbeddingsTelemetryForTesting();
}).not.toThrow();
});
diff --git a/packages/server/src/embeddings/embeddings-telemetry.ts b/packages/server/src/embeddings/embeddings-telemetry.ts
index 8b40281a1..2b0b586dc 100644
--- a/packages/server/src/embeddings/embeddings-telemetry.ts
+++ b/packages/server/src/embeddings/embeddings-telemetry.ts
@@ -1,3 +1,4 @@
+import type { SearchSource } from '@inkeep/open-knowledge-core';
import type { Counter, Histogram } from '@opentelemetry/api';
import { getLogger } from '../logger.ts';
import { getMeter } from '../telemetry.ts';
@@ -61,7 +62,7 @@ function queryTotalCounter(): Counter {
if (!_queryTotal) {
_queryTotal = getMeter().createCounter('ok.search.semantic_query_total', {
description:
- 'Semantic-requested searches, by outcome. Bounded label: outcome ∈ {applied, no_match, warming, incapable, provider_error}.',
+ 'Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.',
});
}
return _queryTotal;
@@ -91,17 +92,19 @@ export function recordEmbeddingRequestDuration(role: EmbeddingRoleLabel, ms: num
export function recordSemanticQuery(event: {
outcome: SemanticQueryOutcome;
+ source: SearchSource;
capable: boolean;
embedded: number;
total: number;
queryEmbedMs: number | null;
vectorContributors: number;
}): void {
- queryTotalCounter().add(1, { outcome: event.outcome });
+ queryTotalCounter().add(1, { outcome: event.outcome, source: event.source });
if (event.queryEmbedMs !== null) queryEmbedDurationHist().record(Math.max(0, event.queryEmbedMs));
log.debug(
{
outcome: event.outcome,
+ source: event.source,
capable: event.capable,
embedded: event.embedded,
total: event.total,
diff --git a/packages/server/src/embeddings/secrets-store.test.ts b/packages/server/src/embeddings/secrets-store.test.ts
index 115b1f484..16ffb4426 100644
--- a/packages/server/src/embeddings/secrets-store.test.ts
+++ b/packages/server/src/embeddings/secrets-store.test.ts
@@ -11,6 +11,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { parse } from 'yaml';
import {
clearEmbeddingsKeyFromAllBackends,
describeStoredEmbeddingsKey,
@@ -54,6 +55,21 @@ describe('FileEmbeddingsBackend', () => {
expect(statSync(secretsFile).mode & 0o777).toBe(0o600);
});
+ test('get() self-heals a world-readable file to 0600 on the read path (no write needed)', async () => {
+ mkdirSync(join(dir, '.ok'), { recursive: true });
+ writeFileSync(secretsFile, `OPENAI_API_KEY: ${KEY}\n`);
+ chmodSync(secretsFile, 0o644);
+ const store = new FileEmbeddingsBackend(secretsFile);
+ expect(await store.get()).toBe(KEY); // read still returns the key...
+ expect(statSync(secretsFile).mode & 0o777).toBe(0o600); // ...and tightened it
+ });
+
+ test('get() leaves an already-0600 file untouched', async () => {
+ await new FileEmbeddingsBackend(secretsFile).set(KEY); // written 0600
+ expect(await new FileEmbeddingsBackend(secretsFile).get()).toBe(KEY);
+ expect(statSync(secretsFile).mode & 0o777).toBe(0o600);
+ });
+
test('clear removes the key; get returns null again', async () => {
const store = new FileEmbeddingsBackend(secretsFile);
await store.set(KEY);
@@ -83,6 +99,31 @@ describe('FileEmbeddingsBackend', () => {
const store = new FileEmbeddingsBackend(secretsFile);
expect(await store.get()).toBeNull();
});
+
+ test('get() falls back to a key stored under the legacy `embeddings` field', async () => {
+ mkdirSync(join(dir, '.ok'), { recursive: true });
+ writeFileSync(secretsFile, `embeddings: ${KEY}\n`);
+ expect(await new FileEmbeddingsBackend(secretsFile).get()).toBe(KEY);
+ });
+
+ test('set() migrates the legacy field to OPENAI_API_KEY and drops it (self-clearing)', async () => {
+ mkdirSync(join(dir, '.ok'), { recursive: true });
+ writeFileSync(secretsFile, 'embeddings: old-key\nother: keep-me\n');
+ await new FileEmbeddingsBackend(secretsFile).set(KEY);
+ expect(await new FileEmbeddingsBackend(secretsFile).get()).toBe(KEY);
+ const data = parse(readFileSync(secretsFile, 'utf-8')) as Record<string, unknown>;
+ expect(data.OPENAI_API_KEY).toBe(KEY);
+ expect(data.embeddings).toBeUndefined(); // legacy field dropped
+ expect(data.other).toBe('keep-me'); // co-resident secrets preserved
+ });
+
+ test('clear() removes the legacy field too — no resurrection via the fallback', async () => {
+ mkdirSync(join(dir, '.ok'), { recursive: true });
+ writeFileSync(secretsFile, `embeddings: ${KEY}\n`);
+ const store = new FileEmbeddingsBackend(secretsFile);
+ await store.clear();
+ expect(await store.get()).toBeNull();
+ });
});
describe('makeLazyEmbeddingsKeyStore', () => {
diff --git a/packages/server/src/embeddings/secrets-store.ts b/packages/server/src/embeddings/secrets-store.ts
index 926cd930e..bbba9aa8c 100644
--- a/packages/server/src/embeddings/secrets-store.ts
+++ b/packages/server/src/embeddings/secrets-store.ts
@@ -1,10 +1,14 @@
-import { chmodSync, existsSync, readFileSync } from 'node:fs';
+import { chmodSync, existsSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import { parse as yamlParse, stringify as yamlStringify } from 'yaml';
import { tracedMkdirSync, tracedUnlinkSync, tracedWriteFileSync } from '../fs-traced.ts';
-const EMBEDDINGS_ACCOUNT = 'embeddings';
+/** `secrets.yml` field the embeddings API key is stored under — named
+ * `OPENAI_API_KEY` so it's self-evident to anyone who opens the file. */
+const SECRETS_KEY_FIELD = 'OPENAI_API_KEY';
+
+const LEGACY_KEY_FIELD = 'embeddings';
export function secretsFilePath(homedirOverride?: string): string {
return join(homedirOverride ?? homedir(), '.ok', 'secrets.yml');
@@ -28,8 +32,33 @@ export class FileEmbeddingsBackend implements EmbeddingsSecretStore {
this.secretsFile = secretsFile ?? secretsFilePath();
}
+ private tightenPermsIfLoose(): void {
+ let mode: number;
+ try {
+ mode = statSync(this.secretsFile).mode & 0o777;
+ } catch {
+ return;
+ }
+ if ((mode & 0o077) === 0) return; // already owner-only — nothing to repair
+ try {
+ chmodSync(this.secretsFile, 0o600);
+ process.stderr.write(
+ `[embeddings] ${this.secretsFile} was readable beyond your user account ` +
+ `(mode ${mode.toString(8)}); tightened to 600. It stores an API key.\n`,
+ );
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : 'unknown error';
+ process.stderr.write(
+ `[embeddings] ${this.secretsFile} is readable beyond your user account ` +
+ `(mode ${mode.toString(8)}) and could not be tightened (${msg}); your API key ` +
+ `remains exposed — run: chmod 600 ${this.secretsFile}\n`,
+ );
+ }
+ }
+
private read(): Record<string, unknown> {
if (!existsSync(this.secretsFile)) return {};
+ this.tightenPermsIfLoose();
try {
return (yamlParse(readFileSync(this.secretsFile, 'utf-8')) ?? {}) as Record<string, unknown>;
} catch (e) {
@@ -49,21 +78,24 @@ export class FileEmbeddingsBackend implements EmbeddingsSecretStore {
}
get(): Promise<string | null> {
- const value = this.read()[EMBEDDINGS_ACCOUNT];
+ const data = this.read();
+ const value = data[SECRETS_KEY_FIELD] ?? data[LEGACY_KEY_FIELD];
return Promise.resolve(typeof value === 'string' && value !== '' ? value : null);
}
set(key: string): Promise<void> {
const data = this.read();
- data[EMBEDDINGS_ACCOUNT] = key;
+ delete data[LEGACY_KEY_FIELD];
+ data[SECRETS_KEY_FIELD] = key;
this.write(data);
return Promise.resolve();
}
clear(): Promise<void> {
const data = this.read();
- if (EMBEDDINGS_ACCOUNT in data) {
- delete data[EMBEDDINGS_ACCOUNT];
+ if (SECRETS_KEY_FIELD in data || LEGACY_KEY_FIELD in data) {
+ delete data[SECRETS_KEY_FIELD];
+ delete data[LEGACY_KEY_FIELD];
if (Object.keys(data).length === 0) {
try {
tracedUnlinkSync(this.secretsFile);
diff --git a/packages/server/src/embeddings/semantic-config.ts b/packages/server/src/embeddings/semantic-config.ts
index 2fd1355d3..df6f7f249 100644
--- a/packages/server/src/embeddings/semantic-config.ts
+++ b/packages/server/src/embeddings/semantic-config.ts
@@ -6,6 +6,7 @@ export interface ResolvedSemanticConfig {
baseUrl: string;
model: string;
dimensions?: number;
+ similarityFloor?: number;
}
export function readProjectLocalSemanticConfig(
@@ -22,5 +23,6 @@ export function readProjectLocalSemanticConfig(
baseUrl: semantic?.baseUrl ?? DEFAULT_EMBEDDINGS_BASE_URL,
model: semantic?.model ?? DEFAULT_EMBEDDINGS_MODEL,
dimensions: semantic?.dimensions ?? undefined,
+ similarityFloor: semantic?.similarityFloor ?? undefined,
};
}
diff --git a/packages/server/src/mcp/tools/search.test.ts b/packages/server/src/mcp/tools/search.test.ts
index 8e1b00a0c..9bb949750 100644
--- a/packages/server/src/mcp/tools/search.test.ts
+++ b/packages/server/src/mcp/tools/search.test.ts
@@ -177,6 +177,7 @@ describe('search MCP tool — happy path', () => {
limit: 5,
scopes: ['page', 'content'],
semantic: true,
+ source: 'mcp',
});
const structured = result.structuredContent as {
diff --git a/packages/server/src/mcp/tools/search.ts b/packages/server/src/mcp/tools/search.ts
index 5f63fd1b0..e20013c9a 100644
--- a/packages/server/src/mcp/tools/search.ts
+++ b/packages/server/src/mcp/tools/search.ts
@@ -259,6 +259,7 @@ export function register(server: ServerInstance, deps: SearchDeps): void {
intent,
limit,
semantic: args.semantic ?? true,
+ source: 'mcp',
};
if (args.scopes) body.scopes = args.scopes;
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 029921abe..05a9093a3 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -679,6 +679,7 @@ export function createServer(options: ServerOptions): ServerInstance {
recentlyRemovedDocs,
serializeDoc,
semanticSearch,
+ getSemanticSimilarityFloor: () => readSemanticSearchConfig().similarityFloor,
embeddingsSecretsFile: secretsFilePath(configHomedirOverride),
ephemeral,
onReferencedAssetsCacheInvalidator: (invalidate) => {