Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions apps/desktop/main/agente/rust-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ type ChatState = {
/** Sent with the first turn of a new session only. */
systemPrompt?: string;
turnId: string | null;
/** The provider and model the running turn uses: steered input goes to it. */
turnModel?: { id: string; model: string };
stopRequested: boolean;
stopGrace?: ReturnType<typeof setTimeout>;
settlement?: { promise: Promise<void>; resolve: () => void };
Expand Down Expand Up @@ -559,17 +561,13 @@ async function prompt(chatId: string, text: string, images?: Array<{ data: strin
const provider = await useProvider(client, chat.provider, chat.model, chat.localSelection);
const expanded = await client.request<{ text: string }>('project.expand_prompt', { project_dir: chat.projectRoot, text });
const media = [...attachments, ...(await storeImages(client, images))];
if (media.length) {
const info = await client.request<{ capabilities: { input_modalities?: string[]; vision: boolean } }>('models.info', { provider: provider.id, model: provider.model });
const modalities = info.capabilities.input_modalities || [];
const unsupported = media.filter((item) => modalities.length ? !modalities.includes(item.kind) && !(item.kind === 'pdf' && modalities.includes('file')) : item.kind !== 'image' || !info.capabilities.vision);
if (unsupported.length) throw new Error(`The selected model cannot accept ${unsupported.map((item) => item.name).join(', ')}. Choose a model with those input modalities.`);
}
await assertModelAccepts(client, provider, media);
const message: Message = { role: 'user', content: expanded.text, attachments: media };
if (chat.owner) trackGoalTurn(chat.sessionId, client, chat.owner, provider.id, provider.model, message.content);
const started = await client.request<{ turn_id: string; conversation_index?: number }>('turn.start', turnParams(chat, provider, message));
chat.systemPrompt = undefined;
chat.turnId = started.turn_id;
chat.turnModel = { id: provider.id, model: provider.model };
goalTurnStarted(chat.sessionId,started.turn_id);
const computerOwner = codeComputerOwner(chat); if (computerOwner) bindComputerOwner(computerOwner);
return { ok: true, conversationIndex: started.conversation_index };
Expand All @@ -580,16 +578,37 @@ async function prompt(chatId: string, text: string, images?: Array<{ data: strin
}
}

/**
* One capability decision for every way input reaches a model (a new turn,
* a steer into a running one, a queued follow-up when it starts): refuse
* media the model that will receive it cannot read, rather than letting the
* provider swap the file for a note while the UI still shows it attached.
*/
async function assertModelAccepts(client: Awaited<ReturnType<typeof connect>>, provider: { id: string; model: string }, media: Attachment[]): Promise<void> {
if (!media.length) return;
const info = await client.request<{ capabilities: { input_modalities?: string[]; vision: boolean } }>('models.info', { provider: provider.id, model: provider.model });
const modalities = info.capabilities.input_modalities || [];
const unsupported = media.filter((item) => modalities.length ? !modalities.includes(item.kind) && !(item.kind === 'pdf' && modalities.includes('file')) : item.kind !== 'image' || !info.capabilities.vision);
if (unsupported.length) throw new Error(`The selected model cannot accept ${unsupported.map((item) => item.name).join(', ')}. Choose a model with those input modalities.`);
}

function failedPrompt(error: unknown, message: string): { ok: false; error: string; errorKey?: string } {
return { ok: false, error: message, ...(error instanceof RuntimeNoModelError ? { errorKey: error.errorKey } : {}) };
}

async function steer(chatId: string, text: string, attachments: Attachment[] = []): Promise<{ ok: boolean }> {
async function steer(chatId: string, text: string, attachments: Attachment[] = []): Promise<{ ok: boolean; error?: string }> {
const chat = chats.get(chatId);
if (!chat || chat.stopRequested) return { ok: false };
if (!chat.turnId) return queueFollowUp(chat, text, attachments);
const turnId = chat.turnId;
const client = await connect();
if (attachments.length) {
try {
await assertModelAccepts(client, chat.turnModel || { id: chat.provider, model: chat.model }, attachments);
} catch (error: unknown) {
return { ok: false, error: error instanceof Error ? error.message : String(error) };
}
}
const expanded = await client.request<{ text: string }>('project.expand_prompt', { project_dir: chat.projectRoot, text });
if (chat.stopRequested || chat.turnId !== turnId) return { ok: false };
return client.request('turn.steer', { turn_id: turnId, content: expanded.text, attachments });
Expand Down
46 changes: 34 additions & 12 deletions apps/desktop/main/content-summarizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,24 @@ function topParagraphsByQuery(text, queryTerms, maxChars) {
return left.index - right.index;
});

// Take the best paragraphs that fit whole (the best one is cut to fit if
// it alone is too long). Picking past the budget and cutting the joined
// text afterwards dropped exactly the late, relevant paragraph once the
// selection went back into page order.
const selected = [];
let used = 0;
for (const item of ranked) {
if (used >= maxChars) break;
const room = maxChars - used;
if (room <= 0) break;
const candidate = item.paragraph;
if (!candidate) continue;
if (candidate.length > room) {
if (!selected.length) {
selected.push({ ...item, paragraph: candidate.slice(0, room) });
used = maxChars;
}
continue;
}
selected.push(item);
used += candidate.length + 2;
}
Expand All @@ -50,7 +62,7 @@ function topParagraphsByQuery(text, queryTerms, maxChars) {
export function summarizeCrawledPages({ pages, query, targetChars } = {}) {
const list = Array.isArray(pages) ? pages : [];
const budget = Math.max(500, Number(targetChars) || 4000);
if (!list.length) return { text: '', truncated: false, usedChars: 0 };
if (!list.length) return { text: '', truncated: false, omitted: 0, usedChars: 0 };

const queryTerms = tokenize(query).slice(0, 12);
const rankedPages = [...list].sort((left, right) => {
Expand All @@ -60,21 +72,27 @@ export function summarizeCrawledPages({ pages, query, targetChars } = {}) {
return Number(right?.score || 0) - Number(left?.score || 0);
});

// Each page gets a fair share of what is left, so every source keeps a
// short excerpt instead of the first pages taking the whole budget.
const blocks = [];
const omittedUrls = [];
let used = 0;
for (const page of rankedPages) {
if (used >= budget) break;
const pageBudget = Math.max(600, Math.min(2200, Math.floor((budget - used) * 0.55)));
const condensed = topParagraphsByQuery(page?.content || '', queryTerms, pageBudget);
if (!condensed) continue;
const block = [
for (let i = 0; i < rankedPages.length; i += 1) {
const page = rankedPages[i];
const header = [
`## ${page?.title || page?.url || 'Untitled page'}`,
page?.url ? `URL: ${page.url}` : null,
condensed
page?.url ? `URL: ${page.url}` : null
].filter(Boolean).join('\n\n');
if (!block) continue;
const share = Math.floor((budget - used) / (rankedPages.length - i)) - header.length - 12;
const pageBudget = Math.min(2200, share);
const condensed = pageBudget >= 120 ? topParagraphsByQuery(page?.content || '', queryTerms, pageBudget) : '';
if (!condensed) {
if (page?.url) omittedUrls.push(page.url);
continue;
}
const block = `${header}\n\n${condensed}`;
blocks.push(block);
used += block.length + 6;
used += block.length + 7;
}

let text = blocks.join('\n\n---\n\n');
Expand All @@ -88,10 +106,14 @@ export function summarizeCrawledPages({ pages, query, targetChars } = {}) {
if (blocks.length < list.length) {
truncated = true;
}
if (omittedUrls.length) {
text = `${text}\n\n(Not included for space: ${omittedUrls.join(', ')})`;
}

return {
text,
truncated,
omitted: list.length - blocks.length,
usedChars: text.length
};
}
19 changes: 19 additions & 0 deletions apps/desktop/main/embedding-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,22 @@ export async function getEmbeddings(texts) {
export function clearEmbeddingCache() {
embeddingCache.clear();
}

/**
* Cosine similarity of two embeddings (0 when either is empty, zero-length
* or the sizes differ, as after a model change). The crawler's link scorer
* imports it; without it semantic scoring silently stayed off.
*/
export function cosineSimilarity(left: ArrayLike<number>, right: ArrayLike<number>): number {
if (!left || !right || left.length === 0 || left.length !== right.length) return 0;
let dot = 0;
let leftNorm = 0;
let rightNorm = 0;
for (let i = 0; i < left.length; i += 1) {
dot += left[i] * right[i];
leftNorm += left[i] * left[i];
rightNorm += right[i] * right[i];
}
if (leftNorm === 0 || rightNorm === 0) return 0;
return dot / Math.sqrt(leftNorm * rightNorm);
}
17 changes: 14 additions & 3 deletions apps/desktop/main/rag-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -505,11 +505,22 @@ async function queryDocumentsHybrid({ query, chat_id, top_k, scope, files, file_
wantedDocIds = new Set<string>();
try {
const records = await chatDatabase.request<Array<{ hash?: string; name?: string; ragDocId?: string | null }>>('listFileRecords');
// A hash names one file. A name can belong to files in several chats
// (or two in one): keep every candidate, and let the scope below pick
// the ones this chat may read — choosing one record first lost the
// in-scope file whenever another chat used the same name.
const byHash = new Map(records.map((file) => [String(file.hash), file]));
const byName = new Map(records.map((file) => [String(file.name).toLowerCase(), file]));
const byName = new Map<string, typeof records>();
for (const file of records) {
const name = String(file.name).toLowerCase();
byName.set(name, [...(byName.get(name) || []), file]);
}
for (const entry of wanted) {
const file = byHash.get(entry) || byName.get(entry.toLowerCase());
if (file?.ragDocId) wantedDocIds.add(String(file.ragDocId));
const exact = byHash.get(entry);
const matches = exact ? [exact] : byName.get(entry.toLowerCase()) || [];
for (const file of matches) {
if (file.ragDocId) wantedDocIds.add(String(file.ragDocId));
}
}
} catch {
// Without the registry a name filter cannot be resolved; the other
Expand Down
17 changes: 13 additions & 4 deletions apps/desktop/main/search-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
normalizeProviderName, providerHasCredentials, providerDisplayName, providerCandidates,
getCacheKey, getCachedResult, setCachedResult, mergeAndRankResults, buildContext,
buildJinaReaderUrl, toErrorMessage, classifyNetworkError, providerSearchError,
REMOVED_SEARCH_PROVIDERS
REMOVED_SEARCH_PROVIDERS, tokenize
} from './search-providers/shared.ts';
import type { SearchResult } from './search-providers/shared.ts';
import {
Expand Down Expand Up @@ -135,7 +135,11 @@ async function fetchPageContent(url: string, options: Record<string, unknown> =

/** Prefer pages with more query-relevant title/snippet before scraping. */
function scoreResultForDeepFetch(result: SearchResult, query: string): number {
const terms = normalizeWhitespace(query).toLowerCase().match(/[a-z0-9]+/g)?.filter((t) => t.length > 2).slice(0, 12) || [];
// Short words count outside ASCII: a Japanese or Chinese word is often one
// or two characters.
const terms = tokenize(query)
.filter((t) => t.length > 2 || /[^\p{ASCII}]/u.test(t))
.slice(0, 12);
const title = normalizeWhitespace(result.title || '').toLowerCase();
const snippet = normalizeWhitespace(result.snippet || '').toLowerCase();
let score = 0;
Expand Down Expand Up @@ -204,11 +208,16 @@ async function enrichWithDeepContent(results: SearchResult[], limit: number, emi
warning: page?.warning,
scrape_quality: normalizeWhitespace(content).length < 200 ? 'thin' : 'ok'
};
if (!content || normalizeWhitespace(content).length < 200) {
// A blocked or thin read ("Sign in to continue") never replaces a
// fuller body the provider already returned; the warning stays in
// the metadata.
const providerBody = item.r.full_content || '';
const fetchedLength = normalizeWhitespace(content).length;
if (!content || fetchedLength < 200 || fetchedLength < normalizeWhitespace(providerBody).length) {
return {
...item.r,
title: page?.title || item.r.title,
full_content: content || undefined,
full_content: normalizeWhitespace(providerBody).length >= fetchedLength ? providerBody : content,
published_at: page?.published_at || item.r.published_at,
metadata: meta,
scrape_quality: 'thin' as const
Expand Down
9 changes: 5 additions & 4 deletions apps/desktop/main/search-providers/aggregator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,13 @@ async function executeEngine(

try {
const results = await runAggregatorEngine(engine, query, limit, { ...options, aggregator_signal: signal });
const success = results.length > 0;
if (success) recordSuccess(key);
else recordFailure(key);
// A well-formed answer with no matches is a healthy engine: only
// transport, service or response failures (thrown below) count toward
// the cooldown. The empty count stays visible in the diagnostics.
recordSuccess(key);
return {
results,
attempt: { engine, success, result_count: results.length, latency_ms: Date.now() - started, error: success ? undefined : 'No results' },
attempt: { engine, success: true, result_count: results.length, latency_ms: Date.now() - started },
};
} catch (error: unknown) {
const cooldownUntil = signal.aborted ? 0 : recordFailure(key);
Expand Down
46 changes: 33 additions & 13 deletions apps/desktop/main/search-providers/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import type { SearchResult } from './shared.ts';

export async function searchSearxng(query: string, maxResults: number, options: Record<string, unknown>): Promise<SearchResult[]> {
const baseUrl = requireOption(options, 'searxng_base_url', 'No SearXNG base URL');
const url = new URL('/search', baseUrl.replace(/\/+$/, '') + '/');
// Relative to the configured base, so a path prefix (`/searx/`) is kept.
const url = new URL('search', baseUrl.replace(/\/+$/, '') + '/');
url.searchParams.set('q', query);
url.searchParams.set('format', 'json');
url.searchParams.set('language', 'en');
Expand Down Expand Up @@ -112,18 +113,13 @@ export async function searchPerplexity(query: string, maxResults: number, option
? data.sources as unknown[]
: [];

const parsed = parseSearchResultsFromText('perplexity', text, maxResults, 'https://www.perplexity.ai');
if (parsed.length) return parsed;

if (citations.length) {
return citations.slice(0, maxResults).map((citation, index) => normalizeSearchItem('perplexity', {
title: text.split(/\r?\n/).find(Boolean) || `Perplexity result ${index + 1}`,
url: typeof citation === 'string' ? citation : (citation as Record<string, unknown>)?.url || (citation as Record<string, unknown>)?.link || '',
snippet: text.slice(0, 1200),
full_content: text.slice(0, 4000),
metadata: citation as Record<string, unknown>
}, index));
}
// Structured citations are the real sources: prefer them to anything read
// out of the answer text, whose last resort is the Perplexity homepage.
const inline = parseSearchResultsFromText('perplexity', text, maxResults)
.filter((result) => /^https?:\/\//i.test(result.url));
const cited = citationResults(citations, inline, text, maxResults);
if (cited.length) return cited;
if (inline.length) return inline;

if (text) {
return [normalizeSearchItem('perplexity', {
Expand All @@ -137,3 +133,27 @@ export async function searchPerplexity(query: string, maxResults: number, option

return [];
}

/** One result per distinct citation URL, titled from the citation or a matching inline link. */
function citationResults(citations: unknown[], inline: SearchResult[], text: string, maxResults: number): SearchResult[] {
const seen = new Set<string>();
const results: SearchResult[] = [];
for (const citation of citations) {
if (results.length >= maxResults) break;
const record = (citation && typeof citation === 'object' ? citation : {}) as Record<string, unknown>;
const url = String(typeof citation === 'string' ? citation : record.url || record.link || '').trim();
if (!/^https?:\/\//i.test(url) || seen.has(url)) continue;
seen.add(url);
const linked = inline.find((result) => result.url === url);
let host = url;
try { host = new URL(url).hostname.replace(/^www\./, ''); } catch { /* keep the URL */ }
results.push(normalizeSearchItem('perplexity', {
title: String(record.title || linked?.title || host),
url,
snippet: linked?.snippet || text.slice(0, 1200),
full_content: text.slice(0, 4000),
metadata: typeof citation === 'string' ? { citation_index: results.length + 1 } : record
}, results.length));
}
return results;
}
Loading
Loading