The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 07:15 UTC
feat(mobile): open localhost tabs on the device, with a Safari-style browser bar (#38045)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 18, 2026 at 19:16 UTC
194b33205530053d7c85b7b758ce19bf1c48d4df
53 files changed
+2878
-353
apps/mobile/app.config.ts
+2
@@ -277,6 +277,8 @@ const config: ExpoConfig = {
277
},
278
NSLocalNetworkUsageDescription:
279
"Allow T3 Code to connect to T3 Code servers on your local network or tailnet.",
280
+ // Built with the iOS 27 SDK, only view controllers can hide or style the status bar.
281
+ UIViewControllerBasedStatusBarAppearance: true,
282
NSPhotoLibraryAddUsageDescription: "Allow T3 Code to save images to your photo library.",
283
// System picture in picture needs background audio to start and survive outside the app.
284
UIBackgroundModes: ["audio"],
apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz
Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz and /dev/null differ
apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz
Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz differ
apps/mobile/modules/t3-preview-tunnel/android/build.gradle
new
+21
@@ -0,0 +1,21 @@
1
+apply plugin: 'com.android.library'
2
+apply plugin: 'org.jetbrains.kotlin.android'
3
+
4
+group = 'com.t3tools.previewtunnel'
5
+version = '0.0.0'
6
+
7
+android {
8
+ namespace 'expo.modules.t3previewtunnel'
9
+ compileSdk rootProject.ext.compileSdkVersion
10
+
11
+ defaultConfig {
12
+ minSdkVersion rootProject.ext.minSdkVersion
13
+ targetSdkVersion rootProject.ext.targetSdkVersion
14
+ }
15
+}
16
+
17
+dependencies {
18
+ implementation project(':expo-modules-core')
19
+ implementation "androidx.webkit:webkit:${rootProject.ext.has('webkitVersion') ? rootProject.ext.get('webkitVersion') : '1.14.0'}"
20
+ implementation 'com.squareup.okhttp3:okhttp:4.12.0'
21
+}
apps/mobile/modules/t3-preview-tunnel/android/src/main/AndroidManifest.xml
new
+1
@@ -0,0 +1 @@
1
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/SocksListener.kt
new
+271
@@ -0,0 +1,271 @@
1
+package expo.modules.t3previewtunnel
2
+
3
+import java.io.DataInputStream
4
+import java.io.OutputStream
5
+import java.net.InetAddress
6
+import java.net.ServerSocket
7
+import java.net.Socket
8
+import java.util.concurrent.CompletableFuture
9
+import java.util.concurrent.TimeUnit
10
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
11
+import okhttp3.OkHttpClient
12
+import okhttp3.Request
13
+import okhttp3.Response
14
+import okhttp3.WebSocket
15
+import okhttp3.WebSocketListener
16
+import okio.ByteString
17
+import okio.ByteString.Companion.toByteString
18
+
19
+private const val SEND_HIGH_WATER_BYTES = 1024L * 1024
20
+private const val HANDSHAKE_TIMEOUT_MS = 10_000
21
+
22
+// Browsers open about six connections per host; this leaves room for several hosts and sockets.
23
+private const val MAX_CONNECTIONS = 64
24
+private const val MAX_SOCKS4_STRING = 255
25
+
26
+private val client = OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build()
27
+
28
+// The webview names the host as typed, so IP literals can also arrive as domain names.
29
+private fun isLoopbackName(name: String): Boolean {
30
+ val host = name.lowercase().removeSuffix(".")
31
+ val literal = host.removePrefix("[").removeSuffix("]")
32
+ val isIpLiteral = literal.all { it.isDigit() || it == '.' || it == ':' || it in 'a'..'f' }
33
+ val isLoopbackIp = isIpLiteral &&
34
+ runCatching { InetAddress.getByName(literal).isLoopbackAddress }.getOrDefault(false)
35
+ return host == "localhost" || host.endsWith(".localhost") || isLoopbackIp
36
+}
37
+
38
+/**
39
+ * A SOCKS listener on 127.0.0.1 that carries each loopback CONNECT over one WebSocket to the
40
+ * environment's /api/preview/tunnel. It never connects anywhere on this device, so a tunnel that
41
+ * fails is a connection error, never one of this device's own servers. SOCKS4 is accepted too,
42
+ * because WebView's `socks://` proxy scheme speaks it.
43
+ */
44
+internal class SocksListener(private val requestAccess: () -> String?) {
45
+ private val server = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
46
+ private val sockets = java.util.Collections.newSetFromMap(
47
+ java.util.concurrent.ConcurrentHashMap<Socket, Boolean>()
48
+ )
49
+ val port: Int = server.localPort
50
+
51
+ init {
52
+ Thread({
53
+ while (!server.isClosed) {
54
+ val socket = runCatching { server.accept() }.getOrNull() ?: break
55
+ // Registration and close() take the same lock, so a socket accepted while the listener
56
+ // closes is dropped instead of starting a worker; a page opens a handful at a time.
57
+ val admitted = synchronized(sockets) {
58
+ !server.isClosed && sockets.size < MAX_CONNECTIONS && sockets.add(socket)
59
+ }
60
+ if (admitted) {
61
+ Thread({ serve(socket) }, "t3-preview-tunnel").apply { isDaemon = true }.start()
62
+ } else {
63
+ runCatching { socket.close() }
64
+ }
65
+ }
66
+ }, "t3-preview-tunnel-accept").apply { isDaemon = true }.start()
67
+ }
68
+
69
+ fun close() {
70
+ val open = synchronized(sockets) {
71
+ runCatching { server.close() }
72
+ sockets.toList().also { sockets.clear() }
73
+ }
74
+ for (socket in open) runCatching { socket.close() }
75
+ }
76
+
77
+ private sealed interface Handshake {
78
+ data class Connect(val port: Int, val reply: (Boolean) -> ByteArray) : Handshake
79
+ data class Refuse(val reply: ByteArray) : Handshake
80
+ }
81
+
82
+ private fun serve(socket: Socket) {
83
+ try {
84
+ // A client that stalls mid-handshake is dropped; the tunnel itself has no deadline.
85
+ socket.soTimeout = HANDSHAKE_TIMEOUT_MS
86
+ val input = DataInputStream(socket.getInputStream())
87
+ val output = socket.getOutputStream()
88
+ val handshake = when (input.readUnsignedByte()) {
89
+ 5 -> readSocks5(input, output)
90
+ 4 -> readSocks4(input)
91
+ else -> null
92
+ }
93
+ when (handshake) {
94
+ null -> Unit
95
+ is Handshake.Refuse -> output.write(handshake.reply)
96
+ is Handshake.Connect -> connect(socket, input, output, handshake)
97
+ }
98
+ } catch (_: Exception) {
99
+ } finally {
100
+ synchronized(sockets) { sockets.remove(socket) }
101
+ runCatching { socket.close() }
102
+ }
103
+ }
104
+
105
+ private fun connect(
106
+ socket: Socket,
107
+ input: DataInputStream,
108
+ output: OutputStream,
109
+ handshake: Handshake.Connect
110
+ ) {
111
+ val base = requestAccess()
112
+ if (base == null) {
113
+ output.write(handshake.reply(false))
114
+ } else {
115
+ tunnel(socket, input, output, base, handshake)
116
+ }
117
+ }
118
+
119
+ @Suppress("ReturnCount") // One refusal per malformed or forbidden request field.
120
+ private fun readSocks5(input: DataInputStream, output: OutputStream): Handshake? {
121
+ val methods = ByteArray(input.readUnsignedByte()).also { input.readFully(it) }
122
+ if (!methods.contains(0)) {
123
+ output.write(byteArrayOf(5, 0xff.toByte()))
124
+ return null
125
+ }
126
+ output.write(byteArrayOf(5, 0))
127
+ val version = input.readUnsignedByte()
128
+ val command = input.readUnsignedByte()
129
+ input.readUnsignedByte()
130
+ val loopback = when (input.readUnsignedByte()) {
131
+ 1 -> ByteArray(4).also { input.readFully(it) }[0] == 127.toByte()
132
+ 4 -> InetAddress.getByAddress(ByteArray(16).also { input.readFully(it) }).isLoopbackAddress
133
+ 3 -> isLoopbackName(String(ByteArray(input.readUnsignedByte()).also { input.readFully(it) }))
134
+ else -> return Handshake.Refuse(socks5Reply(8))
135
+ }
136
+ val port = input.readUnsignedShort()
137
+ if (version != 5 || command != 1) return Handshake.Refuse(socks5Reply(7))
138
+ if (!loopback) return Handshake.Refuse(socks5Reply(2))
139
+ return Handshake.Connect(port) { ok -> socks5Reply(if (ok) 0 else 1) }
140
+ }
141
+
142
+ private fun readSocks4(input: DataInputStream): Handshake {
143
+ val command = input.readUnsignedByte()
144
+ val port = input.readUnsignedShort()
145
+ val address = ByteArray(4).also { input.readFully(it) }
146
+ readCString(input)
147
+ // SOCKS4a: 0.0.0.x means a host name follows the user id.
148
+ val isSocks4a = address.take(3).all { it == 0.toByte() } && address[3] != 0.toByte()
149
+ val loopback = if (isSocks4a) {
150
+ isLoopbackName(readCString(input))
151
+ } else {
152
+ address[0] == 127.toByte()
153
+ }
154
+ val refused = byteArrayOf(0, 0x5b, 0, 0, 0, 0, 0, 0)
155
+ if (command != 1 || !loopback) return Handshake.Refuse(refused)
156
+ val granted = byteArrayOf(0, 0x5a, 0, 0, 0, 0, 0, 0)
157
+ return Handshake.Connect(port) { ok -> if (ok) granted else refused }
158
+ }
159
+
160
+ private fun readCString(input: DataInputStream): String {
161
+ val bytes = StringBuilder()
162
+ while (bytes.length <= MAX_SOCKS4_STRING) {
163
+ val next = input.readUnsignedByte()
164
+ if (next == 0) return bytes.toString()
165
+ bytes.append(next.toChar())
166
+ }
167
+ throw java.io.IOException("SOCKS4 string too long")
168
+ }
169
+
170
+ private fun socks5Reply(code: Int) = byteArrayOf(5, code.toByte(), 0, 1, 0, 0, 0, 0, 0, 0)
171
+
172
+ @Suppress("ReturnCount") // Each failed step answers the client and stops.
173
+ private fun tunnel(
174
+ socket: Socket,
175
+ input: DataInputStream,
176
+ output: OutputStream,
177
+ base: String,
178
+ handshake: Handshake.Connect
179
+ ) {
180
+ val url = base.replaceFirst(Regex("^ws"), "http").toHttpUrlOrNull()
181
+ ?.newBuilder()?.addQueryParameter("port", handshake.port.toString())?.build()
182
+ if (url == null) {
183
+ output.write(handshake.reply(false))
184
+ return
185
+ }
186
+ val opened = CompletableFuture<Boolean>()
187
+ val replied = CompletableFuture<Unit>()
188
+ val closed = CompletableFuture<Unit>()
189
+
190
+ // A server can speak first; its bytes must not reach the page before the SOCKS reply.
191
+ fun writeToPage(webSocket: WebSocket, bytes: ByteArray) {
192
+ runCatching {
193
+ replied.get()
194
+ output.write(bytes)
195
+ }.onFailure { webSocket.cancel() }
196
+ }
197
+ val webSocket = client.newWebSocket(
198
+ Request.Builder().url(url).build(),
199
+ object : WebSocketListener() {
200
+ override fun onOpen(webSocket: WebSocket, response: Response) {
201
+ opened.complete(true)
202
+ }
203
+
204
+ // Writing here blocks OkHttp's reader thread, so a page that stops reading stops the
205
+ // tunnel from reading too instead of buffering the response in memory.
206
+ override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
207
+ writeToPage(webSocket, bytes.toByteArray())
208
+ }
209
+
210
+ override fun onMessage(webSocket: WebSocket, text: String) {
211
+ writeToPage(webSocket, text.toByteArray())
212
+ }
213
+
214
+ override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
215
+ webSocket.close(1000, null)
216
+ closed.complete(Unit)
217
+ }
218
+
219
+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
220
+ opened.complete(false)
221
+ closed.complete(Unit)
222
+ }
223
+ }
224
+ )
225
+ if (!runCatching { opened.get(15, TimeUnit.SECONDS) }.getOrDefault(false)) {
226
+ replied.completeExceptionally(java.io.IOException("tunnel did not open"))
227
+ webSocket.cancel()
228
+ output.write(handshake.reply(false))
229
+ return
230
+ }
231
+ // The page may have gone while the tunnel opened; then nothing must keep the tunnel alive.
232
+ val sent = runCatching { output.write(handshake.reply(true)) }
233
+ if (sent.isFailure) {
234
+ replied.completeExceptionally(java.io.IOException("SOCKS client went away"))
235
+ webSocket.cancel()
236
+ return
237
+ }
238
+ replied.complete(Unit)
239
+ socket.soTimeout = 0
240
+ val reader = Thread({ sendPageBytes(input, webSocket, closed) }, "t3-preview-tunnel-up")
241
+ .apply { isDaemon = true }
242
+ reader.start()
243
+ closed.get()
244
+ // Let the page read what has already arrived before the connection ends.
245
+ runCatching {
246
+ output.flush()
247
+ socket.shutdownOutput()
248
+ }
249
+ reader.join(1000)
250
+ }
251
+
252
+ private fun sendPageBytes(
253
+ input: DataInputStream,
254
+ webSocket: WebSocket,
255
+ closed: CompletableFuture<Unit>
256
+ ) {
257
+ val buffer = ByteArray(64 * 1024)
258
+ try {
259
+ var count = input.read(buffer)
260
+ while (count >= 0) {
261
+ webSocket.send(buffer.toByteString(0, count))
262
+ // OkHttp queues sends without limit and fails the socket past 16 MiB.
263
+ while (webSocket.queueSize() > SEND_HIGH_WATER_BYTES && !closed.isDone) Thread.sleep(5)
264
+ count = input.read(buffer)
265
+ }
266
+ webSocket.close(1000, null)
267
+ } catch (_: Exception) {
268
+ webSocket.cancel()
269
+ }
270
+ }
271
+}
apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/T3PreviewTunnelModule.kt
new
+65
@@ -0,0 +1,65 @@
1
+package expo.modules.t3previewtunnel
2
+
3
+import expo.modules.kotlin.modules.Module
4
+import expo.modules.kotlin.modules.ModuleDefinition
5
+import java.util.concurrent.CompletableFuture
6
+import java.util.concurrent.ConcurrentHashMap
7
+import java.util.concurrent.TimeUnit
8
+import java.util.concurrent.atomic.AtomicInteger
9
+
10
+class T3PreviewTunnelModule : Module() {
11
+ override fun definition() = ModuleDefinition {
12
+ Name("T3PreviewTunnel")
13
+
14
+ Function("resolveAccess") { requestId: String, url: String? ->
15
+ TunnelAccess.resolve(requestId, url)
16
+ }
17
+
18
+ View(T3TunnelWebView::class) {
19
+ Events("onAccessRequest", "onNavigationChange", "onLoadError", "onPageScroll")
20
+
21
+ OnViewDestroys { view: T3TunnelWebView -> view.destroyWebView() }
22
+
23
+ Prop("environmentId") { view: T3TunnelWebView, environmentId: String ->
24
+ view.setEnvironment(environmentId)
25
+ }
26
+ Prop("url") { view: T3TunnelWebView, url: String -> view.loadUrl(url) }
27
+
28
+ AsyncFunction("loadUrl") { view: T3TunnelWebView, url: String ->
29
+ view.post { view.loadUrl(url) }
30
+ }
31
+
32
+ AsyncFunction("goBack") { view: T3TunnelWebView -> view.goBack() }
33
+ AsyncFunction("goForward") { view: T3TunnelWebView -> view.goForward() }
34
+ AsyncFunction("reload") { view: T3TunnelWebView -> view.reload() }
35
+ }
36
+ }
37
+}
38
+
39
+/**
40
+ * Pending asks for a tunnel URL. JavaScript owns the environment's credentials and the route in
41
+ * use, so every connection asks it for a freshly ticketed URL.
42
+ */
43
+internal object TunnelAccess {
44
+ private val pending = ConcurrentHashMap<String, CompletableFuture<String?>>()
45
+ private val nextId = AtomicInteger()
46
+
47
+ /** Blocks the calling connection thread until JavaScript answers or 15 seconds pass. */
48
+ fun request(ask: (String) -> Unit): String? {
49
+ val requestId = "preview-tunnel-${nextId.incrementAndGet()}"
50
+ val answer = CompletableFuture<String?>()
51
+ pending[requestId] = answer
52
+ return try {
53
+ ask(requestId)
54
+ answer.get(15, TimeUnit.SECONDS)
55
+ } catch (_: Exception) {
56
+ null
57
+ } finally {
58
+ pending.remove(requestId)
59
+ }
60
+ }
61
+
62
+ fun resolve(requestId: String, url: String?) {
63
+ pending[requestId]?.complete(url)
64
+ }
65
+}
apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/T3TunnelWebView.kt
new
+190
@@ -0,0 +1,190 @@
1
+package expo.modules.t3previewtunnel
2
+
3
+import android.annotation.SuppressLint
4
+import android.content.Context
5
+import android.graphics.Bitmap
6
+import android.os.Handler
7
+import android.os.Looper
8
+import android.webkit.WebChromeClient
9
+import android.webkit.WebResourceError
10
+import android.webkit.WebResourceRequest
11
+import android.webkit.WebView
12
+import android.webkit.WebViewClient
13
+import androidx.webkit.ProfileStore
14
+import androidx.webkit.ProxyConfig
15
+import androidx.webkit.ProxyController
16
+import androidx.webkit.WebViewCompat
17
+import androidx.webkit.WebViewFeature
18
+import expo.modules.kotlin.AppContext
19
+import expo.modules.kotlin.viewevent.EventDispatcher
20
+import expo.modules.kotlin.views.ExpoView
21
+import kotlin.math.abs
22
+
23
+/**
24
+ * A webview whose loopback is another environment's: `localhost` requests go to a SOCKS listener
25
+ * in this process, which carries each connection over the environment's tunnel.
26
+ *
27
+ * Android's proxy override applies to every WebView in the app, so it is set while this view is
28
+ * attached and cleared when it detaches. Other webviews here never load loopback pages. Each
29
+ * environment gets its own WebView profile, so one environment's localhost cookies and storage
30
+ * never reach another's.
31
+ */
32
+@SuppressLint("SetJavaScriptEnabled")
33
+class T3TunnelWebView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
34
+ override val shouldUseAndroidLayout = true
35
+
36
+ private val onAccessRequest by EventDispatcher()
37
+ private val onNavigationChange by EventDispatcher()
38
+ private val onLoadError by EventDispatcher()
39
+ private val onPageScroll by EventDispatcher()
40
+ private val main = Handler(Looper.getMainLooper())
41
+ private var webView: WebView? = null
42
+ private var listener: SocksListener? = null
43
+ private var proxied = false
44
+ private var pendingUrl: String? = null
45
+ private var loading = false
46
+ private var environmentId: String? = null
47
+ private var reportedScrollY = 0f
48
+
49
+ fun setEnvironment(environmentId: String) {
50
+ if (environmentId == this.environmentId) return
51
+ // A different environment never reuses this WebView or its profile.
52
+ destroyWebView()
53
+ this.environmentId = environmentId
54
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) {
55
+ fail("This WebView cannot keep environments apart. Update Android System WebView.")
56
+ return
57
+ }
58
+ val profile = "t3-preview-tunnel-$environmentId"
59
+ ProfileStore.getInstance().getOrCreateProfile(profile)
60
+ val webView = WebView(context)
61
+ // The profile must be set before anything else touches this WebView.
62
+ WebViewCompat.setProfile(webView, profile)
63
+ webView.settings.javaScriptEnabled = true
64
+ webView.settings.domStorageEnabled = true
65
+ webView.webViewClient = object : WebViewClient() {
66
+ override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) = report(true)
67
+ override fun onPageFinished(view: WebView, url: String?) = report(false)
68
+ override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) =
69
+ report(null)
70
+
71
+ override fun onReceivedError(
72
+ view: WebView,
73
+ request: WebResourceRequest,
74
+ error: WebResourceError
75
+ ) {
76
+ if (request.isForMainFrame) fail(error.description.toString(), request.url.toString())
77
+ }
78
+ }
79
+ webView.webChromeClient = object : WebChromeClient() {
80
+ override fun onReceivedTitle(view: WebView, title: String?) = report(null)
81
+ }
82
+ webView.setOnScrollChangeListener { _, _, scrollY, _, _ -> reportScroll(scrollY) }
83
+ addView(webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
84
+ this.webView = webView
85
+ pendingUrl?.let { loadUrl(it) }
86
+ }
87
+
88
+ private fun fail(description: String, url: String = "") {
89
+ onLoadError(mapOf("code" to -1, "description" to description, "url" to url))
90
+ }
91
+
92
+ /** Reports the page's scroll position in steps, enough for the bar to follow its direction. */
93
+ private fun reportScroll(scrollY: Int) {
94
+ val y = scrollY / resources.displayMetrics.density
95
+ val moved = abs(y - reportedScrollY) >= SCROLL_STEP_DP
96
+ if (!moved && !(y == 0f && reportedScrollY != 0f)) return
97
+ reportedScrollY = y
98
+ onPageScroll(mapOf("y" to y))
99
+ }
100
+
101
+ private fun report(nowLoading: Boolean?) {
102
+ val webView = webView ?: return
103
+ if (nowLoading != null) loading = nowLoading
104
+ onNavigationChange(
105
+ mapOf(
106
+ "url" to (webView.url ?: ""),
107
+ "title" to (webView.title ?: ""),
108
+ "loading" to loading,
109
+ "canGoBack" to webView.canGoBack(),
110
+ "canGoForward" to webView.canGoForward()
111
+ )
112
+ )
113
+ }
114
+
115
+ override fun onAttachedToWindow() {
116
+ super.onAttachedToWindow()
117
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)) {
118
+ fail("This WebView cannot route localhost.")
119
+ return
120
+ }
121
+ val listener = SocksListener {
122
+ TunnelAccess.request { requestId ->
123
+ main.post { onAccessRequest(mapOf("requestId" to requestId)) }
124
+ }
125
+ }
126
+ this.listener = listener
127
+ val onSet = Runnable {
128
+ main.post {
129
+ // Detached before the override applied; onDetachedFromWindow already cleared it.
130
+ if (this.listener !== listener) return@post
131
+ proxied = true
132
+ pendingUrl?.let { loadUrl(it) }
133
+ }
134
+ }
135
+ // `*` loads everything directly, and the implicit-rule removal after it takes loopback back
136
+ // out of that bypass, the same split the desktop app makes with `*,<-loopback>`.
137
+ // Older WebViews reject `socks5://`; their `socks://` is SOCKS4, which the listener speaks too.
138
+ for (scheme in listOf("socks5", "socks")) {
139
+ val config = ProxyConfig.Builder()
140
+ .addProxyRule("$scheme://127.0.0.1:${listener.port}")
141
+ .addBypassRule("*")
142
+ .removeImplicitRules()
143
+ .build()
144
+ val set = runCatching {
145
+ ProxyController.getInstance().setProxyOverride(config, { it.run() }, onSet)
146
+ }
147
+ if (set.isSuccess) return
148
+ }
149
+ fail("This WebView cannot route localhost.")
150
+ }
151
+
152
+ override fun onDetachedFromWindow() {
153
+ super.onDetachedFromWindow()
154
+ // Cleared even when the override has not applied yet, so it never outlives this view.
155
+ if (listener != null) {
156
+ ProxyController.getInstance().clearProxyOverride({ it.run() }) {}
157
+ }
158
+ listener?.close()
159
+ listener = null
160
+ proxied = false
161
+ }
162
+
163
+ /** Called when React removes the view; a detach alone keeps the page for a reattach. */
164
+ fun destroyWebView() {
165
+ webView?.let {
166
+ removeView(it)
167
+ it.destroy()
168
+ }
169
+ webView = null
170
+ }
171
+
172
+ /** Opens `url`, even when it is the address already showing. */
173
+ fun loadUrl(url: String) {
174
+ val webView = webView
175
+ if (!proxied || webView == null) {
176
+ pendingUrl = url
177
+ return
178
+ }
179
+ pendingUrl = null
180
+ webView.loadUrl(url)
181
+ }
182
+
183
+ fun goBack() = main.post { webView?.goBack() }
184
+ fun goForward() = main.post { webView?.goForward() }
185
+ fun reload() = main.post { webView?.reload() }
186
+
187
+ private companion object {
188
+ const val SCROLL_STEP_DP = 24f
189
+ }
190
+}
apps/mobile/modules/t3-preview-tunnel/expo-module.config.json
new
+5
@@ -0,0 +1,5 @@
1
+{
2
+ "platforms": ["apple", "android"],
3
+ "apple": { "modules": ["T3PreviewTunnelModule"] },
4
+ "android": { "modules": ["expo.modules.t3previewtunnel.T3PreviewTunnelModule"] }
5
+}
apps/mobile/modules/t3-preview-tunnel/ios/T3PreviewTunnel.podspec
new
+13
@@ -0,0 +1,13 @@
1
+Pod::Spec.new do |s|
2
+ s.name = 'T3PreviewTunnel'
3
+ s.version = '1.0.0'
4
+ s.summary = 'Webview whose localhost is another T3 Code environment.'
5
+ s.description = "Loads an environment's loopback pages on the device through the server's preview tunnel, keeping their localhost origin."
6
+ s.author = 'T3 Tools'
7
+ s.homepage = 'https://t3tools.com'
8
+ s.platform = :ios, '18.0'
9
+ s.source = { :path => '.' }
10
+ s.static_framework = true
11
+ s.dependency 'ExpoModulesCore'
12
+ s.source_files = '*.swift'
13
+end
apps/mobile/modules/t3-preview-tunnel/ios/T3PreviewTunnelModule.swift
new
+72
@@ -0,0 +1,72 @@
1
+import ExpoModulesCore
2
+import Foundation
3
+
4
+public final class T3PreviewTunnelModule: Module {
5
+ public func definition() -> ModuleDefinition {
6
+ Name("T3PreviewTunnel")
7
+
8
+ Function("resolveAccess") { (requestId: String, url: String?) in
9
+ T3TunnelAccess.shared.resolve(requestId: requestId, url: url)
10
+ }
11
+
12
+ View(T3TunnelWebView.self) {
13
+ Events("onAccessRequest", "onNavigationChange", "onLoadError", "onPageScroll")
14
+
15
+ Prop("environmentId") { (view: T3TunnelWebView, environmentId: String) in
16
+ view.setEnvironment(environmentId)
17
+ }
18
+
19
+ Prop("topInset") { (view: T3TunnelWebView, inset: Double) in
20
+ view.setTopInset(CGFloat(inset))
21
+ }
22
+
23
+ Prop("url") { (view: T3TunnelWebView, url: String) in
24
+ view.load(url)
25
+ }
26
+
27
+ AsyncFunction("loadUrl") { (view: T3TunnelWebView, url: String) in
28
+ view.navigate(url)
29
+ }.runOnQueue(.main)
30
+
31
+ AsyncFunction("goBack") { (view: T3TunnelWebView) in
32
+ view.goBack()
33
+ }.runOnQueue(.main)
34
+
35
+ AsyncFunction("goForward") { (view: T3TunnelWebView) in
36
+ view.goForward()
37
+ }.runOnQueue(.main)
38
+
39
+ AsyncFunction("reload") { (view: T3TunnelWebView) in
40
+ view.reload()
41
+ }.runOnQueue(.main)
42
+ }
43
+ }
44
+}
45
+
46
+/// Pending asks for a tunnel URL. JavaScript owns the environment's credentials and the route in
47
+/// use, so every connection asks it for a freshly ticketed URL.
48
+final class T3TunnelAccess {
49
+ static let shared = T3TunnelAccess()
50
+
51
+ private let lock = NSLock()
52
+ private var pending: [String: (String?) -> Void] = [:]
53
+ private var nextId = 0
54
+
55
+ func request(ask: (String) -> Void, completion: @escaping (String?) -> Void) {
56
+ let requestId: String = lock.withLock {
57
+ nextId += 1
58
+ let requestId = "preview-tunnel-\(nextId)"
59
+ pending[requestId] = completion
60
+ return requestId
61
+ }
62
+ DispatchQueue.global().asyncAfter(deadline: .now() + 15) { [weak self] in
63
+ self?.resolve(requestId: requestId, url: nil)
64
+ }
65
+ ask(requestId)
66
+ }
67
+
68
+ func resolve(requestId: String, url: String?) {
69
+ let completion = lock.withLock { pending.removeValue(forKey: requestId) }
70
+ completion?(url)
71
+ }
72
+}
apps/mobile/modules/t3-preview-tunnel/ios/T3SocksListener.swift
new
+374
@@ -0,0 +1,374 @@
1
+import Foundation
2
+import Network
3
+
4
+/// A SOCKS5 listener on 127.0.0.1 that carries each loopback CONNECT over one WebSocket to the
5
+/// environment's /api/preview/tunnel. It never connects anywhere on this device, so a tunnel
6
+/// that fails is a connection error, never one of this device's own servers.
7
+final class T3SocksListener {
8
+ typealias AccessRequest = (@escaping (String?) -> Void) -> Void
9
+
10
+ private let queue = DispatchQueue(label: "com.t3tools.preview-tunnel")
11
+ private let requestAccess: AccessRequest
12
+ private var listener: NWListener?
13
+ private var connections: [ObjectIdentifier: T3SocksConnection] = [:]
14
+ private var failure: T3TunnelFailure?
15
+
16
+ /// Why the latest tunnel failed, or nil once one opened. The page's error alone can't tell.
17
+ var lastFailure: T3TunnelFailure? { queue.sync { failure } }
18
+
19
+ init(requestAccess: @escaping AccessRequest) {
20
+ self.requestAccess = requestAccess
21
+ }
22
+
23
+ var isListening: Bool { listener?.state == .ready }
24
+
25
+ /// `port` asks for a specific port, so a restarted listener keeps the address WebKit was given.
26
+ /// `onFailed` runs when iOS tears the socket down, as it can while the app is in the background.
27
+ func start(
28
+ port: UInt16? = nil,
29
+ onReady: @escaping (UInt16) -> Void,
30
+ onFailed: @escaping () -> Void = {}
31
+ ) {
32
+ let parameters = NWParameters.tcp
33
+ parameters.allowLocalEndpointReuse = true
34
+ parameters.requiredLocalEndpoint = .hostPort(
35
+ host: "127.0.0.1", port: port.flatMap(NWEndpoint.Port.init(rawValue:)) ?? .any
36
+ )
37
+ guard let listener = try? NWListener(using: parameters) else { return onFailed() }
38
+ self.listener = listener
39
+ listener.stateUpdateHandler = { [weak listener] state in
40
+ switch state {
41
+ case .ready: if let port = listener?.port?.rawValue { onReady(port) }
42
+ case .failed: onFailed()
43
+ default: break
44
+ }
45
+ }
46
+ listener.newConnectionHandler = { [weak self] connection in
47
+ T3TunnelDiagnostics.shared.note { $0.accepted += 1 }
48
+ guard let self else { return connection.cancel() }
49
+ let socks = T3SocksConnection(
50
+ connection: connection,
51
+ queue: queue,
52
+ requestAccess: requestAccess,
53
+ onOutcome: { [weak self] failure in self?.failure = failure },
54
+ onClose: { [weak self] socks in
55
+ self?.connections.removeValue(forKey: ObjectIdentifier(socks))
56
+ }
57
+ )
58
+ connections[ObjectIdentifier(socks)] = socks
59
+ socks.start()
60
+ }
61
+ listener.start(queue: queue)
62
+ }
63
+
64
+ func stop() {
65
+ queue.async { [self] in
66
+ listener?.cancel()
67
+ for socks in connections.values { socks.close() }
68
+ connections.removeAll()
69
+ }
70
+ }
71
+}
72
+
73
+enum T3TunnelFailure: String {
74
+ case environment
75
+ case port
76
+}
77
+
78
+private let replySucceeded: UInt8 = 0
79
+private let replyFailure: UInt8 = 1
80
+private let replyNotAllowed: UInt8 = 2
81
+private let replyCommandNotSupported: UInt8 = 7
82
+private let replyAddressNotSupported: UInt8 = 8
83
+
84
+private func socksReply(_ code: UInt8) -> Data { Data([5, code, 0, 1, 0, 0, 0, 0, 0, 0]) }
85
+
86
+// The webview names the host as typed, so IP literals can also arrive as domain names.
87
+private func isLoopbackName(_ name: String) -> Bool {
88
+ let name = name.lowercased()
89
+ if name == "localhost" || name.hasSuffix(".localhost") { return true }
90
+ if name == T3Loopback.standInHost { return true }
91
+ if let address = IPv4Address(name) { return address.rawValue.first == 127 }
92
+ if let address = IPv6Address(name) { return address.isLoopback }
93
+ return false
94
+}
95
+
96
+private enum SocksRequest {
97
+ case connect(port: UInt16, consumed: Int)
98
+ case refuse(UInt8)
99
+}
100
+
101
+/// Nil until the whole request has arrived.
102
+private func parseConnect(_ data: [UInt8]) -> SocksRequest? {
103
+ guard data.count >= 5 else { return nil }
104
+ let hostLength: Int
105
+ switch data[3] {
106
+ case 1: hostLength = 4
107
+ case 4: hostLength = 16
108
+ case 3: hostLength = 1 + Int(data[4])
109
+ default: return .refuse(replyAddressNotSupported)
110
+ }
111
+ let end = 4 + hostLength + 2
112
+ guard data.count >= end else { return nil }
113
+ guard data[0] == 5, data[1] == 1 else { return .refuse(replyCommandNotSupported) }
114
+ let host = Array(data[4..<(4 + hostLength)])
115
+ let loopback: Bool
116
+ switch data[3] {
117
+ case 1: loopback = host[0] == 127
118
+ case 4: loopback = IPv6Address(Data(host))?.isLoopback ?? false
119
+ default: loopback = isLoopbackName(String(decoding: host.dropFirst(), as: UTF8.self))
120
+ }
121
+ guard loopback else { return .refuse(replyNotAllowed) }
122
+ let port = UInt16(data[end - 2]) << 8 | UInt16(data[end - 1])
123
+ return .connect(port: port, consumed: end)
124
+}
125
+
126
+private final class T3SocksConnection {
127
+ private let connection: NWConnection
128
+ private let queue: DispatchQueue
129
+ private let requestAccess: T3SocksListener.AccessRequest
130
+ private let onOutcome: (T3TunnelFailure?) -> Void
131
+ private let onClose: (T3SocksConnection) -> Void
132
+ private var received: [UInt8] = []
133
+ private var greeted = false
134
+ private var tunnel: URLSessionWebSocketTask?
135
+ private var closed = false
136
+ // Plain HTTP only: the page names the stand-in host, the environment's servers expect localhost.
137
+ private var toServer = T3HostSwap(from: T3Loopback.standInHost, to: "localhost")
138
+ private var toPage = T3HostSwap(from: "localhost", to: T3Loopback.standInHost)
139
+
140
+ init(
141
+ connection: NWConnection,
142
+ queue: DispatchQueue,
143
+ requestAccess: @escaping T3SocksListener.AccessRequest,
144
+ onOutcome: @escaping (T3TunnelFailure?) -> Void,
145
+ onClose: @escaping (T3SocksConnection) -> Void
146
+ ) {
147
+ self.connection = connection
148
+ self.queue = queue
149
+ self.requestAccess = requestAccess
150
+ self.onOutcome = onOutcome
151
+ self.onClose = onClose
152
+ }
153
+
154
+ func start() {
155
+ connection.stateUpdateHandler = { [weak self] state in
156
+ switch state {
157
+ case .failed, .cancelled: self?.close()
158
+ default: break
159
+ }
160
+ }
161
+ connection.start(queue: queue)
162
+ readHandshake()
163
+ }
164
+
165
+ func close() {
166
+ guard !closed else { return }
167
+ closed = true
168
+ tunnel?.cancel(with: .normalClosure, reason: nil)
169
+ connection.cancel()
170
+ onClose(self)
171
+ }
172
+
173
+ /// Sends the final bytes, then closes once they are written.
174
+ private func finish(_ data: Data?) {
175
+ connection.send(
176
+ content: data, contentContext: .finalMessage, isComplete: true,
177
+ completion: .contentProcessed { [weak self] _ in self?.queue.async { self?.close() } }
178
+ )
179
+ }
180
+
181
+ private func readHandshake() {
182
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 4096) {
183
+ [weak self] data, _, isComplete, error in
184
+ guard let self, !closed else { return }
185
+ if let data { received.append(contentsOf: data) }
186
+ if !greeted {
187
+ guard received.count >= 2, received.count >= 2 + Int(received[1]) else {
188
+ return isComplete || error != nil ? close() : readHandshake()
189
+ }
190
+ let methods = received[2..<(2 + Int(received[1]))]
191
+ guard received[0] == 5, methods.contains(0) else { return finish(Data([5, 0xff])) }
192
+ connection.send(content: Data([5, 0]), completion: .idempotent)
193
+ received.removeFirst(2 + Int(received[1]))
194
+ greeted = true
195
+ }
196
+ switch parseConnect(received) {
197
+ case nil:
198
+ if isComplete || error != nil { close() } else { readHandshake() }
199
+ case .refuse(let code):
200
+ T3TunnelDiagnostics.shared.note { $0.refused = "\(code)" }
201
+ finish(socksReply(code))
202
+ case .connect(let port, let consumed):
203
+ received.removeFirst(consumed)
204
+ T3TunnelDiagnostics.shared.note { $0.asked += 1 }
205
+ requestAccess { [weak self] url in
206
+ T3TunnelDiagnostics.shared.note { url == nil ? ($0.denied += 1) : ($0.granted += 1) }
207
+ self?.queue.async { self?.openTunnel(base: url, port: port) }
208
+ }
209
+ }
210
+ }
211
+ }
212
+
213
+ private func openTunnel(base: String?, port: UInt16) {
214
+ guard !closed else { return }
215
+ guard let base, var components = URLComponents(string: base) else {
216
+ onOutcome(.environment)
217
+ return finish(socksReply(replyFailure))
218
+ }
219
+ components.queryItems = (components.queryItems ?? []) + [
220
+ URLQueryItem(name: "port", value: String(port))
221
+ ]
222
+ guard let url = components.url else { return finish(socksReply(replyFailure)) }
223
+ // The same budget as the access request, so a stalled upgrade refuses the page promptly.
224
+ let tunnel = URLSession.shared.webSocketTask(with: URLRequest(url: url, timeoutInterval: 15))
225
+ tunnel.maximumMessageSize = 16 * 1024 * 1024
226
+ self.tunnel = tunnel
227
+ tunnel.resume()
228
+ // A pong is the first sign the handshake succeeded; until then the page gets no reply.
229
+ tunnel.sendPing { [weak self] error in
230
+ if let error { T3TunnelDiagnostics.shared.note { $0.tunnelError = error.localizedDescription } }
231
+ self?.queue.async {
232
+ guard let self, !self.closed else { return }
233
+ if error != nil {
234
+ // The environment marks a dead or blocked port; any other failure, including a proxy's
235
+ // 502 while the environment is down, means the environment itself is out of reach.
236
+ let portRefused = (tunnel.response as? HTTPURLResponse)?
237
+ .value(forHTTPHeaderField: "x-t3-tunnel-port-refused") != nil
238
+ self.onOutcome(portRefused ? .port : .environment)
239
+ return self.finish(socksReply(replyFailure))
240
+ }
241
+ self.onOutcome(nil)
242
+ self.connection.send(content: socksReply(replySucceeded), completion: .idempotent)
243
+ if !self.received.isEmpty {
244
+ let early = Data(self.received)
245
+ self.received = []
246
+ tunnel.send(.data(self.swapToServer(early))) { _ in }
247
+ }
248
+ self.pumpToTunnel(tunnel)
249
+ self.pumpFromTunnel(tunnel)
250
+ }
251
+ }
252
+ }
253
+
254
+ /// The page's first bytes decide: a TLS handshake is left alone, anything else is plain HTTP.
255
+ private func swapToServer(_ data: Data) -> Data {
256
+ if !toServer.isDecided {
257
+ let plain = data.first != 0x16
258
+ toServer.decide(plain)
259
+ toPage.decide(plain)
260
+ }
261
+ return toServer.isEnabled ? toServer.apply(data) : data
262
+ }
263
+
264
+ // Each direction asks for the next chunk only after the previous one is written, so a slow
265
+ // side slows the other instead of piling up in memory.
266
+ private func pumpToTunnel(_ tunnel: URLSessionWebSocketTask) {
267
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) {
268
+ [weak self] data, _, isComplete, error in
269
+ guard let self, !closed else { return }
270
+ if let data, !data.isEmpty {
271
+ let data = swapToServer(data)
272
+ tunnel.send(.data(data)) { [weak self] error in
273
+ self?.queue.async {
274
+ guard let self, !self.closed else { return }
275
+ if error != nil { self.close() } else if isComplete { self.close() } else {
276
+ self.pumpToTunnel(tunnel)
277
+ }
278
+ }
279
+ }
280
+ } else if isComplete || error != nil {
281
+ close()
282
+ } else {
283
+ pumpToTunnel(tunnel)
284
+ }
285
+ }
286
+ }
287
+
288
+ private func pumpFromTunnel(_ tunnel: URLSessionWebSocketTask) {
289
+ tunnel.receive { [weak self] result in
290
+ self?.queue.async {
291
+ guard let self, !self.closed else { return }
292
+ switch result {
293
+ case .failure:
294
+ // The environment closed its side; flush what the page has not read yet.
295
+ self.finish(nil)
296
+ case .success(let message):
297
+ let data: Data
298
+ switch message {
299
+ case .data(let bytes): data = bytes
300
+ case .string(let text): data = Data(text.utf8)
301
+ @unknown default: data = Data()
302
+ }
303
+ self.connection.send(
304
+ content: self.toPage.isEnabled ? self.toPage.apply(data) : data,
305
+ completion: .contentProcessed { [weak self] error in
306
+ self?.queue.async {
307
+ guard let self, !self.closed else { return }
308
+ if error != nil { self.close() } else { self.pumpFromTunnel(tunnel) }
309
+ }
310
+ }
311
+ )
312
+ }
313
+ }
314
+ }
315
+ }
316
+}
317
+
318
+/// Swaps one string for another of the same length within each chunk. Holding back a partial
319
+/// match could stall a reply ending in its first letters, so one split across chunks is missed;
320
+/// the Host header always arrives whole.
321
+struct T3HostSwap {
322
+ private let from: [UInt8]
323
+ private let to: [UInt8]
324
+ private(set) var isDecided = false
325
+ private(set) var isEnabled = false
326
+
327
+ init(from: String, to: String) {
328
+ self.from = Array(from.utf8)
329
+ self.to = Array(to.utf8)
330
+ precondition(self.from.count == self.to.count, "a swap must keep message lengths")
331
+ }
332
+
333
+ mutating func decide(_ enabled: Bool) {
334
+ isDecided = true
335
+ isEnabled = enabled
336
+ }
337
+
338
+ func apply(_ data: Data) -> Data {
339
+ var bytes = [UInt8](data)
340
+ var index = 0
341
+ while index + from.count <= bytes.count {
342
+ if bytes[index..<(index + from.count)].elementsEqual(from) {
343
+ bytes.replaceSubrange(index..<(index + from.count), with: to)
344
+ index += from.count
345
+ } else {
346
+ index += 1
347
+ }
348
+ }
349
+ return Data(bytes)
350
+ }
351
+}
352
+
353
+// What the proxy saw, shown with the page error so a report carries it.
354
+final class T3TunnelDiagnostics {
355
+ struct Counts {
356
+ var accepted = 0
357
+ var asked = 0
358
+ var granted = 0
359
+ var denied = 0
360
+ var refused = "-"
361
+ var tunnelError = "-"
362
+ }
363
+
364
+ static let shared = T3TunnelDiagnostics()
365
+ private let lock = NSLock()
366
+ private var counts = Counts()
367
+
368
+ func note(_ update: (inout Counts) -> Void) { lock.withLock { update(&counts) } }
369
+ var summary: String {
370
+ lock.withLock {
371
+ "accepted \(counts.accepted), asked \(counts.asked), granted \(counts.granted), denied \(counts.denied), refused \(counts.refused), tunnel \(counts.tunnelError)"
372
+ }
373
+ }
374
+}
apps/mobile/modules/t3-preview-tunnel/ios/T3TunnelWebView.swift
new
+382
@@ -0,0 +1,382 @@
1
+import ExpoModulesCore
2
+import Network
3
+import WebKit
4
+
5
+/// A webview whose loopback is another environment's: `localhost` requests go to a SOCKS
6
+/// listener in this process, which carries each connection over the environment's tunnel.
7
+final class T3TunnelWebView: ExpoView, WKNavigationDelegate {
8
+ let onAccessRequest = EventDispatcher()
9
+ let onNavigationChange = EventDispatcher()
10
+ let onLoadError = EventDispatcher()
11
+ let onPageScroll = EventDispatcher()
12
+
13
+ private var webView: WKWebView?
14
+ private var proxyPort: UInt16?
15
+ private var environmentId: String?
16
+ private var pendingUrl: String?
17
+ private var requestedUrl: URL?
18
+ /// A link that failed before its page committed leaves the old page current, so retry it.
19
+ private var failedUrl: URL?
20
+ private var observations: [NSKeyValueObservation] = []
21
+ private var reportedScrollY: CGFloat = 0
22
+ private var scrolledDistance: CGFloat = 0
23
+ private var lastOffsetY: CGFloat = 0
24
+ private var topInset: CGFloat = 0
25
+
26
+ /// JavaScript remounts the view for another environment, so only the first one counts.
27
+ func setEnvironment(_ environmentId: String) {
28
+ guard self.environmentId == nil else { return }
29
+ self.environmentId = environmentId
30
+ T3EnvironmentProxy.forEnvironment(environmentId).attach(self) { [weak self] port in
31
+ self?.proxyPort = port
32
+ self?.attachWebView()
33
+ }
34
+ }
35
+
36
+ private func attachWebView() {
37
+ guard webView == nil, let proxyPort, let environmentId else { return }
38
+ let configuration = WKWebViewConfiguration()
39
+ configuration.websiteDataStore = T3EnvironmentProxy.forEnvironment(environmentId)
40
+ .store(proxyPort: proxyPort)
41
+ let webView = WKWebView(frame: bounds, configuration: configuration)
42
+ webView.navigationDelegate = self
43
+ webView.allowsBackForwardNavigationGestures = true
44
+ // The page scrolls under the browser bar, like Safari; `topInset` keeps its top clear.
45
+ webView.scrollView.contentInsetAdjustmentBehavior = .never
46
+ webView.isOpaque = false
47
+ applyTopInset(to: webView)
48
+ webView.isInspectable = true
49
+ addSubview(webView)
50
+ self.webView = webView
51
+ observations = [
52
+ webView.observe(\.url) { [weak self] _, _ in self?.reportNavigation() },
53
+ webView.observe(\.title) { [weak self] _, _ in self?.reportNavigation() },
54
+ webView.observe(\.isLoading) { [weak self] _, _ in self?.reportNavigation() },
55
+ webView.observe(\.canGoBack) { [weak self] _, _ in self?.reportNavigation() },
56
+ webView.observe(\.canGoForward) { [weak self] _, _ in self?.reportNavigation() },
57
+ webView.observe(\.themeColor) { [weak self] _, _ in self?.reportNavigation() },
58
+ webView.observe(\.underPageBackgroundColor) { [weak self] _, _ in self?.reportNavigation() },
59
+ webView.scrollView.observe(\.contentOffset) { [weak self] scrollView, _ in
60
+ self?.reportScroll(scrollView)
61
+ },
62
+ ]
63
+ if let pendingUrl { load(pendingUrl) }
64
+ }
65
+
66
+ override func layoutSubviews() {
67
+ super.layoutSubviews()
68
+ webView?.frame = bounds
69
+ if let webView { applyIndicatorInsets(to: webView) }
70
+ }
71
+
72
+ override func safeAreaInsetsDidChange() {
73
+ super.safeAreaInsetsDidChange()
74
+ if let webView { applyIndicatorInsets(to: webView) }
75
+ }
76
+
77
+ /// The scroll indicator runs from under the bar to above the home indicator.
78
+ private func applyIndicatorInsets(to webView: WKWebView) {
79
+ let insets = UIEdgeInsets(top: topInset, left: 0, bottom: safeAreaInsets.bottom, right: 0)
80
+ if webView.scrollView.verticalScrollIndicatorInsets != insets {
81
+ webView.scrollView.verticalScrollIndicatorInsets = insets
82
+ }
83
+ }
84
+
85
+ func load(_ url: String) {
86
+ guard let webView else {
87
+ pendingUrl = url
88
+ return
89
+ }
90
+ pendingUrl = nil
91
+ guard let target = URL(string: url).map(T3Loopback.standIn), webView.url != target else {
92
+ return
93
+ }
94
+ requestedUrl = target
95
+ webView.load(URLRequest(url: target))
96
+ }
97
+
98
+ /// Opens `url`, even when it is the address already showing.
99
+ func navigate(_ url: String) {
100
+ guard let webView else {
101
+ pendingUrl = url
102
+ return
103
+ }
104
+ guard let target = URL(string: url).map(T3Loopback.standIn) else { return }
105
+ requestedUrl = target
106
+ webView.load(URLRequest(url: target))
107
+ }
108
+
109
+ func setTopInset(_ inset: CGFloat) {
110
+ guard inset != topInset else { return }
111
+ topInset = inset
112
+ if let webView { applyTopInset(to: webView) }
113
+ }
114
+
115
+ /// A page resting at its top stays there when the bar grows or shrinks.
116
+ private func applyTopInset(to webView: WKWebView) {
117
+ let scrollView = webView.scrollView
118
+ let atTop = scrollView.contentOffset.y <= -scrollView.contentInset.top + 1
119
+ scrollView.contentInset.top = topInset
120
+ applyIndicatorInsets(to: webView)
121
+ if atTop { scrollView.contentOffset.y = -topInset }
122
+ }
123
+
124
+ func goBack() { webView?.goBack() }
125
+ func goForward() { webView?.goForward() }
126
+ // After a failed load the webview may show no page or the previous one, so retry what failed.
127
+ func reload() {
128
+ guard let environmentId else { return reloadPage() }
129
+ T3EnvironmentProxy.forEnvironment(environmentId).ensureListening { [weak self] _ in
130
+ self?.reloadPage()
131
+ }
132
+ }
133
+
134
+ private func reloadPage() {
135
+ guard let webView else { return }
136
+ if let target = failedUrl ?? (webView.url == nil ? requestedUrl : nil) {
137
+ failedUrl = nil
138
+ webView.load(URLRequest(url: target))
139
+ } else {
140
+ webView.reload()
141
+ }
142
+ }
143
+
144
+ /// Reports how far the user has scrolled, in steps, enough for the bar to follow its direction.
145
+ private func reportScroll(_ scrollView: UIScrollView) {
146
+ // Rubber-banding past either end isn't scrolling, or the bounce back would flip the bar.
147
+ let top = -scrollView.adjustedContentInset.top
148
+ let bottom = max(
149
+ top,
150
+ scrollView.contentSize.height - scrollView.bounds.height
151
+ + scrollView.adjustedContentInset.bottom
152
+ )
153
+ let offset = min(max(scrollView.contentOffset.y, top), bottom)
154
+ defer { lastOffsetY = offset }
155
+ // WebKit's own offset changes while loading aren't the user scrolling.
156
+ let userScrolling = scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating
157
+ if userScrolling { scrolledDistance = max(0, scrolledDistance + offset - lastOffsetY) }
158
+ if offset <= top + 1 { scrolledDistance = 0 }
159
+ let y = scrolledDistance
160
+ guard abs(y - reportedScrollY) >= 24 || (y == 0 && reportedScrollY != 0) else { return }
161
+ reportedScrollY = y
162
+ onPageScroll(["y": y])
163
+ }
164
+
165
+ private func reportNavigation() {
166
+ guard let webView else { return }
167
+ onNavigationChange([
168
+ "url": webView.url.map(T3Loopback.shown)?.absoluteString ?? "",
169
+ "title": webView.title ?? "",
170
+ "loading": webView.isLoading,
171
+ "canGoBack": webView.canGoBack,
172
+ "canGoForward": webView.canGoForward,
173
+ // What Safari tints its bar with: the page's theme-color, else its background.
174
+ "pageColor": Self.hex(webView.themeColor ?? webView.underPageBackgroundColor) ?? "",
175
+ ])
176
+ }
177
+
178
+ private static func hex(_ color: UIColor?) -> String? {
179
+ var (red, green, blue, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
180
+ guard let color, color.getRed(&red, green: &green, blue: &blue, alpha: &alpha), alpha > 0
181
+ else { return nil }
182
+ let byte = { (value: CGFloat) in Int((min(max(value, 0), 1) * 255).rounded()) }
183
+ return String(format: "#%02x%02x%02x", byte(red), byte(green), byte(blue))
184
+ }
185
+
186
+ func webView(
187
+ _ webView: WKWebView,
188
+ didFailProvisionalNavigation navigation: WKNavigation!,
189
+ withError error: Error
190
+ ) {
191
+ let nsError = error as NSError
192
+ if !(nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled) {
193
+ let failing = nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String
194
+ failedUrl = failing.flatMap(URL.init(string:)) ?? requestedUrl
195
+ }
196
+ reportError(error)
197
+ }
198
+
199
+ /// Links and redirects to loopback go to the stand-in host, which is the one the proxy carries.
200
+ func webView(
201
+ _ webView: WKWebView,
202
+ decidePolicyFor navigationAction: WKNavigationAction,
203
+ decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void
204
+ ) {
205
+ let url = navigationAction.request.url
206
+ guard let url, navigationAction.targetFrame?.isMainFrame ?? true,
207
+ T3Loopback.standIn(url) != url
208
+ else { return decisionHandler(.allow) }
209
+ decisionHandler(.cancel)
210
+ // The same request at the stand-in host, so a form keeps its method, headers and body.
211
+ var request = navigationAction.request
212
+ let target = T3Loopback.standIn(url)
213
+ request.url = target
214
+ requestedUrl = target
215
+ webView.load(request)
216
+ }
217
+
218
+ func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
219
+ failedUrl = nil
220
+ }
221
+
222
+ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
223
+ reportError(error)
224
+ }
225
+
226
+ private func reportError(_ error: Error) {
227
+ let error = error as NSError
228
+ if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return }
229
+ let failingUrl = (error.userInfo[NSURLErrorFailingURLStringErrorKey] as? String)
230
+ .flatMap(URL.init(string:)).map(T3Loopback.shown)?.absoluteString
231
+ onLoadError([
232
+ "code": error.code,
233
+ "description": error.localizedDescription,
234
+ "url": failingUrl ?? "",
235
+ "debug": "\(error.domain) \(error.code), port \(proxyPort.map(String.init) ?? "none"), " + T3TunnelDiagnostics.shared.summary,
236
+ "cause": environmentId
237
+ .flatMap { T3EnvironmentProxy.forEnvironment($0).lastFailure?.rawValue } ?? "",
238
+ ])
239
+ }
240
+}
241
+
242
+/// Each environment keeps one listener on one port for the app's life, restarted there if iOS tore
243
+/// it down, and one in-memory data store pointed at it, so cookies survive closing or maximizing a
244
+/// page and never reach another environment's pages. A store saved on disk kept an old launch's
245
+/// proxy port on devices. Access requests go to the newest live view. Main thread only.
246
+private final class T3EnvironmentProxy {
247
+ nonisolated(unsafe) private static var proxies: [String: T3EnvironmentProxy] = [:]
248
+
249
+ nonisolated(unsafe) private static var foregroundObserver: NSObjectProtocol?
250
+
251
+ static func forEnvironment(_ environmentId: String) -> T3EnvironmentProxy {
252
+ if let proxy = proxies[environmentId] { return proxy }
253
+ // A real device can drop listening sockets while the app is suspended; the simulator never does.
254
+ foregroundObserver = foregroundObserver ?? NotificationCenter.default.addObserver(
255
+ forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main
256
+ ) { _ in
257
+ for proxy in proxies.values { proxy.ensureListening { _ in } }
258
+ }
259
+ let proxy = T3EnvironmentProxy()
260
+ proxies[environmentId] = proxy
261
+ return proxy
262
+ }
263
+
264
+ private var views: [WeakView] = []
265
+ private var listener: T3SocksListener?
266
+ private var port: UInt16?
267
+ private var waiting: [(UInt16) -> Void] = []
268
+ private var dataStore: WKWebsiteDataStore?
269
+
270
+ func store(proxyPort: UInt16) -> WKWebsiteDataStore {
271
+ if let dataStore { return dataStore }
272
+ let store = WKWebsiteDataStore.nonPersistent()
273
+ var proxy = ProxyConfiguration(
274
+ socksv5Proxy: .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: proxyPort)!)
275
+ )
276
+ // Only the stand-in host belongs to the environment; everything else loads directly.
277
+ proxy.matchDomains = [T3Loopback.standInHost]
278
+ proxy.allowFailover = false
279
+ store.proxyConfigurations = [proxy]
280
+ dataStore = store
281
+ return store
282
+ }
283
+
284
+ func attach(_ view: T3TunnelWebView, onReady: @escaping (UInt16) -> Void) {
285
+ views = views.filter { $0.view != nil } + [WeakView(view: view)]
286
+ ensureListening(onReady)
287
+ }
288
+
289
+ /// Starts the listener, or restarts it on its port if iOS tore it down.
290
+ func ensureListening(_ onReady: @escaping (UInt16) -> Void) {
291
+ if let port, listener?.isListening == true { return onReady(port) }
292
+ waiting.append(onReady)
293
+ guard waiting.count == 1 else { return }
294
+ startListener(attempt: 0)
295
+ }
296
+
297
+ private func startListener(attempt: Int) {
298
+ listener?.stop()
299
+ let listener = T3SocksListener { [weak self] completion in
300
+ T3TunnelAccess.shared.request(
301
+ ask: { requestId in
302
+ DispatchQueue.main.async {
303
+ guard let view = self?.views.last(where: { $0.view != nil })?.view else {
304
+ return T3TunnelAccess.shared.resolve(requestId: requestId, url: nil)
305
+ }
306
+ view.onAccessRequest(["requestId": requestId])
307
+ }
308
+ },
309
+ completion: completion
310
+ )
311
+ }
312
+ self.listener = listener
313
+ listener.start(
314
+ port: port,
315
+ onReady: { [weak self] port in DispatchQueue.main.async { self?.ready(port) } },
316
+ onFailed: { [weak self, weak listener] in
317
+ DispatchQueue.main.async {
318
+ guard let self, let listener, self.listener === listener else { return }
319
+ if self.waiting.isEmpty { return self.ensureListening { _ in } }
320
+ // Startup failed before it was ready: try again shortly, then give the waiters up so
321
+ // a later reload starts over instead of queueing behind a listener that never came.
322
+ guard attempt < 4 else {
323
+ self.listener = nil
324
+ self.waiting = []
325
+ return
326
+ }
327
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
328
+ guard self.listener === listener, !self.waiting.isEmpty else { return }
329
+ self.startListener(attempt: attempt + 1)
330
+ }
331
+ }
332
+ }
333
+ )
334
+ }
335
+
336
+ var lastFailure: T3TunnelFailure? { listener?.lastFailure }
337
+
338
+ private func ready(_ port: UInt16) {
339
+ self.port = port
340
+ let waiting = self.waiting
341
+ self.waiting = []
342
+ for onReady in waiting { onReady(port) }
343
+ }
344
+}
345
+
346
+private struct WeakView {
347
+ weak var view: T3TunnelWebView?
348
+}
349
+
350
+/// Real iPhones never send loopback addresses to a webview's proxy (the simulator does), so the
351
+/// view loads them under a stand-in host the proxy does carry, and shows `localhost` instead.
352
+/// It is as long as `localhost`, so the proxy can swap the two in plain HTTP without
353
+/// changing a message's length.
354
+enum T3Loopback {
355
+ static let standInHost = "t3lo.test"
356
+
357
+ static func isLoopbackHost(_ host: String) -> Bool {
358
+ let host = host.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
359
+ if host == "localhost" || host.hasSuffix(".localhost") { return true }
360
+ if let address = IPv4Address(host) { return address.rawValue.first == 127 }
361
+ if let address = IPv6Address(host) { return address.isLoopback }
362
+ return false
363
+ }
364
+
365
+ static func standIn(_ url: URL) -> URL {
366
+ guard let host = url.host(percentEncoded: false), isLoopbackHost(host) else { return url }
367
+ return replacingHost(url, with: standInHost)
368
+ }
369
+
370
+ static func shown(_ url: URL) -> URL {
371
+ guard url.host(percentEncoded: false)?.lowercased() == standInHost else { return url }
372
+ return replacingHost(url, with: "localhost")
373
+ }
374
+
375
+ private static func replacingHost(_ url: URL, with host: String) -> URL {
376
+ guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
377
+ return url
378
+ }
379
+ components.host = host
380
+ return components.url ?? url
381
+ }
382
+}
apps/mobile/package.json
+1
-1
@@ -135,7 +135,7 @@
135
"react-native-pdf-jsi": "6.1.0",
136
"react-native-reanimated": "4.7.1",
137
"react-native-safe-area-context": "~5.11.1",
138
- "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.59.tgz",
138
+ "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.61.tgz",
139
"react-native-svg": "15.16.1",
140
"react-native-webview": "14.0.1",
141
"react-native-worklets": "0.13.1",
apps/mobile/src/Stack.tsx
+7
-1
@@ -62,6 +62,7 @@ import { ReviewSheet } from "./features/review/ReviewSheet";
62
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
63
import { DevicePreviewRouteScreen } from "./features/devices/DevicePreviewRouteScreen";
64
import { BrowserPreviewRouteScreen } from "./features/browser/BrowserPreviewRouteScreen";
65
+import { LocalPreviewRouteScreen } from "./features/browser/LocalPreviewRouteScreen";
66
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
67
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
68
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
@@ -730,7 +731,12 @@ const RootStackConfig = createWorkspaceStackNavigator({
731
ThreadBrowserPreview: createNativeStackScreen({
732
screen: BrowserPreviewRouteScreen,
733
linking: `${THREAD_LINKING_PREFIX}/browser`,
733
- options: { ...modalRoute({ header: "solid" }), gestureEnabled: false },
734
+ options: immersiveRoute({ fullWidth: true }),
735
+ }),
736
+ ThreadLocalPreview: createNativeStackScreen({
737
+ screen: LocalPreviewRouteScreen,
738
+ linking: "environments/:environmentId/local-preview",
739
+ options: immersiveRoute({ fullWidth: true }),
740
}),
741
ThreadReview: createNativeStackScreen({
742
screen: ReviewSheet,
apps/mobile/src/features/browser/BrowserBar.tsx
new
+397
@@ -0,0 +1,397 @@
1
+import { BlurView } from "expo-blur";
2
+import { GlassView, isGlassEffectAPIAvailable } from "expo-glass-effect";
3
+import { useNavigation } from "@react-navigation/native";
4
+import { use, useEffect, useState, type ReactNode } from "react";
5
+import { Platform, Pressable, StyleSheet, TextInput, View } from "react-native";
6
+import Animated, {
7
+ interpolate,
8
+ useAnimatedStyle,
9
+ useDerivedValue,
10
+ useReducedMotion,
11
+ withTiming,
12
+} from "react-native-reanimated";
13
+import { useSafeAreaInsets } from "react-native-safe-area-context";
14
+import { useGT } from "gt-react-native";
15
+import { withUniwind } from "uniwind";
16
+
17
+import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
18
+import { AppText } from "../../components/ui/AppText";
19
+import { deriveSharedTopBand } from "../../lib/reserved-regions";
20
+import { isDarkThemeColor, themeColorWithAlpha } from "../../lib/mobileTheme";
21
+import { useBarInset } from "../../components/ui/useBarInset";
22
+import { WorkspaceColumnMetricsContext } from "../../native/v5-workspace-context";
23
+import { isDuoDevice } from "../../lib/device-type";
24
+import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
25
+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
26
+
27
+type BrowserBarProps = {
28
+ readonly url: string;
29
+ readonly editable: boolean;
30
+ readonly canGoBack: boolean;
31
+ readonly onClose: () => void;
32
+ readonly onBack: () => void;
33
+ readonly onReload: () => void;
34
+ readonly onSubmit: (value: string) => void;
35
+ /** In the inspector pane, opens the page full screen. */
36
+ readonly onMaximize?: () => void;
37
+ readonly trailing?: ReactNode;
38
+ /** The page's theme or background color; the app's sheet color until the page reports one. */
39
+ readonly pageColor?: string | null;
40
+};
41
+
42
+/**
43
+ * Every browser surface: full screen or in the inspector pane, a page on this device or a
44
+ * stream. The bar shrinks while the page scrolls down, like Safari's, and on the Duo the full
45
+ * screen bar takes the status bar with it. A page that can scroll under the bar gets it laid
46
+ * over itself on iOS, inset by `topInset`; a stream keeps the bar above it.
47
+ */
48
+export function BrowserChrome(props: {
49
+ readonly bar: BrowserBarProps;
50
+ readonly scrollsUnderBar: boolean;
51
+ readonly inPane?: boolean;
52
+ /** Keeps the whole bar showing, such as over an error. */
53
+ readonly holdExpanded?: boolean;
54
+ readonly children: (page: {
55
+ readonly topInset: number;
56
+ readonly onScrollDirection: (direction: "up" | "down") => void;
57
+ }) => ReactNode;
58
+}) {
59
+ const [scrolledDown, setScrolledDown] = useState(false);
60
+ const compact = scrolledDown && !props.holdExpanded;
61
+ const overlay = Platform.OS === "ios" && props.scrollsUnderBar;
62
+ const duo = isDuoDevice(useDeviceType());
63
+ const hidesStatusBar = !props.inPane && duo;
64
+ const navigation = useNavigation();
65
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the status bar is a native screen option
66
+ useEffect(() => {
67
+ if (!hidesStatusBar) return;
68
+ navigation.setOptions({ statusBarHidden: compact, statusBarAnimation: "fade" });
69
+ }, [navigation, hidesStatusBar, compact]);
70
+ // The page stays inset by the whole bar, so the bar shrinking never moves it, like Safari's.
71
+ const fullBarHeight = useBrowserBarLayout(props.inPane === true).height;
72
+ const [barHeight, setBarHeight] = useState(fullBarHeight);
73
+ if (!compact && fullBarHeight !== barHeight) setBarHeight(fullBarHeight);
74
+
75
+ const bar = (
76
+ <BrowserBar
77
+ {...props.bar}
78
+ compact={compact}
79
+ onExpand={() => setScrolledDown(false)}
80
+ compactHidesStatusBar={hidesStatusBar}
81
+ inPane={props.inPane === true}
82
+ />
83
+ );
84
+ const page = props.children({
85
+ topInset: overlay ? barHeight : 0,
86
+ onScrollDirection: (direction) => setScrolledDown(direction === "down"),
87
+ });
88
+ if (!overlay) {
89
+ return (
90
+ <>
91
+ {bar}
92
+ <View className="flex-1">{page}</View>
93
+ </>
94
+ );
95
+ }
96
+ return (
97
+ <View className="flex-1">
98
+ {page}
99
+ <View className="absolute inset-x-0 top-0">{bar}</View>
100
+ </View>
101
+ );
102
+}
103
+
104
+/**
105
+ * Safari's bar: frosted and tinted by the page (`pageColor`), with round controls and a centered
106
+ * host. `compact`, while the page scrolls down, shrinks it to a small host pill that expands it.
107
+ */
108
+function BrowserBar(
109
+ props: BrowserBarProps & {
110
+ readonly compact: boolean;
111
+ readonly onExpand: () => void;
112
+ /** The screen hides the status bar while compact, so the pill can sit at the very top. */
113
+ readonly compactHidesStatusBar: boolean;
114
+ readonly inPane: boolean;
115
+ },
116
+) {
117
+ const gt = useGT();
118
+ const [draft, setDraft] = useState<string | null>(null);
119
+ const layout = useBrowserBarLayout(props.inPane);
120
+ const reduceMotion = useReducedMotion();
121
+ const { themeVariables } = useAppearancePreferences();
122
+ const surface = props.pageColor || themeVariables["--color-sheet-solid"];
123
+ const ink: Ink = isDarkThemeColor(surface) ? "light" : "dark";
124
+ const inkColor = ink === "light" ? "#ffffff" : "#000000";
125
+ const compact = props.compact && draft === null;
126
+ const expandedHeight = layout.height;
127
+ const pillTop = props.compactHidesStatusBar ? 0 : layout.statusTop;
128
+ const compactHeight = pillTop + PILL_ROW_HEIGHT;
129
+ // One bar whose height follows the scroll, so nothing under it jumps between two layouts.
130
+ const progress = useDerivedValue(() =>
131
+ withTiming(compact ? 1 : 0, { duration: reduceMotion ? 0 : 280 }),
132
+ );
133
+ const barStyle = useAnimatedStyle(() => ({
134
+ height: interpolate(progress.value, [0, 1], [expandedHeight, compactHeight]),
135
+ }));
136
+ const controlsStyle = useAnimatedStyle(() => ({
137
+ opacity: interpolate(progress.value, [0, 0.5], [1, 0], "clamp"),
138
+ transform: [{ scale: interpolate(progress.value, [0, 1], [1, 0.92]) }],
139
+ }));
140
+ const pillStyle = useAnimatedStyle(() => ({
141
+ opacity: interpolate(progress.value, [0.4, 1], [0, 1], "clamp"),
142
+ }));
143
+ const hairlineStyle = useAnimatedStyle(() => ({ opacity: progress.value }));
144
+
145
+ return (
146
+ <Animated.View style={[{ overflow: "hidden" }, barStyle]}>
147
+ {Platform.OS === "ios" ? (
148
+ <BlurView
149
+ pointerEvents="none"
150
+ intensity={60}
151
+ tint={ink === "light" ? "dark" : "light"}
152
+ style={StyleSheet.absoluteFill}
153
+ />
154
+ ) : null}
155
+ <View
156
+ pointerEvents="none"
157
+ style={[
158
+ StyleSheet.absoluteFill,
159
+ { backgroundColor: themeColorWithAlpha(surface, Platform.OS === "ios" ? 0.82 : 1) },
160
+ ]}
161
+ />
162
+ <Animated.View
163
+ pointerEvents={compact ? "none" : "auto"}
164
+ style={[
165
+ {
166
+ position: "absolute",
167
+ top: layout.rowTop,
168
+ left: layout.left,
169
+ right: layout.right,
170
+ height: layout.rowHeight,
171
+ justifyContent: "center",
172
+ },
173
+ controlsStyle,
174
+ ]}
175
+ >
176
+ <View
177
+ className={
178
+ layout.narrow
179
+ ? "flex-row items-center gap-1.5 px-2"
180
+ : "flex-row items-center gap-2 px-3"
181
+ }
182
+ >
183
+ <RoundButton icon="xmark" label={gt("Close browser")} ink={ink} onPress={props.onClose} />
184
+ {props.canGoBack ? (
185
+ <RoundButton
186
+ icon="chevron.left"
187
+ label={gt("Back", { $context: "browser history" })}
188
+ ink={ink}
189
+ onPress={props.onBack}
190
+ />
191
+ ) : null}
192
+ {/* On a tablet the address stays a readable width, centered between the buttons. */}
193
+ <View className="min-w-0 flex-1 items-center">
194
+ <Glass ink={ink} className="h-11 w-full max-w-2xl flex-row items-center rounded-full">
195
+ <TextInput
196
+ accessibilityLabel={gt("Address", { $context: "browser address bar" })}
197
+ editable={props.editable}
198
+ // Unfocused, the field shows only the host, like Safari; editing starts from the URL.
199
+ value={draft ?? hostOf(props.url)}
200
+ onFocus={() => setDraft(props.url)}
201
+ onChangeText={setDraft}
202
+ onBlur={() => setDraft(null)}
203
+ onSubmitEditing={() => {
204
+ const value = draft ?? props.url;
205
+ setDraft(null);
206
+ props.onSubmit(value);
207
+ }}
208
+ placeholder={gt("Enter a URL")}
209
+ placeholderTextColor={themeColorWithAlpha(inkColor, 0.45)}
210
+ selectionColor={themeVariables["--color-primary"]}
211
+ autoCapitalize="none"
212
+ autoCorrect={false}
213
+ keyboardType="url"
214
+ returnKeyType="go"
215
+ selectTextOnFocus
216
+ lineBreakModeIOS="middle"
217
+ numberOfLines={1}
218
+ textAlign={draft === null ? "center" : "left"}
219
+ className="h-11 min-w-0 flex-1 pl-3 font-sans text-[15px]"
220
+ style={{ color: inkColor }}
221
+ />
222
+ <Pressable
223
+ accessibilityRole="button"
224
+ accessibilityLabel={gt("Reload page")}
225
+ disabled={!props.editable}
226
+ onPress={props.onReload}
227
+ className="h-11 w-9 items-center justify-center"
228
+ >
229
+ <SymbolView
230
+ name="arrow.clockwise"
231
+ size={16}
232
+ tintColor={themeColorWithAlpha(inkColor, props.editable ? 0.85 : 0.35)}
233
+ />
234
+ </Pressable>
235
+ </Glass>
236
+ </View>
237
+ {props.trailing}
238
+ {props.onMaximize ? (
239
+ <RoundButton
240
+ icon="arrow.up.left.and.arrow.down.right"
241
+ label={gt("Maximize page")}
242
+ ink={ink}
243
+ onPress={props.onMaximize}
244
+ />
245
+ ) : null}
246
+ </View>
247
+ </Animated.View>
248
+ <Animated.View
249
+ pointerEvents={compact ? "auto" : "none"}
250
+ style={[
251
+ { position: "absolute", top: pillTop, left: 0, right: 0, height: PILL_ROW_HEIGHT },
252
+ pillStyle,
253
+ ]}
254
+ className="items-center justify-center"
255
+ >
256
+ <Pressable
257
+ accessibilityRole="button"
258
+ accessibilityLabel={gt("Address {url}. Show the browser controls", { url: props.url })}
259
+ onPress={props.onExpand}
260
+ >
261
+ <Glass ink={ink} className="h-7 justify-center rounded-full px-3.5">
262
+ <AppText numberOfLines={1} className="text-xs" style={{ color: inkColor }}>
263
+ {hostOf(props.url)}
264
+ </AppText>
265
+ </Glass>
266
+ </Pressable>
267
+ </Animated.View>
268
+ <Animated.View
269
+ pointerEvents="none"
270
+ style={[
271
+ {
272
+ position: "absolute",
273
+ left: 0,
274
+ right: 0,
275
+ bottom: 0,
276
+ height: StyleSheet.hairlineWidth,
277
+ backgroundColor: ink === "light" ? "rgba(255,255,255,0.14)" : "rgba(0,0,0,0.12)",
278
+ },
279
+ hairlineStyle,
280
+ ]}
281
+ />
282
+ </Animated.View>
283
+ );
284
+}
285
+
286
+const EXPANDED_ROW_HEIGHT = 56;
287
+// UIKit's navigation bar in a workspace column, whose controls sit in its top 48pt.
288
+const NAVIGATION_BAR_HEIGHT = 58;
289
+const NAVIGATION_BAR_CONTROLS_HEIGHT = 48;
290
+const PILL_ROW_HEIGHT = 40;
291
+
292
+/**
293
+ * Where the whole bar's controls go. Full screen: below the top safe area, or beside the status
294
+ * where it covers only one end of that band. In the inspector pane: centered in the height of
295
+ * the headers beside it. `height` is what a page under the bar insets its content by.
296
+ */
297
+function useBrowserBarLayout(inPane: boolean) {
298
+ const band = deriveSharedTopBand(useNativeColumnLayoutMetrics());
299
+ const safeTop = useSafeAreaInsets().top;
300
+ // The pane draws no native bar of its own, so it lines up with the bars its neighbors draw.
301
+ const columns = use(WorkspaceColumnMetricsContext);
302
+ const barInset = useBarInset();
303
+ const columnTops = [...(columns?.byColumn.values() ?? [])].map((metrics) => metrics.safeArea.top);
304
+ const paneHeight = Math.max(barInset, ...columnTops);
305
+ if (inPane) {
306
+ return {
307
+ rowTop: Math.max(0, paneHeight - NAVIGATION_BAR_HEIGHT),
308
+ rowHeight: NAVIGATION_BAR_CONTROLS_HEIGHT,
309
+ left: 0,
310
+ right: 0,
311
+ narrow: false,
312
+ statusTop: 0,
313
+ height: paneHeight,
314
+ };
315
+ }
316
+ if (band) {
317
+ return {
318
+ rowTop: 0,
319
+ rowHeight: band.height,
320
+ left: band.left,
321
+ right: band.right,
322
+ narrow: true,
323
+ statusTop: safeTop,
324
+ height: band.height,
325
+ };
326
+ }
327
+ return {
328
+ rowTop: safeTop,
329
+ rowHeight: EXPANDED_ROW_HEIGHT,
330
+ left: 0,
331
+ right: 0,
332
+ narrow: false,
333
+ statusTop: safeTop,
334
+ height: safeTop + EXPANDED_ROW_HEIGHT,
335
+ };
336
+}
337
+
338
+type Ink = "light" | "dark";
339
+
340
+const StyledGlassView = withUniwind(GlassView, { style: { fromClassName: "className" } });
341
+
342
+function RoundButton(props: {
343
+ readonly icon: AppSymbolName;
344
+ readonly label: string;
345
+ readonly ink: Ink;
346
+ readonly onPress: () => void;
347
+}) {
348
+ return (
349
+ <Pressable accessibilityRole="button" accessibilityLabel={props.label} onPress={props.onPress}>
350
+ <Glass ink={props.ink} className="size-10 items-center justify-center rounded-full">
351
+ <SymbolView
352
+ name={props.icon}
353
+ size={17}
354
+ tintColor={props.ink === "light" ? "#ffffff" : "#000000"}
355
+ />
356
+ </Glass>
357
+ </Pressable>
358
+ );
359
+}
360
+
361
+/** Liquid glass where iOS has it, matched to the page's lightness rather than the app's. */
362
+function Glass(props: {
363
+ readonly ink: Ink;
364
+ readonly className: string;
365
+ readonly children: ReactNode;
366
+}) {
367
+ if (Platform.OS === "ios" && isGlassEffectAPIAvailable()) {
368
+ return (
369
+ <StyledGlassView
370
+ glassEffectStyle="regular"
371
+ colorScheme={props.ink === "light" ? "dark" : "light"}
372
+ isInteractive
373
+ className={props.className}
374
+ >
375
+ {props.children}
376
+ </StyledGlassView>
377
+ );
378
+ }
379
+ return (
380
+ <View
381
+ className={props.className}
382
+ style={{
383
+ backgroundColor: props.ink === "light" ? "rgba(255,255,255,0.12)" : "rgba(0,0,0,0.06)",
384
+ }}
385
+ >
386
+ {props.children}
387
+ </View>
388
+ );
389
+}
390
+
391
+function hostOf(value: string): string {
392
+ try {
393
+ return new URL(value).host;
394
+ } catch {
395
+ return value;
396
+ }
397
+}
apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
+117
-158
@@ -2,22 +2,24 @@ import { SheetHeader } from "../../components/ui/SheetHeader";
2
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3
import * as Dialog from "../../components/ui/Dialog";
4
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5
-import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/contracts";
5
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
6
import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
7
import * as Option from "effect/Option";
8
import { msg, useGT, useMessages } from "gt-react-native";
9
import { useEffect, useRef, useState } from "react";
10
-import { Platform, TextInput, View } from "react-native";
11
-import { useSafeAreaInsets } from "react-native-safe-area-context";
10
+import { Platform, View } from "react-native";
11
+import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
12
13
import { ControlPill } from "../../components/ui/ControlPill";
14
-import { m } from "../../i18n/messages";
14
+import { Menu } from "../../components/ui/Menu";
15
import { useContentTopInset } from "../../components/ui/useBarInset";
16
+import { m } from "../../i18n/messages";
17
import { useAppForeground } from "../../lib/appState";
18
19
import { useThreadServerBrowserTabs } from "../../state/preview";
20
import { usePreparedConnection } from "../../state/session";
21
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
22
+import { BrowserChrome } from "./BrowserBar";
23
import { BrowserTabMenu } from "./BrowserTabMenu";
24
import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";
25
import {
@@ -52,9 +54,9 @@ export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenPr
54
}
55
56
function BrowserUnavailableScreen({ onClose }: { readonly onClose: () => void }) {
57
+ const gt = useGT();
58
const insets = useSafeAreaInsets();
59
const contentTopInset = useContentTopInset();
57
- const gt = useGT();
60
return (
61
<View
62
className="flex-1 bg-sheet"
@@ -80,11 +82,9 @@ function BrowserPreviewScreen({
82
readonly initialTabId: string | null;
83
readonly onClose: () => void;
84
}) {
83
- const insets = useSafeAreaInsets();
84
- const contentTopInset = useContentTopInset();
85
- const { themeVariables } = useAppearancePreferences();
85
const gt = useGT();
86
const resolveMessage = useMessages();
87
+ const { themeVariables } = useAppearancePreferences();
88
const prepared = usePreparedConnection(environmentId);
89
const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
90
const focused = useIsFocused();
@@ -117,165 +117,124 @@ function BrowserPreviewScreen({
117
};
118
const live = (focused && foreground) || pictureInPicture.active;
119
120
+ const ready = streaming && canControl;
121
+ const command: PreviewStreamRef["command"] = (input) => streamRef.current?.command(input);
122
+ const showPictureInPicture =
123
+ // Android WebView cannot play video in picture in picture.
124
+ Platform.OS === "ios" &&
125
+ pictureInPicture.supported &&
126
+ (pictureInPicture.active || pdfUri === null);
127
+
128
return (
121
- <View
122
- className="flex-1 bg-sheet"
123
- style={{ paddingTop: contentTopInset, paddingBottom: insets.bottom }}
129
+ // The route spans the Duo's rail, so the screen insets its own sides.
130
+ <SafeAreaView
131
+ edges={["left", "right"]}
132
+ style={{ flex: 1, backgroundColor: themeVariables["--color-sheet-solid"] }}
133
>
125
- <SheetHeader
126
- title={
127
- tab ? browserTabTitle(tab, resolveMessage) : gt("Browser", { $context: "screen title" })
128
- }
129
- onClose={onClose}
130
- accessibilityLabel={gt("Close browser")}
131
- actions={
132
- // Android WebView cannot play video in picture in picture.
133
- Platform.OS === "ios" &&
134
- pictureInPicture.supported &&
135
- (pictureInPicture.active || pdfUri === null)
136
- ? [
137
- {
138
- accessibilityLabel: pictureInPicture.active
139
- ? gt("Exit picture in picture")
140
- : gt("Picture in picture"),
141
- icon: {
134
+ <BrowserChrome
135
+ key={tab ? `address:${tab.tabId}` : "address"}
136
+ scrollsUnderBar={false}
137
+ bar={{
138
+ url: tab ? browserTabUrl(tab) : "",
139
+ editable: ready,
140
+ canGoBack: ready && (tab?.canGoBack ?? false),
141
+ onClose,
142
+ onBack: () => command({ type: "history", delta: -1 }),
143
+ onReload: () => command({ type: "reload" }),
144
+ onSubmit: (value) => {
145
+ const url = normalizedOrNull(value);
146
+ if (url === null)
147
+ Dialog.alert(
148
+ m(msg("Could not open this address")),
149
+ m(msg("Enter an http or https URL.")),
150
+ );
151
+ else command({ type: "navigate", url });
152
+ },
153
+ trailing: (
154
+ <>
155
+ {showPictureInPicture ? (
156
+ <ControlPill
157
+ icon={{
158
ios: pictureInPicture.active ? "pip.exit" : "pip.enter",
159
android: "visibility",
144
- },
145
- selected: pictureInPicture.active,
146
- onPress: () => streamRef.current?.togglePictureInPicture(),
147
- },
148
- ]
149
- : []
150
- }
151
- menus={
152
- tabs.length > 1
153
- ? [
154
- {
155
- title: gt("Tabs", { $context: "browser tabs menu" }),
156
- icon: "square.on.square",
157
- items: tabs.map((entry) => ({
160
+ }}
161
+ accessibilityLabel={
162
+ pictureInPicture.active
163
+ ? gt("Exit picture in picture")
164
+ : gt("Picture in picture")
165
+ }
166
+ onPress={() => streamRef.current?.togglePictureInPicture()}
167
+ />
168
+ ) : null}
169
+ {tabs.length > 1 ? (
170
+ <Menu
171
+ accessible
172
+ accessibilityLabel={gt("Tabs", { $context: "browser tabs menu" })}
173
+ accessibilityRole="button"
174
+ actions={tabs.map((entry) => ({
175
id: entry.tabId,
176
title: browserTabTitle(entry, resolveMessage),
177
subtitle: browserTabUrl(entry),
161
- selected: entry.tabId === tabId,
162
- onPress: () => selectTab(entry.tabId),
163
- })),
164
- },
165
- ]
166
- : []
167
- }
168
- />
169
- {tab ? (
170
- <>
171
- <BrowserAddressBar
172
- key={`address:${tab.tabId}`}
173
- environmentId={environmentId}
174
- tab={tab}
175
- streaming={streaming}
176
- ready={streaming && canControl}
177
- onCommand={(input) => streamRef.current?.command(input)}
178
- onPaste={() => streamRef.current?.paste()}
179
- />
180
- {live ? (
181
- <PreviewStreamWebView
182
- key={`stream:${tab.tabId}`}
183
- environmentId={environmentId}
184
- threadId={threadId}
185
- tabId={tab.tabId}
186
- pdfUri={pdfUri}
187
- ref={streamRef}
188
- interactive
189
- background={themeVariables["--color-sheet-solid"]}
190
- onPictureInPicture={onPictureInPicture}
191
- onStreamingChange={setStreaming}
192
- onControl={(control) => setCanControl(control?.controller === "you")}
193
- />
178
+ state: entry.tabId === tabId ? "on" : "off",
179
+ }))}
180
+ onPressAction={({ nativeEvent }) => selectTab(nativeEvent.event)}
181
+ >
182
+ <ControlPill
183
+ icon="square.on.square"
184
+ accessibilityLabel={gt("Tabs", { $context: "browser tabs menu" })}
185
+ />
186
+ </Menu>
187
+ ) : null}
188
+ {tab ? (
189
+ <BrowserTabMenu
190
+ environmentId={environmentId}
191
+ tab={tab}
192
+ streaming={streaming}
193
+ onPaste={ready ? () => streamRef.current?.paste() : undefined}
194
+ onReleaseControl={ready ? () => command({ type: "releaseControl" }) : undefined}
195
+ />
196
+ ) : null}
197
+ </>
198
+ ),
199
+ }}
200
+ >
201
+ {({ onScrollDirection }) =>
202
+ tab ? (
203
+ live ? (
204
+ <PreviewStreamWebView
205
+ key={`stream:${tab.tabId}`}
206
+ environmentId={environmentId}
207
+ threadId={threadId}
208
+ tabId={tab.tabId}
209
+ pdfUri={pdfUri}
210
+ ref={streamRef}
211
+ interactive
212
+ background={themeVariables["--color-sheet-solid"]}
213
+ onPictureInPicture={onPictureInPicture}
214
+ onStreamingChange={setStreaming}
215
+ onScrollDirection={onScrollDirection}
216
+ onControl={(control) => setCanControl(control?.controller === "you")}
217
+ />
218
+ ) : (
219
+ <View className="flex-1" />
220
+ )
221
) : (
195
- <View className="flex-1" />
196
- )}
197
- </>
198
- ) : (
199
- <View className="flex-1 items-center justify-center">
200
- {focused && foreground ? (
201
- <AppActivityIndicator color={themeVariables["--color-icon"]} />
202
- ) : null}
203
- </View>
204
- )}
205
- </View>
222
+ <View className="flex-1 items-center justify-center">
223
+ {focused && foreground ? (
224
+ <AppActivityIndicator color={themeVariables["--color-icon"]} />
225
+ ) : null}
226
+ </View>
227
+ )
228
+ }
229
+ </BrowserChrome>
230
+ </SafeAreaView>
231
);
232
}
233
209
-function BrowserAddressBar({
210
- environmentId,
211
- tab,
212
- ready,
213
- streaming,
214
- onCommand,
215
- onPaste,
216
-}: {
217
- readonly environmentId: EnvironmentId;
218
- readonly tab: PreviewSessionSnapshot;
219
- readonly ready: boolean;
220
- readonly streaming: boolean;
221
- readonly onCommand: PreviewStreamRef["command"];
222
- readonly onPaste: () => void;
223
-}) {
224
- const url = browserTabUrl(tab);
225
- const gt = useGT();
226
- const [draft, setDraft] = useState<string | null>(null);
227
- const submit = () => {
228
- const value = draft ?? url;
229
- setDraft(null);
230
- try {
231
- onCommand({ type: "navigate", url: normalizePreviewUrl(value) });
232
- } catch {
233
- Dialog.alert(m(msg("Could not open this address")), m(msg("Enter an http or https URL.")));
234
- }
235
- };
236
- return (
237
- <View className="flex-row items-center gap-1 px-2 pb-2">
238
- <ControlPill
239
- icon="chevron.left"
240
- accessibilityLabel={gt("Back", { $context: "browser history" })}
241
- disabled={!ready || !tab.canGoBack}
242
- onPress={() => onCommand({ type: "history", delta: -1 })}
243
- />
244
- <ControlPill
245
- icon="chevron.right"
246
- accessibilityLabel={gt("Forward", { $context: "browser history" })}
247
- disabled={!ready || !tab.canGoForward}
248
- onPress={() => onCommand({ type: "history", delta: 1 })}
249
- />
250
- <TextInput
251
- accessibilityLabel={gt("Address", { $context: "browser address bar" })}
252
- editable={ready}
253
- value={draft ?? url}
254
- onChangeText={setDraft}
255
- onBlur={() => setDraft(null)}
256
- onSubmitEditing={submit}
257
- placeholder={gt("Enter a URL")}
258
- placeholderTextColorClassName="accent-placeholder"
259
- autoCapitalize="none"
260
- autoCorrect={false}
261
- keyboardType="url"
262
- returnKeyType="go"
263
- selectTextOnFocus
264
- lineBreakModeIOS="tail"
265
- className="h-10 min-w-0 flex-1 rounded-full border border-input-border bg-input px-4 font-sans text-sm text-foreground"
266
- />
267
- <ControlPill
268
- icon="arrow.clockwise"
269
- accessibilityLabel={gt("Reload page")}
270
- disabled={!ready}
271
- onPress={() => onCommand({ type: "reload" })}
272
- />
273
- <BrowserTabMenu
274
- environmentId={environmentId}
275
- tab={tab}
276
- streaming={streaming}
277
- onPaste={ready ? onPaste : undefined}
278
- />
279
- </View>
280
- );
234
+function normalizedOrNull(value: string): string | null {
235
+ try {
236
+ return normalizePreviewUrl(value);
237
+ } catch {
238
+ return null;
239
+ }
240
}
apps/mobile/src/features/browser/BrowserTabMenu.tsx
+19
-1
@@ -18,6 +18,8 @@ import { Menu } from "../../components/ui/Menu";
18
import { m } from "../../i18n/messages";
19
import { previewEnvironment } from "../../state/preview";
20
import { useAtomCommand } from "../../state/use-atom-command";
21
+import { browserTabUrl, loopbackUrlForDevice } from "./browserTabs";
22
+import { useOpenLocalPreview } from "./useOpenLocalPreview";
23
24
const APPEARANCES = [
25
{
@@ -54,12 +56,15 @@ export function BrowserTabMenu({
56
tab,
57
streaming,
58
onPaste,
59
+ onReleaseControl,
60
}: {
61
readonly environmentId: EnvironmentId;
62
readonly tab: PreviewSessionSnapshot;
63
readonly streaming: boolean;
64
readonly onPaste?: () => void;
65
+ readonly onReleaseControl?: () => void;
66
}) {
67
+ const openLocalPreview = useOpenLocalPreview();
68
const adjust = useAtomCommand(previewEnvironment.adjust, "browser tab change");
69
const resize = useAtomCommand(previewEnvironment.resize, "browser viewport change");
70
const close = useAtomCommand(previewEnvironment.close, "browser tab close");
@@ -87,10 +92,19 @@ export function BrowserTabMenu({
92
image: "xmark",
93
attributes: { destructive: true, disabled: !canClose },
94
};
95
+ const deviceUrl = loopbackUrlForDevice(browserTabUrl(tab));
96
+ // The device preview has its own webview and tunnel, so it doesn't wait for the stream.
97
+ const openOnDevice: MenuAction[] = deviceUrl
98
+ ? [{ id: "open-on-device", title: gt("Open on this device"), image: "iphone" }]
99
+ : [];
100
const actions: MenuAction[] = [
101
+ ...openOnDevice,
102
...(onPaste
103
? [{ id: "paste", title: gt("Paste", { $context: "verb" }), image: "doc.on.clipboard" }]
104
: []),
105
+ ...(onReleaseControl
106
+ ? [{ id: "release-control", title: gt("Release control"), image: "hand.raised" }]
107
+ : []),
108
{ id: "hard-reload", title: gt("Hard reload"), image: "arrow.clockwise.circle" },
109
{
110
id: "appearance",
@@ -146,7 +160,11 @@ export function BrowserTabMenu({
160
});
161
return;
162
}
163
+ if (id === "open-on-device" && deviceUrl) {
164
+ return openLocalPreview({ environmentId, threadId: tab.threadId }, deviceUrl);
165
+ }
166
if (id === "paste") return onPaste?.();
167
+ if (id === "release-control") return onReleaseControl?.();
168
if (id === "hard-reload") return void run({ hardReload: true });
169
if (id === "zoom:in") return void run({ zoomFactor: zoomTo(1) });
170
if (id === "zoom:out") return void run({ zoomFactor: zoomTo(-1) });
@@ -177,7 +195,7 @@ export function BrowserTabMenu({
195
accessible
196
accessibilityLabel={gt("Browser tab options")}
197
accessibilityRole="button"
180
- actions={streaming ? actions : [closeAction]}
198
+ actions={streaming ? actions : [...openOnDevice, closeAction]}
199
onPressAction={({ nativeEvent }) => onAction(nativeEvent.event)}
200
>
201
<ControlPill icon="ellipsis" accessibilityLabel={gt("Browser tab options")} />
apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx
new
+217
@@ -0,0 +1,217 @@
1
+import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
+import { normalizePreviewUrl } from "@t3tools/shared/preview";
4
+import { msg, useGT } from "gt-react-native";
5
+import { useRef, useState } from "react";
6
+import { View } from "react-native";
7
+import { SafeAreaView } from "react-native-safe-area-context";
8
+
9
+import { AppText } from "../../components/ui/AppText";
10
+import * as Dialog from "../../components/ui/Dialog";
11
+import { EmptyState } from "../../components/ui/EmptyState";
12
+import { m } from "../../i18n/messages";
13
+import { useEnvironments } from "../../state/environments";
14
+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
15
+import { BrowserChrome } from "./BrowserBar";
16
+import { loopbackUrlForDevice } from "./browserTabs";
17
+import { TunnelWebView, type TunnelNavigation, type TunnelWebViewRef } from "./TunnelWebView";
18
+
19
+type LocalPreviewRouteScreenProps = StaticScreenProps<{
20
+ readonly environmentId: string;
21
+ readonly url: string;
22
+}>;
23
+
24
+export function LocalPreviewRouteScreen({ route }: LocalPreviewRouteScreenProps) {
25
+ const navigation = useNavigation();
26
+ return (
27
+ <LocalPreviewScreen
28
+ environmentId={EnvironmentId.make(route.params.environmentId)}
29
+ url={route.params.url}
30
+ onClose={() => navigation.goBack()}
31
+ />
32
+ );
33
+}
34
+
35
+/**
36
+ * Another environment's localhost page rendered by this device's own webview, full screen or, with
37
+ * `onMaximize`, in the inspector pane.
38
+ */
39
+export function LocalPreviewScreen(props: {
40
+ readonly environmentId: EnvironmentId;
41
+ readonly url: string;
42
+ readonly onClose: () => void;
43
+ readonly onMaximize?: (url: string) => void;
44
+}) {
45
+ const { environmentId, onMaximize } = props;
46
+ const gt = useGT();
47
+ const initialUrl = forDevice(props.url);
48
+ const environmentLabel =
49
+ useEnvironments().presentationById.get(environmentId)?.entry.target.label ??
50
+ gt("the environment", { $context: "stands in for an environment name in a sentence" });
51
+ const { themeVariables } = useAppearancePreferences();
52
+ const webView = useRef<TunnelWebViewRef>(null);
53
+ const [requested, setRequested] = useState(initialUrl);
54
+ const [page, setPage] = useState<TunnelNavigation | null>(null);
55
+ const [failed, setFailed] = useState(false);
56
+ const [disconnected, setDisconnected] = useState(false);
57
+ const [debug, setDebug] = useState<string | undefined>(undefined);
58
+ const [unsupported, setUnsupported] = useState<string | null>(null);
59
+ // After a failed load the webview reports no URL, so the address stays on the one asked for.
60
+ const current = (!failed && page?.url) || requested;
61
+
62
+ const open = (value: string) => {
63
+ const normalized = normalizedOrNull(value);
64
+ const next = normalized === null ? null : forDevice(normalized);
65
+ if (next === null) {
66
+ Dialog.alert(m(msg("Could not open this address")), m(msg("Enter an http or https URL.")));
67
+ return;
68
+ }
69
+ setFailed(false);
70
+ setRequested(next);
71
+ void webView.current?.loadUrl(next);
72
+ };
73
+ const retry = () => {
74
+ setFailed(false);
75
+ void webView.current?.reload();
76
+ };
77
+ const back = () => void webView.current?.goBack();
78
+ const canGoBack = page?.canGoBack ?? false;
79
+ const pageColor = failed || unsupported !== null ? null : page?.pageColor || null;
80
+
81
+ return (
82
+ // Full screen spans the Duo's rail, so it insets its own sides; the pane is inset already.
83
+ <SafeAreaView
84
+ edges={onMaximize ? [] : ["left", "right"]}
85
+ style={{ flex: 1, backgroundColor: pageColor ?? themeVariables["--color-sheet-solid"] }}
86
+ >
87
+ <BrowserChrome
88
+ scrollsUnderBar
89
+ inPane={onMaximize !== undefined}
90
+ holdExpanded={failed}
91
+ bar={{
92
+ url: current,
93
+ editable: true,
94
+ canGoBack,
95
+ onClose: props.onClose,
96
+ onBack: back,
97
+ onReload: retry,
98
+ onSubmit: open,
99
+ onMaximize: onMaximize ? () => onMaximize(current) : undefined,
100
+ pageColor,
101
+ }}
102
+ >
103
+ {({ topInset, onScrollDirection }) => (
104
+ <>
105
+ <TunnelWebView
106
+ key={environmentId}
107
+ ref={webView}
108
+ className="flex-1"
109
+ environmentId={environmentId}
110
+ url={initialUrl}
111
+ topInset={topInset}
112
+ onNavigationChange={(next) => {
113
+ if (next.loading) setFailed(false);
114
+ setPage(next);
115
+ }}
116
+ onScrollDirection={onScrollDirection}
117
+ onAccess={(available) => setDisconnected(!available)}
118
+ onLoadError={(failure) => {
119
+ if (failure.unsupported) return setUnsupported(failure.description);
120
+ // A link to another port fails with that port's address, not the one typed earlier.
121
+ if (failure.url) setRequested(failure.url);
122
+ setDebug(failure.debug);
123
+ // Android reports no cause, so a refused tunnel request stands in for it there.
124
+ if (failure.cause) setDisconnected(failure.cause === "environment");
125
+ setFailed(true);
126
+ }}
127
+ />
128
+ {unsupported !== null ? (
129
+ <View
130
+ className="absolute inset-0 items-center justify-center"
131
+ style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
132
+ >
133
+ <View className="w-full max-w-md">
134
+ <EmptyState
135
+ variant="plain"
136
+ title={gt("This device can't open localhost pages")}
137
+ detail={gt("{reason} You can still use the streamed browser for this tab.", {
138
+ reason: unsupported,
139
+ })}
140
+ />
141
+ </View>
142
+ </View>
143
+ ) : failed ? (
144
+ // Opaque, so the webview's own error page never shows through the sheet color.
145
+ <View
146
+ className="absolute inset-0 items-center justify-center"
147
+ style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
148
+ >
149
+ <View className="w-full max-w-md">
150
+ <EmptyState
151
+ variant="plain"
152
+ title={
153
+ disconnected
154
+ ? gt("Not connected to {environment}", { environment: environmentLabel })
155
+ : gt("Can't reach {host}", { host: hostOf(current) })
156
+ }
157
+ detail={
158
+ disconnected
159
+ ? gt(
160
+ "Pages on {environment}’s localhost load through its connection. Try again once it reconnects.",
161
+ { environment: environmentLabel },
162
+ )
163
+ : gt(
164
+ "Nothing is listening on port {port} on {environment}. Start the server there, then try again.",
165
+ { port: portOf(current), environment: environmentLabel },
166
+ )
167
+ }
168
+ actionLabel={gt("Try again")}
169
+ onAction={retry}
170
+ />
171
+ {debug ? (
172
+ <AppText
173
+ selectable
174
+ className="px-6 text-center font-mono text-xs text-foreground-muted"
175
+ >
176
+ {debug}
177
+ </AppText>
178
+ ) : null}
179
+ </View>
180
+ </View>
181
+ ) : null}
182
+ </>
183
+ )}
184
+ </BrowserChrome>
185
+ </SafeAreaView>
186
+ );
187
+}
188
+
189
+function portOf(value: string): string {
190
+ try {
191
+ const url = new URL(value);
192
+ return url.port || (url.protocol === "https:" ? "443" : "80");
193
+ } catch {
194
+ return "?";
195
+ }
196
+}
197
+
198
+function hostOf(value: string): string {
199
+ try {
200
+ return new URL(value).host;
201
+ } catch {
202
+ return value;
203
+ }
204
+}
205
+
206
+// The unspecified address would name the phone itself, so it becomes the environment's localhost.
207
+function forDevice(url: string): string {
208
+ return loopbackUrlForDevice(url) ?? url;
209
+}
210
+
211
+function normalizedOrNull(value: string): string | null {
212
+ try {
213
+ return normalizePreviewUrl(value);
214
+ } catch {
215
+ return null;
216
+ }
217
+}
apps/mobile/src/features/browser/PreviewStreamWebView.tsx
+10
-5
@@ -57,6 +57,8 @@ type NativeStreamBridge = {
57
readonly onRefused: (delayMs: number) => void;
58
readonly onGone?: () => void;
59
readonly onViewport?: (viewport: { readonly width: number; readonly height: number }) => void;
60
+ /** The direction a drag scrolls the page, every few dozen pixels of it. */
61
+ readonly onScrollDirection?: (direction: "up" | "down") => void;
62
readonly onControl?: (control: PreviewStreamControl | null) => void;
63
readonly onPictureInPicture?: (state: PreviewPictureInPictureState, detail?: string) => void;
64
/** True while frames show, so commands reach the page. */
@@ -230,6 +232,7 @@ function PreviewStreamDocumentView({
232
onUnauthorized,
233
onGone,
234
onViewport,
235
+ onScrollDirection,
236
onControl,
237
onPictureInPicture,
238
onStreamingChange,
@@ -340,19 +343,18 @@ function PreviewStreamDocumentView({
343
};
344
return (
345
<View className="flex-1" style={{ backgroundColor: background }}>
343
- {!compact ? (
346
+ {/* With control, the bar's menu offers releasing it, so the row would only take space. */}
347
+ {!compact && control?.controller !== "you" ? (
348
<View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
349
<AppText className="text-xs text-foreground-muted">
350
{previewStreamControlLabel(control, messages)}
351
</AppText>
352
{control?.canOperate ? (
353
<Button
350
- label={control.controller === "you" ? gt("Release control") : gt("Take control")}
354
+ label={gt("Take control")}
355
tone="secondary"
356
disabled={control.controller === "another-viewer"}
353
- onPress={() =>
354
- command({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
355
- }
357
+ onPress={() => command({ type: "takeControl" })}
358
/>
359
) : null}
360
</View>
@@ -411,6 +413,9 @@ function PreviewStreamDocumentView({
413
case "viewport":
414
onViewport?.(message);
415
return;
416
+ case "scroll":
417
+ onScrollDirection?.(message.direction);
418
+ return;
419
case "clipboard":
420
void Clipboard.setStringAsync(message.text).catch(() => undefined);
421
return;
apps/mobile/src/features/browser/TunnelWebView.tsx
new
+133
@@ -0,0 +1,133 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import { requireNativeModule, requireNativeView } from "expo";
3
+import { useRef, type Ref } from "react";
4
+import {
5
+ Platform,
6
+ StyleSheet,
7
+ View,
8
+ type NativeSyntheticEvent,
9
+ type ViewProps,
10
+} from "react-native";
11
+
12
+import { readPreviewTunnelUrl } from "../../state/previewTunnel";
13
+
14
+export interface TunnelNavigation {
15
+ readonly url: string;
16
+ readonly title: string;
17
+ readonly loading: boolean;
18
+ readonly canGoBack: boolean;
19
+ readonly canGoForward: boolean;
20
+ /** iOS only: the page's theme-color, else its background, as #rrggbb; empty when unknown. */
21
+ readonly pageColor?: string;
22
+}
23
+
24
+export interface TunnelWebViewRef {
25
+ readonly loadUrl: (url: string) => Promise<void>;
26
+ readonly goBack: () => Promise<void>;
27
+ readonly goForward: () => Promise<void>;
28
+ readonly reload: () => Promise<void>;
29
+}
30
+
31
+const PreviewTunnel = requireNativeModule<{
32
+ resolveAccess(requestId: string, url: string | null): void;
33
+}>("T3PreviewTunnel");
34
+
35
+const NativeTunnelWebView = requireNativeView<
36
+ ViewProps & {
37
+ readonly ref?: Ref<TunnelWebViewRef>;
38
+ readonly environmentId: string;
39
+ readonly url: string;
40
+ readonly topInset?: number;
41
+ readonly onAccessRequest: (event: NativeSyntheticEvent<{ requestId: string }>) => void;
42
+ readonly onNavigationChange: (event: NativeSyntheticEvent<TunnelNavigation>) => void;
43
+ readonly onLoadError: (
44
+ event: NativeSyntheticEvent<{
45
+ code: number;
46
+ description: string;
47
+ url: string;
48
+ debug?: string;
49
+ cause?: string;
50
+ }>,
51
+ ) => void;
52
+ readonly onPageScroll: (event: NativeSyntheticEvent<{ y: number }>) => void;
53
+ }
54
+>("T3PreviewTunnel");
55
+
56
+/** A native webview whose localhost is the environment's loopback, reached through its tunnel. */
57
+export function TunnelWebView({
58
+ environmentId,
59
+ url,
60
+ ref,
61
+ onNavigationChange,
62
+ onLoadError,
63
+ onScrollDirection,
64
+ onAccess,
65
+ topInset,
66
+ ...props
67
+}: ViewProps & {
68
+ readonly environmentId: EnvironmentId;
69
+ readonly url: string;
70
+ readonly ref?: Ref<TunnelWebViewRef>;
71
+ readonly onNavigationChange: (navigation: TunnelNavigation) => void;
72
+ /**
73
+ * `url` is the address that failed, or empty when the platform does not report it.
74
+ * `unsupported` means this device's webview cannot route localhost at all.
75
+ */
76
+ readonly onLoadError: (failure: {
77
+ readonly url: string;
78
+ readonly unsupported: boolean;
79
+ readonly description: string;
80
+ /** What the native proxy saw, shown with the error so a report carries it. iOS only. */
81
+ readonly debug?: string;
82
+ /**
83
+ * iOS only: whether the environment itself was out of reach (`environment`) or answered that
84
+ * nothing listens on the port (`port`).
85
+ */
86
+ readonly cause?: "environment" | "port";
87
+ }) => void;
88
+ /** Whether the last connection could get into the environment's tunnel at all. */
89
+ readonly onAccess?: (available: boolean) => void;
90
+ /** iOS only: room at the top the page scrolls under, for a bar laid over it. */
91
+ readonly topInset?: number;
92
+ /** Reported every few dozen points the page scrolls; "up" also at the top. */
93
+ readonly onScrollDirection?: (direction: "up" | "down") => void;
94
+}) {
95
+ const scrollY = useRef(0);
96
+ // Styling goes on a plain View: a native view from `requireNativeView` ignores className.
97
+ return (
98
+ <View {...props}>
99
+ <NativeTunnelWebView
100
+ style={StyleSheet.absoluteFill}
101
+ ref={ref}
102
+ environmentId={environmentId}
103
+ url={url}
104
+ {...(Platform.OS === "ios" ? { topInset: topInset ?? 0 } : {})}
105
+ onAccessRequest={({ nativeEvent }) => {
106
+ void readPreviewTunnelUrl(environmentId).then((tunnelUrl) => {
107
+ onAccess?.(tunnelUrl !== null);
108
+ PreviewTunnel.resolveAccess(nativeEvent.requestId, tunnelUrl);
109
+ });
110
+ }}
111
+ onNavigationChange={({ nativeEvent }) => onNavigationChange(nativeEvent)}
112
+ onPageScroll={({ nativeEvent }) => {
113
+ const down = nativeEvent.y > 0 && nativeEvent.y > scrollY.current;
114
+ scrollY.current = nativeEvent.y;
115
+ onScrollDirection?.(down ? "down" : "up");
116
+ }}
117
+ onLoadError={({ nativeEvent }) =>
118
+ onLoadError({
119
+ url: nativeEvent.url,
120
+ // The view reports a setup failure with no URL and code -1, before any page loads.
121
+ unsupported: nativeEvent.code === -1 && nativeEvent.url === "",
122
+ description: nativeEvent.description,
123
+ debug: nativeEvent.debug,
124
+ cause:
125
+ nativeEvent.cause === "environment" || nativeEvent.cause === "port"
126
+ ? nativeEvent.cause
127
+ : undefined,
128
+ })
129
+ }
130
+ />
131
+ </View>
132
+ );
133
+}
apps/mobile/src/features/browser/browserTabs.test.ts
new
+20
@@ -0,0 +1,20 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { loopbackUrlForDevice } from "./browserTabs";
4
+
5
+describe("loopbackUrlForDevice", () => {
6
+ it("opens only the environment's loopback pages on this device", () => {
7
+ expect(loopbackUrlForDevice("http://localhost:5173/app?x=1")).toBe(
8
+ "http://localhost:5173/app?x=1",
9
+ );
10
+ expect(loopbackUrlForDevice("http://127.0.0.1:3000/")).toBe("http://127.0.0.1:3000/");
11
+ expect(loopbackUrlForDevice("http://[::1]:3000/")).toBe("http://[::1]:3000/");
12
+ // The unspecified address would name the phone's own interfaces.
13
+ expect(loopbackUrlForDevice("http://0.0.0.0:3000/")).toBe("http://localhost:3000/");
14
+ expect(loopbackUrlForDevice("http://[::]:3000/")).toBe("http://localhost:3000/");
15
+ expect(loopbackUrlForDevice("https://example.com/")).toBeNull();
16
+ expect(loopbackUrlForDevice("http://192.168.1.5:3000/")).toBeNull();
17
+ expect(loopbackUrlForDevice("file:///tmp/a.html")).toBeNull();
18
+ expect(loopbackUrlForDevice("")).toBeNull();
19
+ });
20
+});
apps/mobile/src/features/browser/browserTabs.ts
+15
@@ -1,4 +1,5 @@
1
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
2
+import { isLoopbackHost } from "@t3tools/shared/preview";
3
import { msg } from "gt-react-native";
4
5
import { m, type MessageResolver } from "../../i18n/messages";
@@ -23,3 +24,17 @@ export function browserTabTitle(tab: PreviewSessionSnapshot, resolve: MessageRes
24
return tab.navStatus.url;
25
}
26
}
27
+
28
+/** The tab's URL for this device's tunnelled webview, when it is one of the environment's loopback pages. */
29
+export function loopbackUrlForDevice(value: string): string | null {
30
+ try {
31
+ const url = new URL(value);
32
+ if (!/^https?:$/.test(url.protocol)) return null;
33
+ // The unspecified address would name this device's own interfaces, so use localhost instead.
34
+ if (url.hostname === "0.0.0.0" || url.hostname === "[::]") url.hostname = "localhost";
35
+ if (!isLoopbackHost(url.hostname)) return null;
36
+ return url.toString();
37
+ } catch {
38
+ return null;
39
+ }
40
+}
apps/mobile/src/features/browser/preview-stream-document.ts
+2
@@ -32,6 +32,8 @@ export type PreviewStreamMessage =
32
| { readonly type: "gone" }
33
| ({ readonly type: "hostSetup" } & PreviewStreamHostSetup)
34
| { readonly type: "viewport"; readonly width: number; readonly height: number }
35
+ /** The direction a drag scrolls the page, sent every few dozen pixels of it. */
36
+ | { readonly type: "scroll"; readonly direction: "up" | "down" }
37
| { readonly type: "clipboard"; readonly text: string }
38
| ({ readonly type: "download" } & PreviewStreamDownload)
39
| { readonly type: "fileChooser"; readonly chooser: PreviewStreamFileChooser | null }
apps/mobile/src/features/browser/preview-stream.browser.ts
+10
-1
@@ -32,6 +32,7 @@ const TAP_SLOP_PX = 8;
32
const MULTI_CLICK_MS = 500;
33
const MULTI_CLICK_SLOP_PX = 4;
34
const WHEEL_LINE_PX = 16;
35
+const SCROLL_REPORT_PX = 24;
36
const MAX_PIXEL_RATIO = 2;
37
// Reuse nearby probe answers: slow replies arrive too late after touch-end to raise the iOS keyboard.
38
const PROBE_REUSE_PX = 24;
@@ -307,12 +308,20 @@ export function start(configuration: PreviewStreamConfiguration) {
308
};
309
};
310
311
+ let scrolled = 0;
312
const flushWheel = () => {
313
if (wheelFrame !== null) cancelAnimationFrame(wheelFrame);
314
wheelFrame = null;
315
const wheel = pendingWheel;
316
pendingWheel = null;
315
- if (wheel) send(wheel);
317
+ if (!wheel) return;
318
+ send(wheel);
319
+ // The app shrinks its bar while the page scrolls down, so it only needs the direction.
320
+ scrolled =
321
+ Math.sign(scrolled) === Math.sign(wheel.deltaY) ? scrolled + wheel.deltaY : wheel.deltaY;
322
+ if (Math.abs(scrolled) < SCROLL_REPORT_PX) return;
323
+ post({ type: "scroll", direction: scrolled > 0 ? "down" : "up" });
324
+ scrolled = 0;
325
};
326
const queueWheel = (point: { x: number; y: number }, deltaX: number, deltaY: number) => {
327
pendingWheel = {
apps/mobile/src/features/browser/useOpenLocalPreview.ts
new
+13
@@ -0,0 +1,13 @@
1
+import { useNavigation } from "@react-navigation/native";
2
+
3
+import { useOpenThreadInspector } from "../threads/thread-inspector-navigation";
4
+
5
+/** Opens an environment's localhost page on this device: in the inspector pane where there is one. */
6
+export function useOpenLocalPreview() {
7
+ const navigation = useNavigation();
8
+ const openInspector = useOpenThreadInspector();
9
+ return (source: { readonly environmentId: string; readonly threadId: string }, url: string) => {
10
+ if (openInspector(source, { type: "localPreview", ...source, url })) return;
11
+ navigation.navigate("ThreadLocalPreview", { environmentId: source.environmentId, url });
12
+ };
13
+}
apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
+1
-2
@@ -13,7 +13,7 @@ import { msg, T, useGT } from "gt-react-native";
13
import { useEffect, useRef, useState, type RefObject } from "react";
14
import * as Haptics from "expo-haptics";
15
import { Accelerometer } from "expo-sensors";
16
-import { Pressable, StatusBar, View } from "react-native";
16
+import { Pressable, View } from "react-native";
17
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
18
import { useSafeAreaInsets } from "react-native-safe-area-context";
19
@@ -271,7 +271,6 @@ export function DevicePreviewScreen({
271
];
272
return (
273
<View className="flex-1" style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}>
274
- {!embedded ? <StatusBar hidden animated /> : null}
274
{embedded ? (
275
<>
276
<AppBar
apps/mobile/src/features/layout/route-options.ts
+14
-2
@@ -146,13 +146,25 @@ export function modalRoute(options: ModalRouteOptions = {}): AppScreenOptions {
146
}
147
148
/** Full-screen media (a device stream, a browser, an app) with no bar and no dismiss gesture. */
149
-export function immersiveRoute(options: { readonly hideSystemBars?: boolean } = {}) {
149
+export function immersiveRoute(
150
+ options: {
151
+ readonly hideSystemBars?: boolean;
152
+ /**
153
+ * Like Safari, the Duo puts its status in a top bar instead of a vertical rail, so the page
154
+ * spans the full width. Where the rail stays, the screen spans it and insets its content.
155
+ */
156
+ readonly fullWidth?: boolean;
157
+ } = {},
158
+) {
159
return {
160
presentation: "fullScreenModal",
161
headerShown: false,
162
gestureEnabled: false,
163
+ ...(options.fullWidth
164
+ ? { sheetPrefersHorizontalBars: true, nativeContentInsetHorizontally: false }
165
+ : undefined),
166
...(options.hideSystemBars
155
- ? { autoHideHomeIndicator: true, navigationBarHidden: true }
167
+ ? { autoHideHomeIndicator: true, navigationBarHidden: true, statusBarHidden: true }
168
: undefined),
169
} satisfies AppScreenOptions;
170
}
apps/mobile/src/features/pull-requests/usePullRequestEnvironmentFallback.test.tsx
+8
-1
@@ -15,7 +15,14 @@ const mocks = vi.hoisted(() => ({
15
navigation: { setParams: vi.fn<(params: Partial<PullRequestEnvironmentTarget>) => void>() },
16
}));
17
18
-vi.mock("@react-navigation/native", () => ({ useNavigation: () => mocks.navigation }));
18
+vi.mock("@react-navigation/native", async () => {
19
+ const { useEffect } = await import("react");
20
+ return {
21
+ useNavigation: () => mocks.navigation,
22
+ // The screen under test is focused, so its focus effect runs like an effect.
23
+ useFocusEffect: (effect: () => void) => useEffect(effect, [effect]),
24
+ };
25
+});
26
vi.mock("../../state/entities", () => ({ useProjects: () => mocks.projects }));
27
vi.mock("../../state/workspace", () => ({
28
useWorkspaceEnvironments: () => mocks.environments,
apps/mobile/src/features/pull-requests/usePullRequestEnvironmentFallback.ts
+8
-6
@@ -1,5 +1,5 @@
1
-import { useNavigation } from "@react-navigation/native";
2
-import { useEffect } from "react";
1
+import { useFocusEffect, useNavigation } from "@react-navigation/native";
2
+import { useCallback } from "react";
3
4
import { useProjects } from "../../state/entities";
5
import { useConnectionsReady, useWorkspaceEnvironments } from "../../state/workspace";
@@ -14,8 +14,10 @@ export function usePullRequestEnvironmentFallback(params: PullRequestEnvironment
14
const isReady = useConnectionsReady();
15
const environments = useWorkspaceEnvironments();
16
const fallback = isReady ? pullRequestFallbackEnvironment(params, projects, environments) : null;
17
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rewrites the route params through the navigator to the fallback environment once connections are ready
18
- useEffect(() => {
19
- if (fallback) navigation.setParams(fallback);
20
- }, [fallback, navigation]);
17
+ // Only while focused: a screen kept as a placeholder throws on any navigation action.
18
+ useFocusEffect(
19
+ useCallback(() => {
20
+ if (fallback) navigation.setParams(fallback);
21
+ }, [fallback, navigation]),
22
+ );
23
}
apps/mobile/src/features/threads/ThreadFeed.tsx
+33
@@ -328,6 +328,8 @@ import {
328
} from "./ThreadMarkdownImage";
329
import { ZoomableImagePressable } from "./ZoomableImagePressable";
330
import { openSettings } from "../settings/settings-navigation";
331
+import { loopbackUrlForDevice } from "../browser/browserTabs";
332
+import { useOpenLocalPreview } from "../browser/useOpenLocalPreview";
333
import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
334
import { useMessageTimeFormatter } from "./useMessageTimeFormatter";
335
@@ -3125,6 +3127,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3127
const openPullRequest = useOpenPullRequest();
3128
const navigation = useNavigation();
3129
const openLinkedThread = useOpenLinkedThread();
3130
+ const openLocalPreview = useOpenLocalPreview();
3131
// Recycling a row disposes its native audio player, so a started clip's row stays rendered.
3132
const [retainedMediaRowId, setRetainedMediaRowId] = useState<string | null>(null);
3133
const focused = useIsFocused();
@@ -3406,6 +3409,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3409
if (instructionsPath) openSkillInstructions(instructionsPath);
3410
return;
3411
}
3412
+ // Safari would open the phone's own localhost, so these open on the device by default.
3413
+ const deviceUrl = loopbackUrlForDevice(href);
3414
+ if (deviceUrl) {
3415
+ openLocalPreview(
3416
+ { environmentId: String(props.environmentId), threadId: String(props.threadId) },
3417
+ deviceUrl,
3418
+ );
3419
+ return;
3420
+ }
3421
if (parseThreadLinkHref(href)) {
3422
const target = resolveLinkedThread(href);
3423
if (target) {
@@ -3535,6 +3547,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3547
],
3548
};
3549
}
3550
+ // The environment's localhost, which this device can only reach through the tunnel.
3551
+ if (loopbackUrlForDevice(href)) {
3552
+ return {
3553
+ title: href,
3554
+ actions: [
3555
+ { id: "open-on-device", title: gt("Open on this device") },
3556
+ { id: "copy-link", title: gt("Copy link") },
3557
+ ],
3558
+ };
3559
+ }
3560
const target = resolveFileChipTarget(href, props.workspaceRoot);
3561
return target ? fileChipMenu(target) : undefined;
3562
},
@@ -3552,6 +3574,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3574
else if (actionId === "copy-thread-link") copyTextWithHaptic(hostedThreadLink(thread));
3575
return;
3576
}
3577
+ const deviceUrl = loopbackUrlForDevice(href);
3578
+ if (deviceUrl) {
3579
+ if (actionId === "open-on-device") {
3580
+ markdownLinkRequest.current?.abort();
3581
+ openLocalPreview(
3582
+ { environmentId: String(props.environmentId), threadId: String(props.threadId) },
3583
+ deviceUrl,
3584
+ );
3585
+ } else if (actionId === "copy-link") copyTextWithHaptic(href);
3586
+ return;
3587
+ }
3588
const target = resolveFileChipTarget(href, props.workspaceRoot);
3589
if (!target) return;
3590
switch (actionId) {
apps/mobile/src/features/threads/thread-inspector-navigation.ts
+3
-1
@@ -7,10 +7,12 @@ import { useWorkspacePaneState } from "../layout/AdaptiveWorkspaceLayout";
7
export type ThreadInspectorMode = "route" | "git" | "files" | "preview";
8
9
export type ThreadInspectorTarget = {
10
- readonly type: "thread" | "device";
10
+ readonly type: "thread" | "device" | "localPreview";
11
readonly environmentId: string;
12
readonly threadId: string;
13
readonly deviceKey?: string;
14
+ /** The environment's localhost page a "localPreview" shows. */
15
+ readonly url?: string;
16
};
17
18
export const ThreadInspectorNavigationContext = createContext<
apps/mobile/src/features/threads/thread-inspector-preview.tsx
+16
-1
@@ -6,6 +6,7 @@ import { View } from "react-native";
6
7
import { AppBar } from "../../components/ui/AppBar";
8
import { SheetHeader } from "../../components/ui/SheetHeader";
9
+import { LocalPreviewScreen } from "../browser/LocalPreviewRouteScreen";
10
import { DevicePreviewScreen } from "../devices/DevicePreviewRouteScreen";
11
import {
12
WorkspaceContentWidthContext,
@@ -87,7 +88,21 @@ export function ThreadInspectorPreview(props: {
88
return (
89
<ThreadInspectorNavigationContext value={props.onOpen}>
90
<InspectorContentScope>
90
- {target.type === "device" ? (
91
+ {target.type === "localPreview" && target.url ? (
92
+ <LocalPreviewScreen
93
+ key={`${target.environmentId}:${target.url}`}
94
+ environmentId={EnvironmentId.make(target.environmentId)}
95
+ url={target.url}
96
+ onClose={props.onClose}
97
+ onMaximize={(url) => {
98
+ props.onOpen({ ...target, url });
99
+ navigation.navigate("ThreadLocalPreview", {
100
+ environmentId: target.environmentId,
101
+ url,
102
+ });
103
+ }}
104
+ />
105
+ ) : target.type === "device" ? (
106
<DevicePreviewScreen
107
key={`${target.environmentId}:${target.threadId}`}
108
environmentId={EnvironmentId.make(target.environmentId)}
apps/mobile/src/i18n/translations/de.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "Die eingereihte Nachricht konnte nicht gespeichert werden",
1591
"b02695b75d8b050d": "Deine Bearbeitung ist noch im Eingabefeld.",
1592
"6ad508d2af838010": "Sie wurde möglicherweise bereits gestartet. Deine Bearbeitung ist noch im Eingabefeld.",
1593
+ "2498db230c4b87b6": "Zu viel Kontext",
1594
"74e7e5c0536cda02": "Nebenchat nicht gestartet",
1595
"a0269861cbd8c727": "Eine Nebenfrage stellen",
1596
"d49fc7ca60395d59": "Gib die Frage nach {command} ein und sende sie dann.",
1596
- "2498db230c4b87b6": "Zu viel Kontext",
1597
+ "d6783ef5e11f3e89": "Nebenchat konnte nicht gestartet werden.",
1598
"ed68b68e83ee61bf": "Starte zuerst einen {provider}-Thread",
1599
"c9852e2500018a3c": "Sende eine Nachricht, bevor du Feedback gibst.",
1600
"7a4248cbd73fad20": "Die eingereihte Nachricht konnte nicht gespeichert werden.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "Keine archivierten Threads",
1705
"ef5fd3138f95f318": "Nicht alle Archive konnten geladen werden",
1706
"26a8e439cedbce61": "Archiv wird geladen...",
1707
+ "cfae08fc22229b42": "Browser schließen",
1708
+ "a430e4548d57d722": "Zurück",
1709
+ "e7b9fc04d44070b7": "Adresse",
1710
+ "a8608329f9192866": "URL eingeben",
1711
+ "270506908c58ebcc": "Seite neu laden",
1712
+ "f55a56936aed1cfa": "Seite maximieren",
1713
+ "a5d51502121f1630": "Adresse {url}. Browser-Steuerelemente anzeigen",
1714
"b5f8f4124236be7c": "Bild-in-Bild ist nicht verfügbar",
1715
"47c47bbab985e718": "Diese Adresse konnte nicht geöffnet werden",
1716
"f0287e8bebecf7c2": "Gib eine http- oder https-URL ein.",
1717
"536c1b1898a53eab": "Browser",
1710
- "cfae08fc22229b42": "Browser schließen",
1718
"e208bda0b201c91f": "Bild-in-Bild beenden",
1719
"d483a9b20b305301": "Bild-in-Bild",
1720
"9cf840ddbea731a5": "Tabs",
1714
- "a430e4548d57d722": "Zurück",
1715
- "22fbc48063de5b8e": "Vorwärts",
1716
- "e7b9fc04d44070b7": "Adresse",
1717
- "a8608329f9192866": "URL eingeben",
1718
- "270506908c58ebcc": "Seite neu laden",
1721
"14f99d0dac2d9681": "System",
1722
"a7e960938e75f747": "Hell",
1723
"a6b5d3e28216f795": "Dunkel",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "Dieser Browser-Tab konnte nicht geschlossen werden",
1730
"c91eae915827f9e3": "Der Viewport konnte nicht geändert werden",
1731
"62dc4d3a19ff7ca0": "Tab schließen",
1732
+ "1df5ebbe09388a03": "Auf diesem Gerät öffnen",
1733
"3fdf6cbbb9876fda": "Einfügen",
1734
+ "40269a025cb98db7": "Steuerung abgeben",
1735
"61fb04cd857a1a22": "Hart neu laden",
1736
"863f86bb80c0ea6a": "Zoom ({percent} %)",
1737
"8c32e9085e525c19": "Vergrößern",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Cookies löschen",
1743
"9bce41be8fc55a47": "Cache leeren",
1744
"4d7f5af0445371fd": "Optionen für Browser-Tab",
1745
+ "27025b00be488485": "die Umgebung",
1746
+ "e1ffd0532d64e52c": "Dieses Gerät kann keine localhost-Seiten öffnen",
1747
+ "f72cc72b321f93a5": "{reason} Für diesen Tab kannst du weiterhin den gestreamten Browser verwenden.",
1748
+ "663465f828e70345": "Keine Verbindung zu {environment}",
1749
+ "d14ca43d8ae95c78": "{host} nicht erreichbar",
1750
+ "69e9c247d0266e9f": "Seiten auf dem localhost von {environment} laden über dessen Verbindung. Versuche es erneut, sobald die Verbindung wieder steht.",
1751
+ "301045c720839f4d": "Auf {environment} lauscht nichts auf Port {port}. Starte dort den Server und versuche es dann erneut.",
1752
"0b16434dff468d30": "Der Upload wurde abgelehnt.",
1753
"bbcd3776bcd3e2c5": "{fileName} heruntergeladen",
1754
"f746b1e0bfb2ec4a": "Nicht jetzt",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "Die Seite wurde noch nicht angezeigt. Versuche es gleich noch einmal.",
1768
"eeb59a631fec128d": "Bild-in-Bild ist nicht verfügbar.",
1769
"a3640fd5194ade85": "Browser-Viewer wurde unerwartet beendet.",
1759
- "40269a025cb98db7": "Steuerung abgeben",
1770
"156baef53680396e": "Steuerung übernehmen",
1771
"95afdc33a06d3030": "Die Seite fordert Dateien an.",
1772
"69c659d8b6e271cc": "Die Seite fordert eine Datei an.",
@@ -2737,22 +2747,22 @@
2747
"06a684782801e8f7": "Head-Branch {branch} kopieren",
2748
"8e4f3c862193b8a5": "Bearbeiten",
2749
"8cc970597921c38a": "{branch} aus {repository} löschen? Lokale Branches und Worktrees bleiben unverändert.",
2740
- "42fd133c37a117fe": "{repository} · Offline",
2750
"58bda2aa88d28696": "{term, select, mr {Aktionen für Merge Request} cr {Aktionen für Änderungsanfrage} other {Aktionen für Pull Request}}",
2751
"ffd49822d34cbd30": "Änderungen durch Maintainer erlauben",
2752
"2a83c8767b3e1918": "Wird gelöscht…",
2753
"99a3c6e593d6947d": "Verbinde dich erneut, um diesen Branch zu löschen.",
2754
+ "42fd133c37a117fe": "{repository} · Offline",
2755
"c83fb5e64f34fb1a": "Übersicht",
2756
"8d1ad30ddb277f48": "Leitfaden",
2757
"3724ff240986c6da": "Änderungen committen",
2758
"d85877d9ef77c50c": "Änderungen",
2759
"ebb089d626dfaa7c": "Änderungen werden geladen",
2750
- "89a7eb448db48738": "{count, plural, one {{count} Test ausgeblendet} other {{count} Tests ausgeblendet}}",
2760
"4050f873dc790f8f": "Diff-Optionen",
2761
"81cf438219f0a618": "Zeilenumbruch",
2762
"8ec7e405049af1f7": "Entwurf in diese Zeile verschieben",
2763
"8e5f5001f74a460f": "Review-Kommentar hinzufügen",
2764
"8055c658cf61dd31": "Zeile kopieren",
2765
+ "89a7eb448db48738": "{count, plural, one {{count} Test ausgeblendet} other {{count} Tests ausgeblendet}}",
2766
"b4f58b68410c319f": "Änderungen neu laden",
2767
"01cb0224aa3208c1": "Diff nicht verfügbar",
2768
"b683d10f00d06824": "{term, select, mr {Öffne diesen Merge Request beim Anbieter, um die Änderungen zu sehen.} cr {Öffne diese Änderungsanfrage beim Anbieter, um die Änderungen zu sehen.} other {Öffne diesen Pull Request beim Anbieter, um die Änderungen zu sehen.}}",
@@ -4736,7 +4746,6 @@
4746
"986951276ab5723d": "Verknüpfung mit Thread lösen",
4747
"a9c188a91c93fdb4": "Beobachten konnte nicht geändert werden",
4748
"4bcfa3b976a421cf": "Nebenchat",
4739
- "d6783ef5e11f3e89": "Nebenchat konnte nicht gestartet werden.",
4749
"afd7cfeb929fcdbd": "Der Nebenchat wurde erstellt, hat dieses Gerät aber nicht erreicht.",
4750
"0efeaa8d0ca3a757": "Der Nebenchat ist nicht mehr verfügbar.",
4751
"61fc2531d076d396": "Der Berechtigungsmodus des Nebenchats konnte nicht festgelegt werden.",
apps/mobile/src/i18n/translations/en.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "Could not save the queued message",
1591
"b02695b75d8b050d": "Your edit is still in the composer.",
1592
"6ad508d2af838010": "It may have already started. Your edit is still in the composer.",
1593
+ "2498db230c4b87b6": "Too much context",
1594
"74e7e5c0536cda02": "Side chat not started",
1595
"a0269861cbd8c727": "Ask a side question",
1596
"d49fc7ca60395d59": "Type the question after {command}, then send it.",
1596
- "2498db230c4b87b6": "Too much context",
1597
+ "d6783ef5e11f3e89": "Could not start a side chat.",
1598
"ed68b68e83ee61bf": "Start a {provider} thread first",
1599
"c9852e2500018a3c": "Send a message before you submit feedback.",
1600
"7a4248cbd73fad20": "Failed to save the queued message.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "No archived threads",
1705
"ef5fd3138f95f318": "Could not load every archive",
1706
"26a8e439cedbce61": "Loading archive...",
1707
+ "cfae08fc22229b42": "Close browser",
1708
+ "a430e4548d57d722": "Back",
1709
+ "e7b9fc04d44070b7": "Address",
1710
+ "a8608329f9192866": "Enter a URL",
1711
+ "270506908c58ebcc": "Reload page",
1712
+ "f55a56936aed1cfa": "Maximize page",
1713
+ "a5d51502121f1630": "Address {url}. Show the browser controls",
1714
"b5f8f4124236be7c": "Picture in picture is unavailable",
1715
"47c47bbab985e718": "Could not open this address",
1716
"f0287e8bebecf7c2": "Enter an http or https URL.",
1717
"536c1b1898a53eab": "Browser",
1710
- "cfae08fc22229b42": "Close browser",
1718
"e208bda0b201c91f": "Exit picture in picture",
1719
"d483a9b20b305301": "Picture in picture",
1720
"9cf840ddbea731a5": "Tabs",
1714
- "a430e4548d57d722": "Back",
1715
- "22fbc48063de5b8e": "Forward",
1716
- "e7b9fc04d44070b7": "Address",
1717
- "a8608329f9192866": "Enter a URL",
1718
- "270506908c58ebcc": "Reload page",
1721
"14f99d0dac2d9681": "System",
1722
"a7e960938e75f747": "Light",
1723
"a6b5d3e28216f795": "Dark",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "Could not close this browser tab",
1730
"c91eae915827f9e3": "Could not change the viewport",
1731
"62dc4d3a19ff7ca0": "Close tab",
1732
+ "1df5ebbe09388a03": "Open on this device",
1733
"3fdf6cbbb9876fda": "Paste",
1734
+ "40269a025cb98db7": "Release control",
1735
"61fb04cd857a1a22": "Hard reload",
1736
"863f86bb80c0ea6a": "Zoom ({percent}%)",
1737
"8c32e9085e525c19": "Zoom in",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Clear cookies",
1743
"9bce41be8fc55a47": "Clear cache",
1744
"4d7f5af0445371fd": "Browser tab options",
1745
+ "27025b00be488485": "the environment",
1746
+ "e1ffd0532d64e52c": "This device can't open localhost pages",
1747
+ "f72cc72b321f93a5": "{reason} You can still use the streamed browser for this tab.",
1748
+ "663465f828e70345": "Not connected to {environment}",
1749
+ "d14ca43d8ae95c78": "Can't reach {host}",
1750
+ "69e9c247d0266e9f": "Pages on {environment}’s localhost load through its connection. Try again once it reconnects.",
1751
+ "301045c720839f4d": "Nothing is listening on port {port} on {environment}. Start the server there, then try again.",
1752
"0b16434dff468d30": "The upload was refused.",
1753
"bbcd3776bcd3e2c5": "Downloaded {fileName}",
1754
"f746b1e0bfb2ec4a": "Not now",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "The page has not shown yet. Try again in a moment.",
1768
"eeb59a631fec128d": "Picture in picture is unavailable.",
1769
"a3640fd5194ade85": "Browser viewer stopped unexpectedly.",
1759
- "40269a025cb98db7": "Release control",
1770
"156baef53680396e": "Take control",
1771
"95afdc33a06d3030": "The page asks for files.",
1772
"69c659d8b6e271cc": "The page asks for a file.",
@@ -2737,22 +2747,22 @@
2747
"06a684782801e8f7": "Copy head branch {branch}",
2748
"8e4f3c862193b8a5": "Edit",
2749
"8cc970597921c38a": "Delete {branch} from {repository}? Local branches and worktrees are not changed.",
2740
- "42fd133c37a117fe": "{repository} · Offline",
2750
"58bda2aa88d28696": "{term, select, mr {Merge request} cr {Change request} other {Pull request}} actions",
2751
"ffd49822d34cbd30": "Allow edits from maintainers",
2752
"2a83c8767b3e1918": "Deleting…",
2753
"99a3c6e593d6947d": "Reconnect to delete this branch.",
2754
+ "42fd133c37a117fe": "{repository} · Offline",
2755
"c83fb5e64f34fb1a": "Overview",
2756
"8d1ad30ddb277f48": "Guide",
2757
"3724ff240986c6da": "Commit changes",
2758
"d85877d9ef77c50c": "Changes",
2759
"ebb089d626dfaa7c": "Loading changes",
2750
- "89a7eb448db48738": "{count, plural, one {{count} test hidden} other {{count} tests hidden}}",
2760
"4050f873dc790f8f": "Diff options",
2761
"81cf438219f0a618": "Word wrap",
2762
"8ec7e405049af1f7": "Move draft to this line",
2763
"8e5f5001f74a460f": "Add review comment",
2764
"8055c658cf61dd31": "Copy line",
2765
+ "89a7eb448db48738": "{count, plural, one {{count} test hidden} other {{count} tests hidden}}",
2766
"b4f58b68410c319f": "Reload changes",
2767
"01cb0224aa3208c1": "Diff unavailable",
2768
"b683d10f00d06824": "Open this {term, select, mr {merge request} cr {change request} other {pull request}} on its provider to view the changes.",
@@ -4737,7 +4747,6 @@
4747
"986951276ab5723d": "Unlink from thread",
4748
"a9c188a91c93fdb4": "Couldn't change watching",
4749
"4bcfa3b976a421cf": "Side chat",
4740
- "d6783ef5e11f3e89": "Could not start a side chat.",
4750
"afd7cfeb929fcdbd": "The side chat was created, but it did not reach this device.",
4751
"0efeaa8d0ca3a757": "The side chat is no longer available.",
4752
"61fc2531d076d396": "Could not set the side chat's permission mode.",
apps/mobile/src/i18n/translations/es.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "No se pudo guardar el mensaje en cola",
1591
"b02695b75d8b050d": "Tu edición sigue en el cuadro de mensaje.",
1592
"6ad508d2af838010": "Puede que ya haya empezado. Tu edición sigue en el cuadro de mensaje.",
1593
+ "2498db230c4b87b6": "Demasiado contexto",
1594
"74e7e5c0536cda02": "Chat lateral no iniciado",
1595
"a0269861cbd8c727": "Haz una pregunta aparte",
1596
"d49fc7ca60395d59": "Escribe la pregunta después de {command} y envíala.",
1596
- "2498db230c4b87b6": "Demasiado contexto",
1597
+ "d6783ef5e11f3e89": "No se pudo iniciar un chat lateral.",
1598
"ed68b68e83ee61bf": "Primero inicia un hilo de {provider}",
1599
"c9852e2500018a3c": "Envía un mensaje antes de enviar comentarios.",
1600
"7a4248cbd73fad20": "No se pudo guardar el mensaje en cola.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "No hay hilos archivados",
1705
"ef5fd3138f95f318": "No se pudieron cargar todos los archivados",
1706
"26a8e439cedbce61": "Cargando archivados...",
1707
+ "cfae08fc22229b42": "Cerrar navegador",
1708
+ "a430e4548d57d722": "Atrás",
1709
+ "e7b9fc04d44070b7": "Dirección",
1710
+ "a8608329f9192866": "Introduce una URL",
1711
+ "270506908c58ebcc": "Recargar página",
1712
+ "f55a56936aed1cfa": "Maximizar página",
1713
+ "a5d51502121f1630": "Dirección {url}. Mostrar los controles del navegador",
1714
"b5f8f4124236be7c": "Imagen en imagen no está disponible",
1715
"47c47bbab985e718": "No se pudo abrir esta dirección",
1716
"f0287e8bebecf7c2": "Introduce una URL http o https.",
1717
"536c1b1898a53eab": "Navegador",
1710
- "cfae08fc22229b42": "Cerrar navegador",
1718
"e208bda0b201c91f": "Salir de imagen en imagen",
1719
"d483a9b20b305301": "Imagen en imagen",
1720
"9cf840ddbea731a5": "Pestañas",
1714
- "a430e4548d57d722": "Atrás",
1715
- "22fbc48063de5b8e": "Adelante",
1716
- "e7b9fc04d44070b7": "Dirección",
1717
- "a8608329f9192866": "Introduce una URL",
1718
- "270506908c58ebcc": "Recargar página",
1721
"14f99d0dac2d9681": "Sistema",
1722
"a7e960938e75f747": "Claro",
1723
"a6b5d3e28216f795": "Oscuro",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "No se pudo cerrar esta pestaña del navegador",
1730
"c91eae915827f9e3": "No se pudo cambiar el viewport",
1731
"62dc4d3a19ff7ca0": "Cerrar pestaña",
1732
+ "1df5ebbe09388a03": "Abrir en este dispositivo",
1733
"3fdf6cbbb9876fda": "Pegar",
1734
+ "40269a025cb98db7": "Ceder el control",
1735
"61fb04cd857a1a22": "Recarga forzada",
1736
"863f86bb80c0ea6a": "Zoom ({percent}%)",
1737
"8c32e9085e525c19": "Acercar",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Borrar cookies",
1743
"9bce41be8fc55a47": "Borrar caché",
1744
"4d7f5af0445371fd": "Opciones de la pestaña del navegador",
1745
+ "27025b00be488485": "el entorno",
1746
+ "e1ffd0532d64e52c": "Este dispositivo no puede abrir páginas de localhost",
1747
+ "f72cc72b321f93a5": "{reason} Aún puedes usar el navegador transmitido para esta pestaña.",
1748
+ "663465f828e70345": "Sin conexión con {environment}",
1749
+ "d14ca43d8ae95c78": "No se puede acceder a {host}",
1750
+ "69e9c247d0266e9f": "Las páginas del localhost de {environment} se cargan a través de su conexión. Vuelve a intentarlo cuando se reconecte.",
1751
+ "301045c720839f4d": "Nada escucha en el puerto {port} de {environment}. Inicia el servidor allí y vuelve a intentarlo.",
1752
"0b16434dff468d30": "Se rechazó la subida.",
1753
"bbcd3776bcd3e2c5": "Se descargó {fileName}",
1754
"f746b1e0bfb2ec4a": "Ahora no",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "La página aún no se ha mostrado. Vuelve a intentarlo en un momento.",
1768
"eeb59a631fec128d": "Imagen en imagen no está disponible.",
1769
"a3640fd5194ade85": "El visor del navegador se detuvo inesperadamente.",
1759
- "40269a025cb98db7": "Ceder el control",
1770
"156baef53680396e": "Tomar el control",
1771
"95afdc33a06d3030": "La página pide archivos.",
1772
"69c659d8b6e271cc": "La página pide un archivo.",
@@ -2733,22 +2743,22 @@
2743
"06a684782801e8f7": "Copiar la rama head {branch}",
2744
"8e4f3c862193b8a5": "Editar",
2745
"8cc970597921c38a": "¿Eliminar {branch} de {repository}? Las ramas locales y los worktrees no cambian.",
2736
- "42fd133c37a117fe": "{repository} · Sin conexión",
2746
"58bda2aa88d28696": "Acciones de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}",
2747
"ffd49822d34cbd30": "Permitir ediciones de los mantenedores",
2748
"2a83c8767b3e1918": "Eliminando…",
2749
"99a3c6e593d6947d": "Vuelve a conectarte para eliminar esta rama.",
2750
+ "42fd133c37a117fe": "{repository} · Sin conexión",
2751
"c83fb5e64f34fb1a": "Resumen",
2752
"8d1ad30ddb277f48": "Guía",
2753
"3724ff240986c6da": "Hacer commit de los cambios",
2754
"d85877d9ef77c50c": "Cambios",
2755
"ebb089d626dfaa7c": "Cargando cambios",
2746
- "89a7eb448db48738": "{count, plural, one {{count} prueba oculta} other {{count} pruebas ocultas}}",
2756
"4050f873dc790f8f": "Opciones del diff",
2757
"81cf438219f0a618": "Ajuste de línea",
2758
"8ec7e405049af1f7": "Mover el borrador a esta línea",
2759
"8e5f5001f74a460f": "Añadir comentario de revisión",
2760
"8055c658cf61dd31": "Copiar línea",
2761
+ "89a7eb448db48738": "{count, plural, one {{count} prueba oculta} other {{count} pruebas ocultas}}",
2762
"b4f58b68410c319f": "Recargar cambios",
2763
"01cb0224aa3208c1": "Diff no disponible",
2764
"b683d10f00d06824": "Abre esta {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}} en su proveedor para ver los cambios.",
@@ -4729,7 +4739,6 @@
4739
"986951276ab5723d": "Desvincular del hilo",
4740
"a9c188a91c93fdb4": "No se pudo cambiar el seguimiento",
4741
"4bcfa3b976a421cf": "Chat lateral",
4732
- "d6783ef5e11f3e89": "No se pudo iniciar un chat lateral.",
4742
"afd7cfeb929fcdbd": "Se creó el chat lateral, pero no llegó a este dispositivo.",
4743
"0efeaa8d0ca3a757": "El chat lateral ya no está disponible.",
4744
"61fc2531d076d396": "No se pudo definir el modo de permisos del chat lateral.",
apps/mobile/src/i18n/translations/fr.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "Impossible d’enregistrer le message en file d’attente",
1591
"b02695b75d8b050d": "Votre modification est toujours dans la zone de saisie.",
1592
"6ad508d2af838010": "Il a peut-être déjà démarré. Votre modification est toujours dans la zone de saisie.",
1593
+ "2498db230c4b87b6": "Trop de contexte",
1594
"74e7e5c0536cda02": "Discussion annexe non démarrée",
1595
"a0269861cbd8c727": "Poser une question annexe",
1596
"d49fc7ca60395d59": "Tapez la question après {command}, puis envoyez-la.",
1596
- "2498db230c4b87b6": "Trop de contexte",
1597
+ "d6783ef5e11f3e89": "Impossible de démarrer une discussion annexe.",
1598
"ed68b68e83ee61bf": "Démarrez d’abord un fil {provider}",
1599
"c9852e2500018a3c": "Envoyez un message avant de soumettre des commentaires.",
1600
"7a4248cbd73fad20": "Échec de l’enregistrement du message en file d’attente.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "Aucun fil archivé",
1705
"ef5fd3138f95f318": "Impossible de charger toutes les archives",
1706
"26a8e439cedbce61": "Chargement des archives...",
1707
+ "cfae08fc22229b42": "Fermer le navigateur",
1708
+ "a430e4548d57d722": "Précédent",
1709
+ "e7b9fc04d44070b7": "Adresse",
1710
+ "a8608329f9192866": "Saisissez une URL",
1711
+ "270506908c58ebcc": "Recharger la page",
1712
+ "f55a56936aed1cfa": "Agrandir la page",
1713
+ "a5d51502121f1630": "Adresse {url}. Afficher les commandes du navigateur",
1714
"b5f8f4124236be7c": "Le mode image dans l’image n’est pas disponible",
1715
"47c47bbab985e718": "Impossible d’ouvrir cette adresse",
1716
"f0287e8bebecf7c2": "Saisissez une URL http ou https.",
1717
"536c1b1898a53eab": "Navigateur",
1710
- "cfae08fc22229b42": "Fermer le navigateur",
1718
"e208bda0b201c91f": "Quitter l’image dans l’image",
1719
"d483a9b20b305301": "Image dans l’image",
1720
"9cf840ddbea731a5": "Onglets",
1714
- "a430e4548d57d722": "Précédent",
1715
- "22fbc48063de5b8e": "Suivant",
1716
- "e7b9fc04d44070b7": "Adresse",
1717
- "a8608329f9192866": "Saisissez une URL",
1718
- "270506908c58ebcc": "Recharger la page",
1721
"14f99d0dac2d9681": "Système",
1722
"a7e960938e75f747": "Clair",
1723
"a6b5d3e28216f795": "Sombre",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "Impossible de fermer cet onglet du navigateur",
1730
"c91eae915827f9e3": "Impossible de modifier la fenêtre d’affichage",
1731
"62dc4d3a19ff7ca0": "Fermer l’onglet",
1732
+ "1df5ebbe09388a03": "Ouvrir sur cet appareil",
1733
"3fdf6cbbb9876fda": "Coller",
1734
+ "40269a025cb98db7": "Rendre le contrôle",
1735
"61fb04cd857a1a22": "Recharger sans le cache",
1736
"863f86bb80c0ea6a": "Zoom ({percent} %)",
1737
"8c32e9085e525c19": "Zoom avant",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Effacer les cookies",
1743
"9bce41be8fc55a47": "Vider le cache",
1744
"4d7f5af0445371fd": "Options de l’onglet du navigateur",
1745
+ "27025b00be488485": "l’environnement",
1746
+ "e1ffd0532d64e52c": "Cet appareil ne peut pas ouvrir les pages localhost",
1747
+ "f72cc72b321f93a5": "{reason} Tu peux toujours utiliser le navigateur diffusé pour cet onglet.",
1748
+ "663465f828e70345": "Non connecté à {environment}",
1749
+ "d14ca43d8ae95c78": "Impossible d’atteindre {host}",
1750
+ "69e9c247d0266e9f": "Les pages du localhost de {environment} passent par sa connexion. Réessaie une fois la connexion rétablie.",
1751
+ "301045c720839f4d": "Rien n’écoute sur le port {port} de {environment}. Démarre le serveur là-bas, puis réessaie.",
1752
"0b16434dff468d30": "L’envoi a été refusé.",
1753
"bbcd3776bcd3e2c5": "{fileName} téléchargé",
1754
"f746b1e0bfb2ec4a": "Pas maintenant",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "La page ne s’est pas encore affichée. Réessayez dans un instant.",
1768
"eeb59a631fec128d": "Le mode image dans l’image n’est pas disponible.",
1769
"a3640fd5194ade85": "La visionneuse du navigateur s’est arrêtée de façon inattendue.",
1759
- "40269a025cb98db7": "Rendre le contrôle",
1770
"156baef53680396e": "Prendre le contrôle",
1771
"95afdc33a06d3030": "La page demande des fichiers.",
1772
"69c659d8b6e271cc": "La page demande un fichier.",
@@ -2733,22 +2743,22 @@
2743
"06a684782801e8f7": "Copier la branche de tête {branch}",
2744
"8e4f3c862193b8a5": "Modifier",
2745
"8cc970597921c38a": "Supprimer {branch} de {repository} ? Les branches locales et les worktrees ne sont pas modifiés.",
2736
- "42fd133c37a117fe": "{repository} · Hors ligne",
2746
"58bda2aa88d28696": "Actions de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}",
2747
"ffd49822d34cbd30": "Autoriser les modifications des mainteneurs",
2748
"2a83c8767b3e1918": "Suppression…",
2749
"99a3c6e593d6947d": "Reconnectez-vous pour supprimer cette branche.",
2750
+ "42fd133c37a117fe": "{repository} · Hors ligne",
2751
"c83fb5e64f34fb1a": "Vue d’ensemble",
2752
"8d1ad30ddb277f48": "Guide",
2753
"3724ff240986c6da": "Commiter les modifications",
2754
"d85877d9ef77c50c": "Modifications",
2755
"ebb089d626dfaa7c": "Chargement des modifications",
2746
- "89a7eb448db48738": "{count, plural, one {{count} test masqué} other {{count} tests masqués}}",
2756
"4050f873dc790f8f": "Options du diff",
2757
"81cf438219f0a618": "Retour à la ligne",
2758
"8ec7e405049af1f7": "Déplacer le brouillon sur cette ligne",
2759
"8e5f5001f74a460f": "Ajouter un commentaire de revue",
2760
"8055c658cf61dd31": "Copier la ligne",
2761
+ "89a7eb448db48738": "{count, plural, one {{count} test masqué} other {{count} tests masqués}}",
2762
"b4f58b68410c319f": "Recharger les modifications",
2763
"01cb0224aa3208c1": "Diff indisponible",
2764
"b683d10f00d06824": "Ouvrez cette {term, select, mr {merge request} cr {demande de modification} other {pull request}} chez son fournisseur pour voir les modifications.",
@@ -4730,7 +4740,6 @@
4740
"986951276ab5723d": "Dissocier du fil",
4741
"a9c188a91c93fdb4": "Impossible de modifier le suivi",
4742
"4bcfa3b976a421cf": "Discussion annexe",
4733
- "d6783ef5e11f3e89": "Impossible de démarrer une discussion annexe.",
4743
"afd7cfeb929fcdbd": "La discussion annexe a été créée, mais elle n’est pas parvenue sur cet appareil.",
4744
"0efeaa8d0ca3a757": "La discussion annexe n’est plus disponible.",
4745
"61fc2531d076d396": "Impossible de définir le mode d’autorisation de la discussion annexe.",
apps/mobile/src/i18n/translations/ja.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "キュー内のメッセージを保存できませんでした",
1591
"b02695b75d8b050d": "編集内容は入力欄に残っています。",
1592
"6ad508d2af838010": "すでに開始されている可能性があります。編集内容は入力欄に残っています。",
1593
+ "2498db230c4b87b6": "コンテキストが多すぎます",
1594
"74e7e5c0536cda02": "サイドチャットが開始されていません",
1595
"a0269861cbd8c727": "横から質問する",
1596
"d49fc7ca60395d59": "{command} の後に質問を入力して送信してください。",
1596
- "2498db230c4b87b6": "コンテキストが多すぎます",
1597
+ "d6783ef5e11f3e89": "サイドチャットを開始できませんでした。",
1598
"ed68b68e83ee61bf": "先に {provider} のスレッドを開始してください",
1599
"c9852e2500018a3c": "フィードバックを送信する前にメッセージを送信してください。",
1600
"7a4248cbd73fad20": "キュー内のメッセージを保存できませんでした。",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "アーカイブ済みのスレッドはありません",
1705
"ef5fd3138f95f318": "一部のアーカイブを読み込めませんでした",
1706
"26a8e439cedbce61": "アーカイブを読み込んでいます...",
1707
+ "cfae08fc22229b42": "ブラウザーを閉じる",
1708
+ "a430e4548d57d722": "戻る",
1709
+ "e7b9fc04d44070b7": "アドレス",
1710
+ "a8608329f9192866": "URL を入力",
1711
+ "270506908c58ebcc": "ページを再読み込み",
1712
+ "f55a56936aed1cfa": "ページを最大化",
1713
+ "a5d51502121f1630": "アドレス {url}。ブラウザのコントロールを表示",
1714
"b5f8f4124236be7c": "ピクチャ・イン・ピクチャは利用できません",
1715
"47c47bbab985e718": "このアドレスを開けませんでした",
1716
"f0287e8bebecf7c2": "http または https の URL を入力してください。",
1717
"536c1b1898a53eab": "ブラウザー",
1710
- "cfae08fc22229b42": "ブラウザーを閉じる",
1718
"e208bda0b201c91f": "ピクチャ・イン・ピクチャを終了",
1719
"d483a9b20b305301": "ピクチャ・イン・ピクチャ",
1720
"9cf840ddbea731a5": "タブ",
1714
- "a430e4548d57d722": "戻る",
1715
- "22fbc48063de5b8e": "進む",
1716
- "e7b9fc04d44070b7": "アドレス",
1717
- "a8608329f9192866": "URL を入力",
1718
- "270506908c58ebcc": "ページを再読み込み",
1721
"14f99d0dac2d9681": "システム",
1722
"a7e960938e75f747": "ライト",
1723
"a6b5d3e28216f795": "ダーク",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "このブラウザータブを閉じられませんでした",
1730
"c91eae915827f9e3": "ビューポートを変更できませんでした",
1731
"62dc4d3a19ff7ca0": "タブを閉じる",
1732
+ "1df5ebbe09388a03": "このデバイスで開く",
1733
"3fdf6cbbb9876fda": "貼り付け",
1734
+ "40269a025cb98db7": "操作権を手放す",
1735
"61fb04cd857a1a22": "強制再読み込み",
1736
"863f86bb80c0ea6a": "ズーム ({percent}%)",
1737
"8c32e9085e525c19": "拡大",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Cookie を消去",
1743
"9bce41be8fc55a47": "キャッシュを消去",
1744
"4d7f5af0445371fd": "ブラウザータブのオプション",
1745
+ "27025b00be488485": "環境",
1746
+ "e1ffd0532d64e52c": "このデバイスでは localhost のページを開けません",
1747
+ "f72cc72b321f93a5": "{reason} このタブではストリーミングブラウザを引き続き使えます。",
1748
+ "663465f828e70345": "{environment} に接続されていません",
1749
+ "d14ca43d8ae95c78": "{host} に到達できません",
1750
+ "69e9c247d0266e9f": "{environment} の localhost のページは、その接続を通じて読み込まれます。再接続されたらもう一度お試しください。",
1751
+ "301045c720839f4d": "{environment} のポート {port} で待ち受けているものはありません。そこでサーバーを起動してから、もう一度お試しください。",
1752
"0b16434dff468d30": "アップロードは拒否されました。",
1753
"bbcd3776bcd3e2c5": "{fileName} をダウンロードしました",
1754
"f746b1e0bfb2ec4a": "今はしない",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "ページはまだ表示されていません。しばらくしてからもう一度お試しください。",
1768
"eeb59a631fec128d": "ピクチャーインピクチャーを利用できません。",
1769
"a3640fd5194ade85": "ブラウザービューアーが予期せず停止しました。",
1759
- "40269a025cb98db7": "操作権を手放す",
1770
"156baef53680396e": "操作権を取得",
1771
"95afdc33a06d3030": "ページがファイルを求めています。",
1772
"69c659d8b6e271cc": "ページがファイルを求めています。",
@@ -2730,22 +2740,22 @@
2740
"06a684782801e8f7": "ヘッドブランチ {branch} をコピー",
2741
"8e4f3c862193b8a5": "編集",
2742
"8cc970597921c38a": "{repository} から {branch} を削除しますか?ローカルのブランチとワークツリーは変更されません。",
2733
- "42fd133c37a117fe": "{repository} · オフライン",
2743
"58bda2aa88d28696": "{term, select, mr {マージリクエストの操作} cr {変更リクエストの操作} other {プルリクエストの操作}}",
2744
"ffd49822d34cbd30": "メンテナーによる編集を許可",
2745
"2a83c8767b3e1918": "削除中…",
2746
"99a3c6e593d6947d": "このブランチを削除するには再接続してください。",
2747
+ "42fd133c37a117fe": "{repository} · オフライン",
2748
"c83fb5e64f34fb1a": "概要",
2749
"8d1ad30ddb277f48": "ガイド",
2750
"3724ff240986c6da": "変更をコミット",
2751
"d85877d9ef77c50c": "変更",
2752
"ebb089d626dfaa7c": "変更を読み込んでいます",
2743
- "89a7eb448db48738": "{count, plural, other {{count} 個のテストを非表示}}",
2753
"4050f873dc790f8f": "差分のオプション",
2754
"81cf438219f0a618": "折り返し",
2755
"8ec7e405049af1f7": "下書きをこの行に移動",
2756
"8e5f5001f74a460f": "レビューコメントを追加",
2757
"8055c658cf61dd31": "行をコピー",
2758
+ "89a7eb448db48738": "{count, plural, other {{count} 個のテストを非表示}}",
2759
"b4f58b68410c319f": "変更を再読み込み",
2760
"01cb0224aa3208c1": "差分を利用できません",
2761
"b683d10f00d06824": "{term, select, mr {変更を表示するには、プロバイダーでこのマージリクエストを開いてください。} cr {変更を表示するには、プロバイダーでこの変更リクエストを開いてください。} other {変更を表示するには、プロバイダーでこのプルリクエストを開いてください。}}",
@@ -4711,7 +4721,6 @@
4721
"986951276ab5723d": "スレッドからリンクを解除",
4722
"a9c188a91c93fdb4": "監視を変更できませんでした",
4723
"4bcfa3b976a421cf": "サイドチャット",
4714
- "d6783ef5e11f3e89": "サイドチャットを開始できませんでした。",
4724
"afd7cfeb929fcdbd": "サイドチャットは作成されましたが、このデバイスに届きませんでした。",
4725
"0efeaa8d0ca3a757": "サイドチャットは利用できなくなりました。",
4726
"61fc2531d076d396": "サイドチャットの権限モードを設定できませんでした。",
apps/mobile/src/i18n/translations/ko.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "대기 메시지를 저장할 수 없습니다",
1591
"b02695b75d8b050d": "편집 내용은 입력창에 그대로 있습니다.",
1592
"6ad508d2af838010": "이미 시작되었을 수 있습니다. 편집 내용은 입력창에 그대로 있습니다.",
1593
+ "2498db230c4b87b6": "컨텍스트가 너무 많습니다",
1594
"74e7e5c0536cda02": "사이드 채팅이 시작되지 않음",
1595
"a0269861cbd8c727": "곁가지 질문하기",
1596
"d49fc7ca60395d59": "{command} 뒤에 질문을 입력한 뒤 보내세요.",
1596
- "2498db230c4b87b6": "컨텍스트가 너무 많습니다",
1597
+ "d6783ef5e11f3e89": "사이드 채팅을 시작할 수 없습니다.",
1598
"ed68b68e83ee61bf": "먼저 {provider} 스레드를 시작하세요",
1599
"c9852e2500018a3c": "피드백을 제출하기 전에 메시지를 보내세요.",
1600
"7a4248cbd73fad20": "대기 메시지를 저장하지 못했습니다.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "보관된 스레드 없음",
1705
"ef5fd3138f95f318": "일부 보관함을 불러올 수 없습니다",
1706
"26a8e439cedbce61": "보관함 불러오는 중...",
1707
+ "cfae08fc22229b42": "브라우저 닫기",
1708
+ "a430e4548d57d722": "뒤로",
1709
+ "e7b9fc04d44070b7": "주소",
1710
+ "a8608329f9192866": "URL 입력",
1711
+ "270506908c58ebcc": "페이지 새로 고침",
1712
+ "f55a56936aed1cfa": "페이지 최대화",
1713
+ "a5d51502121f1630": "주소 {url}. 브라우저 컨트롤 표시",
1714
"b5f8f4124236be7c": "PIP를 사용할 수 없습니다",
1715
"47c47bbab985e718": "이 주소를 열 수 없습니다",
1716
"f0287e8bebecf7c2": "http 또는 https URL을 입력하세요.",
1717
"536c1b1898a53eab": "브라우저",
1710
- "cfae08fc22229b42": "브라우저 닫기",
1718
"e208bda0b201c91f": "PIP 종료",
1719
"d483a9b20b305301": "PIP 모드",
1720
"9cf840ddbea731a5": "탭",
1714
- "a430e4548d57d722": "뒤로",
1715
- "22fbc48063de5b8e": "앞으로",
1716
- "e7b9fc04d44070b7": "주소",
1717
- "a8608329f9192866": "URL 입력",
1718
- "270506908c58ebcc": "페이지 새로 고침",
1721
"14f99d0dac2d9681": "시스템",
1722
"a7e960938e75f747": "라이트",
1723
"a6b5d3e28216f795": "다크",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "이 브라우저 탭을 닫을 수 없습니다",
1730
"c91eae915827f9e3": "뷰포트를 변경할 수 없습니다",
1731
"62dc4d3a19ff7ca0": "탭 닫기",
1732
+ "1df5ebbe09388a03": "이 기기에서 열기",
1733
"3fdf6cbbb9876fda": "붙여넣기",
1734
+ "40269a025cb98db7": "제어 해제",
1735
"61fb04cd857a1a22": "강력 새로 고침",
1736
"863f86bb80c0ea6a": "확대/축소({percent}%)",
1737
"8c32e9085e525c19": "확대",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "쿠키 지우기",
1743
"9bce41be8fc55a47": "캐시 지우기",
1744
"4d7f5af0445371fd": "브라우저 탭 옵션",
1745
+ "27025b00be488485": "환경",
1746
+ "e1ffd0532d64e52c": "이 기기에서는 localhost 페이지를 열 수 없습니다",
1747
+ "f72cc72b321f93a5": "{reason} 이 탭에서는 스트리밍 브라우저를 계속 사용할 수 있습니다.",
1748
+ "663465f828e70345": "{environment}에 연결되지 않음",
1749
+ "d14ca43d8ae95c78": "{host}에 연결할 수 없음",
1750
+ "69e9c247d0266e9f": "{environment}의 localhost 페이지는 해당 연결을 통해 로드됩니다. 다시 연결되면 다시 시도하세요.",
1751
+ "301045c720839f4d": "{environment}의 포트 {port}에서 수신 대기 중인 항목이 없습니다. 그곳에서 서버를 시작한 다음 다시 시도하세요.",
1752
"0b16434dff468d30": "업로드가 거부되었습니다.",
1753
"bbcd3776bcd3e2c5": "{fileName} 다운로드됨",
1754
"f746b1e0bfb2ec4a": "나중에",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "페이지가 아직 표시되지 않았습니다. 잠시 후 다시 시도하세요.",
1768
"eeb59a631fec128d": "PIP 모드를 사용할 수 없습니다.",
1769
"a3640fd5194ade85": "브라우저 뷰어가 예기치 않게 중지되었습니다.",
1759
- "40269a025cb98db7": "제어 해제",
1770
"156baef53680396e": "제어하기",
1771
"95afdc33a06d3030": "페이지에서 파일을 요청합니다.",
1772
"69c659d8b6e271cc": "페이지에서 파일을 요청합니다.",
@@ -2734,22 +2744,22 @@
2744
"06a684782801e8f7": "헤드 브랜치 {branch} 복사",
2745
"8e4f3c862193b8a5": "편집",
2746
"8cc970597921c38a": "{repository}에서 {branch}을(를) 삭제할까요? 로컬 브랜치와 워크트리는 변경되지 않습니다.",
2737
- "42fd133c37a117fe": "{repository} · 오프라인",
2747
"58bda2aa88d28696": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 작업",
2748
"ffd49822d34cbd30": "관리자의 편집 허용",
2749
"2a83c8767b3e1918": "삭제 중…",
2750
"99a3c6e593d6947d": "이 브랜치를 삭제하려면 다시 연결하세요.",
2751
+ "42fd133c37a117fe": "{repository} · 오프라인",
2752
"c83fb5e64f34fb1a": "개요",
2753
"8d1ad30ddb277f48": "가이드",
2754
"3724ff240986c6da": "변경 사항 커밋",
2755
"d85877d9ef77c50c": "변경 사항",
2756
"ebb089d626dfaa7c": "변경 사항 불러오는 중",
2747
- "89a7eb448db48738": "{count, plural, other {테스트 {count}개 숨김}}",
2757
"4050f873dc790f8f": "변경 사항 옵션",
2758
"81cf438219f0a618": "자동 줄 바꿈",
2759
"8ec7e405049af1f7": "초안을 이 줄로 이동",
2760
"8e5f5001f74a460f": "검토 댓글 추가",
2761
"8055c658cf61dd31": "줄 복사",
2762
+ "89a7eb448db48738": "{count, plural, other {테스트 {count}개 숨김}}",
2763
"b4f58b68410c319f": "변경 사항 다시 불러오기",
2764
"01cb0224aa3208c1": "변경 사항을 사용할 수 없음",
2765
"b683d10f00d06824": "변경 사항을 보려면 제공자에서 이 {term, select, mr {병합 요청을} cr {변경 요청을} other {풀 리퀘스트를}} 여세요.",
@@ -4716,7 +4726,6 @@
4726
"986951276ab5723d": "스레드에서 연결 해제",
4727
"a9c188a91c93fdb4": "지켜보기를 변경할 수 없습니다",
4728
"4bcfa3b976a421cf": "사이드 채팅",
4719
- "d6783ef5e11f3e89": "사이드 채팅을 시작할 수 없습니다.",
4729
"afd7cfeb929fcdbd": "사이드 채팅이 생성되었지만 이 기기에 도착하지 않았습니다.",
4730
"0efeaa8d0ca3a757": "사이드 채팅을 더 이상 사용할 수 없습니다.",
4731
"61fc2531d076d396": "사이드 채팅의 권한 모드를 설정할 수 없습니다.",
apps/mobile/src/i18n/translations/pt-BR.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "Não foi possível salvar a mensagem da fila",
1591
"b02695b75d8b050d": "Sua edição continua no editor de mensagens.",
1592
"6ad508d2af838010": "Ela pode já ter começado. Sua edição continua no editor de mensagens.",
1593
+ "2498db230c4b87b6": "Contexto demais",
1594
"74e7e5c0536cda02": "Chat paralelo não iniciado",
1595
"a0269861cbd8c727": "Fazer uma pergunta paralela",
1596
"d49fc7ca60395d59": "Digite a pergunta depois de {command} e envie.",
1596
- "2498db230c4b87b6": "Contexto demais",
1597
+ "d6783ef5e11f3e89": "Não foi possível iniciar um chat paralelo.",
1598
"ed68b68e83ee61bf": "Inicie uma thread do {provider} primeiro",
1599
"c9852e2500018a3c": "Envie uma mensagem antes de enviar feedback.",
1600
"7a4248cbd73fad20": "Falha ao salvar a mensagem da fila.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "Nenhuma thread arquivada",
1705
"ef5fd3138f95f318": "Não foi possível carregar todos os arquivos",
1706
"26a8e439cedbce61": "Carregando arquivados...",
1707
+ "cfae08fc22229b42": "Fechar navegador",
1708
+ "a430e4548d57d722": "Voltar",
1709
+ "e7b9fc04d44070b7": "Endereço",
1710
+ "a8608329f9192866": "Digite uma URL",
1711
+ "270506908c58ebcc": "Recarregar página",
1712
+ "f55a56936aed1cfa": "Maximizar página",
1713
+ "a5d51502121f1630": "Endereço {url}. Mostrar os controles do navegador",
1714
"b5f8f4124236be7c": "Picture-in-picture não está disponível",
1715
"47c47bbab985e718": "Não foi possível abrir este endereço",
1716
"f0287e8bebecf7c2": "Digite uma URL http ou https.",
1717
"536c1b1898a53eab": "Navegador",
1710
- "cfae08fc22229b42": "Fechar navegador",
1718
"e208bda0b201c91f": "Sair do picture-in-picture",
1719
"d483a9b20b305301": "Picture-in-picture",
1720
"9cf840ddbea731a5": "Abas",
1714
- "a430e4548d57d722": "Voltar",
1715
- "22fbc48063de5b8e": "Avançar",
1716
- "e7b9fc04d44070b7": "Endereço",
1717
- "a8608329f9192866": "Digite uma URL",
1718
- "270506908c58ebcc": "Recarregar página",
1721
"14f99d0dac2d9681": "Sistema",
1722
"a7e960938e75f747": "Claro",
1723
"a6b5d3e28216f795": "Escuro",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "Não foi possível fechar esta aba do navegador",
1730
"c91eae915827f9e3": "Não foi possível alterar o viewport",
1731
"62dc4d3a19ff7ca0": "Fechar aba",
1732
+ "1df5ebbe09388a03": "Abrir neste dispositivo",
1733
"3fdf6cbbb9876fda": "Colar",
1734
+ "40269a025cb98db7": "Liberar o controle",
1735
"61fb04cd857a1a22": "Recarregamento forçado",
1736
"863f86bb80c0ea6a": "Zoom ({percent}%)",
1737
"8c32e9085e525c19": "Aumentar zoom",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Limpar cookies",
1743
"9bce41be8fc55a47": "Limpar cache",
1744
"4d7f5af0445371fd": "Opções da aba do navegador",
1745
+ "27025b00be488485": "o ambiente",
1746
+ "e1ffd0532d64e52c": "Este dispositivo não consegue abrir páginas de localhost",
1747
+ "f72cc72b321f93a5": "{reason} Você ainda pode usar o navegador transmitido para esta aba.",
1748
+ "663465f828e70345": "Sem conexão com {environment}",
1749
+ "d14ca43d8ae95c78": "Não é possível acessar {host}",
1750
+ "69e9c247d0266e9f": "As páginas do localhost de {environment} carregam pela conexão dele. Tente novamente quando ela se reconectar.",
1751
+ "301045c720839f4d": "Nada está escutando na porta {port} de {environment}. Inicie o servidor lá e tente novamente.",
1752
"0b16434dff468d30": "O envio foi recusado.",
1753
"bbcd3776bcd3e2c5": "{fileName} baixado",
1754
"f746b1e0bfb2ec4a": "Agora não",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "A página ainda não apareceu. Tente novamente em instantes.",
1768
"eeb59a631fec128d": "O picture-in-picture não está disponível.",
1769
"a3640fd5194ade85": "O visualizador do navegador parou inesperadamente.",
1759
- "40269a025cb98db7": "Liberar o controle",
1770
"156baef53680396e": "Assumir o controle",
1771
"95afdc33a06d3030": "A página está pedindo arquivos.",
1772
"69c659d8b6e271cc": "A página está pedindo um arquivo.",
@@ -2733,22 +2743,22 @@
2743
"06a684782801e8f7": "Copiar branch head {branch}",
2744
"8e4f3c862193b8a5": "Editar",
2745
"8cc970597921c38a": "Excluir {branch} de {repository}? Os branches locais e os worktrees não são alterados.",
2736
- "42fd133c37a117fe": "{repository} · Offline",
2746
"58bda2aa88d28696": "Ações {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}",
2747
"ffd49822d34cbd30": "Permitir edições dos mantenedores",
2748
"2a83c8767b3e1918": "Excluindo…",
2749
"99a3c6e593d6947d": "Reconecte para excluir este branch.",
2750
+ "42fd133c37a117fe": "{repository} · Offline",
2751
"c83fb5e64f34fb1a": "Visão geral",
2752
"8d1ad30ddb277f48": "Guia",
2753
"3724ff240986c6da": "Fazer commit das alterações",
2754
"d85877d9ef77c50c": "Alterações",
2755
"ebb089d626dfaa7c": "Carregando alterações",
2746
- "89a7eb448db48738": "{count, plural, one {{count} teste oculto} other {{count} testes ocultos}}",
2756
"4050f873dc790f8f": "Opções do diff",
2757
"81cf438219f0a618": "Quebra de linha",
2758
"8ec7e405049af1f7": "Mover rascunho para esta linha",
2759
"8e5f5001f74a460f": "Adicionar comentário de revisão",
2760
"8055c658cf61dd31": "Copiar linha",
2761
+ "89a7eb448db48738": "{count, plural, one {{count} teste oculto} other {{count} testes ocultos}}",
2762
"b4f58b68410c319f": "Recarregar alterações",
2763
"01cb0224aa3208c1": "Diff indisponível",
2764
"b683d10f00d06824": "Abra {term, select, mr {este merge request} cr {esta solicitação de alteração} other {este pull request}} no provedor para ver as alterações.",
@@ -4730,7 +4740,6 @@
4740
"986951276ab5723d": "Desvincular da thread",
4741
"a9c188a91c93fdb4": "Não foi possível alterar o acompanhamento",
4742
"4bcfa3b976a421cf": "Chat paralelo",
4733
- "d6783ef5e11f3e89": "Não foi possível iniciar um chat paralelo.",
4743
"afd7cfeb929fcdbd": "O chat paralelo foi criado, mas não chegou a este dispositivo.",
4744
"0efeaa8d0ca3a757": "O chat paralelo não está mais disponível.",
4745
"61fc2531d076d396": "Não foi possível definir o modo de permissão do chat paralelo.",
apps/mobile/src/i18n/translations/ru.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "Не удалось сохранить сообщение в очереди",
1591
"b02695b75d8b050d": "Ваша правка всё ещё в поле ввода.",
1592
"6ad508d2af838010": "Возможно, оно уже начало выполняться. Ваша правка всё ещё в поле ввода.",
1593
+ "2498db230c4b87b6": "Слишком много контекста",
1594
"74e7e5c0536cda02": "Боковой чат не начат",
1595
"a0269861cbd8c727": "Задать вопрос в сторону",
1596
"d49fc7ca60395d59": "Введите вопрос после {command} и отправьте.",
1596
- "2498db230c4b87b6": "Слишком много контекста",
1597
+ "d6783ef5e11f3e89": "Не удалось начать боковой чат.",
1598
"ed68b68e83ee61bf": "Сначала начните тред {provider}",
1599
"c9852e2500018a3c": "Отправьте сообщение, прежде чем оставлять отзыв.",
1600
"7a4248cbd73fad20": "Не удалось сохранить сообщение в очереди.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "Нет архивных тредов",
1705
"ef5fd3138f95f318": "Не удалось загрузить все архивы",
1706
"26a8e439cedbce61": "Загрузка архива...",
1707
+ "cfae08fc22229b42": "Закрыть браузер",
1708
+ "a430e4548d57d722": "Назад",
1709
+ "e7b9fc04d44070b7": "Адрес",
1710
+ "a8608329f9192866": "Введите URL",
1711
+ "270506908c58ebcc": "Перезагрузить страницу",
1712
+ "f55a56936aed1cfa": "Развернуть страницу",
1713
+ "a5d51502121f1630": "Адрес {url}. Показать элементы управления браузера",
1714
"b5f8f4124236be7c": "Картинка в картинке недоступна",
1715
"47c47bbab985e718": "Не удалось открыть этот адрес",
1716
"f0287e8bebecf7c2": "Введите URL с http или https.",
1717
"536c1b1898a53eab": "Браузер",
1710
- "cfae08fc22229b42": "Закрыть браузер",
1718
"e208bda0b201c91f": "Выйти из режима «Картинка в картинке»",
1719
"d483a9b20b305301": "Картинка в картинке",
1720
"9cf840ddbea731a5": "Вкладки",
1714
- "a430e4548d57d722": "Назад",
1715
- "22fbc48063de5b8e": "Вперёд",
1716
- "e7b9fc04d44070b7": "Адрес",
1717
- "a8608329f9192866": "Введите URL",
1718
- "270506908c58ebcc": "Перезагрузить страницу",
1721
"14f99d0dac2d9681": "Как в системе",
1722
"a7e960938e75f747": "Светлое",
1723
"a6b5d3e28216f795": "Тёмное",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "Не удалось закрыть эту вкладку браузера",
1730
"c91eae915827f9e3": "Не удалось изменить область просмотра",
1731
"62dc4d3a19ff7ca0": "Закрыть вкладку",
1732
+ "1df5ebbe09388a03": "Открыть на этом устройстве",
1733
"3fdf6cbbb9876fda": "Вставить",
1734
+ "40269a025cb98db7": "Отдать управление",
1735
"61fb04cd857a1a22": "Полная перезагрузка",
1736
"863f86bb80c0ea6a": "Масштаб ({percent}%)",
1737
"8c32e9085e525c19": "Увеличить",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Очистить cookie",
1743
"9bce41be8fc55a47": "Очистить кеш",
1744
"4d7f5af0445371fd": "Параметры вкладки браузера",
1745
+ "27025b00be488485": "окружение",
1746
+ "e1ffd0532d64e52c": "Это устройство не может открывать страницы localhost",
1747
+ "f72cc72b321f93a5": "{reason} Для этой вкладки можно по-прежнему использовать транслируемый браузер.",
1748
+ "663465f828e70345": "Нет подключения к {environment}",
1749
+ "d14ca43d8ae95c78": "Не удаётся открыть {host}",
1750
+ "69e9c247d0266e9f": "Страницы localhost окружения {environment} загружаются через его подключение. Повторите попытку, когда оно восстановится.",
1751
+ "301045c720839f4d": "На порту {port} в {environment} ничего не слушает. Запустите там сервер и повторите попытку.",
1752
"0b16434dff468d30": "Загрузка отклонена.",
1753
"bbcd3776bcd3e2c5": "Скачан {fileName}",
1754
"f746b1e0bfb2ec4a": "Не сейчас",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "Страница ещё не отобразилась. Повторите попытку через мгновение.",
1768
"eeb59a631fec128d": "Картинка в картинке недоступна.",
1769
"a3640fd5194ade85": "Просмотр браузера неожиданно остановился.",
1759
- "40269a025cb98db7": "Отдать управление",
1770
"156baef53680396e": "Взять управление",
1771
"95afdc33a06d3030": "Страница запрашивает файлы.",
1772
"69c659d8b6e271cc": "Страница запрашивает файл.",
@@ -2785,22 +2795,22 @@
2795
"06a684782801e8f7": "Копировать head-ветку {branch}",
2796
"8e4f3c862193b8a5": "Изменить",
2797
"8cc970597921c38a": "Удалить {branch} из {repository}? Локальные ветки и рабочие деревья не изменятся.",
2788
- "42fd133c37a117fe": "{repository} · Офлайн",
2798
"58bda2aa88d28696": "{term, select, mr {Действия с мерж-реквестом} cr {Действия с запросом на изменение} other {Действия с пул-реквестом}}",
2799
"ffd49822d34cbd30": "Разрешить правки мейнтейнерам",
2800
"2a83c8767b3e1918": "Удаление…",
2801
"99a3c6e593d6947d": "Переподключитесь, чтобы удалить эту ветку.",
2802
+ "42fd133c37a117fe": "{repository} · Офлайн",
2803
"c83fb5e64f34fb1a": "Обзор",
2804
"8d1ad30ddb277f48": "Руководство",
2805
"3724ff240986c6da": "Закоммитить изменения",
2806
"d85877d9ef77c50c": "Изменения",
2807
"ebb089d626dfaa7c": "Загрузка изменений",
2798
- "89a7eb448db48738": "{count, plural, one {{count} тест скрыт} few {{count} теста скрыто} many {{count} тестов скрыто} other {{count} теста скрыто}}",
2808
"4050f873dc790f8f": "Параметры диффа",
2809
"81cf438219f0a618": "Перенос строк",
2810
"8ec7e405049af1f7": "Перенести черновик на эту строку",
2811
"8e5f5001f74a460f": "Добавить комментарий ревью",
2812
"8055c658cf61dd31": "Копировать строку",
2813
+ "89a7eb448db48738": "{count, plural, one {{count} тест скрыт} few {{count} теста скрыто} many {{count} тестов скрыто} other {{count} теста скрыто}}",
2814
"b4f58b68410c319f": "Перезагрузить изменения",
2815
"01cb0224aa3208c1": "Дифф недоступен",
2816
"b683d10f00d06824": "{term, select, mr {Откройте этот мерж-реквест у его провайдера, чтобы посмотреть изменения.} cr {Откройте этот запрос на изменение у его провайдера, чтобы посмотреть изменения.} other {Откройте этот пул-реквест у его провайдера, чтобы посмотреть изменения.}}",
@@ -4808,7 +4818,6 @@
4818
"986951276ab5723d": "Отвязать от треда",
4819
"a9c188a91c93fdb4": "Не удалось изменить отслеживание",
4820
"4bcfa3b976a421cf": "Боковой чат",
4811
- "d6783ef5e11f3e89": "Не удалось начать боковой чат.",
4821
"afd7cfeb929fcdbd": "Боковой чат создан, но не дошёл до этого устройства.",
4822
"0efeaa8d0ca3a757": "Боковой чат больше недоступен.",
4823
"61fc2531d076d396": "Не удалось задать режим разрешений бокового чата.",
apps/mobile/src/i18n/translations/sv.json
+20
-11
@@ -1590,10 +1590,11 @@
1590
"bdf11d0dcd29fc4c": "Kunde inte spara det köade meddelandet",
1591
"b02695b75d8b050d": "Din redigering finns kvar i inmatningsfältet.",
1592
"6ad508d2af838010": "Det kan redan ha startat. Din redigering finns kvar i inmatningsfältet.",
1593
+ "2498db230c4b87b6": "För mycket kontext",
1594
"74e7e5c0536cda02": "Sidochatten startades inte",
1595
"a0269861cbd8c727": "Ställ en sidofråga",
1596
"d49fc7ca60395d59": "Skriv frågan efter {command} och skicka den sedan.",
1596
- "2498db230c4b87b6": "För mycket kontext",
1597
+ "d6783ef5e11f3e89": "Kunde inte starta en sidochatt.",
1598
"ed68b68e83ee61bf": "Starta en {provider}-tråd först",
1599
"c9852e2500018a3c": "Skicka ett meddelande innan du skickar feedback.",
1600
"7a4248cbd73fad20": "Kunde inte spara det köade meddelandet.",
@@ -1703,19 +1704,20 @@
1704
"ad25ae072f65b934": "Inga arkiverade trådar",
1705
"ef5fd3138f95f318": "Kunde inte läsa in alla arkiv",
1706
"26a8e439cedbce61": "Läser in arkivet...",
1707
+ "cfae08fc22229b42": "Stäng webbläsaren",
1708
+ "a430e4548d57d722": "Bakåt",
1709
+ "e7b9fc04d44070b7": "Adress",
1710
+ "a8608329f9192866": "Ange en URL",
1711
+ "270506908c58ebcc": "Läs in sidan igen",
1712
+ "f55a56936aed1cfa": "Maximera sidan",
1713
+ "a5d51502121f1630": "Adress {url}. Visa webbläsarens kontroller",
1714
"b5f8f4124236be7c": "Bild-i-bild är inte tillgängligt",
1715
"47c47bbab985e718": "Kunde inte öppna den här adressen",
1716
"f0287e8bebecf7c2": "Ange en http- eller https-URL.",
1717
"536c1b1898a53eab": "Webbläsare",
1710
- "cfae08fc22229b42": "Stäng webbläsaren",
1718
"e208bda0b201c91f": "Avsluta bild-i-bild",
1719
"d483a9b20b305301": "Bild-i-bild",
1720
"9cf840ddbea731a5": "Flikar",
1714
- "a430e4548d57d722": "Bakåt",
1715
- "22fbc48063de5b8e": "Framåt",
1716
- "e7b9fc04d44070b7": "Adress",
1717
- "a8608329f9192866": "Ange en URL",
1718
- "270506908c58ebcc": "Läs in sidan igen",
1721
"14f99d0dac2d9681": "System",
1722
"a7e960938e75f747": "Ljust",
1723
"a6b5d3e28216f795": "Mörkt",
@@ -1727,7 +1729,9 @@
1729
"88a2f4158c1ceb00": "Kunde inte stänga webbläsarfliken",
1730
"c91eae915827f9e3": "Kunde inte ändra visningsytan",
1731
"62dc4d3a19ff7ca0": "Stäng flik",
1732
+ "1df5ebbe09388a03": "Öppna på den här enheten",
1733
"3fdf6cbbb9876fda": "Klistra in",
1734
+ "40269a025cb98db7": "Släpp kontrollen",
1735
"61fb04cd857a1a22": "Hård omladdning",
1736
"863f86bb80c0ea6a": "Zoom ({percent} %)",
1737
"8c32e9085e525c19": "Zooma in",
@@ -1738,6 +1742,13 @@
1742
"27e6fb07a6592a8b": "Rensa cookies",
1743
"9bce41be8fc55a47": "Rensa cache",
1744
"4d7f5af0445371fd": "Alternativ för webbläsarflik",
1745
+ "27025b00be488485": "miljön",
1746
+ "e1ffd0532d64e52c": "Den här enheten kan inte öppna localhost-sidor",
1747
+ "f72cc72b321f93a5": "{reason} Du kan fortfarande använda den strömmade webbläsaren för den här fliken.",
1748
+ "663465f828e70345": "Inte ansluten till {environment}",
1749
+ "d14ca43d8ae95c78": "Kan inte nå {host}",
1750
+ "69e9c247d0266e9f": "Sidor på localhost i {environment} laddas via dess anslutning. Försök igen när den har återanslutit.",
1751
+ "301045c720839f4d": "Inget lyssnar på port {port} i {environment}. Starta servern där och försök sedan igen.",
1752
"0b16434dff468d30": "Uppladdningen nekades.",
1753
"bbcd3776bcd3e2c5": "Laddade ned {fileName}",
1754
"f746b1e0bfb2ec4a": "Inte nu",
@@ -1756,7 +1767,6 @@
1767
"8c5bd5384cf56dfe": "Sidan har inte visats än. Försök igen om en stund.",
1768
"eeb59a631fec128d": "Bild-i-bild är inte tillgängligt.",
1769
"a3640fd5194ade85": "Webbläsarvisaren stoppades oväntat.",
1759
- "40269a025cb98db7": "Släpp kontrollen",
1770
"156baef53680396e": "Ta kontrollen",
1771
"95afdc33a06d3030": "Sidan ber om filer.",
1772
"69c659d8b6e271cc": "Sidan ber om en fil.",
@@ -2737,22 +2747,22 @@
2747
"06a684782801e8f7": "Kopiera huvudgrenen {branch}",
2748
"8e4f3c862193b8a5": "Redigera",
2749
"8cc970597921c38a": "Ta bort {branch} från {repository}? Lokala grenar och worktrees ändras inte.",
2740
- "42fd133c37a117fe": "{repository} · Offline",
2750
"58bda2aa88d28696": "Åtgärder för {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}}",
2751
"ffd49822d34cbd30": "Tillåt ändringar från underhållare",
2752
"2a83c8767b3e1918": "Tar bort…",
2753
"99a3c6e593d6947d": "Återanslut för att ta bort grenen.",
2754
+ "42fd133c37a117fe": "{repository} · Offline",
2755
"c83fb5e64f34fb1a": "Översikt",
2756
"8d1ad30ddb277f48": "Guide",
2757
"3724ff240986c6da": "Committa ändringar",
2758
"d85877d9ef77c50c": "Ändringar",
2759
"ebb089d626dfaa7c": "Läser in ändringar",
2750
- "89a7eb448db48738": "{count, plural, one {{count} test dolt} other {{count} tester dolda}}",
2760
"4050f873dc790f8f": "Diff-alternativ",
2761
"81cf438219f0a618": "Radbrytning",
2762
"8ec7e405049af1f7": "Flytta utkastet till den här raden",
2763
"8e5f5001f74a460f": "Lägg till granskningskommentar",
2764
"8055c658cf61dd31": "Kopiera rad",
2765
+ "89a7eb448db48738": "{count, plural, one {{count} test dolt} other {{count} tester dolda}}",
2766
"b4f58b68410c319f": "Läs in ändringarna igen",
2767
"01cb0224aa3208c1": "Diffen är inte tillgänglig",
2768
"b683d10f00d06824": "Öppna den här {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}} hos leverantören för att se ändringarna.",
@@ -4736,7 +4746,6 @@
4746
"986951276ab5723d": "Ta bort länk från tråd",
4747
"a9c188a91c93fdb4": "Kunde inte ändra bevakningen",
4748
"4bcfa3b976a421cf": "Sidochatt",
4739
- "d6783ef5e11f3e89": "Kunde inte starta en sidochatt.",
4749
"afd7cfeb929fcdbd": "Sidochatten skapades, men den nådde inte den här enheten.",
4750
"0efeaa8d0ca3a757": "Sidochatten är inte längre tillgänglig.",
4751
"61fc2531d076d396": "Kunde inte ange sidochattens behörighetsläge.",
apps/mobile/src/i18n/translations/zh.json
+20
-11
@@ -1591,10 +1591,11 @@
1591
"bdf11d0dcd29fc4c": "无法保存排队消息",
1592
"b02695b75d8b050d": "你的编辑仍在输入框中。",
1593
"6ad508d2af838010": "它可能已经开始处理。你的编辑仍在输入框中。",
1594
+ "2498db230c4b87b6": "上下文过多",
1595
"74e7e5c0536cda02": "侧聊未开始",
1596
"a0269861cbd8c727": "问一个旁支问题",
1597
"d49fc7ca60395d59": "在 {command} 后输入问题,然后发送。",
1597
- "2498db230c4b87b6": "上下文过多",
1598
+ "d6783ef5e11f3e89": "无法开始侧聊。",
1599
"ed68b68e83ee61bf": "请先开始一个 {provider} 会话",
1600
"c9852e2500018a3c": "提交反馈前请先发送一条消息。",
1601
"7a4248cbd73fad20": "保存排队消息失败。",
@@ -1704,19 +1705,20 @@
1705
"ad25ae072f65b934": "没有已归档会话",
1706
"ef5fd3138f95f318": "无法加载全部归档",
1707
"26a8e439cedbce61": "正在加载归档...",
1708
+ "cfae08fc22229b42": "关闭浏览器",
1709
+ "a430e4548d57d722": "后退",
1710
+ "e7b9fc04d44070b7": "地址",
1711
+ "a8608329f9192866": "输入 URL",
1712
+ "270506908c58ebcc": "重新加载页面",
1713
+ "f55a56936aed1cfa": "最大化页面",
1714
+ "a5d51502121f1630": "地址 {url}。显示浏览器控件",
1715
"b5f8f4124236be7c": "画中画不可用",
1716
"47c47bbab985e718": "无法打开此地址",
1717
"f0287e8bebecf7c2": "请输入 http 或 https URL。",
1718
"536c1b1898a53eab": "浏览器",
1711
- "cfae08fc22229b42": "关闭浏览器",
1719
"e208bda0b201c91f": "退出画中画",
1720
"d483a9b20b305301": "画中画",
1721
"9cf840ddbea731a5": "标签页",
1715
- "a430e4548d57d722": "后退",
1716
- "22fbc48063de5b8e": "前进",
1717
- "e7b9fc04d44070b7": "地址",
1718
- "a8608329f9192866": "输入 URL",
1719
- "270506908c58ebcc": "重新加载页面",
1722
"14f99d0dac2d9681": "跟随系统",
1723
"a7e960938e75f747": "浅色",
1724
"a6b5d3e28216f795": "深色",
@@ -1728,7 +1730,9 @@
1730
"88a2f4158c1ceb00": "无法关闭此浏览器标签页",
1731
"c91eae915827f9e3": "无法更改视口",
1732
"62dc4d3a19ff7ca0": "关闭标签页",
1733
+ "1df5ebbe09388a03": "在此设备上打开",
1734
"3fdf6cbbb9876fda": "粘贴",
1735
+ "40269a025cb98db7": "释放控制",
1736
"61fb04cd857a1a22": "强制重新加载",
1737
"863f86bb80c0ea6a": "缩放({percent}%)",
1738
"8c32e9085e525c19": "放大",
@@ -1739,6 +1743,13 @@
1743
"27e6fb07a6592a8b": "清除 Cookie",
1744
"9bce41be8fc55a47": "清除缓存",
1745
"4d7f5af0445371fd": "浏览器标签页选项",
1746
+ "27025b00be488485": "该环境",
1747
+ "e1ffd0532d64e52c": "此设备无法打开 localhost 页面",
1748
+ "f72cc72b321f93a5": "{reason} 你仍可以为此标签页使用流式浏览器。",
1749
+ "663465f828e70345": "未连接到 {environment}",
1750
+ "d14ca43d8ae95c78": "无法访问 {host}",
1751
+ "69e9c247d0266e9f": "{environment} 上的 localhost 页面通过其连接加载。重新连接后请再试一次。",
1752
+ "301045c720839f4d": "{environment} 上的端口 {port} 没有任何服务在监听。请在那里启动服务器,然后再试一次。",
1753
"0b16434dff468d30": "上传被拒绝。",
1754
"bbcd3776bcd3e2c5": "已下载 {fileName}",
1755
"f746b1e0bfb2ec4a": "暂不",
@@ -1757,7 +1768,6 @@
1768
"8c5bd5384cf56dfe": "页面尚未显示。请稍后重试。",
1769
"eeb59a631fec128d": "画中画不可用。",
1770
"a3640fd5194ade85": "浏览器查看器意外停止。",
1760
- "40269a025cb98db7": "释放控制",
1771
"156baef53680396e": "接管控制",
1772
"95afdc33a06d3030": "页面请求选择文件。",
1773
"69c659d8b6e271cc": "页面请求选择一个文件。",
@@ -2734,22 +2744,22 @@
2744
"06a684782801e8f7": "复制头部分支 {branch}",
2745
"8e4f3c862193b8a5": "编辑",
2746
"8cc970597921c38a": "从 {repository} 删除 {branch}?本地分支和工作树不会更改。",
2737
- "42fd133c37a117fe": "{repository} · 离线",
2747
"58bda2aa88d28696": "{term, select, mr {MR} cr {change request} other {PR}} 操作",
2748
"ffd49822d34cbd30": "允许维护者编辑",
2749
"2a83c8767b3e1918": "正在删除…",
2750
"99a3c6e593d6947d": "重新连接以删除此分支。",
2751
+ "42fd133c37a117fe": "{repository} · 离线",
2752
"c83fb5e64f34fb1a": "概览",
2753
"8d1ad30ddb277f48": "导览",
2754
"3724ff240986c6da": "提交更改",
2755
"d85877d9ef77c50c": "改动",
2756
"ebb089d626dfaa7c": "正在加载更改",
2747
- "89a7eb448db48738": "{count, plural, other {已隐藏 {count} 个测试}}",
2757
"4050f873dc790f8f": "差异选项",
2758
"81cf438219f0a618": "自动换行",
2759
"8ec7e405049af1f7": "将草稿移到此行",
2760
"8e5f5001f74a460f": "添加审查评论",
2761
"8055c658cf61dd31": "复制行",
2762
+ "89a7eb448db48738": "{count, plural, other {已隐藏 {count} 个测试}}",
2763
"b4f58b68410c319f": "重新加载更改",
2764
"01cb0224aa3208c1": "差异不可用",
2765
"b683d10f00d06824": "在提供方上打开此 {term, select, mr {merge request} cr {change request} other {pull request}} 以查看更改。",
@@ -4719,7 +4729,6 @@
4729
"986951276ab5723d": "取消与会话的关联",
4730
"a9c188a91c93fdb4": "无法更改关注状态",
4731
"4bcfa3b976a421cf": "侧聊",
4722
- "d6783ef5e11f3e89": "无法开始侧聊。",
4732
"afd7cfeb929fcdbd": "侧聊已创建,但未同步到此设备。",
4733
"0efeaa8d0ca3a757": "这段侧聊已不可用。",
4734
"61fc2531d076d396": "无法设置侧聊的权限模式。",
apps/mobile/src/lib/reserved-regions.test.ts
+40
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
2
import {
3
deriveBottomControlInsets,
4
deriveContentSideInsets,
5
+ deriveSharedTopBand,
6
type NativeLayoutMetrics,
7
} from "./reserved-regions";
8
import { deriveLayout, deriveWorkspacePaneLayout } from "./layout";
@@ -123,6 +124,45 @@ describe("content side insets around reserved regions", () => {
124
});
125
});
126
127
+describe("a bar sharing the top band with the system status", () => {
128
+ // The folded Duo with horizontal bars: its status block sits at the right of a tall top band.
129
+ const foldedDuo: NativeLayoutMetrics = {
130
+ width: 466,
131
+ height: 678,
132
+ horizontalSizeClass: "compact",
133
+ verticalBarEdge: "none",
134
+ safeArea: { top: 82, bottom: 34, left: 0, right: 0 },
135
+ reservedRegions: [
136
+ { kind: "occlusion", x: 399.67, y: 29.33, width: 37, height: 37 },
137
+ { kind: "occlusion", x: 266, y: 0, width: 200, height: 82 },
138
+ ],
139
+ };
140
+
141
+ it.each([
142
+ ["status block on the right", foldedDuo, { height: 82, left: 0, right: 200 }],
143
+ [
144
+ "status block on the left",
145
+ {
146
+ ...foldedDuo,
147
+ reservedRegions: [{ kind: "occlusion" as const, x: 0, y: 0, width: 200, height: 82 }],
148
+ },
149
+ { height: 82, left: 200, right: 0 },
150
+ ],
151
+ ["no status block (a notch or island)", { ...foldedDuo, reservedRegions: [] }, null],
152
+ [
153
+ "a block across the middle",
154
+ {
155
+ ...foldedDuo,
156
+ reservedRegions: [{ kind: "occlusion" as const, x: 133, y: 0, width: 200, height: 82 }],
157
+ },
158
+ null,
159
+ ],
160
+ ["no top safe area", { ...foldedDuo, safeArea: { ...foldedDuo.safeArea, top: 0 } }, null],
161
+ ])("%s", (_, metrics, expected) => {
162
+ expect(deriveSharedTopBand(metrics)).toEqual(expected);
163
+ });
164
+});
165
+
166
describe("Duo workspace sizing", () => {
167
it("shows both columns on the unfolded inner display in portrait", () => {
168
// Reported by the iOS 27.1 Duo simulator: no side bar or fold, only the hinge.
apps/mobile/src/lib/reserved-regions.ts
+22
@@ -68,3 +68,25 @@ export function deriveBottomControlInsets(metrics: NativeLayoutMetrics | null) {
68
}
69
return { left, right: metrics.width - right, bottom: metrics.height - bottom };
70
}
71
+
72
+/**
73
+ * Where a bar can share the top safe area with the system status, as Safari does on iPhone Duo:
74
+ * the status block covers one end of that band, so the rest of it is free. Null otherwise.
75
+ */
76
+export function deriveSharedTopBand(metrics: NativeLayoutMetrics | null) {
77
+ if (!metrics || metrics.safeArea.top <= 0) return null;
78
+ const blocks = metrics.reservedRegions.filter(
79
+ (region) =>
80
+ region.kind === "occlusion" && region.y <= 0 && region.height >= metrics.safeArea.top - 1,
81
+ );
82
+ const [block] = blocks;
83
+ if (blocks.length !== 1 || !block) return null;
84
+ const height = metrics.safeArea.top;
85
+ if (block.x > metrics.width / 2 && block.x + block.width >= metrics.width - 1) {
86
+ return { height, left: 0, right: metrics.width - block.x };
87
+ }
88
+ if (block.x <= 1 && block.x + block.width < metrics.width / 2) {
89
+ return { height, left: block.x + block.width, right: 0 };
90
+ }
91
+ return null;
92
+}
apps/mobile/src/state/previewTunnel.ts
new
+12
@@ -0,0 +1,12 @@
1
+import { createPreviewTunnelUrlReader } from "@t3tools/client-runtime/state/previewTunnel";
2
+
3
+import { connectionAtomRuntime } from "../connection/runtime";
4
+import { appAtomRegistry } from "./atom-registry";
5
+import { environmentSession } from "./session";
6
+
7
+/** The environment's tunnel WebSocket URL with a live media ticket, or null when unreachable. */
8
+export const readPreviewTunnelUrl = createPreviewTunnelUrlReader({
9
+ runtime: connectionAtomRuntime,
10
+ registry: appAtomRegistry,
11
+ preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
12
+});
apps/web/src/state/previewTunnel.ts
+6
-52
@@ -1,58 +1,12 @@
1
-import { environmentEndpointUrl } from "@t3tools/client-runtime/environment";
2
-import { mintMediaTicket } from "@t3tools/client-runtime/state/deviceHubAccess";
3
-import type { EnvironmentId } from "@t3tools/contracts";
4
-import * as DateTime from "effect/DateTime";
5
-import * as Effect from "effect/Effect";
6
-import * as Option from "effect/Option";
7
-import * as Redacted from "effect/Redacted";
8
-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
1
+import { createPreviewTunnelUrlReader } from "@t3tools/client-runtime/state/previewTunnel";
2
3
import { connectionAtomRuntime } from "../connection/runtime";
4
import { appAtomRegistry } from "../rpc/atomRegistry";
5
import { environmentSession } from "./session";
6
14
-const PREVIEW_TUNNEL_PATH = "/api/preview/tunnel";
15
-const TICKET_REFRESH_MARGIN_MS = 30_000;
16
-
17
-// Reading the prepared connection here re-mints for the route in use after a route switch.
18
-const previewTunnelAccessAtom = Atom.family((environmentId: EnvironmentId) =>
19
- connectionAtomRuntime
20
- .atom((get) => {
21
- const prepared = Option.getOrNull(
22
- get(environmentSession.preparedConnectionValueAtom(environmentId)),
23
- );
24
- // Desktop main cannot send this window's cookies, so only ticketed connections tunnel.
25
- if (prepared === null || prepared.httpAuthorization === null) return Effect.succeed(null);
26
- return mintMediaTicket(prepared).pipe(
27
- Effect.map((ticket) => {
28
- const url = new URL(
29
- environmentEndpointUrl(prepared.httpBaseUrl, PREVIEW_TUNNEL_PATH).replace(
30
- /^http/,
31
- "ws",
32
- ),
33
- );
34
- url.searchParams.set("wsTicket", Redacted.value(ticket.ticket));
35
- return { url: url.toString(), expiresAtMillis: DateTime.toEpochMillis(ticket.expiresAt) };
36
- }),
37
- );
38
- })
39
- .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`preview-tunnel-access:${environmentId}`)),
40
-);
41
-
7
/** The environment's tunnel WebSocket URL with a live media ticket, or null when unreachable. */
43
-export function readPreviewTunnelUrl(environmentId: EnvironmentId): Promise<string | null> {
44
- const atom = previewTunnelAccessAtom(environmentId);
45
- const current = appAtomRegistry.get(atom);
46
- const reusable =
47
- AsyncResult.isSuccess(current) &&
48
- current.value !== null &&
49
- current.value.expiresAtMillis - Date.now() > TICKET_REFRESH_MARGIN_MS;
50
- if (!reusable && !current.waiting) appAtomRegistry.refresh(atom);
51
- return Effect.runPromise(
52
- AtomRegistry.getResult(appAtomRegistry, atom, { suspendOnWaiting: true }).pipe(
53
- Effect.map((access) => access?.url ?? null),
54
- Effect.timeout("10 seconds"),
55
- Effect.orElseSucceed(() => null),
56
- ),
57
- );
58
-}
8
+export const readPreviewTunnelUrl = createPreviewTunnelUrlReader({
9
+ runtime: connectionAtomRuntime,
10
+ registry: appAtomRegistry,
11
+ preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
12
+});
docs/internals/remote.md
+3
-1
@@ -178,7 +178,9 @@ undo by accident:
178
connection, which also makes the tunnel follow a route switch.
179
- **Owner check, not auth.** Chromium can't authenticate to a SOCKS proxy, so any local process
180
can connect to the listener and ride this user's tunnel. On Linux the listener looks the client
181
- up in `/proc/net/tcp` and refuses other users. macOS and Windows have no such check yet.
181
+ up in `/proc/net/tcp` and refuses other users. macOS and Windows have no such check yet. The
182
+ mobile app's device preview has the same listener while it is open: iOS suspends other apps, but
183
+ Android lets any app reach it, and apps cannot see another app's socket owner there.
184
- **System browser links** have no tunnel. They keep the private-network rewrite in
185
[`browserTargetResolver.ts`](../../apps/web/src/browser/browserTargetResolver.ts).
186
docs/user/remote-access.md
+11
-1
@@ -289,7 +289,17 @@ host cannot be reached, the tab shows a connection error; a `localhost`,
289
Other names that point at your computer, such as `/etc/hosts` entries, still
290
do. These tabs ignore your system proxy settings, so they can't reach a host
291
you connect to only through a proxy or over HTTPS with a privately issued
292
-certificate. The web and mobile apps keep streaming.
292
+certificate. The web app keeps streaming.
293
+
294
+On iPhone, iPad, and Android, a tab showing one of the host's `localhost` pages
295
+has **Open on this device** in its menu. So does a long press on a `localhost`
296
+link in a chat. It opens the page in the phone's own browser view, at the same
297
+`localhost` address, so it scrolls and responds to touch natively. Like the
298
+desktop app, it never opens a server on the phone itself. The streamed tab
299
+stays where it was, and agents keep using it. Each host keeps its own cookies
300
+and site data on the phone. On iPhone and iPad the page runs under a stand-in
301
+address while the address bar shows `localhost`, so browser features that need
302
+a secure page, such as the clipboard or service workers, aren't available there.
303
304
The first tab downloads a headless Chrome, about 120 MB, into the T3 home. It
305
is the same browser [HTML renders](html-renders.md) use, so a host downloads it
packages/client-runtime/package.json
+4
@@ -271,6 +271,10 @@
271
"types": "./src/state/deviceHubAccess.ts",
272
"default": "./src/state/deviceHubAccess.ts"
273
},
274
+ "./state/previewTunnel": {
275
+ "types": "./src/state/previewTunnel.ts",
276
+ "default": "./src/state/previewTunnel.ts"
277
+ },
278
"./state/peerLinks": {
279
"types": "./src/state/peerLinks.ts",
280
"default": "./src/state/peerLinks.ts"
packages/client-runtime/src/state/previewTunnel.test.ts
new
+56
@@ -0,0 +1,56 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import { EnvironmentId } from "@t3tools/contracts";
3
+import * as Effect from "effect/Effect";
4
+import * as Fiber from "effect/Fiber";
5
+import * as Layer from "effect/Layer";
6
+import * as Option from "effect/Option";
7
+import { HttpClient, HttpClientResponse } from "effect/http";
8
+import { Atom, AtomRegistry } from "effect/reactivity";
9
+
10
+import { BearerConnectionTarget, type PreparedConnection } from "../connection/model.ts";
11
+import { createPreviewTunnelUrlReader } from "./previewTunnel.ts";
12
+
13
+const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
14
+const PREPARED: PreparedConnection = {
15
+ environmentId: ENVIRONMENT_ID,
16
+ label: "Remote environment",
17
+ httpBaseUrl: "https://remote.example.test",
18
+ socketUrl: "wss://remote.example.test/ws",
19
+ httpAuthorization: { _tag: "Bearer", token: "token" },
20
+ target: new BearerConnectionTarget({
21
+ environmentId: ENVIRONMENT_ID,
22
+ label: "Remote environment",
23
+ connectionId: "connection-1",
24
+ }),
25
+};
26
+
27
+describe("preview tunnel url", () => {
28
+ it.live("waits for a reconnecting environment instead of refusing the page", () =>
29
+ Effect.gen(function* () {
30
+ const prepared = Atom.make(Option.none<PreparedConnection>());
31
+ const client = HttpClient.make((request) =>
32
+ Effect.succeed(
33
+ HttpClientResponse.fromWeb(
34
+ request,
35
+ Response.json({ ticket: "media-ticket", expiresAt: "2999-01-01T00:00:00.000Z" }),
36
+ ),
37
+ ),
38
+ );
39
+ const registry = AtomRegistry.make();
40
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
41
+ const read = createPreviewTunnelUrlReader({
42
+ runtime: Atom.runtime(Layer.succeed(HttpClient.HttpClient, client)),
43
+ registry,
44
+ preparedConnectionAtom: () => prepared,
45
+ });
46
+
47
+ const pending = yield* Effect.forkChild(Effect.promise(() => read(ENVIRONMENT_ID)));
48
+ yield* Effect.yieldNow;
49
+ registry.set(prepared, Option.some(PREPARED));
50
+
51
+ expect(yield* Fiber.join(pending)).toBe(
52
+ "wss://remote.example.test/api/preview/tunnel?wsTicket=media-ticket",
53
+ );
54
+ }),
55
+ );
56
+});
packages/client-runtime/src/state/previewTunnel.ts
new
+75
@@ -0,0 +1,75 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import * as Clock from "effect/Clock";
3
+import * as DateTime from "effect/DateTime";
4
+import * as Effect from "effect/Effect";
5
+import * as Option from "effect/Option";
6
+import * as Redacted from "effect/Redacted";
7
+import type { HttpClient } from "effect/http";
8
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
9
+
10
+import type { PreparedConnection } from "../connection/model.ts";
11
+import { environmentEndpointUrl } from "../environment/endpoint.ts";
12
+import { mintMediaTicket } from "./deviceHubAccess.ts";
13
+
14
+const TICKET_REFRESH_MARGIN_MS = 30_000;
15
+
16
+/**
17
+ * Reads an environment's loopback tunnel URL (`/api/preview/tunnel` with a media ticket) for a
18
+ * native webview proxy. Tickets are reused until shortly before they expire, and reading the
19
+ * prepared connection re-mints for the route in use after a route switch.
20
+ */
21
+export function createPreviewTunnelUrlReader<R, E>(input: {
22
+ readonly runtime: Atom.AtomRuntime<HttpClient.HttpClient | R, E>;
23
+ readonly registry: AtomRegistry.AtomRegistry;
24
+ readonly preparedConnectionAtom: (
25
+ environmentId: EnvironmentId,
26
+ ) => Atom.Atom<Option.Option<PreparedConnection>>;
27
+}) {
28
+ const accessAtom = Atom.family((environmentId: EnvironmentId) =>
29
+ input.runtime
30
+ .atom((get) => {
31
+ const prepared = Option.getOrNull(get(input.preparedConnectionAtom(environmentId)));
32
+ // Mid-reconnect, wait for the connection rather than refuse the page; the read times out.
33
+ if (prepared === null) return Effect.never;
34
+ // The proxy cannot send cookies, so only ticketed connections tunnel.
35
+ if (prepared.httpAuthorization === null) return Effect.succeed(null);
36
+ return mintMediaTicket(prepared).pipe(
37
+ Effect.map((ticket) => {
38
+ const url = new URL(
39
+ environmentEndpointUrl(prepared.httpBaseUrl, "/api/preview/tunnel").replace(
40
+ /^http/,
41
+ "ws",
42
+ ),
43
+ );
44
+ url.searchParams.set("wsTicket", Redacted.value(ticket.ticket));
45
+ return {
46
+ url: url.toString(),
47
+ expiresAtMillis: DateTime.toEpochMillis(ticket.expiresAt),
48
+ };
49
+ }),
50
+ );
51
+ })
52
+ .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`preview-tunnel-access:${environmentId}`)),
53
+ );
54
+
55
+ return (environmentId: EnvironmentId): Promise<string | null> =>
56
+ Effect.runPromise(
57
+ Effect.gen(function* () {
58
+ const atom = accessAtom(environmentId);
59
+ const current = input.registry.get(atom);
60
+ const now = yield* Clock.currentTimeMillis;
61
+ const reusable =
62
+ AsyncResult.isSuccess(current) &&
63
+ current.value !== null &&
64
+ current.value.expiresAtMillis - now > TICKET_REFRESH_MARGIN_MS;
65
+ if (!reusable && !current.waiting) input.registry.refresh(atom);
66
+ const access = yield* AtomRegistry.getResult(input.registry, atom, {
67
+ suspendOnWaiting: true,
68
+ });
69
+ return access?.url ?? null;
70
+ }).pipe(
71
+ Effect.timeout("10 seconds"),
72
+ Effect.orElseSucceed(() => null),
73
+ ),
74
+ );
75
+}
pnpm-lock.yaml
+9
-9
@@ -599,7 +599,7 @@ importers:
599
version: 7.5.1(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
600
'@react-navigation/native-stack':
601
specifier: 7.21.0
602
- version: 7.21.0(patch_hash=990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42)(e4f4bc252fa3d94b48061e5b29ad092f)
602
+ version: 7.21.0(patch_hash=990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42)(80a27ad2d896d41b044f138b2bcfd285)
603
'@t3tools/client-runtime':
604
specifier: workspace:*
605
version: link:../../packages/client-runtime
@@ -787,8 +787,8 @@ importers:
787
specifier: ~5.11.1
788
version: 5.11.1(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
789
react-native-screens:
790
- specifier: file:deps/react-native-screens-5.0.0-t3.59.tgz
791
- version: file:apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
790
+ specifier: file:deps/react-native-screens-5.0.0-t3.61.tgz
791
+ version: file:apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
792
react-native-svg:
793
specifier: 15.16.1
794
version: 15.16.1(patch_hash=110f9243ffad03654ce40dd1cdb09f01af16b8fa2ccb2b2cd3d62e682c180399)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -11671,9 +11671,9 @@ packages:
11671
react: '*'
11672
react-native: '*'
11673
11674
- react-native-screens@file:apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz:
11675
- resolution: {integrity: sha512-HeWFWrA4IvwVJUW+c2B6NnFJIVpgoWQeoHWM6P9h+iHTMFxEhcKOtka6pNg0MQRKLroyPuwHpvvWo8UrEYBWjA==, tarball: file:apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz}
11676
- version: 5.0.0-t3.59
11674
+ react-native-screens@file:apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz:
11675
+ resolution: {integrity: sha512-uPb+53SUMB4B30JIqonBTGY3GyKrFpA98FnWYJUDzEDzV2V8pb+f5kSnu9TPpO2jU89znSNYpzABqRRHMZ+KDw==, tarball: file:apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz}
11676
+ version: 5.0.0-t3.61
11677
peerDependencies:
11678
react: '*'
11679
react-native: '*'
@@ -16737,7 +16737,7 @@ snapshots:
16737
optionalDependencies:
16738
'@react-native-masked-view/masked-view': 0.3.2(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
16739
16740
- '@react-navigation/native-stack@7.21.0(patch_hash=990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42)(e4f4bc252fa3d94b48061e5b29ad092f)':
16740
+ '@react-navigation/native-stack@7.21.0(patch_hash=990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42)(80a27ad2d896d41b044f138b2bcfd285)':
16741
dependencies:
16742
'@react-navigation/elements': 2.9.45(83450c2b8dad8f97d4bec4849f35b99e)
16743
'@react-navigation/native': 7.5.1(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
@@ -16745,7 +16745,7 @@ snapshots:
16745
react: 19.3.0
16746
react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6)
16747
react-native-safe-area-context: 5.11.1(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
16748
- react-native-screens: file:apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
16748
+ react-native-screens: file:apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
16749
sf-symbols-typescript: 2.2.0
16750
warn-once: 0.1.1
16751
transitivePeerDependencies:
@@ -22594,7 +22594,7 @@ snapshots:
22594
react: 19.3.0
22595
react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6)
22596
22597
- react-native-screens@file:apps/mobile/deps/react-native-screens-5.0.0-t3.59.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0):
22597
+ react-native-screens@file:apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0):
22598
dependencies:
22599
react: 19.3.0
22600
react-freeze: 1.0.4(react@19.3.0)