Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix(sources): report files skipped during import

周佳儀fd9c9535518c
diff --git a/src/components/sources/sources-view.test.ts b/src/components/sources/sources-view.test.ts
index bdd1f62b..74988ba1 100644
--- a/src/components/sources/sources-view.test.ts
+++ b/src/components/sources/sources-view.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"
import type { FileNode } from "@/types/wiki"
-import { filterSourceTreeByQuery } from "./sources-view"
+import { filterSourceTreeByQuery, summarizeImportOutcome } from "./sources-view"
const TREE: FileNode[] = [
{
@@ -39,3 +39,47 @@ describe("filterSourceTreeByQuery", () => {
expect(filterSourceTreeByQuery(TREE, "missing source")).toEqual([])
})
})
+
+describe("summarizeImportOutcome", () => {
+ it("stays silent when every selected file was imported", () => {
+ expect(
+ summarizeImportOutcome({ imported: ["/project/raw/sources/a.md"], skipped: [] }, null),
+ ).toBeNull()
+ })
+
+ it("reports which files were left out of a partial import", () => {
+ expect(
+ summarizeImportOutcome(
+ {
+ imported: ["/project/raw/sources/a.md"],
+ skipped: [{ name: "審查資料範例.pdf", reason: "too-large", detail: "142.8 MB" }],
+ },
+ null,
+ ),
+ ).toEqual({
+ importedCount: 1,
+ skipped: [{ name: "審查資料範例.pdf", reason: "too-large", detail: "142.8 MB" }],
+ error: null,
+ })
+ })
+
+ it("surfaces a thrown import error that today only reaches the console", () => {
+ expect(
+ summarizeImportOutcome(null, new Error("Cannot import the project folder")),
+ ).toEqual({
+ importedCount: 0,
+ skipped: [],
+ error: "Cannot import the project folder",
+ })
+ })
+
+ it("reports nothing imported when the picker yielded no usable file", () => {
+ expect(
+ summarizeImportOutcome({ imported: [], skipped: [{ name: "a.py", reason: "unsupported-type" }] }, null),
+ ).toEqual({
+ importedCount: 0,
+ skipped: [{ name: "a.py", reason: "unsupported-type" }],
+ error: null,
+ })
+ })
+})
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 60a4bb0d..42e4ebd0 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -20,6 +20,8 @@ import {
enqueueSourceIngest,
importSourceFiles,
importSourceFolder,
+ type SkippedSourceImport,
+ type SourceImportResult,
} from "@/lib/source-lifecycle"
import { filterRawSourceTree } from "@/lib/source-filter"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
@@ -51,6 +53,7 @@ export function SourcesView() {
const [urlInput, setUrlInput] = useState("")
const [urlError, setUrlError] = useState<string | null>(null)
const [urlResults, setUrlResults] = useState<UrlImportResult[]>([])
+ const [importOutcome, setImportOutcome] = useState<ImportOutcome | null>(null)
const [ingestedIdentities, setIngestedIdentities] = useState<string[]>([])
const [queueSnapshot, setQueueSnapshot] = useState<IngestTask[]>(() => [...getQueue()])
const [sourceQuery, setSourceQuery] = useState("")
@@ -202,10 +205,15 @@ export function SourcesView() {
if (!selected || selected.length === 0) return
setImporting(true)
+ setImportOutcome(null)
const paths = Array.isArray(selected) ? selected : [selected]
try {
- await importSourceFiles(project, paths, llmConfig, sourceWatchConfig)
+ const result = await importSourceFiles(project, paths, llmConfig, sourceWatchConfig)
+ setImportOutcome(summarizeImportOutcome(result, null))
await loadSources()
+ } catch (err) {
+ console.error("Failed to import files:", err)
+ setImportOutcome(summarizeImportOutcome(null, err))
} finally {
setImporting(false)
}
@@ -222,11 +230,14 @@ export function SourcesView() {
if (!selected || typeof selected !== "string") return
setImporting(true)
+ setImportOutcome(null)
try {
- await importSourceFolder(project, selected, llmConfig, sourceWatchConfig)
+ const result = await importSourceFolder(project, selected, llmConfig, sourceWatchConfig)
+ setImportOutcome(summarizeImportOutcome(result, null))
await loadSources()
} catch (err) {
console.error(`Failed to import folder:`, err)
+ setImportOutcome(summarizeImportOutcome(null, err))
} finally {
setImporting(false)
}
@@ -474,6 +485,42 @@ export function SourcesView() {
})}
</div>
)}
+ {importOutcome && (
+ <div className="mx-4 mt-3 space-y-1 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
+ <div className="flex items-start justify-between gap-2">
+ <span className="font-medium">
+ {importOutcome.error
+ ? t("sources.importSkip.failed", {
+ defaultValue: "Import failed: {{error}}",
+ error: importOutcome.error,
+ })
+ : t("sources.importSkip.summary", {
+ defaultValue: "Imported {{imported}}, skipped {{skipped}}",
+ imported: importOutcome.importedCount,
+ skipped: importOutcome.skipped.length,
+ })}
+ </span>
+ <button
+ type="button"
+ onClick={() => setImportOutcome(null)}
+ className="shrink-0 rounded p-0.5 hover:bg-destructive/20"
+ aria-label={t("common.dismiss", { defaultValue: "Dismiss" })}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ {importOutcome.skipped.map((item, index) => (
+ <div key={`${item.name}-${index}`} className="pl-1">
+ {item.name}
+ {": "}
+ {t(`sources.importSkip.reason.${item.reason}`, {
+ defaultValue: item.reason,
+ })}
+ {item.detail ? ` (${item.detail})` : ""}
+ </div>
+ ))}
+ </div>
+ )}
{sources.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-3 p-8 text-center text-sm text-muted-foreground">
<p>{t("sources.noSources")}</p>
@@ -563,6 +610,31 @@ function countFiles(nodes: FileNode[]): number {
return count
}
+export interface ImportOutcome {
+ importedCount: number
+ skipped: SkippedSourceImport[]
+ error: string | null
+}
+
+/**
+ * Decides whether an import needs to say anything to the user.
+ * A clean import stays quiet; anything skipped or thrown gets reported.
+ */
+export function summarizeImportOutcome(
+ result: SourceImportResult | null,
+ error: unknown,
+): ImportOutcome | null {
+ if (error) {
+ return {
+ importedCount: result?.imported.length ?? 0,
+ skipped: result?.skipped ?? [],
+ error: error instanceof Error ? error.message : String(error),
+ }
+ }
+ if (!result || result.skipped.length === 0) return null
+ return { importedCount: result.imported.length, skipped: result.skipped, error: null }
+}
+
export function filterSourceTreeByQuery(
nodes: readonly FileNode[],
query: string,
diff --git a/src/i18n/en.json b/src/i18n/en.json
index b8426142..d5ddf6d1 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -186,6 +186,18 @@
"refreshFolderHint": "Rescan the source folder and process new, changed, or deleted files.",
"refreshFolderTooltip": "Rescan the project source folder with the same rules as automatic monitoring. New or modified allowed files are queued for ingest; deleted sources trigger the normal wiki and index cleanup; then the file tree is rebuilt.",
"refreshFailed": "Failed to refresh sources: {{error}}",
+ "importSkip": {
+ "failed": "Import failed: {{error}}",
+ "summary": "Imported {{imported}}, skipped {{skipped}}",
+ "reason": {
+ "unsupported-type": "Unsupported file type",
+ "excluded": "Blocked by an exclusion rule",
+ "too-large": "Exceeds the maximum file size",
+ "unreadable": "Could not read the file",
+ "copy-failed": "Could not copy the file",
+ "sensitive-config": "Withheld as a tool config file"
+ }
+ },
"openExternal": "Open in default app",
"openExternalFailed": "Failed to open {{name}}: {{error}}",
"ingest": "Ingest",
diff --git a/src/i18n/it.json b/src/i18n/it.json
index 0d83badd..04317835 100644
--- a/src/i18n/it.json
+++ b/src/i18n/it.json
@@ -186,6 +186,18 @@
"refreshFolderHint": "Riesamina la cartella delle fonti ed elabora i file nuovi, modificati o eliminati.",
"refreshFolderTooltip": "Riesamina la cartella delle fonti del progetto con le stesse regole del monitoraggio automatico. I file consentiti nuovi o modificati vengono messi in coda per l'elaborazione; le fonti eliminate avviano la normale pulizia di wiki e indice; infine l'albero dei file viene ricostruito.",
"refreshFailed": "Impossibile aggiornare le fonti: {{error}}",
+ "importSkip": {
+ "failed": "Importazione non riuscita: {{error}}",
+ "summary": "Importati {{imported}}, ignorati {{skipped}}",
+ "reason": {
+ "unsupported-type": "Tipo di file non supportato",
+ "excluded": "Bloccato da una regola di esclusione",
+ "too-large": "Supera la dimensione massima del file",
+ "unreadable": "Impossibile leggere il file",
+ "copy-failed": "Impossibile copiare il file",
+ "sensitive-config": "Escluso in quanto file di configurazione"
+ }
+ },
"openExternal": "Apri nell'app predefinita",
"openExternalFailed": "Impossibile aprire {{name}}: {{error}}",
"ingest": "Elabora",
diff --git a/src/i18n/ru.json b/src/i18n/ru.json
index ddeb74a8..19039701 100644
--- a/src/i18n/ru.json
+++ b/src/i18n/ru.json
@@ -186,6 +186,18 @@
"refreshFolderHint": "Заново просканировать папку источников и обработать новые, изменённые или удалённые файлы.",
"refreshFolderTooltip": "Заново просканировать папку источников проекта по тем же правилам, что и автоматический мониторинг. Новые или изменённые разрешённые файлы ставятся в очередь обработки; удалённые источники запускают обычную очистку вики и индекса; затем дерево файлов перестраивается.",
"refreshFailed": "Не удалось обновить источники: {{error}}",
+ "importSkip": {
+ "failed": "Не удалось импортировать: {{error}}",
+ "summary": "Импортировано: {{imported}}, пропущено: {{skipped}}",
+ "reason": {
+ "unsupported-type": "Неподдерживаемый тип файла",
+ "excluded": "Заблокировано правилом исключения",
+ "too-large": "Превышен максимальный размер файла",
+ "unreadable": "Не удалось прочитать файл",
+ "copy-failed": "Не удалось скопировать файл",
+ "sensitive-config": "Пропущен как файл конфигурации"
+ }
+ },
"openExternal": "Открыть в приложении по умолчанию",
"openExternalFailed": "Не удалось открыть «{{name}}»: {{error}}",
"ingest": "Обработать",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 4d4ebffb..8d80a3cb 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -186,6 +186,18 @@
"refreshFolderHint": "重新扫描资料文件夹,并处理新增、修改或删除的文件。",
"refreshFolderTooltip": "按自动监控相同规则重新扫描当前项目的资料文件夹。允许的新增或修改文件会加入提取队列;已删除的资料会走正常的 Wiki 与索引清理流程;随后重建文件树。",
"refreshFailed": "刷新原始资料失败:{{error}}",
+ "importSkip": {
+ "failed": "导入失败:{{error}}",
+ "summary": "已导入 {{imported}} 个,跳过 {{skipped}} 个",
+ "reason": {
+ "unsupported-type": "不支持的文件类型",
+ "excluded": "被排除规则阻止",
+ "too-large": "超过文件大小上限",
+ "unreadable": "无法读取文件",
+ "copy-failed": "无法复制文件",
+ "sensitive-config": "已跳过工具配置文件"
+ }
+ },
"openExternal": "用默认应用打开",
"openExternalFailed": "无法打开「{{name}}」:{{error}}",
"ingest": "提取到 Wiki",
diff --git a/src/lib/source-lifecycle.test.ts b/src/lib/source-lifecycle.test.ts
index 6d3cfd9c..b1cd8635 100644
--- a/src/lib/source-lifecycle.test.ts
+++ b/src/lib/source-lifecycle.test.ts
@@ -117,7 +117,7 @@ describe("source-lifecycle path helpers", () => {
},
)
- expect(copied).toEqual(["/project/raw/sources/imported/keep.md"])
+ expect(copied.imported).toEqual(["/project/raw/sources/imported/keep.md"])
expect(mocks.copyFile).toHaveBeenCalledTimes(1)
expect(mocks.copyFile).toHaveBeenCalledWith("/external/imported/keep.md", "/project/raw/sources/imported/keep.md")
expect(mocks.copyFile).not.toHaveBeenCalledWith("/external/imported/config.json", expect.anything())
@@ -179,7 +179,7 @@ describe("source-lifecycle path helpers", () => {
},
)
- expect(copied).toEqual(["/project/raw/sources/imported/.claude/research.md"])
+ expect(copied.imported).toEqual(["/project/raw/sources/imported/.claude/research.md"])
expect(mocks.copyFile).toHaveBeenCalledTimes(1)
expect(mocks.copyFile).toHaveBeenCalledWith(
"/external/imported/.claude/research.md",
@@ -250,7 +250,7 @@ describe("source-lifecycle path helpers", () => {
},
)
- expect(copied).toEqual(["/project/raw/sources/ready.md"])
+ expect(copied.imported).toEqual(["/project/raw/sources/ready.md"])
expect(mocks.copyFile).toHaveBeenCalledTimes(1)
expect(mocks.copyFile).toHaveBeenCalledWith("/external/ready.md", "/project/raw/sources/ready.md")
expect(mocks.copyFile).not.toHaveBeenCalledWith("/external/drafts/spec.md", expect.anything())
@@ -288,7 +288,7 @@ describe("source-lifecycle path helpers", () => {
},
)
- expect(copied).toEqual(["/project/raw/sources/book.epub"])
+ expect(copied.imported).toEqual(["/project/raw/sources/book.epub"])
expect(mocks.copyFile).toHaveBeenCalledWith(
"/external/book.epub",
"/project/raw/sources/book.epub",
@@ -373,7 +373,7 @@ describe("source-lifecycle path helpers", () => {
},
)
- expect(copied).toEqual([
+ expect(copied.imported).toEqual([
"/project/raw/sources/imported/1.md",
"/project/raw/sources/imported/2.md",
"/project/raw/sources/imported/10.md",
@@ -394,3 +394,190 @@ describe("source-lifecycle path helpers", () => {
])
})
})
+
+describe("source import skip reporting", () => {
+ const project = { id: "p1", name: "Project", path: "/project" }
+
+ const llm = {
+ provider: "openai",
+ endpoint: "https://api.example.com/v1",
+ apiKey: "key",
+ model: "model",
+ customModel: "",
+ reasoning: { enabled: false, effort: "low" },
+ } as never
+
+ function watchConfig(overrides: Record<string, unknown> = {}) {
+ return {
+ enabled: true,
+ autoIngest: true,
+ persistExtractedMarkdown: false,
+ parsingConcurrency: 2,
+ ingestConcurrency: 1,
+ includeExtensions: [],
+ excludeExtensions: [],
+ excludeDirs: [],
+ excludeGlobs: [],
+ maxFileSizeMb: 100,
+ ...overrides,
+ } as never
+ }
+
+ it("reports an oversized file instead of dropping it silently", async () => {
+ mocks.getFileSize.mockResolvedValue(149696996)
+
+ const result = await importSourceFiles(
+ project,
+ ["/external/審查資料範例.pdf"],
+ llm,
+ watchConfig({ maxFileSizeMb: 100 }),
+ )
+
+ expect(result.imported).toEqual([])
+ expect(result.skipped).toEqual([
+ { name: "審查資料範例.pdf", reason: "too-large", detail: "142.8 MB" },
+ ])
+ expect(mocks.copyFile).not.toHaveBeenCalled()
+ })
+
+ it("reports file types the picker offers but ingest cannot read", async () => {
+ const result = await importSourceFiles(
+ project,
+ ["/external/script.py", "/external/photo.png", "/external/notes.md"],
+ llm,
+ watchConfig(),
+ )
+
+ expect(result.imported).toEqual(["/project/raw/sources/notes.md"])
+ expect(result.skipped).toEqual([
+ { name: "script.py", reason: "unsupported-type" },
+ { name: "photo.png", reason: "unsupported-type" },
+ ])
+ })
+
+ it("reports files blocked by an exclusion rule", async () => {
+ const result = await importSourceFiles(
+ project,
+ ["/external/draft-report.pdf", "/external/final.pdf"],
+ llm,
+ watchConfig({ excludeGlobs: ["draft-*"] }),
+ )
+
+ expect(result.imported).toEqual(["/project/raw/sources/final.pdf"])
+ expect(result.skipped).toEqual([
+ { name: "draft-report.pdf", reason: "excluded" },
+ ])
+ })
+
+ it("reports a file whose copy fails instead of only logging it", async () => {
+ mocks.copyFile.mockRejectedValueOnce(new Error("EACCES: permission denied"))
+
+ const result = await importSourceFiles(
+ project,
+ ["/external/locked.pdf"],
+ llm,
+ watchConfig(),
+ )
+
+ expect(result.imported).toEqual([])
+ expect(result.skipped).toEqual([
+ { name: "locked.pdf", reason: "copy-failed", detail: "EACCES: permission denied" },
+ ])
+ })
+
+ it("reports a file whose size cannot be read", async () => {
+ mocks.getFileSize.mockRejectedValueOnce(new Error("ENOENT"))
+
+ const result = await importSourceFiles(
+ project,
+ ["/external/vanished.pdf"],
+ llm,
+ watchConfig(),
+ )
+
+ expect(result.imported).toEqual([])
+ expect(result.skipped).toEqual([
+ { name: "vanished.pdf", reason: "unreadable", detail: "ENOENT" },
+ ])
+ })
+
+ it("reports a withheld tool-config file so it does not just disappear", async () => {
+ const result = await importSourceFiles(
+ project,
+ ["/external/.claude/settings.json", "/external/notes.md"],
+ llm,
+ watchConfig(),
+ )
+
+ expect(result.imported).toEqual(["/project/raw/sources/notes.md"])
+ expect(result.skipped).toEqual([
+ { name: "settings.json", reason: "sensitive-config" },
+ ])
+ })
+
+ it("reports a hidden file as excluded rather than an unsupported type", async () => {
+ const result = await importSourceFiles(
+ project,
+ ["/external/.secret-notes.md"],
+ llm,
+ watchConfig(),
+ )
+
+ expect(result.skipped).toEqual([
+ { name: ".secret-notes.md", reason: "excluded" },
+ ])
+ })
+
+ it("reports files a folder import left behind", async () => {
+ mocks.listDirectory.mockResolvedValue([
+ { name: "keep.md", path: "/external/imported/keep.md", is_dir: false },
+ { name: "huge.pdf", path: "/external/imported/huge.pdf", is_dir: false },
+ { name: "notes.py", path: "/external/imported/notes.py", is_dir: false },
+ ])
+ mocks.getFileSize.mockImplementation(async (path: string) =>
+ path.endsWith("huge.pdf") ? 149696996 : 1024,
+ )
+
+ const result = await importSourceFolder(
+ project,
+ "/external/imported",
+ llm,
+ watchConfig({ includeExtensions: ["md", "pdf"] }),
+ )
+
+ expect(result.imported).toEqual(["/project/raw/sources/imported/keep.md"])
+ expect(result.skipped).toEqual([
+ { name: "huge.pdf", reason: "too-large", detail: "142.8 MB" },
+ { name: "notes.py", reason: "excluded" },
+ ])
+ })
+
+ it("continues a folder import after one nested file cannot be copied", async () => {
+ mocks.listDirectory.mockResolvedValue([
+ {
+ name: "nested",
+ path: "/external/imported/nested",
+ is_dir: true,
+ children: [
+ { name: "locked.md", path: "/external/imported/nested/locked.md", is_dir: false },
+ ],
+ },
+ { name: "keep.md", path: "/external/imported/keep.md", is_dir: false },
+ ])
+ mocks.copyFile.mockImplementation(async (source: string) => {
+ if (source.endsWith("locked.md")) throw new Error("EACCES")
+ })
+
+ const result = await importSourceFolder(
+ project,
+ "/external/imported",
+ llm,
+ watchConfig({ includeExtensions: ["md"] }),
+ )
+
+ expect(result.imported).toEqual(["/project/raw/sources/imported/keep.md"])
+ expect(result.skipped).toEqual([
+ { name: "nested/locked.md", reason: "copy-failed", detail: "EACCES" },
+ ])
+ })
+})
diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.ts
index 88c1eb33..408c4aae 100644
--- a/src/lib/source-lifecycle.ts
+++ b/src/lib/source-lifecycle.ts
@@ -282,14 +282,42 @@ export async function enqueueSourceIngest(
return enqueueBatch(project.id, files)
}
+export type SourceImportSkipReason =
+ | "unsupported-type"
+ | "excluded"
+ | "too-large"
+ | "unreadable"
+ | "copy-failed"
+ | "sensitive-config"
+
+export interface SkippedSourceImport {
+ name: string
+ reason: SourceImportSkipReason
+ detail?: string
+}
+
+export interface SourceImportResult {
+ imported: string[]
+ skipped: SkippedSourceImport[]
+}
+
+function formatMegabytes(bytes: number): string {
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+function errorDetail(err: unknown): string {
+ return err instanceof Error ? err.message : String(err)
+}
+
export async function importSourceFiles(
project: WikiProject,
sourcePaths: string[],
llmConfig: LlmConfig,
sourceWatchConfig?: SourceWatchConfig,
-): Promise<string[]> {
+): Promise<SourceImportResult> {
const pp = normalizePath(project.path)
const importedPaths: string[] = []
+ const skipped: SkippedSourceImport[] = []
const cfg = normalizeSourceWatchConfig(sourceWatchConfig)
// Explicit file selection is user intent, so the watcher's allow-list must
// not silently reject a newly supported format from an older persisted
@@ -301,18 +329,29 @@ export async function importSourceFiles(
for (const sourcePath of sourcePaths) {
const originalName = getFileName(sourcePath) || "unknown"
if (isSensitiveConfigSourceFile(sourcePath)) {
+ skipped.push({ name: originalName, reason: "sensitive-config" })
continue
}
- let allowed = isIngestableSourcePath(sourcePath)
- && isPathAllowedBySourceWatch(sourcePath, explicitImportConfig)
- if (allowed) {
- try {
- allowed = await getFileSize(sourcePath) <= maxBytes
- } catch {
- allowed = false
+ // Exclusions first: a hidden or excluded file may still be a supported
+ // type, and "excluded" is the reason the user can act on.
+ if (!isPathAllowedBySourceWatch(sourcePath, explicitImportConfig)) {
+ skipped.push({ name: originalName, reason: "excluded" })
+ continue
+ }
+ if (!isIngestableSourcePath(sourcePath)) {
+ skipped.push({ name: originalName, reason: "unsupported-type" })
+ continue
+ }
+ try {
+ const size = await getFileSize(sourcePath)
+ if (size > maxBytes) {
+ skipped.push({ name: originalName, reason: "too-large", detail: formatMegabytes(size) })
+ continue
}
+ } catch (err) {
+ skipped.push({ name: originalName, reason: "unreadable", detail: errorDetail(err) })
+ continue
}
- if (!allowed) continue
const destPath = await getUniqueDestPath(`${pp}/raw/sources`, originalName)
try {
@@ -320,6 +359,7 @@ export async function importSourceFiles(
importedPaths.push(destPath)
} catch (err) {
console.error(`Failed to import ${originalName}:`, err)
+ skipped.push({ name: originalName, reason: "copy-failed", detail: errorDetail(err) })
}
}
@@ -327,7 +367,7 @@ export async function importSourceFiles(
parsingConcurrency: cfg.parsingConcurrency,
})
- return importedPaths
+ return { imported: importedPaths, skipped }
}
export async function importSourceFolder(
@@ -335,7 +375,7 @@ export async function importSourceFolder(
selectedFolder: string,
llmConfig: LlmConfig,
sourceWatchConfig?: SourceWatchConfig,
-): Promise<string[]> {
+): Promise<SourceImportResult> {
const pp = normalizePath(project.path)
const sourceRoot = normalizePath(selectedFolder)
if (isProjectScopedImport(pp, sourceRoot)) {
@@ -346,6 +386,7 @@ export async function importSourceFolder(
const cfg = normalizeSourceWatchConfig(sourceWatchConfig)
const maxBytes = cfg.maxFileSizeMb * 1024 * 1024
const allowedFiles: string[] = []
+ const skipped: SkippedSourceImport[] = []
// include hidden: a user importing a folder into raw/sources may
// legitimately want dotfolder notes. Config-like files under known
// agent/tool config folders are still filtered before copy so API
@@ -354,24 +395,36 @@ export async function importSourceFolder(
for (const file of sourceFiles) {
const relativeSourcePath = getRelativePath(file.path, sourceRoot)
+ const displayName = relativeSourcePath || file.name
const destPath = `${destDir}/${relativeSourcePath}`
const relPath = `raw/sources/${folderName}/${relativeSourcePath}`
if (isSensitiveConfigSourceFile(file.path)) {
+ skipped.push({ name: displayName, reason: "sensitive-config" })
continue
}
- let allowed = isPathAllowedBySourceWatch(relPath, cfg)
- if (allowed) {
- try {
- allowed = await getFileSize(file.path) <= maxBytes
- } catch {
- allowed = false
+ if (!isPathAllowedBySourceWatch(relPath, cfg)) {
+ skipped.push({ name: displayName, reason: "excluded" })
+ continue
+ }
+ try {
+ const size = await getFileSize(file.path)
+ if (size > maxBytes) {
+ skipped.push({ name: displayName, reason: "too-large", detail: formatMegabytes(size) })
+ continue
}
+ } catch (err) {
+ skipped.push({ name: displayName, reason: "unreadable", detail: errorDetail(err) })
+ continue
+ }
+ try {
+ const parent = parentPath(destPath)
+ if (parent) await createDirectory(parent)
+ await copyFile(file.path, destPath)
+ allowedFiles.push(destPath)
+ } catch (err) {
+ console.error(`Failed to import ${displayName}:`, err)
+ skipped.push({ name: displayName, reason: "copy-failed", detail: errorDetail(err) })
}
- if (!allowed) continue
- const parent = parentPath(destPath)
- if (parent) await createDirectory(parent)
- await copyFile(file.path, destPath)
- allowedFiles.push(destPath)
}
const naturallyOrderedFiles = [...allowedFiles].sort((a, b) =>
@@ -386,7 +439,7 @@ export async function importSourceFolder(
})
}
- return naturallyOrderedFiles
+ return { imported: naturallyOrderedFiles, skipped }
}
export async function deleteSourceFile(