Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,33 @@

格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。

## [0.0.34] — 2026-11-25

### 新增

- **从 Git 克隆**:`GitManager.cloneInto` 用 JGit 克隆 HTTPS 远程到新项目;地址中的 `user:token` 拆到 `UsernamePasswordCredentialsProvider`,克隆 URL 不含凭据,避免 token 写入 `.git/config`。目标目录必须不存在或为空,失败删除半成品。
- **项目 zip 导入/导出**:`ProjectArchive` 流式读写 zip。导出跳过 `.git`、`build`、`dist`、`node_modules`、`__pycache__`、`.gradle`、`.idea` 与符号链接,上限 256MB;导入先落临时目录,逐条 canonical path 校验,拒绝绝对路径、`..`、Windows 盘符、空路径,限制 10,000 条目 / 单文件 48MB / 总解压 256MB,单顶层目录自动提升,重名自动加 `-1`/`-2`。
- **项目迁移入口**:项目列表新增「从 Git 克隆」「导入 ZIP」「导出当前项目」;启动页与命令面板同步接入,导出/导入使用 SAF,不申请存储权限。

### 修复

- **forkpty 子进程 async-signal-safe**:`ptybridge.c` 在 `forkpty` 前构造 `argv`/`envp`,过滤旧 `TERM`/`PS1` 并追加终端环境;子进程只 `chdir` + `execve`,不再在 `pid==0` 分支调用 `setenv`。
- **命令子进程组回收**:新增 `ProcessGroup`,用 pidfile 记录 shell PID,经 `/system/bin/setsid` 进入新会话,超时先 `SIGTERM` 负 PID,300ms 后 `SIGKILL`;`setsid` 缺失时退回直接子进程。`RunCommandTool` 与 `TerminalSession` 已接入。
- **引擎卡死恢复入口**:`NativeEngine.isBusy` 暴露 busy;`stopRun()` 8 秒后仍占用时置 `engineStuck`,输出面板显示「重启应用」;`restartApp()` 同步保存当前文件,`AlarmManager` 约 900ms 后重新拉起再杀进程。

### 边界

- `engineStuck` 是恢复入口,不是解释器进程隔离;脚本卡在不可中断 C 调用时 `busy` 仍不会复位,只能重启应用。
- `ProcessGroup` 依赖 `/system/bin/setsid` 与负 PID 信号,不同 ROM 的 SELinux/二进制差异未做真机验证。
- 0.0.34 的 clone/zip UI、`restartApp`、PTY execve 均未取得 Android 真机/模拟器运行验收。

### 构建

- `versionCode 34` / `versionName 0.0.34`。
- release APK **24,293,808 B**,SHA-256 `6d2b056a875c52a84d445e652f4d3421ea8975c278813139a4b77aa3ae8b75c6`;debug APK **43,975,164 B**,SHA-256 `8020214efa14b842086688a4a0b0779642a30e8daad0786f53c8fb39d3cd3249`。
- JVM 单测 **144 通过 / 0 失败 / 0 错误**,lintRelease **0 Error / 22 Warning**;两包 `versionCode=34`、正式 release 证书 SHA-256 `1b02135746d1426d7beda47e706fdb2c77a7145ea41e0f7e14addb191b87fac5`,`zipalign -c -p 4` 通过。
- release APK 解压 **55,629,297 B / 1,138 文件**;`assets/python-stdlib.zip` 4,534,942 B / 574 文件;两个 ABI 的 `libptybridge.so` 均按 16KB 页对齐。

## [0.0.33] — 2026-11-25

### 修复
Expand Down
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ Three runtimes are bundled inside the APK: a natively cross-compiled CPython 3.1
- **Python pdb debugger**: real stdlib `pdb`; breakpoints, next/step/continue, `p locals()`, stack, quit; quick-action bar in output panel
- **Offline by design**: no language server process, no model download, hard caps at 300 `.py` files / 512KB per file

