Skip to content
Merged
6 changes: 5 additions & 1 deletion app/src/main/java/com/wangzan101/mika/MikaApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.wangzan101.mika.chat.WorkspaceResolver
import com.wangzan101.mika.core.cap.sandbox.SandboxStatus
import com.wangzan101.mika.cap.sandbox.AndroidSandbox
import com.wangzan101.mika.cap.sandbox.Attachments
import com.wangzan101.mika.cap.sandbox.AttachmentLimits
import com.wangzan101.mika.cap.sandbox.WorkspaceKey
import com.wangzan101.mika.ui.AttachFiles
import com.wangzan101.mika.cap.sandbox.ShareExporter
Expand Down Expand Up @@ -525,7 +526,10 @@ class MikaApp : Application(), WebOwner, SandboxOwner, TaskEnvironment.Owner, Ph
val sandbox = AndroidSandbox(app, SandboxState.get(app))
val dirs = SandboxDirs(app)
val key = workspaceResolver.resolve(id)
Attachments.importInto(app, uris.map(Uri::parse), dirs.workspace(key), dirs.gate, dirs.tree, sandbox::freeBytes) { sandbox.workspaceBytes(key) }
val flags = FeatureFlags.get(app)
Attachments.importInto(app, uris.map(Uri::parse), dirs.workspace(key), dirs.gate, dirs.tree,
freeBytes = sandbox::freeBytes, workspaceBytes = { sandbox.workspaceBytes(key) },
limits = AttachmentLimits(flags.attachmentMaxBytes(), flags.workspaceMaxBytes()))
},
describeAttachments = { uris -> AttachFiles.describe(app, uris) },
deletionImpact = conversationDeleter::impact,
Expand Down
36 changes: 23 additions & 13 deletions app/src/main/java/com/wangzan101/mika/cap/sandbox/Attachments.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ data class AttachmentFailure(val name: String, val reason: AttachmentFailureReas

enum class AttachmentFailureReason { TOO_LARGE, LOW_DEVICE_SPACE, WORKSPACE_LIMIT, IO_ERROR }

/** 单文件与工作区两道存储上限;设置里调档后由调用方注入,默认与历史写死值一致。 */
data class AttachmentLimits(
val maxFileBytes: Long = Attachments.MAX_BYTES,
val workspaceMaxBytes: Long = Attachments.WORKSPACE_MAX,
) {
companion object { val DEFAULT = AttachmentLimits() }
}

/** 用户在聊天里附加的文件:复制进当前对话工作区的 inbox/,沙箱里在 /workspace/inbox/。 */
object Attachments {
const val MAX_BYTES = 200L shl 20
Expand Down Expand Up @@ -57,13 +65,14 @@ object Attachments {
fun numbered(name: String, n: Int): String = WorkspaceFileGate.numbered(name, n)

/**
* 复制到 [workspace] 下的 inbox/;每个文件 ≤ 200 MB(超过的删掉、记进 rejected)。
* 每个文件开始前(复制中每 16 MB 也)看一次空间:手机可用空间低于 500 MB、或工作区超过 4 GB 就不收。
* 复制到 [workspace] 下的 inbox/;每个文件 ≤ [AttachmentLimits.maxFileBytes](超过的删掉、记进 rejected)。
* 每个文件开始前(复制中每 16 MB 也)看一次空间:手机可用空间低于 500 MB、或工作区超过 [AttachmentLimits.workspaceMaxBytes] 就不收。
* 经 [gate] 在 inbox/ 里新建(不覆盖、按句柄核实):inbox 被沙箱里的命令换成链接也写不出去;失败时只删自己建的那个文件。
*/
suspend fun importInto(
context: Context, uris: List<Uri>, workspace: File, gate: WorkspaceFileGate, tree: SandboxTree,
freeBytes: () -> Long = { workspace.usableSpace }, workspaceBytes: () -> Long = { 0L },
limits: AttachmentLimits = AttachmentLimits.DEFAULT,
): ImportResult = tree.shared { withContext(Dispatchers.IO) { // 写进 files/sandbox/:和重置互斥
val added = mutableListOf<Pair<String, Long>>()
val failures = mutableListOf<AttachmentFailure>()
Expand All @@ -73,35 +82,35 @@ object Attachments {
val base = safeName(display)
val result = importOne(workspace, gate, base, freeBytes, workspaceBytes, {
context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open attachment")
}) { e ->
}, logFailure = { e ->
Log.w(TAG, "Attachment import failed for \"$base\" (${e.javaClass.simpleName}: ${e.message})")
}
}, limits = limits)
added += result.added
failures += result.failures
}
ImportResult(added, failures.map { it.name }, failures)
} }

private fun roomFailure(freeBytes: () -> Long, workspaceBytes: () -> Long): AttachmentFailureReason? = when {
private fun roomFailure(freeBytes: () -> Long, workspaceBytes: () -> Long, limits: AttachmentLimits): AttachmentFailureReason? = when {
freeBytes() < MIN_FREE -> AttachmentFailureReason.LOW_DEVICE_SPACE
workspaceBytes() > WORKSPACE_MAX -> AttachmentFailureReason.WORKSPACE_LIMIT
workspaceBytes() > limits.workspaceMaxBytes -> AttachmentFailureReason.WORKSPACE_LIMIT
else -> null
}

internal suspend fun importOne(
workspace: File, gate: WorkspaceFileGate, base: String,
freeBytes: () -> Long, workspaceBytes: () -> Long, open: () -> InputStream,
onCopied: (Pair<String, Long>) -> Unit = {},
logFailure: (Exception) -> Unit = {},
logFailure: (Exception) -> Unit = {}, limits: AttachmentLimits = AttachmentLimits.DEFAULT,
): ImportResult {
fun failure(e: Exception): ImportResult {
logFailure(e)
val reason = (e as? AttachmentLimitException)?.reason ?: AttachmentFailureReason.IO_ERROR
return ImportResult(emptyList(), listOf(base), listOf(AttachmentFailure(base, reason)))
}
val copied = try {
roomFailure(freeBytes, workspaceBytes)?.let { throw AttachmentLimitException(it) }
copyOne(workspace, gate, base, { roomFailure(freeBytes, workspaceBytes) }, open)
roomFailure(freeBytes, workspaceBytes, limits)?.let { throw AttachmentLimitException(it) }
copyOne(workspace, gate, base, { roomFailure(freeBytes, workspaceBytes, limits) }, open, limits.maxFileBytes)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Expand All @@ -128,13 +137,14 @@ object Attachments {
/** Keep the exact handles until the phone accepts the task, so a failed batch leaves no partial input. */
suspend fun <T> withTaskFiles(
sources: List<Pair<String, File>>, workspace: File, gate: WorkspaceFileGate, tree: SandboxTree,
room: () -> Boolean, launch: (List<Pair<String, Long>>) -> T,
room: () -> Boolean, limits: AttachmentLimits = AttachmentLimits.DEFAULT,
launch: (List<Pair<String, Long>>) -> T,
): T = tree.shared {
val created = mutableListOf<GatedFile>()
try {
for ((name, source) in sources) {
if (!room()) throw IOException("Not enough space for task attachments")
created += copyOne(workspace, gate, safeName(name), { if (room()) null else AttachmentFailureReason.IO_ERROR }) { source.inputStream() }
created += copyOne(workspace, gate, safeName(name), { if (room()) null else AttachmentFailureReason.IO_ERROR }, { source.inputStream() }, limits.maxFileBytes)
}
launch(created.map { it.entry() })
} catch (e: Throwable) {
Expand All @@ -144,7 +154,7 @@ object Attachments {
}

private suspend fun copyOne(workspace: File, gate: WorkspaceFileGate, base: String, room: () -> AttachmentFailureReason?,
open: () -> InputStream): GatedFile {
open: () -> InputStream, maxFileBytes: Long = MAX_BYTES): GatedFile {
workspace.mkdirs()
val (_, g) = gate.createNumbered(workspace, INBOX, base, max = 1000)
var size = 0L
Expand All @@ -156,7 +166,7 @@ object Attachments {
val r = input.read(buf)
if (r < 0) break
size += r
if (size > MAX_BYTES) throw AttachmentLimitException(AttachmentFailureReason.TOO_LARGE)
if (size > maxFileBytes) throw AttachmentLimitException(AttachmentFailureReason.TOO_LARGE)
if (size % CHECK_EVERY < r) room()?.let { throw AttachmentLimitException(it) }
g.write(if (r == buf.size) buf else buf.copyOf(r))
}
Expand Down
39 changes: 39 additions & 0 deletions app/src/main/java/com/wangzan101/mika/settings/FeatureFlags.kt
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,35 @@ class FeatureFlags(private val prefs: SharedPreferences) {
prefs.edit().putInt(SANDBOX_BUDGET_LIMIT, minutes.takeIf { it in SANDBOX_BUDGET_MINUTES } ?: 0).commit()
}

/**
* 单个上传文件(聊天附件、微信图片、电脑发任务带的文件)最大多少 MB;只认 [ATTACHMENT_FILE_LIMIT_MB] 里的几档,
* 没设或存了别的值按默认(与 Attachments.MAX_BYTES 一致)算,改完下一次导入生效。
*/
fun attachmentMaxMb(): Int =
prefs.getInt(ATTACHMENT_FILE_LIMIT, 0).takeIf { it in ATTACHMENT_FILE_LIMIT_MB } ?: DEFAULT_ATTACHMENT_FILE_LIMIT_MB

fun attachmentMaxBytes(): Long = attachmentMaxMb().toLong() shl 20

fun setAttachmentMaxMb(mb: Int) {
prefs.edit().putInt(ATTACHMENT_FILE_LIMIT, mb.takeIf { it in ATTACHMENT_FILE_LIMIT_MB } ?: 0).commit()
}

/**
* 一个工作区(对话沙箱目录)最多占多少 GB;只认 [WORKSPACE_LIMIT_GB] 里的几档,
* 没设或存了别的值按默认(与 Attachments.WORKSPACE_MAX 一致)算。
*/
fun workspaceMaxGb(): Int =
prefs.getInt(WORKSPACE_LIMIT, 0).takeIf { it in WORKSPACE_LIMIT_GB } ?: DEFAULT_WORKSPACE_LIMIT_GB

fun workspaceMaxBytes(): Long = workspaceMaxGb().toLong() shl 30

/** 聊天附件与设备文件导入共用的体积档位,每次取用都是当前设置。 */
fun attachmentLimits() = com.wangzan101.mika.cap.sandbox.AttachmentLimits(attachmentMaxBytes(), workspaceMaxBytes())

fun setWorkspaceMaxGb(gb: Int) {
prefs.edit().putInt(WORKSPACE_LIMIT, gb.takeIf { it in WORKSPACE_LIMIT_GB } ?: 0).commit()
}

/** 每个任务允许已报告的输入加输出 Token 总量;null 表示不限制,下次任务起生效。 */
fun taskTokenBudget(): Long? = prefs.getLong(TASK_TOKEN_BUDGET, 0L).takeIf(TokenBudgetLimits::valid)

Expand Down Expand Up @@ -446,6 +475,14 @@ class FeatureFlags(private val prefs: SharedPreferences) {
val SANDBOX_BUDGET_MINUTES = listOf(30, 60, 120, 240)
/** 每任务沙箱命令累计时长没设(或存了档位外的值)时按这个算,与 core 的 [SANDBOX_BUDGET_MS] 一致。 */
val DEFAULT_SANDBOX_BUDGET_MINUTES = (com.wangzan101.mika.core.cap.sandbox.SANDBOX_BUDGET_MS / 60_000L).toInt()
/** 单个上传文件体积可选的几档(MB)。 */
val ATTACHMENT_FILE_LIMIT_MB = listOf(200, 512, 1024, 2048)
/** 单文件上限没设(或存了档位外的值)时按这个算,与 Attachments.MAX_BYTES 一致。 */
val DEFAULT_ATTACHMENT_FILE_LIMIT_MB = (com.wangzan101.mika.cap.sandbox.Attachments.MAX_BYTES shr 20).toInt()
/** 单个工作区空间可选的几档(GB)。 */
val WORKSPACE_LIMIT_GB = listOf(4, 8, 16, 32)
/** 工作区上限没设(或存了档位外的值)时按这个算,与 Attachments.WORKSPACE_MAX 一致。 */
val DEFAULT_WORKSPACE_LIMIT_GB = (com.wangzan101.mika.cap.sandbox.Attachments.WORKSPACE_MAX shr 30).toInt()
private const val SPEED_FLAGS = "speed_flags"
/**
* 提速开关默认值的升级,按先后各做一次(键记下做过没有):v2 打开分级读屏、连续操作、按需看图;
Expand All @@ -462,6 +499,8 @@ class FeatureFlags(private val prefs: SharedPreferences) {
private const val TASK_STEP_LIMIT = "task_step_limit"
private const val TRIGGER_RUN_LIMIT = "trigger_run_limit_minutes"
private const val SANDBOX_BUDGET_LIMIT = "sandbox_budget_limit_minutes"
private const val ATTACHMENT_FILE_LIMIT = "attachment_file_limit_mb"
private const val WORKSPACE_LIMIT = "workspace_limit_gb"
private const val TASK_TOKEN_BUDGET = "task_token_budget"
private const val PROACTIVE_DAILY_TOKEN_BUDGET = "proactive_daily_token_budget"
private const val KEEP_SCREEN_ON = "keep_screen_on"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.os.Bundle
import android.os.ParcelFileDescriptor
import com.wangzan101.mika.cap.phone.shell.HelperHub
import com.wangzan101.mika.cap.sandbox.AndroidSandbox
import com.wangzan101.mika.cap.sandbox.AttachmentLimits
import com.wangzan101.mika.cap.sandbox.SandboxDirs
import com.wangzan101.mika.cap.sandbox.WorkspaceKey
import com.wangzan101.mika.settings.DeviceDirectory
Expand All @@ -29,7 +30,8 @@ internal class AndroidDeviceFiles(
constructor(hub: HelperHub, dirs: SandboxDirs, sandbox: AndroidSandbox, directoryStore: DeviceDirectoryStore,
imports: DeviceImportStore, resolveWorkspace: (String) -> WorkspaceKey = WorkspaceKey::parse,
conversationIdFor: (String) -> String = { it },
) : this(hub, directoryStore, DeviceWorkspaceImports(dirs, sandbox::freeBytes, imports, resolveWorkspace, conversationIdFor))
limits: () -> AttachmentLimits = { AttachmentLimits.DEFAULT },
) : this(hub, directoryStore, DeviceWorkspaceImports(dirs, sandbox::freeBytes, imports, resolveWorkspace, conversationIdFor, limits))

private fun hint(directory: DeviceDirectory): DeviceDirectoryHint {
val status = try { hub.listFiles(directory.path, null, 1).getString("status") ?: "helper_error" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.wangzan101.mika.cap.sandbox.AndroidSandbox
import com.wangzan101.mika.cap.sandbox.AttachmentLimits
import com.wangzan101.mika.cap.sandbox.Attachments
import com.wangzan101.mika.cap.sandbox.SandboxDirs
import com.wangzan101.mika.cap.sandbox.WorkspaceKey
Expand All @@ -23,6 +24,8 @@ internal class DeviceWorkspaceImports(
private val imports: DeviceImportStore,
private val resolveWorkspace: (String) -> WorkspaceKey,
private val conversationIdFor: (String) -> String,
/** 每次导入现取设置里的档位(聊天附件与设备导入共用),改完下一次导入即生效。 */
private val limits: () -> AttachmentLimits = { AttachmentLimits.DEFAULT },
) {
suspend fun fromFolder(path: String, workspace: String, open: (String) -> InputStream) = locked {
// Open through the live SAF grant before touching the workspace or consulting its history.
Expand Down Expand Up @@ -70,7 +73,7 @@ internal class DeviceWorkspaceImports(
},
logFailure = { error ->
if (error is SecurityException) throw SandboxError("device_access_denied", "Access to the device file was denied.", true)
})
}, limits = limits())
val entry = result.added.singleOrNull() ?: run {
val reason = result.failures.firstOrNull()?.reason?.name?.lowercase() ?: "io_error"
throw SandboxError(reason, "Could not copy the device file to the workspace ($reason).", true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ internal class PhoneTaskFiles(private val context: Context, private val exported
val sandbox = AndroidSandbox(context, SandboxState.get(context))
val key = WorkspaceResolver.resolveFor(context, conversation)
val bytes = files.sumOf { it.size }
// 电脑传输不在存储档位范围内:电脑端 RemoteTaskFiles 也是固定 200 MB,这里保持同一定额
if (sandbox.freeBytes() - bytes < Attachments.MIN_FREE || sandbox.workspaceBytes(key) + bytes > Attachments.WORKSPACE_MAX)
throw IOException("Not enough space for attachments")
return runBlocking(Dispatchers.IO) {
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/java/com/wangzan101/mika/task/RunToolStage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ internal suspend fun TaskRun.assembleTools(a: RunAssembly, m: RunModels, ph: Run
val deviceImports = if (provenance.origin == RunOrigin.Ui &&
provenance.attendance != Attendance.Unattended && !runSpec.readOnly) {
DeviceWorkspaceImports(SandboxDirs(service), sandbox::freeBytes, DeviceImportStore.get(service),
resolveWorkspace = { workspaceKey }, conversationIdFor = { conversationId })
resolveWorkspace = { workspaceKey }, conversationIdFor = { conversationId },
limits = { FeatureFlags.get(service).attachmentLimits() }) // 每次导入现取档位,与聊天附件同一套
} else null
val folders = sandbox.folderFiles as? GrantedFolderFiles
val tools = toolDispatcher(privatePhone, model.capabilities.vision, catalog, recordFrames = true,
Expand Down
17 changes: 11 additions & 6 deletions app/src/main/java/com/wangzan101/mika/ui/ChatComposer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import com.wangzan101.mika.ui.theme.MikaTheme
import com.wangzan101.mika.ui.theme.MikaType
import com.wangzan101.mika.voice.HoldToTalk
import com.wangzan101.mika.voice.VoiceSource
import com.wangzan101.mika.i18n.trPlural

/**
* 玻璃胶囊输入栏:左边「+」,右边发送(没内容时灰);任务在跑时多一个停止,补充消息先排在输入栏上方。
Expand Down Expand Up @@ -174,15 +175,19 @@ internal fun Composer(
Column(Modifier.fillMaxWidth().padding(start = 4.dp, bottom = 6.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
if (importing) Text(AttachCopy.IMPORTING, style = MikaType.Caption, color = c.ink3)
if (rejected.isNotEmpty() || overLimit > 0) {
// 超限提示写当前档位,不再硬编码 200 MiB
val ctx = LocalContext.current
val attachmentLimitLabel = remember(ctx) {
trPlural(R.plurals.settings_attachment_file_limit_mb_n, com.wangzan101.mika.settings.FeatureFlags.get(ctx).attachmentMaxMb())
}
val why = listOfNotNull(
rejected.takeIf { it.isNotEmpty() }?.map { failure ->
val reason = when (failure.reason) {
AttachmentFailureReason.TOO_LARGE -> R.string.chat_attach_too_large
AttachmentFailureReason.LOW_DEVICE_SPACE -> R.string.chat_attach_low_device_space
AttachmentFailureReason.WORKSPACE_LIMIT -> R.string.chat_attach_workspace_limit
AttachmentFailureReason.IO_ERROR -> R.string.chat_attach_io_error
when (failure.reason) {
AttachmentFailureReason.TOO_LARGE -> stringResource(R.string.chat_attach_too_large, failure.name, attachmentLimitLabel)
AttachmentFailureReason.LOW_DEVICE_SPACE -> stringResource(R.string.chat_attach_low_device_space, failure.name)
AttachmentFailureReason.WORKSPACE_LIMIT -> stringResource(R.string.chat_attach_workspace_limit, failure.name)
AttachmentFailureReason.IO_ERROR -> stringResource(R.string.chat_attach_io_error, failure.name)
}
stringResource(reason, failure.name)
}?.joinToString("\n"),
overLimit.takeIf { it > 0 }?.let(AttachCopy::overLimit),
).joinToString("\n")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ internal fun DeviceFileBrowser(vm: ChatViewModel, conversationId: String, onClos
AndroidSandbox(context, SandboxState.get(context)),
directories,
importStore,
resolveWorkspace = WorkspaceResolver.resolver(context),
resolveWorkspace = WorkspaceResolver.resolver(context), limits = { FeatureFlags.get(context).attachmentLimits() },
)
}
val records by remember(importStore) {
Expand Down
Loading
Loading