Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import fcntl
|
|
| 6 |
import termios
|
| 7 |
import asyncio
|
| 8 |
import json
|
|
|
|
| 9 |
import spaces
|
| 10 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 11 |
from fastapi.responses import HTMLResponse
|
|
@@ -15,11 +16,11 @@ app = FastAPI()
|
|
| 15 |
|
| 16 |
# ──────────────────────────── Frontend ────────────────────────────
|
| 17 |
HTML_PAGE = r"""<!DOCTYPE html>
|
| 18 |
-
<html lang="
|
| 19 |
<head>
|
| 20 |
<meta charset="utf-8"/>
|
| 21 |
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
| 22 |
-
<title>Web Terminal</title>
|
| 23 |
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/css/xterm.min.css"/>
|
| 24 |
<style>
|
| 25 |
*{margin:0;padding:0;box-sizing:border-box}
|
|
@@ -32,6 +33,8 @@ html,body{height:100%;overflow:hidden;background:#1e1e1e;color:#ccc;font-family:
|
|
| 32 |
.tab .x:hover{color:#f55}
|
| 33 |
#add-btn{background:none;border:1px dashed #555;color:#777;padding:3px 12px;border-radius:4px;cursor:pointer;font-size:18px;margin-bottom:4px;margin-left:4px}
|
| 34 |
#add-btn:hover{color:#fff;border-color:#aaa}
|
|
|
|
|
|
|
| 35 |
#term-box{flex:1;overflow:hidden;padding:2px}
|
| 36 |
.tw{width:100%;height:100%;display:none}
|
| 37 |
.tw.active{display:block}
|
|
@@ -39,8 +42,13 @@ body{display:flex;flex-direction:column}
|
|
| 39 |
</style>
|
| 40 |
</head>
|
| 41 |
<body>
|
| 42 |
-
<div id="tab-bar">
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
<div id="term-box"></div>
|
|
|
|
| 44 |
|
| 45 |
<script src="https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/lib/xterm.min.js"></script>
|
| 46 |
<script src="https://cdn.jsdelivr.net/npm/@xterm/addon-fit@0.10.0/lib/addon-fit.min.js"></script>
|
|
@@ -49,6 +57,10 @@ body{display:flex;flex-direction:column}
|
|
| 49 |
const bar = document.getElementById('tab-bar');
|
| 50 |
const box = document.getElementById('term-box');
|
| 51 |
const addBtn = document.getElementById('add-btn');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
let tabs = [], activeId = null, cnt = 0;
|
| 53 |
|
| 54 |
function wsUrl() {
|
|
@@ -63,7 +75,7 @@ function createTab() {
|
|
| 63 |
el.className = 'tab';
|
| 64 |
el.dataset.id = id;
|
| 65 |
el.innerHTML = `<span>Term ${id}</span><span class="x">×</span>`;
|
| 66 |
-
bar.insertBefore(el,
|
| 67 |
|
| 68 |
const wrap = document.createElement('div');
|
| 69 |
wrap.className = 'tw';
|
|
@@ -99,7 +111,19 @@ function createTab() {
|
|
| 99 |
ws.onmessage = e => {
|
| 100 |
try {
|
| 101 |
const m = JSON.parse(e.data);
|
| 102 |
-
if (m.type === 'output')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
} catch {
|
| 104 |
term.write(e.data);
|
| 105 |
}
|
|
@@ -107,7 +131,7 @@ function createTab() {
|
|
| 107 |
|
| 108 |
ws.onclose = () => term.write('\r\n\x1b[31m[Connection closed]\x1b[0m\r\n');
|
| 109 |
|
| 110 |
-
// ✅ 修正:使用函數調用 () 註冊事件
|
| 111 |
term.onData(d => {
|
| 112 |
if (ws.readyState === WebSocket.OPEN) {
|
| 113 |
ws.send(JSON.stringify({type: 'input', data: d}));
|
|
@@ -159,6 +183,50 @@ function closeTab(id) {
|
|
| 159 |
|
| 160 |
addBtn.onclick = createTab;
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
window.addEventListener('resize', () => tabs.forEach(t => {
|
| 163 |
if (t.wrap.classList.contains('active')) t.fit.fit();
|
| 164 |
}));
|
|
@@ -187,8 +255,24 @@ def dummy_gpu():
|
|
| 187 |
|
| 188 |
@app.on_event("startup")
|
| 189 |
async def startup_event():
|
| 190 |
-
#
|
| 191 |
dummy_gpu()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
@app.websocket("/ws")
|
| 194 |
async def terminal_ws(websocket: WebSocket):
|
|
@@ -196,12 +280,19 @@ async def terminal_ws(websocket: WebSocket):
|
|
| 196 |
|
| 197 |
# ── fork a bash process inside a pty ──
|
| 198 |
pid, fd = pty.fork()
|
| 199 |
-
if pid == 0: # child
|
| 200 |
os.environ["TERM"] = "xterm-256color"
|
| 201 |
os.environ["COLORTERM"] = "truecolor"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
os.execvp("bash", ["bash", "--login"])
|
| 203 |
|
| 204 |
-
# ── parent ──
|
| 205 |
loop = asyncio.get_running_loop()
|
| 206 |
|
| 207 |
def set_winsize(cols: int, rows: int):
|
|
@@ -243,10 +334,53 @@ async def terminal_ws(websocket: WebSocket):
|
|
| 243 |
while True:
|
| 244 |
raw = await websocket.receive_text()
|
| 245 |
msg = json.loads(raw)
|
|
|
|
| 246 |
if msg["type"] == "input":
|
| 247 |
os.write(fd, msg["data"].encode("utf-8"))
|
| 248 |
elif msg["type"] == "resize":
|
| 249 |
set_winsize(msg["cols"], msg["rows"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
except (WebSocketDisconnect, Exception):
|
| 251 |
pass
|
| 252 |
finally:
|
|
@@ -268,5 +402,5 @@ async def terminal_ws(websocket: WebSocket):
|
|
| 268 |
# ──────────────────────────── Entry ───────────────────────────────
|
| 269 |
if __name__ == "__main__":
|
| 270 |
port = int(os.environ.get("PORT", 7860))
|
| 271 |
-
print(f"🚀
|
| 272 |
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
|
|
|
|
| 6 |
import termios
|
| 7 |
import asyncio
|
| 8 |
import json
|
| 9 |
+
import base64
|
| 10 |
import spaces
|
| 11 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 12 |
from fastapi.responses import HTMLResponse
|
|
|
|
| 16 |
|
| 17 |
# ──────────────────────────── Frontend ────────────────────────────
|
| 18 |
HTML_PAGE = r"""<!DOCTYPE html>
|
| 19 |
+
<html lang="zh-TW">
|
| 20 |
<head>
|
| 21 |
<meta charset="utf-8"/>
|
| 22 |
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
| 23 |
+
<title>Web Terminal + OpenCode</title>
|
| 24 |
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/css/xterm.min.css"/>
|
| 25 |
<style>
|
| 26 |
*{margin:0;padding:0;box-sizing:border-box}
|
|
|
|
| 33 |
.tab .x:hover{color:#f55}
|
| 34 |
#add-btn{background:none;border:1px dashed #555;color:#777;padding:3px 12px;border-radius:4px;cursor:pointer;font-size:18px;margin-bottom:4px;margin-left:4px}
|
| 35 |
#add-btn:hover{color:#fff;border-color:#aaa}
|
| 36 |
+
.file-btn{background:#2d2d2d;color:#969696;border:1px solid #3c3c3c;border-radius:4px;padding:4px 10px;cursor:pointer;font-size:13px;margin-bottom:4px;margin-left:4px;transition:all 0.2s}
|
| 37 |
+
.file-btn:hover{color:#fff;border-color:#aaa;background:#3c3c3c}
|
| 38 |
#term-box{flex:1;overflow:hidden;padding:2px}
|
| 39 |
.tw{width:100%;height:100%;display:none}
|
| 40 |
.tw.active{display:block}
|
|
|
|
| 42 |
</style>
|
| 43 |
</head>
|
| 44 |
<body>
|
| 45 |
+
<div id="tab-bar">
|
| 46 |
+
<button id="add-btn" title="New Terminal (Ctrl+Shift+T)">+</button>
|
| 47 |
+
<button id="upload-btn" class="file-btn" title="Upload File to /home/user/">📤 上傳</button>
|
| 48 |
+
<button id="download-btn" class="file-btn" title="Download File from /home/user/">📥 下載</button>
|
| 49 |
+
</div>
|
| 50 |
<div id="term-box"></div>
|
| 51 |
+
<input type="file" id="file-input" style="display:none;" />
|
| 52 |
|
| 53 |
<script src="https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/lib/xterm.min.js"></script>
|
| 54 |
<script src="https://cdn.jsdelivr.net/npm/@xterm/addon-fit@0.10.0/lib/addon-fit.min.js"></script>
|
|
|
|
| 57 |
const bar = document.getElementById('tab-bar');
|
| 58 |
const box = document.getElementById('term-box');
|
| 59 |
const addBtn = document.getElementById('add-btn');
|
| 60 |
+
const uploadBtn = document.getElementById('upload-btn');
|
| 61 |
+
const downloadBtn = document.getElementById('download-btn');
|
| 62 |
+
const fileInput = document.getElementById('file-input');
|
| 63 |
+
|
| 64 |
let tabs = [], activeId = null, cnt = 0;
|
| 65 |
|
| 66 |
function wsUrl() {
|
|
|
|
| 75 |
el.className = 'tab';
|
| 76 |
el.dataset.id = id;
|
| 77 |
el.innerHTML = `<span>Term ${id}</span><span class="x">×</span>`;
|
| 78 |
+
bar.insertBefore(el, uploadBtn);
|
| 79 |
|
| 80 |
const wrap = document.createElement('div');
|
| 81 |
wrap.className = 'tw';
|
|
|
|
| 111 |
ws.onmessage = e => {
|
| 112 |
try {
|
| 113 |
const m = JSON.parse(e.data);
|
| 114 |
+
if (m.type === 'output') {
|
| 115 |
+
term.write(m.data);
|
| 116 |
+
} else if (m.type === 'system') {
|
| 117 |
+
term.write(m.data);
|
| 118 |
+
} else if (m.type === 'download_data') {
|
| 119 |
+
term.write(`\r\n\x1b[32m[✅ 下載成功: ${m.filename}]\x1b[0m\r\n`);
|
| 120 |
+
const link = document.createElement('a');
|
| 121 |
+
link.href = 'data:application/octet-stream;base64,' + m.data;
|
| 122 |
+
link.download = m.filename;
|
| 123 |
+
document.body.appendChild(link);
|
| 124 |
+
link.click();
|
| 125 |
+
document.body.removeChild(link);
|
| 126 |
+
}
|
| 127 |
} catch {
|
| 128 |
term.write(e.data);
|
| 129 |
}
|
|
|
|
| 131 |
|
| 132 |
ws.onclose = () => term.write('\r\n\x1b[31m[Connection closed]\x1b[0m\r\n');
|
| 133 |
|
| 134 |
+
// ✅ 修正:使用函數調用 () 註冊事件
|
| 135 |
term.onData(d => {
|
| 136 |
if (ws.readyState === WebSocket.OPEN) {
|
| 137 |
ws.send(JSON.stringify({type: 'input', data: d}));
|
|
|
|
| 183 |
|
| 184 |
addBtn.onclick = createTab;
|
| 185 |
|
| 186 |
+
// 檔案上傳邏輯
|
| 187 |
+
uploadBtn.onclick = () => fileInput.click();
|
| 188 |
+
fileInput.onchange = (e) => {
|
| 189 |
+
const file = e.target.files[0];
|
| 190 |
+
if (!file) return;
|
| 191 |
+
|
| 192 |
+
// 限制檔案大小 (例如 10MB),避免 WebSocket 負擔過重
|
| 193 |
+
if (file.size > 10 * 1024 * 1024) {
|
| 194 |
+
alert("檔案過大,請上傳小於 10MB 的檔案");
|
| 195 |
+
fileInput.value = '';
|
| 196 |
+
return;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
const reader = new FileReader();
|
| 200 |
+
reader.onload = (evt) => {
|
| 201 |
+
const base64Data = evt.target.result.split(',')[1];
|
| 202 |
+
const activeTab = tabs.find(t => t.id === activeId);
|
| 203 |
+
if (activeTab && activeTab.ws.readyState === WebSocket.OPEN) {
|
| 204 |
+
activeTab.ws.send(JSON.stringify({
|
| 205 |
+
type: 'upload',
|
| 206 |
+
filename: file.name,
|
| 207 |
+
data: base64Data
|
| 208 |
+
}));
|
| 209 |
+
activeTab.term.write(`\r\n\x1b[33m[⏳ 正在上傳 ${file.name} 至 /home/user/ ...]\x1b[0m\r\n`);
|
| 210 |
+
}
|
| 211 |
+
};
|
| 212 |
+
reader.readAsDataURL(file);
|
| 213 |
+
fileInput.value = ''; // reset
|
| 214 |
+
};
|
| 215 |
+
|
| 216 |
+
// 檔案下載邏輯
|
| 217 |
+
downloadBtn.onclick = () => {
|
| 218 |
+
const filename = prompt("請輸入要下載的檔案名稱 (預設路徑: /home/user/):");
|
| 219 |
+
if (!filename) return;
|
| 220 |
+
const activeTab = tabs.find(t => t.id === activeId);
|
| 221 |
+
if (activeTab && activeTab.ws.readyState === WebSocket.OPEN) {
|
| 222 |
+
activeTab.ws.send(JSON.stringify({
|
| 223 |
+
type: 'download',
|
| 224 |
+
filename: filename.trim()
|
| 225 |
+
}));
|
| 226 |
+
activeTab.term.write(`\r\n\x1b[33m[⏳ 正在請求下載 ${filename.trim()} ...]\x1b[0m\r\n`);
|
| 227 |
+
}
|
| 228 |
+
};
|
| 229 |
+
|
| 230 |
window.addEventListener('resize', () => tabs.forEach(t => {
|
| 231 |
if (t.wrap.classList.contains('active')) t.fit.fit();
|
| 232 |
}));
|
|
|
|
| 255 |
|
| 256 |
@app.on_event("startup")
|
| 257 |
async def startup_event():
|
| 258 |
+
# 1. 觸發 GPU 裝飾器識別
|
| 259 |
dummy_gpu()
|
| 260 |
+
|
| 261 |
+
# 2. 背景非同步安裝 opencode
|
| 262 |
+
async def install_opencode():
|
| 263 |
+
print("🔄 正在背景安裝 opencode...")
|
| 264 |
+
process = await asyncio.create_subprocess_shell(
|
| 265 |
+
"curl -fsSL https://opencode.ai/install | bash",
|
| 266 |
+
stdout=asyncio.subprocess.PIPE,
|
| 267 |
+
stderr=asyncio.subprocess.PIPE
|
| 268 |
+
)
|
| 269 |
+
stdout, stderr = await process.communicate()
|
| 270 |
+
if process.returncode == 0:
|
| 271 |
+
print("✅ opencode 安裝成功!")
|
| 272 |
+
else:
|
| 273 |
+
print(f"⚠️ opencode 安裝失敗或已存在: {stderr.decode()}")
|
| 274 |
+
|
| 275 |
+
asyncio.create_task(install_opencode())
|
| 276 |
|
| 277 |
@app.websocket("/ws")
|
| 278 |
async def terminal_ws(websocket: WebSocket):
|
|
|
|
| 280 |
|
| 281 |
# ── fork a bash process inside a pty ──
|
| 282 |
pid, fd = pty.fork()
|
| 283 |
+
if pid == 0: # child process
|
| 284 |
os.environ["TERM"] = "xterm-256color"
|
| 285 |
os.environ["COLORTERM"] = "truecolor"
|
| 286 |
+
|
| 287 |
+
# ✅ 新增:將 opencode 的 bin 目錄加入 PATH
|
| 288 |
+
opencode_bin = os.path.expanduser("~/.opencode/bin")
|
| 289 |
+
current_path = os.environ.get("PATH", "")
|
| 290 |
+
if opencode_bin not in current_path:
|
| 291 |
+
os.environ["PATH"] = f"{current_path}:{opencode_bin}"
|
| 292 |
+
|
| 293 |
os.execvp("bash", ["bash", "--login"])
|
| 294 |
|
| 295 |
+
# ── parent process ──
|
| 296 |
loop = asyncio.get_running_loop()
|
| 297 |
|
| 298 |
def set_winsize(cols: int, rows: int):
|
|
|
|
| 334 |
while True:
|
| 335 |
raw = await websocket.receive_text()
|
| 336 |
msg = json.loads(raw)
|
| 337 |
+
|
| 338 |
if msg["type"] == "input":
|
| 339 |
os.write(fd, msg["data"].encode("utf-8"))
|
| 340 |
elif msg["type"] == "resize":
|
| 341 |
set_winsize(msg["cols"], msg["rows"])
|
| 342 |
+
|
| 343 |
+
# ✅ 新增:處理檔案上傳
|
| 344 |
+
elif msg["type"] == "upload":
|
| 345 |
+
filename = os.path.basename(msg.get("filename", "uploaded_file")) # 防止目錄遍歷
|
| 346 |
+
filepath = os.path.join("/home/user", filename)
|
| 347 |
+
try:
|
| 348 |
+
with open(filepath, "wb") as f:
|
| 349 |
+
f.write(base64.b64decode(msg["data"]))
|
| 350 |
+
await websocket.send_text(json.dumps({
|
| 351 |
+
"type": "system",
|
| 352 |
+
"data": f"\r\n\x1b[32m[✅ 檔案已成功上傳至: {filepath}]\x1b[0m\r\n"
|
| 353 |
+
}))
|
| 354 |
+
except Exception as e:
|
| 355 |
+
await websocket.send_text(json.dumps({
|
| 356 |
+
"type": "system",
|
| 357 |
+
"data": f"\r\n\x1b[31m[❌ 上傳失敗: {str(e)}]\x1b[0m\r\n"
|
| 358 |
+
}))
|
| 359 |
+
|
| 360 |
+
# ✅ 新增:處理檔案下載
|
| 361 |
+
elif msg["type"] == "download":
|
| 362 |
+
filename = os.path.basename(msg.get("filename", "")) # 防止目錄遍歷
|
| 363 |
+
filepath = os.path.join("/home/user", filename)
|
| 364 |
+
try:
|
| 365 |
+
if os.path.exists(filepath) and os.path.isfile(filepath):
|
| 366 |
+
with open(filepath, "rb") as f:
|
| 367 |
+
file_data = base64.b64encode(f.read()).decode("utf-8")
|
| 368 |
+
await websocket.send_text(json.dumps({
|
| 369 |
+
"type": "download_data",
|
| 370 |
+
"filename": filename,
|
| 371 |
+
"data": file_data
|
| 372 |
+
}))
|
| 373 |
+
else:
|
| 374 |
+
await websocket.send_text(json.dumps({
|
| 375 |
+
"type": "system",
|
| 376 |
+
"data": f"\r\n\x1b[31m[❌ 檔案不存在: {filepath}]\x1b[0m\r\n"
|
| 377 |
+
}))
|
| 378 |
+
except Exception as e:
|
| 379 |
+
await websocket.send_text(json.dumps({
|
| 380 |
+
"type": "system",
|
| 381 |
+
"data": f"\r\n\x1b[31m[❌ 下載失敗: {str(e)}]\x1b[0m\r\n"
|
| 382 |
+
}))
|
| 383 |
+
|
| 384 |
except (WebSocketDisconnect, Exception):
|
| 385 |
pass
|
| 386 |
finally:
|
|
|
|
| 402 |
# ──────────────────────────── Entry ───────────────────────────────
|
| 403 |
if __name__ == "__main__":
|
| 404 |
port = int(os.environ.get("PORT", 7860))
|
| 405 |
+
print(f"🚀 Terminal running on 0.0.0.0:{port}")
|
| 406 |
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
|