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
33 changes: 33 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,39 @@

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

## [0.0.31] — 2026-11-25

### 修复

- **关闭自动保存后不再静默丢改动**:切文件、关 Tab、切项目前弹出「保存并继续 / 不保存直接继续 / 取消」;`autoSave=false` 的脏文本不会被新文件覆盖。
- **写入改为原子落盘**:`ProjectManager.write`、`LocalWorkspace.writeBytes`、`CheckpointStore.writeAtomic` 统一临时文件 + fsync + rename;崩溃/断电最多保留旧版本,不再留下半个文件。
- **切后台保存改为同步**:`onStop` 不再只 launch 异步写,进程在写盘前被杀也不会丢掉当前快照。
- **文件打开护栏**:编辑器单文件上限 5MB,二进制文件拒绝按文本打开;超大文件/读失败给出提示,不再闪退。
- **Agent 检查点回收**:快照单文件 8MB 上限,保留最近 20 份清单并删除无引用 blob;反复修改/撤销不再无限吃存储。
- **Agent 会话日志封顶**:单会话 16MB、回放 2000 条、总量 128MB;长任务不会把手机写满。
- **PTY 输入严格 FIFO**:xterm 逐键回调改单消费者队列,快速输入不再乱序;返回键关终端会真正停止 PTY,关闭 Agent 面板会取消后台 Agent。
- **Agent 覆盖保护**:Agent 改完文件后,当前编辑器有未保存修改时不自动用磁盘内容覆盖;撤销检查点也先要求保存/关闭。
- **目录重命名/删除的 Tab 生命周期**:目录下已打开 Tab 会随路径迁移;删除目录会清空其下当前文件和 Tab,`dirty` 复位。
- **文件树节点上限**:单次构建最多 10,000 节点,避免超大项目把 UI 卡死(截断暂不在界面提示,已记录)。
- **后台执行更稳**:`ExecutionService.stop` 改为同进程直接停实例,避开 Android O+ 后台 `startService` 限制;运行时申请 partial wakelock,熄屏长脚本不被挂起。
- **JNI 异常清理**:PTY 字节回调抛异常后立即 `ExceptionClear`,避免后续 JNI 调用连锁失败。
- **分享/输出上限**:分享与剪贴板 200KB 截断,输出单行 4000 字符截断,避免 Binder 事务超限与超大单行 OOM。
- **编辑器手势**:双指捏合只在两指及以上消费事件,单指滚动/光标拖动不再被手势层抢走。
- **状态栏图标跟随主题**:App 内切深色/浅色后同步状态栏与导航栏图标明暗。
- **AI 响应上限**:非流式响应最多读 2MB 字符,异常端点不会把内存打爆。
- **运行命令超时**:`RunCommandTool` 超时强杀并关闭输出流;Android 无 `ProcessHandle`,子进程树彻底回收仍待下一批。

### 边界

- 本轮仍无 Android 真机/模拟器交互验收;x86_64 TCG 继续卡在 `emulator-5556 offline`,PTY、WebView、IME 和 16KB 页需要 ARM64 真机确认。
- 未处理项:不响应中断的 Python 脚本仍可能让引擎 `busy` 卡死、`forkpty` 子进程 `setenv` 的 async-signal 风险、项目 zip 导入/导出、UI 截图回归、字体 200% 可访问性。完整清单见 `docs/RISK_REGISTER_0.0.31.md` 与交付报告。

### 构建

- `versionCode 31` / `versionName 0.0.31`。
- JVM 单测 **137 个通过**(新增 1 个检查点 blob 回收测试)。
- lint Release **0 Error / 37 Warning**,无 Fatal。

## [0.0.30] — 2026-11-24

### 新增
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,16 @@ 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

