This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-05 18:08:20 +09:00
1 parent 7862652733
commit 710b209fec
3 files changed
+34 -129

No files matched your search

+5 -13
View File
@@ -237,7 +237,7 @@ Desktop support still requires its platform dependencies to be available.
### Use your running Chrome
Browser defaults to `managed`: Open Terminal launches a separate Chrome profile.
To use your existing Chrome tabs and signed-in sessions, select `personal`:
To open tabs in your running Chrome with its signed-in sessions, select `personal`:
```sh
export OPEN_TERMINAL_BROWSER_MODE=personal
@@ -259,18 +259,10 @@ instance is unavailable, Open Terminal returns an error rather than launching or
choosing another browser. The equivalent TOML keys are `browser_mode`,
`browser_user_data_dir`, and `browser_cdp_url`. Restart Open Terminal after changes.
Clients can list available HTTP/HTTPS tabs with authenticated `GET /browser/targets`,
then attach one with `POST /browser/sessions` and `{"target_id":"<id>"}`. An existing
proxy session can attach using `PATCH /browser/sessions/{id}` with
`{"mode":"chrome","target_id":"<id>"}`. The same browser tools and viewer stream work
on the attachment. Session responses and `/api/config` report `browser_mode`.
Clients should use the stream state's `width` and `height` for personal-tab input
coordinates; viewport and mobile-emulation requests do not resize the real page.
Closing an attachment or stopping Open Terminal leaves personal Chrome and its
tabs open. Personal mode requires single-user operation. It does not automatically
focus background tabs; a tab may need to be brought forward in Chrome for live
viewing. WebUI's tab-selection UI must support these attachment endpoints.
Use Chrome mode in WebUI as usual. Open Terminal creates a tab in the configured
browser using the same session API, tools, and viewer. No WebUI changes are needed.
Closing the session or stopping Open Terminal closes the tabs it created, leaving
your browser and other tabs open. Personal mode requires single-user operation.
Chromium's sandbox is enabled by default outside Docker. All published Docker image
variants set `OPEN_TERMINAL_BROWSER_NO_SANDBOX=true` so Browser can start under
+26 -65
View File
@@ -146,7 +146,6 @@ class Host:
self.sequence = 0
self.pending = {}
self.handlers = {}
self.targets = {}
self.stderr = b""
self.stderr_reader = asyncio.create_task(self.read_stderr())
self.reader = asyncio.create_task(self.read())
@@ -432,75 +431,57 @@ class Chrome:
self.vnc_peer = None
self.acks = set()
self.refs = {}
self.owns_target = host.process is not None
self.detached = False
self.closed = False
host.handlers[cdp_session] = self.event
@classmethod
async def create(cls, session, target_id=None):
if BROWSER_MODE == "personal" and not target_id:
raise ValueError("Select a Chrome tab from /browser/targets and supply target_id")
if BROWSER_MODE == "managed" and target_id:
raise ValueError("target_id requires personal browser mode")
async def create(cls, session):
host = await get_host(session)
chrome = None
attached = None
if host.process is None:
target = target_id
if target in host.targets:
raise ValueError("This Chrome tab is already attached. Release its Browser session first.")
host.targets[target] = session
else:
target = (
await host.send(
"Target.createTarget",
{"url": "about:blank", "background": bool(host.display)},
)
)["targetId"]
target = (
await host.send(
"Target.createTarget",
{"url": "about:blank", "background": bool(host.display)},
)
)["targetId"]
try:
if host.process is None:
info = (await host.send("Target.getTargetInfo", {"targetId": target}))["targetInfo"]
if info.get("type") != "page" or not info.get("url", "").startswith(("http://", "https://")):
raise ValueError("Select an HTTP or HTTPS Chrome tab")
attached = await host.send(
"Target.attachToTarget", {"targetId": target, "flatten": True}
)
chrome = cls(session, host, target, attached["sessionId"])
await chrome.send("Page.enable")
await chrome.send("Runtime.enable")
if chrome.owns_target:
if host.process is None:
# Match viewer coordinates before its first viewport message, even on Retina displays.
await chrome.send(
"Page.addScriptToEvaluateOnNewDocument",
{
"source": """
"Emulation.setDeviceMetricsOverride",
{"width": chrome.width, "height": chrome.height, "deviceScaleFactor": 1, "mobile": False},
)
await chrome.send(
"Page.addScriptToEvaluateOnNewDocument",
{
"source": """
window.open = url => { if (url) location.assign(url); return null; };
addEventListener('click', e => {const a=e.target.closest?.('a[target]');
if(a && a.target !== '_self'){e.preventDefault(); location.assign(a.href);}},true);
"""
},
)
if session.url:
chrome.navigate(session.url)
else:
await chrome.state()
},
)
if session.url:
chrome.navigate(session.url)
return chrome
except BaseException:
if chrome:
await chrome.close()
else:
if host.targets.get(target) is session:
host.targets.pop(target)
with contextlib.suppress(Exception):
if host.process is not None:
await host.send("Target.closeTarget", {"targetId": target})
elif attached:
await host.send("Target.detachFromTarget", {"sessionId": attached["sessionId"]})
await host.send("Target.closeTarget", {"targetId": target})
raise
async def send(self, method, params=None):
if self.detached or self.closed:
raise RuntimeError("Chrome tab disconnected. Reattach it from /browser/targets.")
raise RuntimeError("Chrome tab disconnected. Reopen this browser tab.")
return await self.host.send(method, params, self.cdp_session)
async def snapshot(self):
@@ -588,8 +569,6 @@ class Chrome:
if method == "Inspector.detached":
self.detached = True
self.refs.clear()
if self.host.targets.get(self.target) is self.session:
self.host.targets.pop(self.target)
self.state_changed.set()
elif method == "Page.screencastFrame":
# A slow viewer must not block Chrome; retain only its newest full frame.
@@ -627,8 +606,6 @@ class Chrome:
if str(exc) == "Not attached to an active page":
return None
raise
if not self.owns_target:
await self.update_viewport()
entries, index = history["entries"], history["currentIndex"]
entry = entries[index] if entries else {}
url = entry.get("url", "")
@@ -643,30 +620,22 @@ class Chrome:
"canGoBack": index > 0,
"canGoForward": index < len(entries) - 1,
"transport": "vnc" if self.host.display else "frames",
"width": self.width,
"height": self.height,
}
async def update_viewport(self):
metrics = await self.send("Page.getLayoutMetrics")
viewport = metrics["cssVisualViewport"]
self.width = max(1, round(viewport["clientWidth"]))
self.height = max(1, round(viewport["clientHeight"]))
async def capture(self):
if self.host.display:
return
await self.send("Page.stopScreencast")
if not self.visible:
return
if self.owns_target:
await self.send("Page.bringToFront")
await self.send("Page.bringToFront")
await self.send(
"Page.startScreencast",
{
"format": "jpeg",
"quality": self.quality,
**({"maxWidth": self.width, "maxHeight": self.height} if self.owns_target else {}),
"maxWidth": self.width,
"maxHeight": self.height,
"everyNthFrame": 1,
},
)
@@ -807,9 +776,6 @@ class Chrome:
self.visible = msg.get("visible") is True
await self.capture()
elif kind == "viewport":
if not self.owns_target:
self.state_changed.set()
continue
self.width = max(240, min(2560, int(msg.get("width", 1024))))
self.height = max(200, min(2160, int(msg.get("height", 768))))
mobile = msg.get("mobile") is True
@@ -943,10 +909,5 @@ class Chrome:
with contextlib.suppress(Exception):
await self.vnc_peer.close(code=4004)
self.host.handlers.pop(self.cdp_session, None)
if self.host.targets.get(self.target) is self.session:
self.host.targets.pop(self.target)
with contextlib.suppress(Exception):
if self.owns_target:
await self.host.send("Target.closeTarget", {"targetId": self.target})
elif not self.detached:
await self.host.send("Target.detachFromTarget", {"sessionId": self.cdp_session})
await self.host.send("Target.closeTarget", {"targetId": self.target})
+3 -51
View File
@@ -154,7 +154,6 @@ def payload(session):
class CreateSession(BaseModel):
url: str = Field(default="", max_length=16384)
target_id: str | None = Field(default=None, min_length=1, max_length=128)
class UpdateSession(BaseModel):
@@ -163,7 +162,6 @@ class UpdateSession(BaseModel):
mode: str | None = None
active: bool | None = None
chat_id: str | None = Field(default=None, min_length=1, max_length=128)
target_id: str | None = Field(default=None, min_length=1, max_length=128)
def valid_url(url):
@@ -173,26 +171,6 @@ def valid_url(url):
raise HTTPException(400, str(exc)) from exc
@router.get("/targets", include_in_schema=False, dependencies=[Depends(verify_api_key)])
async def targets(request: Request, fs: UserFS = Depends(get_filesystem)):
"""Discover personal Chrome tabs; model tools only see attached chat sessions."""
if BROWSER_MODE != "personal":
raise HTTPException(409, "Tab discovery requires personal browser mode")
from .chrome import get_host
try:
host = await get_host(Session("", "", owner(request), "", fs))
result = await host.send("Target.getTargets")
except (RuntimeError, ValueError) as exc:
raise HTTPException(409, str(exc)) from exc
return {"targets": [
{"id": target["targetId"], "title": target.get("title", ""), "url": target["url"]}
for target in result["targetInfos"]
if target["type"] == "page" and target.get("url", "").startswith(("http://", "https://"))
and target["targetId"] not in host.targets
]}
@router.post("/sessions", include_in_schema=False, dependencies=[Depends(verify_api_key)])
async def create(
request: Request, body: CreateSession, fs: UserFS = Depends(get_filesystem)
@@ -212,14 +190,6 @@ async def create(
fs,
url=body.url,
)
if body.target_id:
from .chrome import Chrome
try:
session.chrome = await Chrome.create(session, body.target_id)
except (RuntimeError, ValueError) as exc:
raise HTTPException(409, str(exc)) from exc
session.mode = "chrome"
sessions[session.id] = session
if session.owner not in profiles:
profiles[session.owner] = httpx.AsyncClient(
@@ -238,8 +208,6 @@ async def update(request: Request, sid: str, body: UpdateSession):
session = owned(request, sid)
if body.mode not in (None, "proxy", "chrome"):
raise HTTPException(400, "Invalid browser mode")
if body.target_id and (body.mode != "chrome" or session.chrome is not None):
raise HTTPException(409, "Supply target_id when attaching an unconnected session in Chrome mode")
if body.url:
valid_url(body.url)
async with session.lock:
@@ -265,7 +233,7 @@ async def update(request: Request, sid: str, body: UpdateSession):
from .chrome import Chrome
try:
session.chrome = await Chrome.create(session, body.target_id)
session.chrome = await Chrome.create(session)
except Exception as exc:
raise HTTPException(409, str(exc)) from exc
elif body.mode == "proxy" and session.chrome is not None:
@@ -567,10 +535,8 @@ async def browser_page(request, session_id=None):
)
chrome = session.chrome
if chrome.detached or chrome.host.reader.done():
raise HTTPException(409, "Chrome tab disconnected. Reattach it from /browser/targets.")
raise HTTPException(409, "Chrome tab disconnected. Reopen this browser tab.")
async with chrome.host.view_lock:
if not chrome.owns_target:
await chrome.update_viewport()
# Headed Chrome cannot reliably capture background pages.
if chrome.host.display:
await chrome.send("Page.bringToFront")
@@ -589,21 +555,7 @@ async def image(chrome):
result = await chrome.send(
"Page.captureScreenshot", {"format": "png", "captureBeyondViewport": False}
)
data = base64.b64decode(result["data"])
if not chrome.owns_target:
# CDP screenshots use device pixels; browser_action coordinates use CSS pixels.
def resize():
import io
from PIL import Image
with Image.open(io.BytesIO(data)) as screenshot:
if screenshot.size == (chrome.width, chrome.height):
return data
output = io.BytesIO()
screenshot.resize((chrome.width, chrome.height), Image.Resampling.LANCZOS).save(output, "PNG")
return output.getvalue()
data = await asyncio.to_thread(resize)
return Response(data, media_type="image/png")
return Response(base64.b64decode(result["data"]), media_type="image/png")
@router.get(