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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,21 @@ internal fun approvalDetails(body: JSONObject): String {
return details
}

private class WaitingApproval(val title: String, val message: String, val answer: CompletableFuture<Boolean>)
private class WaitingApproval(
val category: AccessCategory,
val command: String,
val details: String,
val answer: CompletableFuture<Boolean>,
) {
// Rendered when the dialog opens, so it's in the language the buttons are.
fun title() = localized("Allow {access}?", "access" to localized(category.label))

fun message() = buildString {
append(AgentAccess.commandName(command))
if (details.isNotEmpty()) append("\n\n$details")
append("\n\n" + localized("An agent or another device using this phone's server asked for this."))
}
}

/**
* One prompt per request, so an answer can't also cover a command the user never saw. What the
Expand Down Expand Up @@ -77,7 +91,7 @@ internal object AccessApproval {
dismiss: () -> Unit,
): Boolean {
val id = UUID.randomUUID().toString()
val waiting = waitingFor(category, command, details)
val waiting = WaitingApproval(category, command, details, CompletableFuture())
pending[id] = waiting
try {
show(
Expand All @@ -98,16 +112,7 @@ internal object AccessApproval {
}
}

private fun waitingFor(category: AccessCategory, command: String, details: String): WaitingApproval {
val message = buildString {
append(AgentAccess.commandName(command))
if (details.isNotEmpty()) append("\n\n$details")
append("\n\nAn agent or another device using this phone's server asked for this.")
}
return WaitingApproval("Allow ${category.label}?", message, CompletableFuture())
}

fun prompt(id: String): Pair<String, String>? = pending[id]?.let { it.title to it.message }
fun prompt(id: String): Pair<String, String>? = pending[id]?.let { it.title() to it.message() }

fun answer(id: String, allowed: Boolean) {
pending[id]?.answer?.complete(allowed)
Expand All @@ -133,8 +138,8 @@ class AccessApprovalActivity : Activity() {
val shown = AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_Alert)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Allow") { _, _ -> answer(true) }
.setNegativeButton("Don't allow") { _, _ -> answer(false) }
.setPositiveButton(localized("Allow")) { _, _ -> answer(true) }
.setNegativeButton(localized("Don't allow")) { _, _ -> answer(false) }
.setOnCancelListener { answer(false) }
.create()
shown.setCanceledOnTouchOutside(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
"share" -> {
val text = body.getString("text")
val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, text)
startOrNotify(Intent.createChooser(send, null), "Share from an agent", text)
startOrNotify(Intent.createChooser(send, null), localized("Share from an agent"), text)
}
"vibrate" -> vibrate(body.optLong("duration", 1000))
"battery-status" -> batteryStatus()
Expand All @@ -305,7 +305,7 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
"call-log" -> data.callLog(body)
"telephony-call" -> {
val number = body.getString("number")
startOrNotify(Intent(Intent.ACTION_CALL, Uri.fromParts("tel", number, null)), "Call from an agent", number)
startOrNotify(Intent(Intent.ACTION_CALL, Uri.fromParts("tel", number, null)), localized("Call from an agent"), number)
}
"telephony-deviceinfo" -> data.deviceInfo()
"telephony-cellinfo" -> data.cellInfo()
Expand All @@ -318,7 +318,9 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
private fun am(body: JSONObject): Any? {
val intent = appIntent(context, body)
return when (val mode = body.getString("mode")) {
"start" -> launchIntent(context, intent).let { startOrNotify(it, "Open an app from an agent", describeIntent(it)) }
"start" -> launchIntent(context, intent).let {
startOrNotify(it, localized("Open an app from an agent"), describeIntent(it, localized("this intent")), describeIntent(it))
}
"broadcast" -> {
requireTarget(intent)
context.sendBroadcast(intent)
Expand All @@ -333,7 +335,7 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
}

private fun openUrl(url: String): Any? =
startOrNotify(Intent(Intent.ACTION_VIEW, webUri(url)), "Open a link from an agent", url)
startOrNotify(Intent(Intent.ACTION_VIEW, webUri(url)), localized("Open a link from an agent"), url)

private fun webUri(url: String): Uri {
val uri = Uri.parse(url)
Expand All @@ -353,7 +355,7 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
else -> fileIntent(target, send, body.optString("contentType"))
}
val chosen = if (send || body.optBoolean("chooser")) Intent.createChooser(intent, null) else intent
return startOrNotify(chosen, if (send) "Share from an agent" else "Open from an agent", target)
return startOrNotify(chosen, if (send) localized("Share from an agent") else localized("Open from an agent"), target)
}

private fun fileIntent(path: String, send: Boolean, contentType: String): Intent {
Expand Down Expand Up @@ -448,7 +450,14 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
context.startActivity(intent)
} else {
val tap = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_IMMUTABLE)
notify(REQUEST_CHANNEL, REQUEST_TAG, notificationId, "Allow $label?", "An agent wants to run ${AgentAccess.commandName(command)}. Tap to answer.", tap)
notify(
REQUEST_CHANNEL,
REQUEST_TAG,
notificationId,
localized("Allow {access}?", "access" to localized(label)),
localized("An agent wants to run {command}. Tap to answer.", "command" to AgentAccess.commandName(command)),
tap,
)
}
},
dismiss = { notificationManager().cancel(REQUEST_TAG, notificationId) },
Expand All @@ -465,8 +474,9 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
// Notification access is a system settings page, not a prompt.
startOrNotify(
AgentAccess.notificationAccessIntent(context),
"Allow notification access",
"An agent on this phone wants to read its notifications. Turn on T3 Code here.",
localized("Allow notification access"),
localized("An agent on this phone wants to read its notifications. Turn on T3 Code here."),
"the notification access settings",
)
throw BridgeError(
"Android hasn't given T3 Code notification access. The user can turn it on in the settings page " +
Expand All @@ -477,7 +487,14 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
if (!onScreen()) {
val id = requestIds.incrementAndGet()
val tap = PendingIntent.getActivity(context, id, AccessPrompt.intent(context, category), PendingIntent.FLAG_IMMUTABLE)
notify(REQUEST_CHANNEL, REQUEST_TAG, id, "Allow $label?", "An agent on this phone wants $label. Tap to answer Android's prompt.", tap)
notify(
REQUEST_CHANNEL,
REQUEST_TAG,
id,
localized("Allow {access}?", "access" to localized(label)),
localized("An agent on this phone wants {access}. Tap to answer Android's prompt.", "access" to localized(label)),
tap,
)
throw BridgeError(
"Android hasn't given T3 Code $label, and can only ask while T3 Code is on screen. The user can tap " +
"T3 Code's notification to allow it, then run this again.",
Expand All @@ -494,13 +511,14 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
}

/** Android blocks activity starts from the background, but a notification's tap can start one. */
private fun startOrNotify(intent: Intent, title: String, text: String): Any? {
/** [subject] names the target in English for the agent's error; [text] is the notification body. */
private fun startOrNotify(intent: Intent, title: String, text: String, subject: String = text): Any? {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (onScreen()) {
try {
context.startActivity(intent)
} catch (error: ActivityNotFoundException) {
throw BridgeError("No app on this phone opens $text")
throw BridgeError("No app on this phone opens $subject")
}
return null
}
Expand Down Expand Up @@ -583,18 +601,21 @@ class AndroidBridge private constructor(context: Context, private val rootfs: Fi
val manager = notificationManager()
if (!manager.areNotificationsEnabled()) throw BridgeError("T3 Code's notifications are turned off.")
manager.createNotificationChannel(
NotificationChannel(NOTIFICATION_CHANNEL, "Agent notifications", NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Notifications that agents on this phone post."
NotificationChannel(NOTIFICATION_CHANNEL, localized("Agent notifications"), NotificationManager.IMPORTANCE_DEFAULT).apply {
description = localized("Notifications that agents on this phone post.")
},
)
manager.createNotificationChannel(
NotificationChannel(REQUEST_CHANNEL, "Requests from agents", NotificationManager.IMPORTANCE_HIGH).apply {
description = "Links, shares and permissions that agents ask for while T3 Code isn't on screen."
NotificationChannel(REQUEST_CHANNEL, localized("Requests from agents"), NotificationManager.IMPORTANCE_HIGH).apply {
description = localized("Links, shares and permissions that agents ask for while T3 Code isn't on screen.")
},
)
val blocked = manager.getNotificationChannel(channel)
?.takeIf { it.importance == NotificationManager.IMPORTANCE_NONE }
if (blocked != null) throw BridgeError("T3 Code's \"${blocked.name}\" notifications are turned off.")
if (blocked != null) {
val name = if (channel == REQUEST_CHANNEL) "Requests from agents" else "Agent notifications"
throw BridgeError("T3 Code's \"$name\" notifications are turned off.")
}
val icon = context.resources.getIdentifier("notification_icon", "drawable", context.packageName)
.takeIf { it != 0 } ?: context.applicationInfo.icon
val notification = NotificationCompat.Builder(context, channel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ internal fun launchIntent(context: Context, intent: Intent): Intent {
}

/** What a notification or error names the intent by. */
internal fun describeIntent(intent: Intent): String =
intent.component?.flattenToShortString() ?: intent.`package` ?: intent.dataString ?: intent.action ?: "this intent"
internal fun describeIntent(intent: Intent, fallback: String = "this intent"): String =
intent.component?.flattenToShortString() ?: intent.`package` ?: intent.dataString ?: intent.action ?: fallback

/** A broadcast names its app, so one can't reach every app that listens for its action. */
internal fun requireTarget(intent: Intent) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ private val NETWORK_ERROR = Regex("""getaddrinfo|EAI_AGAIN|ENOTFOUND|ECONNREFUSE
internal fun failureMessage(output: String, code: Int): String {
val reason = output.substringAfterLast(CODE_PROMPT, output).lines()
.map { it.trim() }.lastOrNull { it.isNotEmpty() }
?: return "Sign-in exited with status $code."
?: return localized("Sign-in exited with status {code}.", "code" to code)
return if (NETWORK_ERROR.containsMatchIn(reason)) {
"Couldn't reach Claude's servers ($reason). Check the connection, then sign in again."
localized("Couldn't reach Claude's servers ({reason}). Check the connection, then sign in again.", "reason" to reason)
} else {
reason
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ class DeviceRuntime(private val context: Context, private val log: (String) -> U
/** Starts a command in the guest with stderr merged into stdout. */
fun start(guestCommand: List<String>, environment: Map<String, String> = emptyMap()): GuestProcess {
checkCancelled()
if (!ubuntuInstalled) throw IOException("Ubuntu on this phone is missing or damaged. Install it again.")
if (!ubuntuInstalled) throw IOException(localized("Ubuntu on this phone is missing or damaged. Install it again."))
writeGuestConfig()
prootTmp.mkdirs()
hardLinks.mkdirs()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ enum class Hold { Job, Login, Server }
* waits on the browser, or the server would stall as soon as the user switched apps.
*/
object RuntimeForeground {
private val holds = sortedMapOf<Hold, String>()
private val holds = sortedMapOf<Hold, () -> String>()
@Volatile internal var service: DeviceRuntimeService? = null

fun hold(context: Context, hold: Hold, text: String) {
/** [text] renders each time the notification is shown, in the app's language then. */
fun hold(context: Context, hold: Hold, text: () -> String) {
val running = synchronized(this) {
holds[hold] = text
service
Expand All @@ -57,8 +58,12 @@ object RuntimeForeground {
running?.refresh()
}

fun refresh() {
service?.refresh()
}

@Synchronized
internal fun current(): Pair<Hold, String>? = holds.entries.firstOrNull()?.toPair()
internal fun current(): Pair<Hold, String>? = holds.entries.firstOrNull()?.let { it.key to it.value() }
}

/** The T3 server inside the on-device runtime, kept alive by the foreground service. */
Expand All @@ -80,7 +85,7 @@ object DeviceServer {
@Synchronized
private fun launch(context: Context, port: Int, retry: Boolean) {
if (running) return
RuntimeForeground.hold(context, Hold.Server, "The server is running on this phone.")
RuntimeForeground.hold(context, Hold.Server) { localized("The server is running on this phone.") }
val log = logFile(context)
val bridge = AndroidBridge.start(context)
val started = try {
Expand Down Expand Up @@ -128,7 +133,7 @@ object DeviceServer {
val started = guest ?: return
started.terminate()
if (!started.process.waitFor(STOP_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
throw IOException("The server didn't stop within $STOP_TIMEOUT_SECONDS seconds.")
throw IOException(localized("The server didn't stop within {seconds} seconds.", "seconds" to STOP_TIMEOUT_SECONDS))
}
}
}
Expand All @@ -154,7 +159,7 @@ class DeviceRuntimeService : Service() {
}
// A service started with startForegroundService must call startForeground, even when
// its work has already finished.
val current = RuntimeForeground.current() ?: (Hold.Job to "Finishing…")
val current = RuntimeForeground.current() ?: (Hold.Job to localized("Finishing…"))
startForeground(current)
update()
return START_NOT_STICKY
Expand Down Expand Up @@ -206,8 +211,8 @@ class DeviceRuntimeService : Service() {
private fun notification(hold: Hold, text: String): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel(CHANNEL_ID, "T3 Code on this phone", NotificationManager.IMPORTANCE_LOW).apply {
description = "Shown while T3 Code installs, signs in or runs its server on this phone."
NotificationChannel(CHANNEL_ID, localized("T3 Code on this phone"), NotificationManager.IMPORTANCE_LOW).apply {
description = localized("Shown while T3 Code installs, signs in or runs its server on this phone.")
},
)
val open = packageManager.getLaunchIntentForPackage(packageName)?.let {
Expand All @@ -228,7 +233,7 @@ class DeviceRuntimeService : Service() {
Intent(this, DeviceRuntimeService::class.java).setAction(ACTION_STOP_SERVER),
PendingIntent.FLAG_IMMUTABLE,
)
builder.addAction(0, "Stop server", stop)
builder.addAction(0, localized("Stop server"), stop)
}
return builder.build()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package expo.modules.t3deviceruntime

/**
* The app's translations of the English passed to [localized], sent by
* apps/mobile/src/features/device-runtime/native-text.ts. Text it hasn't sent stays English.
*/
@Volatile internal var nativeTranslations: Map<String, String> = emptyMap()

/** Text Android shows the user, in the app's language. Text for agents and logs stays English. */
internal fun localized(english: String, vararg values: Pair<String, Any>): String =
values.fold(nativeTranslations[english] ?: english) { text, (name, value) ->
text.replace("{$name}", value.toString())
}
Loading
Loading