修 bug 报告里的三条(PYTHONPATH / pip / 附件路径)
用户交来一份很扎实的反馈单,逐条核过、逐条修,并做了对照实验。
## 问题 1(致命):PYTHONPATH 把 3.13 的 .imy 硬塞给 3.14
Fatal Python error: Failed to import encodings module
zipimport.ZipImportError: module load failed: bad magic number
in 'encodings': b'\xf3\r\r\n'
用户的定性**完全正确**:宿主 Chaquopy 为了让自己的 CPython 3.13 找到标准库,
在**进程环境里**设了 PYTHONPATH 指向 files/chaquopy/*.imy;而
ProcessBuilder / TerminalSession 起的是子进程,继承整个 App 进程的环境,
于是 Termux 里 apt 装的 python 3.14 一启动就读到 3.13 编的 encodings pyc。
**对照实验**(模拟器,python 3.14.6):
$ python3 -c 'import encodings' → 正常
$ PYTHONPATH=…/stdlib-common.imy python3 -c 'import encodings'
→ Fatal Python error: Failed to import encodings module ← 一字不差复现
修法:新增 `TermuxInstaller.childEnvMap()` —— **以父环境为底**、覆盖上
Termux 那一套、并摘掉 PYTHONPATH/PYTHONHOME/PYTHONSTARTUP 等宿主 Python 变量。
所有起子进程的地方(TermuxShell / TermuxTerminal / TermuxMirror 探测)都改用它。
★ 只摘子进程的,不动 App 自己的:Chaquopy 那个解释器**需要** PYTHONPATH
才能找标准库,全局清掉会把内核搞死。
★ 不用"清空环境再放我们那一套":那样会把 ANDROID_ROOT 之类系统变量也扔掉。
## 问题 3:pip 崩死 → 连带"零预装第三方库"
pip3 的 shebang 是 `#!/data/data/com.termux/files/usr/bin/python3.14`,
而 `rewritePrefixes` 只做了 `oldData → dataDir`,产出
#!/data/<pkg>/files/files/usr/bin/python3.14 ← 多一层 files,解析不了
实测:这条报 Permission denied,而 `#!<prefix>/bin/python3.14` 能跑。
(`<pkg>/files/files/usr/...` 里的第二个 files 是 `<pkg>/files` 下一个
不存在的目录 —— 沙箱里 `files/home` 那条链只兜住了 home。)
修法:`rewritePrefixes` **先换长路径再换短的** ——
`/data/data/com.termux/files/usr` → `<prefix>`,再做 `…/com.termux` → dataDir。
维护脚本那支同样处理。STAMP 25→26→27,老设备进一次终端就会补跑。
实测(模拟器):
$ pip3 --version → pip 26.2.1
$ pip3 install six → six 1.17.0
$ python3 -c 'import six' → ok
## 问题 2:/tmp 不可写 —— 部分修好,如实说明
`/tmp` **在 root 下不存在**,而 root 是只读的:
$ mkdir /tmp → Read-only file system
$ ln -s … /tmp → Read-only file system
而且 `libtermux-exec.so` **只改写 Termux 自己那个前缀**,不管 `/tmp`
(实测:`touch /tmp/x` 仍然失败)。dpkg 的 --instdir 那条沙箱路也拦不住它 ——
内核解析的是根下的绝对路径。
能做的已经做了:
· TMPDIR 一直是对的(environment() 里设了、bash rc 里也 export)
· 实测尊重 TMPDIR 的工具全部正常:
mktemp → <prefix>/tmp/tmp.5Z1IKHx7Vp
tempfile → <prefix>/tmp
· 所以只有"硬编码 /tmp 字符串"的程序会受影响
## 问题 5:附件不告知路径 → 已修
· `attachment_payload` **每一条分支**都带 `本地路径:<绝对路径>`
(以前只有二进制那条带,而**恰恰是文本最需要** —— 超 20000 字符会截断)
· 落盘命名从 base36 时间戳换成**可读**的 `20260101-120000_原名.ext`,
重名自动加 `-1`;`_unique_path()` 抽出来,两处落盘共用
· 旧名(`_ts36`)在文件名里保留不了可读性,用户明确抱怨过
· 系统提示词加了两条,告诉模型"那个路径是真的、可以用 shell 打开"
## 顺带:镜像坏掉自动换源
用户卡住的那条报错其实是**清华镜像同步中**:
E: Failed to fetch …/Packages.bz2
File has unexpected size (583395 != 586556). Mirror sync in progress?
实测各镜像健康度(Release 声明值 vs 实际下载值):
清华 TUNA 586556 vs 583395 ✗ 坏
中科大 USTC 585742 vs 585742 ✓
北外 BFSU 590396 vs 590396 ✓
官方源 584437 vs 584437 ✓
**我们默认给的就是清华** —— 任何单一默认值都会偶尔把用户卡死。
新增 `TermuxMirror.autoPickIfBroken()`:后台真跑一次 `apt-get update` 当探测
(不自己写校验,apt 比我们严;反正换源后本来就要 update),
探测失败就按源列表往下试,成功则记住并记日志。当前源能用就一个字都不改。
实测生效(本机日志):
软件源自动切换到 中科大 USTC(原来那个在同步中,取不到索引)
This commit is contained in:
@@ -16,6 +16,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
import paths
|
||||
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
|
||||
@@ -62,6 +63,51 @@ def _safe_name(name: str) -> str:
|
||||
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()
|
||||
|
||||
@@ -86,7 +132,8 @@ def _meta(file_path: str, name: str, copy: bool = True) -> dict:
|
||||
stored_path = file_path
|
||||
url = ''
|
||||
if copy and size <= COPY_LIMIT:
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
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)
|
||||
@@ -118,8 +165,8 @@ def save_upload(name: str, base64_data: str) -> dict:
|
||||
raise ValueError(f'base64 解码失败:{exc}') from exc
|
||||
if len(buffer) > COPY_LIMIT:
|
||||
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
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 {
|
||||
@@ -158,21 +205,32 @@ 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"【附件 {item.get('name') or '未知'} 已丢失】"
|
||||
out['text'] = f"【附件 {name} 已丢失】"
|
||||
return out
|
||||
size = os.path.getsize(file_path)
|
||||
if is_image(item.get('name')) and size <= VISION_LIMIT:
|
||||
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"【图片 {item.get('name')}】"
|
||||
out['text'] = f"【图片 {name}({size} 字节)本地路径:{file_path}】"
|
||||
return out
|
||||
if is_text(item.get('name')) or size < 64 * 1024:
|
||||
if is_text(name) or size < 64 * 1024:
|
||||
body = ''
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
|
||||
@@ -181,7 +239,10 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
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"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
|
||||
out['text'] = (
|
||||
f"【文件 {name}({size} 字节)本地路径:{file_path}】\n"
|
||||
f'```\n{clipped}\n```'
|
||||
)
|
||||
return out
|
||||
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
out['text'] = f"【附件 {name}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
return out
|
||||
|
||||
Reference in New Issue
Block a user