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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 75 additions & 20 deletions app/src/main/assets/scripts/andcode-browser-mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,37 @@

COMMAND_FILE = Path(".and-code") / "browser-command.json"
STATUS_FILE = Path(".and-code") / "browser-status.json"
# The app publishes its devtools socket name here: /proc/net/unix is unreadable from the guest on
# current Android (SELinux denies it to untrusted_app), so the socket cannot be found by scanning.
DEVTOOLS_FILE = Path(".and-code") / "browser-devtools.txt"
DEVTOOLS_PREFIX = "webview_devtools_remote_"


def _published_devtools_socket() -> str | None:
"""The socket name the app published, if something is actually listening on it."""
try:
name = DEVTOOLS_FILE.read_text(encoding="ascii").strip()
except (OSError, UnicodeDecodeError):
return None
if not name.startswith(DEVTOOLS_PREFIX):
return None
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
probe.settimeout(2)
try:
probe.connect("\0" + name)
except OSError:
return None
finally:
probe.close()
return name


def _find_devtools_socket() -> str | None:
# The published name is this app's own socket; prefer it so a scan can never pick another
# app's WebView (several processes use the same ``webview_devtools_remote_<pid>`` prefix).
published = _published_devtools_socket()
if published is not None:
return published
try:
with open("/proc/net/unix", encoding="ascii") as fh:
lines = fh.readlines()
Expand All @@ -50,6 +78,52 @@ class CdpError(RuntimeError):
pass


def _read_http_body(sock: socket.socket) -> bytes:
"""Reads one HTTP response body, honouring Content-Length or chunked encoding.

The WebView's ``/json`` endpoint keeps the connection open after the body and may end it with
whitespace, so waiting for the socket to close (or for the text to end with ``]``) blocks until
the timeout on every call. Read exactly what the headers promise instead.
"""
data = b""
while b"\r\n\r\n" not in data:
chunk = sock.recv(65536)
if not chunk:
raise CdpError("socket closed while reading the CDP response head")
data += chunk
head, body = data.split(b"\r\n\r\n", 1)
headers: dict[str, str] = {}
for line in head.split(b"\r\n")[1:]:
key, _, value = line.partition(b":")
headers[key.strip().lower().decode("ascii", "replace")] = value.strip().decode("ascii", "replace")
if "chunked" in headers.get("transfer-encoding", "").lower():
decoded = b""
while True:
while b"\r\n" not in body:
chunk = sock.recv(65536)
if not chunk:
raise CdpError("socket closed inside a chunked CDP response")
body += chunk
size_line, body = body.split(b"\r\n", 1)
size = int(size_line.split(b";", 1)[0], 16)
while len(body) < size + 2:
chunk = sock.recv(65536)
if not chunk:
raise CdpError("socket closed inside a chunked CDP response")
body += chunk
decoded += body[:size]
body = body[size + 2:]
if size == 0:
return decoded
length = int(headers.get("content-length", "0"))
while len(body) < length:
chunk = sock.recv(65536)
if not chunk:
raise CdpError("socket closed before the CDP response body was complete")
body += chunk
return body[:length]


class _UnixWs:
"""Minimal WebSocket client (text frames) over an AF_UNIX abstract socket."""

Expand Down Expand Up @@ -145,28 +219,9 @@ def list_targets(self) -> list[dict]:
sock = self._connect()
try:
sock.sendall(b"GET /json HTTP/1.1\r\nHost: localhost\r\n\r\n")
data = b""
while not data.endswith(b"]"):
chunk = sock.recv(65536)
if not chunk:
break
data += chunk
body = _read_http_body(sock)
finally:
sock.close()
body = data.split(b"\r\n\r\n", 1)[1] if b"\r\n\r\n" in data else data
if b"\r\n0\r\n\r\n" in body:
chunks = []
rest = body
while rest:
size_end = rest.find(b"\r\n")
if size_end < 0:
break
size = int(rest[:size_end], 16)
if size == 0:
break
chunks.append(rest[size_end + 2 : size_end + 2 + size])
rest = rest[size_end + 2 + size + 2 :]
body = b"".join(chunks)
return json.loads(body)

def open_page_session(self) -> "_PageSession":
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.yugahashimoto.andcode.data.browser

