Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: support files upload in projects

Louis883c3b732416
diff --git a/core/src/browser/extensions/rag.ts b/core/src/browser/extensions/rag.ts
index 5cbeb1ac6..15addfb52 100644
--- a/core/src/browser/extensions/rag.ts
+++ b/core/src/browser/extensions/rag.ts
@@ -34,6 +34,11 @@ export abstract class RAGExtension extends BaseExtension {
abstract ingestAttachments(threadId: string, files: AttachmentInput[]): Promise<IngestAttachmentsResult>
+ /**
+ * Ingest files for a project-level collection (shared across all threads in the project)
+ */
+ abstract ingestAttachmentsForProject(projectId: string, files: AttachmentInput[]): Promise<IngestAttachmentsResult>
+
/**
* Parse a document into plain text for inline ingestion or preprocessing.
*/
diff --git a/core/src/browser/extensions/vector-db.ts b/core/src/browser/extensions/vector-db.ts
index 27dec0367..cada5f0cc 100644
--- a/core/src/browser/extensions/vector-db.ts
+++ b/core/src/browser/extensions/vector-db.ts
@@ -79,4 +79,35 @@ export abstract class VectorDBExtension extends BaseExtension {
startOrder: number,
endOrder: number
): Promise<VectorSearchResult[]>
+
+ // Project-level operations (shared across all threads in a project)
+ abstract createCollectionForProject(projectId: string, dimension: number): Promise<void>
+ abstract insertChunksForProject(
+ projectId: string,
+ fileId: string,
+ chunks: VectorChunkInput[]
+ ): Promise<void>
+ abstract ingestFileForProject(
+ projectId: string,
+ file: VectorDBFileInput,
+ opts: VectorDBIngestOptions
+ ): Promise<AttachmentFileInfo>
+ abstract searchCollectionForProject(
+ projectId: string,
+ query_embedding: number[],
+ limit: number,
+ threshold: number,
+ mode?: SearchMode,
+ fileIds?: string[]
+ ): Promise<VectorSearchResult[]>
+ abstract deleteChunksForProject(projectId: string, ids: string[]): Promise<void>
+ abstract deleteFileForProject(projectId: string, fileId: string): Promise<void>
+ abstract deleteCollectionForProject(projectId: string): Promise<void>
+ abstract listAttachmentsForProject(projectId: string, limit?: number): Promise<AttachmentFileInfo[]>
+ abstract getChunksForProject(
+ projectId: string,
+ fileId: string,
+ startOrder: number,
+ endOrder: number
+ ): Promise<VectorSearchResult[]>
}
diff --git a/extensions/rag-extension/src/index.ts b/extensions/rag-extension/src/index.ts
index 3307d973a..e73fc5848 100644
--- a/extensions/rag-extension/src/index.ts
+++ b/extensions/rag-extension/src/index.ts
@@ -125,7 +125,9 @@ export default class RagExtension extends RAGExtension {
args: Record<string, unknown>
): Promise<MCPToolCallResult> {
const threadId = String(args['thread_id'] || '')
- if (!threadId) {
+ const scope = String(args['scope'] || 'thread')
+
+ if (!threadId && scope === 'thread') {
return {
error: 'Missing thread_id',
content: [{ type: 'text', text: 'Missing thread_id' }],
@@ -135,7 +137,7 @@ export default class RagExtension extends RAGExtension {
const vec = window.core?.extensionManager.get(
ExtensionTypeEnum.VectorDB
) as unknown as VectorDBExtension
- if (!vec?.listAttachments) {
+ if (!vec?.listAttachments && !vec?.listAttachmentsForProject) {
return {
error: 'Vector DB extension missing listAttachments',
content: [
@@ -146,7 +148,14 @@ export default class RagExtension extends RAGExtension {
],
}
}
- const files = await vec.listAttachments(threadId)
+
+ let files: AttachmentFileInfo[] = []
+ if (scope === 'project' && vec.listAttachmentsForProject) {
+ files = await vec.listAttachmentsForProject(threadId)
+ } else if (vec.listAttachments) {
+ files = await vec.listAttachments(threadId)
+ }
+
return {
error: '',
content: [
@@ -154,16 +163,17 @@ export default class RagExtension extends RAGExtension {
type: 'text',
text: JSON.stringify({
thread_id: threadId,
+ scope,
attachments: files || [],
}),
},
],
}
} catch (e) {
- const msg = e instanceof Error ? e.message : String(e)
+ const msg = e instanceof Error ? e.message : JSON.stringify(e)
return {
error: msg,
- content: [{ type: 'text', text: `List attachments failed: ${msg}` }],
+ content: [{ type: 'text', text: `List attachments failed: ${JSON.stringify(msg)}` }],
}
}
}
@@ -172,8 +182,13 @@ export default class RagExtension extends RAGExtension {
args: Record<string, unknown>
): Promise<MCPToolCallResult> {
const threadId = String(args['thread_id'] || '')
+ const projectId = String(args['project_id'] || '')
const query = String(args['query'] || '')
const fileIds = args['file_ids'] as string[] | undefined
+ const scope = String(args['scope'] || 'thread')
+
+ // Use project_id as threadId when scope is project
+ const effectiveThreadId = scope === 'project' ? projectId || threadId : threadId
const s = this.config
const topK = (args['top_k'] as number) || s.retrievalLimit || 3
@@ -191,9 +206,9 @@ export default class RagExtension extends RAGExtension {
],
}
}
- if (!threadId || !query) {
+ if (!query || (!threadId && scope === 'thread') || (scope === 'project' && !effectiveThreadId)) {
return {
- error: 'Missing thread_id or query',
+ error: 'Missing thread_id, project_id, or query',
content: [{ type: 'text', text: 'Missing required parameters' }],
}
}
@@ -203,7 +218,7 @@ export default class RagExtension extends RAGExtension {
const vec = window.core?.extensionManager.get(
ExtensionTypeEnum.VectorDB
) as unknown as VectorDBExtension
- if (!vec?.searchCollection) {
+ if (!vec?.searchCollection && !vec?.searchCollectionForProject) {
return {
error: 'RAG dependencies not available',
content: [
@@ -220,17 +235,31 @@ export default class RagExtension extends RAGExtension {
}
}
- const results = await vec.searchCollection(
- threadId,
- queryEmb,
- topK,
- threshold,
- mode,
- fileIds
- )
+ let results
+ if (scope === 'project' && vec.searchCollectionForProject) {
+ results = await vec.searchCollectionForProject(
+ effectiveThreadId,
+ queryEmb,
+ topK,
+ threshold,
+ mode,
+ fileIds
+ )
+ } else {
+ results = await vec.searchCollection!(
+ effectiveThreadId,
+ queryEmb,
+ topK,
+ threshold,
+ mode,
+ fileIds
+ )
+ }
const payload = {
thread_id: threadId,
+ project_id: projectId,
+ scope,
query,
citations:
results?.map((r: any) => ({
@@ -270,12 +299,13 @@ export default class RagExtension extends RAGExtension {
const fileId = String(args['file_id'] || '')
const startOrder = args['start_order'] as number | undefined
const endOrder = args['end_order'] as number | undefined
+ const scope = String(args['scope'] || 'thread')
if (
- !threadId ||
!fileId ||
startOrder === undefined ||
- endOrder === undefined
+ endOrder === undefined ||
+ (!threadId && scope === 'thread')
) {
return {
error: 'Missing thread_id, file_id, start_order, or end_order',
@@ -287,7 +317,7 @@ export default class RagExtension extends RAGExtension {
const vec = window.core?.extensionManager.get(
ExtensionTypeEnum.VectorDB
) as unknown as VectorDBExtension
- if (!vec?.getChunks) {
+ if (!vec?.getChunks && !vec?.getChunksForProject) {
return {
error: 'Vector DB extension not available',
content: [
@@ -296,10 +326,16 @@ export default class RagExtension extends RAGExtension {
}
}
- const chunks = await vec.getChunks(threadId, fileId, startOrder, endOrder)
+ let chunks
+ if (scope === 'project' && vec.getChunksForProject) {
+ chunks = await vec.getChunksForProject(threadId, fileId, startOrder, endOrder)
+ } else {
+ chunks = await vec.getChunks!(threadId, fileId, startOrder, endOrder)
+ }
const payload = {
thread_id: threadId,
+ scope,
file_id: fileId,
chunks: chunks || [],
}
@@ -316,7 +352,65 @@ export default class RagExtension extends RAGExtension {
}
}
- // Desktop-only ingestion by file paths
+ // Desktop-only ingestion by file paths for a project
+ async ingestAttachmentsForProject(
+ projectId: string,
+ files: AttachmentInput[]
+ ): Promise<{
+ filesProcessed: number
+ chunksInserted: number
+ files: AttachmentFileInfo[]
+ }> {
+ if (!projectId || !Array.isArray(files) || files.length === 0) {
+ return { filesProcessed: 0, chunksInserted: 0, files: [] }
+ }
+
+ // Respect feature flag: do nothing when disabled
+ if (this.config.enabled === false) {
+ return { filesProcessed: 0, chunksInserted: 0, files: [] }
+ }
+
+ const vec = window.core?.extensionManager.get(
+ ExtensionTypeEnum.VectorDB
+ ) as unknown as VectorDBExtension
+ if (!vec?.ingestFileForProject) {
+ throw new Error('Vector DB extension does not support project-level ingestion')
+ }
+
+ // Load settings
+ const s = this.config
+ const maxSize = (s?.enabled === false ? 0 : s?.maxFileSizeMB) || undefined
+ const chunkSize = s?.chunkSizeChars as number | undefined
+ const chunkOverlap = s?.overlapChars as number | undefined
+
+ let totalChunks = 0
+ const processedFiles: AttachmentFileInfo[] = []
+
+ for (const f of files) {
+ if (!f?.path) continue
+ if (maxSize && f.size && f.size > maxSize * 1024 * 1024) {
+ throw new Error(
+ `File '${f.name}' exceeds size limit (${f.size} bytes > ${maxSize} MB).`
+ )
+ }
+
+ const fileName = f.name || f.path.split(/[\\/]/).pop()
+ const info = await (vec as VectorDBExtension).ingestFileForProject(
+ projectId,
+ { path: f.path, name: fileName, type: f.type, size: f.size },
+ { chunkSize: chunkSize ?? 512, chunkOverlap: chunkOverlap ?? 64 }
+ )
+ totalChunks += Number(info?.chunk_count || 0)
+ processedFiles.push(info)
+ }
+
+ return {
+ filesProcessed: processedFiles.length,
+ chunksInserted: totalChunks,
+ files: processedFiles,
+ }
+ }
+
async ingestAttachments(
threadId: string,
files: AttachmentInput[]
diff --git a/extensions/rag-extension/src/tools.ts b/extensions/rag-extension/src/tools.ts
index a881891b4..8a41363fe 100644
--- a/extensions/rag-extension/src/tools.ts
+++ b/extensions/rag-extension/src/tools.ts
@@ -12,45 +12,62 @@ export function getRAGTools(retrievalLimit: number): MCPTool[] {
{
name: LIST_ATTACHMENTS,
description:
- 'List files attached to the current thread. Thread is inferred automatically; you may optionally provide {"scope":"thread"}. Returns basic file info (name/path).',
+ 'List files attached to the current thread or project. Use scope to specify: "thread" for thread-level files (default), "project" for project-level files shared across all threads in the project.',
inputSchema: {
type: 'object',
- properties: {
- scope: { type: 'string', enum: ['thread'], description: 'Retrieval scope; currently only thread is supported' },
- },
- required: ['scope'],
+ properties: {},
+ required: [],
},
server: RAG_INTERNAL_SERVER,
},
{
name: RETRIEVE,
description:
- 'Retrieve relevant snippets from locally attached, indexed documents. Use query only; do not pass raw document content. Thread context is inferred automatically; you may optionally provide {"scope":"thread"}. Use file_ids to search within specific files only.',
+ 'Retrieve relevant snippets from locally attached, indexed documents. Use query only; do not pass raw document content. Use scope to search: "thread" (default) for thread-level files, "project" for project-level files shared across all threads. Use file_ids to search within specific files only.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'User query to search for' },
- top_k: { type: 'number', description: 'Optional: Max citations to return. Adjust as needed.', minimum: 1, maximum: maxTopK, default: retrievalLimit ?? 3 },
- scope: { type: 'string', enum: ['thread'], description: 'Retrieval scope; currently only thread is supported' },
- file_ids: { type: 'array', items: { type: 'string' }, description: 'Optional: Filter search to specific file IDs from list_attachments' },
+ top_k: {
+ type: 'number',
+ description: 'Optional: Max citations to return. Adjust as needed.',
+ minimum: 1,
+ maximum: maxTopK,
+ default: retrievalLimit ?? 3,
+ },
+ file_ids: {
+ type: 'array',
+ items: { type: 'string' },
+ description:
+ 'Optional: Filter search to specific file IDs from list_attachments',
+ },
},
- required: ['query', 'scope'],
+ required: ['query'],
},
server: RAG_INTERNAL_SERVER,
},
{
name: GET_CHUNKS,
description:
- 'Retrieve chunks from a file by their order range. For a single chunk, use start_order = end_order. Thread context is inferred automatically; you may optionally provide {"scope":"thread"}. Use sparingly; intended for advanced usage. Prefer using retrieve instead for relevance-based fetching.',
+ 'Retrieve chunks from a file by their order range. For a single chunk, use start_order = end_order. Use scope to specify source: "thread" (default) for thread-level, "project" for project-level files. Use sparingly; intended for advanced usage. Prefer using retrieve instead for relevance-based fetching.',
inputSchema: {
type: 'object',
properties: {
- file_id: { type: 'string', description: 'File ID from list_attachments' },
- start_order: { type: 'number', description: 'Start of chunk range (inclusive, 0-indexed)' },
- end_order: { type: 'number', description: 'End of chunk range (inclusive, 0-indexed). For single chunk, use start_order = end_order.' },
- scope: { type: 'string', enum: ['thread'], description: 'Retrieval scope; currently only thread is supported' },
+ file_id: {
+ type: 'string',
+ description: 'File ID from list_attachments',
+ },
+ start_order: {
+ type: 'number',
+ description: 'Start of chunk range (inclusive, 0-indexed)',
+ },
+ end_order: {
+ type: 'number',
+ description:
+ 'End of chunk range (inclusive, 0-indexed). For single chunk, use start_order = end_order.',
+ },
},
- required: ['file_id', 'start_order', 'end_order', 'scope'],
+ required: ['file_id', 'start_order', 'end_order'],
},
server: RAG_INTERNAL_SERVER,
},
diff --git a/extensions/vector-db-extension/src/index.ts b/extensions/vector-db-extension/src/index.ts
index 1d94e9f0c..a3742c4ac 100644
--- a/extensions/vector-db-extension/src/index.ts
+++ b/extensions/vector-db-extension/src/index.ts
@@ -17,6 +17,14 @@ export default class VectorDBExt extends VectorDBExtension {
return `attachments_${threadId}`
}
+ private collectionForProject(projectId: string): string {
+ return `project_${projectId}`
+ }
+
+ async createCollectionForProject(projectId: string, dimension: number): Promise<void> {
+ return await vecdb.createCollection(this.collectionForProject(projectId), dimension)
+ }
+
async createCollection(threadId: string, dimension: number): Promise<void> {
return await vecdb.createCollection(this.collectionForThread(threadId), dimension)
}
@@ -44,6 +52,96 @@ export default class VectorDBExt extends VectorDBExtension {
return await vecdb.deleteCollection(this.collectionForThread(threadId))
}
+ async insertChunksForProject(projectId: string, fileId: string, chunks: VectorChunkInput[]): Promise<void> {
+ return await vecdb.insertChunks(this.collectionForProject(projectId), fileId, chunks)
+ }
+
+ async searchCollectionForProject(
+ projectId: string,
+ query_embedding: number[],
+ limit: number,
+ threshold: number,
+ mode?: SearchMode,
+ fileIds?: string[]
+ ): Promise<VectorSearchResult[]> {
+ return await vecdb.searchCollection(this.collectionForProject(projectId), query_embedding, limit, threshold, mode, fileIds) as VectorSearchResult[]
+ }
+
+ async deleteChunksForProject(projectId: string, ids: string[]): Promise<void> {
+ return await vecdb.deleteChunks(this.collectionForProject(projectId), ids)
+ }
+
+ async deleteCollectionForProject(projectId: string): Promise<void> {
+ return await vecdb.deleteCollection(this.collectionForProject(projectId))
+ }
+
+ async ingestFileForProject(projectId: string, file: VectorDBFileInput, opts: VectorDBIngestOptions): Promise<AttachmentFileInfo> {
+ // First, parse the document and get embeddings to determine dimension
+ const text = await ragApi.parseDocument(file.path, file.type || 'application/octet-stream')
+ const chunks = await this.chunkText(text, opts.chunkSize, opts.chunkOverlap)
+
+ // Get embeddings to determine dimension - use a default if no chunks
+ let dimension = 0
+ if (chunks.length > 0) {
+ const embeddings = await this.embedTexts(chunks)
+ dimension = embeddings[0]?.length || 0
+ }
+
+ // Ensure collection exists (use default dimension 384 if no embeddings yet)
+ const collectionDimension = dimension > 0 ? dimension : 384
+ await this.createCollectionForProject(projectId, collectionDimension)
+
+ // Now check for duplicates
+ const existingFiles = await vecdb.listAttachments(this.collectionForProject(projectId)).catch(() => [])
+ const duplicate = existingFiles.find((f: any) => f.name === file.name && f.path === file.path)
+ if (duplicate) {
+ throw new Error(`File '${file.name}' has already been attached to this project`)
+ }
+
+ if (!chunks.length) {
+ const fi = await vecdb.createFile(this.collectionForProject(projectId), file)
+ return fi
+ }
+
+ // Re-embed if we got dimension from createCollection
+ const embeddings = await this.embedTexts(chunks)
+ const finalDimension = embeddings[0]?.length || 0
+ if (finalDimension <= 0) throw new Error('Embedding dimension not available')
+
+ // Ensure collection has correct dimension
+ if (finalDimension !== collectionDimension) {
+ await this.deleteCollectionForProject(projectId)
+ await this.createCollectionForProject(projectId, finalDimension)
+ }
+
+ const fi = await vecdb.createFile(this.collectionForProject(projectId), file)
+ await vecdb.insertChunks(
+ this.collectionForProject(projectId),
+ fi.id,
+ chunks.map((t, i) => ({ text: t, embedding: embeddings[i] }))
+ )
+ const infos = await vecdb.listAttachments(this.collectionForProject(projectId))
+ const updated = infos.find((e) => e.id === fi.id)
+ return updated || { ...fi, chunk_count: chunks.length }
+ }
+
+ async listAttachmentsForProject(projectId: string, limit?: number): Promise<AttachmentFileInfo[]> {
+ return await vecdb.listAttachments(this.collectionForProject(projectId), limit) as AttachmentFileInfo[]
+ }
+
+ async getChunksForProject(
+ projectId: string,
+ fileId: string,
+ startOrder: number,
+ endOrder: number
+ ): Promise<VectorSearchResult[]> {
+ return await vecdb.getChunks(this.collectionForProject(projectId), fileId, startOrder, endOrder) as VectorSearchResult[]
+ }
+
+ async deleteFileForProject(projectId: string, fileId: string): Promise<void> {
+ return await vecdb.deleteFile(this.collectionForProject(projectId), fileId)
+ }
+
// Optional helper for chunking
private async chunkText(text: string, chunkSize: number, chunkOverlap: number): Promise<string[]> {
return await vecdb.chunkText(text, chunkSize, chunkOverlap)
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3a76defd4..a384dca37 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -104,6 +104,7 @@ rfd = { version = "0.15.4", default-features = false, features = [
chrono = { version = "0.4", features = ["serde"] }
hostname = "0.4"
glob = "0.3"
+tauri-plugin-dialog = "2"
[dependencies.tauri]
version = "2.8.5"
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index c5aa88b8f..d8f84e97c 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -28,6 +28,7 @@
"llamacpp:default",
"updater:default",
"updater:allow-check",
+ "dialog:default",
{
"identifier": "http:default",
"allow": [
diff --git a/src-tauri/src/core/app/commands.rs b/src-tauri/src/core/app/commands.rs
index 72914948e..13a8b2e7b 100644
--- a/src-tauri/src/core/app/commands.rs
+++ b/src-tauri/src/core/app/commands.rs
@@ -34,15 +34,19 @@ pub fn get_app_configurations<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Ap
}
match fs::read_to_string(&configuration_file) {
- Ok(content) => match serde_json::from_str::<AppConfiguration>(&content) {
- Ok(app_configurations) => app_configurations,
- Err(err) => {
- log::error!("Failed to parse app config, returning default config instead. Error: {err}");
- app_default_configuration
+ Ok(content) => {
+ match serde_json::from_str::<AppConfiguration>(&content) {
+ Ok(app_configurations) => app_configurations,
+ Err(err) => {
+ log::error!("Failed to parse app config, returning default config instead. Error: {err}");
+ app_default_configuration
+ }
}
- },
+ }
Err(err) => {
- log::error!("Failed to read app config, returning default config instead. Error: {err}");
+ log::error!(
+ "Failed to read app config, returning default config instead. Error: {err}"
+ );
app_default_configuration
}
}
@@ -96,9 +100,7 @@ pub fn get_jan_data_folder_path<R: Runtime>(app_handle: tauri::AppHandle<R>) ->
#[tauri::command]
pub fn get_configuration_file_path<R: Runtime>(app_handle: tauri::AppHandle<R>) -> PathBuf {
let app_path = app_handle.path().app_data_dir().unwrap_or_else(|err| {
- log::error!(
- "Failed to get app data directory: {err}. Using home directory instead."
- );
+ log::error!("Failed to get app data directory: {err}. Using home directory instead.");
let home_dir = std::env::var(if cfg!(target_os = "windows") {
"USERPROFILE"
diff --git a/src-tauri/src/core/downloads/helpers.rs b/src-tauri/src/core/downloads/helpers.rs
index 948ddfa97..799fd8a45 100644
--- a/src-tauri/src/core/downloads/helpers.rs
+++ b/src-tauri/src/core/downloads/helpers.rs
@@ -1,4 +1,4 @@
-use super::models::{DownloadEvent, DownloadItem, ProxyConfig, ProgressTracker};
+use super::models::{DownloadEvent, DownloadItem, ProgressTracker, ProxyConfig};
use crate::core::app::commands::get_jan_data_folder_path;
use futures_util::StreamExt;
use jan_utils::normalize_path;
@@ -18,7 +18,6 @@ pub fn err_to_string<E: std::fmt::Display>(e: E) -> String {
format!("Error: {e}")
}
-
// ===== VALIDATION FUNCTIONS =====
/// Validates a downloaded file against expected hash and size
@@ -40,13 +39,17 @@ async fn validate_downloaded_file(
// Use model_id from item if available, otherwise extract from save path
// Path structure: llamacpp/models/{modelId}/model.gguf or llamacpp/models/{modelId}/mmproj.gguf
- let model_id = item.model_id.as_ref().map(|s| s.as_str()).unwrap_or_else(|| {
- save_path
- .parent() // get parent directory (modelId folder)
- .and_then(|p| p.file_name())
- .and_then(|n| n.to_str())
- .unwrap_or("unknown")
- });
+ let model_id = item
+ .model_id
+ .as_ref()
+ .map(|s| s.as_str())
+ .unwrap_or_else(|| {
+ save_path
+ .parent() // get parent directory (modelId folder)
+ .and_then(|p| p.file_name())
+ .and_then(|n| n.to_str())
+ .unwrap_or("unknown")
+ });
if emit_event {
app.emit(
@@ -107,7 +110,9 @@ async fn validate_downloaded_file(
if let Some(expected_sha256) = &item.sha256 {
log::info!("Starting Hash verification for {}", item.url);
- match jan_utils::crypto::compute_file_sha256_with_cancellation(save_path, cancel_token).await {
+ match jan_utils::crypto::compute_file_sha256_with_cancellation(save_path, cancel_token)
+ .await
+ {
Ok(computed_sha256) => {
if computed_sha256 != *expected_sha256 {
log::error!(
@@ -368,15 +373,7 @@ pub async fn _download_files_internal(
};
let task = tokio::spawn(async move {
- download_single_file(
- app_clone,
- &item_clone,
- &save_path,
- file_id,
- file_size,
- ctx,
- )
- .await
+ download_single_file(app_clone, &item_clone, &save_path, file_id, file_size, ctx).await
});
download_tasks.push(task);
@@ -395,7 +392,14 @@ pub async fn _download_files_internal(
let path_clone = downloaded_path.clone();
let cancel_token_clone = cancel_token.clone();
let validation_task = tokio::spawn(async move {
- validate_downloaded_file(&item_clone, &path_clone, &app_clone, &cancel_token_clone, false).await
+ validate_downloaded_file(
+ &item_clone,
+ &path_clone,
+ &app_clone,
+ &cancel_token_clone,
+ false,
+ )
+ .await
});
validation_tasks.push((validation_task, downloaded_path, item.clone()));
}
@@ -403,7 +407,8 @@ pub async fn _download_files_internal(
}
}
- let model_id = items.iter()
+ let model_id = items
+ .iter()
.find_map(|item| item.model_id.as_ref())
.map(|s| s.as_str())
.or_else(|| {
@@ -416,7 +421,11 @@ pub async fn _download_files_internal(
})
.unwrap_or("unknown");
- if !validation_tasks.is_empty() && items.iter().any(|item| item.sha256.is_some() || item.size.is_some()) {
+ if !validation_tasks.is_empty()
+ && items
+ .iter()
+ .any(|item| item.sha256.is_some() || item.size.is_some())
+ {
app.emit(
"onModelValidationStarted",
serde_json::json!({
diff --git a/src-tauri/src/core/filesystem/commands.rs b/src-tauri/src/core/filesystem/commands.rs
index bc441f083..aa405e029 100644
--- a/src-tauri/src/core/filesystem/commands.rs
+++ b/src-tauri/src/core/filesystem/commands.rs
@@ -261,53 +261,6 @@ pub fn decompress<R: Runtime>(
Ok(())
}
-// rfd native file dialog
-#[tauri::command]
-pub async fn open_dialog(
- options: Option<DialogOpenOptions>,
-) -> Result<Option<serde_json::Value>, String> {
- let mut dialog = AsyncFileDialog::new();
-
- if let Some(opts) = options {
- // Set default path
- if let Some(path) = opts.default_path {
- dialog = dialog.set_directory(&path);
- }
-
- // Set filters
- if let Some(filters) = opts.filters {
- for filter in filters {
- let extensions: Vec<&str> = filter.extensions.iter().map(|s| s.as_str()).collect();
- dialog = dialog.add_filter(&filter.name, &extensions);
- }
- }
-
- // Handle directory vs file selection
- if opts.directory == Some(true) {
- let result = dialog.pick_folder().await;
- return Ok(result.map(|folder| {
- serde_json::Value::String(folder.path().to_string_lossy().to_string())
- }));
- }
-
- // Handle multiple file selection
- if opts.multiple == Some(true) {
- let result = dialog.pick_files().await;
- return Ok(result.map(|files| {
- let paths: Vec<String> = files
- .iter()
- .map(|f| f.path().to_string_lossy().to_string())
- .collect();
- serde_json::to_value(paths).unwrap()
- }));
- }
- }
-
- // Default: single file selection
- let result = dialog.pick_file().await;
- Ok(result.map(|file| serde_json::Value::String(file.path().to_string_lossy().to_string())))
-}
-
#[tauri::command]
pub async fn save_dialog(options: Option<DialogOpenOptions>) -> Result<Option<String>, String> {
let mut dialog = AsyncFileDialog::new();
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 6c417c420..78e695579 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -9,9 +9,7 @@ use super::{
helpers::{restart_active_mcp_servers, start_mcp_server},
};
use crate::core::{
- app::commands::get_jan_data_folder_path,
- mcp::models::McpSettings,
- state::AppState,
+ app::commands::get_jan_data_folder_path, mcp::models::McpSettings, state::AppState,
};
use crate::core::{
mcp::models::ToolWithServer,
@@ -20,11 +18,7 @@ use crate::core::{
use std::{fs, time::Duration};
async fn tool_call_timeout(state: &State<'_, AppState>) -> Duration {
- state
- .mcp_settings
- .lock()
- .await
- .tool_call_timeout_duration()
+ state.mcp_settings.lock().await.tool_call_timeout_duration()
}
#[tauri::command]
@@ -123,7 +117,10 @@ pub async fn deactivate_mcp_server<R: Runtime>(
}
#[tauri::command]
-pub async fn restart_mcp_servers<R: Runtime>(app: AppHandle<R>, state: State<'_, AppState>) -> Result<(), String> {
+pub async fn restart_mcp_servers<R: Runtime>(
+ app: AppHandle<R>,
+ state: State<'_, AppState>,
+) -> Result<(), String> {
use super::helpers::{stop_mcp_servers_with_context, ShutdownContext};
let servers = state.mcp_servers.clone();
@@ -139,7 +136,6 @@ pub async fn restart_mcp_servers<R: Runtime>(app: AppHandle<R>, state: State<'_,
Ok(())
}
-
#[tauri::command]
pub async fn get_connected_servers(
_app: AppHandle<impl Runtime>,
@@ -237,13 +233,12 @@ pub async fn call_tool(
let servers = state.mcp_servers.lock().await;
// If server_name is provided, only check that specific server
- let servers_to_check: Vec<(&String, &crate::core::state::RunningServiceEnum)> = if let Some(ref server) = server_name {
- servers.iter()
- .filter(|(name, _)| *name == server)
- .collect()
- } else {
- servers.iter().collect()
- };
+ let servers_to_check: Vec<(&String, &crate::core::state::RunningServiceEnum)> =
+ if let Some(ref server) = server_name {
+ servers.iter().filter(|(name, _)| *name == server).collect()
+ } else {
+ servers.iter().collect()
+ };
if servers_to_check.is_empty() {
if let Some(server) = server_name {
@@ -322,7 +317,7 @@ pub async fn cancel_tool_call(
cancellation_token: String,
) -> Result<(), String> {
let mut cancellations = state.tool_call_cancellations.lock().await;
-
+
if let Some(cancel_tx) = cancellations.remove(&cancellation_token) {
// Send cancellation signal - ignore if receiver is already dropped
let _ = cancel_tx.send(());
@@ -562,13 +557,16 @@ async fn try_browser_snapshot_tool(service: &RunningServiceEnum) -> Result<bool,
}
#[tauri::command]
-pub async fn save_mcp_configs<R: Runtime>(app: AppHandle<R>, configs: String) -> Result<(), String> {
+pub async fn save_mcp_configs<R: Runtime>(
+ app: AppHandle<R>,
+ configs: String,
+) -> Result<(), String> {
let mut path = get_jan_data_folder_path(app.clone());
path.push("mcp_config.json");
log::info!("save mcp configs, path: {path:?}");
- let mut config_value: Value = serde_json::from_str(&configs)
- .map_err(|e| format!("Invalid MCP config payload: {e}"))?;
+ let mut config_value: Value =
+ serde_json::from_str(&configs).map_err(|e| format!("Invalid MCP config payload: {e}"))?;
if !config_value.is_object() {
return Err("MCP config must be a JSON object".to_string());
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index 030dd266b..41efea71c 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -26,9 +26,9 @@ use jan_utils::{can_override_npx, can_override_uvx};
#[derive(Debug, Clone, Copy)]
pub enum ShutdownContext {
- AppExit, // User closing app - be fast
+ AppExit, // User closing app - be fast
ManualRestart, // User restarting servers - be thorough
- FactoryReset, // Deleting data - be very thorough
+ FactoryReset, // Deleting data - be very thorough
}
impl ShutdownContext {
@@ -120,9 +120,7 @@ pub async fn run_mcp_commands<R: Runtime>(
// If initial startup failed, we still want to continue with other servers
if let Err(e) = &result {
- log::error!(
- "Initial startup failed for MCP server {name_clone}: {e}"
- );
+ log::error!("Initial startup failed for MCP server {name_clone}: {e}");
}
(name_clone, result)
@@ -208,9 +206,7 @@ pub async fn monitor_mcp_server_handle(
if !health_check_result {
// Server failed health check - remove it and return
- log::error!(
- "MCP server {name} failed health check, removing from active servers"
- );
+ log::error!("MCP server {name} failed health check, removing from active servers");
let mut servers = servers_state.lock().await;
if let Some(service) = servers.remove(&name) {
// Try to cancel the service gracefully
@@ -260,9 +256,7 @@ pub async fn start_mcp_server<R: Runtime>(
Ok(())
}
Err(e) => {
- log::error!(
- "Failed to start MCP server {name} on first attempt: {e}"
- );
+ log::error!("Failed to start MCP server {name} on first attempt: {e}");
Err(e)
}
}
@@ -547,9 +541,7 @@ async fn schedule_mcp_start_task<R: Runtime>(
};
if !server_still_running {
- return Err(format!(
- "MCP server {name} quit immediately after starting"
- ));
+ return Err(format!("MCP server {name} quit immediately after starting"));
}
// Create lock file for Jan Browser MCP
@@ -642,13 +634,7 @@ pub async fn restart_active_mcp_servers<R: Runtime>(
let config_clone = config.clone();
tauri::async_runtime::spawn(async move {
- let _ = start_mcp_server(
- app_clone,
- servers_clone,
- name_clone,
- config_clone,
- )
- .await;
+ let _ = start_mcp_server(app_clone, servers_clone, name_clone, config_clone).await;
});
}
@@ -659,7 +645,9 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(
app: &AppHandle<R>,
port: u16,
) -> Result<bool, String> {
- use crate::core::mcp::lockfile::{check_and_cleanup_stale_lock, is_process_alive, read_lock_file};
+ use crate::core::mcp::lockfile::{
+ check_and_cleanup_stale_lock, is_process_alive, read_lock_file,
+ };
// Check lock file first (fast path)
if let Some(lock) = read_lock_file(app, port) {
@@ -744,10 +732,7 @@ pub async fn kill_orphaned_mcp_process_with_app<R: Runtime>(
log::info!("Cleaned up orphaned process on port {}", port);
Ok(true)
} else {
- Err(format!(
- "Port {} still in use after killing process",
- port
- ))
+ Err(format!("Port {} still in use after killing process", port))
}
}
@@ -875,7 +860,8 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(
let port = if key == "Jan Browser MCP" {
let active_servers = state.mcp_active_servers.lock().await;
active_servers.get(&key).and_then(|config| {
- config.get("env")
+ config
+ .get("env")
.and_then(|e| e.get("BRIDGE_PORT"))
.and_then(|p| p.as_str())
.and_then(|s| s.parse::<u16>().ok())
@@ -894,7 +880,10 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(
return Ok(());
}
- let server_names: Vec<String> = servers_to_stop.iter().map(|(name, _, _)| name.clone()).collect();
+ let server_names: Vec<String> = servers_to_stop
+ .iter()
+ .map(|(name, _, _)| name.clone())
+ .collect();
let per_server_timeout = context.per_server_timeout();
let stop_handles: Vec<_> = servers_to_stop
.into_iter()
@@ -932,8 +921,9 @@ pub async fn stop_mcp_servers_with_context<R: Runtime>(
let overall_timeout = context.overall_timeout();
let results = tokio::time::timeout(
overall_timeout,
- futures_util::future::join_all(stop_handles)
- ).await;
+ futures_util::future::join_all(stop_handles),
+ )
+ .await;
let failed_servers: Vec<String> = match results {
Ok(results) => {
diff --git a/src-tauri/src/core/mcp/lockfile.rs b/src-tauri/src/core/mcp/lockfile.rs
index 44aba55ca..f834f1e2f 100644
--- a/src-tauri/src/core/mcp/lockfile.rs
+++ b/src-tauri/src/core/mcp/lockfile.rs
@@ -43,11 +43,10 @@ pub fn create_lock_file<R: Runtime>(
.unwrap_or_else(|_| "unknown".to_string()),
};
- let lock_json =
- serde_json::to_string_pretty(&lock).map_err(|e| format!("Failed to serialize lock: {}", e))?;
+ let lock_json = serde_json::to_string_pretty(&lock)
+ .map_err(|e| format!("Failed to serialize lock: {}", e))?;
- fs::write(&lock_path, lock_json)
- .map_err(|e| format!("Failed to write lock file: {}", e))?;
+ fs::write(&lock_path, lock_json).map_err(|e| format!("Failed to write lock file: {}", e))?;
log::debug!("Created lock file for port {} at {:?}", port, lock_path);
Ok(())
@@ -68,8 +67,7 @@ pub fn delete_lock_file<R: Runtime>(app: &AppHandle<R>, port: u16) -> Result<(),
let lock_path = get_lock_file_path(app, port);
if lock_path.exists() {
- fs::remove_file(&lock_path)
- .map_err(|e| format!("Failed to delete lock file: {}", e))?;
+ fs::remove_file(&lock_path).map_err(|e| format!("Failed to delete lock file: {}", e))?;
log::debug!("Deleted lock file for port {}", port);
}
diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rs
index 2175bcb05..075f3101d 100644
--- a/src-tauri/src/core/mcp/tests.rs
+++ b/src-tauri/src/core/mcp/tests.rs
@@ -80,15 +80,17 @@ fn test_add_server_config_new_file() {
assert!(result.is_ok(), "Failed to add server config: {result:?}");
// Verify the config was added correctly
- let config_content = std::fs::read_to_string(&config_path)
- .expect("Failed to read config file");
- let config: serde_json::Value = serde_json::from_str(&config_content)
- .expect("Failed to parse config");
+ let config_content = std::fs::read_to_string(&config_path).expect("Failed to read config file");
+ let config: serde_json::Value =
+ serde_json::from_str(&config_content).expect("Failed to parse config");
assert!(config["mcpServers"]["test_server"].is_object());
assert_eq!(config["mcpServers"]["test_server"]["command"], "npx");
assert_eq!(config["mcpServers"]["test_server"]["args"][0], "-y");
- assert_eq!(config["mcpServers"]["test_server"]["args"][1], "test-server");
+ assert_eq!(
+ config["mcpServers"]["test_server"]["args"][1],
+ "test-server"
+ );
// Clean up
std::fs::remove_file(&config_path).expect("Failed to remove config file");
@@ -117,8 +119,12 @@ fn test_add_server_config_existing_servers() {
});
let mut file = File::create(&config_path).expect("Failed to create config file");
- file.write_all(serde_json::to_string_pretty(&initial_config).unwrap().as_bytes())
- .expect("Failed to write to config file");
+ file.write_all(
+ serde_json::to_string_pretty(&initial_config)
+ .unwrap()
+ .as_bytes(),
+ )
+ .expect("Failed to write to config file");
drop(file);
// Add new server
@@ -138,14 +144,16 @@ fn test_add_server_config_existing_servers() {
assert!(result.is_ok(), "Failed to add server config: {result:?}");
// Verify both servers exist
- let config_content = std::fs::read_to_string(&config_path)
- .expect("Failed to read config file");
- let config: serde_json::Value = serde_json::from_str(&config_content)
- .expect("Failed to parse config");
+ let config_content = std::fs::read_to_string(&config_path).expect("Failed to read config file");
+ let config: serde_json::Value =
+ serde_json::from_str(&config_content).expect("Failed to parse config");
// Check existing server is still there
assert!(config["mcpServers"]["existing_server"].is_object());
- assert_eq!(config["mcpServers"]["existing_server"]["command"], "existing_command");
+ assert_eq!(
+ config["mcpServers"]["existing_server"]["command"],
+ "existing_command"
+ );
// Check new server was added
assert!(config["mcpServers"]["new_server"].is_object());
@@ -179,13 +187,12 @@ fn test_add_server_config_missing_config_file() {
"active": false
});
- let result = add_server_config(
- app.handle().clone(),
- "test".to_string(),
- server_value,
- );
+ let result = add_server_config(app.handle().clone(), "test".to_string(), server_value);
- assert!(result.is_err(), "Expected error when config file doesn't exist");
+ assert!(
+ result.is_err(),
+ "Expected error when config file doesn't exist"
+ );
assert!(result.unwrap_err().contains("Failed to read config file"));
}
@@ -300,7 +307,6 @@ async fn test_background_cleanup_with_empty_state() {
let active = state.mcp_active_servers.lock().await;
assert!(active.is_empty());
-
}
#[tokio::test]
@@ -384,14 +390,14 @@ fn test_extension_disconnected_error_detection() {
fn test_extension_connected_response_detection() {
// Valid responses when extension IS connected - should NOT trigger error detection
let connected_responses = [
- "pong", // Successful ping response
- "Success", // Generic success
- "Connected successfully", // Connection confirmation
- "", // Empty response (not an error)
- "Screenshot captured", // Successful browser_snapshot
- "Page loaded", // Browser action success
- "browser", // Single keyword (not an error pattern)
- "tool", // Single keyword (not an error pattern)
+ "pong", // Successful ping response
+ "Success", // Generic success
+ "Connected successfully", // Connection confirmation
+ "", // Empty response (not an error)
+ "Screenshot captured", // Successful browser_snapshot
+ "Page loaded", // Browser action success
+ "browser", // Single keyword (not an error pattern)
+ "tool", // Single keyword (not an error pattern)
];
for msg in connected_responses {
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 46c80c6dd..6c15fec87 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -438,21 +438,28 @@ async fn proxy_request(
(hyper::Method::GET, "/openapi.json") => {
let static_body = include_str!("../../../static/openapi.json"); // relative to src-tauri/src/
- // Parse the static OpenAPI JSON and update the server URL with actual host and port
+ // Parse the static OpenAPI JSON and update the server URL with actual host and port
match serde_json::from_str::<serde_json::Value>(static_body) {
Ok(mut openapi_spec) => {
// Update the servers array with the actual host and port
- if let Some(servers) = openapi_spec.get_mut("servers").and_then(|s| s.as_array_mut()) {
+ if let Some(servers) = openapi_spec
+ .get_mut("servers")
+ .and_then(|s| s.as_array_mut())
+ {
for server in servers {
if let Some(server_obj) = server.as_object_mut() {
if let Some(url) = server_obj.get_mut("url") {
- let base_url = format!("http://{}:{}{}", config.host, config.port, config.prefix);
+ let base_url = format!(
+ "http://{}:{}{}",
+ config.host, config.port, config.prefix
+ );
*url = serde_json::Value::String(base_url);
}
}
}
}
- let body = serde_json::to_string(&openapi_spec).unwrap_or_else(|_| static_body.to_string());
+ let body = serde_json::to_string(&openapi_spec)
+ .unwrap_or_else(|_| static_body.to_string());
return Ok(Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "application/json")
diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rs
index b85a42fe2..9b584e277 100644
--- a/src-tauri/src/core/server/tests.rs
+++ b/src-tauri/src/core/server/tests.rs
@@ -54,12 +54,7 @@ mod tests {
#[test]
fn test_messages_subpath_not_in_exact_whitelist() {
- let whitelisted_paths = [
- "/",
- "/openapi.json",
- "/favicon.ico",
- "/messages",
- ];
+ let whitelisted_paths = ["/", "/openapi.json", "/favicon.ico", "/messages"];
// Only exact match
assert!(!whitelisted_paths.contains(&"/messages/threads"));
assert!(!whitelisted_paths.contains(&"/messages/api"));
@@ -194,9 +189,7 @@ mod tests {
.map(|token| token == api_key)
.unwrap_or(false);
- let api_key_valid = x_api_key_header
- .map(|key| key == api_key)
- .unwrap_or(false);
+ let api_key_valid = x_api_key_header.map(|key| key == api_key).unwrap_or(false);
assert!(auth_valid || api_key_valid);
}
@@ -212,9 +205,7 @@ mod tests {
.map(|token| token == api_key)
.unwrap_or(false);
- let api_key_valid = x_api_key_header
- .map(|key| key == api_key)
- .unwrap_or(false);
+ let api_key_valid = x_api_key_header.map(|key| key == api_key).unwrap_or(false);
assert!(auth_valid || api_key_valid);
}
@@ -230,9 +221,7 @@ mod tests {
.map(|token| token == api_key)
.unwrap_or(false);
- let api_key_valid = x_api_key_header
- .map(|key| key == api_key)
- .unwrap_or(false);
+ let api_key_valid = x_api_key_header.map(|key| key == api_key).unwrap_or(false);
assert!(!auth_valid && !api_key_valid);
}
@@ -248,9 +237,7 @@ mod tests {
.map(|token| token == api_key)
.unwrap_or(false);
- let api_key_valid = x_api_key_header
- .map(|key| key == api_key)
- .unwrap_or(false);
+ let api_key_valid = x_api_key_header.map(|key| key == api_key).unwrap_or(false);
assert!(!auth_valid && !api_key_valid);
}
@@ -267,9 +254,7 @@ mod tests {
.map(|token| token == api_key)
.unwrap_or(false);
- let api_key_valid = x_api_key_header
- .map(|key| key == api_key)
- .unwrap_or(false);
+ let api_key_valid = x_api_key_header.map(|key| key == api_key).unwrap_or(false);
// Should pass if either is valid
assert!(auth_valid || api_key_valid);
diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rs
index e536299e1..f3274855c 100644
--- a/src-tauri/src/core/setup.rs
+++ b/src-tauri/src/core/setup.rs
@@ -6,9 +6,7 @@ use std::{
sync::Arc,
};
use tar::Archive;
-use tauri::{
- App, Emitter, Manager, Runtime, Wry, WindowEvent
-};
+use tauri::{App, Emitter, Manager, Runtime, WindowEvent, Wry};
#[cfg(desktop)]
use tauri::{
@@ -17,9 +15,9 @@ use tauri::{
};
use tauri_plugin_store::Store;
+use crate::core::app::commands::get_jan_data_folder_path;
use crate::core::mcp::constants::DEFAULT_MCP_CONFIG;
use crate::core::mcp::helpers::add_server_config;
-use crate::core::app::commands::get_jan_data_folder_path;
use super::{
extensions::commands::get_jan_extensions_path, mcp::helpers::run_mcp_commands, state::AppState,
@@ -214,16 +212,13 @@ pub fn migrate_mcp_servers(
fn migrate_exa_to_http(app_handle: tauri::AppHandle) -> Result<(), String> {
let config_path = get_jan_data_folder_path(app_handle).join("mcp_config.json");
- let config_str = fs::read_to_string(&config_path)
- .map_err(|e| format!("Failed to read MCP config: {e}"))?;
+ let config_str =
+ fs::read_to_string(&config_path).map_err(|e| format!("Failed to read MCP config: {e}"))?;
let mut config: serde_json::Value = serde_json::from_str(&config_str)
.map_err(|e| format!("Failed to parse MCP config: {e}"))?;
- if let Some(servers) = config
- .get_mut("mcpServers")
- .and_then(|s| s.as_object_mut())
- {
+ if let Some(servers) = config.get_mut("mcpServers").and_then(|s| s.as_object_mut()) {
servers.insert(
"exa".to_string(),
serde_json::json!({
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index 6a9dac448..bea1ec56b 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -6,10 +6,11 @@ use rmcp::{
service::RunningService,
RoleClient, ServiceError,
};
-use tokio::sync::{Mutex, oneshot};
+use tokio::sync::{oneshot, Mutex};
/// Server handle type for managing the proxy server lifecycle
-pub type ServerHandle = tauri::async_runtime::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
+pub type ServerHandle =
+ tauri::async_runtime::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
pub enum RunningServiceEnum {
NoInit(RunningService<RoleClient, ()>),
diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rs
index 1860b2a49..253ba5671 100644
--- a/src-tauri/src/core/system/commands.rs
+++ b/src-tauri/src/core/system/commands.rs
@@ -26,7 +26,8 @@ pub fn factory_reset<R: Runtime>(app_handle: tauri::AppHandle<R>, state: State<'
log::info!("Factory reset, removing data folder: {data_folder:?}");
tauri::async_runtime::block_on(async {
- let _ = stop_mcp_servers_with_context(&app_handle, &state, ShutdownContext::FactoryReset).await;
+ let _ =
+ stop_mcp_servers_with_context(&app_handle, &state, ShutdownContext::FactoryReset).await;
{
let mut active_servers = state.mcp_active_servers.lock().await;
@@ -127,4 +128,3 @@ pub fn is_library_available(library: &str) -> bool {
}
}
}
-
diff --git a/src-tauri/src/core/threads/db.rs b/src-tauri/src/core/threads/db.rs
index b888b94bb..c996fb576 100644
--- a/src-tauri/src/core/threads/db.rs
+++ b/src-tauri/src/core/threads/db.rs
@@ -84,19 +84,15 @@ pub async fn init_database<R: Runtime>(app: &AppHandle<R>) -> Result<(), String>
.map_err(|e| format!("Failed to create messages table: {}", e))?;
// Create indexes
- sqlx::query(
- "CREATE INDEX IF NOT EXISTS idx_messages_thread_id ON messages(thread_id);",
- )
- .execute(&pool)
- .await
- .map_err(|e| format!("Failed to create thread_id index: {}", e))?;
+ sqlx::query("CREATE INDEX IF NOT EXISTS idx_messages_thread_id ON messages(thread_id);")
+ .execute(&pool)
+ .await
+ .map_err(|e| format!("Failed to create thread_id index: {}", e))?;
- sqlx::query(
- "CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);",
- )
- .execute(&pool)
- .await
- .map_err(|e| format!("Failed to create created_at index: {}", e))?;
+ sqlx::query("CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);")
+ .execute(&pool)
+ .await
+ .map_err(|e| format!("Failed to create created_at index: {}", e))?;
// Store pool globally
DB_POOL
@@ -111,9 +107,7 @@ pub async fn init_database<R: Runtime>(app: &AppHandle<R>) -> Result<(), String>
/// Get database pool
async fn get_pool() -> Result<SqlitePool, String> {
- let pool_mutex = DB_POOL
- .get()
- .ok_or("Database not initialized")?;
+ let pool_mutex = DB_POOL.get().ok_or("Database not initialized")?;
let pool_guard = pool_mutex.lock().await;
pool_guard
@@ -122,9 +116,7 @@ async fn get_pool() -> Result<SqlitePool, String> {
}
/// List all threads from database
-pub async fn db_list_threads<R: Runtime>(
- _app_handle: AppHandle<R>,
-) -> Result<Vec<Value>, String> {
+pub async fn db_list_threads<R: Runtime>(_app_handle: AppHandle<R>) -> Result<Vec<Value>, String> {
let pool = get_pool().await?;
let rows = sqlx::query("SELECT data FROM threads ORDER BY updated_at DESC")
@@ -215,13 +207,12 @@ pub async fn db_list_messages<R: Runtime>(
) -> Result<Vec<Value>, String> {
let pool = get_pool().await?;
- let rows = sqlx::query(
- "SELECT data FROM messages WHERE thread_id = ?1 ORDER BY created_at ASC",
- )
- .bind(thread_id)
- .fetch_all(&pool)
- .await
- .map_err(|e| format!("Failed to list messages: {}", e))?;
+ let rows =
+ sqlx::query("SELECT data FROM messages WHERE thread_id = ?1 ORDER BY created_at ASC")
+ .bind(thread_id)
+ .fetch_all(&pool)
+ .await
+ .map_err(|e| format!("Failed to list messages: {}", e))?;
let messages: Result<Vec<Value>, _> = rows
.iter()
diff --git a/src-tauri/src/core/threads/helpers.rs b/src-tauri/src/core/threads/helpers.rs
index 1710c5767..75eb7d69f 100644
--- a/src-tauri/src/core/threads/helpers.rs
+++ b/src-tauri/src/core/threads/helpers.rs
@@ -3,9 +3,9 @@ use std::io::{BufRead, BufReader, Write};
use tauri::Runtime;
// For async file write serialization
-use std::sync::OnceLock;
use std::collections::HashMap;
use std::sync::Arc;
+use std::sync::OnceLock;
use tokio::sync::Mutex;
use super::utils::{get_messages_path, get_thread_metadata_path};
diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rs
index 4a8ccada8..17dfb580e 100644
--- a/src-tauri/src/core/threads/tests.rs
+++ b/src-tauri/src/core/threads/tests.rs
@@ -1,4 +1,3 @@
-
use super::commands::*;
use super::helpers::should_use_sqlite;
use crate::core::app::commands::get_jan_data_folder_path;
@@ -108,7 +107,10 @@ async fn test_create_and_list_messages() {
let messages = list_messages(app.handle().clone(), thread_id.clone())
.await
.unwrap();
- assert!(!messages.is_empty(), "Expected at least one message, but got none. Thread ID: {thread_id}");
+ assert!(
+ !messages.is_empty(),
+ "Expected at least one message, but got none. Thread ID: {thread_id}"
+ );
assert_eq!(messages[0]["role"], "user");
// Clean up
@@ -166,12 +168,18 @@ fn test_should_use_sqlite_platform_detection() {
#[cfg(any(target_os = "android", target_os = "ios"))]
{
- assert!(should_use_sqlite(), "should_use_sqlite should return true on mobile platforms");
+ assert!(
+ should_use_sqlite(),
+ "should_use_sqlite should return true on mobile platforms"
+ );
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{
- assert!(!should_use_sqlite(), "should_use_sqlite should return false on desktop platforms");
+ assert!(
+ !should_use_sqlite(),
+ "should_use_sqlite should return false on desktop platforms"
+ );
}
}
@@ -200,7 +208,10 @@ async fn test_desktop_storage_backend() {
// Verify we can retrieve the thread (which proves file storage works)
let threads = list_threads(app.handle().clone()).await.unwrap();
let found = threads.iter().any(|t| t["id"] == thread_id);
- assert!(found, "Thread should be retrievable from file-based storage");
+ assert!(
+ found,
+ "Thread should be retrievable from file-based storage"
+ );
// Create a message
let message = json!({
@@ -220,7 +231,11 @@ async fn test_desktop_storage_backend() {
let messages = list_messages(app.handle().clone(), thread_id.clone())
.await
.unwrap();
- assert_eq!(messages.len(), 1, "Message should be retrievable from file-based storage");
+ assert_eq!(
+ messages.len(),
+ 1,
+ "Message should be retrievable from file-based storage"
+ );
// Clean up - get the actual data directory used by the app
use super::utils::get_data_dir;
@@ -347,9 +362,12 @@ async fn test_modify_thread_assistant() {
let (app, data_dir) = mock_app_with_temp_data_dir();
let app_handle = app.handle().clone();
- let created = create_thread(app_handle.clone(), create_test_thread("Assistant Mod Thread"))
- .await
- .unwrap();
+ let created = create_thread(
+ app_handle.clone(),
+ create_test_thread("Assistant Mod Thread"),
+ )
+ .await
+ .unwrap();
let thread_id = created["id"].as_str().unwrap();
let assistant = json!({
@@ -365,9 +383,13 @@ async fn test_modify_thread_assistant() {
let mut modified_assistant = assistant;
modified_assistant["assistant_name"] = json!("Modified Assistant");
- modify_thread_assistant(app_handle.clone(), thread_id.to_string(), modified_assistant)
- .await
- .unwrap();
+ modify_thread_assistant(
+ app_handle.clone(),
+ thread_id.to_string(),
+ modified_assistant,
+ )
+ .await
+ .unwrap();
let retrieved = get_thread_assistant(app_handle, thread_id.to_string())
.await
@@ -384,9 +406,23 @@ async fn test_thread_not_found_errors() {
let fake_thread_id = "non-existent-thread-id".to_string();
let assistant = json!({"id": "assistant-1", "assistant_name": "Test Assistant"});
- assert!(get_thread_assistant(app_handle.clone(), fake_thread_id.clone()).await.is_err());
- assert!(create_thread_assistant(app_handle.clone(), fake_thread_id.clone(), assistant.clone()).await.is_err());
- assert!(modify_thread_assistant(app_handle, fake_thread_id, assistant).await.is_err());
+ assert!(
+ get_thread_assistant(app_handle.clone(), fake_thread_id.clone())
+ .await
+ .is_err()
+ );
+ assert!(create_thread_assistant(
+ app_handle.clone(),
+ fake_thread_id.clone(),
+ assistant.clone()
+ )
+ .await
+ .is_err());
+ assert!(
+ modify_thread_assistant(app_handle, fake_thread_id, assistant)
+ .await
+ .is_err()
+ );
let _ = fs::remove_dir_all(data_dir);
}
@@ -430,7 +466,9 @@ async fn test_concurrent_message_operations() {
.collect();
let results = future::join_all(handles).await;
- assert!(results.iter().all(|r| r.is_ok() && r.as_ref().unwrap().is_ok()));
+ assert!(results
+ .iter()
+ .all(|r| r.is_ok() && r.as_ref().unwrap().is_ok()));
let messages = list_messages(app_handle, thread_id).await.unwrap();
assert_eq!(messages.len(), 5);
@@ -451,12 +489,17 @@ async fn test_empty_message_list() {
let (app, data_dir) = mock_app_with_temp_data_dir();
let app_handle = app.handle().clone();
- let created = create_thread(app_handle.clone(), create_test_thread("Empty Messages Test"))
- .await
- .unwrap();
+ let created = create_thread(
+ app_handle.clone(),
+ create_test_thread("Empty Messages Test"),
+ )
+ .await
+ .unwrap();
let thread_id = created["id"].as_str().unwrap();
- let messages = list_messages(app_handle, thread_id.to_string()).await.unwrap();
+ let messages = list_messages(app_handle, thread_id.to_string())
+ .await
+ .unwrap();
assert_eq!(messages.len(), 0);
let _ = fs::remove_dir_all(data_dir);
diff --git a/src-tauri/src/core/updater/commands.rs b/src-tauri/src/core/updater/commands.rs
index 5fbec82df..017d9d10e 100644
--- a/src-tauri/src/core/updater/commands.rs
+++ b/src-tauri/src/core/updater/commands.rs
@@ -1,6 +1,6 @@
/**
* Tauri commands for custom updater with HMAC request signing
- *
+ *
* Convention: First endpoint in tauri.conf.json uses HMAC signing, rest are fallbacks
*/
use super::custom_updater::{CustomUpdater, UpdateInfo};
@@ -80,4 +80,3 @@ pub fn is_update_available(current_version: String, latest_version: String) -> b
};
updater.is_update_available(&current_version, &latest_version)
}
-
diff --git a/src-tauri/src/core/updater/custom_updater.rs b/src-tauri/src/core/updater/custom_updater.rs
index 5c3ccf914..62b40b9fb 100644
--- a/src-tauri/src/core/updater/custom_updater.rs
+++ b/src-tauri/src/core/updater/custom_updater.rs
@@ -1,11 +1,11 @@
/**
* Custom Updater for Jan with HMAC request signing
- *
+ *
* This module provides a custom update checker that:
* 1. Reads endpoints from tauri.conf.json (plugins.updater.endpoints)
* 2. First endpoint is treated as PRIMARY - uses HMAC request signing
* 3. Remaining endpoints are FALLBACK - no signing needed
- *
+ *
* Convention: The first endpoint in the list should be the signed endpoint
* (e.g., https://apps.jan.ai/update-check)
*/
@@ -189,7 +189,11 @@ impl CustomUpdater {
}
/// Check endpoint without signing (for fallback endpoints)
- async fn check_without_signing(&self, endpoint: &str, app_version: &str) -> Result<UpdateInfo, UpdateError> {
+ async fn check_without_signing(
+ &self,
+ endpoint: &str,
+ app_version: &str,
+ ) -> Result<UpdateInfo, UpdateError> {
let response = self
.client
.get(endpoint)
@@ -220,10 +224,7 @@ impl CustomUpdater {
let current = current.trim_start_matches('v');
let latest = latest.trim_start_matches('v');
- let current_parts: Vec<u32> = current
- .split('.')
- .filter_map(|s| s.parse().ok())
- .collect();
+ let current_parts: Vec<u32> = current.split('.').filter_map(|s| s.parse().ok()).collect();
let latest_parts: Vec<u32> = latest.split('.').filter_map(|s| s.parse().ok()).collect();
for i in 0..std::cmp::max(current_parts.len(), latest_parts.len()) {
@@ -263,4 +264,3 @@ mod tests {
assert!(updater.is_update_available("v1.0.0", "v1.0.1"));
}
}
-
diff --git a/src-tauri/src/core/updater/hmac_client.rs b/src-tauri/src/core/updater/hmac_client.rs
index 35d50153c..180d5cd6b 100644
--- a/src-tauri/src/core/updater/hmac_client.rs
+++ b/src-tauri/src/core/updater/hmac_client.rs
@@ -43,7 +43,12 @@ pub fn get_timestamp() -> String {
/// Generate HMAC-SHA256 signature for request verification
/// Message format: "{nonce_seed}:{timestamp}:{nonce}"
-pub fn generate_signature(secret_key: &str, nonce_seed: &str, timestamp: &str, nonce: &str) -> String {
+pub fn generate_signature(
+ secret_key: &str,
+ nonce_seed: &str,
+ timestamp: &str,
+ nonce: &str,
+) -> String {
let message = format!("{}:{}:{}", nonce_seed, timestamp, nonce);
let mut mac =
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index cc17eb1d8..997fe3070 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -17,7 +17,7 @@ use tokio::sync::Mutex;
tauri::mobile_entry_point
)]
pub fn run() {
- let mut builder = tauri::Builder::default();
+ let mut builder = tauri::Builder::default().plugin(tauri_plugin_dialog::init());
#[cfg(desktop)]
{
builder = builder.plugin(tauri_plugin_single_instance::init(|_app, argv, _cwd| {
@@ -62,7 +62,6 @@ pub fn run() {
core::filesystem::commands::write_yaml,
core::filesystem::commands::read_yaml,
core::filesystem::commands::decompress,
- core::filesystem::commands::open_dialog,
core::filesystem::commands::save_dialog,
// App configuration commands
core::app::commands::get_app_configurations,
@@ -135,7 +134,6 @@ pub fn run() {
core::filesystem::commands::write_yaml,
core::filesystem::commands::read_yaml,
core::filesystem::commands::decompress,
- core::filesystem::commands::open_dialog,
core::filesystem::commands::save_dialog,
// App configuration commands
core::app::commands::get_app_configurations,
diff --git a/web-app/package.json b/web-app/package.json
index a480e92b2..3940bb85e 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -52,6 +52,7 @@
"@tanstack/react-virtual": "3.13.12",
"@tauri-apps/api": "2.8.0",
"@tauri-apps/plugin-deep-link": "2.4.3",
+ "@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-http": "2.5.0",
"@tauri-apps/plugin-opener": "2.5.2",
"@tauri-apps/plugin-os": "2.2.1",
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 27a79f46f..b16dcf4bf 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -789,7 +789,7 @@ const ChatInput = ({
}
} catch (e) {
console.error('Failed to attach documents:', e)
- const desc = e instanceof Error ? e.message : String(e)
+ const desc = e instanceof Error ? e.message : JSON.stringify(e)
toast.error('Failed to attach documents', { description: desc })
}
}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index cc1c5faa3..139627547 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -314,7 +314,7 @@ export const MessageItem = memo(
{part.state === 'output-error' && (
<ToolOutput
output={undefined}
- errorText={part.error || 'Tool execution failed'}
+ errorText={part.error || part.errorText || 'Tool execution failed'}
resolver={(input) => Promise.resolve(input)}
/>
)}
diff --git a/web-app/src/containers/ProjectFiles.tsx b/web-app/src/containers/ProjectFiles.tsx
new file mode 100644
index 000000000..ccff25417
--- /dev/null
+++ b/web-app/src/containers/ProjectFiles.tsx
@@ -0,0 +1,365 @@
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { FileText, FilePlusIcon, Trash2 } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip'
+import { cn } from '@/lib/utils'
+import { toast } from 'sonner'
+import { useServiceHub } from '@/hooks/useServiceHub'
+import { createDocumentAttachment, type Attachment } from '@/types/attachment'
+import { useAttachments } from '@/hooks/useAttachments'
+import { ExtensionTypeEnum, FileStat, VectorDBExtension } from '@janhq/core'
+import { ExtensionManager } from '@/lib/extension'
+import { IconLoader2, IconPaperclip } from '@tabler/icons-react'
+
+type ProjectFilesProps = {
+ projectId: string
+ lng: string
+}
+
+type ProjectFile = {
+ id: string
+ name?: string
+ path?: string
+ type?: string
+ size?: number
+ chunk_count: number
+}
+
+function formatBytes(bytes?: number): string {
+ if (!bytes || bytes <= 0) return ''
+ const units = ['B', 'KB', 'MB', 'GB']
+ let i = 0
+ let val = bytes
+ while (val >= 1024 && i < units.length - 1) {
+ val /= 1024
+ i++
+ }
+ return `${val.toFixed(i === 0 ? 0 : 1)} ${units[i]}`
+}
+
+const SUPPORTED_EXTENSIONS = [
+ 'pdf',
+ 'docx',
+ 'txt',
+ 'md',
+ 'csv',
+ 'xlsx',
+ 'xls',
+ 'ods',
+ 'pptx',
+ 'html',
+ 'htm',
+]
+
+async function getFilesFromPaths(paths: string[]): Promise<string[]> {
+ const files: string[] = []
+ const { fs } = await import('@janhq/core')
+
+ for (const path of paths) {
+ try {
+ const stat: FileStat | undefined = await fs.fileStat(path)
+ if (stat?.isDirectory) {
+ // Recursively get files from directory
+ const dirFiles = await getFilesFromDirectory(path, fs)
+ files.push(...dirFiles)
+ } else {
+ files.push(path)
+ }
+ } catch (e) {
+ console.warn(`Failed to get stat for ${path}:`, e)
+ files.push(path)
+ }
+ }
+ return files
+}
+
+async function getFilesFromDirectory(
+ dirPath: string,
+ fs: typeof import('@janhq/core').fs
+): Promise<string[]> {
+ const files: string[] = []
+ try {
+ const entries = await fs.readdirSync(dirPath)
+ for (const entry of entries) {
+ console.log('Reading entry:', entry)
+ const stat = await fs.fileStat(entry)
+ if (stat?.isDirectory) {
+ const nestedFiles = await getFilesFromDirectory(entry, fs)
+ files.push(...nestedFiles)
+ } else if (!stat?.isDirectory) {
+ const ext = entry.split('.').pop()?.toLowerCase()
+ if (ext && SUPPORTED_EXTENSIONS.includes(ext)) {
+ files.push(entry)
+ }
+ }
+ }
+ } catch (e) {
+ console.warn(`Failed to read directory ${dirPath}:`, e)
+ }
+ return files
+}
+
+export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {
+ const { t } = useTranslation(lng)
+ const serviceHub = useServiceHub()
+ const attachmentsEnabled = useAttachments((s) => s.enabled)
+ const maxFileSizeMB = useAttachments((s) => s.maxFileSizeMB)
+
+ const [files, setFiles] = useState<ProjectFile[]>([])
+ const [loading, setLoading] = useState(true)
+ const [uploading, setUploading] = useState(false)
+
+ const loadProjectFiles = useCallback(async () => {
+ setLoading(true)
+ try {
+ const ext = ExtensionManager.getInstance().get<VectorDBExtension>(
+ ExtensionTypeEnum.VectorDB
+ )
+ if (ext?.listAttachmentsForProject) {
+ const projectFiles = await ext.listAttachmentsForProject(projectId)
+ setFiles(projectFiles)
+ } else {
+ setFiles([])
+ }
+ } catch (error) {
+ setFiles([])
+ } finally {
+ setLoading(false)
+ }
+ }, [projectId])
+
+ useEffect(() => {
+ loadProjectFiles()
+ }, [loadProjectFiles])
+
+ const handleUpload = async () => {
+ if (!attachmentsEnabled) {
+ toast.info(
+ t('common:toast.attachmentsDisabledInfo.title') ??
+ 'Attachments are disabled in Settings'
+ )
+ return
+ }
+
+ try {
+ const selection = await serviceHub.dialog().open({
+ multiple: true,
+ directory: false,
+ filters: [
+ {
+ name: 'Documents',
+ extensions: SUPPORTED_EXTENSIONS,
+ },
+ ],
+ })
+ if (!selection) return
+ const paths = Array.isArray(selection) ? selection : [selection]
+ if (!paths.length) return
+
+ // Get files from paths (recursively for directories)
+ const filePaths = await getFilesFromPaths(paths)
+
+ const maxFileSizeBytes =
+ typeof maxFileSizeMB === 'number' && maxFileSizeMB > 0
+ ? maxFileSizeMB * 1024 * 1024
+ : undefined
+
+ const preparedAttachments: Attachment[] = []
+ for (const p of filePaths) {
+ const name = p.split(/[\\/]/).pop() || p
+ const fileType = name.split('.').pop()?.toLowerCase()
+ let size: number | undefined = undefined
+ try {
+ const stat = await import('@janhq/core').then((m) => m.fs.fileStat(p))
+ size = stat?.size ? Number(stat.size) : undefined
+ } catch (e) {
+ console.warn('Failed to read file size for', p, e)
+ }
+
+ if (maxFileSizeBytes !== undefined && size && size > maxFileSizeBytes) {
+ toast.error(t('common:errors.fileTooLarge') ?? 'File too large', {
+ description: t('common:errors.fileTooLargeDescription', {
+ fileName: name,
+ maxFileSizeMB,
+ }),
+ })
+ continue
+ }
+
+ preparedAttachments.push(
+ createDocumentAttachment({
+ name,
+ path: p,
+ fileType,
+ size,
+ })
+ )
+ }
+
+ // Filter duplicates
+ const existingPaths = new Set(
+ files.filter((f) => f.path).map((f) => f.path)
+ )
+ const duplicates: string[] = []
+ const newAttachments = preparedAttachments.filter((att) => {
+ if (existingPaths.has(att.path)) {
+ duplicates.push(att.name)
+ return false
+ }
+ return true
+ })
+
+ if (duplicates.length > 0) {
+ toast.warning(
+ t('common:toast.fileAlreadyExists.title') ?? 'File already attached',
+ {
+ description: duplicates.join(', '),
+ }
+ )
+ }
+
+ if (newAttachments.length === 0) return
+
+ setUploading(true)
+ try {
+ for (const att of newAttachments) {
+ const result = await serviceHub
+ .uploads()
+ .ingestFileAttachmentForProject(projectId, att)
+ if (!result.id) {
+ throw new Error('Failed to ingest file')
+ }
+ }
+ toast.success(
+ t('common:toast.fileUploaded.title') ?? 'File uploaded successfully'
+ )
+ await loadProjectFiles()
+ } catch (error) {
+ console.error('Failed to upload file:', error)
+ toast.error(
+ t('common:toast.uploadFailed.title') ?? 'Failed to upload file',
+ {
+ description:
+ error instanceof Error ? error.message : JSON.stringify(error),
+ }
+ )
+ } finally {
+ setUploading(false)
+ }
+ } catch (error) {
+ console.error('Failed to open file dialog:', error)
+ const desc =
+ error instanceof Error ? error.message : JSON.stringify(error)
+ toast.error(
+ t('common:toast.uploadFailed.title') ?? 'Failed to upload file',
+ {
+ description: desc,
+ }
+ )
+ }
+ }
+
+ const handleDeleteFile = async (fileId: string) => {
+ try {
+ const ext = ExtensionManager.getInstance().get<VectorDBExtension>(
+ ExtensionTypeEnum.VectorDB
+ )
+ if (ext?.deleteFileForProject) {
+ await ext.deleteFileForProject(projectId, fileId)
+ toast.success(
+ t('common:toast.fileDeleted.title') ?? 'File deleted successfully'
+ )
+ await loadProjectFiles()
+ }
+ } catch (error) {
+ console.error('Failed to delete file:', error)
+ toast.error(
+ t('common:toast.deleteFailed.title') ?? 'Failed to delete file',
+ {
+ description:
+ error instanceof Error ? error.message : JSON.stringify(error),
+ }
+ )
+ }
+ }
+
+ const isEmpty = !loading && files.length === 0
+
+ return (
+ <div className="p-4">
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium">{t('common:projects.files')}</h3>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={handleUpload}
+ disabled={uploading}
+ >
+ {uploading ? (
+ <IconLoader2 className="size-4 animate-spin" />
+ ) : (
+ <FilePlusIcon className="size-4" />
+ )}
+ </Button>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center justify-center py-8">
+ <IconLoader2 className="size-6 animate-spin text-muted-foreground" />
+ </div>
+ ) : isEmpty ? (
+ <div className="flex flex-col items-center justify-center py-8 px-4 rounded-lg bg-secondary/30 border border-dashed border-border">
+ <FileText className="size-8 text-muted-foreground/50 mb-3" />
+ <p className="text-sm text-muted-foreground text-center">
+ {t('common:projects.filesDescription')}
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2 max-h-60 overflow-y-auto">
+ {files.map((file) => (
+ <div
+ key={file.id}
+ className={cn(
+ 'flex items-center gap-2 p-2 rounded-lg',
+ 'bg-secondary/30 border border-border/50',
+ 'group hover:bg-secondary/50 transition-colors'
+ )}
+ >
+ <div className="flex-shrink-0">
+ <IconPaperclip className="size-5 text-muted-foreground" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <p className="text-sm font-medium truncate">{file.name}</p>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="text-xs">{file.name}</p>
+ </TooltipContent>
+ </Tooltip>
+ <p className="text-xs text-muted-foreground">
+ {file.size ? formatBytes(file.size) : ''}
+ {file.chunk_count > 0 &&
+ ` · ${t('common:files.chunksCount', { count: file.chunk_count })}`}
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="opacity-0 group-hover:opacity-100 transition-opacity"
+ onClick={() => handleDeleteFile(file.id)}
+ >
+ <Trash2 className="size-3.5 text-muted-foreground hover:text-destructive" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.ts
index 649271637..f0b52061e 100644
--- a/web-app/src/lib/attachmentProcessing.ts
+++ b/web-app/src/lib/attachmentProcessing.ts
@@ -7,6 +7,7 @@ type AttachmentProcessingStatus = 'processing' | 'done' | 'error' | 'clear_all'
type AttachmentProcessingOptions = {
attachments: Attachment[]
threadId: string
+ projectId?: string
serviceHub: ServiceHub
selectedProvider?: string
contextThreshold?: number
@@ -73,6 +74,7 @@ export const processAttachmentsForSend = async (
const {
attachments,
threadId,
+ projectId,
serviceHub,
contextThreshold,
estimateTokens,
@@ -147,7 +149,12 @@ export const processAttachmentsForSend = async (
targetPreference === 'inline' ? 'inline' : 'embeddings'
let parsedContent: string | undefined
- const canInline = targetPreference !== 'embeddings' && !!doc.path
+ // Project files always use embeddings, never inline
+ if (projectId) {
+ targetMode = 'embeddings'
+ }
+
+ const canInline = !projectId && targetPreference !== 'embeddings' && !!doc.path
if (canInline) {
try {
@@ -162,10 +169,12 @@ export const processAttachmentsForSend = async (
if (targetPreference === 'auto') {
// Check if user made a per-file choice for this document
const userChoice = perFileChoices?.get(doc.path || '')
- targetMode = userChoice ?? autoFallbackMode ?? 'embeddings'
+ // Project files always use embeddings
+ const effectiveMode = projectId ? 'embeddings' : (userChoice ?? autoFallbackMode ?? 'embeddings')
+ targetMode = effectiveMode
- // Only do auto-detection if no user choice was made
- if (!userChoice && parsedContent && estimateTokens) {
+ // Only do auto-detection if no user choice was made and not project file
+ if (!projectId && !userChoice && parsedContent && estimateTokens) {
const estimatedTokens = await estimateTokens(parsedContent)
const tokenCount =
typeof estimatedTokens === 'number' &&
@@ -185,11 +194,11 @@ export const processAttachmentsForSend = async (
`Attachment ${doc.name}: token estimate unavailable or non-positive; defaulting to ${targetMode}`
)
}
- } else if (!userChoice && !parsedContent) {
+ } else if (!projectId && !userChoice && !parsedContent) {
console.debug(
`Attachment ${doc.name}: parsed content unavailable for token estimation; defaulting to ${targetMode}`
)
- } else if (!userChoice) {
+ } else if (!projectId && !userChoice) {
console.debug(
`Attachment ${doc.name}: token estimator unavailable; defaulting to ${targetMode}`
)
@@ -197,7 +206,8 @@ export const processAttachmentsForSend = async (
} else if (targetPreference === 'prompt') {
// Check if user made a per-file choice for this document
const userChoice = perFileChoices?.get(doc.path || '')
- targetMode = userChoice ?? autoFallbackMode ?? 'embeddings'
+ // Project files always use embeddings
+ targetMode = projectId ? 'embeddings' : (userChoice ?? autoFallbackMode ?? 'embeddings')
}
if (targetMode === 'inline' && parsedContent) {
@@ -221,7 +231,9 @@ export const processAttachmentsForSend = async (
// Default: ingest as embeddings
notifyUpdate(doc.name, 'processing')
- const res = await serviceHub.uploads().ingestFileAttachment(threadId, doc)
+ const res = projectId
+ ? await serviceHub.uploads().ingestFileAttachmentForProject(projectId, doc)
+ : await serviceHub.uploads().ingestFileAttachment(threadId, doc)
processedAttachments.push({
...doc,
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 15fcd0414..57a4817e1 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -401,6 +401,37 @@
"threadRemovedFromProject": {
"title": "Thread Removed",
"description": "Thread removed from \"{{projectName}}\" successfully"
+ },
+ "fileUploaded": {
+ "title": "File Uploaded",
+ "description": "File has been uploaded and indexed successfully"
+ },
+ "uploadFailed": {
+ "title": "Upload Failed",
+ "description": "Failed to upload file"
+ },
+ "fileDeleted": {
+ "title": "File Deleted",
+ "description": "File has been removed from the project"
+ },
+ "deleteFailed": {
+ "title": "Delete Failed",
+ "description": "Failed to delete file"
+ },
+ "fileAlreadyExists": {
+ "title": "File Already Exists",
+ "description": "File is already attached to this project"
+ },
+ "attachmentsDisabledInfo": {
+ "title": "Attachments Disabled",
+ "description": "Attachments are disabled in Settings"
}
+ },
+ "errors": {
+ "fileTooLarge": "File too large",
+ "fileTooLargeDescription": "{{fileName}} exceeds the {{maxFileSizeMB}}MB limit"
+ },
+ "files": {
+ "chunksCount": "{{count}} chunks"
}
}
diff --git a/web-app/src/routes/project/$projectId.tsx b/web-app/src/routes/project/$projectId.tsx
index aa3086c83..b330a0353 100644
--- a/web-app/src/routes/project/$projectId.tsx
+++ b/web-app/src/routes/project/$projectId.tsx
@@ -11,7 +11,8 @@ import HeaderPage from '@/containers/HeaderPage'
import ThreadList from '@/containers/ThreadList'
import { AvatarEmoji } from '@/containers/AvatarEmoji'
-import { FileText, FolderPenIcon, MessageCircle, MoreHorizontal, PencilIcon, Trash2 } from 'lucide-react'
+import { FolderPenIcon, MessageCircle, MoreHorizontal, PencilIcon, Trash2 } from 'lucide-react'
+import ProjectFiles from '@/containers/ProjectFiles'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import {
DropdownMenu,
@@ -30,7 +31,7 @@ export const Route = createFileRoute('/project/$projectId')({
})
function ProjectPageContent() {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
const { projectId } = useParams({ from: '/project/$projectId' })
const { getFolderById, updateFolder } = useThreadManagement()
const threads = useThreads((state) => state.threads)
@@ -158,17 +159,7 @@ function ProjectPageContent() {
</div>
{/* Files Section */}
- <div className="p-4">
- <div className="flex items-center justify-between mb-3">
- <h3 className="text-sm font-medium">{t('projects.files')}</h3>
- </div>
- <div className="flex flex-col items-center justify-center py-8 px-4 rounded-lg bg-secondary/30 border border-dashed border-border">
- <FileText className="size-8 text-muted-foreground/50 mb-3" />
- <p className="text-sm text-muted-foreground text-center">
- {t('projects.filesDescription')}
- </p>
- </div>
- </div>
+ <ProjectFiles projectId={projectId} lng={i18n.language} />
</div>
{/* Conversation Section */}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 0b920d3e2..d5167ab89 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -30,7 +30,12 @@ import {
extractContentPartsFromUIMessage,
} from '@/lib/messages'
import { newUserThreadContent } from '@/lib/completion'
-import { ThreadMessage, MessageStatus, ChatCompletionRole, ContentType } from '@janhq/core'
+import {
+ ThreadMessage,
+ MessageStatus,
+ ChatCompletionRole,
+ ContentType,
+} from '@janhq/core'
import { createImageAttachment } from '@/types/attachment'
import {
useChatAttachments,
@@ -45,6 +50,8 @@ import { Button } from '@/components/ui/button'
import { IconAlertCircle } from '@tabler/icons-react'
import { useToolApproval } from '@/hooks/useToolApproval'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
+import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'
+import { ExtensionManager } from '@/lib/extension'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -113,6 +120,12 @@ function ThreadDetail() {
? renderInstructions(threadAssistant.instructions)
: undefined
+ const threadRef = useRef(thread)
+
+ useEffect(() => {
+ threadRef.current = thread
+ }, [thread])
+
// Use the AI SDK chat hook
const {
messages: chatMessages,
@@ -178,6 +191,7 @@ function ThreadDetail() {
// Get cached tool names from store (initialized in useTools hook)
const ragToolNames = useAppState.getState().ragToolNames
const mcpToolNames = useAppState.getState().mcpToolNames
+ const projectId = threadRef.current?.metadata?.project?.id
// Process tool calls sequentially, requesting approval for each if needed
;(async () => {
@@ -210,10 +224,13 @@ function ThreadDetail() {
// Route to the appropriate service based on tool name
if (ragToolNames.has(toolName)) {
+
result = await serviceHub.rag().callTool({
toolName,
arguments: toolCall.input,
threadId,
+ projectId: projectId,
+ scope: projectId ? 'project' : 'thread',
})
} else if (mcpToolNames.has(toolName)) {
result = await serviceHub.mcp().callTool({
@@ -249,7 +266,7 @@ function ThreadDetail() {
state: 'output-error',
tool: toolCall.toolName,
toolCallId: toolCall.toolCallId,
- errorText: `Error: ${(error as Error).message}`,
+ errorText: `Error: ${JSON.stringify(error)}`,
})
}
}
@@ -280,18 +297,42 @@ function ThreadDetail() {
// Update RAG tools availability when documents, model, or tool availability changes
useEffect(() => {
- const hasDocuments = Boolean(thread?.metadata?.hasDocuments)
- const ragFeatureAvailable = Boolean(useAttachments.getState().enabled)
- const modelSupportsTools =
- selectedModel?.capabilities?.includes('tools') ?? false
-
- updateRagToolsAvailability(
- hasDocuments,
- modelSupportsTools,
- ragFeatureAvailable
- )
+ const checkDocumentsAvailability = async () => {
+ let hasThreadDocuments = Boolean(thread?.metadata?.hasDocuments)
+ let hasProjectDocuments = false
+
+ // Check if thread belongs to a project and if that project has files
+ const projectId = thread?.metadata?.project?.id
+ if (projectId) {
+ try {
+ const ext = ExtensionManager.getInstance().get<VectorDBExtension>(
+ ExtensionTypeEnum.VectorDB
+ )
+ if (ext?.listAttachmentsForProject) {
+ const projectFiles = await ext.listAttachmentsForProject(projectId)
+ hasProjectDocuments = projectFiles.length > 0
+ }
+ } catch (error) {
+ console.warn('Failed to check project files:', error)
+ }
+ }
+
+ const hasDocuments = hasThreadDocuments || hasProjectDocuments
+ const ragFeatureAvailable = Boolean(useAttachments.getState().enabled)
+ const modelSupportsTools =
+ selectedModel?.capabilities?.includes('tools') ?? false
+
+ updateRagToolsAvailability(
+ hasDocuments,
+ modelSupportsTools,
+ ragFeatureAvailable
+ )
+ }
+
+ checkDocumentsAvailability()
}, [
thread?.metadata?.hasDocuments,
+ thread?.metadata?.project?.id,
selectedModel?.capabilities,
updateRagToolsAvailability,
disabledTools, // Re-run when tools are enabled/disabled
@@ -403,12 +444,14 @@ function ThreadDetail() {
// Process attachments (ingest images, parse/index documents)
let processedAttachments = combinedAttachments
+ const projectId = thread?.metadata?.project?.id
if (combinedAttachments.length > 0) {
try {
const parsePreference = useAttachments.getState().parseMode
const result = await processAttachmentsForSend({
attachments: combinedAttachments,
threadId,
+ projectId,
serviceHub,
selectedProvider,
parsePreference,
@@ -471,6 +514,7 @@ function ThreadDetail() {
[
sendMessage,
threadId,
+ thread,
addMessage,
getAttachments,
attachmentsKey,
@@ -570,7 +614,6 @@ function ThreadDetail() {
// Handle edit message - updates the message and regenerates from it
const handleEditMessage = useCallback(
(messageId: string, newText: string) => {
-
const currentLocalMessages = useMessages.getState().getMessages(threadId)
const messageIndex = currentLocalMessages.findIndex(
(m) => m.id === messageId
@@ -605,7 +648,7 @@ function ThreadDetail() {
setChatMessages(updatedChatMessages)
// Only regenerate if the edited message is from the user
- if(updatedMessage.role === 'assistant') return
+ if (updatedMessage.role === 'assistant') return
// Delete all messages after this one and regenerate
const messagesToDelete = currentLocalMessages.slice(messageIndex + 1)
@@ -686,7 +729,13 @@ function ThreadDetail() {
setTimeout(() => {
handleRegenerate()
}, 1000)
- }, [selectedModel, selectedProvider, getProviderByName, serviceHub, handleRegenerate])
+ }, [
+ selectedModel,
+ selectedProvider,
+ getProviderByName,
+ serviceHub,
+ handleRegenerate,
+ ])
const threadModel = useMemo(() => thread?.model, [thread])
@@ -704,9 +753,7 @@ function ThreadDetail() {
<div className="flex-1 relative">
<Conversation className="absolute inset-0 text-start">
<ConversationContent
- className={cn(
- 'mx-auto w-full md:w-4/5 xl:w-4/6',
- )}
+ className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}
>
{chatMessages.map((message, index) => {
const isLastMessage = index === chatMessages.length - 1
diff --git a/web-app/src/services/dialog/tauri.ts b/web-app/src/services/dialog/tauri.ts
index 2e4ff4f43..51a26f956 100644
--- a/web-app/src/services/dialog/tauri.ts
+++ b/web-app/src/services/dialog/tauri.ts
@@ -3,6 +3,7 @@
*/
import { invoke } from '@tauri-apps/api/core'
+import { open } from '@tauri-apps/plugin-dialog'
import type { DialogOpenOptions } from './types'
import { DefaultDialogService } from './default'
@@ -19,8 +20,8 @@ export class TauriDialogService extends DefaultDialogService {
)
})
}
- const result = await invoke<string | string[] | null>('open_dialog', {
- options,
+ const result = await open({
+ ...options,
})
console.log('TauriDialogService: Dialog result:', result)
return result
diff --git a/web-app/src/services/rag/default.ts b/web-app/src/services/rag/default.ts
index 924f3dd4d..a576eaabf 100644
--- a/web-app/src/services/rag/default.ts
+++ b/web-app/src/services/rag/default.ts
@@ -5,7 +5,9 @@ import { ExtensionTypeEnum } from '@janhq/core'
export class DefaultRAGService implements RAGService {
async getTools(): Promise<MCPTool[]> {
- const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)
+ const ext = ExtensionManager.getInstance().get<RAGExtension>(
+ ExtensionTypeEnum.RAG
+ )
if (ext?.getTools) {
try {
return await ext.getTools()
@@ -16,29 +18,53 @@ export class DefaultRAGService implements RAGService {
return []
}
- async callTool(args: { toolName: string; arguments: Record<string, unknown>; threadId?: string }): Promise<MCPToolCallResult> {
- const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)
+ async callTool(args: {
+ toolName: string
+ arguments: Record<string, unknown>
+ threadId?: string
+ projectId?: string
+ scope: 'project' | 'thread'
+ }): Promise<MCPToolCallResult> {
+ const ext = ExtensionManager.getInstance().get<RAGExtension>(
+ ExtensionTypeEnum.RAG
+ )
if (!ext?.callTool) {
- return { error: 'RAG extension not available', content: [{ type: 'text', text: 'RAG extension not available' }] }
+ return {
+ error: 'RAG extension not available',
+ content: [{ type: 'text', text: 'RAG extension not available' }],
+ }
}
try {
- // Inject thread context when scope requires it
- type ToolCallArgs = Record<string, unknown> & { scope?: string; thread_id?: string }
+ // Inject context when scope requires it
+ type ToolCallArgs = Record<string, unknown> & {
+ scope?: string
+ thread_id?: string
+ project_id?: string
+ }
const a: ToolCallArgs = { ...(args.arguments as Record<string, unknown>) }
- if (!a.scope) a.scope = 'thread'
- if (a.scope === 'thread' && !a.thread_id) {
+ if (args.scope === 'thread' && !a.thread_id) {
a.thread_id = args.threadId
}
+ if (args.scope === 'project' && !a.project_id) {
+ a.project_id = args.projectId
+ a.thread_id = args.projectId
+ }
+ a.scope = args.scope
return await ext.callTool(args.toolName, a)
} catch (e) {
- const msg = e instanceof Error ? e.message : String(e)
- return { error: msg, content: [{ type: 'text', text: `RAG tool failed: ${msg}` }] }
+ const msg = e instanceof Error ? e.message : JSON.stringify(e)
+ return {
+ error: msg,
+ content: [{ type: 'text', text: `RAG tool failed: ${msg}` }],
+ }
}
}
async getToolNames(): Promise<string[]> {
try {
- const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)
+ const ext = ExtensionManager.getInstance().get<RAGExtension>(
+ ExtensionTypeEnum.RAG
+ )
if (ext?.getToolNames) return await ext.getToolNames()
// No fallback to full tool list; return empty to save bandwidth
return []
@@ -50,7 +76,9 @@ export class DefaultRAGService implements RAGService {
async parseDocument(path: string, type?: string): Promise<string> {
try {
- const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)
+ const ext = ExtensionManager.getInstance().get<RAGExtension>(
+ ExtensionTypeEnum.RAG
+ )
const parsed = await ext?.parseDocument?.(path, type)
return parsed ?? ''
} catch (e) {
diff --git a/web-app/src/services/rag/types.ts b/web-app/src/services/rag/types.ts
index 0fa4a8577..18c999a98 100644
--- a/web-app/src/services/rag/types.ts
+++ b/web-app/src/services/rag/types.ts
@@ -5,7 +5,13 @@ export interface RAGService {
// Return tools exposed by RAG-related extensions (e.g., retrieval, list_attachments)
getTools(): Promise<MCPTool[]>
// Execute a RAG tool call (retrieve, list_attachments)
- callTool(args: { toolName: string; arguments: object; threadId?: string }): Promise<MCPToolCallResult>
+ callTool(args: {
+ toolName: string
+ arguments: object
+ threadId?: string
+ projectId?: string
+ scope: 'project' | 'thread'
+ }): Promise<MCPToolCallResult>
// Convenience: return tool names for routing
getToolNames(): Promise<string[]>
// Parse a document to text for inline injection decisions
diff --git a/web-app/src/services/uploads/default.ts b/web-app/src/services/uploads/default.ts
index d1a9b2d3b..5e1ccaeab 100644
--- a/web-app/src/services/uploads/default.ts
+++ b/web-app/src/services/uploads/default.ts
@@ -29,4 +29,22 @@ export class DefaultUploadsService implements UploadsService {
}
throw new Error('Failed to resolve ingested attachment id')
}
+
+ async ingestFileAttachmentForProject(projectId: string, attachment: Attachment): Promise<UploadResult> {
+ if (attachment.type !== 'document') throw new Error('ingestFileAttachmentForProject: attachment is not document')
+ const ext = ExtensionManager.getInstance().get<RAGExtension>(ExtensionTypeEnum.RAG)
+ if (!ext?.ingestAttachmentsForProject) throw new Error('RAG extension does not support project-level ingestion')
+ const res: IngestAttachmentsResult = await ext.ingestAttachmentsForProject(projectId, [
+ { path: attachment.path!, name: attachment.name, type: attachment.fileType, size: attachment.size },
+ ])
+ const files = res.files
+ if (Array.isArray(files) && files[0]?.id) {
+ return {
+ id: files[0].id,
+ size: typeof files[0].size === 'number' ? Number(files[0].size) : undefined,
+ chunkCount: typeof files[0].chunk_count === 'number' ? Number(files[0].chunk_count) : undefined,
+ }
+ }
+ throw new Error('Failed to resolve ingested attachment id')
+ }
}
diff --git a/web-app/src/services/uploads/types.ts b/web-app/src/services/uploads/types.ts
index 4f36b8d51..90c089831 100644
--- a/web-app/src/services/uploads/types.ts
+++ b/web-app/src/services/uploads/types.ts
@@ -13,4 +13,7 @@ export interface UploadsService {
// Ingest a document attachment in the context of a thread
ingestFileAttachment(threadId: string, attachment: Attachment): Promise<UploadResult>
+
+ // Ingest a document attachment in the context of a project (shared across all threads)
+ ingestFileAttachmentForProject(projectId: string, attachment: Attachment): Promise<UploadResult>
}