### Project migration & process teardown (0.0.34)
- **Clone from Git**: `GitManager.cloneInto` uses JGit to clone an HTTPS remote into a new project; credentials go through `UsernamePasswordCredentialsProvider` and are never written into `.git/config`, and the target must be absent or empty
- **Project zip import/export**: stream-based zip import with Zip Slip / absolute path / Windows drive rejection, 10,000-entry, 48MB-per-file and 256MB-total caps; a single top-level folder is promoted to the project root; export skips `.git`, `build`, `node_modules` and caches and caps at 256MB
- **Async-signal-safe PTY child**: `ptybridge.c` now builds `argv`/`envp` before `forkpty`; the child only calls `chdir` + `execve`, with no `setenv` after fork
- **Command process groups**: `ProcessGroup` writes the shell PID to a temp file, enters a new session via `/system/bin/setsid`, and sends `SIGTERM`/`SIGKILL` to the negative PID; when `setsid` is absent it falls back to the old direct-child behavior
- **Engine-stuck escape hatch**: if the native engine is still busy 8s after Stop, the output panel shows a **重启应用** action that saves the current file, relaunches via `AlarmManager`, then kills the process; this is recovery, not true interpreter process isolation

### Lifecycle & memory cleanup (0.0.33)
- **ViewModel teardown**: `onCleared` cancels AI/Agent/model jobs, stops the PTY, and releases the native Python engine + RuntimeRegistry instead of leaving them alive after the Activity is reclaimed
- **Streaming session metadata**: `AgentSessionStore.metaOf` reads a session log once line-by-line; listing 20 sessions no longer pulls multiple 16MB files into memory
Expand All @@ -116,7 +123,7 @@ Three runtimes are bundled inside the APK: a natively cross-compiled CPython 3.1
### Packaging cleanup (0.0.32)
- **Stale toolchain note removed**: the 441MB `usrtar.zip` instructions are gone; the app uses the bundled native CPython runtime and JGit, not the retired Termux bundle
- **Stdlib slimmed**: CPython `test`, `idlelib` and `turtledemo` are excluded from `python-stdlib.zip`; 1740 files / 7.1MB removed, all runtime modules and 53 C extensions untouched
- **Git wording fixed**: docs and site now say init / commit / push / pull (no clone) instead of "full Git capability"
- **Git wording fixed**: 0.0.32 aligned docs and site to init / commit / push / pull; 0.0.34 adds HTTPS clone, so the current list is init / commit / push / pull / clone

### Data safety & lifecycle (0.0.31)
- **No silent data loss**: with auto-save off, switching files/tabs/projects now asks Save / Discard / Cancel instead of overwriting the dirty buffer
Expand Down Expand Up @@ -146,8 +153,8 @@ Three runtimes are bundled inside the APK: a natively cross-compiled CPython 3.1

### Manage projects
- **Multi-project switching** (long-press to delete) · **4 Python templates**
- **JGit Git integration**: init / commit / push / pull, pure Java, offline
- **SAF import/export** (no storage permission needed)
- **JGit Git integration**: init / commit / push / pull / clone (HTTPS), pure Java, offline where possible
- **SAF import/export** (no storage permission needed): project zip in/out with traversal and size guards
- **Offline package management**: inspect built-in modules / import local .whl