import android.content.Context
import android.content.SharedPreferences

/**
* Remembers the page the guest browser was last on, so reopening it resumes there instead of
* starting blank. Sign-ins are not stored here: they live in the WebView's own cookie store and
* keep working on their own.
*/
class GuestBrowserLastUrl(
private val preferences: SharedPreferences,
) {
/** The last web page visited, or null before one has been visited. */
fun load(): String? = stored()?.takeIf(::isWebUrl)

/** Keeps [url] as the page to resume; non-web pages leave the previous one in place. */
@Synchronized
fun save(url: String?) {
val value = url?.takeIf(::isWebUrl) ?: return
if (value == stored()) return
preferences.edit().putString(KEY_URL, value).apply()
}

private fun isWebUrl(url: String): Boolean =
url.startsWith("https://", ignoreCase = true) || url.startsWith("http://", ignoreCase = true)

@Synchronized
private fun stored(): String? = runCatching { preferences.getString(KEY_URL, null) }.getOrNull()

companion object {
internal const val PREFS_NAME = "guest_browser"
internal const val KEY_URL = "last_url"

fun create(context: Context): GuestBrowserLastUrl =
GuestBrowserLastUrl(
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE),
)
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.yugahashimoto.andcode.feature.browser

import android.os.Process
import com.yugahashimoto.andcode.core.storage.DeviceStorage
import com.yugahashimoto.andcode.feature.workspace.WorkspaceFolders
import com.yugahashimoto.andcode.runtime.LocalAgent
Expand All @@ -9,6 +10,7 @@ import java.net.URI

internal const val BROWSER_COMMAND_FILE = ".and-code/browser-command.json"
internal const val BROWSER_STATUS_FILE = ".and-code/browser-status.json"
internal const val BROWSER_DEVTOOLS_FILE = ".and-code/browser-devtools.txt"

internal const val BROWSER_STATUS_AWAITING_USER = "awaiting_user"
internal const val BROWSER_STATUS_USER = "user"
Expand Down Expand Up @@ -53,6 +55,25 @@ internal fun readBrowserStatus(file: File): String? =
JSONObject(file.readText()).optString("state").takeIf { it.isNotBlank() }
}.getOrNull()

/**
* Publishes the name of this app's WebView devtools socket (`webview_devtools_remote_<pid>`) for the
* in-guest MCP server. The guest cannot read `/proc/net/unix` on current Android (SELinux denies it
* to `untrusted_app`), so it cannot discover the socket by scanning; it can still connect to it once
* it knows the name. Rewritten only when it changes, as this runs on every poll.
*/
internal fun publishDevtoolsSocketName(
workspaceDir: File,
pid: Int = Process.myPid(),
) {
runCatching {
val file = File(workspaceDir, BROWSER_DEVTOOLS_FILE)
val name = "webview_devtools_remote_$pid"
if (file.isFile && file.readText() == name) return
file.parentFile?.mkdirs()
file.writeText(name)
}
}

