Skip to content

Commit 2941b3d

Browse files
authored
fix(android): clean up cancelled camera recordings (#129948)
1 parent f94ad76 commit 2941b3d

3 files changed

Lines changed: 67 additions & 20 deletions

File tree

‎apps/android/app/src/main/java/ai/openclaw/app/node/CameraCaptureManager.kt‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,14 @@ internal class CameraClipSession(
6161
return file
6262
}
6363

64-
fun transferFile(): File {
64+
fun transferFile(onTransfer: (File) -> Unit): File {
6565
check(!closed) { "camera clip session is closed" }
6666
return checkNotNull(temporaryFile) { "camera clip session has no file" }
67-
.also { temporaryFile = null }
67+
.also { file ->
68+
// Claim ownership before release because cancellation can discard a dispatched FilePayload.
69+
onTransfer(file)
70+
temporaryFile = null
71+
}
6872
}
6973

7074
override fun close() {
@@ -224,7 +228,10 @@ class CameraCaptureManager(
224228

225229
/** Records a short MP4 clip into a temporary cache file for the caller to encode/delete. */
226230
@SuppressLint("MissingPermission")
227-
suspend fun clip(paramsJson: String?): FilePayload =
231+
suspend fun clip(
232+
paramsJson: String?,
233+
onFileReady: (File) -> Unit,
234+
): FilePayload =
228235
withContext(Dispatchers.Main) {
229236
ensureCameraPermission()
230237
val params = parseJsonParamsObject(paramsJson)
@@ -306,7 +313,7 @@ class CameraCaptureManager(
306313
}
307314

308315
FilePayload(
309-
file = session.transferFile(),
316+
file = session.transferFile(onFileReady),
310317
durationMs = durationMs.toLong(),
311318
hasAudio = includeAudio,
312319
)

‎apps/android/app/src/main/java/ai/openclaw/app/node/CameraHandler.kt‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ import ai.openclaw.app.takeUtf16Safe
77
import android.content.Context
88
import kotlinx.coroutines.CancellationException
99
import kotlinx.coroutines.Dispatchers
10+
import kotlinx.coroutines.NonCancellable
1011
import kotlinx.coroutines.withContext
1112
import kotlinx.serialization.json.JsonPrimitive
1213
import kotlinx.serialization.json.buildJsonArray
1314
import kotlinx.serialization.json.buildJsonObject
1415
import kotlinx.serialization.json.put
16+
import java.util.concurrent.atomic.AtomicReference
1517

1618
internal const val CAMERA_CLIP_MAX_RAW_BYTES: Long = 18L * 1024L * 1024L
1719
private const val CAMERA_DEBUG_STACK_TRACE_MAX_CHARS = 2_000
@@ -121,6 +123,7 @@ class CameraHandler(
121123
message = "MIC_BUSY: another audio capture is active",
122124
)
123125
}
126+
val ownedClipFile = AtomicReference<java.io.File?>()
124127
try {
125128
clipLogFile?.writeText("") // clear
126129
clipLog("starting, params=$paramsJson includeAudio=$includeAudio")
@@ -129,7 +132,10 @@ class CameraHandler(
129132
val filePayload =
130133
try {
131134
clipLog("calling camera.clip()")
132-
val r = camera.clip(paramsJson)
135+
val r =
136+
camera.clip(paramsJson) { file ->
137+
check(ownedClipFile.compareAndSet(null, file)) { "camera clip already owns a file" }
138+
}
133139
clipLog("success, file size=${r.file.length()}")
134140
r
135141
} catch (err: CancellationException) {
@@ -144,8 +150,6 @@ class CameraHandler(
144150
val rawBytes = filePayload.file.length()
145151
if (!isCameraClipWithinPayloadLimit(rawBytes)) {
146152
clipLog("payload too large: bytes=$rawBytes max=$CAMERA_CLIP_MAX_RAW_BYTES")
147-
// Delete oversized clips before returning so cache files do not accumulate after failed invokes.
148-
withContext(Dispatchers.IO) { filePayload.file.delete() }
149153
showCameraHud("Clip too large", CameraHudKind.Error, 2400)
150154
return GatewaySession.InvokeResult.error(
151155
code = "PAYLOAD_TOO_LARGE",
@@ -154,14 +158,7 @@ class CameraHandler(
154158
)
155159
}
156160

157-
val bytes =
158-
withContext(Dispatchers.IO) {
159-
try {
160-
filePayload.file.readBytes()
161-
} finally {
162-
filePayload.file.delete()
163-
}
164-
}
161+
val bytes = withContext(Dispatchers.IO) { filePayload.file.readBytes() }
165162
val base64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
166163
clipLog("returning base64 payload")
167164
showCameraHud("Clip captured", CameraHudKind.Success, 1800)
@@ -175,8 +172,17 @@ class CameraHandler(
175172
clipLog("stack: ${err.stackTraceToString().takeUtf16Safe(CAMERA_DEBUG_STACK_TRACE_MAX_CHARS)}")
176173
return GatewaySession.InvokeResult.error(code = "UNAVAILABLE", message = err.message ?: "camera clip failed")
177174
} finally {
178-
// Prevent talk/transcription capture from competing with camera audio after every exit path.
179-
if (ownsAudioCapture) setCameraAudioCaptureActive(false)
175+
try {
176+
ownedClipFile.getAndSet(null)?.let { file ->
177+
// Nest dispatcher changes so cancellation cannot replace the original failure.
178+
withContext(NonCancellable) {
179+
withContext(Dispatchers.IO) { file.delete() }
180+
}
181+
}
182+
} finally {
183+
// Prevent talk/transcription capture from competing with camera audio after every exit path.
184+
if (ownsAudioCapture) setCameraAudioCaptureActive(false)
185+
}
180186
}
181187
}
182188

‎apps/android/app/src/test/java/ai/openclaw/app/node/CameraHandlerTest.kt‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ class CameraHandlerTest {
5555

5656
val error =
5757
assertThrows(IllegalStateException::class.java) {
58-
runBlocking { CameraCaptureManager(app).clip("""{"includeAudio":false}""") }
58+
runBlocking { CameraCaptureManager(app).clip("""{"includeAudio":false}""") {} }
5959
}
6060

6161
assertEquals("CAMERA_PERMISSION_REQUIRED: grant Camera permission", error.message)
@@ -70,7 +70,7 @@ class CameraHandlerTest {
7070

7171
val error =
7272
assertThrows(IllegalStateException::class.java) {
73-
runBlocking { camera.clip("""{"includeAudio":true}""") }
73+
runBlocking { camera.clip("""{"includeAudio":true}""") {} }
7474
}
7575

7676
assertEquals("MIC_PERMISSION_REQUIRED: grant Microphone permission", error.message)
@@ -160,7 +160,7 @@ class CameraHandlerTest {
160160
session.ownRecording(AutoCloseable { cleanup += "recording" })
161161
session.ownFile(tempFile)
162162

163-
assertSame(tempFile, session.transferFile())
163+
assertSame(tempFile, session.transferFile {})
164164
session.close()
165165

166166
assertEquals(listOf("recording", "unbind"), cleanup)
@@ -169,4 +169,38 @@ class CameraHandlerTest {
169169
tempFile.delete()
170170
}
171171
}
172+
173+
@Test
174+
fun cameraClipSession_transfersFileToCallerBeforeReleasingOwnership() {
175+
val tempFile = File.createTempFile("openclaw-clip-test-", ".mp4")
176+
try {
177+
val session = CameraClipSession(unbind = {}, deleteTemporaryFile = { it.delete() })
178+
session.ownFile(tempFile)
179+
var claimedFile: File? = null
180+
181+
assertSame(tempFile, session.transferFile { claimedFile = it })
182+
session.close()
183+
184+
assertSame(tempFile, claimedFile)
185+
assertTrue(tempFile.exists())
186+
} finally {
187+
tempFile.delete()
188+
}
189+
}
190+
191+
@Test
192+
fun cameraClipSession_keepsFileWhenCallerCannotClaimOwnership() {
193+
val tempFile = File.createTempFile("openclaw-clip-test-", ".mp4")
194+
val session = CameraClipSession(unbind = {}, deleteTemporaryFile = { it.delete() })
195+
session.ownFile(tempFile)
196+
197+
val error =
198+
assertThrows(IllegalStateException::class.java) {
199+
session.transferFile { error("caller already owns a camera clip") }
200+
}
201+
session.close()
202+
203+
assertEquals("caller already owns a camera clip", error.message)
204+
assertFalse(tempFile.exists())
205+
}
172206
}

0 commit comments

Comments
 (0)