feat: 안드로이드 에뮬레이터 관리콘솔/ADB 쉘 + 컨테이너 정리

세션 영속화, 관리콘솔 WS 프록시(attachAndroidConsoleWsProxy), ADB 쉘
엔드포인트, 고아 컨테이너 정리 로직 추가. 2026-07-31 실사용 검증 완료된
작업을 커밋만 안 하고 남겨뒀던 것.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-08-07 13:13:15 +09:00
1 parent b02fe0a184
commit 3ae9b986e9
3 files changed
+423 -32

No files matched your search

+221 -19
View File
@@ -1,19 +1,68 @@
import express from 'express';
import net from 'net';
import http from 'http';
import fs from 'fs';
import path from 'path';
import { execFile } from 'child_process';
import { WebSocketServer } from 'ws';
import { getUserWorkspace } from '../../config/config';
// ── Android emulator sessions (Docker + noVNC) ──────────────────────────────
// One container per session, running budtmo/docker-android with noVNC exposed
// over HTTP/WS and ADB over TCP. Both ports are bound to 127.0.0.1 only — the
// authenticated gateway proxy (HTTP routes below + attachAndroidWsProxy) is the
// sole access path from the browser.
//
// The container itself is still fully ephemeral (fresh `docker run` per
// session, `docker rm -f` on cleanup) — but its AVD state is bind-mounted from
// a per-user host directory, so installed apps/logins survive across
// sessions despite the container being thrown away each time. Tried making
// the container itself persistent (`docker stop` + `docker start` on reuse)
// first, but the image's startup wrapper hits a `sudo chown 1300:1301
// /dev/kvm` step that fails with "unknown user root" on a restarted (as
// opposed to freshly `run`) container — a reproducible bug in budtmo's
// startup script, not something to work around here. Bind-mounting just the
// data and always doing a clean `run` sidesteps it entirely (verified:
// installed app survives a full `docker rm -f` + fresh `docker run` against
// the same mounted dirs).
//
// Two mount points are needed, not one — the AVD's actual disk images live
// under /home/androidusr/emulator, but the emulator resolves the AVD *by
// name* through a small pointer file at
// /home/androidusr/.android/avd/nexus_5_11.0.ini (path=/home/androidusr/emulator).
// Mounting only the former leaves a fresh container without that pointer,
// which fails to boot at all ("Unknown AVD name ... use -list-avds").
function _androidDataDirs(username: string): { emulatorDir: string; dotAndroidDir: string } {
const base = path.join(getUserWorkspace(username), '.android-emulator');
const emulatorDir = path.join(base, 'emulator');
const dotAndroidDir = path.join(base, 'dot-android');
for (const dir of [emulatorDir, dotAndroidDir]) {
fs.mkdirSync(dir, { recursive: true });
// Container runs as androidusr (uid 1300), not root — chmod instead of
// chown since this process doesn't have privileges to change ownership.
fs.chmodSync(dir, 0o777);
}
// The emulator process holds an advisory lock on its AVD dir while
// running (multiinstance.lock, hardware-qemu.ini.lock) so two instances
// can't corrupt the same disk images concurrently — reasonable in
// general, but `docker rm -f` (hard TTL, /reset, or the boot-time orphan
// sweep) SIGKILLs the container without giving qemu a chance to release
// it, so the next container against this same volume immediately hits
// "Running multiple emulators with the same AVD is an experimental
// feature" and never boots. We already guarantee at most one container
// per user via the perUser 429 check above, so any lock still sitting
// here is guaranteed stale by the time we're allowed to start a new one.
for (const f of ['multiinstance.lock', 'hardware-qemu.ini.lock']) {
try { fs.unlinkSync(path.join(emulatorDir, f)); } catch {}
}
return { emulatorDir, dotAndroidDir };
}
const ANDROID_IMAGE = 'budtmo/docker-android:emulator_11.0';
const VNC_PORT_BASE = 26080;
const ADB_PORT_BASE = 25555;
const HARD_TTL_MS = 30 * 60 * 1000; // 30분 하드 킬
const IDLE_TTL_MS = 5 * 60 * 1000; // 마지막 뷰어 접속 종료 5분 후 킬
const CONSOLE_PORT_BASE = 27444; // emulator's own management console (telnet-style, port 5554 in-container)
const HARD_TTL_MS = 4 * 60 * 60 * 1000; // 4시간 하드 킬 (안전망 — 완전히 잊혀진 세션의 자원 누수 방지)
const BOOT_TIMEOUT_MS = 90 * 1000; // noVNC 포트 준비 대기 최대 90초
const MAX_CONCURRENT = 2; // 전체 동시 세션 상한
@@ -22,10 +71,11 @@ interface AndroidSession {
username: string;
vncPort: number;
adbPort: number;
consolePort: number;
consoleAuthToken: string;
createdAt: number;
ready: boolean;
timer: ReturnType<typeof setTimeout>;
idleTimer?: ReturnType<typeof setTimeout>;
viewerConns: Set<any>;
}
@@ -36,7 +86,6 @@ function killAndroidSession(id: string) {
if (!s) return;
androidSessions.delete(id);
clearTimeout(s.timer);
clearTimeout(s.idleTimer);
for (const sock of s.viewerConns) { try { sock.destroy(); } catch {} }
execFile('docker', ['rm', '-f', s.containerId], () => {});
}
@@ -63,6 +112,10 @@ function _isContainerRunning(containerId: string): Promise<boolean> {
async function _reapDeadSession(id: string): Promise<boolean> {
const s = androidSessions.get(id);
if (!s) return false;
// Slot reserved (see /start) but `docker run` hasn't resolved yet — not
// dead, just not born. Treating this as dead would let a concurrent
// request's per-user check race straight past the reservation.
if (!s.containerId) return false;
const alive = await _isContainerRunning(s.containerId);
if (!alive) { killAndroidSession(id); return true; }
return false;
@@ -92,7 +145,64 @@ function _waitForPort(port: number, timeoutMs: number): Promise<void> {
});
}
// The emulator console (telnet-style management port, publised as
// consolePort) requires `auth <token>` as its first line — the token lives
// in a file inside the container that only exists once the emulator process
// has actually started. Read it once so the console WS proxy can send that
// auth line transparently instead of making the user paste it in manually.
function _fetchConsoleAuthToken(containerId: string): Promise<string> {
return new Promise((resolve) => {
execFile('docker', ['exec', containerId, 'cat', '/home/androidusr/.emulator_console_auth_token'], (err, stdout) => {
resolve(err ? '' : stdout.trim());
});
});
}
// androidSessions is in-memory only, so a gateway restart forgets every
// session while the underlying `docker run -d` containers keep running —
// they become orphans holding the VNC_PORT_BASE/ADB_PORT_BASE ports, which
// then collide with the next session's port allocation ("port is already
// allocated"). Sweep them on boot; nothing can legitimately reference an
// old container id once the map that named it is gone.
function _cleanupOrphanedContainers(): void {
execFile('docker', ['ps', '-aq', '--filter', 'name=^android-emu-'], (err, stdout) => {
if (err) return;
const ids = stdout.split('\n').map(s => s.trim()).filter(Boolean);
if (ids.length) execFile('docker', ['rm', '-f', ...ids], () => {});
});
}
export function registerAndroidRoutes(app: express.Application, getSessionUser: (req: express.Request) => any): void {
_cleanupOrphanedContainers();
// Lets the frontend recover an already-running session after a page
// reload — without this, a reload has no memory of the session id from the
// earlier /start call, so openAndroidEmulator() would call /start again,
// get the "already running" 429 (now that idle sessions no longer
// auto-die), and close the panel on what looks like an error.
app.get('/api/android/mine', async (req, res) => {
const session = getSessionUser(req);
if (!session) return res.status(401).json({ error: 'Not authenticated' });
const mine = [...androidSessions.entries()].filter(([, s]) => s.username === session.username);
for (const [sid] of mine) await _reapDeadSession(sid);
const [id, s] = [...androidSessions.entries()].find(([, s]) => s.username === session.username) || [];
if (!s) return res.status(404).json({ error: 'no session' });
res.json({ id, ready: s.ready, vncPort: s.vncPort, adbPort: s.adbPort, consolePort: s.consolePort });
});
// Force-kill every session belonging to this user, live or stuck — an
// escape hatch for when a session wedges (e.g. the frontend's own error
// path closed the panel while the container was still marked running) and
// /start's normal reap-then-check flow doesn't clear it from under the user.
app.post('/api/android/reset', (req, res) => {
const session = getSessionUser(req);
if (!session) return res.status(401).json({ error: 'Not authenticated' });
const ids = [...androidSessions.entries()].filter(([, s]) => s.username === session.username).map(([sid]) => sid);
for (const id of ids) killAndroidSession(id);
res.json({ ok: true, killed: ids.length });
});
app.post('/api/android/start', async (req, res) => {
const session = getSessionUser(req);
@@ -110,18 +220,53 @@ export function registerAndroidRoutes(app: express.Application, getSessionUser:
const usedVnc = new Set([...androidSessions.values()].map(s => s.vncPort));
const usedAdb = new Set([...androidSessions.values()].map(s => s.adbPort));
const usedConsole = new Set([...androidSessions.values()].map(s => s.consolePort));
const vncPort = _allocatePort(VNC_PORT_BASE, usedVnc);
const adbPort = _allocatePort(ADB_PORT_BASE, usedAdb);
const consolePort = _allocatePort(CONSOLE_PORT_BASE, usedConsole);
const id = 'android_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
const containerName = 'android-emu-' + id;
const { emulatorDir, dotAndroidDir } = _androidDataDirs(session.username);
// Reserve the slot synchronously, before the (async) `docker run` even
// starts — `execFile` doesn't resolve for a second or more, and this
// whole handler is `async`, so without a synchronous reservation here a
// second /start for the same user landing in that window sails past the
// perUser check above (nothing in the map yet) and spins up a second
// container. Since this line and everything above it run without an
// `await`, no other request's handler can interleave before it.
const timer = setTimeout(() => killAndroidSession(id), HARD_TTL_MS);
const s: AndroidSession = {
containerId: '', username: session.username, vncPort, adbPort, consolePort, consoleAuthToken: '',
createdAt: Date.now(), ready: false, timer, viewerConns: new Set(),
};
androidSessions.set(id, s);
execFile('docker', [
'run', '-d',
'--name', containerName,
'--device', '/dev/kvm',
'-e', 'DEVICE=Samsung Galaxy S10',
'-v', `${emulatorDir}:/home/androidusr/emulator`,
'-v', `${dotAndroidDir}:/home/androidusr/.android`,
// The wrapper reads EMULATOR_DEVICE (default "Nexus 5" — 1080x1920),
// not DEVICE. That wrong name is why every session so far silently
// booted a Nexus 5 regardless of what we set here. Galaxy S10's own
// skin config is 1440x3040 — confirmed present in this image's
// skins/ dir (Pixel 8/9, also listed as valid names in the wrapper's
// source, are NOT — those would likely fail to boot in this build).
'-e', 'EMULATOR_DEVICE=Samsung Galaxy S10',
'-e', 'EMULATOR_ARGS=-gpu swiftshader_indirect -no-snapshot -no-boot-anim',
// Tried EMULATOR_NO_SKIN=true to drop the phone bezel/buttons and let
// the screen content fill the whole 1600x900 virtual desktop (noVNC's
// scale=true, below, only stretches that whole canvas — it can't do
// anything about how much of it the skinned emulator window itself
// occupies). Confirmed not worth keeping: this wrapper writes
// `skin.path=_no_skin` into config.ini, but the emulator's own
// autoconfig still detects and re-applies a real skin
// (`qemu.skin=1080x1920` in the actual QEMU invocation, "Creating skin
// display surface 1080x1920" in its log) regardless — a limitation in
// this image version, not something fixable from our side.
'-e', 'WEB_VNC=true',
// Software-rendered (no GPU) cold boot easily takes 3-4+ min. The
// container's own readiness-check wrapper polls a fixed 60 times and
@@ -131,6 +276,7 @@ export function registerAndroidRoutes(app: express.Application, getSessionUser:
'-e', 'DEVICE_INTERVAL_WAITING=8',
'-p', `127.0.0.1:${vncPort}:6080`,
'-p', `127.0.0.1:${adbPort}:5555`,
'-p', `127.0.0.1:${consolePort}:5554`,
'--shm-size=1g',
// Host is a 32-thread Xeon E5-2682 v4 with 38GB RAM. Software
// rendering (swiftshader) is multi-threaded, so more cores here
@@ -140,21 +286,18 @@ export function registerAndroidRoutes(app: express.Application, getSessionUser:
ANDROID_IMAGE,
], { timeout: 20000 }, async (err, stdout) => {
if (err) {
clearTimeout(timer);
androidSessions.delete(id);
res.status(500).json({ error: 'Docker 컨테이너 시작 실패: ' + (err.message || err) });
return;
}
const containerId = stdout.trim();
const timer = setTimeout(() => killAndroidSession(id), HARD_TTL_MS);
const s: AndroidSession = {
containerId, username: session.username, vncPort, adbPort,
createdAt: Date.now(), ready: false, timer, viewerConns: new Set(),
};
androidSessions.set(id, s);
s.containerId = stdout.trim();
try {
await _waitForPort(vncPort, BOOT_TIMEOUT_MS);
s.ready = true;
res.json({ id, vncPort, adbPort });
s.consoleAuthToken = await _fetchConsoleAuthToken(s.containerId);
res.json({ id, vncPort, adbPort, consolePort });
} catch (e: any) {
killAndroidSession(id);
res.status(504).json({ error: '에뮬레이터 부팅 시간 초과: ' + (e.message || e) });
@@ -165,7 +308,30 @@ export function registerAndroidRoutes(app: express.Application, getSessionUser:
app.get('/api/android/:id/status', (req, res) => {
const s = androidSessions.get(req.params.id);
if (!s) return res.status(404).json({ error: 'session not found' });
res.json({ ready: s.ready, vncPort: s.vncPort, adbPort: s.adbPort });
res.json({ ready: s.ready, vncPort: s.vncPort, adbPort: s.adbPort, consolePort: s.consolePort });
});
// One-shot `adb shell <cmd>` execution — not a persistent PTY session.
// Mirrors the emulator console's own input-box-not-xterm-typing design:
// each line is a fresh `adb shell` invocation rather than a live
// interactive shell, so there's no session/focus state to keep in sync.
// State doesn't carry between lines (a `cd` in one call doesn't affect
// the next) — chain with `&&` in a single line when that matters.
app.post('/api/android/:id/shell', (req, res) => {
const session = getSessionUser(req);
if (!session) return res.status(401).json({ error: 'Not authenticated' });
const s = androidSessions.get(req.params.id);
if (!s || s.username !== session.username) return res.status(404).json({ error: 'session not found' });
const cmd = String(req.body?.cmd || '');
if (!cmd) return res.status(400).json({ error: 'cmd required' });
const target = `127.0.0.1:${s.adbPort}`;
// Idempotent — harmless (and fast) if already connected, needed if this
// is the first shell command of the session and nothing has adb-connected yet.
execFile('adb', ['connect', target], { timeout: 5000 }, () => {
execFile('adb', ['-s', target, 'shell', cmd], { timeout: 20000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {
res.json({ output: stdout + (stderr || ''), error: err && !stdout ? (err.message || String(err)) : undefined });
});
});
});
app.delete('/api/android/:id', (req, res) => {
@@ -231,8 +397,6 @@ export function attachAndroidWsProxy(server: http.Server, getSessionUser: (req:
if (head && head.length) backendSocket.write(head);
s.viewerConns.add(clientSocket);
clearTimeout(s.idleTimer);
s.idleTimer = undefined;
clientSocket.pipe(backendSocket);
backendSocket.pipe(clientSocket);
@@ -241,9 +405,10 @@ export function attachAndroidWsProxy(server: http.Server, getSessionUser: (req:
s.viewerConns.delete(clientSocket);
try { clientSocket.destroy(); } catch {}
try { backendSocket.destroy(); } catch {}
if (s.viewerConns.size === 0) {
s.idleTimer = setTimeout(() => killAndroidSession(id), IDLE_TTL_MS);
}
// No idle-based auto-kill anymore — a session with zero viewers stays
// up until HARD_TTL_MS or an explicit /reset. The previous 5-minute
// idle kill wiped out in-progress work (installed apps, logins) the
// moment the viewer tab lost focus or the user looked away.
};
clientSocket.on('close', cleanup);
clientSocket.on('error', cleanup);
@@ -253,3 +418,40 @@ export function attachAndroidWsProxy(server: http.Server, getSessionUser: (req:
backendSocket.on('error', () => { try { clientSocket.destroy(); } catch {} });
});
}
// The emulator's own management console (avd status / power / geo fix / etc,
// telnet-style line protocol on consolePort -> container's 5554) doesn't
// speak WebSocket at all, unlike noVNC's backend above — so this proxy
// actually terminates the WS protocol itself (via `ws`'s WebSocketServer)
// instead of just piping raw bytes, and bridges each message to/from a plain
// net.Socket. Auto-sends `auth <token>` right after connecting so the xterm
// on the frontend starts already-authenticated.
const consoleWss = new WebSocketServer({ noServer: true });
export function attachAndroidConsoleWsProxy(server: http.Server, getSessionUser: (req: any) => any): void {
server.on('upgrade', (req, socket, head) => {
const url = req.url || '';
const m = url.match(/^\/api\/android\/([\w-]+)\/console/);
if (!m) return;
const id = m[1];
const s = androidSessions.get(id);
const authedSession = getSessionUser(req);
if (!s || !authedSession || authedSession.username !== s.username) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
consoleWss.handleUpgrade(req, socket, head, (ws) => {
const tcp = net.connect({ host: '127.0.0.1', port: s.consolePort }, () => {
if (s.consoleAuthToken) tcp.write(`auth ${s.consoleAuthToken}\n`);
});
tcp.on('data', (chunk) => { try { ws.send(chunk.toString('utf8')); } catch {} });
tcp.on('close', () => { try { ws.close(); } catch {} });
tcp.on('error', () => { try { ws.close(); } catch {} });
ws.on('message', (data) => { try { tcp.write(data.toString()); } catch {} });
ws.on('close', () => { try { tcp.destroy(); } catch {} });
ws.on('error', () => { try { tcp.destroy(); } catch {} });
});
});
}
+2 -1
View File
@@ -50,7 +50,7 @@ import {
userRequestedImageEdit,
} from './guards/prompt-gates';
import { registerArduinoRoutes } from './routes/routes-arduino';
import { registerAndroidRoutes, attachAndroidWsProxy } from './routes/routes-android';
import { registerAndroidRoutes, attachAndroidWsProxy, attachAndroidConsoleWsProxy } from './routes/routes-android';
import { registerComfyUIRoutes, attachComfyUIWsProxy } from './routes/routes-comfyui';
import { registerBgTasksRoutes, loadTaskHeartbeatConfig } from './routes/routes-bg-tasks';
import { registerKakaoRoutes } from './routes/routes-kakao';
@@ -4477,6 +4477,7 @@ server.on('upgrade', (req, socket, head) => {
}
});
attachAndroidWsProxy(server, getSessionUser);
attachAndroidConsoleWsProxy(server, getSessionUser);
attachComfyUIWsProxy(server, getSessionUserFromUpgradeReq);
attachVoiceRealtimeWsProxy(server, getSessionUserFromUpgradeReq);
wss.on('error', (err: any) => {
+200 -12
View File
@@ -3,18 +3,38 @@
<head>
<meta charset="utf-8">
<title>Android 에뮬레이터</title>
<link rel="stylesheet" href="/vendor/xterm.css">
<script src="/vendor/xterm.js"></script>
<style>
html,body{margin:0;padding:0;height:100%;background:#1a1a1a;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;overflow:hidden}
#wrap{display:flex;flex-direction:column;height:100%}
#bar{flex:0 0 auto;display:flex;align-items:center;gap:10px;padding:6px 10px;background:#222;border-bottom:1px solid #333;font-size:12px}
#bar code{background:#000;color:#8f8;padding:2px 6px;border-radius:4px;cursor:pointer;user-select:all}
#status{color:#aaa}
#stage{flex:1;min-height:0;position:relative}
#vnc-frame{position:absolute;inset:0;width:100%;height:100%;border:none;background:#000}
#consoleBtn{background:#333;color:#ccc;border:1px solid #444;border-radius:4px;padding:3px 8px;cursor:pointer;font-size:12px}
#consoleBtn.active{background:#2d5a3d;color:#cfc;border-color:#3a7a4d}
#body{flex:1;min-height:0;display:flex}
#stage{flex:1;min-height:0;position:relative;overflow:auto}
#vnc-frame{position:absolute;top:0;left:0;width:100%;height:100%;border:none;background:#000}
#zoomCtl{display:flex;align-items:center;gap:6px}
#zoomCtl input[type=range]{width:110px}
#zoomVal{color:#aaa;min-width:38px;text-align:right}
#loading{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:#ccc}
.spinner{width:36px;height:36px;border:3px solid #444;border-top-color:#7c5c2e;border-radius:50%;animation:spin 0.9s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
#err{position:absolute;inset:0;display:none;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:#f88;padding:20px;text-align:center}
#console-panel{display:none;flex-direction:column;width:480px;flex-shrink:0;border-left:1px solid #333;background:#000}
#console-drag{flex:0 0 auto;height:5px;cursor:ew-resize;background:transparent}
#console-drag:hover{background:rgba(124,92,46,.4)}
#console-tabs{flex:0 0 auto;display:flex;background:#222;border-bottom:1px solid #333;font-size:12px}
.console-tab{padding:6px 12px;cursor:pointer;color:#888;border-bottom:2px solid transparent}
.console-tab.active{color:#eee;border-bottom-color:#7c5c2e}
.console-pane{flex:1;min-height:0;display:none;flex-direction:column}
.console-pane.active{display:flex}
.console-term{flex:1;min-height:0;padding:4px}
.console-input-row{flex:0 0 auto;padding:6px 8px;background:#161616;border-top:1px solid #333}
.console-input{width:100%;box-sizing:border-box;background:#000;color:#eee;border:1px solid #444;border-radius:4px;padding:6px 8px;font-family:'IBM Plex Mono',monospace;font-size:13px}
.console-input:focus{outline:none;border-color:#7c5c2e}
</style>
</head>
<body>
@@ -22,12 +42,39 @@
<div id="bar">
<span id="status">준비 중…</span>
<span style="flex:1"></span>
<div id="zoomCtl" style="display:none">
<span>🔍</span>
<input type="range" id="zoomSlider" min="100" max="400" step="10" value="100">
<span id="zoomVal">100%</span>
</div>
<button id="consoleBtn" style="display:none">🖥️ 콘솔</button>
<span id="adbHint" style="display:none">adb: <code id="adbCmd" title="클릭해서 복사"></code></span>
</div>
<div id="stage">
<div id="loading"><div class="spinner"></div><div id="loadingText">Android 에뮬레이터 부팅 중… (최대 90초)</div></div>
<div id="err"><div id="errText"></div></div>
<iframe id="vnc-frame" style="display:none"></iframe>
<div id="body">
<div id="stage">
<div id="loading"><div class="spinner"></div><div id="loadingText">Android 에뮬레이터 부팅 중… (최대 90초)</div></div>
<div id="err"><div id="errText"></div></div>
<iframe id="vnc-frame" style="display:none"></iframe>
</div>
<div id="console-panel">
<div id="console-drag"></div>
<div id="console-tabs">
<div class="console-tab active" data-tab="mgmt">관리 콘솔</div>
<div class="console-tab" data-tab="shell">ADB 쉘</div>
</div>
<div class="console-pane active" id="pane-mgmt">
<div class="console-term" id="console-term"></div>
<div class="console-input-row">
<input type="text" class="console-input" id="console-input" placeholder="명령 입력 후 Enter (예: avd status)" autocomplete="off">
</div>
</div>
<div class="console-pane" id="pane-shell">
<div class="console-term" id="shell-term"></div>
<div class="console-input-row">
<input type="text" class="console-input" id="shell-input" placeholder="adb shell 명령 입력 후 Enter (예: pm list packages)" autocomplete="off">
</div>
</div>
</div>
</div>
</div>
<script>
@@ -42,6 +89,32 @@
const frameEl = document.getElementById('vnc-frame');
const adbHintEl = document.getElementById('adbHint');
const adbCmdEl = document.getElementById('adbCmd');
const zoomCtlEl = document.getElementById('zoomCtl');
const zoomSliderEl = document.getElementById('zoomSlider');
const zoomValEl = document.getElementById('zoomVal');
const consoleBtnEl = document.getElementById('consoleBtn');
const consolePanelEl = document.getElementById('console-panel');
const consoleTermEl = document.getElementById('console-term');
const consoleDragEl = document.getElementById('console-drag');
const consoleInputEl = document.getElementById('console-input');
const shellTermEl = document.getElementById('shell-term');
const shellInputEl = document.getElementById('shell-input');
// The emulator's own skinned window only fills a fraction of its 1600x900
// virtual desktop (a limitation of this docker image we can't fix from our
// side — tried EMULATOR_NO_SKIN, the emulator's autoconfig re-applies a
// skin regardless). noVNC's scale=true already stretches that whole
// desktop to fill #vnc-frame, so the only way to make the phone itself
// bigger is to make #vnc-frame bigger than its visible box and let #stage
// (overflow:auto) scroll/pan across it — genuine iframe resize rather than
// a CSS transform, so noVNC recomputes its own fit-to-frame scale and
// pointer/click coordinates stay correctly mapped.
zoomSliderEl.addEventListener('input', () => {
const pct = zoomSliderEl.value;
zoomValEl.textContent = pct + '%';
frameEl.style.width = pct + '%';
frameEl.style.height = pct + '%';
});
if (!sessionId) {
if (isLoading) { statusEl.textContent = '부팅 중…'; return; }
@@ -56,21 +129,134 @@
statusEl.textContent = '오류';
}
// ── 관리 콘솔 (telnet-style line protocol over our own WS proxy) ──
// xterm handles the OUTPUT side fine (verified: server responses render
// correctly via .write()), but its own keyboard capture never reliably
// grabbed focus once nested this deep (code.html iframe > this page > the
// terminal's own hidden textarea) — real typing produced nothing even
// after forcing focus() and confirming document.hasFocus()/activeElement
// were correct. Since this console is a line-based command protocol
// anyway (not a raw interactive shell), a plain <input> + Enter-to-send
// sidesteps the whole focus problem: browsers focus regular inputs
// reliably regardless of iframe nesting, and xterm stays as a read-only
// scrollback display.
let consoleWs = null;
let consoleTerm = null;
let activeTab = 'mgmt';
function toggleConsole() {
const opening = consolePanelEl.style.display !== 'flex';
consolePanelEl.style.display = opening ? 'flex' : 'none';
consoleBtnEl.classList.toggle('active', opening);
if (opening) {
if (!consoleWs) connectConsole();
if (!shellTerm) initShellTerm();
setTimeout(() => (activeTab === 'mgmt' ? consoleInputEl : shellInputEl).focus(), 0);
}
}
function connectConsole() {
if (!consoleTerm) {
consoleTerm = new Terminal({ convertEol: true, fontSize: 13, theme: { background: '#000' }, disableStdin: true });
consoleTerm.open(consoleTermEl);
consoleTerm.writeln('Connecting to emulator console...');
}
const wsScheme = location.protocol === 'https:' ? 'wss' : 'ws';
consoleWs = new WebSocket(wsScheme + '://' + location.host + '/api/android/' + sessionId + '/console');
consoleWs.onmessage = (ev) => consoleTerm.write(ev.data);
consoleWs.onclose = () => { consoleTerm.writeln('\r\n[연결 종료]'); consoleWs = null; };
consoleWs.onerror = () => { consoleTerm.writeln('\r\n[연결 오류]'); };
}
consoleBtnEl.addEventListener('click', () => toggleConsole());
consoleInputEl.addEventListener('keydown', (e) => {
if (e.key !== 'Enter') return;
const line = consoleInputEl.value;
if (!line) return;
if (consoleWs && consoleWs.readyState === WebSocket.OPEN) {
consoleTerm.writeln('> ' + line);
consoleWs.send(line + '\n');
consoleInputEl.value = '';
} else {
consoleTerm.writeln('[연결 안 됨]');
}
});
// ── ADB 쉘 ── one-shot `adb -s <adbPort> shell <cmd>` per line (see comment
// on /api/android/:id/shell server-side — no persistent session/state).
let shellTerm = null;
function initShellTerm() {
shellTerm = new Terminal({ convertEol: true, fontSize: 13, theme: { background: '#000' }, disableStdin: true });
shellTerm.open(shellTermEl);
shellTerm.writeln('adb shell ready — one command per line, no persistent cwd/state (chain with && if needed).');
}
shellInputEl.addEventListener('keydown', (e) => {
if (e.key !== 'Enter') return;
const cmd = shellInputEl.value;
if (!cmd) return;
shellTerm.writeln('$ ' + cmd);
shellInputEl.value = '';
shellInputEl.disabled = true;
fetch('/api/android/' + sessionId + '/shell', {
method: 'POST', credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cmd }),
}).then(r => r.json()).then(d => {
if (d.error) shellTerm.writeln('[오류] ' + d.error);
if (d.output) shellTerm.write(d.output.replace(/\n/g, '\r\n'));
}).catch(e => shellTerm.writeln('[연결 오류] ' + e.message))
.finally(() => { shellInputEl.disabled = false; shellInputEl.focus(); });
});
// Tab switching between the two console panes.
document.querySelectorAll('.console-tab').forEach(tabEl => {
tabEl.addEventListener('click', () => {
const tab = tabEl.dataset.tab;
activeTab = tab;
document.querySelectorAll('.console-tab').forEach(t => t.classList.toggle('active', t === tabEl));
document.getElementById('pane-mgmt').classList.toggle('active', tab === 'mgmt');
document.getElementById('pane-shell').classList.toggle('active', tab === 'shell');
(tab === 'mgmt' ? consoleInputEl : shellInputEl).focus();
});
});
// Side-panel resize drag (mirrors the bottom-panel drag pattern used
// elsewhere in the app, just horizontal instead of vertical).
(function(){
let startX = 0, startW = 0;
consoleDragEl.addEventListener('mousedown', e => {
startX = e.clientX; startW = consolePanelEl.offsetWidth; e.preventDefault();
frameEl.style.pointerEvents = 'none';
const onMove = e2 => {
const dx = startX - e2.clientX;
consolePanelEl.style.width = Math.max(280, Math.min(window.innerWidth * 0.7, startW + dx)) + 'px';
};
const onUp = () => {
document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp);
frameEl.style.pointerEvents = '';
};
document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp);
});
})();
function showReady(vncPort, adbPort) {
statusEl.textContent = '실행 중';
const host = location.hostname;
const port = location.port || (location.protocol === 'https:' ? 443 : 80);
const wsScheme = location.protocol === 'https:' ? 'wss' : 'ws';
// This image's vnc_lite.html only recognizes host/port/path/view_only/scale
// (checked via its own readQueryVariable() calls) — encrypt/autoconnect
// aren't read at all (it always connects immediately), and the scaling
// flag is named `scale` (boolean), not `resize=scale` — that was silently
// ignored, leaving rfb.scaleViewport at its false default and the phone
// screen rendering at native (small) size inside the much larger panel.
const qs = 'host=' + encodeURIComponent(host) +
'&port=' + encodeURIComponent(port) +
'&path=' + encodeURIComponent('api/android/' + sessionId + '/vnc') +
'&encrypt=' + (wsScheme === 'wss' ? '1' : '0') +
'&autoconnect=true&resize=scale';
'&scale=true';
frameEl.src = '/api/android/' + sessionId + '/app/vnc_lite.html?' + qs;
frameEl.style.display = 'block';
loadingEl.style.display = 'none';
adbCmdEl.textContent = 'adb connect localhost:' + adbPort;
adbHintEl.style.display = 'inline';
zoomCtlEl.style.display = 'flex';
consoleBtnEl.style.display = 'inline-block';
}
adbCmdEl.addEventListener('click', () => {
@@ -95,9 +281,11 @@
}
poll();
window.addEventListener('unload', () => {
fetch('/api/android/' + sessionId, { method: 'DELETE', credentials: 'include', keepalive: true }).catch(() => {});
});
// Deliberately no unload-triggered DELETE here anymore — a page reload or
// tab close unloads this iframe too, which was silently killing the
// session (including installed apps' in-progress state) every time the
// parent code-editor page reloaded. Sessions only end via the HARD_TTL_MS
// backstop or an explicit reset/delete call.
})();
</script>
</body>