""" 附件:上传落盘、拖拽文件待取队列、以及"附件 → 模型输入"的转换。 对应 Node 版 server/src/uploads.mjs,字段完全一致: { id, name, size, mime, path, url, at } 安卓上的差异: * 没有 Electron 的原生选文件钩子,选文件由 Kotlin 侧调用 /api/pick-file 时注入 (main.py 的 native hooks),默认返回"当前环境不支持原生选文件"; * 上传仍然走 base64(前端 FileReader → dataUrl),因为 WebView/Lynx 里拿不到真实路径。 """ import base64 import binascii import os import re import sys import threading from datetime import datetime import paths from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格 _pending = [] _pending_lock = threading.Lock() IMAGE_EXT = {'.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'} TEXT_EXT = { '.txt', '.md', '.markdown', '.json', '.csv', '.tsv', '.log', '.ini', '.toml', '.yml', '.yaml', '.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.html', '.htm', '.css', '.scss', '.xml', '.sql', '.sh', '.bat', '.ps1', '.java', '.c', '.h', '.cpp', '.cs', '.go', '.rs', '.rb', '.php', '.swift', '.kt', '.lua', '.r', '.vue', '.svelte', } # 复制进 uploads 的上限;再大就只登记路径,不复制 # 单个文件上限。 # # ★ 这个值和请求体上限是联动的:走 /api/upload 时文件会先 base64 再塞进 JSON, # 体积涨 1/3 —— 100MB 的文件对应约 133MB 的请求体,所以 app.py 那边 # /api/upload 的 read_json_body 得给到 150MB,否则会先被"请求体过大"挡下来。 # # 内存提醒:一次上传的峰值占用大约是 文件大小 × 2.4(原始 JSON 字符串 + # base64 解码结果)。100MB 的文件在手机上要吃掉 240MB 左右,低端机有可能 # 直接被系统杀掉。真要传超大文件,正确做法是分片上传,不是继续抬这个数。 COPY_LIMIT = 100 * 1024 * 1024 # 喂给模型的单张图片上限 VISION_LIMIT = 6 * 1024 * 1024 _MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.bmp': 'image/bmp', '.pdf': 'application/pdf', '.json': 'application/json', '.md': 'text/markdown', } def _rid() -> str: return f'f_{_ts36()}_{_rand36(4)}' def _safe_name(name: str) -> str: """去掉路径分隔符和 Windows 非法字符,并只保留末尾 60 个字符(和 Node 一致)。""" cleaned = re.sub(r'[\\/:*?"<>|]', '_', str(name or 'file')) return cleaned[-60:] def _stamp() -> str: """ 落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。 ★ 以前这里用的是 `_ts36()`(base36 的毫秒数,形如 `m5k8xk2`)。 它唯一的优点是不会重名,缺点是**看见文件名完全不知道是什么时候的东西** —— 排查问题时只能一个个 `ls -la`。 用户明确反馈过这一点(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名 临时件,无统一约定"。所以换成可读格式。 ★ 秒级精度会撞名(同一秒传两个同名文件)。落盘前用 [_unique_path] 消歧, 不靠时间戳本身保证唯一。 """ return datetime.now().strftime('%Y%m%d-%H%M%S') def uploads_dir() -> str: """ 附件的固定落地目录(绝对路径)。**只有这一个入口,别在别处拼路径。** 存在的意义是给"AI 拿到附件后想去 shell 里处理它"一个稳定约定 —— `attachment_payload` 会把 `path` 明明白白写进给模型的内容里, 模型不必去猜文件在哪(bug 报告问题 5 的核心诉求)。 """ return os.path.join(paths.get().uploads_dir, '').rstrip(os.sep) def _unique_path(directory: str, stamp: str, safe_name: str) -> str: """ `{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`… ★ 一定要保留扩展名:`report.pdf` 变成 `report-1.pdf` 而不是 `report.pdf-1` —— 一堆工具(含我们自己的 `is_image()` / `mime_of()`)都按扩展名判断类型。 """ base, ext = os.path.splitext(safe_name) for i in range(0, 1000): suffix = '' if i == 0 else f'-{i}' candidate = os.path.join(directory, f'{stamp}_{base}{suffix}{ext}') if not os.path.exists(candidate): return candidate # 极端情况:同秒同名超过 1000 个,交给随机后缀 return os.path.join(directory, f'{stamp}_{base}-{_rand36(4)}{ext}') def _ext_of(name: str) -> str: return os.path.splitext(str(name or ''))[1].lower() def is_image(name: str) -> bool: return _ext_of(name) in IMAGE_EXT def is_text(name: str) -> bool: return _ext_of(name) in TEXT_EXT def mime_of(name: str) -> str: ext = _ext_of(name) if ext in _MIME: return _MIME[ext] return 'text/plain' if is_text(name) else 'application/octet-stream' def _meta(file_path: str, name: str, copy: bool = True) -> dict: size = os.path.getsize(file_path) stored_path = file_path url = '' if copy and size <= COPY_LIMIT: os.makedirs(uploads_dir(), exist_ok=True) target = _unique_path(uploads_dir(), _stamp(), _safe_name(name)) with open(file_path, 'rb') as src, open(target, 'wb') as dst: while True: chunk = src.read(256 * 1024) if not chunk: break dst.write(chunk) stored_path = target url = f'/uploads/{os.path.basename(target)}' return { 'id': _rid(), 'name': str(name), 'size': size, 'mime': mime_of(name), 'path': stored_path, 'url': url, 'at': now_iso(), } def save_upload(name: str, base64_data: str) -> dict: """浏览器上传:base64(dataUrl) → 落盘。""" if not name or not base64_data: raise ValueError('缺少 name 或 base64') raw = re.sub(r'^data:[^,]+,', '', str(base64_data)) try: # validate=False:和 Node 的 Buffer.from(x,'base64') 一样,忽略非法字符 buffer = base64.b64decode(raw, validate=False) except (binascii.Error, ValueError) as exc: raise ValueError(f'base64 解码失败:{exc}') from exc if len(buffer) > COPY_LIMIT: raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB') os.makedirs(uploads_dir(), exist_ok=True) target = _unique_path(uploads_dir(), _stamp(), _safe_name(name)) with open(target, 'wb') as fh: fh.write(buffer) return { 'id': _rid(), 'name': str(name), 'size': len(buffer), 'mime': mime_of(name), 'path': target, 'url': f'/uploads/{os.path.basename(target)}', 'at': now_iso(), } def register_local_file(file_path: str) -> dict: """安卓/Kotlin 侧选完文件后登记(必要时复制进 uploads)。""" if not os.path.isfile(file_path): raise ValueError(f'文件不存在:{file_path}') return _meta(file_path, os.path.basename(file_path)) def add_pending(items: list) -> None: with _pending_lock: _pending.extend(items or []) def take_pending() -> list: """取走待处理附件(取完即清空),Lynx 界面轮询这个接口挂输入框。""" global _pending with _pending_lock: items = _pending _pending = [] return items def attachment_payload(attachment: dict) -> dict: """ 把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。 返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。 ★★★ **每一条分支都会把落盘的绝对路径写进 text。** 这一条是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉 模型文件落在哪,模型想去 shell / python 里处理它只能靠猜,猜错就是 FileNotFoundError。之前只有"二进制"那一条给了路径,文本和图片都没给 —— 而**恰恰是文本最需要**:超过 20000 字符会被截断,被截掉的那部分 只能靠模型自己去读原文件。 格式统一成 `本地路径:<绝对路径>`,模型一眼能捞出来。 """ out = {'text': '', 'images': []} item = attachment or {} file_path = item.get('path') or '' name = item.get('name') or '未知' if not file_path or not os.path.isfile(file_path): out['text'] = f"【附件 {name} 已丢失】" return out size = os.path.getsize(file_path) if is_image(name) and size <= VISION_LIMIT: with open(file_path, 'rb') as fh: b64 = base64.b64encode(fh.read()).decode('ascii') out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"}) out['text'] = f"【图片 {name}({size} 字节)本地路径:{file_path}】" return out if is_text(name) or size < 64 * 1024: body = '' try: with open(file_path, 'r', encoding='utf-8', errors='replace') as fh: body = fh.read() except OSError as exc: print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr) if body: clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body out['text'] = ( f"【文件 {name}({size} 字节)本地路径:{file_path}】\n" f'```\n{clipped}\n```' ) return out out['text'] = f"【附件 {name}({size} 字节,二进制)本地路径:{file_path}】" return out