HelloSun commited on
Commit
4f19b82
·
verified ·
1 Parent(s): 7cf33ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -37
app.py CHANGED
@@ -33,8 +33,8 @@ html,body{height:100%;overflow:hidden;background:#1e1e1e;color:#ccc;font-family:
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}
@@ -44,8 +44,10 @@ body{display:flex;flex-direction:column}
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;" />
@@ -57,11 +59,14 @@ body{display:flex;flex-direction:column}
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() {
67
  const p = location.protocol === 'https:' ? 'wss:' : 'ws:';
@@ -75,7 +80,7 @@ function createTab() {
75
  el.className = 'tab';
76
  el.dataset.id = id;
77
  el.innerHTML = `<span>Term ${id}</span><span class="x">&times;</span>`;
78
- bar.insertBefore(el, uploadBtn);
79
 
80
  const wrap = document.createElement('div');
81
  wrap.className = 'tw';
@@ -112,6 +117,14 @@ function createTab() {
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);
@@ -183,15 +196,42 @@ function closeTab(id) {
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
  }
@@ -204,24 +244,26 @@ fileInput.onchange = (e) => {
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
  }
@@ -247,7 +289,6 @@ createTab();
247
  async def index():
248
  return HTMLResponse(HTML_PAGE)
249
 
250
- # ✅ 修正:改為同步 def,並加入 queue=False 確保啟動時不卡排隊
251
  @spaces.GPU(duration=1, queue=False)
252
  def dummy_gpu():
253
  """空函數,僅用於讓平台識別到 GPU 裝飾器,滿足 Hugging Face 要求"""
@@ -255,10 +296,8 @@ def dummy_gpu():
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(
@@ -278,30 +317,27 @@ async def startup_event():
278
  async def terminal_ws(websocket: WebSocket):
279
  await websocket.accept()
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):
299
- fcntl.ioctl(fd, termios.TIOCSWINSZ,
300
- struct.pack("HHHH", rows, cols, 0, 0))
301
 
302
  set_winsize(120, 30)
303
 
304
- # non-blocking master fd
305
  fl = fcntl.fcntl(fd, fcntl.F_GETFL)
306
  fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
307
 
@@ -323,8 +359,8 @@ async def terminal_ws(websocket: WebSocket):
323
  break
324
  try:
325
  await websocket.send_text(
326
- json.dumps({"type": "output",
327
- "data": chunk.decode("utf-8", errors="replace")}))
328
  except Exception:
329
  break
330
 
@@ -340,10 +376,20 @@ async def terminal_ws(websocket: WebSocket):
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"]))
@@ -357,10 +403,19 @@ async def terminal_ws(websocket: WebSocket):
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:
@@ -398,8 +453,6 @@ async def terminal_ws(websocket: WebSocket):
398
  except Exception:
399
  pass
400
 
401
-
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}")
 
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
+ .action-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;white-space:nowrap}
37
+ .action-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}
 
44
  <body>
45
  <div id="tab-bar">
46
  <button id="add-btn" title="New Terminal (Ctrl+Shift+T)">+</button>
47
+ <button id="copy-btn" class="action-btn" title="Copy selected text">📋 複製</button>
48
+ <button id="paste-btn" class="action-btn" title="Paste to terminal">📌 貼上</button>
49
+ <button id="upload-btn" class="action-btn" title="Upload to current directory">📤 上傳</button>
50
+ <button id="download-btn" class="action-btn" title="Download from current directory">📥 下載</button>
51
  </div>
52
  <div id="term-box"></div>
53
  <input type="file" id="file-input" style="display:none;" />
 
59
  const bar = document.getElementById('tab-bar');
60
  const box = document.getElementById('term-box');
61
  const addBtn = document.getElementById('add-btn');
62
+ const copyBtn = document.getElementById('copy-btn');
63
+ const pasteBtn = document.getElementById('paste-btn');
64
  const uploadBtn = document.getElementById('upload-btn');
65
  const downloadBtn = document.getElementById('download-btn');
66
  const fileInput = document.getElementById('file-input');
67
 
68
  let tabs = [], activeId = null, cnt = 0;
69
+ let currentDir = "/home/user"; // 預設當前目錄,會由後端動態更新
70
 