/**
* Resolves the active guest workspace to the same host folder its PRoot process sees, or null when
* the workspace is remote or the runtime is not local.
Expand Down Expand Up @@ -94,6 +115,9 @@ internal fun consumeBrowserCommand(
val workspace =
activeWorkspaceHostDirectory(workspacePath, agent, runtimeDirectory, deviceStorage)
?: return null
// The devtools socket only exists after the user's agent-control opt-in, so the name is
// published under the same opt-in.
if (allowRemotePreview) publishDevtoolsSocketName(workspace)
val commandFile = File(workspace, BROWSER_COMMAND_FILE)
if (!commandFile.isFile) return null
val command = JSONObject(commandFile.readText())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.yugahashimoto.andcode.R
import com.yugahashimoto.andcode.data.browser.GuestBrowserLastUrl

/** In-app browser for pages served inside the guest runtime (e.g. http://127.0.0.1:PORT/). */
@OptIn(ExperimentalMaterial3Api::class)
Expand All @@ -48,7 +50,12 @@ fun GuestBrowserScreen(
agentControlEnabled: Boolean = false,
onEnableAgentControl: (() -> Unit)? = null,
) {
var urlInput by rememberSaveable { mutableStateOf(initialUrl) }
val context = LocalContext.current
val lastUrl = remember(context) { GuestBrowserLastUrl.create(context) }
// An explicit URL (agent `browser_show`, a preview handoff) wins; otherwise resume the page the
// user was last on instead of opening blank.
val startUrl = remember(initialUrl, lastUrl) { initialUrl.ifBlank { lastUrl.load().orEmpty() } }
var urlInput by rememberSaveable { mutableStateOf(startUrl) }
var progress by remember { mutableIntStateOf(0) }
var canGoBack by remember { mutableStateOf(false) }
var canGoForward by remember { mutableStateOf(false) }
Expand Down Expand Up @@ -100,13 +107,14 @@ fun GuestBrowserScreen(
WebViewUnavailableNotice(modifier = Modifier.weight(1f).fillMaxWidth())
} else {
GuestWebContent(
url = initialUrl,
url = startUrl,
modifier = Modifier.weight(1f).clipToBounds(),
agentControlEnabled = agentControlEnabled,
onWebViewCreated = { webView = it },
onProgress = { progress = it },
onNavigationStateChange = { url, back, forward ->
urlInput = url
lastUrl.save(url)
canGoBack = back
canGoForward = forward
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,10 @@ fun NavGraphBuilder.workspaceNavGraph(
composable(GUEST_BROWSER_ROUTE_PATTERN) { backStack ->
val requestedUrl = backStack.arguments?.getString(GUEST_BROWSER_ARG_URL)?.let { decodeRouteArg(it) }
val preferences by app.preferences.state.collectAsState()
// Opened from Settings without a URL, there is no page to guess at: the runtime's HTTP
// Opened from Settings without a URL, the screen resumes the page the user was last on;
// before any page has been visited there is none to guess at, because the runtime's HTTP
// servers (opencode serve included) are APIs, not UIs, and the local one now requires basic
// auth. Leave the URL bar empty for the user to fill in instead of loading a 401.
// auth. In that case the URL bar stays empty for the user to fill in instead of loading a 401.
GuestBrowserScreen(
initialUrl = requestedUrl.orEmpty(),
agentControlEnabled = preferences.guestBrowserAgentControlEnabled,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.yugahashimoto.andcode.data.browser

import com.yugahashimoto.andcode.data.security.InMemorySharedPreferences
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

class GuestBrowserLastUrlTest {
private val preferences = InMemorySharedPreferences()

@Test
fun `nothing is resumed before a page was visited`() {
assertNull(GuestBrowserLastUrl(preferences).load())
}

@Test
fun `the last web page is kept and resumed by a new instance`() {
GuestBrowserLastUrl(preferences).save("https://x.com/home")

assertEquals("https://x.com/home", GuestBrowserLastUrl(preferences).load())
}

@Test
fun `a non-web page leaves the previous page in place`() {
val store = GuestBrowserLastUrl(preferences)
store.save("https://example.com/")

store.save("about:blank")

assertEquals("https://example.com/", store.load())
}

@Test
fun `a stored non-web value is never resumed`() {
preferences.edit().putString(GuestBrowserLastUrl.KEY_URL, "file:///etc/passwd").commit()

assertNull(GuestBrowserLastUrl(preferences).load())
}

@Test
fun `loopback dev servers are resumed too`() {
val store = GuestBrowserLastUrl(preferences)
store.save("http://127.0.0.1:5173/")

assertEquals("http://127.0.0.1:5173/", GuestBrowserLastUrl(preferences).load())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ class BrowserCommandWatcherTest {
}
}

@Test
fun `devtools socket name is published only after the agent-control opt-in`() {
val devtools = File(File(runtimeDirectory, "environment/rootfs/root/project").apply { mkdirs() }, BROWSER_DEVTOOLS_FILE)

consume("/root/project", LocalAgent.OPEN_CODE)
assertFalse(devtools.exists())

consume("/root/project", LocalAgent.OPEN_CODE, allowRemotePreview = true)
assertTrue(devtools.readText().startsWith("webview_devtools_remote_"))
}

@Test
fun `nested workspace commands are read from the bind mount`() {
val file = command("workspace/team/project")
Expand Down
Loading