Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Refactor global search: drop edit-chat indexes, add agent / skill body search
claw2b2043457efac
diff --git a/src/main/features/agents.ts b/src/main/features/agents.tsindex a73fcbae..32e0c16b 100644--- a/src/main/features/agents.ts+++ b/src/main/features/agents.ts@@ -44,7 +44,6 @@ import {import { listSkillSpecs } from '../model/core-agent/skill-registry';import { readDisabledSets, setAgentEnabled } from './component_enabled';import { renameAgentInMembers } from './group_chat/state';-import * as search from './search';export type AgentSource = 'builtin' | 'custom';@@ -894,7 +893,6 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {try { await fsp.rm(chatDir, { recursive: true, force: true }); }catch (err) { log.warn(`rm failed user=${uid} agent=${agentId}: ${(err as Error).message}`); }invalidateLineCount(path.join(chatDir, 'chat.jsonl'));- search.dropAgentChat(uid, agentId);}const sessionId = defaultAgentEditSessionId(uid, agentId);try { evictSession(sessionId); } catch { /* cache may not hold it */ }@@ -1061,8 +1059,7 @@ export async function getAgentChatMessages(userId: string, agentId: string, limiasync function _appendAgentChatMessage(userId: string, agentId: string, record: any): Promise<void> {const file = agentChatMsgsPath(userId, agentId);- const { msgIndex } = await appendJsonlAtomic(file, record);- search.indexAgentChatMessage(userId, agentId, msgIndex, record);+ await appendJsonlAtomic(file, record);}export async function clearAgentChat(userId: string, agentId: string): Promise<boolean> {@@ -1075,7 +1072,6 @@ export async function clearAgentChat(userId: string, agentId: string): Promise<b}}invalidateLineCount(agentChatMsgsPath(userId, agentId));- search.dropAgentChat(userId, agentId);// Also evict + drop the core-agent persistent session jsonl. Without this// the LLM retains its full prior context even though the UI history is// empty — same bug pattern as clearSkillChat (paths from before adiff --git a/src/main/features/search/index.ts b/src/main/features/search/index.tsindex a1b9e29e..fffc5984 100644--- a/src/main/features/search/index.ts+++ b/src/main/features/search/index.ts@@ -10,19 +10,26 @@* one stat per source file plus a re-tokenize for any whose mtime/size* moved.*- * Contexts (KB) are indexed by relPath only — directory + filename, not- * body. Full-text content lookup goes through the vector KB (kb_search- * tool). Chat-style kinds still tokenize message bodies and generate- * snippets lazily at query time.+ * Indexed kinds:+ * - `context` — KB tree, by relPath only (directory + filename, not+ * body). Full-text content goes through the vector KB.+ * - `chat` — main-conversation jsonl message bodies.+ *+ * Agents and skills are NOT indexed — `searchAgents` / `searchSkills`+ * call the existing list APIs and run an in-memory substring match at+ * query time. The list cardinality is small (typically < 50) so a token+ * inverted index would be over-engineered, and it sidesteps i18n+ * invalidation (description picks per current UI lang at query time).*/import * as fs from 'node:fs';+import * as fsp from 'node:fs/promises';import * as path from 'node:path';import {- WS_ROOT, userChatsDir, userSkillChatDir, userAgentChatDir,+ WS_ROOT, userChatsDir,userContextsIndexPath, userChatsIndexPath,- userSkillChatsIndexPath, userAgentChatsIndexPath,+ userSearchDir,} from '../../paths';import { getActiveUserId } from '../users';import { createLogger } from '../../logger';@@ -35,9 +42,8 @@ import * as indexer from './indexer';export {upsertContext, dropContext,- indexChatMessage, indexSkillChatMessage, indexAgentChatMessage,- reindexSkillChatFile,- dropChatConversation, dropSkillChat, dropAgentChat,+ indexChatMessage,+ dropChatConversation,flushAll,} from './indexer';@@ -56,7 +62,7 @@ interface SourceCache {}export interface SearchResult {- kind: 'context' | 'chat' | 'skill_chat' | 'agent_chat';+ kind: 'context' | 'chat' | 'agent' | 'skill';score: number;snippet: string;[extra: string]: unknown;@@ -222,58 +228,118 @@ export async function searchChats(userId: string, query: string): Promise<Search});}-export async function searchSkillChats(userId: string, query: string): Promise<SearchResult[]> {+// ── Agent / skill body search (in-memory, no persistent index) ──────────+//+// Score scheme (shared across both):+// name === q : 100+// name startsWith q : 50+// name includes q : 30+// description includes q : 10+// else : 0 (filtered out)+//+// All comparisons are case-insensitive. Description picks the current UI+// language via the renderer-side `pickDescription` resolver — we do the+// same lookup here against the bilingual fields directly to avoid a+// circular dep into core-agent.++function _matchScore(name: string, description: string, qLower: string): number {+ const n = (name || '').toLowerCase();+ const d = (description || '').toLowerCase();+ if (!qLower) return 0;+ if (n === qLower) return 100;+ if (n.startsWith(qLower)) return 50;+ if (n.includes(qLower)) return 30;+ if (d.includes(qLower)) return 10;+ return 0;+}++function _descSnippet(description: string, qLower: string): string {+ if (!description) return '';+ const flat = description.replace(/\s+/g, ' ');+ const lower = flat.toLowerCase();+ const idx = qLower ? lower.indexOf(qLower) : -1;+ if (idx < 0) return flat.slice(0, SNIPPET_RADIUS * 2);+ const start = Math.max(0, idx - SNIPPET_RADIUS);+ const end = Math.min(flat.length, idx + qLower.length + SNIPPET_RADIUS);+ return (start > 0 ? '…' : '') + flat.slice(start, end) + (end < flat.length ? '…' : '');+}++async function _currentLang(): Promise<'zh' | 'en'> {+ try {+ const { getCurrentLang } = await import('../../i18n');+ return getCurrentLang() === 'zh' ? 'zh' : 'en';+ } catch { return 'en'; }+}++function _pickDesc(item: { description_zh?: string; description_en?: string }, lang: 'zh' | 'en'): string {+ const primary = lang === 'zh' ? item.description_zh : item.description_en;+ if (primary && primary.trim()) return primary;+ const fallback = lang === 'zh' ? item.description_en : item.description_zh;+ return fallback || '';+}++export async function searchAgents(_userId: string, query: string): Promise<SearchResult[]> {const q = (query || '').trim();if (!q) return [];- const entry = await indexer.getEntry(userSkillChatsIndexPath(userId), 'skill_chat');- const tokens = tokenize(q);- const scores = _scoreIndex(entry.idx as RuntimeIndex, tokens);- const cache = _makeSourceCache();- return _topN<SearchResult>(scores, MAX_PER_KIND, (docId, score) => {- const doc = entry.idx.docs[docId] as Doc & { skill_id?: string; msg_index?: number; role?: string; time?: string };- if (!doc) return null;- const file = path.join(userSkillChatDir(userId, String(doc.skill_id)), 'chat.jsonl');- const msg = cache.jsonlMessage(file, Number(doc.msg_index));- return {- kind: 'skill_chat',- skill_id: doc.skill_id,- msg_index: doc.msg_index,- role: doc.role,- time: doc.time,- snippet: _makeSnippet(msg && typeof msg.content === 'string' ? msg.content : '', q),+ const qLower = q.toLowerCase();+ const lang = await _currentLang();+ const { listAgents } = await import('../agents');+ const list = await listAgents();+ const scored: SearchResult[] = [];+ for (const a of list) {+ const desc = _pickDesc(a, lang);+ const score = _matchScore(a.name || '', desc, qLower);+ if (score <= 0) continue;+ scored.push({+ kind: 'agent',+ id: a.agent_id,+ name: a.name || a.agent_id,+ description: desc,+ source: a.source,+ snippet: _descSnippet(desc, qLower) || (a.name || ''),score,- };- });+ });+ }+ scored.sort((a, b) =>+ b.score - a.score || String(a.name).localeCompare(String(b.name)));+ return scored.slice(0, MAX_PER_KIND);}-export async function searchAgentChats(userId: string, query: string): Promise<SearchResult[]> {+export async function searchSkills(_userId: string, query: string): Promise<SearchResult[]> {const q = (query || '').trim();if (!q) return [];- const entry = await indexer.getEntry(userAgentChatsIndexPath(userId), 'agent_chat');- const tokens = tokenize(q);- const scores = _scoreIndex(entry.idx as RuntimeIndex, tokens);- const cache = _makeSourceCache();- return _topN<SearchResult>(scores, MAX_PER_KIND, (docId, score) => {- const doc = entry.idx.docs[docId] as Doc & { agent_id?: string; msg_index?: number; role?: string; time?: string };- if (!doc) return null;- const file = path.join(userAgentChatDir(userId, String(doc.agent_id)), 'chat.jsonl');- const msg = cache.jsonlMessage(file, Number(doc.msg_index));- return {- kind: 'agent_chat',- agent_id: doc.agent_id,- msg_index: doc.msg_index,- role: doc.role,- time: doc.time,- snippet: _makeSnippet(msg && typeof msg.content === 'string' ? msg.content : '', q),+ const qLower = q.toLowerCase();+ const lang = await _currentLang();+ const { listSkills } = await import('../skills');+ const list = await listSkills();+ const scored: SearchResult[] = [];+ for (const s of list) {+ const desc = _pickDesc(s, lang);+ const score = _matchScore(s.name || s.id, desc, qLower);+ if (score <= 0) continue;+ scored.push({+ kind: 'skill',+ id: s.id,+ name: s.name || s.id,+ description: desc,+ source: s.source,+ snippet: _descSnippet(desc, qLower) || (s.name || s.id),score,- };- });+ });+ }+ scored.sort((a, b) =>+ b.score - a.score || String(a.name).localeCompare(String(b.name)));+ return scored.slice(0, MAX_PER_KIND);}/*** Run every kind's reconcile once — intended for startup or post-sync hooks.* Walks every user dir under WS_ROOT for per-user indexes. Runs in parallel* and logs progress so a long first-boot build shows up in the log.+ *+ * Also unlinks legacy `skill_chats.idx.json` / `agent_chats.idx.json` files+ * left behind by older builds — those scopes were dropped from search and+ * the files would otherwise sit forever as orphaned ~MBs in local/search/.*/export async function reconcileAll(): Promise<void> {const t0 = Date.now();@@ -286,8 +352,7 @@ export async function reconcileAll(): Promise<void> {if (uid === 'logs' || uid === 'builtin') continue;tasks.push(indexer.reconcileContextsIndex(uid));tasks.push(indexer.reconcileChatsIndex(uid));- tasks.push(indexer.reconcileSkillChatsIndex(uid));- tasks.push(indexer.reconcileAgentChatsIndex(uid));+ tasks.push(_unlinkLegacyIndexes(uid));}}const results = await Promise.allSettled(tasks);@@ -295,7 +360,18 @@ export async function reconcileAll(): Promise<void> {log.info(`reconcileAll done in ${Date.now() - t0}ms (${tasks.length} idx, ${failed} failed)`);}-export interface SearchAllOptions { limit?: number; scope?: 'all' | 'context' | 'chat' | 'skill' | 'agent' }+async function _unlinkLegacyIndexes(uid: string): Promise<void> {+ for (const name of ['skill_chats.idx.json', 'agent_chats.idx.json']) {+ const p = path.join(userSearchDir(uid), name);+ try { await fsp.unlink(p); }+ catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT') log.warn(`legacy idx unlink ${p}: ${(err as Error).message}`);+ }+ }+}++export interface SearchAllOptions { limit?: number; scope?: 'all' | 'context' | 'chat' | 'agent' | 'skill' }export async function searchAll(userId: string, query: string, { limit = 30, scope = 'all' }: SearchAllOptions = {},@@ -306,8 +382,8 @@ export async function searchAll(const tasks: Array<Promise<void>> = [];if (scope === 'all' || scope === 'context') tasks.push(searchContexts(q).then((r) => { buckets.push(...r); }));if (scope === 'all' || scope === 'chat') tasks.push(searchChats(userId, q).then((r) => { buckets.push(...r); }));- if (scope === 'all' || scope === 'skill') tasks.push(searchSkillChats(userId, q).then((r) => { buckets.push(...r); }));- if (scope === 'all' || scope === 'agent') tasks.push(searchAgentChats(userId, q).then((r) => { buckets.push(...r); }));+ if (scope === 'all' || scope === 'agent') tasks.push(searchAgents(userId, q).then((r) => { buckets.push(...r); }));+ if (scope === 'all' || scope === 'skill') tasks.push(searchSkills(userId, q).then((r) => { buckets.push(...r); }));await Promise.all(tasks);buckets.sort((a, b) => b.score - a.score);return { results: buckets.slice(0, limit), total: buckets.length };diff --git a/src/main/features/search/indexer.ts b/src/main/features/search/indexer.tsindex a60981fe..93135cae 100644--- a/src/main/features/search/indexer.ts+++ b/src/main/features/search/indexer.ts@@ -20,9 +20,8 @@ import * as path from 'node:path';import { Mutex } from 'async-mutex';import {- userContextsDir, userChatsDir, userSkillChatDir, userAgentChatDir,+ userContextsDir, userChatsDir,userContextsIndexPath, userChatsIndexPath,- userSkillChatsIndexPath, userAgentChatsIndexPath,} from '../../paths';import { getActiveUserId } from '../users';import { createLogger } from '../../logger';@@ -282,29 +281,14 @@ export function dropContext(userId: string, relPath: string): void {})().catch((err) => log.warn(`dropContext failed: ${err.message}`));}-// ── Chat-style indexes (chat / skill_chat / agent_chat) ──────────────────-// Each jsonl line is a doc; fileKey identifies the conversation.+// ── Chat index (main conversations only) ────────────────────────────────+// Each jsonl line is a doc; fileKey is the conversation id (cid). Skill /+// agent edit conversations used to share this code path through a+// `_CHAT_KINDS` registry; that was removed when those scopes were dropped+// from search — agent / skill bodies are now queried in-memory at request+// time via `listAgents` / `listSkills` (see features/search/index.ts).-type ChatStyleKind = 'chat' | 'skill_chat' | 'agent_chat';--interface ChatKindConfig {- idField: string;- idxPathFn: (uid: string) => string;- fileFn: (uid: string, key: string) => string;- listFn: (uid: string) => Promise<ChatFileInfo[]>;-}--const _CHAT_KINDS: Record<ChatStyleKind, ChatKindConfig> = {- chat: { idField: 'cid', idxPathFn: userChatsIndexPath,- fileFn: (uid, key) => path.join(userChatsDir(uid), `${key}.jsonl`),- listFn: _listUserChats },- skill_chat: { idField: 'skill_id', idxPathFn: userSkillChatsIndexPath,- fileFn: (uid, key) => path.join(userSkillChatDir(uid, key), 'chat.jsonl'),- listFn: _listSkillChats },- agent_chat: { idField: 'agent_id', idxPathFn: userAgentChatsIndexPath,- fileFn: (uid, key) => path.join(userAgentChatDir(uid, key), 'chat.jsonl'),- listFn: _listAgentChats },-};+type ChatStyleKind = 'chat';async function _listUserChats(userId: string): Promise<ChatFileInfo[]> {const root = userChatsDir(userId);@@ -320,31 +304,9 @@ async function _listUserChats(userId: string): Promise<ChatFileInfo[]> {}));}-async function _listChatStyleSubdirs(base: string, fileFn: (name: string) => string): Promise<ChatFileInfo[]> {- let dirs;- try { dirs = await fsp.readdir(base, { withFileTypes: true }); }- catch { return []; }- const out = await Promise.all(dirs.map(async (d) => {- if (!d.isDirectory()) return null;- const file = fileFn(d.name);- try {- const st = await fsp.stat(file);- return { fileKey: d.name, file, mtime: st.mtimeMs, size: st.size } as ChatFileInfo;- } catch { return null; }- }));- return out.filter((x): x is ChatFileInfo => x !== null);-}--function _listSkillChats(userId: string): Promise<ChatFileInfo[]> {- return _listChatStyleSubdirs(- path.join(userChatsDir(userId), 'skill'),- (name) => path.join(userSkillChatDir(userId, name), 'chat.jsonl'));-}--function _listAgentChats(userId: string): Promise<ChatFileInfo[]> {- return _listChatStyleSubdirs(- path.join(userChatsDir(userId), 'agent'),- (name) => path.join(userAgentChatDir(userId, name), 'chat.jsonl'));+function _chatIdxPath(uid: string): string { return userChatsIndexPath(uid); }+function _chatJsonlFile(uid: string, cid: string): string {+ return path.join(userChatsDir(uid), `${cid}.jsonl`);}function _docId(kind: IndexKind, fileKey: string, msgIndex: number): string {@@ -352,31 +314,27 @@ function _docId(kind: IndexKind, fileKey: string, msgIndex: number): string {}async function _reindexChatFile(- idx: RuntimeIndex, kind: ChatStyleKind, fileKey: string,- file: string, mtimeMs: number, size: number,+ idx: RuntimeIndex, fileKey: string, file: string, mtimeMs: number, size: number,): Promise<void> {- const cfg = _CHAT_KINDS[kind];_dropDocsByFileKey(idx, fileKey);const msgs = await _readJsonl(file);msgs.forEach((m, i) => {const text = _msgText(m);if (!text) return;const doc: Doc = {- fileKey, kind, msg_index: i,- [cfg.idField]: fileKey,+ fileKey, kind: 'chat', msg_index: i, cid: fileKey,role: m.role || '', time: m.time || '', len: text.length,};- _putDoc(idx, _docId(kind, fileKey, i), doc, text);+ _putDoc(idx, _docId('chat', fileKey, i), doc, text);});idx.files[fileKey] = { mtime: mtimeMs, size };}-async function _reconcileChatStyle(userId: string, kind: ChatStyleKind): Promise<void> {- const cfg = _CHAT_KINDS[kind];- const idxPath = cfg.idxPathFn(userId);- const files = await cfg.listFn(userId);+export async function reconcileChatsIndex(userId: string): Promise<void> {+ const idxPath = _chatIdxPath(userId);+ const files = await _listUserChats(userId);await _getLock(idxPath).runExclusive(async () => {- const entry = await _getEntry(idxPath, kind);+ const entry = await _getEntry(idxPath, 'chat');const seen = new Set<string>();let dirty = false;const toUpdate: ChatFileInfo[] = [];@@ -387,7 +345,7 @@ async function _reconcileChatStyle(userId: string, kind: ChatStyleKind): PromisetoUpdate.push(f);}for (const f of toUpdate) {- await _reindexChatFile(entry.idx, kind, f.fileKey, f.file, f.mtime, f.size);+ await _reindexChatFile(entry.idx, f.fileKey, f.file, f.mtime, f.size);dirty = true;}for (const fk of Object.keys(entry.idx.files)) {@@ -397,10 +355,6 @@ async function _reconcileChatStyle(userId: string, kind: ChatStyleKind): Promise});}-export const reconcileChatsIndex = (uid: string) => _reconcileChatStyle(uid, 'chat');-export const reconcileSkillChatsIndex = (uid: string) => _reconcileChatStyle(uid, 'skill_chat');-export const reconcileAgentChatsIndex = (uid: string) => _reconcileChatStyle(uid, 'agent_chat');-/*** Upsert a single chat message doc — the hot path on every appended message.*@@ -409,73 +363,36 @@ export const reconcileAgentChatsIndex = (uid: string) => _reconcileChatStyle(uid* and posting update — independent of conversation length.*/async function _upsertChatMessageDoc(- userId: string, kind: ChatStyleKind, fileKey: string,- msgIndex: number, msg: ChatMessage,+ userId: string, fileKey: string, msgIndex: number, msg: ChatMessage,): Promise<void> {- const cfg = _CHAT_KINDS[kind];const text = _msgText(msg);if (!text) return;- const idxPath = cfg.idxPathFn(userId);- const file = cfg.fileFn(userId, fileKey);+ const idxPath = _chatIdxPath(userId);+ const file = _chatJsonlFile(userId, fileKey);let st: fs.Stats | undefined;try { st = await fsp.stat(file); } catch { /* file may have been deleted */ }await _getLock(idxPath).runExclusive(async () => {- const entry = await _getEntry(idxPath, kind);+ const entry = await _getEntry(idxPath, 'chat');const doc: Doc = {- fileKey, kind, msg_index: msgIndex,- [cfg.idField]: fileKey,+ fileKey, kind: 'chat', msg_index: msgIndex, cid: fileKey,role: msg.role || '', time: msg.time || '', len: text.length,};- _putDoc(entry.idx, _docId(kind, fileKey, msgIndex), doc, text);+ _putDoc(entry.idx, _docId('chat', fileKey, msgIndex), doc, text);if (st) entry.idx.files[fileKey] = { mtime: st.mtimeMs, size: st.size };entry.dirty = true;});_markDirty(idxPath);}-/**- * Bulk re-index one chat file (used by reconcile + rename cascade). Drops- * every doc under `fileKey`, reads the jsonl, re-inserts each non-empty line.- * Callers already hold the per-idx lock.- */-async function _reindexOneChat(userId: string, kind: ChatStyleKind, fileKey: string): Promise<void> {- const cfg = _CHAT_KINDS[kind];- const idxPath = cfg.idxPathFn(userId);- const file = cfg.fileFn(userId, fileKey);- let st: fs.Stats;- try { st = await fsp.stat(file); } catch { return; }- await _getLock(idxPath).runExclusive(async () => {- const entry = await _getEntry(idxPath, kind);- await _reindexChatFile(entry.idx, kind, fileKey, file, st.mtimeMs, st.size);- entry.dirty = true;- });- _markDirty(idxPath);-}-export function indexChatMessage(userId: string, cid: string, msgIndex: number, msg: ChatMessage): void {- _upsertChatMessageDoc(userId, 'chat', cid, msgIndex, msg)+ _upsertChatMessageDoc(userId, cid, msgIndex, msg).catch((err) => log.warn(`index chat msg failed: ${err.message}`));}-export function indexSkillChatMessage(userId: string, skillId: string, msgIndex: number, msg: ChatMessage): void {- _upsertChatMessageDoc(userId, 'skill_chat', skillId, msgIndex, msg)- .catch((err) => log.warn(`index skill chat msg failed: ${err.message}`));-}-export function indexAgentChatMessage(userId: string, agentId: string, msgIndex: number, msg: ChatMessage): void {- _upsertChatMessageDoc(userId, 'agent_chat', agentId, msgIndex, msg)- .catch((err) => log.warn(`index agent chat msg failed: ${err.message}`));-}--// Bulk rebuild for a renamed conversation (no per-message context available).-export function reindexSkillChatFile(userId: string, skillId: string): void {- _reindexOneChat(userId, 'skill_chat', skillId)- .catch((err) => log.warn(`reindex skill chat failed: ${err.message}`));-}-async function _dropChatStyleFile(userId: string, kind: ChatStyleKind, fileKey: string): Promise<void> {- const cfg = _CHAT_KINDS[kind];- const idxPath = cfg.idxPathFn(userId);+async function _dropChatFile(userId: string, fileKey: string): Promise<void> {+ const idxPath = _chatIdxPath(userId);await _getLock(idxPath).runExclusive(async () => {- const entry = await _getEntry(idxPath, kind);+ const entry = await _getEntry(idxPath, 'chat');if (!entry.idx.files[fileKey]) return;_dropDocsByFileKey(entry.idx, fileKey);entry.dirty = true;@@ -484,13 +401,7 @@ async function _dropChatStyleFile(userId: string, kind: ChatStyleKind, fileKey:}export function dropChatConversation(userId: string, cid: string): void {- _dropChatStyleFile(userId, 'chat', cid).catch(() => {});-}-export function dropSkillChat(userId: string, skillId: string): void {- _dropChatStyleFile(userId, 'skill_chat', skillId).catch(() => {});-}-export function dropAgentChat(userId: string, agentId: string): void {- _dropChatStyleFile(userId, 'agent_chat', agentId).catch(() => {});+ _dropChatFile(userId, cid).catch(() => {});}// ── Internal handle for query-side reads ─────────────────────────────────diff --git a/src/main/features/search/storage.ts b/src/main/features/search/storage.tsindex 49bf5a78..fad4127c 100644--- a/src/main/features/search/storage.ts+++ b/src/main/features/search/storage.ts@@ -4,7 +4,7 @@* Schema (JSON, one file per kind):* {* "version": 2,- * "kind": "context" | "chat" | "skill_chat" | "agent_chat",+ * "kind": "context" | "chat",* "files": { "<fileKey>": { "mtime": number, "size": number } },* "docs": { "<docId>": { kind, fileKey, ...kindFields, len } },* "postings": { "<token>": [[docId, tf], ...] }@@ -12,7 +12,9 @@** The shape is intentionally hand-rollable JSON — no FTS engine, no native* dep. Reconciliation by mtime+size makes this self-healing if an edit- * happens out-of-band (sync, manual touch).+ * happens out-of-band (sync, manual touch). `skill_chat` / `agent_chat`+ * kinds existed in earlier builds; their .idx.json files are now stale and+ * unlinked at startup by `reconcileAll` in features/search/index.ts.*/import * as fs from 'node:fs';@@ -27,7 +29,7 @@ const fsp = fs.promises;// rebuild on next reconcile.export const SCHEMA_VERSION = 3;-export type IndexKind = 'context' | 'chat' | 'skill_chat' | 'agent_chat';+export type IndexKind = 'context' | 'chat';export interface FileMeta { mtime: number; size: number }diff --git a/src/main/features/skills.ts b/src/main/features/skills.tsindex e06bd115..057fd23d 100644--- a/src/main/features/skills.ts+++ b/src/main/features/skills.ts@@ -43,7 +43,6 @@ import {nowIso, readJson, writeJson, writeTextAtomicSync,appendJsonlAtomic, invalidateLineCount, readJsonl,} from '../storage';-import * as search from './search';import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';import { readDisabledSets, setSkillEnabled } from './component_enabled';@@ -601,8 +600,6 @@ export async function updateCustomSkill(const m = await loadSkillChatMeta(uid, newName);m.session_id = defaultSkillSessionId(uid, newName);await saveSkillChatMeta(uid, newName, m);- search.dropSkillChat(uid, skillId);- search.reindexSkillChatFile(uid, newName);} catch (err) {log.warn(`rename user=${uid} ${oldChatDir} -> ${newChatDir} failed: ${(err as Error).message}`);}@@ -648,7 +645,6 @@ export async function deleteCustomSkill(skillId: string): Promise<boolean> {try { fs.rmSync(chatDir, { recursive: true, force: true }); }catch (err) { log.warn(`rm failed user=${uid} skill=${skillId}: ${(err as Error).message}`); }invalidateLineCount(path.join(chatDir, 'chat.jsonl'));- search.dropSkillChat(uid, skillId);}const sessionId = defaultSkillSessionId(uid, skillId);try { evictSession(sessionId); } catch { /* cache may not hold it */ }@@ -987,8 +983,7 @@ export async function getSkillChatMessages(userId: string, skillId: string, limiasync function _appendSkillChatMessage(userId: string, skillId: string, record: any): Promise<void> {const file = skillChatMsgsPath(userId, skillId);- const { msgIndex } = await appendJsonlAtomic(file, record);- search.indexSkillChatMessage(userId, skillId, msgIndex, record);+ await appendJsonlAtomic(file, record);}export async function clearSkillChat(userId: string, skillId: string): Promise<boolean> {@@ -1000,7 +995,6 @@ export async function clearSkillChat(userId: string, skillId: string): Promise<b}}invalidateLineCount(skillChatMsgsPath(userId, skillId));- search.dropSkillChat(userId, skillId);// Also evict + drop the core-agent persistent session jsonl. Without this// the LLM retains its full prior context (tool calls, paths, file contents)// even though the UI history is empty — visible as the LLM "remembering"diff --git a/src/main/paths.ts b/src/main/paths.tsindex eff1e3e1..9c918b12 100644--- a/src/main/paths.ts+++ b/src/main/paths.ts@@ -22,9 +22,8 @@* agents/<agent_id>/ skills/<skill_id>/ meta/<agent_id>/* config/preferences.json* local/ ← 🔒 本机域(永不同步)- * contexts_tmp/* config/ ← auth-profiles.json + web-search-cache.json- * search/ ← contexts / chats / skill_chats / agent_chats idx+ * search/ ← contexts / chats inverted idx (agent / skill bodies queried in-memory at request time)** Runtime overrides:* ORKAS_WORKSPACE_ROOT point data root elsewhere (src/main/index.ts sets this in packaged builds; env var name predates the dir rename — kept for stability)@@ -140,8 +139,6 @@ export const userPreferencesFile = (uid: string) => path.join(userCloudConfigDirexport const userComponentEnabledFile = (uid: string) => path.join(userCloudConfigDir(uid), 'component-enabled.json');// ── Local-only per-user (不同步) ─────────────────────────────────────────-// 待整理中转区(本地工作区,不云同步)-export const userContextsTmpDir = (uid: string) => path.join(userLocalRoot(uid), 'contexts_tmp');// 本机凭证 + provider 缓存:CORE_AGENT_AUTH_DIR 由 activateUser() pin 到这里,// core-agent 的 auth store 与 web-search provider cache 都落在同一目录。@@ -150,12 +147,12 @@ export const userAuthProfilesFile = (uid: string) => path.join(userLocalConfigDiexport const userWebSearchCache = (uid: string) => path.join(userLocalConfigDir(uid), 'web-search-cache.json');export const userReflectionStateFile = (uid: string) => path.join(userLocalConfigDir(uid), 'reflection-state.json');-// 本地搜索索引(派生数据,reconcile 自愈,永不同步)+// 本地搜索索引(派生数据,reconcile 自愈,永不同步)。+// 当前只为主对话 + 知识库建持久化倒排;智能体 / 技能本体改成 listAgents /+// listSkills 内存即查(数据集小、UI 语言切换不用重建索引)。export const userSearchDir = (uid: string) => path.join(userLocalRoot(uid), 'search');export const userContextsIndexPath = (uid: string) => path.join(userSearchDir(uid), 'contexts.idx.json');export const userChatsIndexPath = (uid: string) => path.join(userSearchDir(uid), 'chats.idx.json');-export const userSkillChatsIndexPath = (uid: string) => path.join(userSearchDir(uid), 'skill_chats.idx.json');-export const userAgentChatsIndexPath = (uid: string) => path.join(userSearchDir(uid), 'agent_chats.idx.json');// 超大工具输出(>50K 字符)落盘副本:tool_result 里只留 preview + 文件引用,// 模型真要看完整原文时调 read_file(path) 拉回。按 session_id 分子目录,@@ -259,11 +256,17 @@ export function ensureUserLayout(uid: string): void {// userMetaDir 已废弃 —— per-agent meta 落 `agents/<aid>/meta/` 子目录,// agent 创建时按需 mkdir,不需要顶层占位。userCloudConfigDir(uid),- userContextsTmpDir(uid),userLocalConfigDir(uid),userSearchDir(uid),userFileCacheDir(uid),userToolResultsDir(uid),];for (const d of dirs) fs.mkdirSync(d, { recursive: true });++ // Legacy sweep: `contexts_tmp/` was the staging area for the retired+ // two-region KB design (see features/contexts.ts header). Older builds+ // created the empty dir on every activate; remove it once if still+ // present + empty, leave it alone if a user somehow stuffed files there.+ const legacyContextsTmp = path.join(userLocalRoot(uid), 'contexts_tmp');+ try { fs.rmdirSync(legacyContextsTmp); } catch { /* ENOENT or ENOTEMPTY — both fine */ }}diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex e9d52f13..78ba4d1e 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -673,6 +673,8 @@<div class="search-tabs" id="search-tabs" role="tablist"><button class="search-tab is-active" data-tab="all" data-i18n="search.tab.all">全部</button><button class="search-tab" data-tab="chat" data-i18n="search.tab.chat">对话</button>+ <button class="search-tab" data-tab="agent" data-i18n="search.tab.agent">智能体</button>+ <button class="search-tab" data-tab="skill" data-i18n="search.tab.skill">技能</button><button class="search-tab" data-tab="context" data-i18n="search.tab.context">知识库</button></div><div class="search-body" id="search-body">diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 88a595ef..b803dec2 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -477,14 +477,20 @@"search.failed": "Search failed: {msg}","search.tab.all": "All","search.tab.chat": "Chats",+ "search.tab.agent": "Agents",+ "search.tab.skill": "Skills","search.tab.context": "Knowledge","search.section.chat": "Chats",+ "search.section.agent": "Agents",+ "search.section.skill": "Skills","search.section.context": "Knowledge","search.show_more": "View more","search.scope.context": "Knowledge","search.scope.chat": "Conversations",- "search.scope.skill_chat": "Skill edits",- "search.scope.agent_chat": "Agent edits",+ "search.scope.agent": "Agent",+ "search.scope.skill": "Skill",+ "search.source.custom": "Custom",+ "search.source.builtin": "Built-in","search.no_results": "No results for \"{query}\"","search.role.user": "Me","search.role.ai": "AI",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 14d64a85..4dbb4edf 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -477,14 +477,20 @@"search.failed": "搜索失败: {msg}","search.tab.all": "全部","search.tab.chat": "对话",+ "search.tab.agent": "智能体",+ "search.tab.skill": "技能","search.tab.context": "知识库","search.section.chat": "对话",+ "search.section.agent": "智能体",+ "search.section.skill": "技能","search.section.context": "知识库","search.show_more": "查看更多","search.scope.context": "知识库","search.scope.chat": "对话",- "search.scope.skill_chat": "技能编辑",- "search.scope.agent_chat": "智能体编辑",+ "search.scope.agent": "智能体",+ "search.scope.skill": "技能",+ "search.source.custom": "自定义",+ "search.source.builtin": "内置","search.no_results": "未找到「{query}」相关内容","search.role.user": "我","search.role.ai": "AI",diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.jsindex e8404233..82d0a038 100644--- a/src/renderer/modules/search.js+++ b/src/renderer/modules/search.js@@ -9,7 +9,7 @@ const _SEARCH_FETCH_LIMIT = 200; // backend cap; we filter/slice locally per tconst _SEARCH_ALL_PER_SECTION = 10; // "all" tab shows up to N per section, overflow → 查看更多let _searchTimer = null;let _searchSeq = 0;-let _searchTab = 'all'; // 'all' | 'chat' | 'context'+let _searchTab = 'all'; // 'all' | 'chat' | 'agent' | 'skill' | 'context'let _searchResults = [];let _searchActiveIdx = -1;let _searchLastQuery = '';@@ -33,19 +33,28 @@ function _bindGlobalSearch() {overlay?.addEventListener('click', (e) => {if (e.target === overlay) closeGlobalSearch();});- // Global Cmd/Ctrl+K shortcut+ // Global Cmd/Ctrl+K shortcut. Toggle behaviour: if the overlay is already+ // open, a second Cmd+K closes it (parity with Cmd+K-style command palettes+ // in VS Code / Notion / etc.) — without this, the keystroke would re-call+ // openGlobalSearch() and reset query + tab state mid-typing.document.addEventListener('keydown', (e) => {if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {e.preventDefault();- openGlobalSearch();+ const overlay = document.getElementById('search-overlay');+ if (overlay && overlay.style.display !== 'none') {+ closeGlobalSearch();+ } else {+ openGlobalSearch();+ }} else if (e.key === 'Escape' && document.getElementById('search-overlay').style.display !== 'none') {closeGlobalSearch();}});}+const _SEARCH_VALID_TABS = new Set(['all', 'chat', 'agent', 'skill', 'context']);function _setSearchTab(tab) {- if (!tab || (tab !== 'all' && tab !== 'chat' && tab !== 'context')) return;+ if (!tab || !_SEARCH_VALID_TABS.has(tab)) return;_searchTab = tab;document.querySelectorAll('.search-tab').forEach((b) => {b.classList.toggle('is-active', b.dataset.tab === tab);@@ -117,17 +126,28 @@ async function _runSearchNow(queryArg) {}}-// Split results into 2 buckets per the tab-grouping spec:-// - chats: chat + skill_chat + agent_chat, sorted by time DESC-// - contexts: context kind only, sorted by path-segment count ASC then path alpha-// Chats sort by time (recency is the useful signal); contexts sort by-// "shortest directory path first" so root-level files come before deeply-// nested ones.+// Split results into 4 buckets per the tab-grouping spec:+// - chats: main-conversation messages, sorted by time DESC (recency)+// - agents: agent body matches, sorted by score DESC then name+// - skills: skill body matches, sorted by score DESC then name+// - contexts: KB path matches, sorted by directory depth ASC then path+// Skill/agent EDIT conversations were removed from search — only the+// main-conversation jsonls feed the chats bucket.function _partitionSearchResults(results) {const chats = results- .filter((r) => r.kind === 'chat' || r.kind === 'skill_chat' || r.kind === 'agent_chat')+ .filter((r) => r.kind === 'chat').slice().sort((a, b) => String(b.time || '').localeCompare(String(a.time || '')));+ const agents = results+ .filter((r) => r.kind === 'agent')+ .slice()+ .sort((a, b) => (b.score || 0) - (a.score || 0)+ || String(a.name || '').localeCompare(String(b.name || '')));+ const skills = results+ .filter((r) => r.kind === 'skill')+ .slice()+ .sort((a, b) => (b.score || 0) - (a.score || 0)+ || String(a.name || '').localeCompare(String(b.name || '')));const contexts = results.filter((r) => r.kind === 'context').slice()@@ -137,7 +157,7 @@ function _partitionSearchResults(results) {if (da !== db) return da - db;return pa.localeCompare(pb);});- return { chats, contexts };+ return { chats, agents, skills, contexts };}function _renderSearchEmptyState() {@@ -184,10 +204,15 @@ function _highlightSnippet(snippet, query) {// Labels resolved lazily via t() so switching lang re-labels future renders.const _SEARCH_KIND_META = {- context: { labelKey: 'search.scope.context', cls: 'is-context' },- chat: { labelKey: 'search.scope.chat', cls: 'is-chat' },- skill_chat: { labelKey: 'search.scope.skill_chat', cls: 'is-skill' },- agent_chat: { labelKey: 'search.scope.agent_chat', cls: 'is-agent' },+ context: { labelKey: 'search.scope.context', cls: 'is-context' },+ chat: { labelKey: 'search.scope.chat', cls: 'is-chat' },+ agent: { labelKey: 'search.scope.agent', cls: 'is-agent' },+ skill: { labelKey: 'search.scope.skill', cls: 'is-skill' },+};++const _SEARCH_SOURCE_LABEL = {+ custom: 'search.source.custom',+ builtin: 'search.source.builtin',};// Render one result into HTML. Uses the shared `_renderSearchRow` helper for@@ -204,18 +229,10 @@ function _renderSearchRow(r, dataIdx, query) {} else if (r.kind === 'chat') {title = r.conv_title || t('chat.new_conv_title');sub = `${roleLabel(r.role)} · ${formatTime(r.time || '')}`;- } else if (r.kind === 'skill_chat') {- title = r.skill_id;- sub = `${roleLabel(r.role)} · ${formatTime(r.time || '')}`;- } else if (r.kind === 'agent_chat') {- // agent_id is an opaque hex (e.g. "51bc903ae443") — never show that- // to the user. Resolve through the global agents cache loaded on- // view-mount; fall back to the id only if the cache hasn't filled.- const agent = (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache))- ? _agentsCache.find((a) => a && a.agent_id === r.agent_id)- : null;- title = (agent && agent.name) || r.agent_id;- sub = `${roleLabel(r.role)} · ${formatTime(r.time || '')}`;+ } else if (r.kind === 'agent' || r.kind === 'skill') {+ title = r.name || r.id;+ const srcKey = _SEARCH_SOURCE_LABEL[r.source] || '';+ sub = srcKey ? t(srcKey) : '';}const active = dataIdx === _searchActiveIdx ? ' active' : '';return `@@ -243,30 +260,26 @@ function _renderSearchResults(query) {body.innerHTML = `<div class="search-empty">${escapeHtml(t('search.no_results', { query }))}</div>`;return;}- const { chats, contexts } = _partitionSearchResults(_searchResults);+ const { chats, agents, skills, contexts } = _partitionSearchResults(_searchResults);const parts = [];const visible = [];- // "全部" 显示 chats (前 10) + contexts (前 10),超出给"查看更多"→对应 tab。- // "对话" 只显示 chats;"知识库" 只显示 contexts。- if (_searchTab === 'all' || _searchTab === 'chat') {- const slice = _searchTab === 'all' ? chats.slice(0, _SEARCH_ALL_PER_SECTION) : chats;- if (slice.length) {- parts.push(`<div class="search-section-label">${escapeHtml(t('search.section.chat'))}</div>`);- for (const r of slice) { parts.push(_renderSearchRow(r, visible.length, query)); visible.push(r); }- if (_searchTab === 'all' && chats.length > slice.length) {- parts.push(`<button class="search-show-more" data-goto="chat">${escapeHtml(t('search.show_more'))} (${chats.length})</button>`);- }- }- }- if (_searchTab === 'all' || _searchTab === 'context') {- const slice = _searchTab === 'all' ? contexts.slice(0, _SEARCH_ALL_PER_SECTION) : contexts;- if (slice.length) {- parts.push(`<div class="search-section-label">${escapeHtml(t('search.section.context'))}</div>`);- for (const r of slice) { parts.push(_renderSearchRow(r, visible.length, query)); visible.push(r); }- if (_searchTab === 'all' && contexts.length > slice.length) {- parts.push(`<button class="search-show-more" data-goto="context">${escapeHtml(t('search.show_more'))} (${contexts.length})</button>`);- }+ // "全部" tab 顺序:对话 → 智能体 → 技能 → 知识库;每段最多 _SEARCH_ALL_PER_SECTION 条,+ // 超出给"查看更多"按钮跳到对应 tab。其它 tab 只显示自己那段(不截顶,让用户能滚完)。+ const sections = [+ { tab: 'chat', bucket: chats, labelKey: 'search.section.chat' },+ { tab: 'agent', bucket: agents, labelKey: 'search.section.agent' },+ { tab: 'skill', bucket: skills, labelKey: 'search.section.skill' },+ { tab: 'context', bucket: contexts, labelKey: 'search.section.context' },+ ];+ for (const s of sections) {+ if (_searchTab !== 'all' && _searchTab !== s.tab) continue;+ const slice = _searchTab === 'all' ? s.bucket.slice(0, _SEARCH_ALL_PER_SECTION) : s.bucket;+ if (!slice.length) continue;+ parts.push(`<div class="search-section-label">${escapeHtml(t(s.labelKey))}</div>`);+ for (const r of slice) { parts.push(_renderSearchRow(r, visible.length, query)); visible.push(r); }+ if (_searchTab === 'all' && s.bucket.length > slice.length) {+ parts.push(`<button class="search-show-more" data-goto="${s.tab}">${escapeHtml(t('search.show_more'))} (${s.bucket.length})</button>`);}}@@ -331,31 +344,27 @@ function _gotoSearchResult(r) {setView('conversation', r.cid);// Scroll to the matched message after history loads.setTimeout(() => _scrollToMsgIndex('chat-history', r.msg_index), 300);- } else if (r.kind === 'skill_chat') {- // Navigate to skills, select that skill, enter edit mode.- setView('skills');+ } else if (r.kind === 'agent') {+ // Open the agent detail view in read mode. Edit mode is intentionally+ // NOT auto-toggled — the user is looking up "this agent", not editing.+ setView('agents');setTimeout(async () => {- const cached = (_skillsCache || []).find((s) => s.id === r.skill_id);- if (cached && typeof _showSkillsDetailView === 'function') {- await _showSkillsDetailView(cached.source, cached.id);- if (typeof toggleSkillEditMode === 'function' && !_skillEditMode) {- await toggleSkillEditMode();- }- setTimeout(() => _scrollToMsgIndex('skills-chat-messages', r.msg_index), 300);+ if (typeof _showAgentsDetailView === 'function') {+ await _showAgentsDetailView(r.id);}}, 100);- } else if (r.kind === 'agent_chat') {- setView('agents');+ } else if (r.kind === 'skill') {+ setView('skills');setTimeout(async () => {- // Use _showAgentsDetailView (not selectAgent) so the grid → detail- // view swap actually happens — selectAgent only fills the detail- // pane's content, leaving grid-view on top.- if (typeof _showAgentsDetailView === 'function') {- await _showAgentsDetailView(r.agent_id);- if (typeof toggleAgentEditMode === 'function' && !_agentEditing) {- await toggleAgentEditMode();- }- setTimeout(() => _scrollToMsgIndex('agents-chat-messages', r.msg_index), 300);+ const cached = (typeof _skillsCache !== 'undefined' && Array.isArray(_skillsCache))+ ? _skillsCache.find((s) => s.id === r.id)+ : null;+ if (cached && typeof _showSkillsDetailView === 'function') {+ await _showSkillsDetailView(cached.source, cached.id);+ } else if (typeof _showSkillsDetailView === 'function') {+ // Cache may not be primed yet — fall back to the search result's+ // own source field so we still land on the right card.+ await _showSkillsDetailView(r.source, r.id);}}, 100);}