71
  function wsUrl() {
72
  const p = location.protocol === 'https:' ? 'wss:' : 'ws:';
 
80
  el.className = 'tab';
81
  el.dataset.id = id;
82
  el.innerHTML = `<span>Term ${id}</span><span class="x">&times;</span>`;
83
+ bar.insertBefore(el, copyBtn);
84
 
85
  const wrap = document.createElement('div');
86
  wrap.className = 'tw';
 
117
  try {
118
  const m = JSON.parse(e.data);
119
  if (m.type === 'output') {
120
+ // ✅ 智能偵測當前目錄:攔截後端發送的 OSC 0 序列 (\x1b]0;PWD:/path\x07)
121
+ const pwdRegex = /\x1b\]0;PWD:(.*?)\x07/g;
122
+ let match;
123
+ while ((match = pwdRegex.exec(m.data)) !== null) {
124
+ currentDir = match[1];
125
+ }
126
+ // 從顯示中移除控制序列,避免污染終端畫面
127
+ m.data = m.data.replace(/\x1b\]0;PWD:.*?\x07/g, '');
128
  term.write(m.data);
129
  } else if (m.type === 'system') {
130
  term.write(m.data);
 
196
 
197
  addBtn.onclick = createTab;
198
 
199
+ // 📋 複製功能
200
+ copyBtn.onclick = async () => {
201
+ const text = term.getSelection();
202
+ if (text) {
203
+ try {
204
+ await navigator.clipboard.writeText(text);
205
+ term.write('\r\n\x1b[32m[✅ 已複製選取文字到系統剪貼簿]\x1b[0m\r\n');
206
+ } catch (err) {
207
+ term.write('\r\n\x1b[31m[❌ 複製失敗,請檢查瀏覽器權限]\x1b[0m\r\n');
208
+ }
209
+ } else {
210
+ term.write('\r\n\x1b[33m[⚠️ 請先用滑鼠在終端機中選取要複製的文字]\x1b[0m\r\n');
211
+ }
212
+ };
213
+
214
+ // 📌 貼上功能
215
+ pasteBtn.onclick = async () => {
216
+ try {
217
+ const text = await navigator.clipboard.readText();
218
+ const activeTab = tabs.find(t => t.id === activeId);
219
+ if (activeTab && activeTab.ws.readyState === WebSocket.OPEN) {
220
+ activeTab.ws.send(JSON.stringify({type: 'input', data: text}));
221
+ }
222
+ } catch (err) {
223
+ term.write('\r\n\x1b[31m[❌ 貼上失敗,請允許瀏覽器讀取剪貼簿權限]\x1b[0m\r\n');
224
+ }
225
+ };
226
+
227
+ // 📤 上傳功能
228
  uploadBtn.onclick = () => fileInput.click();
229
  fileInput.onchange = (e) => {
230
  const file = e.target.files[0];
231
  if (!file) return;
232
 
233
+ if (file.size > 15 * 1024 * 1024) {
234
+ alert("檔案過大,請上傳小於 15MB 的檔案");
 
235
  fileInput.value = '';
236
  return;
237
  }
 
244
  activeTab.ws.send(JSON.stringify({
245
  type: 'upload',
246
  filename: file.name,
247
+ data: base64Data,
248
+ targetDir: currentDir // ✅ 傳送當前偵測到的目錄
249
  }));
250
+ activeTab.term.write(`\r\n\x1b[33m[⏳ 正在上傳 ${file.name} 至 ${currentDir} ...]\x1b[0m\r\n`);
251
  }
252
  };
253
  reader.readAsDataURL(file);
254
+ fileInput.value = '';
255
  };
256
 
