Skip to content

armgit / Orkas

Public Imported from GitHub
0

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.

Sync remaining 1.7.2 runtime mechanisms

wyte7c9ab20748d
diff --git a/src/core-agent/src/providers/request-diagnostics.ts b/src/core-agent/src/providers/request-diagnostics.ts
index e032a1c1..48303856 100644
--- a/src/core-agent/src/providers/request-diagnostics.ts
+++ b/src/core-agent/src/providers/request-diagnostics.ts
@@ -8,6 +8,11 @@ export interface ProviderRequestFailure {
source: ProviderFailureSource;
lastEvent: string;
requestSequence?: number;
+ /** Opaque transport correlation; restricted diagnostics only. */
+ requestRef?: string;
+ contextWindow?: number;
+ outputLimit?: number;
+ budgetObserved?: boolean;
}
export type ProviderFailureSource = 'unknown' | 'payload' | 'transport' | 'http' | 'sdk_error' | 'exception';
@@ -45,6 +50,7 @@ function safeCode(error: unknown): string {
export function createRequestDiagnostics(
signal?: AbortSignal,
onFailure?: (failure: ProviderRequestFailure) => void,
+ requestRef?: unknown,
) {
const started = performance.now();
const requestSequence = onFailure ? Math.min(1_000_000_000, (requestSequences.get(onFailure) ?? 0) + 1) : undefined;
@@ -56,6 +62,9 @@ export function createRequestDiagnostics(
let code = 'unknown';
let reported = false;
let observed = false;
+ let contextWindow: number | undefined;
+ let outputLimit: number | undefined;
+ let budgetObserved = false;
const onResponse = (response: { status: number }) => {
phase = 'after_response';
status = Number.isInteger(response.status) && response.status >= 100 && response.status <= 599
@@ -79,6 +88,17 @@ export function createRequestDiagnostics(
return {
get observed(): boolean { return observed; },
onResponse,
+ observeBudget(payload: unknown, window: unknown): void {
+ // O(1) observation of the final adapter payload. Never estimate tokens here.
+ try {
+ if (!payload || typeof payload !== 'object') return;
+ const body = payload as Record<string, unknown>;
+ const bounded = (value: unknown) => typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 1_000_000_000 ? value : undefined;
+ contextWindow = bounded(window);
+ outputLimit = bounded(body.max_output_tokens ?? body.max_completion_tokens ?? body.max_tokens);
+ budgetObserved = true;
+ } catch { /* Metadata cannot change the payload result. */ }
+ },
requestFetch,
observeEvent(type: string): void {
// Retain the event preceding failure, not the generic terminal error.
@@ -101,6 +121,8 @@ export function createRequestDiagnostics(
reported = true;
const failure: ProviderRequestFailure = {
phase,
+ ...(budgetObserved ? { budgetObserved, contextWindow, outputLimit } : {}),
+ ...(typeof requestRef === 'string' && /^(?:[a-f0-9]{12}|[a-f0-9]{32})$/.test(requestRef) ? { requestRef } : {}),
source: source !== 'unknown' ? source : status !== undefined && status >= 400 ? 'http' : boundary,
lastEvent,
...(requestSequence === undefined ? {} : { requestSequence }),
diff --git a/src/main/features/chat-history-records.ts b/src/main/features/chat-history-records.ts
index 4ee7bcd0..5b08ac43 100644
--- a/src/main/features/chat-history-records.ts
+++ b/src/main/features/chat-history-records.ts
@@ -56,13 +56,16 @@ export function* historyProcessTexts(message: { process?: unknown }, contentOnly
/** Explicit process events are archived evidence, never inferred intent. Public
* tool calls/results and progress only; private model reasoning is excluded. */
-export function historyRecordText(message: { text?: unknown; content?: unknown; process?: unknown; attachments?: unknown; references?: unknown; produced?: unknown }, includeProcess = false): string {
- const parts = [projectHistoryMediaText(typeof message.text === 'string' ? message.text : typeof message.content === 'string' ? message.content : '')];
+export function* historyRecordTextParts(message: { text?: unknown; content?: unknown; process?: unknown; attachments?: unknown; references?: unknown; produced?: unknown }, includeProcess = false): Generator<string> {
+ yield projectHistoryMediaText(typeof message.text === 'string' ? message.text : typeof message.content === 'string' ? message.content : '');
for (const field of ['attachments', 'references', 'produced'] as const) {
- if (Array.isArray(message[field]) && message[field].length) parts.push(`${field}: ${stringifyHistoryMedia(message[field])}`);
+ if (Array.isArray(message[field]) && message[field].length) yield `${field}: ${stringifyHistoryMedia(message[field])}`;
}
- if (includeProcess) for (const text of historyProcessTexts(message)) parts.push(text);
- return parts.filter(Boolean).join('\n');
+ if (includeProcess) yield* historyProcessTexts(message);
+}
+
+export function historyRecordText(message: Parameters<typeof historyRecordTextParts>[0], includeProcess = false): string {
+ return [...historyRecordTextParts(message, includeProcess)].filter(Boolean).join('\n');
}
export async function historyMessagesAtFile(file: string, indexes: ReadonlySet<number>): Promise<Map<number, MessageRecord>> {
diff --git a/src/main/features/search/chat-rebuild-entry.js b/src/main/features/search/chat-rebuild-entry.js
new file mode 100644
index 00000000..989f6203
--- /dev/null
+++ b/src/main/features/search/chat-rebuild-entry.js
@@ -0,0 +1,6 @@
+'use strict';
+
+// Same source/packaged TypeScript loader as bootstrap.cjs. Keep the entry JS:
+// workers do not inherit the main thread's require hooks.
+require('tsx/cjs');
+require('./chat-rebuild-worker');
diff --git a/src/main/features/search/chat-rebuild-worker.ts b/src/main/features/search/chat-rebuild-worker.ts
new file mode 100644
index 00000000..8f4d3db9
--- /dev/null
+++ b/src/main/features/search/chat-rebuild-worker.ts
@@ -0,0 +1,80 @@
+import * as fs from 'node:fs';
+import { parentPort, workerData } from 'node:worker_threads';
+import { historyRecordText } from '../chat-history-records';
+import * as store from './chat_store';
+import type { ChatRebuildFile, ChatRebuildBatch } from './chat-rebuild';
+
+const uid: string = workerData.userId;
+// Bound ordinary transactions by both record count and extracted characters.
+// One oversized record stays atomic and searchable in full, on this worker.
+const MAX_BATCH_CHARS = 256 * 1024;
+let current: { file: ChatRebuildFile; messages: any[]; next: number; reset: boolean } | undefined;
+
+function unchanged(file: ChatRebuildFile): boolean {
+ try {
+ const stat = fs.statSync(file.file);
+ return stat.mtimeMs === file.mtime && stat.size === file.size;
+ } catch { return false; }
+}
+
+function rebuildBatch(file: ChatRebuildFile): ChatRebuildBatch {
+ if (!unchanged(file)) { current = undefined; return { valid: false, complete: false, next: 0 }; }
+ if (!current || current.file.file !== file.file || current.file.mtime !== file.mtime || current.file.size !== file.size) {
+ const lines = fs.readFileSync(file.file, 'utf8').split('\n');
+ const messages: any[] = [];
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ try { messages.push(JSON.parse(line)); } catch { /* preserve legacy malformed-row handling */ }
+ }
+ if (!unchanged(file)) return { valid: false, complete: false, next: 0 };
+ const cursor = store.readRebuildCursor(uid, file.fileKey);
+ const resume = cursor && cursor.mtime === file.mtime && cursor.size === file.size
+ && Number.isInteger(cursor.next) && cursor.next >= 0 && cursor.next <= messages.length;
+ current = { file, messages, next: resume ? cursor.next : 0, reset: !resume };
+ }
+ const docs: store.ChatDocInput[] = [];
+ let chars = 0;
+ const start = current.next;
+ while (current.next < current.messages.length && current.next - start < 16 && chars < MAX_BATCH_CHARS) {
+ const i = current.next++;
+ const msg = current.messages[i];
+ const text = msg ? historyRecordText(msg, true) : '';
+ if (text) {
+ docs.push({ cid: file.fileKey, msgIndex: i, text,
+ role: msg.from || msg.role || '', time: msg.ts || msg.time || '' });
+ chars += text.length;
+ }
+ }
+ const next = current.next;
+ const complete = next === current.messages.length;
+ store.writeRebuildBatch(uid, file.fileKey, docs,
+ { mtime: file.mtime, size: file.size, next }, current.reset, complete);
+ current.reset = false;
+ const valid = unchanged(file);
+ if (!valid) store.dropFileWatermark(uid, file.fileKey);
+ if (complete || !valid) current = undefined;
+ return { valid, complete, next };
+}
+
+parentPort!.on('message', (command) => {
+ try {
+ let value: unknown;
+ if (command.kind === 'batch') value = rebuildBatch(command.file);
+ else if (command.kind === 'prune') {
+ const seen = new Set<string>(command.seen);
+ let deleted = 0;
+ for (const cid of store.indexedConversationIds(uid)) {
+ if (!seen.has(cid)) { store.deleteConversation(uid, cid); deleted++; }
+ }
+ value = deleted;
+ } else if (command.kind === 'close') {
+ current = undefined;
+ store.closeAllChatStores();
+ } else throw new Error('Unknown chat rebuild command');
+ parentPort!.postMessage({ ok: true, value });
+ } catch {
+ // The host retries from the committed cursor with a new worker. Never
+ // forward source records or paths embedded in parser/native exceptions.
+ parentPort!.postMessage({ ok: false });
+ }
+});
diff --git a/src/main/features/search/chat-rebuild.ts b/src/main/features/search/chat-rebuild.ts
new file mode 100644
index 00000000..e01f832c
--- /dev/null
+++ b/src/main/features/search/chat-rebuild.ts
@@ -0,0 +1,65 @@
+import { Worker } from 'node:worker_threads';
+import * as path from 'node:path';
+import { WS_ROOT } from '../../paths';
+
+export interface ChatRebuildFile {
+ fileKey: string;
+ file: string;
+ mtime: number;
+ size: number;
+}
+
+export interface ChatRebuildBatch { valid: boolean; complete: boolean; next: number }
+
+/** One writer per reconcile pass. Only file metadata crosses this boundary;
+ * source bodies, tokenization, postings writes and orphan deletion stay off
+ * main. Main admits each batch, so cancellation never queues more work. */
+export class ChatRebuildWorker {
+ private worker: Worker;
+ private pending?: { resolve: (value: any) => void; reject: (error: Error) => void };
+ private failed = false;
+
+ constructor(userId: string) {
+ this.worker = new Worker(path.join(__dirname, 'chat-rebuild-entry.js'), {
+ workerData: { userId }, execArgv: [],
+ env: { ...process.env, ORKAS_WORKSPACE_ROOT: WS_ROOT },
+ });
+ this.worker.on('message', (message) => {
+ const pending = this.pending;
+ this.pending = undefined;
+ if (message.ok) pending?.resolve(message.value);
+ else pending?.reject(new Error('Chat index rebuild batch failed'));
+ });
+ // Native/loader failures may contain source paths or content. Do not relay
+ // their raw messages to main's logs or to the renderer.
+ const fail = () => {
+ this.failed = true;
+ this.pending?.reject(new Error('Chat index rebuild worker stopped'));
+ this.pending = undefined;
+ };
+ this.worker.on('error', fail);
+ this.worker.on('exit', fail);
+ }
+
+ private request(command: object): Promise<any> {
+ if (this.failed) return Promise.reject(new Error('Chat index rebuild worker unavailable'));
+ if (this.pending) return Promise.reject(new Error('Chat index rebuild already has a pending batch'));
+ return new Promise((resolve, reject) => {
+ this.pending = { resolve, reject };
+ this.worker.postMessage(command);
+ });
+ }
+
+ rebuildBatch(file: ChatRebuildFile): Promise<ChatRebuildBatch> {
+ return this.request({ kind: 'batch', file });
+ }
+
+ deleteMissing(seen: string[]): Promise<number> {
+ return this.request({ kind: 'prune', seen });
+ }
+
+ async close(): Promise<void> {
+ try { if (!this.failed) await this.request({ kind: 'close' }); }
+ finally { await this.worker.terminate(); }
+ }
+}
diff --git a/src/main/features/search/chat-snippet-entry.js b/src/main/features/search/chat-snippet-entry.js
new file mode 100644
index 00000000..3fc20655
--- /dev/null
+++ b/src/main/features/search/chat-snippet-entry.js
@@ -0,0 +1,5 @@
+'use strict';
+
+// Workers need the same TypeScript loader in source and packaged builds.
+require('tsx/cjs');
+require('./chat-snippet-worker');
diff --git a/src/main/features/search/chat-snippet-worker.ts b/src/main/features/search/chat-snippet-worker.ts
new file mode 100644
index 00000000..6416cc09
--- /dev/null
+++ b/src/main/features/search/chat-snippet-worker.ts
@@ -0,0 +1,51 @@
+import { parentPort } from 'node:worker_threads';
+import { indexedJsonlStamp, mapIndexedJsonlRecords } from '../../util/indexed-jsonl';
+import { projectChatSnippet, type ChatSnippet } from './snippet';
+
+type Rows = Array<[number, ChatSnippet | undefined]>;
+const cache = new Map<string, { stamp: string; rows: Rows; bytes: number }>();
+const MAX_CACHE_BYTES = 2 * 1024 * 1024;
+const MAX_CACHE_ENTRIES = 512;
+let cacheBytes = 0;
+let chain = Promise.resolve();
+
+function forget(key: string): void {
+ cacheBytes -= cache.get(key)?.bytes || 0;
+ cache.delete(key);
+}
+
+// Serialized source reads bound raw-record memory. Cache only small rendered
+// projections, never full execution trails, and validate source identity on
+// every use so append, sync replacement and deletion cannot serve stale text.
+parentPort!.on('message', (request: { id: number; file: string; indexes: number[]; tokens: string[] }) => {
+ chain = chain.then(async () => {
+ let rows: Rows = [];
+ try {
+ const stamp = await indexedJsonlStamp(request.file);
+ const key = JSON.stringify([request.file, request.indexes, request.tokens]);
+ const hit = cache.get(key);
+ if (hit && hit.stamp === stamp) {
+ cache.delete(key); cache.set(key, hit);
+ rows = hit.rows;
+ } else {
+ forget(key);
+ rows = [...await mapIndexedJsonlRecords(request.file, new Set(request.indexes),
+ message => projectChatSnippet(message, request.tokens))];
+ if (stamp !== await indexedJsonlStamp(request.file)) rows = [];
+ else if (stamp && rows.length) {
+ const bytes = 2 * (key.length + JSON.stringify(rows).length);
+ if (bytes <= MAX_CACHE_BYTES) {
+ while (cache.size && (cache.size >= MAX_CACHE_ENTRIES || cacheBytes + bytes > MAX_CACHE_BYTES)) {
+ forget(cache.keys().next().value!);
+ }
+ cache.set(key, { stamp, rows, bytes }); cacheBytes += bytes;
+ }
+ }
+ }
+ } catch {
+ // Missing/changing sources retain the existing partial-coverage result.
+ rows = [];
+ }
+ parentPort!.postMessage({ id: request.id, rows });
+ });
+});
diff --git a/src/main/features/search/chat-snippets.ts b/src/main/features/search/chat-snippets.ts
new file mode 100644
index 00000000..2848f978
--- /dev/null
+++ b/src/main/features/search/chat-snippets.ts
@@ -0,0 +1,82 @@
+import { Worker } from 'node:worker_threads';
+import * as path from 'node:path';
+import { Semaphore } from 'async-mutex';
+import { WS_ROOT } from '../../paths';
+import { createLogger } from '../../logger';
+import type { ChatSnippet } from './snippet';
+
+const log = createLogger('search');
+
+let worker: Worker | undefined;
+let sequence = 0;
+let unavailableUntil = 0;
+let generation = 0;
+const io = new Semaphore(4);
+const pending = new Map<number, {
+ resolve: (rows: Map<number, ChatSnippet | undefined>) => void;
+ reject: (error: Error) => void;
+}>();
+
+function rejectPending(): void {
+ for (const request of pending.values()) request.reject(new Error('Chat snippet reader unavailable'));
+ pending.clear();
+}
+
+/** Large JSON parsing and display projection must not monopolize Electron's
+ * main loop. Only paths/positions go in and small display snippets come back.
+ * A shared IO semaphore bounds this worker's in-flight queue. */
+export function readChatSnippets(file: string, indexes: ReadonlySet<number>, tokens: readonly string[]): Promise<Map<number, ChatSnippet | undefined>> {
+ const expectedGeneration = generation;
+ return io.runExclusive(() => {
+ if (generation !== expectedGeneration) throw new Error('Chat snippet reader closed');
+ return requestSnippets(file, indexes, tokens);
+ });
+}
+
+function requestSnippets(file: string, indexes: ReadonlySet<number>, tokens: readonly string[]): Promise<Map<number, ChatSnippet | undefined>> {
+ if (Date.now() < unavailableUntil) return Promise.reject(new Error('Chat snippet reader unavailable'));
+ if (!worker) {
+ const current = new Worker(path.join(__dirname, 'chat-snippet-entry.js'), {
+ execArgv: [], env: { ...process.env, ORKAS_WORKSPACE_ROOT: WS_ROOT },
+ });
+ worker = current;
+ current.on('message', (message) => {
+ if (worker !== current) return;
+ const request = pending.get(message.id);
+ pending.delete(message.id);
+ request?.resolve(new Map(message.rows));
+ if (!pending.size) current.unref();
+ });
+ const fail = () => {
+ if (worker !== current) return;
+ worker = undefined;
+ unavailableUntil = Date.now() + 30_000;
+ log.warn('chat snippet worker stopped; retry deferred');
+ rejectPending();
+ void current.terminate();
+ };
+ current.on('error', fail);
+ current.on('exit', fail);
+ }
+ const current = worker;
+ const id = ++sequence;
+ current.ref();
+ return new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject });
+ try { current.postMessage({ id, file, indexes: [...indexes], tokens }); }
+ catch {
+ pending.delete(id);
+ if (!pending.size) current.unref();
+ reject(new Error('Chat snippet reader unavailable'));
+ }
+ });
+}
+
+export async function closeChatSnippetReader(): Promise<void> {
+ generation++;
+ const current = worker;
+ worker = undefined;
+ unavailableUntil = 0;
+ rejectPending();
+ await current?.terminate();
+}
diff --git a/src/main/features/search/chat_store.ts b/src/main/features/search/chat_store.ts
index 7b206db4..a1298a2d 100644
--- a/src/main/features/search/chat_store.ts
+++ b/src/main/features/search/chat_store.ts
@@ -23,19 +23,27 @@
* sampled terms and identical document lengths).
*
* Concurrency: better-sqlite3 is synchronous and every mutation here is a
- * single `db.transaction(...)`, which cannot interleave on one thread, so this
- * store needs no write mutex. Reads are lock-free.
+ * single `db.transaction(...)`. The indexer admits exactly one writer: main
+ * for live upserts, or a worker for reconciliation. WAL readers remain usable
+ * during rebuilds; data_version invalidates their cached scoring aggregates.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
+import { isMainThread } from 'node:worker_threads';
import Database from 'better-sqlite3';
-import { createLogger } from '../../logger';
import { userSearchDir } from '../../paths';
import { tokenize } from './tokenize';
-const log = createLogger('search:chat_store');
+function warn(message: string, error: unknown): void {
+ // Electron APIs are unavailable in Node workers. In dev, the electron npm
+ // package masks that boundary; packaged workers cannot import electron-log.
+ // Worker failures go back through its bounded, redacted reply instead.
+ if (!isMainThread) throw new Error(message);
+ const { createLogger } = require('../../logger') as typeof import('../../logger');
+ createLogger('search:chat_store').warn(message, { error: (error as Error).message });
+}
export const CHAT_STORE_SCHEMA_VERSION = 1;
@@ -86,6 +94,7 @@ interface Handle {
/** Aggregates the scorer needs on every query; recomputing them per query is
* a full table scan, so they are cached and dropped by any document write. */
stats: { count: number; avgLen: number } | null;
+ dataVersion: number;
}
const _stores = new Map<string, Handle>();
@@ -173,7 +182,7 @@ function handleFor(uid: string): Handle {
try { db.close(); } catch { /* preserve the original failure */ }
throw err;
}
- const handle: Handle = { db, dbPath, stats: null };
+ const handle: Handle = { db, dbPath, stats: null, dataVersion: -1 };
_stores.set(uid, handle);
return handle;
}
@@ -428,6 +437,11 @@ export function docsByIds(uid: string, ids: number[]): Map<number, ChatDocRow> {
function statsFor(uid: string): { count: number; avgLen: number } {
const handle = handleFor(uid);
+ const dataVersion = handle.db.pragma('data_version', { simple: true }) as number;
+ if (dataVersion !== handle.dataVersion) {
+ handle.stats = null;
+ handle.dataVersion = dataVersion;
+ }
if (handle.stats) return handle.stats;
const row = handle.db
.prepare('SELECT COUNT(*) AS n, AVG(len) AS avg FROM chat_docs')
@@ -493,7 +507,7 @@ export function compact(uid: string): void {
handle.db.pragma('wal_checkpoint(TRUNCATE)');
handle.db.exec('VACUUM');
} catch (err) {
- log.warn('chat store vacuum failed', { error: (err as Error).message });
+ warn('chat store vacuum failed', err);
}
}
@@ -501,7 +515,7 @@ export function closeChatStore(uid: string): void {
const handle = _stores.get(uid);
if (!handle) return;
try { handle.db.close(); }
- catch (err) { log.warn('close chat store failed', { error: (err as Error).message }); }
+ catch (err) { warn('close chat store failed', err); }
_stores.delete(uid);
}
diff --git a/src/main/features/search/index.ts b/src/main/features/search/index.ts
index a77d3488..4494ad3a 100644
--- a/src/main/features/search/index.ts
+++ b/src/main/features/search/index.ts
@@ -1,4 +1,3 @@
-import { hasHistoryProcess, historyMessagesAtFile, historyProcessTexts } from '../chat-history-records';
/**
* Global search query API.
*
@@ -26,7 +25,6 @@ import { hasHistoryProcess, historyMessagesAtFile, historyProcessTexts } from '.
import * as fs from 'node:fs';
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
-import { Semaphore } from 'async-mutex';
import {
WS_ROOT,
@@ -44,6 +42,8 @@ import { tokenize, isCJK } from './tokenize';
import { SCHEMA_VERSION, type Index, type Doc } from './storage';
import * as indexer from './indexer';
import * as chatStore from './chat_store';
+import type { ChatSnippet } from './snippet';
+import { readChatSnippets } from './chat-snippets';
import {
isRelevantLibraryContentHit,
libraryContentDisplayScore,
@@ -217,18 +217,6 @@ function _queryEmbedding(
// ── Source readers ──────────────────────────────────────────────────────
-interface ChatSourceMessage {
- id?: unknown;
- content?: unknown;
- text?: unknown;
- process?: unknown;
- deleted_at?: unknown;
- dispatch?: unknown;
-}
-
-// Bound concurrent exact source reads, including cold index construction.
-const _chatSnippetIo = new Semaphore(4);
-
export function invalidateChatsIndex(userId: string): void {
indexer.invalidateChatsIndex(userId);
}
@@ -634,6 +622,11 @@ export async function searchChats(
return (await searchChatsWithStatus(userId, query, options)).results;
}
+/** Cheap coverage-only IPC path: no source bodies, embeddings or rebuild. */
+export async function searchIndexStatus(userId: string): Promise<{ chat_index_complete: boolean }> {
+ return { chat_index_complete: indexer.isChatsIndexTrusted(userId) || await indexer.isChatsIndexCurrent(userId) };
+}
+
/** Query-local index status: a scheduled repair must not turn a partial miss
* into proof that history contains no matches. Existing UI callers keep arrays. */
export async function searchChatsWithStatus(
@@ -649,7 +642,7 @@ export async function searchChatsWithStatus(
// Cold and partial indexes use the same background path. Searching must
// never inherit a history-wide rebuild, including during first migration.
- let indexComplete = indexer.isChatsIndexTrusted(userId) || await indexer.isChatsIndexCurrent(userId);
+ let indexComplete = (await searchIndexStatus(userId)).chat_index_complete;
if (!indexComplete) indexer.scheduleChatIndexRepair(userId);
const tokens = tokenize(q);
// Normalize BM25 against the currently available corpus, including a
@@ -684,10 +677,6 @@ export async function searchChatsWithStatus(
if (Number.isInteger(options.beforeMsgIndex) && msgIndex >= Number(options.beforeMsgIndex)) return null;
if (options.excludeCid && cid === options.excludeCid) return null;
if (options.scope === 'project' && (!options.projectId || pid !== options.projectId)) return null;
- // The catalog above already resolved project membership. Supplying it
- // avoids `conversationMessageReadFile` re-scanning every project index
- // once per search result.
- const file = conversationMessageReadFile(userId, cid, pid || undefined);
const result: ChatCandidate = {
kind: 'chat',
cid: doc.cid,
@@ -701,7 +690,7 @@ export async function searchChatsWithStatus(
// ranking full-query matches first; the row list they cut down to is
// otherwise re-sorted by raw score and loses the tier.
term_coverage: scored.coverage,
- sourceFile: file,
+ sourceFile: '',
sourceIndex: msgIndex,
};
if (pid) {
@@ -715,48 +704,33 @@ export async function searchChatsWithStatus(
);
const byFile = new Map<string, Set<number>>();
+ const filesByCid = new Map<string, string>();
for (const candidate of candidates) {
+ const cid = String(candidate.cid);
+ let file = filesByCid.get(cid);
+ if (!file) {
+ // Resolve only selected conversations, not every scored document. An
+ // explicit global hint avoids rediscovering catalog ownership on disk.
+ const pid = displayCatalog.cidToPid.get(cid);
+ file = conversationMessageReadFile(userId, cid, pid || (displayCatalog.titles.has(cid) ? null : undefined));
+ filesByCid.set(cid, file);
+ }
+ candidate.sourceFile = file;
const indexes = byFile.get(candidate.sourceFile) || new Set<number>();
indexes.add(candidate.sourceIndex);
byFile.set(candidate.sourceFile, indexes);
}
- const sourceRows = new Map<string, Map<number, ChatSourceMessage>>();
+ const sourceRows = new Map<string, Map<number, ChatSnippet | undefined>>();
await Promise.all(Array.from(byFile, async ([file, indexes]) => {
- sourceRows.set(file, await _chatSnippetIo.runExclusive(async () => {
- try { return await historyMessagesAtFile(file, indexes); }
- catch { return new Map(); } // Source changes/missing files are repaired by reconciliation.
- }));
+ try { sourceRows.set(file, await readChatSnippets(file, indexes, tokens)); }
+ catch { sourceRows.set(file, new Map()); } // Source changes/missing files are repaired by reconciliation.
}));
const results = candidates.flatMap(({ sourceFile, sourceIndex, ...result }) => {
- const msg = sourceRows.get(sourceFile)?.get(sourceIndex);
- if (!msg) indexComplete = false;
- if (
- options.userVisibleOnly
- && (
- !msg
- || !!msg.deleted_at
- || !!msg.dispatch
- || !indexer.readMsgText(msg).trim()
- )
- ) {
- return [];
- }
- result.snippet = _makeSnippet(indexer.readMsgText(msg), q);
- if (msg && hasHistoryProcess(msg)) {
- result.has_process = true;
- // Compare public execution entries separately so a leading dialogue
- // acknowledgement or call input cannot hide a more relevant result.
- let best = '', coverage = 0;
- const terms = [...new Set(tokens)];
- for (const text of historyProcessTexts(msg, true)) {
- const lower = text.toLowerCase();
- const matched = terms.reduce((count, term) => count + Number(lower.includes(term)), 0);
- if (matched > coverage) { best = text; coverage = matched; }
- }
- if (best) result.process_snippet = _makeSnippet(best, q);
- }
- if (typeof msg?.id === 'string' && msg.id) result.msg_id = msg.id;
- return [result];
+ const projected = sourceRows.get(sourceFile)?.get(sourceIndex);
+ if (!projected) indexComplete = false;
+ if (options.userVisibleOnly && !projected?.visible) return [];
+ const { visible: _visible, ...snippet } = projected || { visible: false, snippet: '' };
+ return [{ ...result, ...snippet }];
});
return { results, indexComplete };
}
diff --git a/src/main/features/search/indexer.ts b/src/main/features/search/indexer.ts
index 0e6b76a8..fc295f2a 100644
--- a/src/main/features/search/indexer.ts
+++ b/src/main/features/search/indexer.ts
@@ -10,7 +10,7 @@ import { historyRecordText } from '../chat-history-records';
* re-tokenized, missing files have their docs dropped
* 4. `flushAll()` is called from app quit
*
- * Chat rebuilds yield between bounded transactions. Live messages remain in
+ * Chat rebuilds run in an independent worker. Live messages remain in
* their durable JSONL until catch-up; source revisions guard the ready handoff.
*/
@@ -20,6 +20,7 @@ import * as path from 'node:path';
import { Mutex } from 'async-mutex';
import * as chatStore from './chat_store';
+import { ChatRebuildWorker } from './chat-rebuild';
import {
userContextsDir, userChatsDir, projectChatsDir,
@@ -28,6 +29,7 @@ import {
import { conversationMessageReadFile, listProjectIds } from '../../util/project-layout';
import { getActiveUserId } from '../users';
import { createLogger } from '../../logger';
+import { closeChatSnippetReader } from './chat-snippets';
import { logErrorSummary, logPathRef } from '../../util/log-redact';
import { isBootAdmissionIdle, scheduleBootBackground, type ScheduledBootBackgroundTask } from '../../util/boot_init';
@@ -227,6 +229,7 @@ export async function flushOne(idxPath: string): Promise<void> {
export async function flushAll(): Promise<void> {
_closing = true;
+ await closeChatSnippetReader();
for (const uid of _chatRepairTasks.keys()) cancelChatIndexRepair(uid);
await Promise.allSettled([..._chatReconcileRuns.values()]);
await drainDeferredChatWrites();
@@ -337,24 +340,6 @@ function _putDoc(idx: RuntimeIndex, docId: string, doc: Doc, text: string): void
// ── Helpers ──────────────────────────────────────────────────────────────
-async function _readJsonl(file: string, signal?: AbortSignal): Promise<ChatMessage[] | null> {
- let text: string;
- try { text = await fsp.readFile(file, 'utf8'); }
- catch { return null; }
- const out: ChatMessage[] = [];
- const lines = text.split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (i > 0 && i % CPU_YIELD_EVERY === 0) {
- await new Promise<void>((resolve) => setImmediate(resolve));
- if (signal?.aborted) return null;
- }
- const line = lines[i];
- if (!line.trim()) continue;
- try { out.push(JSON.parse(line)); } catch { /* skip malformed */ }
- }
- return out;
-}
-
function _msgText(msg: ChatMessage | null | undefined): string {
return msg ? historyRecordText(msg, true) : '';
}
@@ -654,36 +639,15 @@ function _docId(kind: IndexKind, fileKey: string, msgIndex: number): string {
}
async function _reindexChatFile(
- userId: string, f: ChatFileInfo, shouldStop: () => boolean,
+ userId: string, f: ChatFileInfo, shouldStop: () => boolean, worker: ChatRebuildWorker,
): Promise<boolean> {
const revision = _chatRevisions.get(userId) || 0;
- const msgs = await _readJsonl(f.file);
- if (!msgs || shouldStop()) return false;
- // A sync pull or append during the read cannot certify this source snapshot.
- const stat = await fsp.stat(f.file).catch(() => undefined);
- if (!stat || stat.mtimeMs !== f.mtime || stat.size !== f.size
- || revision !== (_chatRevisions.get(userId) || 0)) return false;
- const cursor = chatStore.readRebuildCursor(userId, f.fileKey);
- const resume = cursor && cursor.mtime === f.mtime && cursor.size === f.size;
- let next = resume ? cursor.next : 0;
- let reset = !resume;
- do {
+ while (true) {
if (shouldStop() || revision !== (_chatRevisions.get(userId) || 0)) return false;
- const end = Math.min(next + 16, msgs.length);
- const docs: chatStore.ChatDocInput[] = [];
- for (let i = next; i < end; i++) {
- const m = msgs[i];
- const text = _msgText(m);
- if (text) docs.push({ cid: f.fileKey, msgIndex: i, role: _msgRole(m), time: _msgTime(m), text });
- }
- chatStore.writeRebuildBatch(userId, f.fileKey, docs,
- { mtime: f.mtime, size: f.size, next: end }, reset, end === msgs.length);
- reset = false;
- next = end;
- // Yield after the actual tokenization/SQLite work, not just after building
- // an input array. The persisted cursor survives a slice or process exit.
- await new Promise<void>((resolve) => setImmediate(resolve));
- } while (next < msgs.length);
+ const batch = await worker.rebuildBatch(f);
+ if (!batch.valid) return false;
+ if (batch.complete) break;
+ }
// Sync can replace the file before its completion callback invalidates the
// index. Recheck the source after the final yielded batch as well as before it.
const finalStat = await fsp.stat(f.file).catch(() => undefined);
@@ -733,24 +697,41 @@ async function _reconcileChatsPass(
let deleted = 0;
let cancelled = false;
const seen = new Set(scan.files.map(f => f.fileKey));
- for (const f of scan.files) {
- if (shouldStop()) { cancelled = true; break; }
- const known = chatStore.readFileWatermark(userId, f.fileKey);
- if (!_dirtyChats.get(userId)?.has(f.fileKey)
- && known && known.mtime === f.mtime && known.size === f.size) continue;
- if (!await _reindexChatFile(userId, f, shouldStop)) { cancelled = true; break; }
- updated++;
+ // The pass owns the writer until the worker is closed. Invalidation and
+ // live appends only mark durable source work meanwhile; a main-thread SQL
+ // write here would block behind the worker's transaction via busy_timeout.
+ let worker: ChatRebuildWorker | undefined;
+ try {
+ for (const f of scan.files) {
+ if (shouldStop() || revision !== (_chatRevisions.get(userId) || 0)) { cancelled = true; break; }
+ const known = chatStore.readFileWatermark(userId, f.fileKey);
+ if (!_dirtyChats.get(userId)?.has(f.fileKey)
+ && known && known.mtime === f.mtime && known.size === f.size) continue;
+ worker ??= new ChatRebuildWorker(userId);
+ if (!await _reindexChatFile(userId, f, shouldStop, worker)) { cancelled = true; break; }
+ updated++;
+ }
+ if (!cancelled && !shouldStop() && revision === (_chatRevisions.get(userId) || 0)) {
+ const missing = [...chatStore.indexedConversationIds(userId)].some(cid => !seen.has(cid));
+ if (missing) {
+ worker ??= new ChatRebuildWorker(userId);
+ deleted = await worker.deleteMissing([...seen]);
+ }
+ }
+ } finally {
+ await worker?.close();
}
const sourceStampAfter = cancelled ? undefined : await _chatSourceStamp(userId);
const complete = !cancelled && !shouldStop()
&& revision === (_chatRevisions.get(userId) || 0) && sourceStampBefore === sourceStampAfter;
if (complete) {
- // Deletion and the ready marker share a synchronous boundary. No new
- // append/invalidation can interleave between the final check and handoff.
- for (const cid of chatStore.indexedConversationIds(userId)) {
- if (!seen.has(cid)) { chatStore.deleteConversation(userId, cid); deleted++; }
- }
+ // The worker is closed. No append/invalidation can interleave between
+ // this final revision check and the synchronous ready handoff.
_dirtyChats.delete(userId);
+ // Rebuilds replace or delete rows and leave free SQLite pages behind.
+ // Reclaim them once while the index is still marked as migrating, never
+ // on the latency-sensitive incremental append path.
+ if (updated > 0 || deleted > 0) chatStore.compact(userId);
chatStore.markRebuildComplete(userId, sourceStampAfter!);
_migratingChats.delete(userId);
_currentChatIndexes.add(userId);
@@ -767,12 +748,18 @@ async function _reconcileChatsPass(
* directory walk on the query path. */
export async function isChatsIndexCurrent(userId: string): Promise<boolean> {
if (_chatReconcileRuns.has(userId) || _isMigrating(userId)) return false;
+ const revision = _chatRevisions.get(userId) || 0;
const stamp = chatStore.readSourceStamp(userId);
if (!stamp) {
_currentChatIndexes.delete(userId);
return false;
}
- const current = stamp === await _chatSourceStamp(userId);
+ const sourceStamp = await _chatSourceStamp(userId);
+ // The async catalog read can overlap sync invalidation or a new repair.
+ // An old read must not resurrect trust after either has cleared it.
+ const current = stamp === sourceStamp && !_chatReconcileRuns.has(userId)
+ && !_isMigrating(userId) && revision === (_chatRevisions.get(userId) || 0)
+ && stamp === chatStore.readSourceStamp(userId);
if (current) _currentChatIndexes.add(userId);
else _currentChatIndexes.delete(userId);
return current;
@@ -792,7 +779,8 @@ export function isChatsIndexTrusted(userId: string): boolean {
export function invalidateChatsIndex(userId: string): void {
_noteChatChange(userId);
_currentChatIndexes.delete(userId);
- chatStore.writeSourceStamp(userId, undefined);
+ // A running pass persisted invalidation before opening its writer.
+ if (!_chatReconcileRuns.has(userId)) chatStore.writeSourceStamp(userId, undefined);
scheduleChatIndexRepair(userId, 1_000);
}
@@ -874,6 +862,11 @@ export function indexChatMessage(
async function _dropChatFile(userId: string, fileKey: string): Promise<void> {
_noteChatChange(userId, fileKey);
await _getLock(_chatIdxPath(userId)).runExclusive(async () => {
+ if (_chatReconcileRuns.has(userId)) {
+ _currentChatIndexes.delete(userId);
+ scheduleChatIndexRepair(userId, 1_000);
+ return;
+ }
chatStore.deleteConversation(userId, fileKey);
});
}
diff --git a/src/main/features/search/snippet.ts b/src/main/features/search/snippet.ts
new file mode 100644
index 00000000..e07706a5
--- /dev/null
+++ b/src/main/features/search/snippet.ts
@@ -0,0 +1,76 @@
+import { hasHistoryProcess, historyProcessTexts, historyRecordTextParts } from '../chat-history-records';
+
+/** Preserve the first-token snippet without projecting the rest of a large
+ * execution trail after its display window is already known. Parts have the
+ * same newline separator as historyRecordText; query tokens contain no spaces. */
+export function makeSnippet(parts: Iterable<string>, tokens: readonly string[], radius = 60): string {
+ const chunks: string[] = [];
+ let length = 0, lowerLength = 0, trailingSpace = false;
+ let bestIdx = -1, bestLen = 0;
+ for (const part of parts) {
+ if (!part) continue;
+ let flat = part.replace(/\s+/g, ' ');
+ if (length) {
+ if (trailingSpace && flat.startsWith(' ')) flat = flat.slice(1);
+ else if (!trailingSpace && !flat.startsWith(' ')) flat = ' ' + flat;
+ }
+ const lower = flat.toLowerCase();
+ if (bestIdx < 0) {
+ for (const token of tokens) {
+ const idx = lower.indexOf(token);
+ if (idx >= 0 && (bestIdx < 0 || lowerLength + idx < bestIdx)) {
+ bestIdx = lowerLength + idx;
+ bestLen = token.length;
+ }
+ }
+ }
+ chunks.push(flat);
+ length += flat.length;
+ lowerLength += lower.length;
+ if (flat) trailingSpace = flat.endsWith(' ');
+ // One character beyond the window proves the trailing ellipsis. Do not
+ // touch later tool payloads just to discard them from the visible snippet.
+ if (bestIdx >= 0 && length > bestIdx + bestLen + radius) break;
+ }
+ const flat = chunks.join('');
+ if (bestIdx < 0) return flat.slice(0, radius * 2);
+ const start = Math.max(0, bestIdx - radius);
+ const end = Math.min(flat.length, bestIdx + bestLen + radius);
+ return (start > 0 ? '…' : '') + flat.slice(start, end) + (end < flat.length ? '…' : '');
+}
+
+export interface ChatSnippet {
+ snippet: string;
+ visible: boolean;
+ msg_id?: string;
+ has_process?: boolean;
+ process_snippet?: string;
+}
+
+/** Only this small projection survives a source read. Large execution records
+ * are released one at a time instead of retaining every search candidate. */
+export function projectChatSnippet(message: any, tokens: readonly string[]): ChatSnippet | undefined {
+ if (!message) return undefined;
+ let visible = false;
+ if (!message.deleted_at && !message.dispatch) {
+ for (const part of historyRecordTextParts(message, true)) {
+ if (part.trim()) { visible = true; break; }
+ }
+ }
+ const result: ChatSnippet = { snippet: makeSnippet(historyRecordTextParts(message, true), tokens), visible };
+ if (hasHistoryProcess(message)) {
+ result.has_process = true;
+ let best = '', coverage = 0;
+ const terms = [...new Set(tokens)];
+ for (const text of historyProcessTexts(message, true)) {
+ const lower = text.toLowerCase();
+ const matched = terms.reduce((count, term) => count + Number(lower.includes(term)), 0);
+ if (matched > coverage) { best = text; coverage = matched; }
+ // Later entries cannot improve full coverage; ties retain the first.
+ if (coverage === terms.length) break;
+ }
+ if (best) result.process_snippet = makeSnippet([best], tokens);
+ }
+ if (typeof message.id === 'string' && message.id) result.msg_id = message.id;
+ return result;
+}
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 65a2dd80..8970ad88 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -962,6 +962,7 @@ async function _afterRecycleRestore(ctx: IpcContext, paths: string[]): Promise<v
// merged into a `{ ok: true, ...result }` response. Throw to signal error.
const invokeHandlers: Record<string, InvokeHandler> = {
+ ...webAppInvokeHandlers,
'clientConfig.getQuickStart': async () => getQuickStartConfigState(),
'user.init': async () => {
const user = await users.getOrCreateSelfUser();
@@ -2834,6 +2835,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
// ── Global search (knowledge base + chat history) ──
+ 'search.status': async (_payload, ctx) => search.searchIndexStatus(ctx.userId),
'search.global': async ({ query, limit, scope, projectId }, ctx) => {
return search.searchAll(ctx.userId, query || '', {
limit: typeof limit === 'number' ? limit : 30,
diff --git a/src/main/model/core-agent/event-mapper.ts b/src/main/model/core-agent/event-mapper.ts
index bd20c14e..19466cd2 100644
--- a/src/main/model/core-agent/event-mapper.ts
+++ b/src/main/model/core-agent/event-mapper.ts
@@ -174,6 +174,7 @@ function modelFailureDetails(
if (isStorageFullError(error)) failureCode = 'storage_full';
else if (code === 'OUTPUT_LIMIT') failureCode = 'provider_max_tokens';
+ else if (code === 'PROVIDER_CANDIDATES_UNAVAILABLE') failureCode = 'provider_unavailable';
else if (code === 'PROVIDER_RETRIES_EXHAUSTED') failureCode = 'provider_retries_exhausted';
else if (code === 'PROVIDER_NO_FIRST_EVENT_TIMEOUT') failureCode = 'provider_no_first_event';
else if (code === 'PROVIDER_EMPTY_NORMAL') failureCode = 'empty_response_normal';
@@ -391,6 +392,7 @@ function localizeKnownRunnerError(error: AgentErrorMeta, providerId?: string): s
const known = localizeKnownRunnerText(raw, error.code);
if (known !== raw) return known;
const code = String(error.code || '').trim().toUpperCase();
+ if (code === 'PROVIDER_CANDIDATES_UNAVAILABLE') return t('errors.model_temporarily_unavailable');
const explicitKind: KeyFailureKind | null = /BALANCE|QUOTA|CREDIT|FUNDS|PAYMENT/.test(code)
? 'balance'
: error.kind === 'auth' || code === 'PROVIDER_AUTH_EXHAUSTED'
diff --git a/src/main/model/core-agent/rotating-provider.ts b/src/main/model/core-agent/rotating-provider.ts
index 67b1ca55..4907bb7c 100644
--- a/src/main/model/core-agent/rotating-provider.ts
+++ b/src/main/model/core-agent/rotating-provider.ts
@@ -78,6 +78,16 @@ export const PROVIDER_EMPTY_TRANSPORT_CODE = 'PROVIDER_EMPTY_TRANSPORT';
export const PROVIDER_EMPTY_NORMAL_CODE = 'PROVIDER_EMPTY_NORMAL';
export const PROVIDER_EMPTY_SAFETY_CODE = 'PROVIDER_EMPTY_SAFETY';
export const PROVIDER_EMPTY_UNKNOWN_CODE = 'PROVIDER_EMPTY_UNKNOWN';
+export const PROVIDER_CANDIDATES_UNAVAILABLE_CODE = 'PROVIDER_CANDIDATES_UNAVAILABLE';
+
+class ProviderCandidatesUnavailableError extends Error {
+ readonly code = PROVIDER_CANDIDATES_UNAVAILABLE_CODE;
+
+ constructor() {
+ super('No configured model candidate is currently available');
+ this.name = 'ProviderCandidatesUnavailableError';
+ }
+}
class ProviderNoFirstEventTimeoutError extends Error {
readonly code = PROVIDER_NO_FIRST_EVENT_TIMEOUT_CODE;
@@ -750,7 +760,7 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LL
async complete(params: CompletionParams): Promise<CompletionResult> {
if (terminalRateLimit) throw terminalRateLimit;
- let lastErr: unknown = new Error('rotating-provider: no candidates');
+ let lastErr: unknown = new ProviderCandidatesUnavailableError();
let lastCand: RotatingCandidate | null = null;
let lastFailure: PreCommitFailure | null = null;
let exhaustedNetwork = false;
@@ -861,7 +871,7 @@ export function createRotatingProvider(config: CreateRotatingProviderConfig): LL
async *stream(params: CompletionParams): AsyncIterable<StreamEvent> {
if (terminalRateLimit) throw terminalRateLimit;
- let lastErr: unknown = new Error('rotating-provider: no candidates');
+ let lastErr: unknown = new ProviderCandidatesUnavailableError();
let lastCand: RotatingCandidate | null = null;
let lastFailure: PreCommitFailure | null = null;
let exhaustedNetwork = false;
diff --git a/src/main/util/indexed-jsonl.ts b/src/main/util/indexed-jsonl.ts
index 974f6830..95acbdee 100644
--- a/src/main/util/indexed-jsonl.ts
+++ b/src/main/util/indexed-jsonl.ts
@@ -6,10 +6,27 @@ import { createReadStream, type Stats } from 'node:fs';
export type IndexedJsonlEntry<T> = { index: number; offset: number; bytes: number; metadata: T };
export type IndexedJsonl<T> = { stamp: string; entries: IndexedJsonlEntry<T>[] };
-type Cache = IndexedJsonl<unknown> & { project: (record: any) => unknown; terminated: boolean; size: number };
+type Cache = IndexedJsonl<unknown> & { project: (record: any) => unknown; terminated: boolean; size: number; complete: boolean };
const cache = new Map<string, Cache>();
const pending = new Map<string, Promise<Cache>>();
-const MAX_CACHED_FILES = 32;
+// A search can hit 200 conversations. A 32-file cache evicts its own working
+// set before the next query. Bound lightweight offsets by files AND entries.
+const MAX_CACHED_FILES = 512;
+const MAX_CACHED_ENTRIES = 50_000;
+let cachedEntries = 0;
+function forget(file: string): void {
+ cachedEntries -= cache.get(file)?.entries.length || 0;
+ cache.delete(file);
+}
+function remember(file: string, value: Cache): void {
+ forget(file);
+ if (value.entries.length > MAX_CACHED_ENTRIES) return;
+ while (cache.size && (cache.size >= MAX_CACHED_FILES || cachedEntries + value.entries.length > MAX_CACHED_ENTRIES)) {
+ forget(cache.keys().next().value!);
+ }
+ cache.set(file, value);
+ cachedEntries += value.entries.length;
+}
function stampOf(stat: Stats): string {
return [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':');
}
@@ -17,47 +34,68 @@ export async function indexedJsonlStamp(file: string): Promise<string> {
try { return stampOf(await fs.stat(file)); }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return ''; throw error; }
}
-export async function getIndexedJsonl<T>(file: string, project: (record: any) => T): Promise<IndexedJsonl<T>> {
+export async function getIndexedJsonl<T>(file: string, project: (record: any) => T, options: {
+ throughIndex?: number;
+ visit?: (record: any, index: number) => void;
+} = {}): Promise<IndexedJsonl<T>> {
+ const through = options.throughIndex ?? Infinity;
const stamp = await indexedJsonlStamp(file);
const hit = cache.get(file);
- if (hit?.stamp === stamp && hit.project === project) return hit as IndexedJsonl<T>;
- if (pending.has(file)) { await pending.get(file); return getIndexedJsonl(file, project); }
+ const reusable = hit?.stamp === stamp && hit.project === project;
+ if (reusable && (hit.complete || hit.entries.length > through)) {
+ cache.delete(file); cache.set(file, hit);
+ return hit as IndexedJsonl<T>;
+ }
+ if (pending.has(file)) { await pending.get(file); return getIndexedJsonl(file, project, options); }
const task = (async (): Promise<Cache> => {
- const entries: IndexedJsonlEntry<T>[] = [];
- let offset = 0;
+ const entries = reusable ? hit.entries.slice() as IndexedJsonlEntry<T>[] : [];
+ let offset = reusable ? hit.size : 0;
let pendingBytes = 0;
let pieces: Buffer[] = [];
const acceptLine = (line: Buffer) => {
+ let record: any;
try {
- const record = JSON.parse(line.toString('utf8'));
+ record = JSON.parse(line.toString('utf8'));
entries.push({ index: entries.length, offset, bytes: line.length, metadata: project(record) });
- } catch { /* Same valid-record numbering as storage.readJsonlWindow. */ }
+ } catch { return; } // Same valid-record numbering as storage.readJsonlWindow.
+ options.visit?.(record, entries.length - 1);
};
- if (stamp) for await (const raw of createReadStream(file)) {
- const chunk = raw as Buffer;
- let start = 0;
- for (let end = chunk.indexOf(10); end >= 0; end = chunk.indexOf(10, start)) {
- const fragment = chunk.subarray(start, end);
- const lineBytes = pendingBytes + fragment.length;
- // Join a long JSONL record once, not once per incoming chunk.
- acceptLine(pieces.length ? Buffer.concat([...pieces, fragment], lineBytes) : fragment);
- offset += lineBytes + 1;
- pendingBytes = 0;
- pieces = [];
- start = end + 1;
- }
- if (start < chunk.length) {
- pieces.push(chunk.subarray(start));
- pendingBytes += chunk.length - start;
+ let complete = true;
+ if (stamp) {
+ const stream = createReadStream(file, { start: offset });
+ const closed = new Promise<void>(resolve => stream.once('close', resolve));
+ try {
+ scan: for await (const raw of stream) {
+ const chunk = raw as Buffer;
+ let start = 0;
+ for (let end = chunk.indexOf(10); end >= 0; end = chunk.indexOf(10, start)) {
+ const fragment = chunk.subarray(start, end);
+ const lineBytes = pendingBytes + fragment.length;
+ // Join a long JSONL record once, not once per incoming chunk.
+ acceptLine(pieces.length ? Buffer.concat([...pieces, fragment], lineBytes) : fragment);
+ offset += lineBytes + 1;
+ pendingBytes = 0;
+ pieces = [];
+ start = end + 1;
+ if (entries.length > through) { complete = false; break scan; }
+ }
+ if (start < chunk.length) {
+ pieces.push(chunk.subarray(start));
+ pendingBytes += chunk.length - start;
+ }
+ }
+ } finally {
+ // Breaking async iteration destroys the stream but does not await its
+ // descriptor closing. Callers may immediately replace/delete history.
+ stream.destroy();
+ await closed;
}
}
const terminated = pendingBytes === 0;
if (pendingBytes) acceptLine(Buffer.concat(pieces, pendingBytes));
if (await indexedJsonlStamp(file) !== stamp) throw new Error('Conversation changed during history indexing; retry the read.');
- const result = { stamp, entries, project, terminated, size: offset + pendingBytes };
- cache.delete(file);
- if (cache.size >= MAX_CACHED_FILES) cache.delete(cache.keys().next().value!);
- cache.set(file, result);
+ const result = { stamp, entries, project, terminated, size: offset + pendingBytes, complete };
+ remember(file, result);
return result;
})();
pending.set(file, task);
@@ -70,20 +108,21 @@ export async function prepareIndexedJsonlAppend(file: string): Promise<(record:
const prior = cache.get(file);
if (!prior) return async () => {};
let valid = false;
- try { valid = prior.terminated && prior.stamp === await indexedJsonlStamp(file); } catch { cache.delete(file); }
+ try { valid = prior.complete && prior.terminated && prior.stamp === await indexedJsonlStamp(file); } catch { forget(file); }
return async (record, bytes) => {
try {
- if (!valid || cache.get(file) !== prior) { cache.delete(file); return; }
+ if (!valid || cache.get(file) !== prior) { forget(file); return; }
const stat = await fs.stat(file);
- if (stat.size !== prior.size + bytes) { cache.delete(file); return; }
+ if (stat.size !== prior.size + bytes) { forget(file); return; }
const entry = { index: prior.entries.length, offset: prior.size, bytes: bytes - 1, metadata: prior.project(record) };
+ forget(file);
prior.entries.push(entry);
- cache.set(file, { ...prior, size: stat.size, stamp: stampOf(stat) });
- } catch { cache.delete(file); } // Cache failure must never turn a committed append into a retry.
+ remember(file, { ...prior, size: stat.size, stamp: stampOf(stat) });
+ } catch { forget(file); } // Cache failure must never turn a committed append into a retry.
};
}
-export async function readIndexedJsonlRecords<T>(file: string, index: IndexedJsonl<unknown>, entries: readonly IndexedJsonlEntry<unknown>[]): Promise<T[]> {
+export async function readIndexedJsonlRecords<T>(file: string, index: IndexedJsonl<unknown>, entries: readonly IndexedJsonlEntry<unknown>[], project: (record: any, index: number) => T = record => record): Promise<T[]> {
if (!entries.length) return [];
if (await indexedJsonlStamp(file) !== index.stamp) throw new Error('Conversation changed; retry the history lookup.');
const handle = await fs.open(file, 'r');
@@ -97,9 +136,27 @@ export async function readIndexedJsonlRecords<T>(file: string, index: IndexedJso
if (!result.bytesRead) throw new Error('Conversation record is incomplete; retry the history lookup.');
read += result.bytesRead;
}
- records.push(JSON.parse(bytes.toString('utf8')));
+ records.push(project(JSON.parse(bytes.toString('utf8')), entry.index));
}
if (await indexedJsonlStamp(file) !== index.stamp) throw new Error('Conversation changed; retry the history lookup.');
return records;
} finally { await handle.close(); }
}
+
+const offsetOnly = () => undefined;
+
+/** Project selected records during a cold prefix scan, or seek them directly
+ * from cached offsets. Never parse the requested rows a second time on cold
+ * search, nor retain their large source bodies after projection. */
+export async function mapIndexedJsonlRecords<T>(file: string, indexes: ReadonlySet<number>, project: (record: any, index: number) => T): Promise<Map<number, T>> {
+ const wanted = [...indexes].filter(index => Number.isInteger(index) && index >= 0);
+ const out = new Map<number, T>();
+ if (!wanted.length) return out;
+ const index = await getIndexedJsonl(file, offsetOnly, {
+ throughIndex: Math.max(...wanted),
+ visit: (record, position) => { if (indexes.has(position)) out.set(position, project(record, position)); },
+ });
+ const remaining = wanted.filter(position => !out.has(position)).map(position => index.entries[position]).filter(Boolean);
+ await readIndexedJsonlRecords(file, index, remaining, (record, position) => { out.set(position, project(record, position)); });
+ return out;
+}
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 2e58b1e4..902badc1 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -775,39 +775,57 @@
</div>
<aside class="project-detail-side" aria-label="Project resources">
<section class="project-side-card project-side-context">
+ <!-- Head is two rows: the card identity, then the context
+ type tabs. Instructions and memory are different
+ long-lived stores, so the tabs get their own line
+ instead of sharing one 44px strip with the title. -->
<div class="project-side-card-head project-side-card-head-tabs">
- <div class="project-side-card-title-wrap">
- <span class="project-side-card-title" data-i18n="project.context.title">Context</span>
+ <div class="project-side-card-head-top">
+ <div class="project-side-card-title-wrap">
+ <span class="project-side-card-title" data-i18n="project.context.title">Context</span>
+ </div>
+ <span class="project-side-card-scope" data-i18n="project.context.scope">Shared by every conversation</span>
</div>
<div class="project-side-tabs" role="tablist" data-project-side-tabs="context">
<button type="button" class="project-side-tab is-active" data-project-side-tab="instructions">
- <span data-i18n="project.context.instructions_tab">Instructions</span>
+ <span data-i18n="project.context.instructions_tab">Goals &amp; rules</span>
</button>
<button type="button" class="project-side-tab" data-project-side-tab="memory">
<span data-i18n="project.context.memory_tab">Memory</span>
<span class="project-side-tab-count" id="project-memory-count"></span>
</button>
</div>
- <button type="button" class="project-side-icon-btn" id="project-memory-add-btn"
- data-project-context-action="memory" hidden
- data-i18n-title="project.memory.add" title="Add memory"
- data-i18n-aria-label="project.memory.add" aria-label="Add memory">
- <span data-ui-icon="plus" data-ui-icon-class="project-side-add-icon"></span>
- </button>
</div>
+ <!-- Instructions read first, edit on demand: the saved rules
+ are what every conversation actually gets, so the panel
+ shows them as copy and moves the editor into a dialog
+ instead of parking an empty textarea in the rail. -->
<div class="project-side-panel project-side-instructions-panel" data-project-side-panel="instructions">
- <p class="project-context-help" data-i18n="project.instructions.subtitle">Set project goals, priorities, and rules. The AI follows them in every conversation.</p>
- <textarea class="project-instructions-input" id="project-instructions-input" rows="5"
- data-i18n-placeholder="project.instructions.placeholder"
- placeholder="Rules and context every conversation in this project should follow"></textarea>
- <div class="project-instructions-foot">
- <span class="project-instructions-counter muted" id="project-instructions-counter"></span>
- <button type="button" class="btn btn-sm btn-primary" id="project-instructions-save-btn"
- data-i18n="project.instructions.save" disabled>Save</button>
+ <div class="project-context-section-head">
+ <h3 class="project-context-section-title" data-i18n="project.instructions.heading">Rules in effect</h3>
+ <button type="button" class="btn btn-sm project-context-action" id="project-instructions-edit-btn"
+ data-i18n="common.edit">Edit</button>
+ </div>
+ <div class="project-instructions-read" id="project-instructions-read"></div>
+ <div class="project-instructions-empty" id="project-instructions-empty" hidden>
+ <p class="project-context-help" data-i18n="project.instructions.subtitle">Set project goals, priorities, and rules. The AI follows them in every conversation.</p>
+ <button type="button" class="btn btn-sm" id="project-instructions-setup-btn"
+ data-i18n="project.instructions.setup">Set goals and rules</button>
</div>
+ <div class="project-context-status" id="project-instructions-status" role="status"></div>
</div>
<div class="project-side-panel project-side-memory-panel" data-project-side-panel="memory" hidden>
- <p class="project-context-help" data-i18n="project.memory.subtitle">Record project facts, decisions, and progress for the AI to reference in future conversations.</p>
+ <!-- Same shape as the rules panel: guidance while the
+ store is empty, heading once there is something to
+ read. -->
+ <div class="project-context-section-head" id="project-memory-section-head" hidden>
+ <h3 class="project-context-section-title" data-i18n="project.memory.heading">Saved facts and decisions</h3>
+ <button type="button" class="btn btn-sm project-context-action" id="project-memory-add-btn"
+ data-project-context-action="memory" hidden
+ data-i18n="project.memory.add_short"
+ data-i18n-title="project.memory.add" title="Add memory"
+ data-i18n-aria-label="project.memory.add" aria-label="Add memory">Add</button>
+ </div>
<div class="project-memory-editor" id="project-memory-editor" hidden>
<textarea class="project-memory-editor-input" id="project-memory-editor-input" rows="3" maxlength="2500"
data-i18n-placeholder="project.memory.placeholder" placeholder="Record a durable fact, decision, or project update"></textarea>
@@ -820,14 +838,32 @@
</div>
</div>
<div class="project-side-card-list project-memory-list" id="project-memory-list"></div>
- <div class="empty muted" id="project-memory-empty" data-i18n="project.memory.empty">No project memory yet</div>
+ <div class="empty project-memory-empty-state" id="project-memory-empty">
+ <p class="project-context-help" data-i18n="project.memory.subtitle">Record project facts, decisions, and progress for the AI to reference in future conversations.</p>
+ <button type="button" class="btn btn-sm" id="project-memory-add-empty-btn"
+ data-i18n="project.memory.add">Add memory</button>
+ </div>
</div>
</section>
<section class="project-side-card project-side-resources">
<div class="project-side-card-head project-side-card-head-tabs">
- <div class="project-side-card-title-wrap">
- <span class="project-side-card-title" data-i18n="project.resources.title">Resources</span>
+ <div class="project-side-card-head-top">
+ <div class="project-side-card-title-wrap">
+ <span class="project-side-card-title" data-i18n="project.resources.title">Resources</span>
+ </div>
+ <button type="button" class="project-side-icon-btn" id="project-add-agent-btn"
+ data-project-resource-action="agents"
+ data-i18n-title="project.bindings.add_agent" title="Add"
+ data-i18n-aria-label="project.bindings.add_agent" aria-label="Add">
+ <span data-ui-icon="plus" data-ui-icon-class="project-side-add-icon"></span>
+ </button>
+ <button type="button" class="project-side-icon-btn project-library-add-btn ctx-row-menu-btn ctx-root-menu-btn" id="project-library-root-menu-btn"
+ data-project-resource-action="files" hidden
+ data-i18n-title="contexts.menu.more_actions" title="More actions"
+ data-i18n-aria-label="contexts.menu.more_actions" aria-label="More actions">
+ <span data-ui-icon="plus" data-ui-icon-class="project-side-add-icon"></span>
+ </button>
</div>
<div class="project-side-tabs" role="tablist" data-project-side-tabs="resources">
<button type="button" class="project-side-tab is-active" data-project-side-tab="agents">
@@ -839,18 +875,6 @@
<span class="project-side-tab-count" id="project-detail-files-count"></span>
</button>
</div>
- <button type="button" class="project-side-icon-btn" id="project-add-agent-btn"
- data-project-resource-action="agents"
- data-i18n-title="project.bindings.add_agent" title="Add"
- data-i18n-aria-label="project.bindings.add_agent" aria-label="Add">
- <span data-ui-icon="plus" data-ui-icon-class="project-side-add-icon"></span>
- </button>
- <button type="button" class="project-side-icon-btn project-library-add-btn ctx-row-menu-btn ctx-root-menu-btn" id="project-library-root-menu-btn"
- data-project-resource-action="files" hidden
- data-i18n-title="contexts.menu.more_actions" title="More actions"
- data-i18n-aria-label="contexts.menu.more_actions" aria-label="More actions">
- <span data-ui-icon="plus" data-ui-icon-class="project-side-add-icon"></span>
- </button>
</div>
<div class="project-side-panel project-side-agents-panel" data-project-side-panel="agents">
<div class="project-side-card-list project-agent-rail-list" id="project-agents-list"></div>
@@ -867,6 +891,36 @@
</aside>
</div>
+ <!-- Goals & rules editor. The rail shows saved rules; writing
+ them happens here so the draft has room and never looks like
+ the live value. Save path is unchanged. -->
+ <div class="modal-overlay project-instructions-modal" id="project-instructions-modal" aria-hidden="true">
+ <div class="modal project-instructions-dialog" role="dialog" aria-modal="true" aria-labelledby="project-instructions-dialog-title">
+ <div class="modal-header">
+ <h3 class="modal-title" id="project-instructions-dialog-title" data-i18n="project.instructions.edit_title">Goals and rules</h3>
+ <button type="button" class="modal-close-btn" id="project-instructions-close-btn"
+ data-i18n-title="common.close" title="Close"
+ data-i18n-aria-label="common.close" aria-label="Close">
+ <span data-ui-icon="x" data-ui-icon-class="modal-close-icon"></span>
+ </button>
+ </div>
+ <div class="modal-body">
+ <p class="project-context-help" data-i18n="project.instructions.subtitle">Set project goals, priorities, and rules. The AI follows them in every conversation.</p>
+ <textarea class="project-instructions-input" id="project-instructions-input" rows="12"
+ data-i18n-placeholder="project.instructions.placeholder"
+ placeholder="Rules and context every conversation in this project should follow"></textarea>
+ </div>
+ <div class="project-instructions-foot">
+ <span class="project-instructions-counter muted" id="project-instructions-counter"></span>
+ <span class="project-instructions-foot-actions">
+ <button type="button" class="btn btn-sm" id="project-instructions-cancel-btn" data-i18n="common.cancel">Cancel</button>
+ <button type="button" class="btn btn-sm btn-primary" id="project-instructions-save-btn"
+ data-i18n="project.instructions.save" disabled>Save</button>
+ </span>
+ </div>
+ </div>
+ </div>
+
<div class="modal-overlay project-library-viewer-modal" id="project-library-viewer-modal" aria-hidden="true">
<div class="modal project-library-viewer-dialog" role="dialog" aria-modal="true" aria-labelledby="project-library-editor-path">
<div class="contexts-editor-empty" id="project-library-editor-empty">
@@ -1820,8 +1874,8 @@
</div>
<div class="form-msg" id="kb-picker-msg"></div>
<div class="modal-actions">
- <button class="btn" onclick="closeKbPicker()" data-i18n="common.cancel">Cancel</button>
- <button class="btn btn-primary" onclick="confirmKbPicker()" data-i18n="common.confirm">Confirm</button>
+ <button class="btn" id="kb-picker-cancel" type="button" data-i18n="common.cancel">Cancel</button>
+ <button class="btn btn-primary" id="kb-picker-confirm" type="button" data-i18n="common.confirm">Confirm</button>
</div>
</div>
</div>
diff --git a/src/renderer/locales/de.json b/src/renderer/locales/de.json
index c0f15a70..1996c874 100644
--- a/src/renderer/locales/de.json
+++ b/src/renderer/locales/de.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "Aufgaben",
"project.tab_auto": "Automatisierung",
"project.context.title": "Kontext",
- "project.context.instructions_tab": "Anweisungen",
+ "project.context.instructions_tab": "Ziele & Regeln",
"project.context.memory_tab": "Gedächtnis",
+ "project.context.scope": "Alle Unterhaltungen dieses Projekts",
+ "project.instructions.heading": "Geltende Regeln",
+ "project.instructions.setup": "Ziele und Regeln festlegen",
+ "project.instructions.edit_title": "Ziele und Regeln",
+ "project.instructions.saved": "Gespeichert",
+ "project.instructions.discard_confirm": "Nicht gespeicherte Änderungen verwerfen?",
+ "project.memory.heading": "Gesicherte Fakten und Entscheidungen",
+ "project.memory.add_short": "Hinzufügen",
"project.resources.title": "Ressourcen",
"project.resources.agents_tab": "Agenten",
"project.resources.files_tab": "Bibliothek",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "Legen Sie Ziele, Prioritäten und Regeln des Projekts fest. Die KI befolgt sie in jedem Gespräch.",
"project.memory.title": "Projektgedächtnis",
"project.memory.subtitle": "Halten Sie Projektfakten, Entscheidungen und dauerhafte Ergebnisse fest, auf die die KI in künftigen Gesprächen zurückgreifen kann.",
- "project.memory.empty": "Noch kein Projektgedächtnis",
"project.memory.add": "Projektgedächtniseintrag hinzufügen",
"project.memory.placeholder": "Dauerhaften Fakt, Entscheidung, Konvention oder Ergebnis festhalten…",
"project.memory.edit": "Bearbeiten",
@@ -2236,7 +2243,7 @@
"search.source.custom": "Benutzerdefiniert",
"search.source.marketplace": "Marketplace",
"search.no_results": "Keine Ergebnisse für „{query}“",
- "search.history_indexing": "Der Chatverlauf wird indexiert. Die Ergebnisse sind möglicherweise unvollständig. Bitte später erneut suchen.",
+ "search.history_indexing": "Wird vorbereitet. Die Ergebnisse sind möglicherweise unvollständig. Bitte später erneut versuchen.",
"search.role.user": "Ich",
"search.role.ai": "KI",
"model_guard.modal": "Es wurde kein Modell hinzugefügt, daher ist diese Funktion derzeit nicht verfügbar.\n\nFügen Sie in den Einstellungen ein Modellkonto hinzu.",
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index c4b23280..9b8a7a28 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "Tasks",
"project.tab_auto": "Automation",
"project.context.title": "Context",
- "project.context.instructions_tab": "Instructions",
+ "project.context.instructions_tab": "Goals & rules",
"project.context.memory_tab": "Memory",
+ "project.context.scope": "Every conversation in this project",
+ "project.instructions.heading": "Rules in effect",
+ "project.instructions.setup": "Set goals and rules",
+ "project.instructions.edit_title": "Goals and rules",
+ "project.instructions.saved": "Saved",
+ "project.instructions.discard_confirm": "Discard unsaved changes?",
+ "project.memory.heading": "Saved facts and decisions",
+ "project.memory.add_short": "Add",
"project.resources.title": "Resources",
"project.resources.agents_tab": "Agents",
"project.resources.files_tab": "Library",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "Set project goals, priorities, and rules. The AI follows them in every conversation.",
"project.memory.title": "Project memory",
"project.memory.subtitle": "Record project facts, decisions, and durable outcomes for the AI to reference in future conversations.",
- "project.memory.empty": "No project memory yet",
"project.memory.add": "Add project memory",
"project.memory.placeholder": "Record a durable fact, decision, convention, or outcome…",
"project.memory.edit": "Edit",
@@ -2236,7 +2243,7 @@
"search.source.custom": "Custom",
"search.source.marketplace": "marketplace",
"search.no_results": "No results for \"{query}\"",
- "search.history_indexing": "Indexing chat history. Results may be incomplete; try again shortly.",
+ "search.history_indexing": "Preparing. Results may be incomplete; try again shortly.",
"search.role.user": "Me",
"search.role.ai": "AI",
"model_guard.modal": "No model has been added, so this feature is currently unavailable.\n\nAdd a model account in Settings.",
diff --git a/src/renderer/locales/es.json b/src/renderer/locales/es.json
index ba1f4b91..b423d69c 100644
--- a/src/renderer/locales/es.json
+++ b/src/renderer/locales/es.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "Tareas",
"project.tab_auto": "Automatización",
"project.context.title": "Contexto",
- "project.context.instructions_tab": "Instrucciones",
+ "project.context.instructions_tab": "Objetivos y reglas",
"project.context.memory_tab": "Memoria",
+ "project.context.scope": "Conversaciones de este proyecto",
+ "project.instructions.heading": "Reglas vigentes",
+ "project.instructions.setup": "Definir objetivos y reglas",
+ "project.instructions.edit_title": "Objetivos y reglas",
+ "project.instructions.saved": "Guardado",
+ "project.instructions.discard_confirm": "¿Descartar los cambios sin guardar?",
+ "project.memory.heading": "Hechos y decisiones guardados",
+ "project.memory.add_short": "Añadir",
"project.resources.title": "Recursos",
"project.resources.agents_tab": "Agentes",
"project.resources.files_tab": "Biblioteca",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "Define objetivos, prioridades y reglas del proyecto. La IA los sigue en cada conversación.",
"project.memory.title": "Memoria del proyecto",
"project.memory.subtitle": "Registra hechos, decisiones y resultados duraderos del proyecto para que la IA los consulte en conversaciones futuras.",
- "project.memory.empty": "Aún no hay memoria del proyecto",
"project.memory.add": "Añadir memoria del proyecto",
"project.memory.placeholder": "Registra un hecho, decisión, convención o resultado duradero…",
"project.memory.edit": "Editar",
@@ -2236,7 +2243,7 @@
"search.source.custom": "Personalizado",
"search.source.marketplace": "marketplace",
"search.no_results": "Sin resultados para \"{query}\"",
- "search.history_indexing": "Se está indexando el historial de chats. Los resultados pueden estar incompletos. Vuelve a intentarlo en breve.",
+ "search.history_indexing": "Preparando. Los resultados pueden estar incompletos. Vuelve a intentarlo en breve.",
"search.role.user": "Yo",
"search.role.ai": "IA",
"model_guard.modal": "No se ha añadido ningún modelo, por lo que esta función no está disponible.\n\nAñade una cuenta de modelo en Configuración.",
diff --git a/src/renderer/locales/fr.json b/src/renderer/locales/fr.json
index 635b3a33..223380e0 100644
--- a/src/renderer/locales/fr.json
+++ b/src/renderer/locales/fr.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "Tâches",
"project.tab_auto": "Automatisation",
"project.context.title": "Contexte",
- "project.context.instructions_tab": "Instructions",
+ "project.context.instructions_tab": "Objectifs et règles",
"project.context.memory_tab": "Mémoire",
+ "project.context.scope": "Toutes les conversations de ce projet",
+ "project.instructions.heading": "Règles en vigueur",
+ "project.instructions.setup": "Définir les objectifs et règles",
+ "project.instructions.edit_title": "Objectifs et règles",
+ "project.instructions.saved": "Enregistré",
+ "project.instructions.discard_confirm": "Abandonner les modifications non enregistrées ?",
+ "project.memory.heading": "Faits et décisions enregistrés",
+ "project.memory.add_short": "Ajouter",
"project.resources.title": "Ressources",
"project.resources.agents_tab": "Agents",
"project.resources.files_tab": "Bibliothèque",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "Définissez les objectifs, priorités et règles du projet. L’IA les suit dans chaque conversation.",
"project.memory.title": "Mémoire du projet",
"project.memory.subtitle": "Consignez les faits, décisions et résultats durables du projet pour que l’IA s’y réfère dans les futures conversations.",
- "project.memory.empty": "Aucune mémoire de projet pour le moment",
"project.memory.add": "Ajouter un élément à la mémoire du projet",
"project.memory.placeholder": "Consignez un fait, une décision, une convention ou un résultat durable…",
"project.memory.edit": "Modifier",
@@ -2236,7 +2243,7 @@
"search.source.custom": "Personnalisé",
"search.source.marketplace": "marketplace",
"search.no_results": "Aucun résultat pour « {query} »",
- "search.history_indexing": "Indexation de l’historique des discussions en cours. Les résultats peuvent être incomplets. Réessayez dans un instant.",
+ "search.history_indexing": "Préparation en cours. Les résultats peuvent être incomplets. Réessayez dans un instant.",
"search.role.user": "Moi",
"search.role.ai": "IA",
"model_guard.modal": "Aucun modèle n’a été ajouté ; cette fonctionnalité est donc indisponible.\n\nAjoutez un compte de modèle dans les paramètres.",
diff --git a/src/renderer/locales/it.json b/src/renderer/locales/it.json
index 1b94a732..ee64c2e2 100644
--- a/src/renderer/locales/it.json
+++ b/src/renderer/locales/it.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "Attività",
"project.tab_auto": "Automazione",
"project.context.title": "Contesto",
- "project.context.instructions_tab": "Istruzioni",
+ "project.context.instructions_tab": "Obiettivi e regole",
"project.context.memory_tab": "Memoria",
+ "project.context.scope": "Conversazioni di questo progetto",
+ "project.instructions.heading": "Regole in vigore",
+ "project.instructions.setup": "Imposta obiettivi e regole",
+ "project.instructions.edit_title": "Obiettivi e regole",
+ "project.instructions.saved": "Salvato",
+ "project.instructions.discard_confirm": "Scartare le modifiche non salvate?",
+ "project.memory.heading": "Fatti e decisioni salvati",
+ "project.memory.add_short": "Aggiungi",
"project.resources.title": "Risorse",
"project.resources.agents_tab": "Agenti",
"project.resources.files_tab": "Biblioteca",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "Imposta obiettivi, priorità e regole del progetto. L'IA li segue in ogni conversazione.",
"project.memory.title": "Memoria del progetto",
"project.memory.subtitle": "Registra fatti, decisioni e risultati duraturi del progetto che l'IA potrà consultare nelle conversazioni future.",
- "project.memory.empty": "Nessuna memoria del progetto",
"project.memory.add": "Aggiungi memoria del progetto",
"project.memory.placeholder": "Registra un fatto, una decisione, una convenzione o un risultato duraturo…",
"project.memory.edit": "Modifica",
@@ -2236,7 +2243,7 @@
"search.source.custom": "Personalizzato",
"search.source.marketplace": "marketplace",
"search.no_results": "Nessun risultato per \"{query}\"",
- "search.history_indexing": "Indicizzazione della cronologia chat in corso. I risultati potrebbero essere incompleti. Riprova tra poco.",
+ "search.history_indexing": "Preparazione in corso. I risultati potrebbero essere incompleti. Riprova tra poco.",
"search.role.user": "Io",
"search.role.ai": "IA",
"model_guard.modal": "Non è stato aggiunto alcun modello, quindi questa funzione non è al momento disponibile.\n\nAggiungi un account del modello nelle Impostazioni.",
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index b25cdebd..41ed0960 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "タスク",
"project.tab_auto": "自動化",
"project.context.title": "コンテキスト",
- "project.context.instructions_tab": "説明",
+ "project.context.instructions_tab": "目標とルール",
"project.context.memory_tab": "メモリ",
+ "project.context.scope": "このプロジェクトの全会話で共有",
+ "project.instructions.heading": "適用中のルール",
+ "project.instructions.setup": "目標とルールを設定",
+ "project.instructions.edit_title": "目標とルール",
+ "project.instructions.saved": "保存しました",
+ "project.instructions.discard_confirm": "保存していない変更を破棄しますか?",
+ "project.memory.heading": "確定した事実と決定",
+ "project.memory.add_short": "追加",
"project.resources.title": "リソース",
"project.resources.agents_tab": "エージェント",
"project.resources.files_tab": "ライブラリ",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "プロジェクトの目標、優先事項、ルールを設定します。AI はすべての会話で参照し従います。",
"project.memory.title": "プロジェクトメモリ",
"project.memory.subtitle": "プロジェクトの事実、決定、長期的な成果を記録し、今後の会話で AI が継続的に参照します。",
- "project.memory.empty": "プロジェクトメモリはまだありません",
"project.memory.add": "プロジェクトメモリを追加",
"project.memory.placeholder": "長期的な事実、決定、慣例、または成果を記録…",
"project.memory.edit": "編集",
@@ -2236,7 +2243,7 @@
"search.source.custom": "カスタム",
"search.source.marketplace": "マーケットプレイス",
"search.no_results": "「{query}」の結果はありません",
- "search.history_indexing": "チャット履歴のインデックスを作成中です。結果が一部表示されない場合があります。しばらくしてから再検索してください。",
+ "search.history_indexing": "準備中です。結果はまだ不完全です。しばらくしてから再検索してください。",
"search.role.user": "自分",
"search.role.ai": "AI",
"model_guard.modal": "モデルが追加されていないため、この機能は現在利用できません。\n\n設定でモデルアカウントを追加してください。",
diff --git a/src/renderer/locales/ko.json b/src/renderer/locales/ko.json
index a5f25954..89ad8122 100644
--- a/src/renderer/locales/ko.json
+++ b/src/renderer/locales/ko.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "작업",
"project.tab_auto": "자동화",
"project.context.title": "컨텍스트",
- "project.context.instructions_tab": "지침",
+ "project.context.instructions_tab": "목표와 규칙",
"project.context.memory_tab": "메모리",
+ "project.context.scope": "이 프로젝트의 모든 대화에서 공유",
+ "project.instructions.heading": "적용 중인 규칙",
+ "project.instructions.setup": "목표와 규칙 설정",
+ "project.instructions.edit_title": "목표와 규칙",
+ "project.instructions.saved": "저장됨",
+ "project.instructions.discard_confirm": "저장하지 않은 변경 사항을 취소할까요?",
+ "project.memory.heading": "정리된 사실과 결정",
+ "project.memory.add_short": "추가",
"project.resources.title": "리소스",
"project.resources.agents_tab": "에이전트",
"project.resources.files_tab": "라이브러리",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "프로젝트 목표, 우선순위, 규칙을 설정하세요. AI가 모든 대화에서 따릅니다.",
"project.memory.title": "프로젝트 메모리",
"project.memory.subtitle": "프로젝트의 사실, 결정 사항, 지속적으로 유효한 결과를 기록하여 AI가 향후 대화에서 참고할 수 있게 하세요.",
- "project.memory.empty": "아직 프로젝트 메모리가 없습니다",
"project.memory.add": "프로젝트 메모리 추가",
"project.memory.placeholder": "장기적으로 유효한 사실, 결정 사항, 규칙 또는 결과를 기록하세요…",
"project.memory.edit": "편집",
@@ -2236,7 +2243,7 @@
"search.source.custom": "사용자 지정",
"search.source.marketplace": "마켓플레이스",
"search.no_results": "\"{query}\" 검색 결과 없음",
- "search.history_indexing": "채팅 기록을 색인화하고 있습니다. 일부 결과가 누락될 수 있으니 잠시 후 다시 검색해 주세요.",
+ "search.history_indexing": "준비 중입니다. 결과가 불완전할 수 있으니 잠시 후 다시 시도해 주세요.",
"search.role.user": "나",
"search.role.ai": "AI",
"model_guard.modal": "추가된 모델이 없어 현재 이 기능을 사용할 수 없습니다.\n\n설정에서 모델 계정을 추가해 주세요.",
diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.json
index 882bbbda..5996b46c 100644
--- a/src/renderer/locales/pt.json
+++ b/src/renderer/locales/pt.json
@@ -2109,8 +2109,16 @@
"project.tab_tasks": "Tarefas",
"project.tab_auto": "Automação",
"project.context.title": "Contexto",
- "project.context.instructions_tab": "Instruções",
+ "project.context.instructions_tab": "Metas e regras",
"project.context.memory_tab": "Memória",
+ "project.context.scope": "Todas as conversas deste projeto",
+ "project.instructions.heading": "Regras em vigor",
+ "project.instructions.setup": "Definir metas e regras",
+ "project.instructions.edit_title": "Metas e regras",
+ "project.instructions.saved": "Salvo",
+ "project.instructions.discard_confirm": "Descartar alterações não salvas?",
+ "project.memory.heading": "Fatos e decisões salvos",
+ "project.memory.add_short": "Adicionar",
"project.resources.title": "Recursos",
"project.resources.agents_tab": "Agentes",
"project.resources.files_tab": "Biblioteca",
@@ -2164,7 +2172,6 @@
"project.instructions.subtitle": "Defina objetivos, prioridades e regras do projeto. A IA os segue em todas as conversas.",
"project.memory.title": "Memória do projeto",
"project.memory.subtitle": "Registre fatos, decisões e resultados duradouros do projeto para a IA consultar em conversas futuras.",
- "project.memory.empty": "Nenhuma memória do projeto ainda",
"project.memory.add": "Adicionar memória do projeto",
"project.memory.placeholder": "Registre um fato, decisão, convenção ou resultado duradouro…",
"project.memory.edit": "Editar",
@@ -2225,7 +2232,7 @@
"search.source.custom": "Personalizado",
"search.source.marketplace": "Marketplace",
"search.no_results": "Nenhum resultado para \"{query}\"",
- "search.history_indexing": "O histórico de conversas está sendo indexado. Os resultados podem estar incompletos. Tente novamente em breve.",
+ "search.history_indexing": "Preparando. Os resultados podem estar incompletos. Tente novamente em breve.",
"search.role.user": "Eu",
"search.role.ai": "IA",
"model_guard.modal": "Nenhum modelo foi adicionado, portanto este recurso está indisponível no momento.\n\nAdicione uma conta de modelo nas Configurações.",
diff --git a/src/renderer/locales/ru.json b/src/renderer/locales/ru.json
index 7039988a..b0daf23a 100644
--- a/src/renderer/locales/ru.json
+++ b/src/renderer/locales/ru.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "Задачи",
"project.tab_auto": "Автоматизация",
"project.context.title": "Контекст",
- "project.context.instructions_tab": "Инструкции",
+ "project.context.instructions_tab": "Цели и правила",
"project.context.memory_tab": "Память",
+ "project.context.scope": "Во всех диалогах этого проекта",
+ "project.instructions.heading": "Действующие правила",
+ "project.instructions.setup": "Задать цели и правила",
+ "project.instructions.edit_title": "Цели и правила",
+ "project.instructions.saved": "Сохранено",
+ "project.instructions.discard_confirm": "Отменить несохранённые изменения?",
+ "project.memory.heading": "Сохранённые факты и решения",
+ "project.memory.add_short": "Добавить",
"project.resources.title": "Ресурсы",
"project.resources.agents_tab": "Агенты",
"project.resources.files_tab": "Библиотека",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "Задайте цели, приоритеты и правила проекта. ИИ следует им в каждом диалоге.",
"project.memory.title": "Память проекта",
"project.memory.subtitle": "Записывайте факты проекта, решения и значимые результаты, к которым ИИ сможет обращаться в будущих диалогах.",
- "project.memory.empty": "Память проекта пока пуста",
"project.memory.add": "Добавить запись в память проекта",
"project.memory.placeholder": "Запишите долгосрочный факт, решение, договорённость или результат…",
"project.memory.edit": "Редактировать",
@@ -2236,7 +2243,7 @@
"search.source.custom": "Пользовательский",
"search.source.marketplace": "маркетплейс",
"search.no_results": "Нет результатов для «{query}»",
- "search.history_indexing": "Идёт индексация истории чатов. Результаты могут быть неполными. Повторите поиск чуть позже.",
+ "search.history_indexing": "Идёт подготовка. Результаты могут быть неполными. Повторите попытку чуть позже.",
"search.role.user": "Я",
"search.role.ai": "ИИ",
"model_guard.modal": "Модель не добавлена, поэтому эта функция сейчас недоступна.\n\nДобавьте аккаунт модели в настройках.",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 6037e731..5471c7b5 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -2120,8 +2120,16 @@
"project.tab_tasks": "任务",
"project.tab_auto": "自动化",
"project.context.title": "上下文",
- "project.context.instructions_tab": "说明",
+ "project.context.instructions_tab": "目标与规则",
"project.context.memory_tab": "记忆",
+ "project.context.scope": "项目内所有对话共享",
+ "project.instructions.heading": "当前生效的规则",
+ "project.instructions.setup": "设置目标与规则",
+ "project.instructions.edit_title": "目标与规则",
+ "project.instructions.saved": "已保存",
+ "project.instructions.discard_confirm": "放弃尚未保存的修改?",
+ "project.memory.heading": "已沉淀的事实与决策",
+ "project.memory.add_short": "添加",
"project.resources.title": "资源",
"project.resources.agents_tab": "智能体",
"project.resources.files_tab": "资料库",
@@ -2175,7 +2183,6 @@
"project.instructions.subtitle": "设置项目目标、优先事项和规则;每次对话 AI 都会参考并遵循。",
"project.memory.title": "项目记忆",
"project.memory.subtitle": "记录项目事实、决定和长期结论;后续对话 AI 会持续参考。",
- "project.memory.empty": "暂无项目记忆",
"project.memory.add": "新增项目记忆",
"project.memory.placeholder": "记录长期有效的事实、决定、约定或结论……",
"project.memory.edit": "编辑",
@@ -2236,7 +2243,7 @@
"search.source.custom": "自定义",
"search.source.marketplace": "平台",
"search.no_results": "未找到「{query}」相关内容",
- "search.history_indexing": "正在建立聊天记录索引,结果暂不完整,请稍后重试。",
+ "search.history_indexing": "正在准备中,结果暂不完整,请稍后重试。",
"search.role.user": "我",
"search.role.ai": "AI",
"model_guard.modal": "尚未添加模型,暂时无法使用此功能。\n\n请先在设置中添加模型账号。",
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index 09bdb946..c347e19a 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -52,6 +52,7 @@ const _IPC_ROUTES = [
['POST', '/api/contexts/reveal', 'contexts.reveal'],
['POST', '/api/library/write-text', 'library.writeText'],
['POST', '/api/search/global', 'search.global'],
+ ['GET', '/api/search/status', 'search.status'],
['POST', '/api/conversations/attachments/adopt', 'conversations.attachments.adopt'],
['POST', '/api/common/pick-directory', 'common.pickDirectory'],
['GET', '/api/kb/status', 'kb.status'],
diff --git a/src/renderer/modules/kb-picker.js b/src/renderer/modules/kb-picker.js
index b03a7f9a..af7190d3 100644
--- a/src/renderer/modules/kb-picker.js
+++ b/src/renderer/modules/kb-picker.js
@@ -299,6 +299,8 @@ async function confirmKbPicker() {
}
}
window.confirmKbPicker = confirmKbPicker;
+document.getElementById('kb-picker-cancel')?.addEventListener('click', closeKbPicker);
+document.getElementById('kb-picker-confirm')?.addEventListener('click', confirmKbPicker);
/**
* Derive a default filename stem from message content. Strips markdown
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
index 3bd39432..b213b5f5 100644
--- a/src/renderer/modules/project-detail.js
+++ b/src/renderer/modules/project-detail.js
@@ -486,6 +486,11 @@ function _bindProjectAutoAddBtn() {
// ── Project instructions (user-authored ORKAS.md) ─────────────────────────
// The user's own rules for this project — injected into every conversation
// in the project. User-owned: saved only from here, agents just read it.
+//
+// The rail reads: it shows the last saved rules as copy. Editing happens in
+// a dialog, so a draft is never mistaken for what conversations actually get.
+
+let _projectInstructionsStatusTimer = 0;
function _renderProjectInstructions() {
const input = document.getElementById('project-instructions-input');
@@ -499,9 +504,77 @@ function _renderProjectInstructions() {
// Instructions failed to load (e.g. legacy main) → disable rather than
// let a save blank out content we never saw.
input.disabled = !meta;
+ _renderProjectInstructionsRead();
_updateProjectInstructionsFoot();
}
+/** Mirror the saved rules into the rail. Reads `savedValue`, never the live
+ * textarea, so an open draft cannot leak into the read view. */
+function _renderProjectInstructionsRead() {
+ const input = document.getElementById('project-instructions-input');
+ const readEl = document.getElementById('project-instructions-read');
+ const emptyEl = document.getElementById('project-instructions-empty');
+ const headEl = document.querySelector('.project-side-instructions-panel .project-context-section-head');
+ const editBtn = document.getElementById('project-instructions-edit-btn');
+ const setupBtn = document.getElementById('project-instructions-setup-btn');
+ if (!readEl) return;
+ const saved = String(input?.dataset.savedValue || '');
+ const hasContent = !!saved.trim();
+ readEl.textContent = saved;
+ readEl.hidden = !hasContent;
+ if (emptyEl) emptyEl.hidden = hasContent;
+ // With no rules yet the empty state owns the call to action, so the
+ // "rules in effect" heading and its Edit button step aside.
+ if (headEl) headEl.hidden = !hasContent;
+ const locked = !input || input.disabled;
+ if (editBtn) editBtn.disabled = locked;
+ if (setupBtn) setupBtn.disabled = locked;
+}
+
+function _setProjectInstructionsStatus(text) {
+ const el = document.getElementById('project-instructions-status');
+ if (!el) return;
+ el.textContent = text || '';
+ clearTimeout(_projectInstructionsStatusTimer);
+ if (text) _projectInstructionsStatusTimer = setTimeout(() => { el.textContent = ''; }, 2400);
+}
+
+function _openProjectInstructionsEditor() {
+ const modal = document.getElementById('project-instructions-modal');
+ const input = document.getElementById('project-instructions-input');
+ if (!modal || !input || input.disabled) return;
+ input.value = input.dataset.savedValue || '';
+ _setProjectInstructionsStatus('');
+ modal.classList.add('open');
+ modal.setAttribute('aria-hidden', 'false');
+ _updateProjectInstructionsFoot();
+ input.focus();
+ const end = input.value.length;
+ input.setSelectionRange(end, end);
+}
+
+/** Close the editor. An unsaved draft asks first; `force` is for the path
+ * that already persisted the content. */
+async function _closeProjectInstructionsEditor({ force = false } = {}) {
+ const modal = document.getElementById('project-instructions-modal');
+ const input = document.getElementById('project-instructions-input');
+ if (!modal || !modal.classList.contains('open')) return;
+ const saved = input ? (input.dataset.savedValue || '') : '';
+ const dirty = !!input && !input.disabled && input.value !== saved;
+ if (!force && dirty && typeof uiConfirm === 'function') {
+ const ok = await uiConfirm(t('project.instructions.discard_confirm'));
+ if (!ok) return;
+ }
+ if (input) input.value = saved;
+ modal.classList.remove('open');
+ modal.setAttribute('aria-hidden', 'true');
+ _updateProjectInstructionsFoot();
+ const returnTo = saved.trim()
+ ? document.getElementById('project-instructions-edit-btn')
+ : document.getElementById('project-instructions-setup-btn');
+ returnTo?.focus();
+}
+
function _updateProjectInstructionsFoot() {
const input = document.getElementById('project-instructions-input');
const counter = document.getElementById('project-instructions-counter');
@@ -524,6 +597,30 @@ function _bindProjectInstructions() {
if (!input || input.dataset.bound === '1') return;
input.dataset.bound = '1';
input.addEventListener('input', _updateProjectInstructionsFoot);
+ input.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key !== 'Enter' || !(e.metaKey || e.ctrlKey)) return;
+ if (saveBtn?.disabled) return;
+ e.preventDefault();
+ saveBtn?.click();
+ });
+ document.getElementById('project-instructions-edit-btn')?.addEventListener('click', _openProjectInstructionsEditor);
+ document.getElementById('project-instructions-setup-btn')?.addEventListener('click', _openProjectInstructionsEditor);
+ document.getElementById('project-instructions-cancel-btn')?.addEventListener('click', () => {
+ _closeProjectInstructionsEditor();
+ });
+ document.getElementById('project-instructions-close-btn')?.addEventListener('click', () => {
+ _closeProjectInstructionsEditor();
+ });
+ document.getElementById('project-instructions-modal')?.addEventListener('mousedown', (e) => {
+ if (e.target === e.currentTarget) _closeProjectInstructionsEditor();
+ });
+ document.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229 || e.key !== 'Escape') return;
+ if (!document.getElementById('project-instructions-modal')?.classList.contains('open')) return;
+ e.preventDefault();
+ _closeProjectInstructionsEditor();
+ });
saveBtn?.addEventListener('click', async () => {
if (!_projectDetailPid || input.disabled) return;
const projectId = _projectDetailPid;
@@ -552,6 +649,9 @@ function _bindProjectInstructions() {
if (projectId === _projectDetailPid && _projectDetailMeta?.instructions) {
_projectDetailMeta.instructions.content = content;
}
+ _renderProjectInstructionsRead();
+ _closeProjectInstructionsEditor({ force: true });
+ _setProjectInstructionsStatus(t('project.instructions.saved'));
_projectTrackEvent('project_instructions_update_result', {
result: 'success',
source: 'detail',
@@ -746,14 +846,14 @@ function _renderProjectMemoryList() {
const actions = document.createElement('div');
actions.className = 'project-memory-item-actions';
+ // Written-out verbs, not glyphs: these two sit under body copy the user
+ // is reading, and a pencil next to a paragraph reads as decoration.
const edit = document.createElement('button');
edit.type = 'button';
edit.className = 'project-memory-item-action';
edit.dataset.action = 'project-memory-edit';
edit.dataset.memoryIndex = String(index);
- edit.title = t('project.memory.edit');
- edit.setAttribute('aria-label', edit.title);
- edit.innerHTML = typeof uiIconHtml === 'function' ? uiIconHtml('edit-pencil') : '✎';
+ edit.textContent = t('project.memory.edit');
actions.appendChild(edit);
const remove = document.createElement('button');
@@ -761,9 +861,7 @@ function _renderProjectMemoryList() {
remove.className = 'project-memory-item-action is-danger';
remove.dataset.action = 'project-memory-delete';
remove.dataset.memoryIndex = String(index);
- remove.title = t('project.memory.delete');
- remove.setAttribute('aria-label', remove.title);
- remove.innerHTML = typeof uiIconHtml === 'function' ? uiIconHtml('x') : '×';
+ remove.textContent = t('project.memory.delete');
actions.appendChild(remove);
row.appendChild(actions);
@@ -773,6 +871,10 @@ function _renderProjectMemoryList() {
listEl.style.display = shown ? '' : 'none';
if (countEl) countEl.textContent = shown > 0 ? String(shown) : '';
if (emptyEl) emptyEl.style.display = shown ? 'none' : '';
+ // Guidance until there is something saved, heading after — the same swap
+ // the goals-and-rules panel makes.
+ const headEl = document.getElementById('project-memory-section-head');
+ if (headEl) headEl.hidden = !shown;
}
function _updateProjectMemoryEditor() {
@@ -908,13 +1010,19 @@ async function _saveProjectMemoryEditor() {
}
function _bindProjectMemory() {
- const add = document.getElementById('project-memory-add-btn');
+ // Two ways in, one action: the header button once entries exist, and the
+ // empty state's own call to action before that.
+ const addButtons = [
+ document.getElementById('project-memory-add-btn'),
+ document.getElementById('project-memory-add-empty-btn'),
+ ];
const input = document.getElementById('project-memory-editor-input');
const cancel = document.getElementById('project-memory-editor-cancel');
const save = document.getElementById('project-memory-editor-save');
const list = document.getElementById('project-memory-list');
- if (add && add.dataset.bound !== '1') {
+ for (const add of addButtons) {
+ if (!add || add.dataset.bound === '1') continue;
add.dataset.bound = '1';
add.addEventListener('click', () => _openProjectMemoryEditor('add'));
}
diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.js
index d356515b..627a2883 100644
--- a/src/renderer/modules/search.js
+++ b/src/renderer/modules/search.js
@@ -18,6 +18,7 @@ let _searchResults = [];
let _searchActiveIdx = -1;
let _searchLastQuery = '';
let _searchChatIndexComplete = true;
+let _searchLoading = false;
const _SEARCH_FAILURE_DEDUPE_MS = 60 * 1000;
const _SEARCH_FAILURE_MAX_KEYS = 16;
const _SEARCH_FAILURE_STAGES = new Set(['request', 'response', 'partial']);
@@ -136,6 +137,7 @@ function openGlobalSearch(entryPoint = 'unknown') {
const input = document.getElementById('search-input');
if (input) {
input.value = '';
+ _searchLoading = false;
_searchResults = [];
_searchActiveIdx = -1;
_searchLastQuery = '';
@@ -145,6 +147,7 @@ function openGlobalSearch(entryPoint = 'unknown') {
_setSearchTabsVisible(false); // hide tabs while empty/history state is shown
setTimeout(() => input.focus(), 30);
_renderSearchEmptyState();
+ void _refreshSearchIndexStatus(_searchSeq, '', { active: true });
}
}
@@ -165,12 +168,18 @@ function closeGlobalSearch() {
// flight so it cannot repaint hidden state or report a failure the user no
// longer encountered.
_searchSeq++;
+ _searchLoading = false;
overlay.style.display = 'none';
if (_searchTimer) { clearTimeout(_searchTimer); _searchTimer = null; }
}
function _scheduleSearch(query) {
if (_searchTimer) clearTimeout(_searchTimer);
+ _searchTimer = null;
+ // Invalidate at input time, including the debounce window.
+ _searchSeq++;
+ if (!query.trim()) { void _runSearchNow(''); return; }
+ _showSearchLoading(query.trim());
// Library body search embeds the settled query once. A slightly longer
// debounce avoids running native inference for every intermediate IME or
// fast-typing state while keeping filename/chat feedback responsive.
@@ -190,10 +199,44 @@ function _activeProjectIdForSearch() {
return '';
}
+// Coverage must not wait for the all-scope query (including embeddings and
+// snippets). A late status response must never overwrite newer query results.
+async function _refreshSearchIndexStatus(seq, query, pending) {
+ try {
+ const response = await apiFetch('/api/search/status');
+ const data = await response.json();
+ if (seq !== _searchSeq || !pending.active || !data.ok) return;
+ _searchChatIndexComplete = data.chat_index_complete !== false;
+ if (!_searchChatIndexComplete) {
+ if (query) {
+ if (query !== _searchLastQuery) {
+ _searchResults = [];
+ _searchVisibleResults = [];
+ }
+ _searchLastQuery = query;
+ _setSearchTabsVisible(true);
+ _renderSearchResults(query);
+ } else _renderSearchEmptyState();
+ }
+ } catch (_) { /* the result response remains the authoritative fallback */ }
+}
+
+function _showSearchLoading(query) {
+ _searchLoading = true;
+ _searchResults = [];
+ _searchVisibleResults = [];
+ _searchActiveIdx = -1;
+ _searchLastQuery = query;
+ _setSearchTabsVisible(true);
+ _renderSearchResults(query);
+}
+
async function _runSearchNow(queryArg) {
+ if (_searchTimer) { clearTimeout(_searchTimer); _searchTimer = null; }
const input = document.getElementById('search-input');
const query = (queryArg !== undefined ? queryArg : (input?.value || '')).trim();
if (!query) {
+ _searchLoading = false;
_searchSeq++;
_searchResults = [];
_searchVisibleResults = [];
@@ -202,11 +245,15 @@ async function _runSearchNow(queryArg) {
_searchChatIndexComplete = true;
_setSearchTabsVisible(false);
_renderSearchEmptyState();
+ void _refreshSearchIndexStatus(_searchSeq, '', { active: true });
return;
}
const seq = ++_searchSeq;
const startedAt = Date.now();
const projectId = _activeProjectIdForSearch();
+ _showSearchLoading(query);
+ const pending = { active: true };
+ void _refreshSearchIndexStatus(seq, query, pending);
try {
const res = await apiFetch('/api/search/global', {
method: 'POST',
@@ -225,6 +272,7 @@ async function _runSearchNow(queryArg) {
});
return; // a newer query arrived; drop this
}
+ _searchLoading = false;
if (!data.ok) {
const failure = _reportGlobalSearchFailure('response', data, 'search_rejected');
_trackGlobalSearchResult('failure', failure.stage, startedAt, {
@@ -266,6 +314,7 @@ async function _runSearchNow(queryArg) {
});
return;
}
+ _searchLoading = false;
const failure = _reportGlobalSearchFailure('request', e, 'search_request_failed');
_trackGlobalSearchResult('failure', failure.stage, startedAt, {
has_project: !!projectId,
@@ -273,6 +322,8 @@ async function _runSearchNow(queryArg) {
error_code: failure.error_code,
});
_renderSearchError(e.message || String(e));
+ } finally {
+ pending.active = false;
}
}
@@ -331,7 +382,9 @@ function _renderSearchEmptyState() {
${history.map((q) => `<button class="search-history-item" data-history-q="${escapeHtml(q)}">${escapeHtml(q)}</button>`).join('')}
</div>`
: '';
- body.innerHTML = historyHtml || `<div class="search-empty">${escapeHtml(t('search.empty_hint'))}</div>`;
+ const notice = !_searchChatIndexComplete
+ ? `<div class="search-section-label is-status" role="status">${escapeHtml(t('search.history_indexing'))}</div>` : '';
+ body.innerHTML = notice + (historyHtml || (notice ? '' : `<div class="search-empty">${escapeHtml(t('search.empty_hint'))}</div>`));
body.querySelectorAll('[data-history-q]').forEach((btn) => {
btn.addEventListener('click', () => {
const q = btn.dataset.historyQ;
@@ -449,6 +502,10 @@ function _renderSearchResults(query) {
const notice = indexing
? `<div class="search-section-label is-status" role="status">${escapeHtml(t('search.history_indexing'))}</div>`
: '';
+ if (_searchLoading) {
+ body.innerHTML = notice + `<div class="search-empty search-loading" role="status"><span class="search-loading-spinner" aria-hidden="true"></span><span>${escapeHtml(t('common.loading'))}</span></div>`;
+ return;
+ }
if (!_searchResults.length) {
_searchVisibleResults = [];
body.innerHTML = indexing
@@ -644,7 +701,8 @@ function _saveSearchHistoryEntry(query) {
// with the active locale as well.
document.addEventListener('i18n-change', () => {
const overlay = document.getElementById('search-overlay');
- if (overlay && overlay.style.display !== 'none' && _searchLastQuery) {
- _renderSearchResults(_searchLastQuery);
+ if (overlay && overlay.style.display !== 'none') {
+ if (_searchLastQuery) _renderSearchResults(_searchLastQuery);
+ else _renderSearchEmptyState();
}
});
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index a6b42d79..89d56710 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -1857,8 +1857,9 @@ if (typeof document !== 'undefined') document.addEventListener('loadedmetadata',
* old conversation whose workspace was since cleaned would grow one tombstone
* per generated file where previously there was none.
*
- * Media the model wrote into its own prose keeps the placeholder: the
- * surrounding text refers to it, so its absence has to be visible.
+ * Media the model wrote into its own prose stays on the authored failure path:
+ * the surrounding text refers to it, so its absence normally has to remain
+ * visible. The narrow stale-duplicate exception is handled separately below.
*/
function _dropFailedProducedPreview(el) {
const host = el?.closest?.('.chat-msg-produced-media');
@@ -1869,6 +1870,47 @@ function _dropFailedProducedPreview(el) {
return true;
}
+// Return a basename only for media references that claim to be local. Remote
+// URLs with a coincidentally equal basename must never be folded into a file
+// produced by this turn.
+function _localMediaReferenceBasename(src) {
+ const raw = String(src || '').trim();
+ if (!raw || /[\u0000-\u001f\u007f]/.test(raw)) return '';
+ let local = _chatMediaLocalPathFromUrl(raw);
+ if (!local) {
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(raw)) return '';
+ local = raw.split(/[?#]/, 1)[0];
+ }
+ let base = String(local).split(/[\\/]/).filter(Boolean).pop() || '';
+ try { base = decodeURIComponent(base); } catch (_) { return ''; }
+ return base && !/[\u0000-\u001f\u007f]/.test(base) ? base : '';
+}
+
+/**
+ * A failed model-authored media reference normally stays visible so the user
+ * can see that the surrounding prose points at something missing. There is
+ * one stronger recovery signal: the same bubble already contains the host's
+ * produced-file preview with the same local basename and media kind. In that
+ * case the failed card is only a stale duplicate (for example an earlier
+ * narration audition path), while the produced preview is the usable result.
+ */
+function _dropFailedDuplicateMarkdownPreview(el) {
+ if (!el || el.closest?.('.chat-msg-produced-media')) return false;
+ const bubble = el.closest?.('.chat-bubble');
+ const base = _localMediaReferenceBasename(el.getAttribute?.('src'));
+ if (!bubble || !base || typeof bubble.querySelectorAll !== 'function') return false;
+ const tag = String(el.tagName || '').toLowerCase();
+ if (tag !== 'img' && tag !== 'video' && tag !== 'audio') return false;
+ const candidates = bubble.querySelectorAll(`.chat-msg-produced-media ${tag}[src]`);
+ const duplicate = Array.from(candidates).some((candidate) => (
+ _localMediaReferenceBasename(candidate.getAttribute?.('src')) === base
+ ));
+ if (!duplicate) return false;
+ const blockSelector = '.chat-image-shell, .chat-md-video-shell, .chat-md-audio-card';
+ (el.closest(blockSelector) || el).remove();
+ return true;
+}
+
if (typeof document !== 'undefined') document.addEventListener('error', (e) => {
const target = e.target;
if (!target || target.nodeType !== 1) return;
@@ -1877,6 +1919,7 @@ if (typeof document !== 'undefined') document.addEventListener('error', (e) => {
|| (target.tagName === 'AUDIO' && target.classList?.contains('chat-md-audio'));
if (!isChatMedia) return;
if (_dropFailedProducedPreview(target)) return;
+ if (_dropFailedDuplicateMarkdownPreview(target)) return;
if (target.tagName === 'IMG') {
_replaceMissingMarkdownImage(target);
return;
@@ -2627,6 +2670,7 @@ if (typeof module !== 'undefined' && typeof module.exports === 'object') {
_normalizeLocalMediaSrc,
_mediaDedupKey,
_dropFailedProducedPreview,
+ _localMediaReferenceBasename,
_parseOrkasMediaTitle,
_chatVideoNativeControlsHit,
escapeHtml,
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 4e99ebe4..6d411c62 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -511,6 +511,12 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: #94a3b8;
font-size: 13px;
}
+.search-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+}
.search-section-label {
padding: 8px 16px 4px;
font-size: 11px;
@@ -1135,8 +1141,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-detail-grid {
flex: 1;
display: grid;
- grid-template-columns: minmax(0, 1fr) 336px;
- gap: 22px;
+ grid-template-columns: minmax(0, 1fr) 352px;
+ gap: 20px;
align-items: stretch;
padding: 24px 28px;
min-height: 0;
@@ -1144,6 +1150,11 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
box-sizing: border-box;
overflow: hidden;
}
+/* Narrow windows (or a pinned app sidebar) get the previous rail width back
+ before the composer and task rows start losing room. */
+@media (max-width: 1280px) {
+ .project-detail-grid { grid-template-columns: minmax(0, 1fr) 336px; }
+}
.project-detail-main {
flex: 1;
min-width: 0;
@@ -1205,11 +1216,37 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-detail-tabs {
flex: 0 0 auto;
display: flex;
- align-items: center;
- min-height: 48px;
+ align-items: stretch;
+ min-height: 44px;
padding: 0 16px;
border-bottom: 1px solid var(--border);
}
+.project-detail-tabs > .project-detail-tab-group {
+ align-items: stretch;
+ gap: 20px;
+ min-height: 0;
+ margin-bottom: -1px;
+ padding: 0;
+ border-radius: 0;
+ background: transparent;
+}
+.project-detail-tabs .project-detail-tab {
+ align-self: stretch;
+ min-height: 0;
+ padding: 0;
+ border-radius: 0;
+ border-bottom: 2px solid transparent;
+ font-size: 13px;
+}
+.project-detail-tabs .project-detail-tab:hover {
+ color: var(--text);
+ background: transparent;
+}
+.project-detail-tabs .project-detail-tab.is-active {
+ border-bottom-color: var(--primary);
+ background: transparent;
+ box-shadow: none;
+}
.project-detail-tab-group {
display: inline-flex;
align-items: center;
@@ -1254,7 +1291,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--muted);
background: transparent;
font-family: var(--font-mono);
- font-size: 10.5px;
+ font-size: 11px;
font-weight: 500;
line-height: 1;
text-align: center;
@@ -1281,16 +1318,23 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
text-align: center;
}
+/* Right rail sizes to its content. The two cards used to split the column
+ in half, which left the Context card holding a tall empty textarea and the
+ Resources card stretched past its last row. The rail itself scrolls when
+ the cards outgrow the viewport. */
.project-detail-side {
min-width: 0;
min-height: 0;
- display: grid;
- grid-template-rows: repeat(2, minmax(0, 1fr));
- gap: 12px;
- overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ align-content: flex-start;
+ gap: 16px;
+ overflow-y: auto;
+ padding-right: 2px;
}
.project-side-card {
+ flex: 0 0 auto;
min-height: 0;
display: flex;
flex-direction: column;
@@ -1301,38 +1345,114 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
/* Instructions are user-authored rules injected into every conversation in
- the project. They share the Context card with agent-written memory. */
+ the project. They share the Context card with agent-written memory. The
+ panel shows the saved text; `.project-instructions-input` lives in the
+ editor dialog. */
.project-context-help {
flex: 0 0 auto;
+ margin: 0 0 12px;
+ padding: 0;
+ color: var(--text-2);
+ font-size: 12px;
+ line-height: 1.5;
+}
+.project-context-section-head {
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-height: 28px;
+ margin-bottom: 8px;
+}
+.project-context-section-head[hidden] { display: none; }
+.project-context-section-title {
margin: 0;
- padding: 8px 12px 0;
- color: var(--muted);
- font-size: 11px;
- line-height: 1.45;
+ min-width: 0;
+ color: var(--text);
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 1.35;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
+/* Secondary by default: saving and sending are the only primary-filled
+ actions on this surface. */
+.project-context-action {
+ flex: 0 0 auto;
+}
+.project-instructions-read {
+ flex: 0 1 auto;
+ min-height: 0;
+ max-height: 248px;
+ overflow-y: auto;
+ margin-bottom: 14px;
+ color: var(--text);
+ font-size: 13.5px;
+ line-height: 1.7;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.project-instructions-read[hidden] { display: none; }
+.project-instructions-empty {
+ flex: 0 0 auto;
+ padding: 2px 0 4px;
+}
+.project-instructions-empty[hidden] { display: none; }
+.project-context-status {
+ flex: 0 0 auto;
+ min-height: 16px;
+ margin-top: 6px;
+ color: var(--primary-text);
+ font-size: 11.5px;
+ line-height: 1.4;
+}
+.project-context-status:empty { min-height: 0; }
+
+/* Editor dialog — one text field, sized for writing a page of rules. */
+.project-instructions-dialog {
+ max-width: 640px;
+ padding: 24px;
+}
+.project-instructions-dialog .project-context-help { margin-bottom: 10px; }
.project-instructions-input {
- flex: 1 1 auto;
- width: calc(100% - 24px);
+ width: 100%;
box-sizing: border-box;
- margin: 7px 12px 6px;
- padding: 8px 10px;
- border: 1px solid var(--border);
+ padding: 12px;
+ border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--text);
- font-size: 12.5px;
- line-height: 1.5;
- resize: none;
- min-height: 0;
+ font-family: inherit;
+ font-size: 14px;
+ line-height: 1.7;
+ resize: vertical;
+ min-height: 240px;
+ outline: none;
+}
+.project-instructions-input:focus {
+ border-color: var(--primary);
+ box-shadow: 0 0 0 2px var(--primary-soft);
}
.project-instructions-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
- padding: 0 12px 10px;
+ margin-top: 16px;
+ padding-top: 14px;
+ border-top: 1px solid var(--border);
+}
+.project-instructions-foot-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+}
+.project-instructions-counter {
+ font-family: var(--font-mono);
+ font-size: 11px;
}
-.project-instructions-counter { font-size: 11px; }
.project-instructions-counter.is-over { color: var(--danger); }
.project-side-card-head {
@@ -1347,31 +1467,47 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
border-bottom: 1px solid var(--border);
background: var(--surface);
}
+/* Card identity on one line, the two context/resource types on the next.
+ One 44px strip could not hold a title, two tabs and an action without
+ shrinking the tabs to 11px. */
.project-side-card-head-tabs {
- min-height: 44px;
+ flex-direction: column;
+ align-items: stretch;
justify-content: flex-start;
- padding-top: 0;
- padding-bottom: 0;
+ gap: 10px;
+ min-height: 0;
+ padding: 14px 16px 0;
}
-.project-side-card-head-tabs > .project-side-card-title-wrap {
- flex: 0 0 auto;
- align-self: center;
+.project-side-card-head-top {
+ display: flex;
align-items: center;
+ gap: 8px;
+ min-height: 24px;
}
-.project-side-card-head-tabs > .project-side-tabs {
+.project-side-card-head-top > .project-side-card-title-wrap { flex: 1 1 auto; }
+.project-side-card-head-top > .project-side-icon-btn { flex: 0 0 auto; }
+.project-side-card-scope {
flex: 0 1 auto;
- align-self: center;
min-width: 0;
- min-height: 28px;
- height: 28px;
- gap: 2px;
- padding: 2px;
- border-bottom: 0;
- border-radius: 8px;
+ margin-left: auto;
+ padding: 2px 8px;
+ border-radius: 6px;
background: var(--surface-2);
+ color: var(--text-2);
+ font-size: 11.5px;
+ line-height: 1.4;
+ text-align: right;
}
-.project-side-card-head-tabs > .project-side-icon-btn {
- margin-left: auto;
+.project-side-card-head-tabs > .project-side-tabs {
+ flex: 0 0 auto;
+ align-self: stretch;
+ min-width: 0;
+ min-height: 34px;
+ margin-bottom: -1px;
+ gap: 20px;
+ padding: 0;
+ border-bottom: 0;
+ background: transparent;
}
.project-side-card-title-wrap {
@@ -1382,7 +1518,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.project-side-card-title {
- font-size: 12.5px;
+ font-size: 13px;
font-weight: 600;
color: var(--text);
min-width: 0;
@@ -1424,20 +1560,22 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-side-card-count,
.project-side-tab-count {
font-family: var(--font-mono);
- font-size: 10.5px;
+ font-size: 11px;
color: var(--muted);
}
.project-side-card-count:empty,
.project-side-tab-count:empty { display: none; }
+/* Underlined tabs, same size and rhythm as the workbench tabs in the main
+ column — one tab idiom on the page instead of two pill sizes. */
.project-side-tabs {
flex: 0 0 auto;
display: flex;
- align-items: center;
- gap: 16px;
- min-height: 38px;
- padding: 0 12px;
+ align-items: stretch;
+ gap: 20px;
+ min-height: 34px;
+ padding: 0 16px;
border-bottom: 1px solid var(--border);
}
.project-side-tab {
@@ -1445,45 +1583,25 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
align-self: stretch;
display: inline-flex;
align-items: center;
- gap: 5px;
+ gap: 6px;
padding: 0;
border: 0;
border-bottom: 2px solid transparent;
- color: var(--muted);
+ color: var(--text-2);
background: transparent;
font-family: inherit;
- font-size: 11.5px;
+ font-size: 13px;
+ font-weight: 500;
cursor: pointer;
+ transition: color 0.15s, border-color 0.15s;
}
-.project-side-tab:hover { color: var(--text-2); }
+.project-side-tab:hover { color: var(--text); }
.project-side-tab.is-active {
- margin-bottom: -1px;
border-bottom-color: var(--primary);
- color: var(--text);
- font-weight: 600;
-}
-.project-side-card-head-tabs .project-side-tab {
- align-self: stretch;
- padding: 0 8px;
- border: 0;
- border-radius: 6px;
- color: var(--muted);
- font-size: 11px;
-}
-.project-side-card-head-tabs .project-side-tab:hover {
- color: var(--text-2);
- background: rgba(255, 255, 255, 0.55);
-}
-.project-side-card-head-tabs .project-side-tab.is-active {
- margin-bottom: 0;
- border-bottom-color: transparent;
- color: var(--primary-text);
- background: var(--surface);
- box-shadow: 0 1px 3px rgba(15, 23, 42, 0.12);
-}
-.project-side-card-head-tabs .project-side-tab.is-active .project-side-tab-count {
color: var(--primary-text);
+ font-weight: 600;
}
+.project-side-tab.is-active .project-side-tab-count { color: var(--primary-text); }
.project-side-panel {
flex: 1 1 auto;
min-height: 0;
@@ -1492,15 +1610,31 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
overflow: hidden;
}
.project-side-panel[hidden] { display: none; }
+.project-side-instructions-panel,
+.project-side-memory-panel {
+ padding: 14px 16px 16px;
+}
.project-side-memory-panel .project-memory-list {
- padding: 7px 12px 12px;
+ flex: 0 1 auto;
+ max-height: 320px;
+ padding: 0;
+}
+/* Empty memory reads like the empty rules panel — guidance left-aligned with
+ its call to action, not a centred placeholder. Keeps `.empty` so the open
+ editor still hides it through the sibling rule below. */
+#project-memory-empty {
+ display: block;
+ flex: 0 0 auto;
+ min-height: 0;
+ padding: 2px 0 4px;
+ text-align: left;
}
.project-memory-editor {
- flex: 1 1 auto;
+ flex: 0 0 auto;
min-height: 0;
display: flex;
flex-direction: column;
- padding: 7px 12px 12px;
+ padding: 0 0 8px;
background: var(--surface);
}
.project-memory-editor[hidden] { display: none; }
@@ -1511,7 +1645,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
.project-memory-editor-input {
flex: 1 1 auto;
width: 100%;
- min-height: 56px;
+ min-height: 84px;
box-sizing: border-box;
padding: 8px 10px;
resize: none;
@@ -1521,8 +1655,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--text);
background: var(--surface);
font-family: inherit;
- font-size: 12.5px;
- line-height: 1.5;
+ font-size: 13px;
+ line-height: 1.6;
}
.project-memory-editor-input:focus {
border-color: var(--primary);
@@ -1545,7 +1679,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
gap: 6px;
}
.project-side-files-panel .project-library-side-list {
- flex: 1 1 auto;
+ flex: 0 1 auto;
+ max-height: 320px;
}
/* To-do lives in the normal project workbench as a third tab. The composer and
right rail remain part of the project detail layout in every tab. */
@@ -1568,14 +1703,15 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
display: flex;
align-items: center;
justify-content: center;
- min-height: 0;
+ min-height: 84px;
padding: 12px;
text-align: center;
}
.project-side-card-list {
- flex: 1;
+ flex: 0 1 auto;
min-height: 0;
+ max-height: 320px;
overflow-y: auto;
}
@@ -1890,16 +2026,20 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
/* Project memory card — plain body-copy rows from the project's MEMORY.md. */
-.project-memory-list { display: flex; flex-direction: column; gap: 2px; }
+.project-memory-list { display: flex; flex-direction: column; gap: 0; }
.project-memory-item {
display: flex;
- align-items: flex-start;
- gap: 8px;
- padding: 6px 0;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 4px;
+ padding: 10px 0;
+ border-bottom: 1px solid var(--border);
color: var(--text);
- font-size: 12.5px;
- line-height: 1.5;
+ font-size: 13px;
+ line-height: 1.6;
}
+.project-memory-item:first-child { padding-top: 2px; }
+.project-memory-item:last-child { border-bottom: 0; padding-bottom: 2px; }
.project-memory-item-text {
flex: 1 1 auto;
min-width: 0;
@@ -1908,23 +2048,24 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
.project-memory-item-actions {
flex: 0 0 auto;
- display: inline-flex;
+ display: flex;
align-items: center;
+ justify-content: flex-end;
gap: 2px;
}
.project-memory-item-action {
- width: 22px;
- height: 22px;
- padding: 0;
+ min-height: 24px;
+ padding: 2px 8px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 0;
- border-radius: 5px;
- color: var(--muted);
+ border-radius: 6px;
+ color: var(--text-2);
background: transparent;
font-family: inherit;
- font-size: 14px;
+ font-size: 12px;
+ line-height: 1.4;
cursor: pointer;
}
.project-memory-item-action:hover {
@@ -1935,7 +2076,6 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--danger);
background: rgba(220, 38, 38, 0.08);
}
-.project-memory-item-action svg { width: 13px; height: 13px; }
.project-side-card-list::-webkit-scrollbar,
.project-detail-tab-panel::-webkit-scrollbar,
@@ -2043,6 +2183,19 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
min-width: 44px;
height: 28px;
}
+.project-agent-row .agent-card-use {
+ background: transparent;
+ border-color: var(--border-strong);
+ color: var(--text-2);
+ transition: background 0.12s, color 0.12s, border-color 0.12s, box-shadow 0.12s;
+}
+.project-agent-row:hover .agent-card-use:not(:disabled),
+.project-agent-row .agent-card-use:not(:disabled):hover,
+.project-agent-row .agent-card-use:not(:disabled):focus-visible {
+ background: var(--primary);
+ border-color: var(--primary);
+ color: #fff;
+}
.project-agent-row-remove {
flex-shrink: 0;
width: 24px;
@@ -2066,6 +2219,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
#project-agents-empty {
flex: 1;
+ min-height: 84px;
display: flex;
align-items: center;
justify-content: center;
@@ -2490,8 +2644,15 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
}
@media (max-width: 980px) {
+ /* Single column: each row takes its content height and the page scrolls.
+ Auto rows here still get stretched to equal halves by the grid's definite
+ height, which squeezes the task list until the rail paints over it —
+ hence min-content tracks packed from the top. */
.project-detail-grid {
grid-template-columns: 1fr;
+ grid-template-rows: min-content min-content;
+ align-content: start;
+ align-items: start;
min-height: 0;
overflow-y: auto;
}
@@ -2499,8 +2660,7 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
overflow: visible;
}
.project-detail-side {
- grid-template-rows: repeat(2, minmax(220px, 1fr));
- min-height: 452px;
+ overflow: visible;
}
.chat-input-area.is-project {
max-width: 100%;
@@ -4030,8 +4190,9 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
/* AI-team grid only: a screen of filled primary "use" blocks reads as noise,
so inside `.agent-card` the button rests as a ghost and fills only while
its own card is hovered (or the button is keyboard-focused). Other reuses
- of `.agent-card-use` (detail dialog, connector cards, project rows) render
- a single button and keep the filled default. Rules sit after the shared
+ of `.agent-card-use` (detail dialog, connector cards) render a single
+ button and keep the filled default; the project rail does the same ghost
+ trick as the grid for the same reason. Rules sit after the shared
family so the equal-specificity disabled override below wins by order. */
.agent-card .agent-card-use {
background: transparent;
@@ -5846,6 +6007,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.chat-history-load-earlier.is-error {
color: var(--danger);
}
+.search-loading-spinner,
.chat-history-inline-spinner {
width: 14px;
height: 14px;
@@ -5856,6 +6018,10 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
animation: spin 0.8s linear infinite;
}
+@media (prefers-reduced-motion: reduce) {
+ .search-loading-spinner { animation: none; }
+}
+
/* While a new exchange is in flight, a DOM spacer (`.chat-scroll-spacer`)
is appended as the last child of the messages container to reserve room
so a short user message can scroll to the top of the viewport. Using a
@@ -15808,7 +15974,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
background: var(--surface);
border-color: var(--border-strong);
}
-.header-entry-btn-create { background: var(--surface-2); }
.header-entry-btn:hover { background: var(--surface-2); }
.header-entry-btn:active { background: var(--primary-soft); }
.header-entry-btn:focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }
diff --git a/test/e2e/chat_e2e_model_stream.spec.ts b/test/e2e/chat_e2e_model_stream.spec.ts
index 85787c85..5215643a 100644
--- a/test/e2e/chat_e2e_model_stream.spec.ts
+++ b/test/e2e/chat_e2e_model_stream.spec.ts
@@ -45,7 +45,7 @@ async function sendNewChatToAgent(
function destructiveDeleteCommand(filePath: string, recursive = false): string {
return process.platform === 'win32'
? `Remove-Item -Force${recursive ? ' -Recurse' : ''} -LiteralPath ${JSON.stringify(filePath)}`
- : `rm ${recursive ? '-rf' : '-f'} ${JSON.stringify(filePath)}`;
+ : `rm ${recursive ? '-r' : '-f'} ${JSON.stringify(filePath)}`;
}
async function requireApprovalMode(
@@ -278,7 +278,7 @@ test.describe('real chat pipeline with a local model', () => {
expect(modelOrkas.modelRequests).toHaveLength(3);
});
- test('shows a started tool action before delayed arguments and replaces only that lifecycle row', async ({ modelOrkas }) => {
+ test('shows a preparing tool action before delayed arguments and replaces only that lifecycle row', async ({ modelOrkas }) => {
const outputPath = path.join(modelOrkas.userWorkspaceRoot, 'delayed-process.html');
expect(existsSync(outputPath)).toBe(false);
modelOrkas.setDelayedWriteFileScenario(
@@ -292,7 +292,7 @@ test.describe('real chat pipeline with a local model', () => {
const lifecycleRow = page.locator(
'#chat-history .stream-process-line[data-process-call-id^="tool:call-e2e-write-conflict-file"]',
);
- await expect(lifecycleRow).toHaveText('Started · Edit file', { timeout: 20_000 });
+ await expect(lifecycleRow).toHaveText('Preparing: Edit file', { timeout: 20_000 });
expect(existsSync(outputPath)).toBe(false);
await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toContainText(
diff --git a/test/e2e/conversation_outputs_e2e_panel.spec.ts b/test/e2e/conversation_outputs_e2e_panel.spec.ts
index 28d4007b..e3ca00ec 100644
--- a/test/e2e/conversation_outputs_e2e_panel.spec.ts
+++ b/test/e2e/conversation_outputs_e2e_panel.spec.ts
@@ -51,6 +51,32 @@ function pngBytes(width: number, height: number): Buffer {
]);
}
+/** A short, valid PCM WAV so Chromium has real metadata to distinguish the
+ * usable produced narration from the stale same-named reference. */
+function wavBytes(): Buffer {
+ const sampleRate = 8_000;
+ const samples = 800;
+ const pcm = Buffer.alloc(samples * 2);
+ for (let i = 0; i < samples; i += 1) {
+ pcm.writeInt16LE(Math.round(Math.sin((i / sampleRate) * Math.PI * 2 * 440) * 8_000), i * 2);
+ }
+ const out = Buffer.alloc(44 + pcm.length);
+ out.write('RIFF', 0, 'ascii');
+ out.writeUInt32LE(out.length - 8, 4);
+ out.write('WAVEfmt ', 8, 'ascii');
+ out.writeUInt32LE(16, 16);
+ out.writeUInt16LE(1, 20);
+ out.writeUInt16LE(1, 22);
+ out.writeUInt32LE(sampleRate, 24);
+ out.writeUInt32LE(sampleRate * 2, 28);
+ out.writeUInt16LE(2, 32);
+ out.writeUInt16LE(16, 34);
+ out.write('data', 36, 'ascii');
+ out.writeUInt32LE(pcm.length, 40);
+ pcm.copy(out, 44);
+ return out;
+}
+
test.describe.configure({ timeout: 120_000 });
test('surfaces produced files, outside files, and artifacts for one conversation', async ({ orkas }, testInfo) => {
@@ -181,6 +207,31 @@ test('surfaces produced files, outside files, and artifacts for one conversation
await expect(pasted.locator('img.chat-md-img')).toHaveCount(1);
await expect(pasted.locator('.chat-msg-produced-media')).toHaveCount(0);
+ // A model can retain an earlier audition path while the completed turn
+ // publishes a new same-named narration. The stale player reports 0:00 and
+ // the host-rendered produced player works; once that failure is known, keep
+ // only the usable narration rather than showing two indistinguishable cards.
+ const narrationPath = path.join(wsDir, 'narration.wav');
+ writeFileSync(narrationPath, wavBytes());
+ const staleNarrationPath = path.join(listing.root, 'discarded-audition', 'narration.wav');
+ const staleNarrationUrl = `chat-media://local/${
+ staleNarrationPath.replace(/^\//, '').split('/').map(encodeURIComponent).join('/')
+ }`;
+ appendFileSync(chatFile(cid), `${JSON.stringify({
+ id: 'm_outputs_reply_stale_narration',
+ ts: new Date().toISOString(),
+ from: 'commander',
+ to: ['user'],
+ text: `Narration audition:\n\n[narration.wav](${staleNarrationUrl})`,
+ produced: [narrationPath],
+ })}\n`, 'utf8');
+ await reopen();
+
+ const narration = page.locator('#chat-history .chat-message.assistant').last();
+ await expect(narration.locator('.chat-md-audio-card')).toHaveCount(1);
+ await expect(narration.locator('.chat-msg-produced-media .chat-md-audio')).toHaveJSProperty('duration', 0.1);
+ await expect(narration.locator('.chat-msg-produced-item')).toContainText('narration.wav');
+
// Revisit existing files in the body while the footer contains only this
// reply's new output. The outside file needs the current conversation scope;
// a custom link label must not replace the filename used to select a viewer.
diff --git a/test/e2e/projects_e2e_smoke.spec.ts b/test/e2e/projects_e2e_smoke.spec.ts
index 984a1a0b..997148a9 100644
--- a/test/e2e/projects_e2e_smoke.spec.ts
+++ b/test/e2e/projects_e2e_smoke.spec.ts
@@ -74,15 +74,23 @@ test.describe('projects', () => {
if (!orkas.page) throw new Error('Orkas renderer is unavailable');
let page = orkas.page;
+ // A project with no rules yet shows the empty state; the textarea lives in
+ // the editor dialog behind it.
+ await page.locator('#project-instructions-setup-btn').click();
const instructions = page.locator('#project-instructions-input');
await expect(instructions).toBeEnabled();
await instructions.fill('Always verify generated artifacts before reporting completion.');
await page.locator('#project-instructions-save-btn').click();
await expect(page.locator('#project-instructions-save-btn')).toBeDisabled();
+ await expect(page.locator('#project-instructions-modal')).not.toHaveClass(/open/);
+ await expect(page.locator('#project-instructions-read')).toHaveText(
+ 'Always verify generated artifacts before reporting completion.',
+ );
await page.locator('[data-project-side-tabs="context"] [data-project-side-tab="memory"]').click();
await expect(page.locator('[data-project-side-panel="memory"]')).toBeVisible();
- await page.locator('#project-memory-add-btn').click();
+ // No memory yet, so the empty state owns the call to action.
+ await page.locator('#project-memory-add-empty-btn').click();
await page.locator('#project-memory-editor-input').fill('The release checklist is the source of truth.');
await page.locator('#project-memory-editor-save').click();
await expect(page.locator('.project-memory-item', { hasText: 'The release checklist is the source of truth.' })).toBeVisible();
@@ -103,7 +111,7 @@ test.describe('projects', () => {
has: page.locator('.project-name', { hasText: projectName }),
});
await projectRow.click();
- await expect(page.locator('#project-instructions-input')).toHaveValue(
+ await expect(page.locator('#project-instructions-read')).toHaveText(
'Always verify generated artifacts before reporting completion.',
);
await page.locator('[data-project-side-tabs="context"] [data-project-side-tab="memory"]').click();
diff --git a/test/e2e/search_e2e_rebuild.spec.ts b/test/e2e/search_e2e_rebuild.spec.ts
new file mode 100644
index 00000000..1a35efdb
--- /dev/null
+++ b/test/e2e/search_e2e_rebuild.spec.ts
@@ -0,0 +1,193 @@
+import path from 'node:path';
+import { cpSync, mkdirSync, readFileSync, existsSync } from 'node:fs';
+import { createPackageWithOptions } from '@electron/asar';
+import { expect, test, OrkasTestApp } from './fixtures/orkas';
+
+const pcRoot = path.resolve(__dirname, '../..');
+let previousKeepLogs: string | undefined;
+test.beforeEach(() => {
+ previousKeepLogs = process.env.ORKAS_E2E_KEEP_LOGS;
+ process.env.ORKAS_E2E_KEEP_LOGS = '1';
+});
+test.afterEach(async ({}, info) => {
+ if (previousKeepLogs === undefined) delete process.env.ORKAS_E2E_KEEP_LOGS;
+ else process.env.ORKAS_E2E_KEEP_LOGS = previousKeepLogs;
+ const file = info.outputPath('electron-main.log');
+ expect(existsSync(file), 'Retain all main, renderer and cleanup logs on success too').toBe(true);
+});
+
+test('shows preparation before full results, searches partial history, and resumes after a real Electron restart', async ({}, testInfo) => {
+ test.setTimeout(120_000);
+ const app = new OrkasTestApp(testInfo, { configuredModel: false });
+ try {
+ await app.launch();
+ await app.invoke('config.setLanguage', { language: 'zh' });
+ await app.page!.evaluate(() => (window as any).setLang('zh'));
+ const created = await app.invoke<{ conversation: { conversation_id: string } }>('conversations.create', {
+ title: 'Search recovery fixture',
+ });
+ const cid = created.conversation.conversation_id;
+ const prefix = await app.electronApp!.evaluate(async (_electron, input) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ const ix = require(`${input.root}/src/main/features/search/indexer.ts`);
+ const boot = require(`${input.root}/src/main/util/boot_init.ts`);
+ boot.configureBootAdmission({ isRuntimeBusy: () => true });
+ await ix.flushAll();
+ const uid = require(`${input.root}/src/main/features/users.ts`).getActiveUserId();
+ const paths = require(`${input.root}/src/main/paths.ts`);
+ const layout = require(`${input.root}/src/main/util/project-layout.ts`);
+ const fs = require('node:fs');
+ const file = layout.conversationMessageReadFile(uid, input.cid);
+ fs.writeFileSync(file, Array.from({ length: 70 }, (_, i) => JSON.stringify({
+ role: 'user', content: i === 69 ? 'suffixmarker' : `prefixmarker row${i}`, time: '2026-09-20T00:00:00Z',
+ })).join('\n') + '\n');
+ const store = require(`${input.root}/src/main/features/search/chat_store.ts`);
+ store.docCount(uid);
+ const Database = require(`${input.root}/node_modules/better-sqlite3`);
+ const db = new Database(store.chatStorePath(uid));
+ db.exec("DELETE FROM chat_meta WHERE key IN ('migration_complete', 'source_stamp')");
+ db.close();
+ fs.writeFileSync(paths.userChatsIndexPath(uid), '{}');
+ ix.invalidateChatsIndex(uid);
+ const { ChatRebuildWorker } = require(`${input.root}/src/main/features/search/chat-rebuild.ts`);
+ const original = ChatRebuildWorker.prototype.rebuildBatch;
+ const controller = new AbortController();
+ ChatRebuildWorker.prototype.rebuildBatch = async function(file: unknown) {
+ const batch = await original.call(this, file);
+ controller.abort();
+ return batch;
+ };
+ try { await ix.reconcileChatsIndex(uid, controller.signal); }
+ finally { ChatRebuildWorker.prototype.rebuildBatch = original; }
+ return { count: store.docCount(uid), next: store.readRebuildCursor(uid, input.cid)?.next,
+ id: store.postingsFor(uid, 'row0')[0]?.doc, legacy: fs.existsSync(paths.userChatsIndexPath(uid)) };
+ }, { root: pcRoot, cid });
+ expect(prefix).toMatchObject({ count: 16, next: 16, legacy: true });
+ expect(prefix.id).toBeGreaterThan(0);
+ expect(await app.invoke('search.status')).toMatchObject({ ok: true, chat_index_complete: false });
+ expect(await app.invoke('search.global', { query: 'suffixmarker', scope: 'chat' }))
+ .toMatchObject({ ok: true, chat_index_complete: false, results: [] });
+
+ let page = app.page!;
+ // Hold only delivery of the real global request. Status uses the actual
+ // renderer shim/preload/IPC handler; no search or status response is faked.
+ await page.evaluate(() => {
+ const app = window as any;
+ const original = app.apiFetch;
+ app.__searchRelease = null;
+ const gate = new Promise<void>(resolve => { app.__searchRelease = resolve; });
+ app.apiFetch = async (url: string, options: unknown) => {
+ if (url === '/api/search/global') await gate;
+ return original(url, options);
+ };
+ });
+ await page.locator('#sidebar-search-btn').click();
+ const notice = page.locator('#search-body .is-status');
+ const copy = '正在准备中,结果暂不完整,请稍后重试。';
+ await expect(notice).toHaveText(copy);
+ await page.locator('#search-input').fill('prefixmarker');
+ const loading = page.locator('#search-body .search-loading');
+ await expect(loading).toHaveText('加载中…');
+ await expect(loading.locator('.search-loading-spinner')).toBeVisible();
+ await page.screenshot({ path: testInfo.outputPath('search-loading.png') });
+ await expect(notice).toHaveText(copy);
+ await expect(page.locator('#search-body .search-result')).toHaveCount(0);
+ await page.evaluate(() => (window as any).__searchRelease());
+ await expect(page.locator('#search-body .search-result').first()).toBeVisible();
+ await expect(notice).toHaveText(copy);
+ await expect(loading).toHaveCount(0);
+ await page.screenshot({ path: testInfo.outputPath('partial-search.png') });
+ await page.locator('#search-close-btn').click();
+
+ page = await app.relaunch();
+ // Startup owns resumption; no manual repair invocation after relaunch.
+ // Low-memory hosts start the deferred phase after 6s, then admit disk
+ // work after another 30s. Allow that documented boot budget, not a query
+ // repair that would hide a broken startup continuation.
+ await expect.poll(async () => app.invoke('search.status'), { timeout: 60_000 })
+ .toMatchObject({ ok: true, chat_index_complete: true });
+ const resumed = await app.electronApp!.evaluate((_electron, root) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ const uid = require(`${root}/src/main/features/users.ts`).getActiveUserId();
+ const store = require(`${root}/src/main/features/search/chat_store.ts`);
+ return { count: store.docCount(uid), prefixId: store.postingsFor(uid, 'row0')[0]?.doc,
+ legacy: require('node:fs').existsSync(require(`${root}/src/main/paths.ts`).userChatsIndexPath(uid)) };
+ }, pcRoot);
+ expect(resumed).toEqual({ count: 70, prefixId: prefix.id, legacy: false });
+ await page.locator('#sidebar-search-btn').click();
+ await page.locator('#search-input').fill('suffixmarker');
+ await expect(page.locator('#search-body .search-result').first()).toBeVisible();
+ await expect(page.locator('#search-body [role="status"]')).toHaveCount(0);
+ await page.screenshot({ path: testInfo.outputPath('complete-search.png') });
+ expect(app.modelRequests).toHaveLength(0);
+ } finally { await app.dispose(); }
+});
+
+test('runs rebuild and snippet workers from an ASAR with the shipped dependency layout', async ({}, testInfo) => {
+ const app = new OrkasTestApp(testInfo, { configuredModel: false });
+ try {
+ const source = path.join(app.root, 'package-source');
+ const archive = path.join(app.root, 'fixture.asar');
+ const pkg = JSON.parse(readFileSync(path.join(pcRoot, 'package.json'), 'utf8'));
+ mkdirSync(source, { recursive: true });
+ cpSync(path.join(pcRoot, 'src/main'), path.join(source, 'src/main'), { recursive: true });
+ cpSync(path.join(pcRoot, 'package.json'), path.join(source, 'package.json'));
+ cpSync(path.join(pcRoot, 'tsconfig.json'), path.join(source, 'tsconfig.json'));
+ const dependencies = ['tsx', 'get-tsconfig', 'resolve-pkg-maps', 'esbuild',
+ `@esbuild/${process.platform}-${process.arch}`, 'better-sqlite3', 'bindings',
+ 'file-uri-to-path', 'electron-log', 'async-mutex', 'tslib'];
+ for (const name of dependencies) {
+ cpSync(path.join(pcRoot, 'node_modules', name), path.join(source, 'node_modules', name),
+ { recursive: true, dereference: true });
+ }
+ // Use the actual packaging rules, not a test-only unpack-all workaround.
+ // asar matches absolute filenames; electron-builder's patterns are relative.
+ const unpack = pkg.build.asarUnpack.map((pattern: string) => path.join(source, pattern).replaceAll('\\', '/'));
+ await createPackageWithOptions(source, archive, { unpack: `{${unpack.join(',')}}` });
+ const esbuild = path.join(`${archive}.unpacked`, 'node_modules', '@esbuild',
+ `${process.platform}-${process.arch}`, ...(process.platform === 'win32' ? ['esbuild.exe'] : ['bin', 'esbuild']));
+ expect(existsSync(esbuild)).toBe(true);
+ await app.launch();
+ const result = await app.electronApp!.evaluate(async (_electron, input) => {
+ const require = (process as any).mainModule.require.bind((process as any).mainModule);
+ const old = process.env.ESBUILD_BINARY_PATH;
+ process.env.ESBUILD_BINARY_PATH = input.esbuild;
+ const { ChatRebuildWorker } = require(`${input.archive}/src/main/features/search/chat-rebuild.ts`);
+ // The host already has its reader/logger loaded. Only the new worker
+ // executes the packaged copy; loading a second main logger registers
+ // duplicate Electron IPC handlers and is not a real packaging path.
+ const store = require(`${input.sourceRoot}/src/main/features/search/chat_store.ts`);
+ const paths = require(`${input.sourceRoot}/src/main/paths.ts`);
+ const fs = require('node:fs');
+ const file = require('node:path').join(paths.userChatsDir('packaged-fixture'), 'source.jsonl');
+ fs.mkdirSync(require('node:path').dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify({ role: 'user', content: 'packagedmarker', time: 't' }) + '\n');
+ const stat = fs.statSync(file);
+ store.docCount('packaged-fixture');
+ const worker = new ChatRebuildWorker('packaged-fixture');
+ const { Worker } = require('node:worker_threads');
+ let snippetWorker: import('node:worker_threads').Worker | undefined;
+ try {
+ const batch = await worker.rebuildBatch({ file, fileKey: 'source', mtime: stat.mtimeMs, size: stat.size });
+ snippetWorker = new Worker(`${input.archive}/src/main/features/search/chat-snippet-entry.js`, {
+ execArgv: [], env: { ...process.env },
+ });
+ const snippet = await new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error('Packaged snippet worker did not respond')), 10_000);
+ snippetWorker.once('error', (error: Error) => { clearTimeout(timeout); reject(error); });
+ snippetWorker.once('message', (message: any) => { clearTimeout(timeout); resolve(message.rows[0]?.[1]?.snippet); });
+ snippetWorker.postMessage({ id: 1, file, indexes: [0], tokens: ['packagedmarker'] });
+ });
+ return { complete: batch.complete, count: store.docCount('packaged-fixture'),
+ matches: store.postingsFor('packaged-fixture', 'packagedmarker').length, snippet };
+ } finally {
+ await snippetWorker?.terminate();
+ await worker.close();
+ store.closeAllChatStores();
+ if (old === undefined) delete process.env.ESBUILD_BINARY_PATH;
+ else process.env.ESBUILD_BINARY_PATH = old;
+ }
+ }, { archive, esbuild, sourceRoot: pcRoot });
+ expect(result).toEqual({ complete: true, count: 1, matches: 1, snippet: 'packagedmarker' });
+ } finally { await app.dispose(); }
+});
diff --git a/test/main/features/search/chat-snippet-failure.test.ts b/test/main/features/search/chat-snippet-failure.test.ts
new file mode 100644
index 00000000..5148fe94
--- /dev/null
+++ b/test/main/features/search/chat-snippet-failure.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'node:events';
+
+const state = vi.hoisted(() => ({ workers: [] as any[], warn: vi.fn() }));
+vi.mock('../../../../src/main/logger', () => ({ createLogger: () => ({ warn: state.warn }) }));
+vi.mock('node:worker_threads', () => ({
+ Worker: class extends EventEmitter {
+ commands: any[] = [];
+ constructor() { super(); state.workers.push(this); }
+ ref() {}
+ unref() {}
+ postMessage(command: unknown) { this.commands.push(command); }
+ terminate() { return Promise.resolve(0); }
+ },
+}));
+
+afterEach(async () => {
+ await (await import('../../../../src/main/features/search/chat-snippets')).closeChatSnippetReader();
+ vi.restoreAllMocks();
+});
+
+it('fails pending and queued reads on worker failure without leaking source details or causing a restart storm', async () => {
+ const { readChatSnippets } = await import('../../../../src/main/features/search/chat-snippets');
+ let now = 100_000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const pending = Promise.allSettled(Array.from({ length: 20 }, () => readChatSnippets('source', new Set([0]), ['needle'])));
+ await vi.waitFor(() => expect(state.workers[0]?.commands).toHaveLength(4));
+ state.workers[0].emit('error', new Error('private source content'));
+ const outcomes = await pending;
+ expect(outcomes.every(result => result.status === 'rejected')).toBe(true);
+ expect(outcomes.map(result => result.status === 'rejected' ? String(result.reason) : '').join(' ')).not.toContain('private');
+ expect(state.workers).toHaveLength(1);
+ expect(state.warn.mock.calls).toEqual([['chat snippet worker stopped; retry deferred']]);
+ now += 30_001;
+ const recovered = readChatSnippets('source', new Set([0]), ['needle']);
+ await vi.waitFor(() => expect(state.workers).toHaveLength(2));
+ const command = state.workers[1].commands[0];
+ state.workers[1].emit('message', { id: command.id, rows: [[0, { snippet: 'needle', visible: true }]] });
+ expect((await recovered).get(0)?.snippet).toBe('needle');
+});
diff --git a/test/main/features/search/chat-snippets.test.ts b/test/main/features/search/chat-snippets.test.ts
new file mode 100644
index 00000000..f0dc79b4
--- /dev/null
+++ b/test/main/features/search/chat-snippets.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+let root: string;
+beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-snippets-')); });
+afterEach(async () => {
+ await (await import('../../../../src/main/features/search/chat-snippets')).closeChatSnippetReader();
+ fs.rmSync(root, { recursive: true, force: true });
+});
+const body = (text: string) => JSON.stringify({ id: 'message', text }) + '\n';
+
+it('refreshes cached snippets after append, same-size replacement and deletion, isolated by source', async () => {
+ const { readChatSnippets } = await import('../../../../src/main/features/search/chat-snippets');
+ const file = path.join(root, 'first.jsonl'), other = path.join(root, 'second.jsonl');
+ fs.writeFileSync(file, body('needle old')); fs.writeFileSync(other, body('needle elsewhere'));
+ const read = (source = file) => readChatSnippets(source, new Set([0, 1]), ['needle']);
+ expect((await read()).get(0)?.snippet).toBe('needle old');
+ expect((await read()).get(0)?.snippet).toBe('needle old');
+ expect((await read(other)).get(0)?.snippet).toBe('needle elsewhere');
+ fs.appendFileSync(file, body('needle appended'));
+ expect((await read()).get(1)?.snippet).toBe('needle appended');
+ fs.writeFileSync(path.join(root, 'replacement'), body('needle new'));
+ fs.renameSync(path.join(root, 'replacement'), file);
+ expect([...(await read()).values()].map(row => row?.snippet)).toEqual(['needle new']);
+ // The awaited response owns no open source stream, including on Windows.
+ fs.unlinkSync(file);
+ expect((await read()).size).toBe(0);
+});
+
+it('releases a queued batch at shutdown and can open a fresh reader afterwards', async () => {
+ const { readChatSnippets, closeChatSnippetReader } = await import('../../../../src/main/features/search/chat-snippets');
+ const file = path.join(root, 'queue.jsonl'); fs.writeFileSync(file, body('needle'));
+ const requests = Array.from({ length: 20 }, () => readChatSnippets(file, new Set([0]), ['needle']));
+ // Attach handlers before closing to prove cancellation cannot leak rejected
+ // promises or leave queued reads resurrecting a worker after shutdown.
+ const settled = Promise.allSettled(requests);
+ await closeChatSnippetReader();
+ expect((await settled).every(result => result.status === 'rejected')).toBe(true);
+ expect((await readChatSnippets(file, new Set([0]), ['needle'])).get(0)?.snippet).toBe('needle');
+});
+
+it('returns bounded snippets and keeps main responsive while parsing a large cold execution record', async () => {
+ const { readChatSnippets } = await import('../../../../src/main/features/search/chat-snippets');
+ const file = path.join(root, 'large.jsonl');
+ const prefix = 'needle ' + 'visible '.repeat(40);
+ const event = (output: string) => ({ type: 'event', event: { stream: 'tool', data: { output } } });
+ fs.writeFileSync(file, JSON.stringify({ id: 'large', text: prefix, process: [
+ event(prefix), event('unrelated '.repeat(3_000_000)),
+ ] }) + '\n');
+ const gaps: number[] = [];
+ let last = performance.now();
+ const timer = setInterval(() => { const now = performance.now(); gaps.push(now - last); last = now; }, 5);
+ const started = performance.now();
+ let rows;
+ try { rows = await readChatSnippets(file, new Set([0]), ['needle']); }
+ finally { clearInterval(timer); }
+ expect(rows.get(0)).toMatchObject({ msg_id: 'large', visible: true, has_process: true });
+ expect(rows.get(0)?.snippet).toContain('needle');
+ expect(rows.get(0)?.process_snippet).toContain('needle');
+ expect(JSON.stringify([...rows]).length).toBeLessThan(512);
+ expect(gaps.length).toBeGreaterThan(3);
+ expect(Math.max(...gaps)).toBeLessThan(300);
+ console.info('search snippet worker performance', JSON.stringify({ source_bytes: fs.statSync(file).size,
+ elapsed_ms: Math.round(performance.now() - started), main_max_gap_ms: Math.round(Math.max(...gaps)),
+ response_chars: JSON.stringify([...rows]).length }));
+});
diff --git a/test/main/features/search/index.test.ts b/test/main/features/search/index.test.ts
index e5b12e48..0b5e89e0 100644
--- a/test/main/features/search/index.test.ts
+++ b/test/main/features/search/index.test.ts
@@ -962,9 +962,13 @@ describe('search › startup reconcile', () => {
fs.writeFileSync(snapshot, JSON.stringify({ version: 4, kind: 'chat', files: {}, docs: {}, postings: {} }));
fs.writeFileSync(`${snapshot}.tmp`, 'half-written flush');
+ const chatStore = await import('../../../../src/main/features/search/chat_store');
+ const compact = vi.spyOn(chatStore, 'compact').mockImplementation(() => undefined);
const s = await loadSearch();
await s.reconcileActive();
+ expect(compact).toHaveBeenCalledTimes(1);
+ expect(compact).toHaveBeenCalledWith(TEST_UID);
expect(fs.existsSync(snapshot), 'the retired snapshot is removed').toBe(false);
expect(fs.existsSync(`${snapshot}.tmp`), 'and so is a half-written flush').toBe(false);
const results = await s.searchChats(TEST_UID, 'quokka');
diff --git a/test/main/features/search/indexer.test.ts b/test/main/features/search/indexer.test.ts
index de960b6b..59bdfb44 100644
--- a/test/main/features/search/indexer.test.ts
+++ b/test/main/features/search/indexer.test.ts
@@ -3,18 +3,17 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-vi.mock('node:fs', async (importOriginal) => {
- const actual = await importOriginal<typeof import('node:fs')>();
- return { ...actual, createReadStream: vi.fn(actual.createReadStream) };
-});
-
// Pass-through by default. One case needs to hold a single `stat` so two
// deferred upserts would reach the index out of order; the namespace of a
// built-in cannot be spied, so the seam lives here.
-const statHook = vi.hoisted(() => ({ holdNextChatStat: false, holdMs: 40 }));
+const statHook = vi.hoisted(() => ({ holdNextChatStat: false, holdNextCatalogStat: false, holdMs: 40 }));
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>();
const stat = (async (target: unknown, ...rest: unknown[]) => {
+ if (statHook.holdNextCatalogStat && String(target).endsWith(`${path.sep}cloud${path.sep}chats`)) {
+ statHook.holdNextCatalogStat = false;
+ await new Promise((resolve) => setTimeout(resolve, statHook.holdMs));
+ }
if (statHook.holdNextChatStat && String(target).endsWith('c1.jsonl')) {
statHook.holdNextChatStat = false;
await new Promise((resolve) => setTimeout(resolve, statHook.holdMs));
@@ -38,6 +37,7 @@ let prevWs: string | undefined;
const TEST_UID = 'u1';
beforeEach(async () => {
+ statHook.holdNextCatalogStat = false;
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-indexer-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
@@ -233,6 +233,19 @@ describe('search/indexer › reconcileChatsIndex', () => {
expect(await chatDocIds()).toEqual(['chat:c1:2']);
});
+ it('does not let an in-flight coverage check re-trust a concurrently invalidated index', async () => {
+ writeChat('u1', 'c1', [{ role: 'user', content: 'catalogmarker', time: 't' }]);
+ const ix = await loadIndexer();
+ await ix.reconcileChatsIndex('u1');
+ statHook.holdNextCatalogStat = true;
+ const coverage = ix.isChatsIndexCurrent('u1');
+ // Sync can invalidate an existing JSONL without changing the chat-root
+ // stat. An old pending catalog read must not undo that explicit signal.
+ ix.invalidateChatsIndex('u1');
+ expect(await coverage).toBe(false);
+ expect(ix.isChatsIndexTrusted('u1')).toBe(false);
+ });
+
it('does not delete chat docs from a cancelled partial scan', async () => {
writeChat('u1', 'c1', [{ role: 'user', content: 'one', time: 't' }]);
writeChat('u1', 'c2', [{ role: 'user', content: 'two', time: 't' }]);
@@ -256,28 +269,6 @@ describe('search/indexer › reconcileChatsIndex', () => {
// conversation stops being searchable with no error anywhere. Observed in the
// field as a 260-message conversation with only its last 16 messages indexed.
describe('search/indexer › chat index completeness across incremental appends', () => {
- it('closes snippet readers before returning an early history match', async () => {
- writeChat(TEST_UID, 'c1', [
- { from: 'user', text: 'quokka first match' },
- { from: 'user', text: 'unrelated trailing row' },
- ]);
- await (await loadIndexer()).reconcileChatsIndex(TEST_UID);
- const search = await import('../../../../src/main/features/search/index');
- const reader = vi.mocked(fs.createReadStream);
- reader.mockClear();
- const hits = await search.searchChats(TEST_UID, 'quokka');
- const streams = reader.mock.results.filter(result => result.type === 'return')
- .map(result => result.value as fs.ReadStream);
- try {
- expect(hits.map(hit => hit.msg_index)).toEqual([0]);
- expect(streams.length).toBeGreaterThan(0);
- expect(streams.every(stream => stream.closed)).toBe(true);
- } finally {
- await Promise.all(streams.filter(stream => !stream.closed)
- .map(stream => new Promise<void>(resolve => stream.once('close', resolve))));
- }
- });
-
it('keeps history the index never read reachable after a later message arrives', async () => {
// History exists on disk but no reconcile ever covered this file.
writeChat('u1', 'c1', [
diff --git a/test/main/features/search/migration.test.ts b/test/main/features/search/migration.test.ts
index 3e2171a9..f1e554c1 100644
--- a/test/main/features/search/migration.test.ts
+++ b/test/main/features/search/migration.test.ts
@@ -4,20 +4,10 @@ import * as os from 'node:os';
import * as path from 'node:path';
const gate = vi.hoisted(() => ({ wait: null as Promise<void> | null, entered: null as (() => void) | null }));
-vi.mock('node:fs/promises', async (original) => {
- const actual = await original<typeof import('node:fs/promises')>();
- const readFile = async (...args: any[]) => {
- if (String(args[0]).endsWith('c2.jsonl') && gate.wait) {
- gate.entered?.();
- await gate.wait;
- }
- return (actual.readFile as any)(...args);
- };
- return { ...actual, readFile, default: { ...actual, readFile } };
-});
vi.mock('../../../../src/main/logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) }));
let root: string;
let oldRoot: string | undefined;
+let realBatch: import('../../../../src/main/features/search/chat-rebuild').ChatRebuildWorker['rebuildBatch'];
function write(cid: string, text: string) {
const file = path.join(root, 'u1/cloud/chats', `${cid}.jsonl`);
fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -37,6 +27,13 @@ beforeEach(async () => {
gate.wait = null;
gate.entered = null;
(await import('../../../../src/main/features/users')).activateUser('u1');
+ const { ChatRebuildWorker } = await import('../../../../src/main/features/search/chat-rebuild');
+ const real = ChatRebuildWorker.prototype.rebuildBatch;
+ realBatch = real;
+ vi.spyOn(ChatRebuildWorker.prototype, 'rebuildBatch').mockImplementation(async function(file) {
+ if (file.fileKey === 'c2' && gate.wait) { gate.entered?.(); await gate.wait; }
+ return real.call(this, file);
+ });
});
afterEach(async () => {
const search = await import('../../../../src/main/features/search');
@@ -66,9 +63,9 @@ it('keeps the old files on interruption and resumes a large conversation after r
const ix = await import('../../../../src/main/features/search/indexer');
const store = await import('../../../../src/main/features/search/chat_store');
const controller = new AbortController();
- const real = store.writeRebuildBatch;
- const spy = vi.spyOn(store, 'writeRebuildBatch').mockImplementation((...args) => {
- real(...args); controller.abort();
+ const { ChatRebuildWorker } = await import('../../../../src/main/features/search/chat-rebuild');
+ const spy = vi.spyOn(ChatRebuildWorker.prototype, 'rebuildBatch').mockImplementation(async function(file) {
+ const batch = await realBatch.call(this, file); controller.abort(); return batch;
});
expect((await ix.reconcileChatsIndex('u1', controller.signal)).complete).toBe(false);
expect(store.docCount('u1')).toBe(16);
@@ -76,14 +73,14 @@ it('keeps the old files on interruption and resumes a large conversation after r
expect(store.readRebuildCursor('u1', 'c1')?.next).toBe(16);
expect(fs.existsSync(legacy)).toBe(true);
expect(fs.existsSync(`${legacy}.tmp`)).toBe(true);
+ const prefixId = store._allDocsForTests('u1')[0].id;
spy.mockRestore();
await search.flushAll();
vi.resetModules();
const resumedStore = await import('../../../../src/main/features/search/chat_store');
const resumedIx = await import('../../../../src/main/features/search/indexer');
- const batches = vi.spyOn(resumedStore, 'writeRebuildBatch');
expect((await resumedIx.reconcileChatsIndex('u1')).complete).toBe(true);
- expect(batches.mock.calls[0][2][0].msgIndex, 'resume the committed prefix, not a fresh rebuild').toBe(16);
+ expect(resumedStore._allDocsForTests('u1')[0].id, 'keep the committed prefix, not a fresh rebuild').toBe(prefixId);
expect(resumedStore.docCount('u1')).toBe(70);
expect(resumedStore.postingsFor('u1', 'record0')).toHaveLength(1);
expect(resumedStore.postingsFor('u1', 'record69')).toHaveLength(1);
@@ -159,9 +156,9 @@ it('automatically resumes an interrupted startup slice only after the runtime be
let busy = false;
boot.configureBootAdmission({ isRuntimeBusy: () => busy });
const controller = new AbortController();
- const real = store.writeRebuildBatch;
- const spy = vi.spyOn(store, 'writeRebuildBatch').mockImplementationOnce((...args) => {
- real(...args); controller.abort(); busy = true;
+ const { ChatRebuildWorker } = await import('../../../../src/main/features/search/chat-rebuild');
+ const spy = vi.spyOn(ChatRebuildWorker.prototype, 'rebuildBatch').mockImplementationOnce(async function(file) {
+ const batch = await realBatch.call(this, file); controller.abort(); busy = true; return batch;
});
await search.reconcileActive(controller.signal);
expect(store.hasCompletedRebuild('u1')).toBe(false);
@@ -199,7 +196,8 @@ it('preserves old files and retries after a failed batch instead of declaring su
const legacy = legacySnapshot();
const search = await import('../../../../src/main/features/search');
const store = await import('../../../../src/main/features/search/chat_store');
- vi.spyOn(store, 'writeRebuildBatch').mockImplementationOnce(() => { throw new Error('injected write failure'); });
+ const { ChatRebuildWorker } = await import('../../../../src/main/features/search/chat-rebuild');
+ vi.spyOn(ChatRebuildWorker.prototype, 'rebuildBatch').mockRejectedValueOnce(new Error('injected worker failure'));
await search.reconcileActive();
expect(store.hasCompletedRebuild('u1')).toBe(false);
expect(fs.existsSync(legacy)).toBe(true);
@@ -231,11 +229,12 @@ it('does not certify a source replaced after its read but before its final batch
const legacy = legacySnapshot();
const ix = await import('../../../../src/main/features/search/indexer');
const store = await import('../../../../src/main/features/search/chat_store');
- const real = store.writeRebuildBatch;
- vi.spyOn(store, 'writeRebuildBatch').mockImplementationOnce((...args) => {
- real(...args);
+ const { ChatRebuildWorker } = await import('../../../../src/main/features/search/chat-rebuild');
+ vi.spyOn(ChatRebuildWorker.prototype, 'rebuildBatch').mockImplementationOnce(async function(file) {
+ const batch = await realBatch.call(this, file);
// A sync file write can precede the end-of-pass invalidation event.
write('c1', 'replacementword');
+ return batch;
});
expect((await ix.reconcileChatsIndex('u1')).complete).toBe(false);
expect(fs.existsSync(legacy)).toBe(true);
diff --git a/test/main/features/search/search_e2e_rebuild.test.ts b/test/main/features/search/search_e2e_rebuild.test.ts
new file mode 100644
index 00000000..666a2558
--- /dev/null
+++ b/test/main/features/search/search_e2e_rebuild.test.ts
@@ -0,0 +1,169 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import { performance } from 'node:perf_hooks';
+import Database from 'better-sqlite3';
+
+vi.mock('../../../../src/main/logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }) }));
+let root: string;
+let previousRoot: string | undefined;
+const uid = 'worker-user';
+function write(cid: string, messages: object[]) {
+ const file = path.join(root, uid, 'cloud/chats', `${cid}.jsonl`);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, messages.map(message => JSON.stringify(message)).join('\n') + '\n');
+ return file;
+}
+beforeEach(async () => {
+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-worker-search-'));
+ process.env.ORKAS_WORKSPACE_ROOT = root;
+ vi.resetModules();
+ (await import('../../../../src/main/features/users')).activateUser(uid);
+ // Tests own explicit reconciliation; query-triggered idle jobs must not race it.
+ (await import('../../../../src/main/util/boot_init')).configureBootAdmission({ isRuntimeBusy: () => true });
+});
+afterEach(async () => {
+ await (await import('../../../../src/main/features/search/indexer')).flushAll();
+ (await import('../../../../src/main/util/boot_init'))._resetForTests();
+ vi.restoreAllMocks();
+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+it('keeps real searches and the main timer responsive while indexing a full multi-MB execution record', async () => {
+ const ix = await import('../../../../src/main/features/search/indexer');
+ const search = await import('../../../../src/main/features/search');
+ const store = await import('../../../../src/main/features/search/chat_store');
+ write('existing', [{ role: 'user', content: 'existingmarker', time: 't' }]);
+ await ix.reconcileChatsIndex(uid);
+ expect((await search.searchChatsWithStatus(uid, 'existingmarker')).results).toHaveLength(1);
+ // The old 16-record bound cannot protect against a single large tool result.
+ const vocabulary = Array.from({ length: 150_000 }, (_, i) => `term${String(i).padStart(7, '0')}`).join(' ') + ' ';
+ const text = vocabulary.repeat(5) + 'tailmarker'; // 9 MB; full tail must survive.
+ const processRecord = { from: 'assistant', text: 'Completed', ts: 't', process: [
+ { type: 'event', event: { stream: 'tool', data: { type: 'tool_result', output: text } } },
+ { type: 'event', event: { stream: 'thinking', data: { text: 'privatereasoningmarker' } } },
+ ] };
+ write('large', [processRecord]);
+
+ // Negative control: same native tokenizer/postings writer on main. This
+ // rejects an async wrapper that still performs the heavy transaction here.
+ let controlGap = 0;
+ const controlStart = performance.now();
+ const controlTimer = new Promise<void>(resolve => setTimeout(() => {
+ controlGap = performance.now() - controlStart; resolve();
+ }, 0));
+ store.writeRebuildBatch('control', 'large', [{ cid: 'large', msgIndex: 0, role: 'assistant', time: 't', text }],
+ { mtime: 1, size: text.length, next: 1 }, true, true);
+ await controlTimer;
+ store.closeChatStore('control');
+
+ const gaps: number[] = [];
+ const queries: Array<{ ms: number; count: number; complete: boolean }> = [];
+ let last = performance.now();
+ const timer = setInterval(() => { const now = performance.now(); gaps.push(now - last); last = now; }, 10);
+ let done = false;
+ const startedAt = performance.now();
+ const cpu = process.cpuUsage();
+ const rebuild = ix.reconcileChatsIndex(uid).finally(() => { done = true; });
+ try {
+ while (!done) {
+ const start = performance.now();
+ const page = await search.searchChatsWithStatus(uid, 'existingmarker');
+ queries.push({ ms: performance.now() - start, count: page.results.length, complete: page.indexComplete });
+ await new Promise(resolve => setTimeout(resolve, 20));
+ }
+ expect((await rebuild).complete).toBe(true);
+ } finally { clearInterval(timer); await rebuild; }
+ const elapsed = performance.now() - startedAt;
+ const cpuUse = process.cpuUsage(cpu);
+ const partial = queries.filter(query => !query.complete);
+ expect(partial.length).toBeGreaterThan(3);
+ expect(partial.every(query => query.count === 1)).toBe(true);
+ const maxGap = Math.max(...gaps);
+ const sorted = partial.map(query => query.ms).sort((a, b) => a - b);
+ const p95 = sorted[Math.floor((sorted.length - 1) * .95)];
+ expect(maxGap, 'main timer remains interactive during the native worker transaction').toBeLessThan(300);
+ expect(maxGap, 'negative control must detect main-thread tokenization/writes').toBeLessThan(controlGap / 2);
+ expect(p95).toBeLessThan(200);
+ expect(store.docCount(uid), 'reader statistics observe external worker commits').toBe(2);
+ expect(store.postingsFor(uid, 'tailmarker')).toHaveLength(1);
+ expect(store.postingsFor(uid, 'term0149999')).toHaveLength(1);
+ expect(store.postingsFor(uid, 'privatereasoningmarker')).toHaveLength(0);
+ expect((await search.searchChatsWithStatus(uid, 'tailmarker')).results).toHaveLength(1);
+ console.info('search worker performance', JSON.stringify({ characters: text.length,
+ control_main_gap_ms: Math.round(controlGap), worker_total_ms: Math.round(elapsed),
+ main_max_gap_ms: Math.round(maxGap), query_p95_ms: Math.round(p95), samples: partial.length,
+ process_cpu_ms: Math.round((cpuUse.user + cpuUse.system) / 1000), rss_mb: Math.round(process.memoryUsage().rss / 1024 / 1024) }));
+});
+
+it('rolls back a real worker SQL failure and resumes committed rows with a new worker', async () => {
+ const ix = await import('../../../../src/main/features/search/indexer');
+ const store = await import('../../../../src/main/features/search/chat_store');
+ write('recovery', Array.from({ length: 40 }, (_, i) => ({ role: 'user', content: `marker${i}`, time: 't' })));
+ const legacy = path.join(root, uid, 'local/search/chats.idx.json');
+ expect(store.docCount(uid)).toBe(0); // Open the reader before the worker writes.
+ fs.writeFileSync(legacy, '{}');
+ const db = new Database(store.chatStorePath(uid));
+ try {
+ db.exec("CREATE TRIGGER injected_failure BEFORE INSERT ON chat_docs WHEN NEW.msg_index = 17 BEGIN SELECT RAISE(ABORT, 'private fixture detail'); END");
+ await expect(ix.reconcileChatsIndex(uid)).rejects.toThrow('Chat index rebuild batch failed');
+ expect(store.docCount(uid)).toBe(16);
+ expect(store.readRebuildCursor(uid, 'recovery')?.next).toBe(16);
+ expect(store.postingsFor(uid, 'marker16')).toHaveLength(0);
+ expect(store.hasCompletedRebuild(uid)).toBe(false);
+ expect(fs.existsSync(legacy)).toBe(true);
+ const prefixId = store.postingsFor(uid, 'marker0')[0].doc;
+ db.exec('DROP TRIGGER injected_failure');
+ await ix.flushAll();
+ expect((await ix.reconcileChatsIndex(uid)).complete).toBe(true);
+ expect(store.postingsFor(uid, 'marker0')[0].doc).toBe(prefixId);
+ expect(store.postingsFor(uid, 'marker39')).toHaveLength(1);
+ expect(store.docCount(uid)).toBe(40);
+ expect(fs.existsSync(legacy)).toBe(false);
+ } finally { db.close(); }
+});
+
+it('does not block main invalidation or deletion behind an active worker write transaction', async () => {
+ const ix = await import('../../../../src/main/features/search/indexer');
+ const store = await import('../../../../src/main/features/search/chat_store');
+ const { ChatRebuildWorker } = await import('../../../../src/main/features/search/chat-rebuild');
+ const existing = write('existing', [{ role: 'user', content: 'deletemarker', time: 't' }]);
+ await ix.reconcileChatsIndex(uid);
+ const text = Array.from({ length: 180_000 }, (_, i) => `unique${i}`).join(' ');
+ const large = write('large', [{ role: 'user', content: text, time: 't' }]);
+ const db = new Database(store.chatStorePath(uid));
+ db.pragma('busy_timeout = 0');
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ const real = ChatRebuildWorker.prototype.rebuildBatch;
+ vi.spyOn(ChatRebuildWorker.prototype, 'rebuildBatch').mockImplementation(function(file) {
+ const batch = real.call(this, file); entered(); return batch;
+ });
+ const run = ix.reconcileChatsIndex(uid);
+ try {
+ await started;
+ await vi.waitFor(() => {
+ let busy = false;
+ try { db.exec('BEGIN IMMEDIATE; ROLLBACK'); }
+ catch (error) { if ((error as any).code === 'SQLITE_BUSY') busy = true; else throw error; }
+ expect(busy, 'prove a real writer lock is held, not merely a pending promise').toBe(true);
+ }, { timeout: 5_000, interval: 10 });
+ const start = performance.now();
+ fs.unlinkSync(existing);
+ fs.appendFileSync(large, JSON.stringify({ role: 'user', content: 'freshmarker', time: 't2' }) + '\n');
+ ix.invalidateChatsIndex(uid);
+ ix.indexChatMessageDeferred(uid, 'large', 1, { role: 'user', content: 'freshmarker', time: 't2' });
+ await ix.dropChatConversation(uid, 'existing');
+ expect(performance.now() - start).toBeLessThan(200);
+ expect((await run).complete).toBe(false);
+ expect(store.readSourceStamp(uid)).toBeUndefined();
+ expect((await ix.reconcileChatsIndex(uid)).complete).toBe(true);
+ expect(store.postingsFor(uid, 'deletemarker')).toHaveLength(0);
+ expect(store.postingsFor(uid, 'freshmarker')).toHaveLength(1);
+ expect(store.docCount(uid)).toBe(2);
+ } finally { await run.catch(() => undefined); db.close(); }
+});
diff --git a/test/main/features/search/snippet.test.ts b/test/main/features/search/snippet.test.ts
new file mode 100644
index 00000000..06654b77
--- /dev/null
+++ b/test/main/features/search/snippet.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+import { makeSnippet, projectChatSnippet } from '../../../../src/main/features/search/snippet';
+import { tokenize } from '../../../../src/main/features/search/tokenize';
+
+// Frozen pre-optimization display contract, independent of the lazy reader.
+function formerSnippet(text: string, query: string): string {
+ const flat = text.replace(/\s+/g, ' '), lower = flat.toLowerCase();
+ let at = -1, width = 0;
+ for (const token of tokenize(query)) {
+ const candidate = lower.indexOf(token);
+ if (candidate >= 0 && (at < 0 || candidate < at)) { at = candidate; width = token.length; }
+ }
+ if (at < 0) return flat.slice(0, 120);
+ const start = Math.max(0, at - 60), end = Math.min(flat.length, at + width + 60);
+ return (start ? '…' : '') + flat.slice(start, end) + (end < flat.length ? '…' : '');
+}
+
+describe('search snippet compatibility', () => {
+ it('preserves first-token windows, whitespace, Unicode and unmatched prefixes across lazy parts', () => {
+ const atoms = ['', ' \t\n', '搜索资料', 'Orkas', 'İstanbul', '🧾', 'prefix '.repeat(25), 'tail '.repeat(25)];
+ for (const a of atoms) for (const b of atoms) for (const c of ['', ' 搜索 Orkas ', ' tail']) {
+ const parts = [a, b, c];
+ const complete = parts.filter(Boolean).join('\n');
+ for (const query of ['搜索', 'Orkas', 'tail', 'missing', '搜索 Orkas', 'the']) {
+ expect(makeSnippet(parts, tokenize(query))).toBe(formerSnippet(complete, query));
+ }
+ }
+ });
+
+ it('stops projecting an execution trail once both display windows are determined', () => {
+ const event = (output: string) => ({ type: 'event', event: { stream: 'tool', data: { output } } });
+ const text = 'needle ' + 'visible '.repeat(30);
+ const first = event('needle ' + 'evidence '.repeat(30));
+ const unused = { type: 'event', get event(): never { throw new Error('Unneeded large execution payload was expanded'); } };
+ expect(projectChatSnippet({ id: 'm1', text, process: [first, unused] }, ['needle'])).toEqual({
+ visible: true, msg_id: 'm1', has_process: true,
+ snippet: formerSnippet(text, 'needle'),
+ process_snippet: formerSnippet('[process 0] ' + first.event.data.output, 'needle'),
+ });
+ });
+
+ it('keeps the earliest best public process hit and omits private reasoning and inline media', () => {
+ const process = [
+ { type: 'event', event: { stream: 'thinking', data: { output: 'alpha beta private' } } },
+ { type: 'progress', text: 'alpha only' },
+ { type: 'event', event: { stream: 'tool', data: { output: 'alpha beta evidence' } } },
+ { type: 'progress', text: 'alpha beta later tie' },
+ ];
+ const result = projectChatSnippet({ text: 'Done', process }, ['alpha', 'beta']);
+ expect(result?.process_snippet).toBe('[process 2] alpha beta evidence');
+ expect(result?.snippet).not.toContain('private');
+ expect(projectChatSnippet({ content: 'photo data:image/png;base64,c2VjcmV0' }, ['photo'])?.snippet)
+ .toBe('photo [inline image/png data omitted from history]');
+ expect(projectChatSnippet({ text: 'hidden', dispatch: true }, ['hidden'])?.visible).toBe(false);
+ expect(projectChatSnippet({ text: 'deleted', deleted_at: 't' }, ['deleted'])?.visible).toBe(false);
+ expect(projectChatSnippet({ text: ' \n\t ' }, [])?.visible).toBe(false);
+ });
+});
diff --git a/test/main/model/core-agent/chat-history-tools.test.ts b/test/main/model/core-agent/chat-history-tools.test.ts
index f62333fd..b578ac72 100644
--- a/test/main/model/core-agent/chat-history-tools.test.ts
+++ b/test/main/model/core-agent/chat-history-tools.test.ts
@@ -316,8 +316,9 @@ describe('chat-history-tools › chat_history(search)', () => {
// index of the triggering message. Parsing the whole JSONL for it on
// every call was the per-turn cost (K-5). While the source revision stays
// unchanged, the first lookup serves later searches of the turn.
- // Oracle: opens of the log (the page reader goes through
- // fs.promises.open; the search snippet reader does not).
+ // Oracle: full source scans for boundary metadata. Snippets now use a
+ // separate worker, so counting main-process snippet opens proves nothing
+ // about whether this boundary is being repeatedly parsed.
const { _resetCurrentBoundaryCacheForTest } = await import('../../../../src/main/model/core-agent/chat-history-tools');
_resetCurrentBoundaryCacheForTest();
writeConversation('boundary-cache', 'Boundary', [
@@ -328,10 +329,9 @@ describe('chat-history-tools › chat_history(search)', () => {
userId: TEST_UID, currentCid: 'boundary-cache', currentMessageId: 'trigger',
});
const logPath = path.join(tmpDir, TEST_UID, 'cloud', 'chats', 'boundary-cache.jsonl');
- // storage.ts binds `node:fs/promises` as an ESM namespace, so the patched
- // property has to be re-synced into that namespace.
- const { syncBuiltinESMExports } = await import('node:module');
- const openSpy = vi.spyOn(fs.promises, 'open');
+ const { createRequire, syncBuiltinESMExports } = await import('node:module');
+ const nativeFs = createRequire(import.meta.url)('node:fs') as typeof fs;
+ const openSpy = vi.spyOn(nativeFs, 'createReadStream');
syncBuiltinESMExports();
const logOpens = () => openSpy.mock.calls.filter((call) => String(call[0]) === logPath).length;
const search = () => chatSearch.execute({ query: 'CACHEDBOUNDARY', scope: 'current', k: 10 }, ctxFor());
@@ -343,12 +343,12 @@ describe('chat-history-tools › chat_history(search)', () => {
const second = await search();
expect(second.content).toContain('CACHEDBOUNDARY earlier result');
- expect(logOpens()).toBe(opensForFirst + 1); // one direct hit read, no full transcript read
+ expect(logOpens()).toBe(opensForFirst);
- // Forgetting the boundary still reuses the metadata index and seeks only the hit.
+ // Forgetting the boundary still reuses the metadata index.
_resetCurrentBoundaryCacheForTest();
await search();
- expect(logOpens()).toBe(opensForFirst + 2);
+ expect(logOpens()).toBe(opensForFirst);
} finally {
openSpy.mockRestore();
syncBuiltinESMExports();
diff --git a/test/main/model/core-agent/rotating-provider.test.ts b/test/main/model/core-agent/rotating-provider.test.ts
index b739163f..260aaaba 100644
--- a/test/main/model/core-agent/rotating-provider.test.ts
+++ b/test/main/model/core-agent/rotating-provider.test.ts
@@ -1362,6 +1362,24 @@ describe('rotating-provider › exhausted stream candidates', () => {
})).toThrow(/candidates list is empty/);
});
+ it('returns a structured unavailable error when every candidate was exhausted earlier in the run', async () => {
+ const authErr = Object.assign(new Error('Unauthorized'), { status: 401 });
+ const p = createRotatingProvider({
+ providerId: 'test',
+ candidates: [candidate('p1', { throwBefore: authErr })],
+ });
+
+ await expect(collect(p.stream(PARAMS))).rejects.toMatchObject({
+ code: 'PROVIDER_AUTH_EXHAUSTED',
+ });
+ await expect(p.complete(PARAMS)).rejects.toMatchObject({
+ code: 'PROVIDER_CANDIDATES_UNAVAILABLE',
+ });
+ await expect(collect(p.stream(PARAMS))).rejects.toMatchObject({
+ code: 'PROVIDER_CANDIDATES_UNAVAILABLE',
+ });
+ });
+
it('retries each network-failing candidate and surfaces a stable exhausted error without cooldown', async () => {
const netErr = new TypeError('fetch failed');
let p1Builds = 0;
diff --git a/test/main/model/event-mapper.test.ts b/test/main/model/event-mapper.test.ts
index 641fee6b..3cce29b3 100644
--- a/test/main/model/event-mapper.test.ts
+++ b/test/main/model/event-mapper.test.ts
@@ -1797,6 +1797,37 @@ describe('event-mapper › tool_start / tool_end emit a single structured event'
expect(out[0].failureRawCode).toBeUndefined();
});
+ it('maps exhausted in-run candidates to actionable unavailable-model guidance', async () => {
+ setCurrentLang('zh');
+ try {
+ const out = await collect([
+ {
+ type: 'done',
+ result: {
+ text: '',
+ meta: {
+ error: {
+ kind: 'provider_error',
+ message: 'rotating-provider: no candidates',
+ code: 'PROVIDER_CANDIDATES_UNAVAILABLE',
+ },
+ },
+ },
+ },
+ ]);
+ expect(out).toEqual([expect.objectContaining({
+ type: 'error',
+ failureKind: 'model',
+ failureCode: 'provider_unavailable',
+ })]);
+ expect(String(out[0].text || '')).toContain('暂时不可用');
+ expect(String(out[0].text || '')).not.toContain('rotating-provider');
+ expect(String(out[0].text || '')).not.toContain('no candidates');
+ } finally {
+ setCurrentLang('en');
+ }
+ });
+
it('diagnoses a repeatedly failing custom endpoint on the second consecutive 4xx', async () => {
// W4-1 replay: a custom provider answered `410 (no body)` three runs in a
// row; the user only ever saw "模型调用失败:410" and left with nothing.
diff --git a/test/main/util/indexed-jsonl.test.ts b/test/main/util/indexed-jsonl.test.ts
index 7996d2c5..1e16161f 100644
--- a/test/main/util/indexed-jsonl.test.ts
+++ b/test/main/util/indexed-jsonl.test.ts
@@ -1,16 +1,70 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-import { getIndexedJsonl, readIndexedJsonlRecords } from '../../../src/main/util/indexed-jsonl';
+import { getIndexedJsonl, readIndexedJsonlRecords, mapIndexedJsonlRecords } from '../../../src/main/util/indexed-jsonl';
import { appendJsonlAtomic, readJsonlWindow, writeTextAtomicSync } from '../../../src/main/storage';
+vi.mock('node:fs', async (original) => {
+ const actual = await original<typeof import('node:fs')>();
+ return { ...actual, createReadStream: vi.fn(actual.createReadStream) };
+});
+
let directory: string;
beforeEach(() => { directory = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-indexed-history-')); });
afterEach(() => { fs.rmSync(directory, { recursive: true, force: true }); });
const metadata = (record: { id: string }) => ({ id: record.id });
describe('indexed JSONL history reads', () => {
+ it('reads only the requested prefix, projects cold records once, and closes the source before returning', async () => {
+ const file = path.join(directory, 'prefix.jsonl');
+ fs.writeFileSync(file, '\ninvalid\n' + JSON.stringify({ id: 'first', text: '用户🧾' }) + '\n' +
+ JSON.stringify({ id: 'second', text: 'evidence' }) + '\n' +
+ JSON.stringify({ id: 'large-tail', text: 'x'.repeat(4_000_000) }) + '\n');
+ const reader = vi.mocked(fs.createReadStream); reader.mockClear();
+ const project = vi.fn((row: { id: string }) => row.id);
+ expect([...await mapIndexedJsonlRecords(file, new Set([1, 0]), project)])
+ .toEqual([[0, 'first'], [1, 'second']]);
+ expect(project.mock.calls.map(([row]) => row.id)).toEqual(['first', 'second']);
+ const streams = reader.mock.results.map(result => result.value as fs.ReadStream);
+ expect(streams.every(stream => stream.closed)).toBe(true);
+ expect(streams.reduce((sum, stream) => sum + stream.bytesRead, 0)).toBeLessThan(256 * 1024);
+ // A later history request must extend the prefix, never mistake it for
+ // the complete conversation or count a malformed row as a message.
+ expect([...await mapIndexedJsonlRecords(file, new Set([2]), row => row.id)])
+ .toEqual([[2, 'large-tail']]);
+ expect((await getIndexedJsonl(file, metadata)).entries).toHaveLength(3);
+ });
+
+ it('keeps a normal search working set warm beyond 32 conversations without retaining source bodies', async () => {
+ const files = Array.from({ length: 96 }, (_, index) => path.join(directory, `${index}.jsonl`));
+ for (const [index, file] of files.entries()) {
+ fs.writeFileSync(file, JSON.stringify({ id: String(index), text: 'private body' }) + '\n');
+ await mapIndexedJsonlRecords(file, new Set([0]), row => row.id);
+ }
+ const reader = vi.mocked(fs.createReadStream); reader.mockClear();
+ for (const [index, file] of files.entries()) {
+ expect([...await mapIndexedJsonlRecords(file, new Set([0]), row => row.id)]).toEqual([[0, String(index)]]);
+ }
+ expect(reader.mock.results, 'repeat lookup must seek selected rows instead of rescanning each source').toHaveLength(0);
+ });
+
+ it('does not skip an unscanned suffix after append, and rejects rewritten or missing source data', async () => {
+ const file = path.join(directory, 'changing.jsonl');
+ fs.writeFileSync(file, '{"id":"a"}\ninvalid\n{"id":"b"}\n');
+ expect([...await mapIndexedJsonlRecords(file, new Set([0]), row => row.id)]).toEqual([[0, 'a']]);
+ await appendJsonlAtomic(file, { id: 'c' });
+ expect([...await mapIndexedJsonlRecords(file, new Set([1, 2]), row => row.id)]).toEqual([[1, 'b'], [2, 'c']]);
+ fs.writeFileSync(file, '{"id":"new"}\n');
+ expect([...await mapIndexedJsonlRecords(file, new Set([0, 2]), row => row.id)]).toEqual([[0, 'new']]);
+ fs.writeFileSync(file, '{"id":"race"}\n');
+ await expect(mapIndexedJsonlRecords(file, new Set([0]), row => {
+ fs.writeFileSync(file, '{"id":"changed during read"}\n'); return row.id;
+ })).rejects.toThrow('Conversation changed');
+ fs.unlinkSync(file);
+ expect([...await mapIndexedJsonlRecords(file, new Set([0]), row => row.id)]).toEqual([]);
+ });
+
it('keeps valid-record numbering and exact UTF-8 source bytes across malformed rows', async () => {
const file = path.join(directory, 'history.jsonl');
const records = [{ id: 'a', text: '用户🧾' }, { id: 'b', text: 'quoted\n"input"' }];
diff --git a/test/renderer/global-search-navigation.test.ts b/test/renderer/global-search-navigation.test.ts
index b9394270..4f025e87 100644
--- a/test/renderer/global-search-navigation.test.ts
+++ b/test/renderer/global-search-navigation.test.ts
@@ -31,12 +31,164 @@ function extractFunction(source: string, name: string): string {
throw new Error(`unterminated ${name}`);
}
+function loadingHarness() {
+ const body = { innerHTML: '', classList: { add: vi.fn(), remove: vi.fn() },
+ querySelectorAll: () => [], querySelector: () => null };
+ const input = { value: '', focus: vi.fn() };
+ const overlay = { style: { display: '' } };
+ const requests: Array<{ resolve: (data: any) => void; reject: (error: Error) => void }> = [];
+ const locale = JSON.parse(fs.readFileSync(path.join(root, 'src/renderer/locales/zh.json'), 'utf8'));
+ const context: any = {
+ setTimeout, clearTimeout, window: {},
+ document: {
+ addEventListener: vi.fn(), querySelectorAll: () => [],
+ getElementById: (id: string) => ({ 'search-body': body, 'search-input': input,
+ 'search-overlay': overlay }[id] || null),
+ },
+ escapeHtml: (s: string) => s, t: (key: string) => locale[key], formatTime: () => '',
+ localStorage: { getItem: () => null, setItem: vi.fn() },
+ apiFetch: (url: string) => url.endsWith('/status')
+ ? Promise.resolve({ json: async () => ({ ok: true, chat_index_complete: true }) })
+ : new Promise((resolve, reject) => requests.push({
+ resolve: data => resolve({ json: async () => data }), reject,
+ })),
+ };
+ vm.createContext(context);
+ vm.runInContext(searchSource, context);
+ return { body, input, overlay, requests, context };
+}
+
describe('global search conversation navigation', () => {
+ // Visible wait feedback must survive reordering; no stale hit may become
+ // actionable while the next input is still waiting for its debounce.
+ it('keeps loading for the latest input through stale replies, tabs, clearing and reopening', async () => {
+ vi.useFakeTimers();
+ try {
+ const { body, input, overlay, requests, context } = loadingHarness();
+ const old = context._runSearchNow('old');
+ expect(body.innerHTML).toContain('加载中…');
+ context._scheduleSearch('next');
+ requests[0].resolve({ ok: true, results: [{ kind: 'chat', conv_title: 'stale hit' }] });
+ await old;
+ expect(body.innerHTML).toContain('加载中…');
+ expect(body.innerHTML).not.toContain('stale hit');
+ context._setSearchTab('chat');
+ expect(body.innerHTML).toContain('加载中…');
+ await vi.advanceTimersByTimeAsync(300);
+ expect(requests).toHaveLength(2);
+ context._scheduleSearch('');
+ expect(body.innerHTML).not.toContain('search-loading');
+ requests[1].reject(new Error('obsolete failure'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(body.innerHTML).not.toContain('obsolete failure');
+ expect(body.innerHTML).not.toContain('search-loading');
+
+ input.value = 'closing';
+ context._scheduleSearch(input.value);
+ context.closeGlobalSearch();
+ expect(overlay.style.display).toBe('none');
+ context.openGlobalSearch();
+ await vi.advanceTimersByTimeAsync(300);
+ expect(requests).toHaveLength(2);
+ expect(body.innerHTML).not.toContain('search-loading');
+ } finally { vi.useRealTimers(); }
+ });
+
+ it.each(['results', 'empty', 'rejected', 'network'])('replaces loading with the current %s outcome and permits retry', async outcome => {
+ const { body, requests, context } = loadingHarness();
+ const pending = context._runSearchNow('marker');
+ expect(body.innerHTML).toContain('role="status"');
+ expect(body.innerHTML).toContain('加载中…');
+ expect(body.innerHTML).not.toContain('search-result');
+ if (outcome === 'network') requests[0].reject(new Error('offline'));
+ else requests[0].resolve(outcome === 'rejected' ? { ok: false, error: 'unavailable' }
+ : { ok: true, results: outcome === 'empty' ? [] : [{ kind: 'chat', conv_title: 'matching conversation' }] });
+ await pending;
+ expect(body.innerHTML).not.toContain('search-loading');
+ if (outcome === 'results') expect(body.innerHTML).toContain('matching conversation');
+ else if (outcome === 'empty') expect(body.innerHTML).toContain('未找到');
+ else expect(body.innerHTML).toContain('搜索失败');
+ const retry = context._runSearchNow('retry');
+ expect(body.innerHTML).toContain('加载中…');
+ requests[1].resolve({ ok: true, results: [{ kind: 'chat', conv_title: 'retry hit' }] });
+ await retry;
+ expect(body.innerHTML).toContain('retry hit');
+ expect(body.innerHTML).not.toContain('search-loading');
+ });
+
+ it('paints the localized preparation notice before results settle and rejects late status after a ready result', async () => {
+ const body = { innerHTML: '', classList: { remove: vi.fn() }, querySelectorAll: () => [] };
+ const locale = JSON.parse(fs.readFileSync(path.join(root, 'src/renderer/locales/zh.json'), 'utf8'));
+ let resolveStatus!: (value: any) => void;
+ let resolveResults!: (value: any) => void;
+ const context: any = {
+ _searchResults: [], _searchVisibleResults: [], _searchActiveIdx: -1,
+ _searchLoading: false, _searchTab: 'all', _searchChatIndexComplete: true, _searchSeq: 0, _searchLastQuery: '',
+ _searchTimer: null,
+ _SEARCH_FETCH_LIMIT: 200,
+ document: { getElementById: () => body }, escapeHtml: (s: string) => s,
+ t: (key: string) => locale[key], _activeProjectIdForSearch: () => '',
+ _setSearchTabsVisible: vi.fn(), _trackGlobalSearchResult: vi.fn(),
+ _renderSearchError: vi.fn(), _reportGlobalSearchFailure: vi.fn(),
+ _partitionSearchResults: (rows: any[]) => ({ chats: rows, agents: [], skills: [], contexts: [] }),
+ _sectionRows: (s: any) => s.bucket, _renderSearchRow: () => '<div class="search-result">existing hit</div>',
+ apiFetch: (url: string) => new Promise(resolve => {
+ if (url.endsWith('/status')) resolveStatus = data => resolve({ json: async () => data });
+ else resolveResults = data => resolve({ json: async () => data });
+ }),
+ };
+ vm.createContext(context);
+ for (const name of ['_refreshSearchIndexStatus', '_showSearchLoading', '_runSearchNow', '_renderSearchResults']) {
+ vm.runInContext(extractFunction(searchSource, name), context);
+ }
+ const pending = context._runSearchNow('marker');
+ expect(body.innerHTML).toContain('search-loading');
+ expect(body.innerHTML).toContain(locale['common.loading']);
+ resolveStatus({ ok: true, chat_index_complete: false });
+ await new Promise(resolve => setImmediate(resolve));
+ const copy = '正在准备中,结果暂不完整,请稍后重试。';
+ expect(body.innerHTML).toContain(copy);
+ expect(body.innerHTML).toContain('search-loading');
+ expect(body.innerHTML).not.toContain(locale['search.no_results']);
+ resolveResults({ ok: true, chat_index_complete: false, results: [{ kind: 'chat' }] });
+ await pending;
+ expect(body.innerHTML).toContain(copy);
+ expect(body.innerHTML).toContain('existing hit');
+ expect(body.innerHTML).not.toContain('search-loading');
+
+ const ready = context._runSearchNow('marker');
+ resolveResults({ ok: true, chat_index_complete: true, results: [{ kind: 'chat' }] });
+ await ready;
+ resolveStatus({ ok: true, chat_index_complete: false });
+ await new Promise(resolve => setImmediate(resolve));
+ expect(body.innerHTML).not.toContain(copy);
+ expect(body.innerHTML).toContain('existing hit');
+ expect(context._renderSearchError).not.toHaveBeenCalled();
+ });
+
+ it('ignores preparation status from a closed or superseded search session', async () => {
+ let reply!: (value: any) => void;
+ const context: any = {
+ _searchSeq: 1, _searchChatIndexComplete: true,
+ apiFetch: () => new Promise(resolve => { reply = data => resolve({ json: async () => data }); }),
+ _renderSearchEmptyState: vi.fn(), _renderSearchResults: vi.fn(),
+ };
+ vm.createContext(context);
+ vm.runInContext(extractFunction(searchSource, '_refreshSearchIndexStatus'), context);
+ const pending = context._refreshSearchIndexStatus(1, '', { active: true });
+ context._searchSeq++;
+ reply({ ok: true, chat_index_complete: false });
+ await pending;
+ expect(context._searchChatIndexComplete).toBe(true);
+ expect(context._renderSearchEmptyState).not.toHaveBeenCalled();
+ expect(context._renderSearchResults).not.toHaveBeenCalled();
+ });
+
it('shows incomplete-history status for empty and partial results, clears it after migration, and scopes it to chats', () => {
const body = { innerHTML: '', classList: { remove: vi.fn() }, querySelectorAll: () => [] };
const context: any = {
_searchResults: [], _searchVisibleResults: [], _searchActiveIdx: -1,
- _searchTab: 'all', _searchChatIndexComplete: false,
+ _searchLoading: false, _searchTab: 'all', _searchChatIndexComplete: false,
document: { getElementById: () => body },
escapeHtml: (s: string) => s, t: (key: string) => key,
_partitionSearchResults: (rows: any[]) => ({ chats: rows, agents: [], skills: [], contexts: [] }),
@@ -84,6 +236,8 @@ describe('global search conversation navigation', () => {
_setSearchTab: vi.fn(),
_setSearchTabsVisible: vi.fn(),
_renderSearchEmptyState: vi.fn(),
+ _showSearchLoading: vi.fn(),
+ _refreshSearchIndexStatus: vi.fn(),
setTimeout: (fn: () => void) => { fn(); return 1; },
window: { Monitor: true },
Monitor: {
@@ -298,6 +452,7 @@ describe('global search conversation navigation', () => {
const trackResult = vi.fn();
const context: any = {
Date,
+ _searchTimer: null,
_SEARCH_FETCH_LIMIT: 200,
_searchSeq: 0,
_searchResults: [],
@@ -310,6 +465,8 @@ describe('global search conversation navigation', () => {
_activeProjectIdForSearch: () => '',
_setSearchTabsVisible: () => {},
_renderSearchEmptyState: () => { rendered.push('empty'); },
+ _showSearchLoading: vi.fn(),
+ _refreshSearchIndexStatus: vi.fn(),
_renderSearchResults: (query: string) => { rendered.push(`results:${query}`); },
_renderSearchError: (message: string) => { rendered.push(`error:${message}`); },
_trackGlobalSearchResult: trackResult,
@@ -346,9 +503,9 @@ describe('global search conversation navigation', () => {
const overlay: any = { style: { display: '' } };
const input: any = { value: 'private query' };
const context: any = {
+ _searchTimer: null,
_SEARCH_FETCH_LIMIT: 200,
_searchSeq: 0,
- _searchTimer: null,
document: {
getElementById: (id: string) => (id === 'search-overlay' ? overlay : (id === 'search-input' ? input : null)),
},
@@ -356,6 +513,8 @@ describe('global search conversation navigation', () => {
_activeProjectIdForSearch: () => '',
_setSearchTabsVisible: vi.fn(),
_renderSearchEmptyState: vi.fn(),
+ _showSearchLoading: vi.fn(),
+ _refreshSearchIndexStatus: vi.fn(),
_renderSearchResults: vi.fn(),
_renderSearchError: renderError,
_reportGlobalSearchFailure: reportFailure,
diff --git a/test/renderer/kb-picker.test.ts b/test/renderer/kb-picker.test.ts
index c875b35f..224126a3 100644
--- a/test/renderer/kb-picker.test.ts
+++ b/test/renderer/kb-picker.test.ts
@@ -7,8 +7,15 @@ const source = readFileSync(
resolve(__dirname, '../../src/renderer/modules/kb-picker.js'),
'utf8',
);
+const indexSource = readFileSync(
+ resolve(__dirname, '../../src/renderer/index.html'),
+ 'utf8',
+);
-function load(initialStorage: Record<string, string> = {}) {
+function load(
+ initialStorage: Record<string, string> = {},
+ elements: Record<string, unknown> = {},
+) {
const values = new Map(Object.entries(initialStorage));
const translations: Record<string, string> = {
'contexts.root_label': 'Root',
@@ -31,7 +38,7 @@ function load(initialStorage: Record<string, string> = {}) {
setItem: (key: string, value: string) => { values.set(key, value); },
removeItem: (key: string) => { values.delete(key); },
},
- document: { getElementById: () => null },
+ document: { getElementById: (id: string) => elements[id] ?? null },
setTimeout: vi.fn(),
window: {},
};
@@ -41,6 +48,22 @@ function load(initialStorage: Record<string, string> = {}) {
}
describe('Library location picker', () => {
+ it('binds the visible cancel and confirm actions without inline global lookups', () => {
+ const cancel = { addEventListener: vi.fn() };
+ const confirm = { addEventListener: vi.fn() };
+ const { sandbox } = load({}, {
+ 'kb-picker-cancel': cancel,
+ 'kb-picker-confirm': confirm,
+ });
+
+ expect(indexSource).toContain('id="kb-picker-cancel"');
+ expect(indexSource).toContain('id="kb-picker-confirm"');
+ expect(indexSource).not.toContain('onclick="closeKbPicker()"');
+ expect(indexSource).not.toContain('onclick="confirmKbPicker()"');
+ expect(cancel.addEventListener).toHaveBeenCalledWith('click', sandbox.window.closeKbPicker);
+ expect(confirm.addEventListener).toHaveBeenCalledWith('click', sandbox.window.confirmKbPicker);
+ });
+
it('identifies the Global or Project Library in both the title and destination', () => {
const { sandbox } = load();
const target = { textContent: '' };
diff --git a/test/renderer/project-instructions-editor.test.ts b/test/renderer/project-instructions-editor.test.ts
new file mode 100644
index 00000000..1ccb44ca
--- /dev/null
+++ b/test/renderer/project-instructions-editor.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+const rendererRoot = path.join(__dirname, '../../src/renderer');
+const source = fs.readFileSync(path.join(rendererRoot, 'modules/project-detail.js'), 'utf8');
+const html = fs.readFileSync(path.join(rendererRoot, 'index.html'), 'utf8');
+
+type Stub = Record<string, any>;
+
+function element(extra: Stub = {}): Stub {
+ const classes = new Set<string>();
+ return {
+ hidden: false,
+ disabled: false,
+ value: '',
+ textContent: '',
+ dataset: {},
+ style: {},
+ classList: {
+ add: (name: string) => classes.add(name),
+ remove: (name: string) => classes.delete(name),
+ contains: (name: string) => classes.has(name),
+ toggle: (name: string, on: boolean) => (on ? classes.add(name) : classes.delete(name)),
+ },
+ focused: false,
+ focus() { this.focused = true; },
+ setAttribute(name: string, value: string) { this[`attr:${name}`] = value; },
+ setSelectionRange() {},
+ addEventListener() {},
+ ...extra,
+ };
+}
+
+/** Load the module with just the nodes the instructions panel touches. */
+function mount(content: string | null) {
+ const elements: Record<string, Stub> = {
+ 'project-instructions-input': element(),
+ 'project-instructions-read': element(),
+ 'project-instructions-empty': element(),
+ 'project-instructions-edit-btn': element(),
+ 'project-instructions-setup-btn': element(),
+ 'project-instructions-counter': element(),
+ 'project-instructions-save-btn': element(),
+ 'project-instructions-status': element(),
+ 'project-instructions-modal': element(),
+ };
+ const sectionHead = element();
+ const context = vm.createContext({
+ console,
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ document: {
+ readyState: 'loading',
+ addEventListener() {},
+ getElementById: (id: string) => elements[id] || null,
+ querySelector: (selector: string) => (
+ selector === '.project-side-instructions-panel .project-context-section-head' ? sectionHead : null
+ ),
+ createElement: () => element(),
+ },
+ window: { addEventListener() {}, orkas: { invoke: async () => ({ ok: true }) } },
+ escapeHtml: (value: string) => value,
+ t: (key: string) => key,
+ setTimeout,
+ clearTimeout,
+ });
+ vm.runInContext(source, context, { filename: 'project-detail.js' });
+ vm.runInContext(
+ content === null
+ ? '_projectDetailMeta = {}'
+ : `_projectDetailMeta = { instructions: { content: ${JSON.stringify(content)}, limit: 4000 } }`,
+ context,
+ );
+ context._renderProjectInstructions();
+ return { context, elements, sectionHead };
+}
+
+describe('project instructions editor', () => {
+ it('keeps the textarea in a dialog and the saved rules in the rail', () => {
+ expect(html).toContain('id="project-instructions-modal"');
+ expect(html).toMatch(/project-instructions-modal[\s\S]*?id="project-instructions-input"/);
+ expect(html).toContain('id="project-instructions-read"');
+ expect(html).toContain('id="project-instructions-edit-btn"');
+ });
+
+ it('renders saved rules as read-only copy', () => {
+ const { elements, sectionHead } = mount('Verify sources before reporting.');
+ expect(elements['project-instructions-read'].textContent).toBe('Verify sources before reporting.');
+ expect(elements['project-instructions-read'].hidden).toBe(false);
+ expect(elements['project-instructions-empty'].hidden).toBe(true);
+ expect(sectionHead.hidden).toBe(false);
+ expect(elements['project-instructions-edit-btn'].disabled).toBe(false);
+ });
+
+ it('offers the empty state instead of a blank editor when there are no rules', () => {
+ const { elements, sectionHead } = mount('');
+ expect(elements['project-instructions-read'].hidden).toBe(true);
+ expect(elements['project-instructions-empty'].hidden).toBe(false);
+ expect(sectionHead.hidden).toBe(true);
+ });
+
+ it('locks both entry points when instructions never loaded', () => {
+ const { elements } = mount(null);
+ expect(elements['project-instructions-edit-btn'].disabled).toBe(true);
+ expect(elements['project-instructions-setup-btn'].disabled).toBe(true);
+ });
+
+ it('opens on the saved value and drops an abandoned draft on close', async () => {
+ const { context, elements } = mount('Original rules.');
+ const input = elements['project-instructions-input'];
+ const modal = elements['project-instructions-modal'];
+
+ context._openProjectInstructionsEditor();
+ expect(modal.classList.contains('open')).toBe(true);
+ expect(input.value).toBe('Original rules.');
+
+ input.value = 'A draft nobody saved.';
+ await context._closeProjectInstructionsEditor({ force: true });
+ expect(modal.classList.contains('open')).toBe(false);
+ expect(input.value).toBe('Original rules.');
+ // The rail keeps showing what conversations actually get.
+ expect(elements['project-instructions-read'].textContent).toBe('Original rules.');
+
+ context._openProjectInstructionsEditor();
+ expect(input.value).toBe('Original rules.');
+ });
+
+ it('refuses to open the editor for instructions it could not load', () => {
+ const { context, elements } = mount(null);
+ context._openProjectInstructionsEditor();
+ expect(elements['project-instructions-modal'].classList.contains('open')).toBe(false);
+ });
+});
diff --git a/test/renderer/project-memory-controls.test.ts b/test/renderer/project-memory-controls.test.ts
index 53c3d225..6544d242 100644
--- a/test/renderer/project-memory-controls.test.ts
+++ b/test/renderer/project-memory-controls.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
+import * as vm from 'node:vm';
const rendererRoot = path.join(__dirname, '../../src/renderer');
const html = fs.readFileSync(path.join(rendererRoot, 'index.html'), 'utf8');
@@ -54,6 +55,44 @@ describe('project memory controls', () => {
}
});
+ it('swaps the guidance line for the heading once an entry exists', () => {
+ const nodes: Record<string, any> = {
+ 'project-memory-list': { innerHTML: '', style: {}, children: [] as any[], appendChild(child: any) { this.children.push(child); } },
+ 'project-memory-empty': { style: {} },
+ 'project-memory-count': { textContent: '' },
+ 'project-memory-section-head': { hidden: false },
+ };
+ const context = vm.createContext({
+ console,
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ document: {
+ readyState: 'loading',
+ addEventListener() {},
+ getElementById: (id: string) => nodes[id] || null,
+ querySelector: () => null,
+ createElement: () => ({
+ appendChild() {}, className: '', dataset: {}, style: {}, textContent: '',
+ setAttribute() {}, addEventListener() {},
+ }),
+ },
+ window: { addEventListener() {}, orkas: { invoke: async () => ({ ok: true }) } },
+ escapeHtml: (value: string) => value,
+ t: (key: string) => key,
+ setTimeout,
+ clearTimeout,
+ });
+ vm.runInContext(source, context, { filename: 'project-detail.js' });
+
+ vm.runInContext('_projectMemory = []; _renderProjectMemoryList()', context);
+ expect(nodes['project-memory-section-head'].hidden).toBe(true);
+ expect(nodes['project-memory-empty'].style.display).toBe('');
+
+ vm.runInContext("_projectMemory = ['The release checklist is the source of truth.']; _renderProjectMemoryList()", context);
+ expect(nodes['project-memory-section-head'].hidden).toBe(false);
+ expect(nodes['project-memory-empty'].style.display).toBe('none');
+ expect(nodes['project-memory-count'].textContent).toBe('1');
+ });
+
it('guards project-instruction saves with dirty, limit, and error states', () => {
expect(source).toContain("window.orkas.invoke('projects.instructions.set'");
expect(source).toContain("input.value !== (input.dataset.savedValue || '')");
diff --git a/test/renderer/settings-open.test.ts b/test/renderer/settings-open.test.ts
index adf7e5a3..7f1e4ce2 100644
--- a/test/renderer/settings-open.test.ts
+++ b/test/renderer/settings-open.test.ts
@@ -178,6 +178,8 @@ describe('settings sidebar navigation', () => {
expect(handler).toContain("entryPoint: 'agents_connect_cli_button'");
expect(css).toMatch(/\.header-entry-actions\s*{[\s\S]*?gap:\s*6px;[\s\S]*?align-items:\s*stretch;/);
expect(css).toMatch(/\.header-entry-btn\s*{[\s\S]*?min-height:\s*36px;[\s\S]*?padding:\s*4px 10px;[\s\S]*?font-size:\s*12px;/);
+ expect(css).toMatch(/\.header-entry-btn\s*{[\s\S]*?background:\s*var\(--surface\);/);
+ expect(css).not.toMatch(/\.header-entry-btn-create\s*{[^}]*background:/);
expect(css).toMatch(/\.header-entry-icon\s*{[^}]*width:\s*14px;[^}]*height:\s*14px;/);
});
});
diff --git a/test/renderer/utils-autolink.test.ts b/test/renderer/utils-autolink.test.ts
index 4b539495..4df7c842 100644
--- a/test/renderer/utils-autolink.test.ts
+++ b/test/renderer/utils-autolink.test.ts
@@ -32,6 +32,7 @@ const {
_chatMediaLocalPathFromUrl,
_normalizeLocalMediaSrc,
_mediaDedupKey,
+ _localMediaReferenceBasename,
_parseOrkasMediaTitle,
_chatVideoNativeControlsHit,
renderMarkdown,
@@ -48,6 +49,7 @@ const {
_chatMediaLocalPathFromUrl: (src: string) => string;
_normalizeLocalMediaSrc: (src: string) => string;
_mediaDedupKey: (src: string) => string;
+ _localMediaReferenceBasename: (src: string) => string;
_parseOrkasMediaTitle: (title: string) => { kind: 'image' | 'video'; remoteSrc: string } | null;
_chatVideoNativeControlsHit: (clientY: number, rectTop: number, rectBottom: number) => boolean;
renderMarkdown: (md: string) => string;
@@ -379,6 +381,14 @@ describe('markdown media links', () => {
expect(_chatMediaLocalPathFromUrl('https://x.test/a.mp4')).toBe('');
});
+ it('matches stale local media by basename without treating remote media as a produced-file duplicate', () => {
+ expect(_localMediaReferenceBasename('chat-media://local/Users/user/old/narration%20final.wav?v=1'))
+ .toBe('narration final.wav');
+ expect(_localMediaReferenceBasename('drafts/narration.wav#preview')).toBe('narration.wav');
+ expect(_localMediaReferenceBasename('https://cdn.example/narration.wav')).toBe('');
+ expect(_localMediaReferenceBasename('data:audio/wav;base64,AAAA')).toBe('');
+ });
+
it('reserves native video controls while allowing the rest of the surface to toggle playback', () => {
expect(_chatVideoNativeControlsHit(351, 100, 360)).toBe(true);
expect(_chatVideoNativeControlsHit(312, 100, 360)).toBe(true);