Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: index source code files in project sources, knowledge bases and linked folders (#10395)

Harsha86108d841f09
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.py
index 003de624eb6..beca8d19c4b 100644
--- a/studio/backend/core/rag/config.py
+++ b/studio/backend/core/rag/config.py
@@ -41,13 +41,41 @@ CONVERSATION_FORCED_MIN_SCORE = float(os.environ.get("RAG_CONVERSATION_FORCED_MI
# Types parsers.parse handles; frontend and Rust parity tests read this literal.
SUPPORTED_UPLOAD_EXTS = {".pdf", ".txt", ".md", ".markdown", ".docx", ".html", ".htm"}
+# Source and config files, decoded like .txt; the chat's TEXT_ATTACHMENT_EXTENSIONS minus the above (parity test).
+SOURCE_TEXT_EXTS = frozenset(
+ """
+ .text .log .mdx .rst .adoc .asciidoc .org .textile .wiki .tex .latex .sty .cls .bib .rmd .qmd
+ .srt .vtt .sbv .ass .ssa .sub .lrc
+ .csv .tsv .psv .json .jsonl .ndjson .jsonc .json5 .geojson .har .avsc .xml .yaml .yml .toml .ini
+ .cfg .conf .cnf .env .properties .plist .edn .ron .cue .lock .mod .sum .reg .desktop .service
+ .po .pot .strings .resx .xliff .xlf .ics .vcf .eml .mbox .m3u8 .pls
+ .css .scss .sass .less .styl .svg .vue .svelte .astro .pug .jade .haml .slim .ejs .erb .hbs
+ .handlebars .mustache .njk .jinja .jinja2 .j2 .twig .liquid .cshtml .razor .aspx .jsp .tpl .qml
+ .js .jsx .mjs .cjs .ts .tsx .mts .cts .py .pyi .pyx .pxd .ipynb
+ .java .kt .kts .scala .groovy .gradle .sbt .clj .cljs .cljc
+ .c .h .cc .cpp .hpp .cxx .hxx .hh .ipp .inl .cu .cuh .rs .go .zig .odin .nim .nims .nimble .cr .d
+ .v .sv .svh .vhd .vhdl .asm .s
+ .cs .vb .vbs .fs .fsi .fsx .csproj .vbproj .fsproj .sln .props .targets
+ .m .mm .swift .applescript .metal
+ .rb .rake .gemspec .podspec .php .pl .pm .r .jl .lua .tcl .dart .hx .hs .lhs .ml .mli .ex .exs
+ .erl .hrl .rkt .scm .ss .lisp .lsp .cl .el .pas .pp .ada .adb .ads .cob .cbl .f .for .f90 .f95
+ .f03 .sas .awk .sed .m4 .sol .move .cairo .mojo .gd .sqf
+ .sh .bash .zsh .fish .ksh .csh .tcsh .nu .ps1 .psm1 .psd1 .bat .cmd
+ .sql .psql .plsql .hql .cql .graphql .gql .proto .thrift .capnp .prisma
+ .tf .tfvars .tfstate .hcl .nix .dhall .bicep .dockerfile .containerfile .makefile .mk .mak .cmake
+ .ninja .bzl .bazel .star .starlark .gn .gni .pro .pri .cabal .opam
+ .glsl .frag .vert .geom .comp .hlsl .wgsl .shader
+ .mmd .mermaid .puml .plantuml .dot .gv .feature .robot .http .rest .diff .patch
+ """.split()
+)
+_PARSEABLE_EXTS = SUPPORTED_UPLOAD_EXTS | SOURCE_TEXT_EXTS
# RAG_UPLOAD_EXTS (e.g. ".md,.markdown") can only narrow: a type without a parser would fail every ingest.
_requested_exts = {
"." + ext.strip().lstrip(".").lower()
for ext in os.environ.get("RAG_UPLOAD_EXTS", "").split(",")
if ext.strip().lstrip(".")
}
-UPLOAD_EXTS = (SUPPORTED_UPLOAD_EXTS & _requested_exts) or set(SUPPORTED_UPLOAD_EXTS)
+UPLOAD_EXTS = (_PARSEABLE_EXTS & _requested_exts) or set(_PARSEABLE_EXTS)
# 0 disables the cap; bounds parse + vision work at ingest.
MAX_UPLOAD_BYTES = int(os.environ.get("RAG_MAX_UPLOAD_BYTES", str(200 * 1024 * 1024)))
diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.py
index b09e218b970..e9bd35e1b10 100644
--- a/studio/backend/core/rag/folder_sync.py
+++ b/studio/backend/core/rag/folder_sync.py
@@ -55,6 +55,36 @@ _MAX_NAMED_FAILURES = 3
_MAX_WITHHELD_PATHS = 500
_JOB_EVENT_KEEPALIVE_S = 4.0
_SQLITE_INTEGER_MAX = (1 << 63) - 1
+# Dependency, VCS and cache trees would flood the index with third-party source.
+_IGNORE_SCAN_DIRS = frozenset(
+ {
+ ".git",
+ ".svn",
+ ".hg",
+ ".venv",
+ "venv",
+ "node_modules",
+ "bower_components",
+ "__pycache__",
+ ".pytest_cache",
+ ".mypy_cache",
+ }
+)
+_LOCKFILES = frozenset(
+ {"package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "pnpm-lock.yml"}
+)
+
+
+def _is_ignored_scan_dir(name: str, path: str) -> bool:
+ return name.lower() in _IGNORE_SCAN_DIRS or os.path.exists(os.path.join(path, "pyvenv.cfg"))
+
+
+def _is_ignored_scan_file(name: str) -> bool:
+ # .env and Terraform state hold plaintext secrets that retrieval would paste into prompts; lockfiles are noise.
+ lower = name.lower()
+ if lower == ".env" or lower.startswith(".env.") or lower.endswith(".env"):
+ return True
+ return lower.endswith((".lock", ".lockb", ".tfstate")) or lower in _LOCKFILES
class _SyncStopped(Exception):
@@ -1000,6 +1030,8 @@ def _scan(
if entry.is_symlink():
continue
if entry.is_dir(follow_symlinks = False):
+ if _is_ignored_scan_dir(entry.name, full):
+ continue
resolved = os.path.realpath(full)
if (
not _is_within(root, resolved)
@@ -1037,6 +1069,8 @@ def _scan(
continue
if not entry.is_file(follow_symlinks = False):
continue
+ if _is_ignored_scan_file(entry.name):
+ continue
if os.path.splitext(entry.name)[1].lower() not in config.UPLOAD_EXTS:
continue
# Finder metadata carries the document's extension, so a text parser would embed and cite it as a
diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.py
index bbeca01a637..d541263d9ee 100644
--- a/studio/backend/core/rag/parsers.py
+++ b/studio/backend/core/rag/parsers.py
@@ -862,10 +862,14 @@ def parse(path: str, *, want_images: bool = False):
pages = _docx(path)
return (pages, []) if want_images else pages
- if ext in (".html", ".htm", ".txt", ".md", ".markdown"):
+ if ext in (".html", ".htm", ".txt", ".md", ".markdown") or ext in config.SOURCE_TEXT_EXTS:
is_html = ext in (".html", ".htm")
with open(path, "rb") as f:
raw = _decode_text(f.read(), html = is_html)
+ # NUL never occurs in source text; a binary under a source extension (Fortran .mod, binary .plist) would
+ # otherwise embed as mojibake.
+ if ext in config.SOURCE_TEXT_EXTS and "\x00" in raw:
+ raise ValueError(f"unsupported binary content in text file: {os.path.basename(path)}")
# Universal newlines, as text-mode open() gave: the chunker splits on "\n\n".
raw = raw.replace("\r\n", "\n").replace("\r", "\n")
pages = _html(raw) if is_html else [_page(raw, None)]
diff --git a/studio/backend/tests/test_rag_config_upload_exts.py b/studio/backend/tests/test_rag_config_upload_exts.py
index 8667599f8d3..5cb82bddf01 100644
--- a/studio/backend/tests/test_rag_config_upload_exts.py
+++ b/studio/backend/tests/test_rag_config_upload_exts.py
@@ -29,12 +29,13 @@ def _reload(monkeypatch, value):
@pytest.mark.parametrize(
"value, expected",
[
- (None, config.SUPPORTED_UPLOAD_EXTS),
- ("", config.SUPPORTED_UPLOAD_EXTS),
+ (None, config.SUPPORTED_UPLOAD_EXTS | config.SOURCE_TEXT_EXTS),
+ ("", config.SUPPORTED_UPLOAD_EXTS | config.SOURCE_TEXT_EXTS),
(" .MD , .Markdown ", {".md", ".markdown"}),
("md,pdf", {".md", ".pdf"}),
- (".md,.py", {".md"}),
- (".py,.exe", config.SUPPORTED_UPLOAD_EXTS),
+ (".md,.exe", {".md"}),
+ (".py,.exe", {".py"}),
+ (".exe", config.SUPPORTED_UPLOAD_EXTS | config.SOURCE_TEXT_EXTS),
],
)
def test_upload_exts_env(monkeypatch, value, expected):
diff --git a/studio/backend/tests/test_rag_source_files_indexing.py b/studio/backend/tests/test_rag_source_files_indexing.py
new file mode 100644
index 00000000000..762951025c7
--- /dev/null
+++ b/studio/backend/tests/test_rag_source_files_indexing.py
@@ -0,0 +1,86 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import io
+import re
+from pathlib import Path
+
+import pytest
+from fastapi import UploadFile
+
+from core.rag import config, folder_sync, parsers
+from routes.rag import _save_upload
+
+_TEXT_ACCEPT_TS = (
+ Path(__file__).resolve().parents[2] / "frontend/src/features/chat/text-attachment-accept.ts"
+)
+
+
+def test_source_exts_mirror_chat_text_attachments():
+ source = _TEXT_ACCEPT_TS.read_text(encoding = "utf-8")
+ block = re.search(r"TEXT_ATTACHMENT_EXTENSIONS = \[(.*?)\];", source, re.S).group(1)
+ chat = set(re.findall(r'"(\.[^"]+)"', block))
+ assert chat - config.SUPPORTED_UPLOAD_EXTS == config.SOURCE_TEXT_EXTS
+
+
+ "name, content",
+ [
+ ("index.php", "<?php echo 'hello'; ?>"),
+ ("Program.cs", "class Program { static void Main() {} }"),
+ ("deploy.yaml", "apiVersion: v1\nkind: Pod"),
+ ],
+)
+def test_parse_source_file(tmp_path, name, content):
+ path = tmp_path / name
+ path.write_text(content, encoding = "utf-8")
+ assert [page.text for page in parsers.parse(str(path))] == [content]
+
+
+def test_parse_source_file_strips_bom(tmp_path):
+ path = tmp_path / "script.py"
+ path.write_bytes(b"\xef\xbb\xbfdef test(): pass")
+ assert [page.text for page in parsers.parse(str(path))] == ["def test(): pass"]
+
+
+def test_parse_rejects_binary_under_source_extension(tmp_path):
+ path = tmp_path / "module.mod"
+ path.write_bytes(b"GFORTRAN\x00\x01\x02")
+ with pytest.raises(ValueError, match = "unsupported binary content"):
+ parsers.parse(str(path))
+
+
+def test_scan_indexes_source_and_skips_dependencies_and_secrets(tmp_path):
+ files = {
+ "src/app.js": "a",
+ "src/index.php": "a",
+ "build/out.js": "a",
+ "infra/env/main.tf": "a",
+ "infra/env/terraform.tfstate": "a",
+ "src/unsupported.exe": "a",
+ "src/.env": "a",
+ "src/.env.local": "a",
+ "src/prod.env": "a",
+ "src/package-lock.json": "a",
+ "src/Cargo.lock": "a",
+ "node_modules/dep.js": "a",
+ ".git/config.json": "a",
+ "pyenv/pyvenv.cfg": "a",
+ "pyenv/lib/site.py": "a",
+ }
+ for rel, content in files.items():
+ (tmp_path / rel).parent.mkdir(parents = True, exist_ok = True)
+ (tmp_path / rel).write_text(content, encoding = "utf-8")
+ found, _ = folder_sync._scan(str(tmp_path))
+ assert {key.replace("\\", "/") for key in found} == {
+ "src/app.js",
+ "src/index.php",
+ "build/out.js",
+ "infra/env/main.tf",
+ }
+
+
+def test_upload_accepts_source_file(rag_home):
+ upload = UploadFile(file = io.BytesIO(b"<?php echo 1; ?>"), filename = "index.php")
+ _, filename, _ = _save_upload(upload)
+ assert filename == "index.php"
diff --git a/studio/backend/tests/test_rag_upload_formats.py b/studio/backend/tests/test_rag_upload_formats.py
index 9fb0bb7de3c..2b6c7be743a 100644
--- a/studio/backend/tests/test_rag_upload_formats.py
+++ b/studio/backend/tests/test_rag_upload_formats.py
@@ -83,7 +83,7 @@ def persist_document(monkeypatch):
def test_formats_finish_and_remain_searchable(
rag_home, stub_embeddings, tmp_path, monkeypatch, persist_document, extension, transport
):
- assert set(EXTENSIONS) == config.UPLOAD_EXTS
+ assert set(EXTENSIONS) == config.SUPPORTED_UPLOAD_EXTS
source = write_document(tmp_path / f"report{extension}", large = True)
stored, filename, content_hash = persist_document(source, transport)
assert Path(stored).read_bytes() == source.read_bytes()
diff --git a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
index 02cb2a63e17..725ab8f5a08 100644
--- a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
+++ b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
@@ -43,13 +43,10 @@ import {
updateKnowledgeBase,
} from "../api/rag-api";
import { useRagAvailabilityStore } from "../api/rag-availability";
-import {
- type KnowledgeBase,
- RAG_UPLOAD_ACCEPT,
- isLinkedFolderManaged,
-} from "../types/rag";
+import { type KnowledgeBase, isLinkedFolderManaged } from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
import { LinkedFoldersManager } from "./linked-folders-manager";
+import { RAG_SOURCE_UPLOAD_ACCEPT } from "./source-drop-policy";
import { useRagDocuments } from "./use-rag-documents";
import { useSourceDrop } from "./use-source-drop";
@@ -376,7 +373,7 @@ function KnowledgeBaseDocuments({
ref={fileInputRef}
type="file"
multiple={true}
- accept={RAG_UPLOAD_ACCEPT}
+ accept={RAG_SOURCE_UPLOAD_ACCEPT}
className="hidden"
onChange={(e) => {
if (e.target.files?.length) void upload(e.target.files);
diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
index e17035c4b4b..457c1f36adc 100644
--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
@@ -20,8 +20,10 @@ import {
noteProjectWork,
uploadProjectDocument,
} from "../api/rag-api";
-import { RAG_UPLOAD_ACCEPT } from "../types/rag";
-import { partitionSupported } from "./source-drop-policy";
+import {
+ RAG_SOURCE_UPLOAD_ACCEPT,
+ partitionSupported,
+} from "./source-drop-policy";
import {
addStagedSources,
EXPIRY_GRACE_MS,
@@ -251,7 +253,7 @@ export function ProjectSourceDropzone({
unsupported.length === 1
? `Can't add ${unsupported[0]}`
: `Can't add ${unsupported.length} files`,
- { description: `Supported types: ${RAG_UPLOAD_ACCEPT}` },
+ { description: "Supported types: documents and source code files" },
);
}
// Name, size and mtime can in principle match for two different files, so
@@ -369,7 +371,7 @@ export function ProjectSourceDropzone({
ref={inputRef}
type="file"
multiple={true}
- accept={RAG_UPLOAD_ACCEPT}
+ accept={RAG_SOURCE_UPLOAD_ACCEPT}
className="hidden"
onChange={(e) => {
const files = Array.from(e.target.files ?? []);
diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
index e9e41b480e4..5fb0d56da83 100644
--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx
+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
@@ -14,9 +14,10 @@ import {
listProjectDocuments,
subscribeProjectSourcesUpdated,
} from "../api/rag-api";
-import { RAG_UPLOAD_ACCEPT, isLinkedFolderManaged } from "../types/rag";
+import { isLinkedFolderManaged } from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
import { LinkedFoldersManager } from "./linked-folders-manager";
+import { RAG_SOURCE_UPLOAD_ACCEPT } from "./source-drop-policy";
import {
type RagUploadItem,
fileItems,
@@ -104,7 +105,7 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
} = useNativeFileDrop({
onFiles: handleFiles,
onNativeIntents: handleNativeIntents,
- accept: RAG_UPLOAD_ACCEPT,
+ accept: RAG_SOURCE_UPLOAD_ACCEPT,
disabled: uploading,
disabledReason: "Wait for the current upload to finish, then drop again.",
});
@@ -115,7 +116,7 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
ref={fileInputRef}
type="file"
multiple={true}
- accept={RAG_UPLOAD_ACCEPT}
+ accept={RAG_SOURCE_UPLOAD_ACCEPT}
className="hidden"
onChange={(e) => {
const files = Array.from(e.target.files ?? []);
diff --git a/studio/frontend/src/features/rag/components/source-drop-policy.ts b/studio/frontend/src/features/rag/components/source-drop-policy.ts
index 8dc688c343c..86dee573ce3 100644
--- a/studio/frontend/src/features/rag/components/source-drop-policy.ts
+++ b/studio/frontend/src/features/rag/components/source-drop-policy.ts
@@ -1,7 +1,23 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { isSupportedSourceName } from "../types/rag.ts";
+import { TEXT_ATTACHMENT_EXTENSIONS } from "../../chat/text-attachment-accept.ts";
+import { RAG_UPLOAD_ACCEPT } from "../types/rag.ts";
+
+// Projects and knowledge bases also index source files; backend SOURCE_TEXT_EXTS mirrors this list.
+export const RAG_SOURCE_UPLOAD_ACCEPT = [
+ ...new Set([...RAG_UPLOAD_ACCEPT.split(","), ...TEXT_ATTACHMENT_EXTENSIONS]),
+].join(",");
+
+const ACCEPTED_UPLOAD_EXTS = new Set(RAG_SOURCE_UPLOAD_ACCEPT.split(","));
+
+// `accept` only filters the picker, so a drop can carry anything, including an
+// extension-less folder entry the backend would reject.
+export function isSupportedSourceName(name: string): boolean {
+ const dot = name.lastIndexOf(".");
+ if (dot <= 0) return false;
+ return ACCEPTED_UPLOAD_EXTS.has(name.slice(dot).toLowerCase());
+}
/** Split a drop into what can be indexed and the names of what cannot, so the
* caller can report the rejects instead of discarding them silently. */
diff --git a/studio/frontend/src/features/rag/components/use-source-drop.ts b/studio/frontend/src/features/rag/components/use-source-drop.ts
index 6527ae816cd..8f1e0733dbc 100644
--- a/studio/frontend/src/features/rag/components/use-source-drop.ts
+++ b/studio/frontend/src/features/rag/components/use-source-drop.ts
@@ -13,7 +13,6 @@ import {
useRef,
useState,
} from "react";
-import { RAG_UPLOAD_ACCEPT } from "../types/rag";
import { partitionSupported } from "./source-drop-policy";
import { type RagUploadItem, uploadItemFromIntent } from "./use-rag-documents";
@@ -63,7 +62,7 @@ export function useSourceDrop({
names.length === 1
? `Can't add ${names[0]}`
: `Can't add ${names.length} files`,
- { description: `Supported types: ${RAG_UPLOAD_ACCEPT}` },
+ { description: "Supported types: documents and source code files" },
);
}, []);
diff --git a/studio/frontend/src/features/rag/types/rag.ts b/studio/frontend/src/features/rag/types/rag.ts
index c476adf72ff..0ceafac9fe8 100644
--- a/studio/frontend/src/features/rag/types/rag.ts
+++ b/studio/frontend/src/features/rag/types/rag.ts
@@ -181,15 +181,3 @@ export interface PreviewTarget {
}
export const RAG_UPLOAD_ACCEPT = ".pdf,.txt,.md,.markdown,.docx,.html,.htm";
-
-const ACCEPTED_UPLOAD_EXTS = new Set(
- RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase()),
-);
-
-// `accept` only filters the picker, so a drop can carry anything, including an
-// extension-less folder entry the backend would reject.
-export function isSupportedSourceName(name: string): boolean {
- const dot = name.lastIndexOf(".");
- if (dot <= 0) return false;
- return ACCEPTED_UPLOAD_EXTS.has(name.slice(dot).toLowerCase());
-}
diff --git a/studio/frontend/tests/rag-source-drop-filter.test.ts b/studio/frontend/tests/rag-source-drop-filter.test.ts
index a2141f161d8..22128749d47 100644
--- a/studio/frontend/tests/rag-source-drop-filter.test.ts
+++ b/studio/frontend/tests/rag-source-drop-filter.test.ts
@@ -4,11 +4,12 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { partitionSupported } from "../src/features/rag/components/source-drop-policy.ts";
import {
- RAG_UPLOAD_ACCEPT,
+ RAG_SOURCE_UPLOAD_ACCEPT,
isSupportedSourceName,
-} from "../src/features/rag/types/rag.ts";
+ partitionSupported,
+} from "../src/features/rag/components/source-drop-policy.ts";
+import { RAG_UPLOAD_ACCEPT } from "../src/features/rag/types/rag.ts";
test("every type the picker offers is accepted from a drop", () => {
for (const ext of RAG_UPLOAD_ACCEPT.split(",")) {
@@ -67,3 +68,10 @@ test("an empty drop yields nothing to upload and nothing to report", () => {
assert.equal(supported.length, 0);
assert.equal(unsupported.length, 0);
});
+
+test("source files the project picker offers are accepted from a drop", () => {
+ for (const ext of RAG_SOURCE_UPLOAD_ACCEPT.split(",")) {
+ assert.equal(isSupportedSourceName(`app${ext}`), true, ext);
+ }
+ assert.equal(isSupportedSourceName("index.php"), true);
+});