257
+ // 📥 下載功能
258
  downloadBtn.onclick = () => {
259
+ const filename = prompt(`請輸入要下載的檔案名稱:\n(預設目錄: ${currentDir})`);
260
  if (!filename) return;
261
  const activeTab = tabs.find(t => t.id === activeId);
262
  if (activeTab && activeTab.ws.readyState === WebSocket.OPEN) {
263
  activeTab.ws.send(JSON.stringify({
264
  type: 'download',
265
+ filename: filename.trim(),
266
+ targetDir: currentDir // ✅ 傳送當前偵測到的目錄
267
  }));
268
  activeTab.term.write(`\r\n\x1b[33m[⏳ 正在請求下載 ${filename.trim()} ...]\x1b[0m\r\n`);
269
  }
 
289
  async def index():
290
  return HTMLResponse(HTML_PAGE)
291
 
 
292
  @spaces.GPU(duration=1, queue=False)
293
  def dummy_gpu():
294
  """空函數,僅用於讓平台識別到 GPU 裝飾器,滿足 Hugging Face 要求"""
 
296
 
297
  @app.on_event("startup")
298
  async def startup_event():
 
299
  dummy_gpu()
300
 
 
301
  async def install_opencode():
302
  print("🔄 正在背景安裝 opencode...")
303
  process = await asyncio.create_subprocess_shell(
 
317
  async def terminal_ws(websocket: WebSocket):
318
  await websocket.accept()
319
 
 
320
  pid, fd = pty.fork()
321
+ if pid == 0:
322
  os.environ["TERM"] = "xterm-256color"
323
  os.environ["COLORTERM"] = "truecolor"
324
 
 
325
  opencode_bin = os.path.expanduser("~/.opencode/bin")
326
  current_path = os.environ.get("PATH", "")
327
  if opencode_bin not in current_path:
328
  os.environ["PATH"] = f"{current_path}:{opencode_bin}"
329
+
330
+ # ✅ 智能目錄追蹤:注入 PROMPT_COMMAND,每次顯示提示符時透過 OSC 0 序列報告當前目錄
331
+ bash_cmd = "export PROMPT_COMMAND='echo -ne \"\\033]0;PWD:$PWD\\007\"'; exec bash --login"
332
+ os.execvp("bash", ["bash", "-c", bash_cmd])
333
 
 
334
  loop = asyncio.get_running_loop()
335
 
336
  def set_winsize(cols: int, rows: int):
337
+ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
 
338
 
339
  set_winsize(120, 30)
340
 
 
341
  fl = fcntl.fcntl(fd, fcntl.F_GETFL)
342
  fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
343
 
 
359
  break
360
  try:
361
  await websocket.send_text(
362
+ json.dumps({"type": "output", "data": chunk.decode("utf-8", errors="replace")})
363
+ )
364
  except Exception:
365
  break
366
 
 
376
  elif msg["type"] == "resize":
377
  set_winsize(msg["cols"], msg["rows"])
378
 
 
379
  elif msg["type"] == "upload":
380
+ filename = os.path.basename(msg.get("filename", "uploaded_file"))
381
+ target_dir = msg.get("targetDir", "/home/user")
382
+
383
+ # ✅ 安全檢查:確保目錄在允許的範圍內,防止目錄遍歷攻擊
384
+ allowed_bases = ["/home/user", "/workspace", "/home/app"]
385
+ safe_dir = "/home/user"
386
+ abs_target = os.path.abspath(target_dir)
387
+ for base in allowed_bases:
388
+ if abs_target.startswith(base):
389
+ safe_dir = abs_target
390
+ break
391
+
392
+ filepath = os.path.join(safe_dir, filename)
393
  try:
394
  with open(filepath, "wb") as f:
395
  f.write(base64.b64decode(msg["data"]))
 
403
  "data": f"\r\n\x1b[31m[❌ 上傳失敗: {str(e)}]\x1b[0m\r\n"
404
  }))
405
 
 
406
  elif msg["type"] == "download":
407
+ filename = os.path.basename(msg.get("filename", ""))
408
+ target_dir = msg.get("targetDir", "/home/user")
409
+
410
+ allowed_bases = ["/home/user", "/workspace", "/home/app"]
411
+ safe_dir = "/home/user"
412
+ abs_target = os.path.abspath(target_dir)
413
+ for base in allowed_bases:
414
+ if abs_target.startswith(base):
415
+ safe_dir = abs_target
416
+ break
417
+
418
+ filepath = os.path.join(safe_dir, filename)
419
  try:
420
  if os.path.exists(filepath) and os.path.isfile(filepath):
421
  with open(filepath, "rb") as f:
 
453
  except Exception:
454
  pass
455
 
 
 
456
  if __name__ == "__main__":
457
  port = int(os.environ.get("PORT", 7860))
458
  print(f"🚀 Terminal running on 0.0.0.0:{port}")