From 96277c00b4aec50e0f1723be5a041383e5d25270 Mon Sep 17 00:00:00 2001 From: kelvinwww <1970138194@qq.com> Date: Sat, 24 Oct 2026 09:54:14 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20Markdown=20Windows?= =?UTF-8?q?=20=E8=B7=AF=E5=BE=84=E9=93=BE=E6=8E=A5=E6=89=93=E5=BC=80?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + src/client/EditorHost.tsx | 113 +++++++++++++++++++++++++++-- src/client/locales-ar.ts | 10 +++ src/client/locales-de.ts | 10 +++ src/client/locales-fr.ts | 10 +++ src/client/locales-hi.ts | 10 +++ src/client/locales-id.ts | 10 +++ src/client/locales-it.ts | 10 +++ src/client/locales-ja.ts | 10 +++ src/client/locales-ko.ts | 10 +++ src/client/locales-nl.ts | 10 +++ src/client/locales-pl.ts | 10 +++ src/client/locales-pt.ts | 10 +++ src/client/locales-ru.ts | 10 +++ src/client/locales-sv.ts | 10 +++ src/client/locales-th.ts | 10 +++ src/client/locales-tr.ts | 10 +++ src/client/locales-vi.ts | 10 +++ src/client/locales-zh-HK.ts | 10 +++ src/client/locales-zh-MO.ts | 10 +++ src/client/locales-zh-TW.ts | 10 +++ src/client/locales.ts | 20 +++++ src/client/markdown-path-repair.ts | 53 ++++++++++++++ src/client/sidebar.module.css | 19 +++++ src/file-stream.ts | 8 +- src/fs-read-error.ts | 13 ++++ src/index.ts | 15 ++-- tests/fs-read-error.spec.ts | 17 +++++ tests/markdown-path-repair.spec.ts | 31 ++++++++ 29 files changed, 459 insertions(+), 21 deletions(-) create mode 100644 src/client/markdown-path-repair.ts create mode 100644 src/fs-read-error.ts create mode 100644 tests/fs-read-error.spec.ts create mode 100644 tests/markdown-path-repair.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e487b4f3..300bb3da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### 未发布 +- **Markdown 文件链接错误恢复**:Windows 路径因转义丢失分隔符时,侧栏会检查有限数量的候选路径;唯一命中时自动打开,多个命中时提供选择。文件不存在时显示可读提示,并提供复制路径、文件管理器打开和重试操作。 - **任务图展开修复**:平移画布后,聚合卡和 Agent 卡的下一次点击不再被误判为拖动;展开聚合与查看详情恢复正常。 - **任务图性能**:卡片内容使用独立 memo 边界,平移与布局补间不再重复渲染内容;布局用索引和显式栈替代逐边查找与深递归,同次宽度适配复用相同列数的布局。2000 个非根 Agent 的纯布局对照及 200/500 Agent 真浏览器证据见[验证记录](docs/plans/2026-10-23-tasks-folding-performance-validation.md),布局加速不外推为整页加速。 - **任务页拖拽改为每帧一次更新**:图模式背景平移、后台任务浮窗标题拖动、锚定弹层拖动不再按鼠标事件频率重绘(高回报率鼠标下此前每个 pointermove 都提交整块画布);松手同步落位,点击判定与最终位置不变。实测同一帧内 100 次移动的画布提交由 98 次降到 1 次。 diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index cadcaced..ac811caf 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -25,11 +25,12 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { createElement } from 'react' import clsx from 'clsx' -import { IconCheckOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { Button, IconCheckOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegular, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '../context-types.ts' -import { api, mediaUrl, type SessionScope } from './api.ts' +import { api, mediaUrl, SidebarApiError, type SessionScope } from './api.ts' import { BinaryDownload } from './binary-download.tsx' import { planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts' +import { isWindowsAbsolutePath, markdownPathRepairCandidates } from './markdown-path-repair.ts' import { clearEditorDirty, setEditorDirty } from './editor-dirty.ts' import { baseName } from './FileTree.tsx' import { createFrameBatcher } from './frame-batcher.ts' @@ -49,7 +50,7 @@ import css from './sidebar.module.css' type EditorLoad = | { status: 'loading' } - | { status: 'error'; message: string } + | { status: 'error'; message: string; fileNotFound?: boolean; windowsAbsolutePath?: boolean; repairStatus?: 'searching' | 'done'; repairMatches?: string[]; repairError?: string } | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; size?: number; largeFile?: { size: number }; mtimeMs?: number; mediaUrl?: string; customData?: unknown } | { status: 'binary' } @@ -136,6 +137,7 @@ export function EditorHost(props: { // the viewer loading flow (a directory is not a file). const isDir = metaOf(tab).dir === true const [load, setLoad] = useState({ status: 'loading' }) + const [fileErrorAction, setFileErrorAction] = useState(null) // Manual refresh (issue #167): bumping the sequence re-runs the load effect // with the same path/scope — the only reload entry besides open/close. const [reloadSeq, setReloadSeq] = useState(0) @@ -433,6 +435,7 @@ export function EditorHost(props: { // closed, path changed, session switched) or re-matches the viewer. const controller = new AbortController() setLoad({ status: 'loading' }) + setFileErrorAction(null) const mediaUrlOf = (): string => mediaUrl(scope, path) const apply = (action: EditorLoadAction): void => { if (cancelled) return @@ -470,9 +473,63 @@ export function EditorHost(props: { // editor uses it as the save baseline (fs-conflict on drift). if (outcome.kind === 'render') setLoad({ ...outcome, status: 'ready', mtimeMs: result.mtimeMs }) else apply(outcome) - }).catch((error: unknown) => { + }).catch(async (error: unknown) => { if (cancelled) return - setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) }) + const message = error instanceof Error ? error.message : String(error) + const fileNotFound = error instanceof SidebarApiError + && error.code === 'fs-error' + && message.startsWith('File not found: ') + if (!fileNotFound) { + setLoad({ status: 'error', message }) + return + } + + const candidates = markdownPathRepairCandidates(path) + setLoad({ + status: 'error', + message, + fileNotFound: true, + windowsAbsolutePath: isWindowsAbsolutePath(path), + ...(candidates.length > 0 ? { repairStatus: 'searching' as const } : {}), + }) + if (candidates.length === 0) return + + const matches = new Set() + try { + for (let offset = 0; offset < candidates.length; offset += 8) { + const batch = candidates.slice(offset, offset + 8) + const results = await Promise.all(batch.map(candidate => api.fsSearch(scope, candidate, undefined, controller.signal))) + for (const result of results) { + const directories = new Set(result.dirs) + for (const match of result.matches) { + if (!directories.has(match)) matches.add(match) + } + } + } + } catch (repairError: unknown) { + if (cancelled) return + setLoad({ + status: 'error', + message, + fileNotFound: true, + windowsAbsolutePath: true, + repairStatus: 'done', + repairError: repairError instanceof Error ? repairError.message : String(repairError), + }) + return + } + + if (cancelled) return + const repairMatches = [...matches] + if (repairMatches.length === 1) { + const repairedPath = repairMatches[0]! + const betterSidebar = ctx.get('betterSidebar') + if (betterSidebar?.updateTab !== undefined) { + betterSidebar.updateTab(tab.id, { path: repairedPath, title: baseName(repairedPath) }, scope.sessionId) + return + } + } + setLoad({ status: 'error', message, fileNotFound: true, windowsAbsolutePath: true, repairStatus: 'done', repairMatches }) }) return } @@ -652,7 +709,51 @@ export function EditorHost(props: {
{showEmpty &&
{t('editorEmptyHint')}
} {!showEmpty && load.status === 'loading' &&
{t('loading')}
} - {!showEmpty && load.status === 'error' &&
{load.message}
} + {!showEmpty && load.status === 'error' && ( +
+
{load.fileNotFound ? t('editorFileNotFound', { path }) : load.message}
+ {load.fileNotFound && load.windowsAbsolutePath && ( +
{t('editorMarkdownPathHint')}
+ )} + {load.repairStatus === 'searching' &&
{t('editorPathRepairSearching')}
} + {load.repairStatus === 'done' && load.repairMatches?.length === 0 && ( +
{t('editorPathRepairNone')}
+ )} + {load.repairMatches !== undefined && load.repairMatches.length > 0 && ( +
+
{t('editorPathRepairChoices')}
+ {load.repairMatches.map(candidate => ( + + ))} +
+ )} + {load.repairError !== undefined && ( +
{t('editorPathRepairFailed', { message: load.repairError })}
+ )} +
+ + + +
+ {fileErrorAction !== null &&
{fileErrorAction}
} +
+ )} {!showEmpty && load.status === 'binary' && } {!showEmpty && load.status === 'ready' && createElement(load.viewer.component, { ctx, store, scope, path, title, diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index 027785ef..70972251 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -54,6 +54,16 @@ export const ar: Record = { explorerExcludeAdd: 'إضافة', explorerExcludeRemove: 'إزالة', editorTreeToggle: 'لوحة شجرة الملفات', + editorFileNotFound: 'الملف غير موجود: {path}', + editorMarkdownPathHint: 'قد يكون Markdown قد حذف شرطة مائلة عكسية من مسار Windows. جرّب استخدام الشرطات المائلة أو وضع المسار في كتلة تعليمات برمجية.', + editorPathRepairSearching: 'جارٍ فحص مسارات Windows المحتملة…', + editorPathRepairNone: 'لم يتم العثور على مسار مطابق بشكل فريد. تحقّق من المسار ثم أعد المحاولة.', + editorPathRepairChoices: 'تم العثور على عدة مسارات محتملة. اختر المسار الصحيح:', + editorPathRepairFailed: 'تعذّر فحص المسارات المُصلحة: {message}', + editorCopyPath: 'نسخ المسار', + editorOpenInFileManager: 'فتح في مدير الملفات', + editorCopyPathFailed: 'تعذّر نسخ المسار', + editorRevealPathFailed: 'تعذّر فتح هذا المسار في مدير الملفات', editorPathPlaceholder: 'مسار الملف (نسبي لدليل الجلسة أو مطلق)، Enter للفتح', editorSearchPlaceholder: 'البحث في الملفات بالاسم…', editorSearchNoResults: 'لا ملفات مطابقة', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index 41573831..b557d8ea 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -39,6 +39,16 @@ export const de: Record = { explorerExcludeAdd: 'Hinzufügen', explorerExcludeRemove: 'Entfernen', editorTreeToggle: 'Dateibaum-Panel', + editorFileNotFound: 'Datei nicht gefunden: {path}', + editorMarkdownPathHint: 'Markdown hat möglicherweise einen Backslash im Windows-Pfad entfernt. Verwende Schrägstriche oder setze den Pfad in einen Codeblock.', + editorPathRepairSearching: 'Mögliche Windows-Pfade werden geprüft…', + editorPathRepairNone: 'Es wurde kein eindeutiger Pfad gefunden. Prüfe den Pfad und versuche es erneut.', + editorPathRepairChoices: 'Mehrere mögliche Pfade gefunden. Wähle den richtigen Pfad:', + editorPathRepairFailed: 'Reparierte Pfade konnten nicht geprüft werden: {message}', + editorCopyPath: 'Pfad kopieren', + editorOpenInFileManager: 'Im Dateimanager öffnen', + editorCopyPathFailed: 'Pfad konnte nicht kopiert werden', + editorRevealPathFailed: 'Pfad konnte nicht im Dateimanager geöffnet werden', editorPathPlaceholder: 'Dateipfad (relativ zum Sitzungsverzeichnis oder absolut), Enter zum Öffnen', editorSearchPlaceholder: 'Nach Dateiname suchen…', editorSearchNoResults: 'Keine passenden Dateien', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index d9a974a3..94931a0d 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -46,6 +46,16 @@ export const fr: Record = { explorerExcludeAdd: 'Ajouter', explorerExcludeRemove: 'Supprimer', editorTreeToggle: 'Panneau d’arborescence', + editorFileNotFound: 'Fichier introuvable : {path}', + editorMarkdownPathHint: 'Markdown a peut-être supprimé une barre oblique inverse de ce chemin Windows. Essayez les barres obliques ou placez le chemin dans un bloc de code.', + editorPathRepairSearching: 'Recherche de chemins Windows possibles…', + editorPathRepairNone: 'Aucun chemin correspondant unique trouvé. Vérifiez le chemin puis réessayez.', + editorPathRepairChoices: 'Plusieurs chemins possibles trouvés. Choisissez le bon chemin :', + editorPathRepairFailed: 'Impossible de vérifier les chemins réparés : {message}', + editorCopyPath: 'Copier le chemin', + editorOpenInFileManager: 'Ouvrir dans le gestionnaire de fichiers', + editorCopyPathFailed: 'Impossible de copier le chemin', + editorRevealPathFailed: 'Impossible d’ouvrir ce chemin dans le gestionnaire de fichiers', editorPathPlaceholder: 'Saisissez un chemin de fichier (relatif au répertoire de session ou absolu), Entrée pour ouvrir', editorSearchPlaceholder: 'Rechercher par nom de fichier…', editorSearchNoResults: 'Aucun fichier correspondant', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index d2bbb942..9ae28f65 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -53,6 +53,16 @@ export const hi: Record = { explorerExcludeAdd: 'जोड़ें', explorerExcludeRemove: 'हटाएँ', editorTreeToggle: 'फ़ाइल ट्री पैनल', + editorFileNotFound: 'फ़ाइल नहीं मिली: {path}', + editorMarkdownPathHint: 'Markdown ने Windows पथ से बैकस्लैश हटा दिया हो सकता है। फ़ॉरवर्ड स्लैश आज़माएँ या पथ को कोड ब्लॉक में रखें।', + editorPathRepairSearching: 'संभावित Windows पथ जाँचे जा रहे हैं…', + editorPathRepairNone: 'कोई एकल मेल खाता पथ नहीं मिला। पथ जाँचकर फिर प्रयास करें।', + editorPathRepairChoices: 'कई संभावित पथ मिले। सही पथ चुनें:', + editorPathRepairFailed: 'सुधारे गए पथ जाँचे नहीं जा सके: {message}', + editorCopyPath: 'पथ कॉपी करें', + editorOpenInFileManager: 'फ़ाइल प्रबंधक में खोलें', + editorCopyPathFailed: 'पथ कॉपी नहीं हो सका', + editorRevealPathFailed: 'यह पथ फ़ाइल प्रबंधक में नहीं खुल सका', editorPathPlaceholder: 'फ़ाइल पथ दर्ज करें (सत्र डायरेक्टरी के सापेक्ष या निरपेक्ष), Enter से खोलें', editorSearchPlaceholder: 'फ़ाइल नाम से खोजें…', editorSearchNoResults: 'कोई मेल खाती फ़ाइल नहीं', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 73ac5cf9..bfd2c6cb 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -51,6 +51,16 @@ export const id: Record = { explorerExcludeAdd: 'Tambah', explorerExcludeRemove: 'Hapus', editorTreeToggle: 'Panel pohon berkas', + editorFileNotFound: 'Berkas tidak ditemukan: {path}', + editorMarkdownPathHint: 'Markdown mungkin menghapus garis miring terbalik dari jalur Windows ini. Coba gunakan garis miring biasa atau letakkan jalur di blok kode.', + editorPathRepairSearching: 'Memeriksa kemungkinan jalur Windows…', + editorPathRepairNone: 'Tidak ditemukan jalur yang cocok secara unik. Periksa jalur lalu coba lagi.', + editorPathRepairChoices: 'Beberapa jalur mungkin ditemukan. Pilih jalur yang benar:', + editorPathRepairFailed: 'Tidak dapat memeriksa jalur yang diperbaiki: {message}', + editorCopyPath: 'Salin jalur', + editorOpenInFileManager: 'Buka di pengelola berkas', + editorCopyPathFailed: 'Jalur tidak dapat disalin', + editorRevealPathFailed: 'Jalur ini tidak dapat dibuka di pengelola berkas', editorPathPlaceholder: 'Path berkas (relatif terhadap direktori sesi atau absolut), Enter untuk membuka', editorSearchPlaceholder: 'Cari berkas berdasarkan nama…', editorSearchNoResults: 'Tidak ada berkas yang cocok', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index 51048bab..0a532213 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -44,6 +44,16 @@ export const it: Record = { explorerExcludeAdd: 'Aggiungi', explorerExcludeRemove: 'Rimuovi', editorTreeToggle: 'Pannello dell’albero dei file', + editorFileNotFound: 'File non trovato: {path}', + editorMarkdownPathHint: 'Markdown potrebbe aver rimosso una barra inversa da questo percorso Windows. Prova con le barre normali oppure inserisci il percorso in un blocco di codice.', + editorPathRepairSearching: 'Controllo dei possibili percorsi Windows…', + editorPathRepairNone: 'Nessun percorso univoco trovato. Controlla il percorso e riprova.', + editorPathRepairChoices: 'Trovati più percorsi possibili. Scegli quello corretto:', + editorPathRepairFailed: 'Impossibile controllare i percorsi corretti: {message}', + editorCopyPath: 'Copia percorso', + editorOpenInFileManager: 'Apri nel file manager', + editorCopyPathFailed: 'Impossibile copiare il percorso', + editorRevealPathFailed: 'Impossibile aprire questo percorso nel file manager', editorPathPlaceholder: 'Percorso del file (relativo alla directory della sessione o assoluto), Invio per aprire', editorSearchPlaceholder: 'Cerca file per nome…', editorSearchNoResults: 'Nessun file corrispondente', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index 06942641..7ef27174 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -53,6 +53,16 @@ export const ja: Record = { explorerExcludeAdd: '追加', explorerExcludeRemove: '削除', editorTreeToggle: 'ファイルツリーパネル', + editorFileNotFound: 'ファイルが見つかりません: {path}', + editorMarkdownPathHint: 'Markdown が Windows パスのバックスラッシュを取り除いた可能性があります。スラッシュを使うか、パスをコードブロックに入れてください。', + editorPathRepairSearching: 'Windows パスの候補を確認しています…', + editorPathRepairNone: '一致するパスを一意に特定できませんでした。パスを確認して再試行してください。', + editorPathRepairChoices: '複数の候補が見つかりました。正しいパスを選択してください:', + editorPathRepairFailed: '修復候補を確認できませんでした: {message}', + editorCopyPath: 'パスをコピー', + editorOpenInFileManager: 'ファイルマネージャーで開く', + editorCopyPathFailed: 'パスをコピーできませんでした', + editorRevealPathFailed: 'ファイルマネージャーでこのパスを開けませんでした', editorPathPlaceholder: 'ファイルパス(セッションディレクトリからの相対 or 絶対)、Enter で開く', editorSearchPlaceholder: 'ファイル名で検索…', editorSearchNoResults: '一致するファイルはありません', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index d48e0456..ab8ab823 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -45,6 +45,16 @@ export const ko: Record = { explorerExcludeAdd: '추가', explorerExcludeRemove: '제거', editorTreeToggle: '파일 트리 패널', + editorFileNotFound: '파일을 찾을 수 없습니다: {path}', + editorMarkdownPathHint: 'Markdown이 Windows 경로의 백슬래시를 제거했을 수 있습니다. 슬래시를 사용하거나 경로를 코드 블록에 넣어 보세요.', + editorPathRepairSearching: '가능한 Windows 경로를 확인하는 중…', + editorPathRepairNone: '일치하는 경로를 하나로 특정하지 못했습니다. 경로를 확인한 뒤 다시 시도하세요.', + editorPathRepairChoices: '가능한 경로가 여러 개 있습니다. 올바른 경로를 선택하세요:', + editorPathRepairFailed: '수정된 경로를 확인하지 못했습니다: {message}', + editorCopyPath: '경로 복사', + editorOpenInFileManager: '파일 관리자에서 열기', + editorCopyPathFailed: '경로를 복사하지 못했습니다', + editorRevealPathFailed: '파일 관리자에서 이 경로를 열지 못했습니다', editorPathPlaceholder: '파일 경로 입력(세션 디렉터리 기준 상대 경로 또는 절대 경로), Enter로 열기', editorSearchPlaceholder: '파일 이름으로 검색…', editorSearchNoResults: '일치하는 파일 없음', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index 938a2af0..92450617 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -51,6 +51,16 @@ export const nl: Record = { explorerExcludeAdd: 'Toevoegen', explorerExcludeRemove: 'Verwijderen', editorTreeToggle: 'Bestandsboompaneel', + editorFileNotFound: 'Bestand niet gevonden: {path}', + editorMarkdownPathHint: 'Markdown heeft mogelijk een backslash uit dit Windows-pad verwijderd. Probeer schuine strepen of plaats het pad in een codeblok.', + editorPathRepairSearching: 'Mogelijke Windows-paden controleren…', + editorPathRepairNone: 'Geen uniek overeenkomend pad gevonden. Controleer het pad en probeer het opnieuw.', + editorPathRepairChoices: 'Meerdere mogelijke paden gevonden. Kies het juiste pad:', + editorPathRepairFailed: 'Herstelde paden konden niet worden gecontroleerd: {message}', + editorCopyPath: 'Pad kopiëren', + editorOpenInFileManager: 'Openen in bestandsbeheer', + editorCopyPathFailed: 'Het pad kon niet worden gekopieerd', + editorRevealPathFailed: 'Dit pad kon niet worden geopend in bestandsbeheer', editorPathPlaceholder: 'Voer een bestandspad in (relatief aan de sessiemap of absoluut), Enter om te openen', editorSearchPlaceholder: 'Zoek op bestandsnaam…', editorSearchNoResults: 'Geen overeenkomende bestanden', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index 224bed33..763c0ce8 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -55,6 +55,16 @@ export const pl: Record = { explorerExcludeAdd: 'Dodaj', explorerExcludeRemove: 'Usuń', editorTreeToggle: 'Panel drzewa plików', + editorFileNotFound: 'Nie znaleziono pliku: {path}', + editorMarkdownPathHint: 'Markdown mógł usunąć ukośnik odwrotny z tej ścieżki Windows. Użyj ukośników lub umieść ścieżkę w bloku kodu.', + editorPathRepairSearching: 'Sprawdzanie możliwych ścieżek Windows…', + editorPathRepairNone: 'Nie znaleziono jednej pasującej ścieżki. Sprawdź ścieżkę i spróbuj ponownie.', + editorPathRepairChoices: 'Znaleziono kilka możliwych ścieżek. Wybierz właściwą:', + editorPathRepairFailed: 'Nie można sprawdzić naprawionych ścieżek: {message}', + editorCopyPath: 'Kopiuj ścieżkę', + editorOpenInFileManager: 'Otwórz w menedżerze plików', + editorCopyPathFailed: 'Nie można skopiować ścieżki', + editorRevealPathFailed: 'Nie można otworzyć tej ścieżki w menedżerze plików', editorPathPlaceholder: 'Ścieżka pliku (względna do katalogu sesji lub bezwzględna), Enter, aby otworzyć', editorSearchPlaceholder: 'Szukaj po nazwie pliku…', editorSearchNoResults: 'Brak pasujących plików', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index 5540b06c..7230ab42 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -36,6 +36,16 @@ export const pt: Record = { explorerExcludeAdd: 'Adicionar', explorerExcludeRemove: 'Remover', editorTreeToggle: 'Painel da árvore de arquivos', + editorFileNotFound: 'Arquivo não encontrado: {path}', + editorMarkdownPathHint: 'O Markdown pode ter removido uma barra invertida deste caminho do Windows. Experimente usar barras normais ou colocar o caminho em um bloco de código.', + editorPathRepairSearching: 'Verificando possíveis caminhos do Windows…', + editorPathRepairNone: 'Nenhum caminho correspondente único foi encontrado. Confira o caminho e tente novamente.', + editorPathRepairChoices: 'Vários caminhos possíveis foram encontrados. Escolha o caminho correto:', + editorPathRepairFailed: 'Não foi possível verificar os caminhos corrigidos: {message}', + editorCopyPath: 'Copiar caminho', + editorOpenInFileManager: 'Abrir no gerenciador de arquivos', + editorCopyPathFailed: 'Não foi possível copiar o caminho', + editorRevealPathFailed: 'Não foi possível abrir este caminho no gerenciador de arquivos', editorPathPlaceholder: 'Caminho do arquivo (relativo ao diretório da sessão ou absoluto), Enter para abrir', editorSearchPlaceholder: 'Pesquisar arquivos por nome…', editorSearchNoResults: 'Nenhum arquivo correspondente', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 2ca67f8e..63a947f1 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -49,6 +49,16 @@ export const ru: Record = { explorerExcludeAdd: 'Добавить', explorerExcludeRemove: 'Убрать', editorTreeToggle: 'Панель дерева файлов', + editorFileNotFound: 'Файл не найден: {path}', + editorMarkdownPathHint: 'Markdown мог удалить обратную косую черту из этого пути Windows. Используйте прямые косые черты или поместите путь в блок кода.', + editorPathRepairSearching: 'Проверка возможных путей Windows…', + editorPathRepairNone: 'Не найден единственный подходящий путь. Проверьте путь и повторите попытку.', + editorPathRepairChoices: 'Найдено несколько возможных путей. Выберите правильный:', + editorPathRepairFailed: 'Не удалось проверить исправленные пути: {message}', + editorCopyPath: 'Копировать путь', + editorOpenInFileManager: 'Открыть в файловом менеджере', + editorCopyPathFailed: 'Не удалось скопировать путь', + editorRevealPathFailed: 'Не удалось открыть этот путь в файловом менеджере', editorPathPlaceholder: 'Введите путь к файлу (относительно каталога сессии или абсолютный), Enter, чтобы открыть', editorSearchPlaceholder: 'Поиск по имени файла…', editorSearchNoResults: 'Нет совпадающих файлов', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 03af167d..1887ec0b 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -36,6 +36,16 @@ export const sv: Record = { explorerExcludeAdd: 'Lägg till', explorerExcludeRemove: 'Ta bort', editorTreeToggle: 'Filträdspanel', + editorFileNotFound: 'Filen hittades inte: {path}', + editorMarkdownPathHint: 'Markdown kan ha tagit bort ett omvänt snedstreck från den här Windows-sökvägen. Prova vanliga snedstreck eller placera sökvägen i ett kodblock.', + editorPathRepairSearching: 'Kontrollerar möjliga Windows-sökvägar…', + editorPathRepairNone: 'Ingen entydig sökväg hittades. Kontrollera sökvägen och försök igen.', + editorPathRepairChoices: 'Flera möjliga sökvägar hittades. Välj rätt sökväg:', + editorPathRepairFailed: 'Det gick inte att kontrollera reparerade sökvägar: {message}', + editorCopyPath: 'Kopiera sökväg', + editorOpenInFileManager: 'Öppna i filhanteraren', + editorCopyPathFailed: 'Det gick inte att kopiera sökvägen', + editorRevealPathFailed: 'Det gick inte att öppna sökvägen i filhanteraren', editorPathPlaceholder: 'Filsökväg (relativ sessionskatalogen eller absolut), Enter för att öppna', editorSearchPlaceholder: 'Sök filer efter namn…', editorSearchNoResults: 'Inga matchande filer', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index 24e163f7..601dee93 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -53,6 +53,16 @@ export const th: Record = { explorerExcludeAdd: 'เพิ่ม', explorerExcludeRemove: 'ลบ', editorTreeToggle: 'พาเนลต้นไม้ไฟล์', + editorFileNotFound: 'ไม่พบไฟล์: {path}', + editorMarkdownPathHint: 'Markdown อาจลบแบ็กสแลชออกจากพาธ Windows นี้ ลองใช้เครื่องหมายทับหรือใส่พาธไว้ในบล็อกโค้ด', + editorPathRepairSearching: 'กำลังตรวจสอบพาธ Windows ที่เป็นไปได้…', + editorPathRepairNone: 'ไม่พบพาธที่ตรงกันเพียงรายการเดียว โปรดตรวจสอบพาธแล้วลองอีกครั้ง', + editorPathRepairChoices: 'พบพาธที่เป็นไปได้หลายรายการ โปรดเลือกพาธที่ถูกต้อง:', + editorPathRepairFailed: 'ตรวจสอบพาธที่ซ่อมแล้วไม่สำเร็จ: {message}', + editorCopyPath: 'คัดลอกพาธ', + editorOpenInFileManager: 'เปิดในตัวจัดการไฟล์', + editorCopyPathFailed: 'คัดลอกพาธไม่สำเร็จ', + editorRevealPathFailed: 'เปิดพาธนี้ในตัวจัดการไฟล์ไม่สำเร็จ', editorPathPlaceholder: 'พาธไฟล์ (สัมพันธ์กับไดเรกทอรีเซสชันหรือแบบ absolute), Enter เพื่อเปิด', editorSearchPlaceholder: 'ค้นหาไฟล์ตามชื่อ…', editorSearchNoResults: 'ไม่มีไฟล์ที่ตรง', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index 9e69ee6c..ede229f7 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -53,6 +53,16 @@ export const tr: Record = { explorerExcludeAdd: 'Ekle', explorerExcludeRemove: 'Kaldır', editorTreeToggle: 'Dosya ağacı paneli', + editorFileNotFound: 'Dosya bulunamadı: {path}', + editorMarkdownPathHint: 'Markdown bu Windows yolundaki ters eğik çizgiyi kaldırmış olabilir. Eğik çizgi kullanmayı veya yolu kod bloğuna koymayı deneyin.', + editorPathRepairSearching: 'Olası Windows yolları denetleniyor…', + editorPathRepairNone: 'Tek bir eşleşen yol bulunamadı. Yolu denetleyip yeniden deneyin.', + editorPathRepairChoices: 'Birden çok olası yol bulundu. Doğru yolu seçin:', + editorPathRepairFailed: 'Düzeltilen yollar denetlenemedi: {message}', + editorCopyPath: 'Yolu kopyala', + editorOpenInFileManager: 'Dosya yöneticisinde aç', + editorCopyPathFailed: 'Yol kopyalanamadı', + editorRevealPathFailed: 'Bu yol dosya yöneticisinde açılamadı', editorPathPlaceholder: 'Dosya yolu (oturum dizinine göreli veya mutlak), Enter ile aç', editorSearchPlaceholder: 'Dosya adına göre ara…', editorSearchNoResults: 'Eşleşen dosya yok', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index 0463ea7c..d85ee90d 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -53,6 +53,16 @@ export const vi: Record = { explorerExcludeAdd: 'Thêm', explorerExcludeRemove: 'Xóa', editorTreeToggle: 'Panel cây tệp', + editorFileNotFound: 'Không tìm thấy tệp: {path}', + editorMarkdownPathHint: 'Markdown có thể đã xóa dấu gạch chéo ngược khỏi đường dẫn Windows này. Hãy thử dùng dấu gạch chéo xuôi hoặc đặt đường dẫn trong khối mã.', + editorPathRepairSearching: 'Đang kiểm tra các đường dẫn Windows có thể có…', + editorPathRepairNone: 'Không tìm thấy đường dẫn khớp duy nhất. Hãy kiểm tra đường dẫn rồi thử lại.', + editorPathRepairChoices: 'Tìm thấy nhiều đường dẫn có thể có. Hãy chọn đường dẫn đúng:', + editorPathRepairFailed: 'Không thể kiểm tra các đường dẫn đã sửa: {message}', + editorCopyPath: 'Sao chép đường dẫn', + editorOpenInFileManager: 'Mở trong trình quản lý tệp', + editorCopyPathFailed: 'Không thể sao chép đường dẫn', + editorRevealPathFailed: 'Không thể mở đường dẫn này trong trình quản lý tệp', editorPathPlaceholder: 'Nhập đường dẫn tệp (tương đối thư mục phiên hoặc tuyệt đối), Enter để mở', editorSearchPlaceholder: 'Tìm theo tên tệp…', editorSearchNoResults: 'Không có tệp phù hợp', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index 70553cba..a5f59ee0 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -68,6 +68,16 @@ export const zhHK: Record = { explorerExcludeAdd: '新增', explorerExcludeRemove: '移除', editorTreeToggle: '檔案樹面板', + editorFileNotFound: '找不到檔案:{path}', + editorMarkdownPathHint: 'Markdown 可能移除了 Windows 路徑中的反斜線。請改用正斜線,或將路徑放在程式碼區塊中。', + editorPathRepairSearching: '正在檢查可能的 Windows 路徑…', + editorPathRepairNone: '找不到唯一符合的路徑。請檢查路徑後重試。', + editorPathRepairChoices: '找到多個可能的路徑,請選擇正確路徑:', + editorPathRepairFailed: '無法檢查修復後的路徑:{message}', + editorCopyPath: '複製路徑', + editorOpenInFileManager: '在檔案管理員中開啟', + editorCopyPathFailed: '無法複製路徑', + editorRevealPathFailed: '無法在檔案管理員中開啟此路徑', editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟', editorSearchPlaceholder: '按檔案名稱搜尋…', editorSearchNoResults: '無匹配檔案', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index 1569cc73..dc25ae82 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -68,6 +68,16 @@ export const zhMO: Record = { explorerExcludeAdd: '新增', explorerExcludeRemove: '移除', editorTreeToggle: '檔案樹面板', + editorFileNotFound: '找不到檔案:{path}', + editorMarkdownPathHint: 'Markdown 可能移除了 Windows 路徑中的反斜線。請改用正斜線,或將路徑放在程式碼區塊中。', + editorPathRepairSearching: '正在檢查可能的 Windows 路徑…', + editorPathRepairNone: '找不到唯一符合的路徑。請檢查路徑後重試。', + editorPathRepairChoices: '找到多個可能的路徑,請選擇正確路徑:', + editorPathRepairFailed: '無法檢查修復後的路徑:{message}', + editorCopyPath: '複製路徑', + editorOpenInFileManager: '在檔案管理員中開啟', + editorCopyPathFailed: '無法複製路徑', + editorRevealPathFailed: '無法在檔案管理員中開啟此路徑', editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟', editorSearchPlaceholder: '按檔案名稱搜尋…', editorSearchNoResults: '無匹配檔案', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index 88327c9c..e38b4bdf 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -68,6 +68,16 @@ export const zhTW: Record = { explorerExcludeAdd: '新增', explorerExcludeRemove: '移除', editorTreeToggle: '檔案樹面板', + editorFileNotFound: '找不到檔案:{path}', + editorMarkdownPathHint: 'Markdown 可能移除了 Windows 路徑中的反斜線。請改用正斜線,或將路徑放在程式碼區塊中。', + editorPathRepairSearching: '正在檢查可能的 Windows 路徑…', + editorPathRepairNone: '找不到唯一符合的路徑。請檢查路徑後重試。', + editorPathRepairChoices: '找到多個可能的路徑,請選擇正確路徑:', + editorPathRepairFailed: '無法檢查修復後的路徑:{message}', + editorCopyPath: '複製路徑', + editorOpenInFileManager: '在檔案管理員中開啟', + editorCopyPathFailed: '無法複製路徑', + editorRevealPathFailed: '無法在檔案管理員中開啟此路徑', editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟', editorSearchPlaceholder: '按檔案名稱搜尋…', editorSearchNoResults: '無匹配檔案', diff --git a/src/client/locales.ts b/src/client/locales.ts index 9da3f719..3d3ddb43 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -65,6 +65,16 @@ export const zh = { explorerExcludeAdd: '添加', explorerExcludeRemove: '移除', editorTreeToggle: '文件树面板', + editorFileNotFound: '文件不存在:{path}', + editorMarkdownPathHint: 'Markdown 可能吞掉了 Windows 路径中的反斜杠。请改用正斜杠,或将路径放在代码块中。', + editorPathRepairSearching: '正在检查可能的 Windows 路径…', + editorPathRepairNone: '没有找到唯一匹配的路径。请核对路径后重试。', + editorPathRepairChoices: '找到多个可能的路径,请选择正确路径:', + editorPathRepairFailed: '检查修复路径失败:{message}', + editorCopyPath: '复制路径', + editorOpenInFileManager: '在资源管理器中打开', + editorCopyPathFailed: '复制路径失败', + editorRevealPathFailed: '无法在资源管理器中打开该路径', editorPathPlaceholder: '输入文件路径(相对会话目录或绝对路径),Enter 打开', editorSearchPlaceholder: '按文件名搜索…', editorSearchNoResults: '无匹配文件', @@ -708,6 +718,16 @@ export const en: Record = { explorerExcludeAdd: 'Add', explorerExcludeRemove: 'Remove', editorTreeToggle: 'File tree panel', + editorFileNotFound: 'File not found: {path}', + editorMarkdownPathHint: 'Markdown may have consumed a backslash in this Windows path. Try forward slashes or put the path in a code block.', + editorPathRepairSearching: 'Checking possible Windows paths…', + editorPathRepairNone: 'No unique matching path was found. Check the path and retry.', + editorPathRepairChoices: 'Multiple possible paths were found. Choose the correct path:', + editorPathRepairFailed: 'Could not check repaired paths: {message}', + editorCopyPath: 'Copy path', + editorOpenInFileManager: 'Open in file manager', + editorCopyPathFailed: 'Could not copy the path', + editorRevealPathFailed: 'Could not open this path in the file manager', editorPathPlaceholder: 'File path (relative to the session directory or absolute), Enter to open', editorSearchPlaceholder: 'Search files by name…', editorSearchNoResults: 'No matching files', diff --git a/src/client/markdown-path-repair.ts b/src/client/markdown-path-repair.ts new file mode 100644 index 00000000..e565d29c --- /dev/null +++ b/src/client/markdown-path-repair.ts @@ -0,0 +1,53 @@ +/** The maximum number of candidate paths checked after a Markdown path failure. */ +const MAX_INSERTIONS = 8 + +/** + * Check whether a path uses a Windows drive or UNC absolute-path form. + * + * @param path - Path received from the host Markdown renderer + * @returns Whether the path is absolute in Windows syntax + */ +export function isWindowsAbsolutePath(path: string): boolean { + return /^[A-Za-z]:[\\/]/u.test(path) + || /^(?:\\\\[^\\/]+[\\/][^\\/]+|\/\/[^/]+\/[^/]+)/u.test(path) +} + +/** + * Build Windows path candidates by restoring separators before Markdown punctuation. + * + * @param path - The decoded path received from the host Markdown renderer. + * @returns Candidate paths, or an empty list when the path is not Windows-absolute + * or contains more than eight punctuation positions. + */ +export function markdownPathRepairCandidates(path: string): string[] { + if (!isWindowsAbsolutePath(path)) return [] + + const isDrivePath = /^[A-Za-z]:[\\/]/u.test(path) + const positions: number[] = [] + for (let index = 0; index < path.length; index += 1) { + const code = path.charCodeAt(index) + const punctuation = (code >= 33 && code <= 47) + || (code >= 58 && code <= 64) + || (code >= 91 && code <= 96) + || (code >= 123 && code <= 126) + if (!punctuation || path[index] === '/' || path[index] === '\\' || (isDrivePath && index === 1)) continue + positions.push(index) + if (positions.length > MAX_INSERTIONS) return [] + } + + if (positions.length === 0) return [] + const candidates: string[] = [] + for (let mask = 1; mask < 2 ** positions.length; mask += 1) { + let candidate = '' + let positionIndex = 0 + for (let index = 0; index < path.length; index += 1) { + if (positions[positionIndex] === index) { + if ((mask & (1 << positionIndex)) !== 0) candidate += '\\' + positionIndex += 1 + } + candidate += path[index] + } + candidates.push(candidate) + } + return candidates +} diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index 96c30035..0585c909 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -1517,6 +1517,25 @@ body[data-dsh-sidebar-dragging] .bottomPanel { color: var(--dsw-alias-state-error-primary); } +.editorErrorHint { + margin-top: 8px; + color: var(--dsw-alias-label-secondary); +} + +.editorErrorCandidates, +.editorErrorActions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 10px; +} + +.editorErrorCandidates { + align-items: flex-start; + flex-direction: column; +} + .editorBanner { flex: none; padding: 4px 8px; diff --git a/src/file-stream.ts b/src/file-stream.ts index bc325385..70f35a4d 100644 --- a/src/file-stream.ts +++ b/src/file-stream.ts @@ -20,7 +20,7 @@ import { once } from 'node:events' import type { ServerResponse } from 'node:http' import { pipeline } from 'node:stream/promises' import type { SidebarHttpResponse } from './context-types.ts' -import { SidebarError } from './wire.ts' +import { fileReadError } from './fs-read-error.ts' /** * Stream one file into the response with the given headers. @@ -53,11 +53,7 @@ export async function streamFileToResponse( await once(stream, 'open') } catch (error: unknown) { stream.destroy() - throw new SidebarError( - 'fs-error', - `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, - 400, - ) + throw fileReadError(path, error) } res.writeHead(200, { ...headers, 'content-length': String(size) }) try { diff --git a/src/fs-read-error.ts b/src/fs-read-error.ts new file mode 100644 index 00000000..29d8aefc --- /dev/null +++ b/src/fs-read-error.ts @@ -0,0 +1,13 @@ +import { SidebarError } from './wire.ts' + +/** + * Convert a filesystem read failure into the message returned by sidebar routes. + * ENOENT stays readable without exposing Node's platform-specific error text. + */ +export function fileReadError(path: string, error: unknown): SidebarError { + const code = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined + const message = code === 'ENOENT' + ? `File not found: "${path}"` + : `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}` + return new SidebarError('fs-error', message, 400) +} diff --git a/src/index.ts b/src/index.ts index e7bb19ce..4a60ec62 100644 --- a/src/index.ts +++ b/src/index.ts @@ -49,6 +49,7 @@ import { buildSidechatApi } from './sidechat-routes.ts' import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts' import { readJsonBody, readTextBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts' import { streamFileToResponse } from './file-stream.ts' +import { fileReadError } from './fs-read-error.ts' import { readPersistedSession } from './session-store.ts' import { createChangesOpsApi } from './changes-ops.ts' import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' @@ -405,11 +406,7 @@ const READ_HEAD_LIMIT = 4096 */ async function statFileForRoute(path: string): Promise { return await stat(path).catch((error: unknown) => { - throw new SidebarError( - 'fs-error', - `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, - 400, - ) + throw fileReadError(path, error) }) } @@ -441,7 +438,7 @@ export type SidebarReadResult = */ async function readText(path: string): Promise { const info = await stat(path).catch((error: unknown) => { - throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) + throw fileReadError(path, error) }) if (info.isDirectory()) { throw new SidebarError('fs-error', `"${path}" is a directory`, 400) @@ -449,7 +446,7 @@ async function readText(path: string): Promise { const size = info.size const oversized = size > MAX_EDITABLE_BYTES const handle = await open(path, 'r').catch((error: unknown) => { - throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) + throw fileReadError(path, error) }) try { // An over-limit file still yields its first bytes: that is what decides @@ -527,7 +524,7 @@ interface ReadPageResult { */ async function readPage(path: string, offset: number): Promise { const info = await stat(path).catch((error: unknown) => { - throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) + throw fileReadError(path, error) }) if (info.isDirectory()) { throw new SidebarError('fs-error', `"${path}" is a directory`, 400) @@ -546,7 +543,7 @@ async function readPage(path: string, offset: number): Promise { } } const handle = await open(path, 'r').catch((error: unknown) => { - throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) + throw fileReadError(path, error) }) try { const length = Math.min(PAGE_BYTES, size - offset) diff --git a/tests/fs-read-error.spec.ts b/tests/fs-read-error.spec.ts new file mode 100644 index 00000000..429e3d12 --- /dev/null +++ b/tests/fs-read-error.spec.ts @@ -0,0 +1,17 @@ +import { stat } from 'node:fs/promises' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { fileReadError } from '../src/fs-read-error.ts' + +describe('fileReadError', () => { + it('returns a readable message for a real missing-path error', async () => { + const path = join(process.cwd(), `missing-file-${process.pid}-${Date.now()}.txt`) + const error = await stat(path).then( + () => { throw new Error('Expected stat to fail for a missing path') }, + reason => reason, + ) + + expect((error as NodeJS.ErrnoException).code).toBe('ENOENT') + expect(fileReadError(path, error).message).toBe(`File not found: "${path}"`) + }) +}) diff --git a/tests/markdown-path-repair.spec.ts b/tests/markdown-path-repair.spec.ts new file mode 100644 index 00000000..789ed865 --- /dev/null +++ b/tests/markdown-path-repair.spec.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { isWindowsAbsolutePath, markdownPathRepairCandidates } from '../src/client/markdown-path-repair.ts' + +describe('markdownPathRepairCandidates', () => { + it('recognizes Windows drive and UNC absolute paths', () => { + expect(isWindowsAbsolutePath('C:\\Users\\ADMIN\\report.md')).toBe(true) + expect(isWindowsAbsolutePath('\\\\server\\share\\report.md')).toBe(true) + expect(isWindowsAbsolutePath('/workspace/report.md')).toBe(false) + }) + + it('restores a separator before an escaped underscore in an absolute Windows path', () => { + const candidates = markdownPathRepairCandidates('C:\\Users\\ADMIN\\workspace_analysis\\report.md') + + expect(candidates).toContain('C:\\Users\\ADMIN\\workspace\\_analysis\\report.md') + }) + + it('supports paths with multiple consumed separators', () => { + const candidates = markdownPathRepairCandidates('C:\\workspaces\\team_project-file.md') + + expect(candidates).toContain('C:\\workspaces\\team\\_project\\-file.md') + }) + + it('does not propose repairs for POSIX paths or paths with too many punctuation positions', () => { + expect(markdownPathRepairCandidates('/workspace/file_name.md')).toEqual([]) + expect(markdownPathRepairCandidates('C:\\a_b-c.d_e-f.g_x-h.i')).toEqual([]) + }) + + it('checks paths with up to eight punctuation positions', () => { + expect(markdownPathRepairCandidates('C:\\a_b-c.d_e-f.g_x-h')).toHaveLength(255) + }) +})