JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:非utf-8编码文件读取报错问题
xiaoyao42c60dd1c11384
diff --git a/jiuwenclaw/channels/web/app_web.py b/jiuwenclaw/channels/web/app_web.pyindex 1e1512f595..a3fcc57ae6 100644--- a/jiuwenclaw/channels/web/app_web.py+++ b/jiuwenclaw/channels/web/app_web.py@@ -597,6 +597,7 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):if path == "/file-api/file-content":file_arg = query.get("path", "")+ encoding_arg = query.get("encoding", "utf-8")if not file_arg:self._write_json(400, {"error": "missing_file_path"})return@@ -614,8 +615,30 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):if not full_path.exists():self._write_json(404, {"error": "file_not_found", "fullPath": str(full_path)})return++ def read_file_with_encoding(file_path: Path, encoding: str) -> tuple[str, str]:+ if encoding == "auto":+ import charset_normalizer+ raw_data = file_path.read_bytes()+ detected = charset_normalizer.from_bytes(raw_data).best()+ if detected is None:+ detected_encoding = "utf-8"+ else:+ detected_encoding = detected.encoding or "utf-8"+ try:+ return raw_data.decode(detected_encoding), detected_encoding+ except (UnicodeDecodeError, LookupError) as decode_exc:+ for try_encoding in ["gbk", "gb2312", "big5", "shift_jis", "euc_kr"]:+ try:+ return raw_data.decode(try_encoding), try_encoding+ except (UnicodeDecodeError, LookupError):+ continue+ raise OSError(f"Unable to decode file with any known encoding") from decode_exc+ else:+ return file_path.read_text(encoding=encoding), encoding+try:- data = full_path.read_text(encoding="utf-8")+ data, used_encoding = read_file_with_encoding(full_path, encoding_arg)except OSError as exc:self._write_json(500, {"error": str(exc)})return@@ -623,6 +646,7 @@ class _SpaStaticHandler(SimpleHTTPRequestHandler):self.send_response(200)self.send_header("Content-Type", "text/plain; charset=utf-8")self.send_header("Content-Length", str(len(body)))+ self.send_header("X-Original-Encoding", used_encoding)self.end_headers()if self.command != "HEAD":self.wfile.write(body)diff --git a/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx b/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsxindex e91df4f1af..8c1b79e416 100644--- a/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx+++ b/jiuwenclaw/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx@@ -44,6 +44,7 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPrconst [isEditing, setIsEditing] = useState(false);const [error, setError] = useState<string | null>(null);const [saveError, setSaveError] = useState<string | null>(null);+ const [fileEncoding, setFileEncoding] = useState<string>('auto');const lowerFileName = fileName.toLowerCase();const isMarkdown = lowerFileName.endsWith('.md') || lowerFileName.endsWith('.mdx');const isJson = lowerFileName.endsWith('.json');@@ -119,7 +120,7 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPrtry {const encodedPath = encodeURIComponent(filePath);- const url = `/file-api/file-content?path=${encodedPath}`;+ const url = `/file-api/file-content?path=${encodedPath}&encoding=${fileEncoding}`;const response = await fetch(url, { cache: 'no-store' });if (!response.ok) {@@ -127,6 +128,11 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPrthrow new Error(`HTTP ${response.status}: ${errorData.substring(0, 100)}`);}+ const originalEncoding = response.headers.get('X-Original-Encoding');+ if (originalEncoding && fileEncoding === 'auto') {+ console.log(`File encoding detected: ${originalEncoding}`);+ }+const text = await response.text();setContent(text);setDraftContent(text);@@ -139,7 +145,7 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr};loadFile();- }, [filePath, fileName, isPreviewable, reloadNonce]);+ }, [filePath, fileName, isPreviewable, reloadNonce, fileEncoding]);useEffect(() => {if (isHistoryJson) {@@ -206,6 +212,23 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr</p></div></div>+ <div className="flex items-center gap-2">+ <label className="text-xs text-text-muted">Encoding:</label>+ <select+ value={fileEncoding}+ onChange={(e) => setFileEncoding(e.target.value)}+ className="rounded border border-border bg-bg px-2 py-1 text-xs text-text"+ >+ <option value="auto">Auto Detect</option>+ <option value="utf-8">UTF-8</option>+ <option value="gbk">GBK</option>+ <option value="gb2312">GB2312</option>+ <option value="big5">Big5</option>+ <option value="shift_jis">Shift_JIS</option>+ <option value="euc_kr">EUC-KR</option>+ <option value="iso-8859-1">ISO-8859-1</option>+ </select>+ </div>{isMarkdown && !loading ? (<div className="flex flex-shrink-0 items-center gap-2 self-stretch">{isEditing ? (diff --git a/jiuwenclaw/channels/web/frontend/src/components/ToolPanel/ReadOnlyFileModal.tsx b/jiuwenclaw/channels/web/frontend/src/components/ToolPanel/ReadOnlyFileModal.tsxindex fd94b34ae6..b2f8f8fb0e 100644--- a/jiuwenclaw/channels/web/frontend/src/components/ToolPanel/ReadOnlyFileModal.tsx+++ b/jiuwenclaw/channels/web/frontend/src/components/ToolPanel/ReadOnlyFileModal.tsx@@ -43,6 +43,7 @@ export function ReadOnlyFileModal({ open, filePath, fileName, onClose }: ReadOnlconst [content, setContent] = useState<string>('');const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);+ const [fileEncoding, setFileEncoding] = useState<string>('auto');useEffect(() => {if (!open) return;@@ -73,7 +74,7 @@ export function ReadOnlyFileModal({ open, filePath, fileName, onClose }: ReadOnltry {const encodedPath = encodeURIComponent(filePath);- const url = `/file-api/file-content?path=${encodedPath}`;+ const url = `/file-api/file-content?path=${encodedPath}&encoding=${fileEncoding}`;const response = await fetch(url, { cache: 'no-store' });if (!response.ok) {@@ -92,7 +93,7 @@ export function ReadOnlyFileModal({ open, filePath, fileName, onClose }: ReadOnl};loadFile();- }, [open, filePath, fileName, t]);+ }, [open, filePath, fileName, t, fileEncoding]);if (!open) {return null;@@ -177,6 +178,23 @@ export function ReadOnlyFileModal({ open, filePath, fileName, onClose }: ReadOnl{filePath}</p></div>+ <div className="flex items-center gap-2">+ <label className="text-xs text-text-muted">Encoding:</label>+ <select+ value={fileEncoding}+ onChange={(e) => setFileEncoding(e.target.value)}+ className="rounded border border-border bg-bg px-2 py-1 text-xs text-text"+ >+ <option value="auto">Auto Detect</option>+ <option value="utf-8">UTF-8</option>+ <option value="gbk">GBK</option>+ <option value="gb2312">GB2312</option>+ <option value="big5">Big5</option>+ <option value="shift_jis">Shift_JIS</option>+ <option value="euc_kr">EUC-KR</option>+ <option value="iso-8859-1">ISO-8859-1</option>+ </select>+ </div><buttontype="button"onClick={onClose}diff --git a/jiuwenclaw/channels/web/frontend/vite.config.ts b/jiuwenclaw/channels/web/frontend/vite.config.tsindex 2c9342ea29..34701a3ff8 100644--- a/jiuwenclaw/channels/web/frontend/vite.config.ts+++ b/jiuwenclaw/channels/web/frontend/vite.config.ts@@ -41,6 +41,45 @@ function resolveProjectRootDir(): string {return repoRoot}+const FILE_CONTENT_ENCODING_ALIASES: Record<string, string> = {+ utf8: 'utf-8',+ 'utf_8': 'utf-8',+ gb2312: 'gb18030',+ gbk: 'gb18030',+ 'shift-jis': 'shift_jis',+ sjis: 'shift_jis',+ euc_kr: 'euc-kr',+ latin1: 'iso-8859-1',+}++function normalizeFileContentEncoding(encoding: string): string {+ const key = encoding.trim().toLowerCase()+ return FILE_CONTENT_ENCODING_ALIASES[key] ?? key+}++function decodeFileContent(raw: Buffer, requestedEncoding: string): { content: string; encoding: string } {+ const normalizedEncoding = normalizeFileContentEncoding(requestedEncoding || 'utf-8')+ if (normalizedEncoding !== 'auto') {+ return {+ content: new TextDecoder(normalizedEncoding, { fatal: true }).decode(raw),+ encoding: normalizedEncoding,+ }+ }++ const candidates = ['utf-8', 'gb18030', 'big5', 'shift_jis', 'euc-kr', 'iso-8859-1']+ for (const candidate of candidates) {+ try {+ return {+ content: new TextDecoder(candidate, { fatal: true }).decode(raw),+ encoding: candidate,+ }+ } catch {+ /* try next encoding */+ }+ }+ throw new Error('Unable to decode file with any known encoding')+}+/** WS proxy 中常见的、可安全忽略的 socket 错误码(跨平台) */const WS_PROXY_IGNORABLE_CODES = new Set(['EPIPE', // 对端已关闭@@ -374,6 +413,7 @@ function devFileContentApi(): Plugin {if (req.method === 'GET') {const url = new URL(req.url || '/file-api/file-content', 'http://localhost')const filePath = url.searchParams.get('path')+ const requestedEncoding = url.searchParams.get('encoding') || 'utf-8'if (!filePath) {res.statusCode = 400res.setHeader('content-type', 'application/json; charset=utf-8')@@ -398,9 +438,10 @@ function devFileContentApi(): Plugin {cwd: path.dirname(path.dirname(generateAgentFoldersScriptPath)),})if (runResult.status === 0 && fs.existsSync(fullPath)) {- const content = fs.readFileSync(fullPath, 'utf-8')+ const { content, encoding } = decodeFileContent(fs.readFileSync(fullPath), requestedEncoding)res.statusCode = 200res.setHeader('content-type', 'text/plain; charset=utf-8')+ res.setHeader('X-Original-Encoding', encoding)res.end(content)return}@@ -414,9 +455,10 @@ function devFileContentApi(): Plugin {return}- const content = fs.readFileSync(fullPath, 'utf-8')+ const { content, encoding } = decodeFileContent(fs.readFileSync(fullPath), requestedEncoding)res.statusCode = 200res.setHeader('content-type', 'text/plain; charset=utf-8')+ res.setHeader('X-Original-Encoding', encoding)res.end(content)} catch (error) {res.statusCode = 500