Add enhanced one-session diagnostic bundles

This commit is contained in:
wallentx authored and Kurt Himebauch committed 2026-11-05 13:32:46 -05:00
1 parent b563b8d1eb
commit 5614bd5d5a
32 files changed
+3100 -141

No files matched your search

@@ -577,6 +577,7 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var enhancedDiagnosticsArmed by mutableStateOf(false)
private var gameDebugLogsEnabled by mutableStateOf(false)
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
@@ -1136,6 +1137,7 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
@@ -1327,6 +1329,15 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onEnhancedDiagnostics = {
val requested = !com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
if (!com.droiddeck.launcher.session.EnhancedDiagnostics.setArmed(this, requested)) {
android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
}
enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
},
onGameDebugLogs = {
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
if (!changed) android.widget.Toast.makeText(
@@ -1350,9 +1361,19 @@ class FrontEndActivity : ComponentActivity() {
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
},
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
val folder = SessionLogShare.latest(this)
if (folder == null) {
android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
} else if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
if (zips.isEmpty()) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else shareEnhancedArchives(zips)
}
} else {
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
}
}
},
onShareSessionLog = { folder ->
@@ -2688,6 +2709,26 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
!SessionPaths.currentSessionLogsRetained(this)
private fun shareEnhancedArchives(zips: List<java.io.File>) {
val choices = zips.map { zip ->
val label = when {
zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
else -> getString(R.string.diagnostics_share_games)
}
label to listOf(zip)
} + (getString(R.string.diagnostics_share_all) to zips)
android.app.AlertDialog.Builder(this)
.setTitle(R.string.diagnostics_share_title)
.setItems(choices.map { it.first }.toTypedArray()) { _, which ->
val selected = choices[which].second
startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
else SessionLogShare.shareEnhancedIntent(this, selected))
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun refresh() {
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
@@ -2712,6 +2753,7 @@ class FrontEndActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
@@ -1884,7 +1884,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Toast.makeText(this, R.string.session_no_logs, Toast.LENGTH_LONG).show()
return
}
SessionLogShare.prepare(this, { folder }) { zip ->
if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
if (zips.isEmpty()) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else runCatching { shareEnhancedArchives(zips) }
.onFailure {
Log.w(TAG, "could not share current session logs", it)
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
}
}
} else SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else {
@@ -1897,6 +1907,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun shareEnhancedArchives(zips: List<File>) {
val choices = zips.map { zip ->
val label = when {
zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
else -> getString(R.string.diagnostics_share_games)
}
label to listOf(zip)
} + (getString(R.string.diagnostics_share_all) to zips)
android.app.AlertDialog.Builder(this)
.setTitle(R.string.diagnostics_share_title)
.setItems(choices.map { it.first }.toTypedArray()) { _, which ->
val selected = choices[which].second
startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
else SessionLogShare.shareEnhancedIntent(this, selected))
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -131,42 +131,81 @@ object LogRedactor {
@Volatile
private var accounts: List<Learned> = emptyList()
fun learnAccounts(vararg loginUsers: java.io.File) {
internal const val MAX_LEARN_INPUT_BYTES = 2 * 1024 * 1024
private const val MAX_LEARNED_ACCOUNTS = 2048
private const val MAX_LEARNED_ADDRESSES = 1024
private const val MAX_ACCOUNT_LENGTH = 256
private fun boundedText(file: java.io.File): String? = try {
file.inputStream().buffered().use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
var remaining = MAX_LEARN_INPUT_BYTES
while (remaining > 0) {
val read = input.read(buffer, 0, minOf(buffer.size, remaining))
if (read < 0) return out.toString(Charsets.UTF_8.name())
if (read == 0) continue
out.write(buffer, 0, read)
remaining -= read
}
if (input.read() != -1) null else out.toString(Charsets.UTF_8.name())
}
} catch (_: Exception) {
null
}
fun learnAccounts(vararg loginUsers: java.io.File): Boolean {
val names = LinkedHashSet<String>()
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
var unread = false
for (file in loginUsers) {
if (!file.isFile) continue
val text = try { file.readText() } catch (e: Exception) { unread = true; continue }
kv.findAll(text).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.forEach { names += it }
val text = boundedText(file)
if (text == null) {
unread = true
continue
}
for (match in kv.findAll(text)) {
val name = match.groupValues[2].trim()
if (name.length < 3) continue
if (name.length > MAX_ACCOUNT_LENGTH || names.size >= MAX_LEARNED_ACCOUNTS) {
unread = true
break
}
names += name
}
}
val learned = names.map { name ->
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
}
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
accounts = if (unread) (learned + accounts).distinctBy { it.regex.pattern }.take(MAX_LEARNED_ACCOUNTS) else learned
return !unread
}
fun learnFromRuntime(root: java.io.File) {
learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
learnAccounts(
fun learnFromRuntime(root: java.io.File): Boolean {
val addressesComplete = learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
val accountsComplete = learnAccounts(
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
)
matchers.remove()
return addressesComplete && accountsComplete
}
@Volatile
private var own: List<Learned> = emptyList()
fun learnOwnAddresses(linkFile: java.io.File) {
fun learnOwnAddresses(linkFile: java.io.File): Boolean {
val found = ArrayList<Learned>()
try {
if (linkFile.isFile) linkFile.forEachLine { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
val text = if (linkFile.isFile) boundedText(linkFile) ?: return false else ""
text.lineSequence().forEach { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEach
if (found.size >= MAX_LEARNED_ADDRESSES) return false
when (kind(addr)) {
"public IPv6" -> {
val groups = expand6(addr)?.take(4) ?: return@forEachLine
val groups = expand6(addr)?.take(4) ?: return@forEach
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
found += Learned(
Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?"),
@@ -177,9 +216,10 @@ object LogRedactor {
}
}
} catch (e: Exception) {
return
return false
}
own = found
return true
}
fun kind(address: String): String? {
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object EnhancedDiagnostics {
const val MANIFEST_FILE = "enhanced-diagnostics.json"
private const val TAG = "EnhancedDiagnostics"
private const val PREFS = "session"
private const val ARMED = "enhancedDiagnosticsNext"
private const val ACTIVE_RECORDS = "enhancedDiagnosticsActiveSessions"
private const val SCHEMA = 1
fun isArmed(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ARMED, false)
fun setArmed(context: Context, armed: Boolean): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(ARMED, armed).commit()
fun isActive(context: Context, folder: File?): Boolean = activeAt(context, folder) != null
internal fun isCurrentSessionActive(context: Context): Boolean = isActive(context, SessionPaths.current())
fun manifest(context: Context, folder: File?): JSONObject? {
val activeAt = activeAt(context, folder) ?: return null
return buildManifest(folder!!, activeAt)
}
@Synchronized
internal fun consumeInto(context: Context, folder: File): Boolean {
if (!isArmed(context)) return isActive(context, folder)
if (!folder.isDirectory) return false
val activatedAt = System.currentTimeMillis()
if (!activateAndConsume(context, folder, activatedAt)) return false
val marker = AtomicFile(File(folder, MANIFEST_FILE))
val manifest = buildManifest(folder, activatedAt)
val output = try {
marker.startWrite()
} catch (error: Exception) {
Log.w(TAG, "could not start the informational enhanced diagnostics manifest", error)
return true
}
try {
output.write((manifest.toString() + "\n").toByteArray(Charsets.UTF_8))
marker.finishWrite(output)
} catch (error: Exception) {
marker.failWrite(output)
Log.w(TAG, "could not write the informational enhanced diagnostics manifest", error)
}
return true
}
@Synchronized
internal fun clearRecordFor(context: Context, folder: File) {
removeRecord(context, folder)
}
private fun buildManifest(folder: File, activatedAt: Long) = JSONObject()
.put("schema", SCHEMA)
.put("profile", "enhanced")
.put("sessionId", folder.name)
.put("activatedAtEpochMs", activatedAt)
.put("exportBundlesBounded", true)
.put("rawCaptureByteBounded", false)
.put("rawCaptureLimitation", "Game and component diagnostics may grow until the session ends")
.put("collectorsRequested", JSONArray(listOf(
"session", "graphics", "games", "processes", "audio", "network", "components",
)))
private fun activeAt(context: Context, folder: File?): Long? {
val path = trustedPath(context, folder) ?: return null
return records(context).optLong(path, Long.MIN_VALUE).takeIf { it != Long.MIN_VALUE }
}
private fun activateAndConsume(context: Context, folder: File, activatedAt: Long): Boolean {
val path = trustedPath(context, folder) ?: return false
val records = records(context)
records.keys().asSequence().toList().forEach { known ->
if (!File(known).isDirectory) records.remove(known)
}
records.put(path, activatedAt)
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(ACTIVE_RECORDS, records.toString())
.putBoolean(ARMED, false)
.commit()
}
private fun removeRecord(context: Context, folder: File) {
val path = runCatching { folder.canonicalPath }.getOrNull() ?: return
val records = records(context)
if (records.has(path)) {
records.remove(path)
saveRecords(context, records)
}
}
private fun trustedPath(context: Context, folder: File?): String? {
if (folder == null || !SessionPaths.isSessionFolder(folder)) return null
return runCatching {
val canonical = folder.canonicalFile
if (canonical.parentFile != SessionFiles.logDirectory(context).canonicalFile) null else canonical.path
}.getOrNull()
}
private fun records(context: Context): JSONObject {
val text = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(ACTIVE_RECORDS, null)
return runCatching { JSONObject(text ?: "{}") }.getOrDefault(JSONObject())
}
private fun saveRecords(context: Context, records: JSONObject): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(ACTIVE_RECORDS, records.toString()).commit()
}
@@ -0,0 +1,731 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.channels.Channels
import java.nio.channels.FileChannel
import java.nio.channels.SeekableByteChannel
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.security.MessageDigest
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
internal data class EnhancedShareLimits(
val maxFilesPerArchive: Int = 256,
val maxDiscoveredFiles: Int = 768,
val maxBytesPerFile: Long = 8L * 1024 * 1024,
val maxBytesTotal: Long = 64L * 1024 * 1024,
)
internal object EnhancedSessionLogShare {
private enum class Category(val suffix: String) { SESSION("session"), GRAPHICS("graphics"), GAMES("games") }
private data class Candidate(
val file: File,
val anchor: File,
val entry: String,
val origin: String,
val category: Category,
val linePrefix: String? = null,
)
private data class Record(
val entry: String,
val origin: String,
val status: String,
val sourceBytes: Long = 0,
val capturedBytes: Long = 0,
val reason: String? = null,
)
private data class Snapshot(val file: File, val sourceBytes: Long, val truncated: Boolean)
private data class CollectionResult(val candidates: List<Candidate>, val truncated: Boolean)
private data class ScanResult(val files: List<File>, val truncated: Boolean)
private data class LegacySource(val file: File, val root: File, val entry: String)
private class Budget(val limit: Long, var remaining: Long = limit)
fun create(
context: Context,
folder: File,
onProgress: ((Float) -> Unit)? = null,
limits: EnhancedShareLimits = EnhancedShareLimits(),
): List<File> {
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
return emptyList()
}
val out = SessionLogShare.shareDir(context).apply { deleteRecursively(); mkdirs() }
val stage = File(out, ".diagnostic-stage").apply { mkdirs() }
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = false)
val candidates = discovery.candidates
val totalCandidates = candidates.size.coerceAtLeast(1)
val share = limits.maxBytesTotal / Category.values().size
val budgets = Category.values().associateWith { category ->
Budget(if (category == Category.GAMES) limits.maxBytesTotal - share * 2 else share)
}
var completed = 0
return try {
Category.values().map { category ->
val budget = budgets.getValue(category)
val records = ArrayList<Record>()
val selected = candidates.filter { it.category == category }
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
selected.forEachIndexed { index, candidate ->
val safeEntry = safeEntry(candidate.entry)
val record = when {
index >= limits.maxFilesPerArchive -> Record(
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
)
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
}
records += record
completed++
onProgress?.invoke((completed.toFloat() / totalCandidates).coerceIn(0f, 1f))
}
if (category == Category.SESSION) addTrustedActivation(context, folder, archive)?.let(records::add)
if (selected.isEmpty()) records += Record("", category.suffix, "unavailable", reason = "no-matching-artifacts")
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
addManifest(
archive, folder.name, category.suffix, records, limits, budget.limit, redactionLearningComplete,
)
}
zip
}
} finally {
stage.deleteRecursively()
}
}
fun createLegacy(
context: Context,
folder: File,
onProgress: ((Float) -> Unit)? = null,
limits: EnhancedShareLimits = EnhancedShareLimits(maxFilesPerArchive = 512),
): File? {
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
return null
}
val out = SessionLogShare.shareDir(context).apply { deleteRecursively(); mkdirs() }
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = true)
val candidates = discovery.candidates.filter { it.linePrefix == null }
if (candidates.isEmpty()) {
out.deleteRecursively()
return null
}
val stage = File(out, ".diagnostic-stage").apply { mkdirs() }
val records = ArrayList<Record>()
val budget = Budget(limits.maxBytesTotal)
val zip = File(out, "DroidDeck-${folder.name}.zip")
return try {
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
candidates.forEachIndexed { index, candidate ->
val safeEntry = safeEntry(candidate.entry)
records += when {
index >= limits.maxFilesPerArchive -> Record(
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
)
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
}
onProgress?.invoke((index + 1f) / candidates.size)
}
addTrustedActivation(context, folder, archive)?.let(records::add)
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
addManifest(archive, folder.name, "all", records, limits, budget.limit, redactionLearningComplete)
}
zip
} finally {
stage.deleteRecursively()
}
}
private fun addTrustedActivation(
context: Context,
folder: File,
archive: ZipOutputStream,
): Record? {
val manifest = EnhancedDiagnostics.manifest(context, folder) ?: return null
val bytes = (manifest.toString(2) + "\n").toByteArray()
val entry = "${folder.name}/${EnhancedDiagnostics.MANIFEST_FILE}"
archive.putNextEntry(ZipEntry(entry))
archive.write(bytes)
archive.closeEntry()
return Record(entry, "app-private-activation-state", "captured", bytes.size.toLong(), bytes.size.toLong())
}
private fun addCandidate(
archive: ZipOutputStream,
candidate: Candidate,
stage: File,
budget: Budget,
limits: EnhancedShareLimits,
): Record {
if (budget.remaining <= 0) {
return Record(candidate.entry, candidate.origin, "omitted", reason = "bundle-byte-limit")
}
val snapshot = runCatching {
snapshot(candidate, stage, minOf(limits.maxBytesPerFile, budget.remaining))
}.getOrElse {
return Record(candidate.entry, candidate.origin, "error", reason = it.javaClass.simpleName)
} ?: return Record(candidate.entry, candidate.origin, "omitted", reason = "unsafe-or-unavailable-source")
if (snapshot.file.length() == 0L && candidate.linePrefix != null) {
snapshot.file.delete()
return Record(candidate.entry, candidate.origin, "unavailable", snapshot.sourceBytes, reason = "no-matching-lines")
}
return try {
budget.remaining -= snapshot.file.length()
archive.putNextEntry(ZipEntry(candidate.entry))
val writer = archive.bufferedWriter()
LogRedactor.scrubForShare(snapshot.file, writer)
writer.flush()
archive.closeEntry()
Record(
candidate.entry,
candidate.origin,
if (snapshot.truncated) "truncated" else "captured",
snapshot.sourceBytes,
snapshot.file.length(),
if (snapshot.truncated) "per-file-or-bundle-byte-limit" else null,
)
} finally {
snapshot.file.delete()
}
}
private fun snapshot(candidate: Candidate, stage: File, limit: Long): Snapshot? {
val rootPath = candidate.anchor.toPath().toAbsolutePath().normalize()
val sourcePath = candidate.file.toPath().toAbsolutePath().normalize()
if (!sourcePath.startsWith(rootPath) || sourcePath == rootPath || limit < 1) return null
val target = File.createTempFile("diagnostic-", ".log", stage)
try {
val relative = rootPath.relativize(sourcePath)
return withSecureChannel(rootPath, relative) { input ->
val size = input.size()
candidate.linePrefix?.let { prefix ->
val truncated = filterChannel(input, target, prefix, size, TRACE_SCAN_BYTES, limit)
return@withSecureChannel Snapshot(target, size, truncated)
}
FileOutputStream(target).channel.use { output ->
if (size <= limit) {
copy(input, output, 0, size)
} else {
val marker = "\n<diagnostic file truncated: beginning and tail retained>\n".toByteArray()
val content = (limit - marker.size).coerceAtLeast(0)
copyCompleteHead(input, output, content / 2)
val markerBytes = minOf(marker.size.toLong(), limit - output.position()).toInt()
output.write(ByteBuffer.wrap(marker, 0, markerBytes))
copyCompleteTail(input, output, size, (limit - output.position()).coerceAtLeast(0))
}
output.force(false)
}
Snapshot(target, size, size > limit)
} ?: target.delete().let { null }
} catch (e: Exception) {
target.delete()
throw e
}
}
private fun filterChannel(
channel: SeekableByteChannel,
target: File,
prefix: String,
sourceSize: Long,
scanLimit: Long,
outputLimit: Long,
): Boolean {
val wanted = prefix.toByteArray()
var written = 0L
var truncated = sourceSize > scanLimit
target.outputStream().buffered().use { output ->
fun scan(start: Long, count: Long, discardPartialFirstLine: Boolean) {
channel.position(start)
val input = Channels.newInputStream(channel)
val line = ByteArrayOutputStream(1024)
var oversized = false
var scanned = 0L
var discard = discardPartialFirstLine
fun emit() {
val bytes = line.toByteArray()
if (!discard && !oversized && bytes.size >= wanted.size && wanted.indices.all { bytes[it] == wanted[it] }) {
if (written + bytes.size + 1 <= outputLimit) {
output.write(bytes)
output.write('\n'.code)
written += bytes.size + 1
} else truncated = true
}
line.reset()
oversized = false
discard = false
}
while (scanned < count) {
val value = input.read()
if (value < 0) break
scanned++
if (value == '\n'.code) emit()
else if (!oversized && !discard) {
if (line.size() >= LogRedactor.MAX_LINE_LENGTH) {
oversized = true
line.reset()
} else line.write(value)
}
}
if (start + scanned >= sourceSize && (line.size() > 0 || oversized)) emit()
}
if (sourceSize <= scanLimit) {
scan(0, sourceSize, false)
} else {
val head = scanLimit / 2
val tail = scanLimit - head
scan(0, head, false)
scan((sourceSize - tail).coerceAtLeast(0), tail, true)
}
}
return truncated
}
private fun <T> withSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
val opened = ArrayList<ParcelFileDescriptor>()
return try {
val parts = relative.map { it.toString() }
if (parts.isEmpty()) return null
val rootFd = openDescriptor(root.toString()) ?: return null
if (!OsConstants.S_ISDIR(Os.fstat(rootFd).st_mode)) {
Os.close(rootFd)
return null
}
opened += duplicateAndClose(rootFd)
for (part in parts.dropLast(1)) {
val childFd = openDescriptor(procChild(opened.last(), part)) ?: return null
if (!OsConstants.S_ISDIR(Os.fstat(childFd).st_mode)) {
Os.close(childFd)
return null
}
opened += duplicateAndClose(childFd)
}
val leafFd = openDescriptor(procChild(opened.last(), parts.last())) ?: return null
val stat = Os.fstat(leafFd)
if (!OsConstants.S_ISREG(stat.st_mode) || stat.st_nlink != 1L) {
Os.close(leafFd)
return null
}
val stream = try {
FileInputStream(leafFd)
} catch (error: Exception) {
Os.close(leafFd)
throw error
}
stream.use { block(it.channel) }
} catch (_: Exception) {
null
} finally {
opened.asReversed().forEach { runCatching { it.close() } }
}
}
private fun openDescriptor(path: String): java.io.FileDescriptor? = runCatching {
Os.open(
path,
OsConstants.O_RDONLY or OsConstants.O_CLOEXEC or OsConstants.O_NOFOLLOW or OsConstants.O_NONBLOCK,
0,
)
}.getOrNull()
private fun duplicateAndClose(fd: java.io.FileDescriptor): ParcelFileDescriptor =
try {
ParcelFileDescriptor.dup(fd)
} finally {
Os.close(fd)
}
private fun procChild(directory: ParcelFileDescriptor, name: String): String =
"/proc/self/fd/${directory.fd}/$name"
private fun copy(input: SeekableByteChannel, output: FileChannel, start: Long, count: Long) {
input.position(start)
var left = count
val buffer = ByteBuffer.allocate(64 * 1024)
while (left > 0) {
buffer.clear()
buffer.limit(minOf(buffer.capacity().toLong(), left).toInt())
val read = input.read(buffer)
if (read < 0) break
buffer.flip()
while (buffer.hasRemaining()) output.write(buffer)
left -= read
}
}
private fun copyCompleteHead(input: SeekableByteChannel, output: FileChannel, limit: Long) {
if (limit <= 0) return
copy(input, output, 0, limit)
val copied = output.position()
input.position(0)
val buffer = ByteBuffer.allocate(64 * 1024)
var scanned = 0L
var lastComplete = 0L
while (scanned < copied) {
buffer.clear()
buffer.limit(minOf(buffer.capacity().toLong(), copied - scanned).toInt())
val read = input.read(buffer)
if (read < 0) break
buffer.flip()
repeat(read) { index ->
if (buffer.get(index) == '\n'.code.toByte()) lastComplete = scanned + index + 1
}
scanned += read
}
output.truncate(lastComplete)
output.position(lastComplete)
}
private fun copyCompleteTail(
input: SeekableByteChannel,
output: FileChannel,
sourceSize: Long,
limit: Long,
) {
if (limit <= 0 || sourceSize <= 0) return
var start = (sourceSize - limit).coerceAtLeast(0)
if (start > 0) {
input.position(start)
val one = ByteBuffer.allocate(1)
while (start < sourceSize) {
one.clear()
if (input.read(one) < 0) return
start++
one.flip()
if (one.get() == '\n'.code.toByte()) break
}
}
copy(input, output, start, (sourceSize - start).coerceAtMost(limit))
}
private fun addManifest(
archive: ZipOutputStream,
sessionId: String,
category: String,
records: List<Record>,
limits: EnhancedShareLimits,
categoryBudget: Long,
redactionLearningComplete: Boolean,
) {
val entries = JSONArray()
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
entries.put(JSONObject().apply {
put("entry", record.entry)
put("origin", record.origin)
put("status", record.status)
put("sourceBytes", record.sourceBytes)
put("capturedBytes", record.capturedBytes)
record.reason?.let { put("reason", it) }
})
}
if (records.size > MAX_MANIFEST_RECORDS) {
entries.put(JSONObject().apply {
put("entry", "")
put("origin", "manifest")
put("status", "omitted")
put("reason", "${records.size - MAX_MANIFEST_RECORDS} additional records")
})
}
val manifest = JSONObject().apply {
put("schema", 1)
put("sessionId", sessionId)
put("category", category)
put("generatedAtMillis", System.currentTimeMillis())
put("redactionLearning", if (redactionLearningComplete) "complete" else "incomplete")
put("limits", JSONObject().apply {
put("maxFilesPerArchive", limits.maxFilesPerArchive)
put("maxDiscoveredFiles", limits.maxDiscoveredFiles)
put("maxBytesPerFile", limits.maxBytesPerFile)
put("budgetBasis", "raw-input-snapshot-bytes")
put("maxRawInputBytesTotal", limits.maxBytesTotal)
put("categoryRawInputBudgetBytes", categoryBudget)
})
put("entries", entries)
}.toString(2) + "\n"
archive.putNextEntry(ZipEntry("diagnostics-manifest.json"))
archive.write(manifest.toByteArray())
archive.closeEntry()
}
private fun collect(context: Context, folder: File, maxFiles: Int, legacy: Boolean): CollectionResult {
val out = LinkedHashMap<String, Candidate>()
val categoryCounts = HashMap<Category, Int>()
val perCategory = (maxFiles / Category.values().size).coerceAtLeast(1)
var truncated = false
fun add(
file: File,
root: File,
entry: String,
origin: String,
forcedCategory: Category? = null,
linePrefix: String? = null,
) {
val safe = safeEntry(entry) ?: return
val category = forcedCategory ?: category(entry)
if (out.size >= maxFiles || (categoryCounts[category] ?: 0) >= perCategory) {
truncated = true
return
}
val anchor = anchorFor(context, root)
if (out.putIfAbsent(safe, Candidate(file, anchor, safe, origin, category, linePrefix)) == null) {
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
}
}
CRITICAL_SESSION_FILES.forEach { name ->
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
}
File(folder, "session.log").takeIf { it.exists() }?.let { file ->
add(
file, folder, "${folder.name}/graphics/frame-trace.log", "guest-frame-trace",
Category.GRAPHICS, "DROIDDECK_FRAME_TRACE ",
)
add(
file, folder, "${folder.name}/graphics/process-trace.log", "guest-process-trace",
Category.GRAPHICS, "DROIDDECK_PROCESS_TRACE ",
)
add(
file, folder, "${folder.name}/games/game-lifecycle.log", "guest-game-lifecycle",
Category.GAMES, "DROIDDECK_DIAGNOSTICS event=game_",
)
}
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
val scan = directFiles(steam, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
scan.files.forEach {
add(it, steam, "${folder.name}/steam/${it.name}", "live-steam")
}
}
val logs = LinuxRuntime.logDir(context)
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
val scan = directFiles(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
scan.files.asSequence().filter { recent(it) }
.forEach { add(it, root, "$name/${it.name}", name) }
}
if (legacy) {
legacyBattleNet(context).forEach { source ->
add(source.file, source.root, source.entry, "battlenet")
}
} else {
battleNetRoots(context).forEach { (prefix, root) ->
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
.forEach { file ->
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
add(file, root, "battlenet/$prefix/$relative", "battlenet")
}
}
}
val sessionScan = walk(folder, remaining(maxFiles, out.size))
truncated = truncated || sessionScan.truncated
sessionScan.files.forEach { file ->
val relative = file.toPath().toAbsolutePath().normalize()
.let { folder.toPath().toAbsolutePath().normalize().relativize(it).joinToString("/") }
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
add(file, folder, "${folder.name}/$relative", "session")
}
return CollectionResult(out.values.toList(), truncated)
}
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
private fun walk(root: File, limit: Int): ScanResult {
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val files = ArrayList<File>(limit)
var truncated = false
Files.walk(root.toPath()).use { paths ->
val iterator = paths.iterator()
var visited = 0
val visitLimit = (limit * 4).coerceAtLeast(limit).coerceAtMost(MAX_DISCOVERY_VISITS)
while (iterator.hasNext() && files.size < limit && visited < visitLimit) {
val path = iterator.next()
visited++
if (path != root.toPath() &&
(Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(path))) {
files += path.toFile()
}
}
truncated = iterator.hasNext()
}
return ScanResult(files, truncated)
}
private fun directFiles(root: File, limit: Int): ScanResult {
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val files = ArrayList<File>(limit)
var truncated = false
Files.newDirectoryStream(root.toPath()).use { entries ->
val iterator = entries.iterator()
while (iterator.hasNext() && files.size < limit) {
val path = iterator.next()
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(path)) {
files += path.toFile()
}
}
truncated = iterator.hasNext()
}
return ScanResult(files, truncated)
}
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
return listOf(
"droiddeck" to File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet"),
"client" to File(drive, "users/steamuser/AppData/Local/Battle.net/Logs"),
"agent" to File(data, "Agent"),
"setup" to File(data, "Setup"),
)
}
private fun legacyBattleNet(context: Context): List<LegacySource> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
val agent = File(data, "Agent")
val setup = File(data, "Setup")
return legacyNewest(
"droiddeck",
listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")),
2,
setOf("battlenet.log", "spawned.log"),
) + legacyNewest(
"client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6,
) + legacyNewest(
"agent",
listOf(File(agent, "Logs")) + childDirectories(agent, "Agent.").map { File(it, "Logs") },
10,
byDir = true,
) + legacyNewest(
"setup", childDirectories(setup, "").map { File(it, "Logs") }, 3, byDir = true,
)
}
private fun legacyNewest(
folder: String,
roots: List<File>,
count: Int,
names: Set<String>? = null,
byDir: Boolean = false,
): List<LegacySource> = roots.flatMap { root ->
directFiles(root, MAX_BATTLENET_SCAN).files.asSequence()
.filter { recent(it) && it.name.endsWith(".log") && it.length() <= LEGACY_LOG_MAX_BYTES }
.filter { names == null || it.name in names }
.map { it to root }
.toList()
}.sortedByDescending { it.first.lastModified() }.take(count).map { (file, root) ->
val relative = if (byDir) "$folder/${file.parentFile?.parentFile?.name}/${file.name}" else "$folder/${file.name}"
LegacySource(file, root, "battlenet/$relative")
}
private fun childDirectories(root: File, prefix: String): List<File> {
if (!root.isDirectory || Files.isSymbolicLink(root.toPath())) return emptyList()
val found = ArrayList<File>()
Files.newDirectoryStream(root.toPath()).use { entries ->
val iterator = entries.iterator()
while (iterator.hasNext() && found.size < MAX_BATTLENET_DIRECTORIES) {
val path = iterator.next()
if (path.fileName.toString().startsWith(prefix) &&
Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) found += path.toFile()
}
}
return found
}
private fun recent(file: File): Boolean = file.lastModified() >= System.currentTimeMillis() - RECENT_MILLIS
private fun anchorFor(context: Context, root: File): File {
val path = root.toPath().toAbsolutePath().normalize()
for (anchor in listOf(context.filesDir, context.cacheDir)) {
if (path.startsWith(anchor.toPath().toAbsolutePath().normalize())) return anchor
}
return root.parentFile ?: root
}
private fun safeEntry(name: String): String? {
if (name.any { it.code < 0x20 || it.code == 0x7f }) return null
val normalized = name.replace('\\', '/').trimStart('/')
val parts = normalized.split('/')
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
return parts.joinToString("/") { safeComponent(it) }
}
private fun safeComponent(value: String): String {
if (value in KNOWN_COMPONENTS || KNOWN_COMPONENT_PATTERNS.any { it.matches(value) }) return value
val suffix = SAFE_SUFFIX.find(value)?.value.orEmpty().lowercase(Locale.US)
val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
.take(8).joinToString("") { "%02x".format(Locale.US, it.toInt() and 0xff) }
return "entry-$digest$suffix"
}
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
private val KNOWN_COMPONENTS = setOf(
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
)
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
Regex("steam-[0-9]+\\.(?:log|txt)"),
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
)
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
private val CRITICAL_SESSION_FILES = listOf(
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
"events.jsonl", "memory.csv", "capture.json", "crash.log",
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
private const val MAX_BATTLENET_SCAN = 64
private const val MAX_BATTLENET_DIRECTORIES = 64
private const val MAX_MANIFEST_RECORDS = 512
private const val MAX_DISCOVERY_VISITS = 4096
}
@@ -117,8 +117,7 @@ object GameEnvironmentStore {
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
json.put(
GAME_DEBUG_LOGS,
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
gameDebugLogsOverride ?: SessionPrefs.gameDebugLogsEffective(context),
)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@@ -40,6 +40,7 @@ object SessionFiles {
WinComponents.publish(context)
val files = arrayOf(
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
@@ -11,12 +11,8 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.FileProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import java.util.ArrayList
object SessionLogShare {
data class Details(val sizeBytes: Long, val modifiedAt: Long)
@@ -62,84 +58,30 @@ object SessionLogShare {
return knownSession && folder.isDirectory && folder.deleteRecursively()
}
fun prepareEnhanced(context: Context, folder: () -> File?, done: (List<File>) -> Unit) {
if (progress != null) return
progress = 0f
Thread({
val zips = runCatching {
folder()?.let { dir ->
EnhancedSessionLogShare.create(context, dir, onProgress = { p ->
main.post { if (progress != null) progress = p }
})
}.orEmpty()
}.onFailure { Log.w("SessionLogShare", "could not package enhanced diagnostics", it) }
.getOrDefault(emptyList())
main.post { progress = null; done(zips) }
}, "share-diagnostics").start()
}
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
if (!folder.isDirectory) return null
val files = folder.walkTopDown().filter { it.isFile }
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
if (files.isEmpty()) return null
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
val zip = File(out, "DroidDeck-${folder.name}.zip")
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val live = liveSteamLogs(context, folder)
val logs = LinuxRuntime.logDir(context)
val stores = recent(File(logs, STORES_DIR))
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
val battleNet = battleNetLogs(context)
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
done += f.length()
val percent = (done * 100 / total).toInt()
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
}
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).invariantSeparatorsPath, f); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
}
return zip
return EnhancedSessionLogShare.createLegacy(context, folder, onProgress)
}
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
z.putNextEntry(ZipEntry(name))
val w = z.bufferedWriter()
LogRedactor.scrubForShare(f, w)
w.flush()
z.closeEntry()
}
private fun liveSteamLogs(context: Context, folder: File): List<File> {
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
val logs = File(SessionPrefs.activeSteamRoot(context), "logs")
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
}
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
const val STORES_DIR = "stores"
private const val RECENT_DAYS = 7
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
private const val BATTLENET_DIR = "battlenet"
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
}
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dirs.flatMap { dir ->
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
}
}
private fun recent(dir: File): List<File> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
}
internal fun shareDir(context: Context): File = File(context.cacheDir, "share")
fun clear(context: Context) {
shareDir(context).deleteRecursively()
@@ -156,4 +98,19 @@ object SessionLogShare {
send.clipData = ClipData.newRawUri(zip.name, uri)
return Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
fun shareEnhancedIntent(context: Context, zips: List<File>): Intent {
require(zips.isNotEmpty())
val uris = ArrayList(zips.map { FileProvider.getUriForFile(context, context.packageName + ".logs", it) })
val send = Intent(Intent.ACTION_SEND_MULTIPLE)
.setType("application/zip")
.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
.putExtra(Intent.EXTRA_SUBJECT, zips.first().name.substringBeforeLast('-'))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
send.clipData = ClipData.newUri(context.contentResolver, zips.first().name, uris.first()).also { clip ->
for (i in 1 until uris.size) clip.addItem(ClipData.Item(uris[i]))
}
return Intent.createChooser(send, context.getString(R.string.logshare_chooser))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
@@ -26,7 +26,8 @@ object SessionPaths {
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
val enhanced = EnhancedDiagnostics.isArmed(context)
val parent = if (SessionPrefs.logsEnabled(context) || enhanced) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
val last = parent.listFiles()?.mapNotNull { f ->
@@ -36,9 +37,13 @@ object SessionPaths {
var number = last + 1
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
EnhancedDiagnostics.clearRecordFor(context, made)
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
Log.e(TAG, "could not activate enhanced diagnostics for $made")
}
Log.i(TAG, "session logs: $made" + if (parent == SessionFiles.logDirectory(context)) "" else " (logs off: discarded at the end)")
return made
}
@@ -824,7 +824,7 @@ object SessionPrefs {
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
newEffective = gameDebugLogsEffective(context, on, gameDebugLogsEnabled(context)),
)
}
@@ -837,7 +837,7 @@ object SessionPrefs {
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
newEffective = gameDebugLogsEffective(context, logsEnabled(context), on),
)
}
@@ -850,8 +850,7 @@ object SessionPrefs {
): Boolean {
if (oldValue == newValue) return true
val saved = prefs(context)
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
SessionPaths.currentSessionLogsRetained(context)
val oldEffective = gameDebugLogsEffective(context)
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
if (oldEffective == newEffective) {
if (saved.edit().putBoolean(key, newValue).commit()) return true
@@ -887,6 +886,13 @@ object SessionPrefs {
}
}
internal fun gameDebugLogsEffective(
context: Context,
logs: Boolean = logsEnabled(context),
gameLogs: Boolean = gameDebugLogsEnabled(context),
): Boolean = EnhancedDiagnostics.isCurrentSessionActive(context) ||
(logs && gameLogs && SessionPaths.currentSessionLogsRetained(context))
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
@@ -540,6 +540,7 @@ class SessionService : Service() {
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
@@ -768,6 +769,7 @@ class SessionService : Service() {
SessionState.sessionId = sessionDir.name
SessionState.eventsFile = File(sessionDir, "events.jsonl")
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
if (EnhancedDiagnostics.isActive(this, sessionDir)) SessionEvents.record("diagnostics.enhanced", mapOf("schema" to 1))
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"))
@@ -22,7 +22,7 @@ object SettingsReset {
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
@@ -102,6 +102,7 @@ class FrontEndState(
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
val enhancedDiagnosticsArmed: Boolean = false,
val gameDebugLogsEnabled: Boolean = false,
val gameDebugLogsNeedsRestart: Boolean = false,
val vacDiagnostics: Boolean = false,
@@ -227,6 +228,7 @@ class FrontEndActions(
val onFiles: () -> Unit,
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onEnhancedDiagnostics: () -> Unit = {},
val onGameDebugLogs: () -> Unit = {},
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
@@ -546,6 +546,10 @@ internal fun SetupPanel(
5 -> {
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
ToggleRow(
host, "enhanced-diagnostics", stringResource(R.string.setup_enhanced_diagnostics),
stringResource(R.string.setup_enhanced_diagnostics_hint), s.enhancedDiagnosticsArmed,
) { a.onEnhancedDiagnostics() }
ToggleRow(
host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs),
stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint),
+7
View File
@@ -915,6 +915,13 @@
<string name="setup_session">Session</string>
<string name="setup_logs">Session logs</string>
<string name="setup_logs_hint">Saved after each session</string>
<string name="setup_enhanced_diagnostics">Enhanced diagnostics for next session</string>
<string name="setup_enhanced_diagnostics_hint">Captures detailed logs for one session. May reduce performance and use more storage. Turns itself off when the session starts; review logs before sharing.</string>
<string name="diagnostics_share_title">Share diagnostic bundles</string>
<string name="diagnostics_share_session">Session and device</string>
<string name="diagnostics_share_graphics">Graphics</string>
<string name="diagnostics_share_games">Games and compatibility</string>
<string name="diagnostics_share_all">All bundles</string>
<string name="setup_game_debug_logs">Game debug logs</string>
<string name="setup_game_debug_logs_hint">Include Proton, Wine and graphics diagnostics on the next game launch. Can reduce performance and use more storage.</string>
<string name="setup_game_debug_logs_restart">Restart this session to save game debug logs</string>
@@ -316,6 +316,60 @@ class LogRedactorTest {
}
}
@Test fun oversizedAccountMetadataIsRejectedWithoutForgettingKnownNames() {
val users = tmp.newFile("known-loginusers.vdf")
val oversized = tmp.newFile("oversized-loginusers.vdf")
users.writeText("\"AccountName\" \"previous_player\"")
java.io.RandomAccessFile(oversized, "rw").use {
it.setLength(LogRedactor.MAX_LEARN_INPUT_BYTES.toLong() + 1)
}
try {
assertTrue(LogRedactor.learnAccounts(users))
assertFalse(LogRedactor.learnAccounts(oversized))
assertEquals("<redacted:account>", LogRedactor.redact("previous_player"))
} finally {
LogRedactor.learnAccounts()
}
}
@Test fun repeatedIncompleteAccountLearningKeepsOnlyABoundedRecentSet() {
val users = tmp.newFile("changing-loginusers.vdf")
val oversized = tmp.newFile("unreadable-loginusers.vdf")
java.io.RandomAccessFile(oversized, "rw").use {
it.setLength(LogRedactor.MAX_LEARN_INPUT_BYTES.toLong() + 1)
}
try {
LogRedactor.learnAccounts()
repeat(3) { batch ->
users.writeText((0 until 1024).joinToString("\n") {
"\"AccountName\" \"round${batch}player${it.toString().padStart(4, '0')}\""
})
assertFalse(LogRedactor.learnAccounts(users, oversized))
}
assertEquals("<redacted:account>", LogRedactor.redact("round2player0000"))
assertEquals("<redacted:account>", LogRedactor.redact("round1player0000"))
assertEquals("round0player0000", LogRedactor.redact("round0player0000"))
} finally {
LogRedactor.learnAccounts()
}
}
@Test fun oversizedAddressMetadataIsRejectedWithoutForgettingKnownAddresses() {
val link = tmp.newFile("known-network")
val oversized = tmp.newFile("oversized-network")
link.writeText("addr 203.0.113.40 24\n")
java.io.RandomAccessFile(oversized, "rw").use {
it.setLength(LogRedactor.MAX_LEARN_INPUT_BYTES.toLong() + 1)
}
try {
assertTrue(LogRedactor.learnOwnAddresses(link))
assertFalse(LogRedactor.learnOwnAddresses(oversized))
assertEquals("<redacted:ip>", LogRedactor.redact("203.0.113.40"))
} finally {
LogRedactor.learnOwnAddresses(tmp.root.resolve("missing-network"))
}
}
@Test fun manyLearnedAddressesKeepOtherAddresses() {
val link = tmp.newFile("droiddeck-net")
link.writeText((1..40).joinToString("\n") { "addr 203.0.113.$it 24" })
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class EnhancedDiagnosticsTest {
private lateinit var context: Context
private lateinit var guest: File
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
SessionPaths.take()?.let { SessionPaths.release(context, it) }
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.remove("enhancedDiagnosticsNext")
.remove("enhancedDiagnosticsActiveSessions")
.commit()
guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json")
}
@After fun tearDown() {
SessionPaths.take()?.let { folder ->
SessionPaths.release(context, folder)
folder.deleteRecursively()
}
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.remove("enhancedDiagnosticsNext")
.remove("enhancedDiagnosticsActiveSessions")
.commit()
GameEnvironmentStore.publish(context)
}
@Test fun armedSessionIsRetainedAndConsumesTheOneShotPreference() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("logs", false).commit()
assertTrue(EnhancedDiagnostics.setArmed(context, true))
val folder = SessionPaths.beginOrCurrent(context, "enhanced-test")
assertEquals(SessionFiles.logDirectory(context), folder.parentFile)
assertFalse(EnhancedDiagnostics.isArmed(context))
assertTrue(EnhancedDiagnostics.isActive(context, folder))
val manifest = JSONObject(File(folder, EnhancedDiagnostics.MANIFEST_FILE).readText())
assertEquals(1, manifest.getInt("schema"))
assertEquals("enhanced", manifest.getString("profile"))
assertEquals(folder.name, manifest.getString("sessionId"))
assertTrue(manifest.getBoolean("exportBundlesBounded"))
assertFalse(manifest.getBoolean("rawCaptureByteBounded"))
}
@Test fun activeProfileForcesGameDiagnosticsWithoutChangingUserPreferences() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putBoolean("logs", false)
.putBoolean("gameDebugLogsEnabled", false)
.commit()
assertTrue(EnhancedDiagnostics.setArmed(context, true))
SessionPaths.beginOrCurrent(context, "enhanced-game-logs")
GameEnvironmentStore.publish(context)
assertTrue(JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))
assertFalse(SessionPrefs.logsEnabled(context))
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
}
@Test fun cancellingTheOneShotLeavesOrdinaryLogRetentionUnchanged() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("logs", false).commit()
assertTrue(EnhancedDiagnostics.setArmed(context, true))
assertTrue(EnhancedDiagnostics.setArmed(context, false))
val folder = SessionPaths.beginOrCurrent(context, "ordinary-test")
assertEquals(File(context.cacheDir, "session-logs"), folder.parentFile)
assertFalse(EnhancedDiagnostics.isActive(context, folder))
}
@Test fun guestCannotForgeEnhancedDiagnosticsByWritingAMarker() {
val folder = SessionPaths.beginOrCurrent(context, "forged-marker")
File(folder, EnhancedDiagnostics.MANIFEST_FILE).writeText(
"""{"schema":1,"profile":"enhanced"}""",
)
assertFalse(EnhancedDiagnostics.isActive(context, folder))
assertNull(EnhancedDiagnostics.manifest(context, folder))
}
@Test fun trustedStateSurvivesGuestMarkerDeletionAndSessionRecovery() {
assertTrue(EnhancedDiagnostics.setArmed(context, true))
val folder = SessionPaths.beginOrCurrent(context, "deleted-marker")
assertTrue(File(folder, EnhancedDiagnostics.MANIFEST_FILE).delete())
assertTrue(EnhancedDiagnostics.isActive(context, File(folder.path)))
assertEquals(folder.name, EnhancedDiagnostics.manifest(context, folder)?.getString("sessionId"))
assertEquals(folder, SessionPaths.take())
assertTrue(EnhancedDiagnostics.isActive(context, folder))
}
@Test fun informationalMarkerFailureDoesNotRearmTheNextSession() {
val parent = SessionFiles.logDirectory(context).apply { mkdirs() }
val folder = File(parent, "2026-11-04-99-marker-failure").apply { mkdirs() }
File(folder, EnhancedDiagnostics.MANIFEST_FILE).mkdirs()
assertTrue(EnhancedDiagnostics.setArmed(context, true))
assertTrue(EnhancedDiagnostics.consumeInto(context, folder))
assertTrue(EnhancedDiagnostics.isActive(context, folder))
assertFalse(EnhancedDiagnostics.isArmed(context))
folder.deleteRecursively()
}
@Test fun aReusedSessionPathDoesNotInheritTrustedState() {
assertTrue(EnhancedDiagnostics.setArmed(context, true))
val original = SessionPaths.beginOrCurrent(context, "reused-path")
assertTrue(EnhancedDiagnostics.isActive(context, original))
assertEquals(original, SessionPaths.take())
original.deleteRecursively()
val replacement = SessionPaths.beginOrCurrent(context, "reused-path")
assertEquals(original.path, replacement.path)
assertFalse(EnhancedDiagnostics.isActive(context, replacement))
}
}
@@ -0,0 +1,331 @@
package com.droiddeck.launcher.session
import android.content.Intent
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeFalse
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.RandomAccessFile
import java.nio.file.Files
import java.util.zip.ZipFile
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EnhancedSessionLogShareTest {
@get:Rule val tmp = TemporaryFolder()
private val app get() = RuntimeEnvironment.getApplication()
@Test fun diagnosticsAreSplitIntoManifestedArchivesWithOneSessionIdentity() {
val session = tmp.newFolder("2026-11-04-01-steam")
session.resolve("session.log").writeText("startup ok\n")
session.resolve("wayland.log").writeText("frame import ok\n")
session.resolve("steam-42.log").writeText("dxvk: present ok\n")
val zips = EnhancedSessionLogShare.create(app, session)
assertEquals(
setOf("session", "graphics", "games"),
zips.map { it.nameWithoutExtension.substringAfterLast('-') }.toSet(),
)
val expected = mapOf(
"session" to "${session.name}/session.log",
"graphics" to "${session.name}/wayland.log",
"games" to "${session.name}/steam-42.log",
)
zips.forEach { zip ->
val category = zip.nameWithoutExtension.substringAfterLast('-')
ZipFile(zip).use { archive ->
assertTrue(archive.getEntry(expected.getValue(category)) != null)
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
.bufferedReader().readText())
assertEquals(1, manifest.getInt("schema"))
assertEquals(session.name, manifest.getString("sessionId"))
assertEquals(category, manifest.getString("category"))
assertEquals("captured", manifest.getJSONArray("entries").getJSONObject(0).getString("status"))
}
}
SessionLogShare.clear(app)
}
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
val session = tmp.newFolder("2026-11-04-02-game")
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
val limits = EnhancedShareLimits(maxFilesPerArchive = 8, maxBytesPerFile = 96, maxBytesTotal = 512)
val games = EnhancedSessionLogShare.create(app, session, limits = limits)
.single { it.name.endsWith("-games.zip") }
ZipFile(games).use { archive ->
val text = archive.getInputStream(archive.getEntry("${session.name}/steam-7.log")).bufferedReader().readText()
assertTrue(text.startsWith("begin"))
assertTrue(text.contains("diagnostic file truncated"))
assertTrue(text.endsWith("tail\n"))
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
.bufferedReader().readText())
assertEquals("truncated", manifest.getJSONArray("entries").getJSONObject(0).getString("status"))
assertTrue(manifest.getJSONArray("entries").getJSONObject(0).getLong("capturedBytes") <= 96)
}
SessionLogShare.clear(app)
}
@Test fun symbolicLinksAreNotReadAndTheirOmissionIsRecorded() {
assumeFalse(System.getProperty("os.name").startsWith("Windows"))
val session = tmp.newFolder("2026-11-04-03-steam")
session.resolve("session.log").writeText("safe\n")
val outside = tmp.newFile("private.log").apply { writeText("do-not-share\n") }
val link = session.toPath().resolve("wayland.log")
runCatching { Files.createSymbolicLink(link, outside.toPath()) }.getOrElse { return }
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
ZipFile(graphics).use { archive ->
assertFalse(archive.entries().toList().any { it.name.endsWith("wayland.log") })
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
.bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }
.any { it.optString("reason") == "unsafe-or-unavailable-source" })
}
SessionLogShare.clear(app)
}
@Test fun enhancedShareUsesOneMultipleAttachmentIntent() {
val session = tmp.newFolder("2026-11-04-04-steam")
session.resolve("session.log").writeText("safe\n")
val zips = EnhancedSessionLogShare.create(app, session)
val chooser = SessionLogShare.shareEnhancedIntent(app, zips)
val send = chooser.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)!!
assertEquals(Intent.ACTION_SEND_MULTIPLE, send.action)
assertEquals("application/zip", send.type)
assertEquals(3, send.getParcelableArrayListExtra<android.net.Uri>(Intent.EXTRA_STREAM)!!.size)
assertEquals(3, send.clipData!!.itemCount)
SessionLogShare.clear(app)
}
@Test fun graphicsArchiveIncludesOnlyBoundedFrameTraceSummariesFromTheSessionLog() {
val session = tmp.newFolder("2026-11-04-05-steam")
session.resolve("session.log").writeText(
"normal startup line\n" +
"DROIDDECK_FRAME_TRACE xdamage=4 commits=2\n" +
"unrelated account=test-user\n" +
"DROIDDECK_FRAME_TRACE xdamage=9 commits=8\n" +
"DROIDDECK_PROCESS_TRACE pid=42 gpuLibs=libvulkan.so\n",
)
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
ZipFile(graphics).use { archive ->
val trace = archive.getInputStream(archive.getEntry("${session.name}/graphics/frame-trace.log"))
.bufferedReader().readText()
assertEquals(
"DROIDDECK_FRAME_TRACE xdamage=4 commits=2\n" +
"DROIDDECK_FRAME_TRACE xdamage=9 commits=8\n",
trace,
)
assertFalse(trace.contains("normal startup"))
assertFalse(trace.contains("test-user"))
val process = archive.getInputStream(archive.getEntry("${session.name}/graphics/process-trace.log"))
.bufferedReader().readText()
assertEquals("DROIDDECK_PROCESS_TRACE pid=42 gpuLibs=libvulkan.so\n", process)
}
SessionLogShare.clear(app)
}
@Test fun truncationNeverSharesASecretWhoseLabelWasCutOffAtTheBoundary() {
val session = tmp.newFolder("2026-11-04-06-game")
val secret = "abcdef1234567890"
session.resolve("steam-8.log").writeText(
"padding-refresh_token=$secret" + "x".repeat(512) + "\nvisible tail\n",
)
val limits = EnhancedShareLimits(maxFilesPerArchive = 8, maxBytesPerFile = 128, maxBytesTotal = 512)
val games = EnhancedSessionLogShare.create(app, session, limits = limits)
.single { it.name.endsWith("-games.zip") }
val shared = ZipFile(games).use { archive ->
archive.getInputStream(archive.getEntry("${session.name}/steam-8.log")).bufferedReader().readText()
}
assertFalse(shared.contains(secret))
assertTrue(shared.contains("diagnostic file truncated"))
assertTrue(shared.endsWith("visible tail\n"))
SessionLogShare.clear(app)
}
@Test fun discoveryStopsAtItsBoundAndDeclaresTheTruncatedInventory() {
val session = tmp.newFolder("2026-11-04-07-steam")
repeat(20) { session.resolve("log-$it.txt").writeText("line $it\n") }
val limits = EnhancedShareLimits(
maxFilesPerArchive = 8,
maxDiscoveredFiles = 2,
maxBytesPerFile = 1024,
maxBytesTotal = 4096,
)
val zips = EnhancedSessionLogShare.create(app, session, limits = limits)
val captured = zips.sumOf { zip ->
ZipFile(zip).use { archive -> archive.entries().toList().count { it.name != "diagnostics-manifest.json" } }
}
assertTrue(captured <= 2)
zips.forEach { zip ->
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
.bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }
.any { it.optString("origin") == "discovery" && it.optString("status") == "truncated" })
}
}
SessionLogShare.clear(app)
}
@Test fun aGuestForgedActivationMarkerIsNeverExportedAsTrustedMetadata() {
val session = tmp.newFolder("2026-11-04-08-steam")
session.resolve("session.log").writeText("safe\n")
session.resolve(EnhancedDiagnostics.MANIFEST_FILE).writeText("{\"profile\":\"forged\"}\n")
val zips = EnhancedSessionLogShare.create(app, session)
zips.forEach { zip ->
ZipFile(zip).use { archive ->
assertFalse(archive.entries().toList().any { it.name.endsWith(EnhancedDiagnostics.MANIFEST_FILE) })
}
}
SessionLogShare.clear(app)
}
@Test fun hardLinksAreRejectedInsteadOfFollowingASecondNameToItsContent() {
assumeFalse(System.getProperty("os.name").startsWith("Windows"))
val session = tmp.newFolder("2026-11-04-09-steam")
session.resolve("session.log").writeText("safe\n")
val outside = tmp.newFile("outside-hardlink.log").apply { writeText("private hard-link content\n") }
runCatching { Files.createLink(session.toPath().resolve("wayland.log"), outside.toPath()) }.getOrElse { return }
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
ZipFile(graphics).use { archive ->
assertFalse(archive.entries().toList().any { it.name.endsWith("wayland.log") })
val all = archive.entries().toList().joinToString("\n") { entry ->
archive.getInputStream(entry).bufferedReader().readText()
}
assertFalse(all.contains("private hard-link content"))
}
SessionLogShare.clear(app)
}
@Test fun guestControlledAndControlCharacterNamesNeverEnterTheArchiveOrManifest() {
val session = tmp.newFolder("2026-11-04-10-steam")
session.resolve("private-window-title.log").writeText("safe diagnostic\n")
session.resolve("wayland\nsecret.log").writeText("must not be named\n")
val sessionZip = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-session.zip") }
ZipFile(sessionZip).use { archive ->
val names = archive.entries().toList().map { it.name }
assertTrue(names.any { it.contains("/entry-") && it.endsWith(".log") })
assertFalse(names.any { it.contains("private-window-title") || it.contains('\n') })
val manifest = archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText()
assertFalse(manifest.contains("private-window-title"))
assertFalse(manifest.contains("wayland\\nsecret"))
}
SessionLogShare.clear(app)
}
@Test fun oneCategoryCannotConsumeTheOtherCategoriesByteReservations() {
val session = tmp.newFolder("2026-11-04-11-steam")
session.resolve("session.log").writeText("session\n".repeat(100))
session.resolve("wayland.log").writeText("graphics\n".repeat(100))
session.resolve("steam-11.log").writeText("game\n".repeat(100))
val limits = EnhancedShareLimits(maxBytesPerFile = 1024, maxBytesTotal = 300)
val zips = EnhancedSessionLogShare.create(app, session, limits = limits)
zips.forEach { zip ->
ZipFile(zip).use { archive ->
assertTrue(archive.entries().toList().any { it.name != "diagnostics-manifest.json" })
}
}
SessionLogShare.clear(app)
}
@Test fun filteredTraceScanFindsLateSummariesAndMarksThePartialSource() {
val session = tmp.newFolder("2026-11-04-12-steam")
val source = session.resolve("session.log")
RandomAccessFile(source, "rw").use { file ->
file.setLength(17L * 1024 * 1024)
file.seek(file.length() - 80)
file.write("\nDROIDDECK_PROCESS_TRACE pid=99 gpuLibs=libGLES.so\n".toByteArray())
}
val graphics = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-graphics.zip") }
ZipFile(graphics).use { archive ->
val trace = archive.getInputStream(archive.getEntry("${session.name}/graphics/process-trace.log"))
.bufferedReader().readText()
assertTrue(trace.contains("pid=99"))
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
.bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
assertTrue((0 until entries.length()).map { entries.getJSONObject(it) }.any {
it.optString("origin") == "guest-process-trace" && it.optString("status") == "truncated"
})
}
SessionLogShare.clear(app)
}
@Test fun diagnosticLookingGuestNamesCannotExposeEmbeddedSecrets() {
val session = tmp.newFolder("2026-11-04-13-game")
val tokenName = "dxvk-refresh_token_abcdef123456.log"
val accountName = "battle.net-secretvalue.log"
session.resolve(tokenName).writeText("dxvk diagnostic\n")
session.resolve(accountName).writeText("battle net diagnostic\n")
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
ZipFile(games).use { archive ->
val names = archive.entries().toList().map { it.name }
assertFalse(names.any { it.contains("refresh_token") || it.contains("secretvalue") })
assertTrue(names.count { it.substringAfterLast('/').startsWith("entry-") } >= 2)
val manifest = archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText()
assertFalse(manifest.contains("refresh_token"))
assertFalse(manifest.contains("secretvalue"))
}
SessionLogShare.clear(app)
}
@Test fun gamesArchiveIncludesOnlyGameLifecycleSummariesFromTheSessionLog() {
val session = tmp.newFolder("2026-11-04-14-game")
session.resolve("session.log").writeText(
"DROIDDECK_DIAGNOSTICS event=game_start appId=42 pid=123\n" +
"unrelated launch detail\n" +
"DROIDDECK_DIAGNOSTICS event=game_exit appId=42 status=139\n",
)
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
ZipFile(games).use { archive ->
val lifecycle = archive.getInputStream(archive.getEntry("${session.name}/games/game-lifecycle.log"))
.bufferedReader().readText()
assertEquals(
"DROIDDECK_DIAGNOSTICS event=game_start appId=42 pid=123\n" +
"DROIDDECK_DIAGNOSTICS event=game_exit appId=42 status=139\n",
lifecycle,
)
assertFalse(lifecycle.contains("unrelated launch detail"))
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json"))
.bufferedReader().readText())
assertTrue(manifest.toString().contains("guest-game-lifecycle"))
}
SessionLogShare.clear(app)
}
}
@@ -86,8 +86,9 @@ class SessionLogShareTest {
File(folder, "events.jsonl").writeText("$secret\n")
val out = zip(folder)
for (name in listOf("app.log", "session.log", "steam/deep/nested.txt", ".hidden.txt", "events.jsonl"))
for (name in listOf("app.log", "session.log", "events.jsonl"))
assertFalse(name, out.getValue(name).contains(leaked))
assertTrue(out.values.none { it.contains(leaked) })
}
@Test fun aRecordUnderOtherRedactorRulesVouchesForNothing() {
@@ -187,7 +188,7 @@ class SessionLogShareTest {
assertFalse(File(folder, ".scrubbed-r${LogRedactor.RULES_VERSION}").exists())
}
@Test fun steamLogsPastTheSizeLimitStayOut() {
@Test fun steamLogsPastTheSizeLimitAreBoundedAndDeclared() {
val folder = tmp.newFolder("2026-10-06-07-steam")
File(folder, "session.log").writeText("ok\n")
File(folder, "steam").mkdirs()
@@ -196,9 +197,11 @@ class SessionLogShareTest {
val line = ByteArray(1024) { 'x'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() }
repeat(9 * 1024) { out.write(line) }
}
val names = zip(folder).keys
assertTrue("steam/console_log.txt" in names)
assertFalse("steam/cef_log.previous.txt" in names)
val output = zip(folder)
assertTrue("steam/console_log.txt" in output)
assertTrue("steam/cef_log.previous.txt" in output)
assertTrue(output.getValue("steam/cef_log.previous.txt").contains("diagnostic file truncated"))
assertTrue(output.getValue("diagnostics-manifest.json").contains("\"status\": \"truncated\""))
}
@Test fun streamingComparisonPreservesUnchangedFileAndReplacesChangedFile() {
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -38,23 +37,11 @@ class SessionLogShareZipTest {
val zip = SessionLogShare.zipFolder(app, session)!!
ZipFile(zip).use { archive ->
val entry = archive.getEntry("${session.name}/steam-42.log")!!
archive.getInputStream(entry).use { input ->
val expected = "${com.droiddeck.launcher.core.LogRedactor.OVERSIZED_LINE}\n"
val prefix = ByteArray(expected.toByteArray(StandardCharsets.UTF_8).size)
var offset = 0
while (offset < prefix.size) {
val count = input.read(prefix, offset, prefix.size - offset)
assertTrue("zip entry ended before its scrubbed prefix", count > 0)
offset += count
}
assertEquals(expected, String(prefix, StandardCharsets.UTF_8))
input.bufferedReader().use { reader ->
val trailing = requireNotNull(reader.readLine())
assertFalse("trailing secret survived", trailing.contains(trailingSecret))
assertEquals("refresh_token=<redacted:token>", trailing)
assertEquals(null, reader.readLine())
}
}
val shared = archive.getInputStream(entry).bufferedReader().readText()
assertTrue(shared.contains("diagnostic file truncated"))
assertFalse("early secret survived", shared.contains(earlySecret))
assertFalse("trailing secret survived", shared.contains(trailingSecret))
assertTrue(shared.contains("refresh_token=<redacted:token>"))
}
} finally {
SessionLogShare.clear(app)
@@ -35,6 +35,7 @@ class SettingsResetTest {
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
SessionPrefs.setGuestHostname(app, "MyDeck")
assertTrue(SessionPrefs.setGameDebugLogsEnabled(app, true))
assertTrue(EnhancedDiagnostics.setArmed(app, true))
SessionPrefs.setHudShowFps(app, false)
SessionPrefs.setHudShowBattery(app, false)
SessionPrefs.setHudShowGraph(app, false)
@@ -58,6 +59,7 @@ class SettingsResetTest {
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
assertFalse(SessionPrefs.gameDebugLogsEnabled(app))
assertFalse(EnhancedDiagnostics.isArmed(app))
val guest = java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app),
"root/.config/droiddeck/game-environment.json")
assertFalse(org.json.JSONObject(guest.readText()).getBoolean(GameEnvironmentStore.GAME_DEBUG_LOGS))