### 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
- **Atomic saves**: temp file + `fsync` + `rename` for editor files, workspace writes and Agent checkpoints; a crash leaves the old version, not half a file
- **Durable background save**: `onStop` writes synchronously, so a kill right after backgrounding cannot drop the latest snapshot
- **Bounded I/O**: 5MB editor files, 8MB checkpoint blobs, 32MB SAF imports, 16MB Agent session logs, 10k file-tree nodes, 2MB AI responses, 200KB share/clipboard text
- **Lifecycle cleanup**: Back closing the terminal stops the PTY; closing the Agent panel cancels the running Agent; renaming/deleting a directory migrates/removes its open tabs
- **Agent overwrite guard**: Agent edits and checkpoint restore never silently replace an unsaved editor buffer
- **Execution robustness**: foreground-service stop no longer relies on background `startService`; a partial wakelock keeps long scripts running with the screen off; PTY input is FIFO and JNI callback exceptions are cleared
- **Theme/IME polish**: status/navigation bar icon contrast follows the in-app theme; two-finger pinch no longer steals one-finger editor scrolling

### Mobile layout & keyboard (0.0.30)
- **No more clipped panels**: every dialog is edge-to-edge and sized to the area above the IME; title, footer input and action buttons stay fixed while only the body scrolls
- **Terminal resizes with the keyboard**: PTY body uses the remaining height, so Esc/Tab/Ctrl/arrow keys stay visible instead of being pushed under the soft keyboard
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 = 30
versionName = "0.0.30"
versionCode = 31
versionName = "0.0.31"
vectorDrawables { useSupportLibrary = true }
// 原生 CPython 引擎:同时打 arm64 与 x86_64(后者用于模拟器/ChromeOS)
ndk { abiFilters += listOf("arm64-v8a", "x86_64") }
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<!-- 仅 AI 助手(可选功能)访问用户自配端点使用;默认未配置时 App 不发起任何网络请求 -->
<uses-permission android:name="android.permission.INTERNET" />
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/cpp/ptybridge.c
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ static void call_bytes(JNIEnv *env, const char *buf, int len) {
if (!arr) return;
(*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)buf);
(*env)->CallVoidMethod(env, g_callback, g_on_bytes, arr);
// Kotlin 回调一旦抛异常,异常会挂在 native 线程上;不清理会让后续所有
// JNI 调用(包括 on_exit)失败。终端已经出错时静默丢弃本次回调即可。
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
(*env)->DeleteLocalRef(env, arr);
}

Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/com/devterminal/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.material3.Surface
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.devterminal.engine.CrashLogger
import com.devterminal.settings.resolvesDark
import com.devterminal.ui.EditorScreen
import com.devterminal.ui.EditorViewModel
import com.devterminal.ui.theme.CodePocketTheme
Expand All @@ -34,6 +37,15 @@ class MainActivity : ComponentActivity() {
setContent {
// 主题跟随用户设置(跟随系统/浅色/深色),设置页可实时切换
val ui by viewModel.ui.collectAsStateWithLifecycle()
val dark = ui.settings.themeMode.resolvesDark(this@MainActivity)
// enableEdgeToEdge 只按系统深色模式定一次状态栏图标;App 内切换主题后
// 必须同步图标明暗,否则深色主题 + 浅色系统会出现「黑图标压黑背景」。
LaunchedEffect(dark) {
WindowCompat.getInsetsController(window, window.decorView).apply {
isAppearanceLightStatusBars = !dark
isAppearanceLightNavigationBars = !dark
}
}
CodePocketTheme(themeMode = ui.settings.themeMode) {
// safeDrawingPadding:edge-to-edge 下吃掉系统栏与软键盘(IME) inset,
// 软键盘弹出时整屏内容随之上推,输入框/编辑器不被遮挡。
Expand Down
28 changes: 23 additions & 5 deletions app/src/main/java/com/devterminal/agent/AgentSessionStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,21 @@ class AgentSessionStore(private val dir: File) {
ensureDir()
val file = File(dir, "$sessionId.jsonl")
if (!file.isFile) return
// 单会话日志封顶,避免一个忘记结束的长任务把手机存储写满。
if (file.length() >= MAX_SESSION_BYTES) return
file.appendText(AgentEventCodec.encode(event) + "\n")
}

fun read(sessionId: String): List<AgentEvent> {
val file = File(dir, "$sessionId.jsonl")
if (!file.isFile) return emptyList()
return file.useLines { lines ->
lines.drop(1).mapNotNull { line ->
if (line.isBlank()) null else AgentEventCodec.decode(line)
}.toList()
lines.drop(1)
.take(MAX_REPLAY_EVENTS)
.mapNotNull { line ->
if (line.isBlank()) null else AgentEventCodec.decode(line)
}
.toList()
}
}

Expand All @@ -74,7 +79,7 @@ class AgentSessionStore(private val dir: File) {
fun delete(sessionId: String): Boolean = File(dir, "$sessionId.jsonl").delete()

private fun metaOf(file: File): AgentSessionMeta? {
val lines = runCatching { file.readLines() }.getOrNull() ?: return null
val lines = runCatching { file.useLines { it.toList() } }.getOrNull() ?: return null
val head = lines.firstOrNull() ?: return null
val json = runCatching { JSONObject(head) }.getOrNull() ?: return null
if (json.optString("type") != "session_meta") return null
Expand All @@ -92,14 +97,27 @@ class AgentSessionStore(private val dir: File) {
)
}

private fun prune(keep: Int = 30) {
private fun prune(keep: Int = 30, maxTotalBytes: Long = 128L * 1024 * 1024) {
val files = dir.listFiles { file -> file.isFile && file.extension == "jsonl" }
?.sortedByDescending { it.lastModified() }
?: return
files.drop(keep).forEach { it.delete() }
val kept = files.take(keep)
var total = kept.sumOf { it.length() }
// 即使份数没超,总占用也要设上限;从最旧的会话开始删。
kept.asReversed().forEach { file ->
if (total <= maxTotalBytes) return@forEach
total -= file.length()
file.delete()
}
}

private fun ensureDir() {
if (!dir.isDirectory) dir.mkdirs()
}

private companion object {
const val MAX_SESSION_BYTES = 16L * 1024 * 1024
const val MAX_REPLAY_EVENTS = 2000
}
}
39 changes: 38 additions & 1 deletion app/src/main/java/com/devterminal/agent/CheckpointStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.devterminal.agent

import com.devterminal.workspace.Workspace
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.URLDecoder
import java.net.URLEncoder
Expand Down Expand Up @@ -46,6 +47,9 @@ class CheckpointStore(
for (path in distinct.sorted()) {
val file = workspace.resolve(path)
require(file.isFile) { "Not a file: $path" }
require(file.length() <= MAX_SNAPSHOT_BYTES) {
"文件过大,无法建立检查点:$path (${file.length()} bytes)"
}
val bytes = file.readBytes()
val hash = sha256(bytes)
val blob = File(blobsDir, hash)
Expand All @@ -54,6 +58,9 @@ class CheckpointStore(
}

writeAtomic(File(snapshotsDir, "$id.tsv"), body.toString().toByteArray(Charsets.UTF_8))
// 快照会持续产生新 blob;每次落盘后回收无引用对象并限制保留份数,
// 否则反复 Agent 修改/撤销会把手机存储慢慢吃满。
runCatching { gc() }
return Checkpoint(id, label, createdAt, distinct.sorted())
}

Expand All @@ -63,6 +70,7 @@ class CheckpointStore(
for ((path, expectedHash) in manifest.entries) {
val blob = File(blobsDir, expectedHash)
if (!blob.isFile) throw IOException("Missing checkpoint blob: $expectedHash")
require(blob.length() <= MAX_SNAPSHOT_BYTES) { "Checkpoint blob too large: $expectedHash" }
val bytes = blob.readBytes()
val actual = sha256(bytes)
if (actual != expectedHash) throw IOException("Checkpoint blob is corrupted: $expectedHash")
Expand All @@ -89,6 +97,27 @@ class CheckpointStore(
fun delete(checkpointId: String) {
val file = File(snapshotsDir, "$checkpointId.tsv")
if (!file.delete() && file.exists()) throw IOException("Cannot delete checkpoint: $checkpointId")
runCatching { gc() }
}

/** 只保留最近 [MAX_CHECKPOINTS] 份快照,并删除没有任何清单引用的 blob。 */
private fun gc() {
ensureDirs()
val manifests = snapshotsDir.listFiles { f -> f.isFile && f.name.endsWith(".tsv") }
?.sortedByDescending { it.lastModified() }
?: return
manifests.drop(MAX_CHECKPOINTS).forEach { runCatching { it.delete() } }

val referenced = HashSet<String>()
// 只引用「实际还存在」的清单:若旧清单删除失败,它的 blob 不能被误删。
manifests.filter { it.exists() }.forEach { file ->
runCatching {
readManifest(file.name.removeSuffix(".tsv")).entries.forEach { referenced += it.second }
}
}
blobsDir.listFiles()?.forEach { blob ->
if (blob.isFile && blob.name !in referenced) runCatching { blob.delete() }
}
}

private fun readManifest(id: String): Manifest {
Expand Down Expand Up @@ -128,7 +157,10 @@ class CheckpointStore(
private fun writeAtomic(target: File, bytes: ByteArray) {
val temp = File(target.parentFile, ".${target.name}.tmp-${UUID.randomUUID()}")
try {
temp.writeBytes(bytes)
FileOutputStream(temp).use { out ->
out.write(bytes)
out.fd.sync()
}
if (!temp.renameTo(target)) {
target.outputStream().use { it.write(bytes) }
}
Expand All @@ -145,4 +177,9 @@ class CheckpointStore(
private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8")

private fun decode(value: String): String = URLDecoder.decode(value, "UTF-8")

private companion object {
const val MAX_SNAPSHOT_BYTES = 8L * 1024 * 1024
const val MAX_CHECKPOINTS = 20
}
}
13 changes: 12 additions & 1 deletion app/src/main/java/com/devterminal/agent/tools/RunCommandTool.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.devterminal.agent.tools

import android.os.Build
import com.devterminal.agent.Tool
import com.devterminal.agent.ToolCall
import com.devterminal.agent.ToolResult
Expand Down Expand Up @@ -61,7 +62,8 @@ class RunCommandTool : Tool {
}
if (isProcessAlive(process)) {
timedOut = true
process.destroy()
destroyTree(process)
runCatching { process.inputStream.close() }
}
reader.join(1500)
val exitCode = if (timedOut) -1 else runCatching { process.exitValue() }.getOrDefault(-1)
Expand All @@ -78,6 +80,15 @@ 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() }
}

private fun isProcessAlive(process: Process): Boolean = runCatching {
process.exitValue()
false
Expand Down
18 changes: 17 additions & 1 deletion app/src/main/java/com/devterminal/engine/AiClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class AiClient(private val settings: com.devterminal.settings.AppSettings) {
BufferedReader(InputStreamReader(conn.inputStream, Charsets.UTF_8))
else
BufferedReader(InputStreamReader(conn.errorStream ?: conn.inputStream, Charsets.UTF_8))
val resp = reader.use { it.readText() }
val resp = reader.use { readCapped(it) }

if (code !in 200..299) {
if (isRetryable(code) && attempt < MAX_ATTEMPTS) {
Expand Down Expand Up @@ -215,6 +215,22 @@ class AiClient(private val settings: com.devterminal.settings.AppSettings) {
}
}

/** 限制单次响应体积;BYOK 端点异常返回超大内容时不能把手机内存打爆。 */
private fun readCapped(reader: BufferedReader, maxChars: Int = 2_000_000): String {
val sb = StringBuilder()
val buffer = CharArray(8192)
while (true) {
val n = reader.read(buffer)
if (n < 0) break
if (sb.length + n > maxChars) {
sb.append(buffer, 0, (maxChars - sb.length).coerceAtLeast(0))
break
}
sb.append(buffer, 0, n)
}
return sb.toString()
}

private fun parseChoices(raw: String): String = runCatching {
val json = JSONObject(raw)
json.getJSONArray("choices").getJSONObject(0)
Expand Down
Loading
Loading