merge #1048: fix(editor) readable Windows markdown path failures and repair choices

# Conflicts:
#	CHANGELOG.md
#	src/client/EditorHost.tsx
#	src/index.ts
This commit is contained in:
Menghuan1918 committed 2026-11-08 00:22:24 +08:00
commit acea51ad13
29 files changed
+460 -21

No files matched your search

+2
View File
@@ -21,6 +21,8 @@
- **另一个可观察变化**:团队模式下**所有**直接子 agent 都是成员,不再存在"部分成员",所以「已完成」折叠组只在**无团队**的树里出现(成员恒为待命),同一父节点下不会再有 done / idle 两个组并存。
- 🧪 测试:`tests/team-projection.spec.ts` 重写为 catalog 驱动的名册(`enabled:false` 隐藏、旧宿主无 `enabled` 仍显示、Summary 的 run 位优先于 live 驻留);`tests/tasks-model.spec.ts` 与 `tests/tasks-page.spec.tsx` 改用 catalog 名构造成员,并把"同父下 done/idle 不再共存"写进用例注释。
- **Markdown 文件链接错误恢复**:Windows 路径因转义丢失分隔符时,侧栏会检查有限数量的候选路径;唯一命中时自动打开,多个命中时提供选择。文件不存在时显示可读提示,并提供复制路径、文件管理器打开和重试操作。
### v0.30.1
- 🎯 **设置页「侧边卡片」的导航图标不再叠成两个**:插件此前按"宿主设置导航还没有图标通道"的老假设,用 CSS 把兜底齿轮藏起来、再画自己的图标;宿主早已提供按 section id 寻址的 `settings.section.icon` 插槽,而且图标的 DOM 外面多了一层 span,老选择器失效后兜底 SVG 露了出来,与插件图标并排显示。现在改为**走宿主插槽**提供图标,删掉标记 + CSS 遮罩那一套(顺带去掉了一个监听整个 document 的 MutationObserver)。
+107 -6
View File
@@ -25,11 +25,12 @@
import { useCallback, useEffect, useLayoutEffect, 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 { isDirectoryReadError, planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts'
import { isWindowsAbsolutePath, markdownPathRepairCandidates } from './markdown-path-repair.ts'
import { clearDraftBackup } from './editor-draft-backup.ts'
import { clearEditorDirty, isEditorDirty, setEditorDirty } from './editor-dirty.ts'
import { baseName } from './FileTree.tsx'
@@ -54,7 +55,7 @@ interface LineNav { key: string; nonce: number | null; end?: number }
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' }
@@ -149,6 +150,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<EditorLoad>({ status: 'loading' })
const [fileErrorAction, setFileErrorAction] = useState<string | null>(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)
@@ -503,6 +505,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
@@ -540,8 +543,9 @@ 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
const message = error instanceof Error ? error.message : String(error)
if (isDirectoryReadError(error)) {
// A path that resolves to a DIRECTORY is not a failed read: the
// editor tab must become the plugin's folder window instead of
@@ -570,7 +574,60 @@ export function EditorHost(props: {
}, scope.sessionId)
return
}
setLoad({ status: 'error', 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<string>()
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
}
@@ -749,7 +806,51 @@ export function EditorHost(props: {
<div className={css.editorMain}>
{showEmpty && <div className={css.editorPlaceholder}>{t('editorEmptyHint')}</div>}
{!showEmpty && load.status === 'loading' && <div className={css.editorPlaceholder}>{t('loading')}</div>}
{!showEmpty && load.status === 'error' && <div className={css.editorError}>{load.message}</div>}
{!showEmpty && load.status === 'error' && (
<div className={css.editorError} role="alert">
<div>{load.fileNotFound ? t('editorFileNotFound', { path }) : load.message}</div>
{load.fileNotFound && load.windowsAbsolutePath && (
<div className={css.editorErrorHint}>{t('editorMarkdownPathHint')}</div>
)}
{load.repairStatus === 'searching' && <div className={css.editorErrorHint}>{t('editorPathRepairSearching')}</div>}
{load.repairStatus === 'done' && load.repairMatches?.length === 0 && (
<div className={css.editorErrorHint}>{t('editorPathRepairNone')}</div>
)}
{load.repairMatches !== undefined && load.repairMatches.length > 0 && (
<div className={css.editorErrorCandidates}>
<div>{t('editorPathRepairChoices')}</div>
{load.repairMatches.map(candidate => (
<Button key={candidate} variant="outline" onClick={() => {
ctx.get('betterSidebar')?.updateTab(tab.id, { path: candidate, title: baseName(candidate) }, scope.sessionId)
}}>
{candidate}
</Button>
))}
</div>
)}
{load.repairError !== undefined && (
<div className={css.editorErrorHint}>{t('editorPathRepairFailed', { message: load.repairError })}</div>
)}
<div className={css.editorErrorActions}>
<Button variant="outline" onClick={() => {
void writeClipboard(path).then((copied) => {
setFileErrorAction(copied ? null : t('editorCopyPathFailed'))
})
}}>
{t('editorCopyPath')}
</Button>
<Button variant="outline" onClick={() => {
void openInApp.reveal(path).then((opened) => {
setFileErrorAction(opened ? null : t('editorRevealPathFailed'))
})
}}>
{t('editorOpenInFileManager')}
</Button>
<Button variant="outline" onClick={refreshFile}>{t('retry')}</Button>
</div>
{fileErrorAction !== null && <div className={css.editorErrorHint} role="status">{fileErrorAction}</div>}
</div>
)}
{!showEmpty && load.status === 'binary' && <BinaryDownload scope={scope} path={path} />}
{!showEmpty && load.status === 'ready' && createElement(load.viewer.component, {
ctx, store, scope, path, title,
+10
View File
@@ -54,6 +54,16 @@ export const ar: Record<string, string> = {
explorerExcludeAdd: 'إضافة',
explorerExcludeRemove: 'إزالة',
editorTreeToggle: 'لوحة شجرة الملفات',
editorFileNotFound: 'الملف غير موجود: {path}',
editorMarkdownPathHint: 'قد يكون Markdown قد حذف شرطة مائلة عكسية من مسار Windows. جرّب استخدام الشرطات المائلة أو وضع المسار في كتلة تعليمات برمجية.',
editorPathRepairSearching: 'جارٍ فحص مسارات Windows المحتملة…',
editorPathRepairNone: 'لم يتم العثور على مسار مطابق بشكل فريد. تحقّق من المسار ثم أعد المحاولة.',
editorPathRepairChoices: 'تم العثور على عدة مسارات محتملة. اختر المسار الصحيح:',
editorPathRepairFailed: 'تعذّر فحص المسارات المُصلحة: {message}',
editorCopyPath: 'نسخ المسار',
editorOpenInFileManager: 'فتح في مدير الملفات',
editorCopyPathFailed: 'تعذّر نسخ المسار',
editorRevealPathFailed: 'تعذّر فتح هذا المسار في مدير الملفات',
editorPathPlaceholder: 'مسار الملف (نسبي لدليل الجلسة أو مطلق)، Enter للفتح',
editorSearchPlaceholder: 'البحث في الملفات بالاسم…',
editorSearchNoResults: 'لا ملفات مطابقة',
+10
View File
@@ -39,6 +39,16 @@ export const de: Record<string, string> = {
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',
+10
View File
@@ -46,6 +46,16 @@ export const fr: Record<string, string> = {
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',
+10
View File
@@ -53,6 +53,16 @@ export const hi: Record<string, string> = {
explorerExcludeAdd: 'जोड़ें',
explorerExcludeRemove: 'हटाएँ',
editorTreeToggle: 'फ़ाइल ट्री पैनल',
editorFileNotFound: 'फ़ाइल नहीं मिली: {path}',
editorMarkdownPathHint: 'Markdown ने Windows पथ से बैकस्लैश हटा दिया हो सकता है। फ़ॉरवर्ड स्लैश आज़माएँ या पथ को कोड ब्लॉक में रखें।',
editorPathRepairSearching: 'संभावित Windows पथ जाँचे जा रहे हैं…',
editorPathRepairNone: 'कोई एकल मेल खाता पथ नहीं मिला। पथ जाँचकर फिर प्रयास करें।',
editorPathRepairChoices: 'कई संभावित पथ मिले। सही पथ चुनें:',
editorPathRepairFailed: 'सुधारे गए पथ जाँचे नहीं जा सके: {message}',
editorCopyPath: 'पथ कॉपी करें',
editorOpenInFileManager: 'फ़ाइल प्रबंधक में खोलें',
editorCopyPathFailed: 'पथ कॉपी नहीं हो सका',
editorRevealPathFailed: 'यह पथ फ़ाइल प्रबंधक में नहीं खुल सका',
editorPathPlaceholder: 'फ़ाइल पथ दर्ज करें (सत्र डायरेक्टरी के सापेक्ष या निरपेक्ष), Enter से खोलें',
editorSearchPlaceholder: 'फ़ाइल नाम से खोजें…',
editorSearchNoResults: 'कोई मेल खाती फ़ाइल नहीं',
+10
View File
@@ -51,6 +51,16 @@ export const id: Record<string, string> = {
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',
+10
View File
@@ -44,6 +44,16 @@ export const it: Record<string, string> = {
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',
+10
View File
@@ -53,6 +53,16 @@ export const ja: Record<string, string> = {
explorerExcludeAdd: '追加',
explorerExcludeRemove: '削除',
editorTreeToggle: 'ファイルツリーパネル',
editorFileNotFound: 'ファイルが見つかりません: {path}',
editorMarkdownPathHint: 'Markdown が Windows パスのバックスラッシュを取り除いた可能性があります。スラッシュを使うか、パスをコードブロックに入れてください。',
editorPathRepairSearching: 'Windows パスの候補を確認しています…',
editorPathRepairNone: '一致するパスを一意に特定できませんでした。パスを確認して再試行してください。',
editorPathRepairChoices: '複数の候補が見つかりました。正しいパスを選択してください:',
editorPathRepairFailed: '修復候補を確認できませんでした: {message}',
editorCopyPath: 'パスをコピー',
editorOpenInFileManager: 'ファイルマネージャーで開く',
editorCopyPathFailed: 'パスをコピーできませんでした',
editorRevealPathFailed: 'ファイルマネージャーでこのパスを開けませんでした',
editorPathPlaceholder: 'ファイルパス(セッションディレクトリからの相対 or 絶対)、Enter で開く',
editorSearchPlaceholder: 'ファイル名で検索…',
editorSearchNoResults: '一致するファイルはありません',
+10
View File
@@ -45,6 +45,16 @@ export const ko: Record<string, string> = {
explorerExcludeAdd: '추가',
explorerExcludeRemove: '제거',
editorTreeToggle: '파일 트리 패널',
editorFileNotFound: '파일을 찾을 수 없습니다: {path}',
editorMarkdownPathHint: 'Markdown이 Windows 경로의 백슬래시를 제거했을 수 있습니다. 슬래시를 사용하거나 경로를 코드 블록에 넣어 보세요.',
editorPathRepairSearching: '가능한 Windows 경로를 확인하는 중…',
editorPathRepairNone: '일치하는 경로를 하나로 특정하지 못했습니다. 경로를 확인한 뒤 다시 시도하세요.',
editorPathRepairChoices: '가능한 경로가 여러 개 있습니다. 올바른 경로를 선택하세요:',
editorPathRepairFailed: '수정된 경로를 확인하지 못했습니다: {message}',
editorCopyPath: '경로 복사',
editorOpenInFileManager: '파일 관리자에서 열기',
editorCopyPathFailed: '경로를 복사하지 못했습니다',
editorRevealPathFailed: '파일 관리자에서 이 경로를 열지 못했습니다',
editorPathPlaceholder: '파일 경로 입력(세션 디렉터리 기준 상대 경로 또는 절대 경로), Enter로 열기',
editorSearchPlaceholder: '파일 이름으로 검색…',
editorSearchNoResults: '일치하는 파일 없음',
+10
View File
@@ -51,6 +51,16 @@ export const nl: Record<string, string> = {
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',
+10
View File
@@ -55,6 +55,16 @@ export const pl: Record<string, string> = {
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',
+10
View File
@@ -36,6 +36,16 @@ export const pt: Record<string, string> = {
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',
+10
View File
@@ -49,6 +49,16 @@ export const ru: Record<string, string> = {
explorerExcludeAdd: 'Добавить',
explorerExcludeRemove: 'Убрать',
editorTreeToggle: 'Панель дерева файлов',
editorFileNotFound: 'Файл не найден: {path}',
editorMarkdownPathHint: 'Markdown мог удалить обратную косую черту из этого пути Windows. Используйте прямые косые черты или поместите путь в блок кода.',
editorPathRepairSearching: 'Проверка возможных путей Windows…',
editorPathRepairNone: 'Не найден единственный подходящий путь. Проверьте путь и повторите попытку.',
editorPathRepairChoices: 'Найдено несколько возможных путей. Выберите правильный:',
editorPathRepairFailed: 'Не удалось проверить исправленные пути: {message}',
editorCopyPath: 'Копировать путь',
editorOpenInFileManager: 'Открыть в файловом менеджере',
editorCopyPathFailed: 'Не удалось скопировать путь',
editorRevealPathFailed: 'Не удалось открыть этот путь в файловом менеджере',
editorPathPlaceholder: 'Введите путь к файлу (относительно каталога сессии или абсолютный), Enter, чтобы открыть',
editorSearchPlaceholder: 'Поиск по имени файла…',
editorSearchNoResults: 'Нет совпадающих файлов',
+10
View File
@@ -36,6 +36,16 @@ export const sv: Record<string, string> = {
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',
+10
View File
@@ -53,6 +53,16 @@ export const th: Record<string, string> = {
explorerExcludeAdd: 'เพิ่ม',
explorerExcludeRemove: 'ลบ',
editorTreeToggle: 'พาเนลต้นไม้ไฟล์',
editorFileNotFound: 'ไม่พบไฟล์: {path}',
editorMarkdownPathHint: 'Markdown อาจลบแบ็กสแลชออกจากพาธ Windows นี้ ลองใช้เครื่องหมายทับหรือใส่พาธไว้ในบล็อกโค้ด',
editorPathRepairSearching: 'กำลังตรวจสอบพาธ Windows ที่เป็นไปได้…',
editorPathRepairNone: 'ไม่พบพาธที่ตรงกันเพียงรายการเดียว โปรดตรวจสอบพาธแล้วลองอีกครั้ง',
editorPathRepairChoices: 'พบพาธที่เป็นไปได้หลายรายการ โปรดเลือกพาธที่ถูกต้อง:',
editorPathRepairFailed: 'ตรวจสอบพาธที่ซ่อมแล้วไม่สำเร็จ: {message}',
editorCopyPath: 'คัดลอกพาธ',
editorOpenInFileManager: 'เปิดในตัวจัดการไฟล์',
editorCopyPathFailed: 'คัดลอกพาธไม่สำเร็จ',
editorRevealPathFailed: 'เปิดพาธนี้ในตัวจัดการไฟล์ไม่สำเร็จ',
editorPathPlaceholder: 'พาธไฟล์ (สัมพันธ์กับไดเรกทอรีเซสชันหรือแบบ absolute), Enter เพื่อเปิด',
editorSearchPlaceholder: 'ค้นหาไฟล์ตามชื่อ…',
editorSearchNoResults: 'ไม่มีไฟล์ที่ตรง',
+10
View File
@@ -53,6 +53,16 @@ export const tr: Record<string, string> = {
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',
+10
View File
@@ -53,6 +53,16 @@ export const vi: Record<string, string> = {
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',
+10
View File
@@ -68,6 +68,16 @@ export const zhHK: Record<string, string> = {
explorerExcludeAdd: '新增',
explorerExcludeRemove: '移除',
editorTreeToggle: '檔案樹面板',
editorFileNotFound: '找不到檔案:{path}',
editorMarkdownPathHint: 'Markdown 可能移除了 Windows 路徑中的反斜線。請改用正斜線,或將路徑放在程式碼區塊中。',
editorPathRepairSearching: '正在檢查可能的 Windows 路徑…',
editorPathRepairNone: '找不到唯一符合的路徑。請檢查路徑後重試。',
editorPathRepairChoices: '找到多個可能的路徑,請選擇正確路徑:',
editorPathRepairFailed: '無法檢查修復後的路徑:{message}',
editorCopyPath: '複製路徑',
editorOpenInFileManager: '在檔案管理員中開啟',
editorCopyPathFailed: '無法複製路徑',
editorRevealPathFailed: '無法在檔案管理員中開啟此路徑',
editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟',
editorSearchPlaceholder: '按檔案名稱搜尋…',
editorSearchNoResults: '無匹配檔案',
+10
View File
@@ -68,6 +68,16 @@ export const zhMO: Record<string, string> = {
explorerExcludeAdd: '新增',
explorerExcludeRemove: '移除',
editorTreeToggle: '檔案樹面板',
editorFileNotFound: '找不到檔案:{path}',
editorMarkdownPathHint: 'Markdown 可能移除了 Windows 路徑中的反斜線。請改用正斜線,或將路徑放在程式碼區塊中。',
editorPathRepairSearching: '正在檢查可能的 Windows 路徑…',
editorPathRepairNone: '找不到唯一符合的路徑。請檢查路徑後重試。',
editorPathRepairChoices: '找到多個可能的路徑,請選擇正確路徑:',
editorPathRepairFailed: '無法檢查修復後的路徑:{message}',
editorCopyPath: '複製路徑',
editorOpenInFileManager: '在檔案管理員中開啟',
editorCopyPathFailed: '無法複製路徑',
editorRevealPathFailed: '無法在檔案管理員中開啟此路徑',
editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟',
editorSearchPlaceholder: '按檔案名稱搜尋…',
editorSearchNoResults: '無匹配檔案',
+10
View File
@@ -68,6 +68,16 @@ export const zhTW: Record<string, string> = {
explorerExcludeAdd: '新增',
explorerExcludeRemove: '移除',
editorTreeToggle: '檔案樹面板',
editorFileNotFound: '找不到檔案:{path}',
editorMarkdownPathHint: 'Markdown 可能移除了 Windows 路徑中的反斜線。請改用正斜線,或將路徑放在程式碼區塊中。',
editorPathRepairSearching: '正在檢查可能的 Windows 路徑…',
editorPathRepairNone: '找不到唯一符合的路徑。請檢查路徑後重試。',
editorPathRepairChoices: '找到多個可能的路徑,請選擇正確路徑:',
editorPathRepairFailed: '無法檢查修復後的路徑:{message}',
editorCopyPath: '複製路徑',
editorOpenInFileManager: '在檔案管理員中開啟',
editorCopyPathFailed: '無法複製路徑',
editorRevealPathFailed: '無法在檔案管理員中開啟此路徑',
editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟',
editorSearchPlaceholder: '按檔案名稱搜尋…',
editorSearchNoResults: '無匹配檔案',
+20
View File
@@ -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: '无匹配文件',
@@ -724,6 +734,16 @@ export const en: Record<keyof typeof zh, string> = {
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',
+53
View File
@@ -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
}
+19
View File
@@ -1545,6 +1545,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;
+2 -6
View File
@@ -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 {
+13
View File
@@ -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)
}
+6 -9
View File
@@ -51,6 +51,7 @@ import { readSidechatImage } from './sidechat-routes.ts'
import { SIDECHAT_METADATA_BYTES, sidechatPromptBodyLimit } from './sidechat-image-admission.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 { createChangesOpsApi } from './changes-ops.ts'
import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
import {
@@ -479,11 +480,7 @@ const READ_HEAD_LIMIT = 4096
*/
async function statFileForRoute(path: string): Promise<Stats> {
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)
})
}
@@ -515,7 +512,7 @@ export type SidebarReadResult =
*/
async function readText(path: string): Promise<SidebarReadResult> {
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()) {
// A dedicated code, not a generic fs failure: the client promotes the tab
@@ -526,7 +523,7 @@ async function readText(path: string): Promise<SidebarReadResult> {
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
@@ -604,7 +601,7 @@ interface ReadPageResult {
*/
async function readPage(path: string, offset: number): Promise<ReadPageResult> {
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-directory', `"${path}" is a directory`, 400)
@@ -623,7 +620,7 @@ async function readPage(path: string, offset: number): Promise<ReadPageResult> {
}
}
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)
+17
View File
@@ -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}"`)
})
})
+31
View File
@@ -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)
})
})