### See results
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ android {
applicationId = "com.devterminal"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
versionCode = 33
versionName = "0.0.33"
versionCode = 34
versionName = "0.0.34"
vectorDrawables { useSupportLibrary = true }
// 原生 CPython 引擎:同时打 arm64 与 x86_64(后者用于模拟器/ChromeOS)
ndk { abiFilters += listOf("arm64-v8a", "x86_64") }
Expand Down
90 changes: 85 additions & 5 deletions app/src/main/cpp/ptybridge.c
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,66 @@ static jmethodID g_on_exit = NULL;
static volatile int g_closing = 0;
static int g_thread_started = 0;

/*
* fork 之后子进程只能调用 async-signal-safe 函数;setenv 会 malloc,
* 多线程进程 fork 后可能卡在 malloc 锁上。这里在 fork 之前把 argv/envp
* 全部构造好,子进程只做 chdir + execve。
*/
extern char **environ;

static int env_is_key(const char *entry, const char *key) {
size_t n = strlen(key);
return strncmp(entry, key, n) == 0 && entry[n] == '=';
}

static char **build_child_env(void) {
int count = 0;
while (environ && environ[count]) count++;
char **envp = (char **)calloc((size_t)count + 3, sizeof(char *));
if (!envp) return NULL;
int out = 0;
for (int i = 0; i < count; i++) {
if (env_is_key(environ[i], "TERM") || env_is_key(environ[i], "PS1")) continue;
envp[out] = strdup(environ[i]);
if (!envp[out]) {
for (int j = 0; j < out; j++) free(envp[j]);
free(envp);
return NULL;
}
out++;
}
envp[out++] = strdup("TERM=xterm-256color");
envp[out++] = strdup("PS1=\\w $ ");
envp[out] = NULL;
if (!envp[out - 2] || !envp[out - 1]) {
for (int j = 0; j < out; j++) free(envp[j]);
free(envp);
return NULL;
}
return envp;
}

static void free_child_env(char **envp) {
if (!envp) return;
for (int i = 0; envp[i]; i++) free(envp[i]);
free(envp);
}

static char **build_child_argv(const char *shell) {
char **argv = (char **)calloc(3, sizeof(char *));
if (!argv) return NULL;
argv[0] = strdup(shell);
argv[1] = strdup("-i");
argv[2] = NULL;
if (!argv[0] || !argv[1]) {
free(argv[0]);
free(argv[1]);
free(argv);
return NULL;
}
return argv;
}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
(void)reserved;
g_vm = vm;
Expand Down Expand Up @@ -133,6 +193,18 @@ Java_com_devterminal_engine_PtyBridge_nativeStart(

const char *cwd_s = (*env)->GetStringUTFChars(env, cwd, NULL);
const char *shell_s = (*env)->GetStringUTFChars(env, shell, NULL);
const char *shell_path = shell_s ? shell_s : "/system/bin/sh";
char **child_env = build_child_env();
char **child_argv = build_child_argv(shell_path);
if (!child_env || !child_argv) {
LOGE("build child env/argv failed");
free_child_env(child_env);
free(child_argv);
if (cwd_s) (*env)->ReleaseStringUTFChars(env, cwd, cwd_s);
if (shell_s) (*env)->ReleaseStringUTFChars(env, shell, shell_s);
pthread_mutex_unlock(&g_lock);
return -ENOMEM;
}
struct winsize ws;
memset(&ws, 0, sizeof(ws));
ws.ws_col = (unsigned short)(cols > 0 ? cols : 80);
Expand All @@ -143,22 +215,30 @@ Java_com_devterminal_engine_PtyBridge_nativeStart(
if (pid < 0) {
int err = errno;
LOGE("forkpty failed: %s", strerror(err));
free_child_env(child_env);
free(child_argv[0]);
free(child_argv[1]);
free(child_argv);
if (cwd_s) (*env)->ReleaseStringUTFChars(env, cwd, cwd_s);
if (shell_s) (*env)->ReleaseStringUTFChars(env, shell, shell_s);
pthread_mutex_unlock(&g_lock);
return -err;
}

if (pid == 0) {
// 子进程:forkpty 已建立控制终端;这里只切目录并 exec 交互 shell。
// 子进程:forkpty 已建立控制终端;这里只做 async-signal-safe 的
// chdir + execve,环境变量在 fork 前已构造好,不再调用 setenv。
if (cwd_s && chdir(cwd_s) != 0) _exit(127);
setenv("TERM", "xterm-256color", 1);
setenv("PS1", "\\w $ ", 1);
execl(shell_s ? shell_s : "/system/bin/sh",
shell_s ? shell_s : "sh", "-i", (char *)NULL);
execve(shell_path, child_argv, child_env);
_exit(127);
}

// 父进程:子进程 fork 后拥有自己的地址空间,这里可以安全释放构造的数组。
free_child_env(child_env);
free(child_argv[0]);
free(child_argv[1]);
free(child_argv);

// 父进程
g_master = master;
g_child = pid;
Expand Down
22 changes: 6 additions & 16 deletions app/src/main/java/com/devterminal/agent/tools/RunCommandTool.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.devterminal.agent.tools

import android.os.Build
import com.devterminal.agent.Tool
import com.devterminal.agent.ToolCall
import com.devterminal.agent.ToolResult
import com.devterminal.agent.ToolSpec
import com.devterminal.engine.ProcessGroup
import com.devterminal.workspace.Workspace
import java.io.File
import java.util.concurrent.TimeUnit
Expand Down Expand Up @@ -34,14 +34,12 @@ class RunCommandTool : Tool {
?: return ToolResult.failure(call.id, "设备没有可用的 sh")

val output = StringBuilder()
val process = runCatching {
ProcessBuilder(shell, "-c", command)
.directory(workspace.root)
.redirectErrorStream(true)
.start()
val handle = runCatching {
ProcessGroup.start(shell, command, workspace.root, redirectErrorStream = true)
}.getOrElse { e ->
return ToolResult.failure(call.id, "启动命令失败:${e.message}")
}
val process = handle.process

val reader = Thread {
runCatching {
Expand All @@ -62,7 +60,7 @@ class RunCommandTool : Tool {
}
if (isProcessAlive(process)) {
timedOut = true
destroyTree(process)
ProcessGroup.destroy(handle)
runCatching { process.inputStream.close() }
}
reader.join(1500)
Expand All @@ -80,15 +78,7 @@ class RunCommandTool : Tool {
}
}

/** Android 的 Process 没有 ProcessHandle;至少强杀 sh 并关闭输出流,避免 reader 挂死。 */
private fun destroyTree(process: Process) {
runCatching {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) process.destroyForcibly()
else process.destroy()
}
runCatching { process.inputStream.close() }
}

/** 判断直接子进程是否还活着;进程组清理见 [ProcessGroup.destroy]。 */
private fun isProcessAlive(process: Process): Boolean = runCatching {
process.exitValue()
false
Expand Down
27 changes: 27 additions & 0 deletions app/src/main/java/com/devterminal/engine/GitManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,33 @@ class GitManager {
}
}

/**
* 把远程仓库克隆到 targetDir。
*
* targetDir 必须不存在或为空;调用方负责分配不冲突的目录。克隆全程走 JGit,
* 不启动系统 git,也不把带 token 的 URL 写进 `.git/config`。
*/
fun cloneInto(targetDir: File, remoteUrl: String): String {
if (remoteUrl.isBlank()) return "远程地址不能为空"
if (targetDir.exists() && (targetDir.isDirectory && targetDir.listFiles()?.isNotEmpty() == true ||
targetDir.isFile)
) {
return "目标目录不是空目录:${targetDir.name}"
}
targetDir.parentFile?.mkdirs()
return guarded("克隆") {
val cmd = Git.cloneRepository()
.setURI(tokenlessUrl(remoteUrl))
.setDirectory(targetDir)
.setCloneAllBranches(true)
credentials(remoteUrl)?.let { cmd.setCredentialsProvider(it) }
cmd.call().use { g ->
val branch = runCatching { g.repository.branch }.getOrNull() ?: "HEAD"
"已克隆 ${hostOf(remoteUrl)} · 分支 $branch"
}
}
}

/** 暂存全部变更并提交(含删除) */
fun commitAll(dir: File, message: String, userName: String, userEmail: String): String {
if (message.isBlank()) return "提交信息不能为空"
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/devterminal/engine/NativeEngine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ class NativeEngine(private val context: Context) : RunEngine {

private val busy = AtomicBoolean(false)

/** UI 用它判断停止 8 秒后是否仍被不响应中断的原生调用占着。 */
override val isBusy: Boolean get() = busy.get()

/** 解释器初始化是否完成(首次 run 前惰性初始化,耗时约 0.5~2s) */
private val initLock = Any()
@Volatile
Expand Down
91 changes: 91 additions & 0 deletions app/src/main/java/com/devterminal/engine/ProcessGroup.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package com.devterminal.engine

import android.os.Build
import java.io.File

/**
* 给每条 shell 命令套一个独立进程组。
*
* Android 的 `java.lang.Process` 没有 `ProcessHandle`,`destroyForcibly()` 只能
* 杀掉直接子进程;`python -m pytest` 再起 worker、`sh -c 'a & b'` 这类命令会在
* 超时后留下孤儿。这里用 Android 自带的 `setsid` 把命令放进新会话,再对负 PID
* (进程组)发信号,至少能把同一组里的子孙一起收掉。
*
* `setsid` 不存在时退化为普通 `sh -c`,行为和旧版一致;不会因为工具缺失而
* 让命令起不来。
*/
object ProcessGroup {

private const val SETSID = "/system/bin/setsid"
private const val SIGTERM = 15
private const val SIGKILL = 9

/** 一个命令的直接子进程 + 它的进程组 ID(setsid 后的 shell PID)。 */
data class Handle(val process: Process, val pid: Long)

/**
* 启动命令。
*
* 先用 `sh -c 'echo $$ > pidfile; shift; exec setsid "$@"'` 把 shell PID 落盘:
* Android 的 `java.lang.Process` 在 API 24 没有 `pid()`,不能直接取 PID;
* 写文件既不依赖隐藏 API,也能在 setsid 失败时拿到真实 shell PID。
*/
fun start(
shell: String,
command: String,
cwd: File,
redirectErrorStream: Boolean,
): Handle {
val pidFile = File.createTempFile("cp-pg-", ".pid")
val setsid = File(SETSID).takeIf { it.isFile && it.canExecute() }
val launcher = if (setsid != null) {
"echo \$\$ > \"\$1\"; shift; exec $SETSID \"\$@\""
} else {
"echo \$\$ > \"\$1\"; shift; exec \"\$@\""
}
val args = mutableListOf(shell, "-c", launcher, "cp-pg", pidFile.absolutePath, shell, "-c", command)
val process = ProcessBuilder(args)
.directory(cwd)
.redirectErrorStream(redirectErrorStream)
.start()
var pid = -1L
runCatching {
for (i in 0 until 10) {
if (pidFile.exists() && pidFile.length() > 0L) {
pid = pidFile.readText().trim().toLongOrNull() ?: -1L
if (pid > 0L) break
}
Thread.sleep(50)
}
}
pidFile.delete()
return Handle(process, pid)
}

/**
* 先礼后兵:SIGTERM 整个进程组,给 300ms 清理;还活着就 SIGKILL 进程组,
* 最后再 `destroyForcibly()` 兜底直接子进程。
*/
fun destroy(handle: Handle) {
val process = handle.process
val pid = handle.pid
if (pid > 0) {
runCatching { android.os.Process.sendSignal(-pid.toInt(), SIGTERM) }
Thread.sleep(300)
if (isAlive(process)) {
runCatching { android.os.Process.sendSignal(-pid.toInt(), SIGKILL) }
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
runCatching { process.destroyForcibly() }
} else {
runCatching { process.destroy() }
}
runCatching { process.inputStream.close() }
}

fun isAlive(process: Process): Boolean = runCatching {
process.exitValue()
false
}.getOrElse { true }
}
Loading
Loading