HelloSun commited on
Commit
87e68ae
·
verified ·
1 Parent(s): 6f60f0a

終端機改用 tmux:不同裝置各自尺寸、修正 opencode 擠歪與重新整理亂碼

Browse files
Files changed (1) hide show
  1. app.py +261 -113
app.py CHANGED
@@ -50,8 +50,6 @@ PRIMARY_SESSION_ID = "primary" # 第一頁的固定 id
50
  NEW_SESSION_ID = "__new__" # 舊前端要求「開新分頁」時仍相容
51
  MAX_TABS = int(os.environ.get("WEBTERM_MAX_TABS", "12"))
52
  TABS_FILE = os.path.join(HOME, ".webterm_tabs.json")
53
- # 每個 session 保留的畫面回放緩衝區大小上限(bytes)
54
- SESSION_BUFFER_MAX = 300_000
55
  # 本機測試時可跳過 opencode / 編輯器安裝
56
  SKIP_INSTALL = os.environ.get("WEBTERM_SKIP_INSTALL", "") == "1"
57
  # ──────────────────────────── Frontend ────────────────────────────
@@ -740,8 +738,8 @@ async def api_sessions():
740
  async with SESSIONS_LOCK:
741
  items = [{
742
  "id": s.id,
743
- "primary": s.id == PRIMARY_SESSION_ID,
744
- "persistent": s.persistent,
745
  "pid": s.pid,
746
  "cols": s.cols,
747
  "rows": s.rows,
@@ -749,15 +747,16 @@ async def api_sessions():
749
  "created_at": round(s.created_at, 3),
750
  "last_active": round(s.last_active, 3),
751
  "idle_seconds": round(now - s.last_active, 3),
752
- "buffer_bytes": len(s.buffer),
753
  } for s in SESSIONS.values()]
754
- return {"primary": PRIMARY_SESSION_ID, "max_tabs": MAX_TABS, "sessions": items}
 
755
 
756
 
757
  @app.get("/api/tabs")
758
  async def api_tabs():
759
  """共用分頁清單:所有裝置都以此為準。"""
760
- return {"tabs": tabs_snapshot(), "max_tabs": MAX_TABS}
 
761
 
762
 
763
  @app.post("/api/tabs")
@@ -768,7 +767,8 @@ async def api_new_tab():
768
  return JSONResponse({"error": str(exc)}, status_code=409)
769
  except OSError as exc:
770
  return JSONResponse({"error": f"無法建立終端機:{exc}"}, status_code=500)
771
- return {"tabs": tabs_snapshot(), "max_tabs": MAX_TABS}
 
772
 
773
 
774
  @app.delete("/api/tabs/{tab_id}")
@@ -777,7 +777,8 @@ async def api_delete_tab(tab_id: str):
777
  return JSONResponse({"error": "找不到分頁"}, status_code=404)
778
  if not await delete_shared_tab(tab_id):
779
  return JSONResponse({"error": "至少要保留一個分頁"}, status_code=409)
780
- return {"tabs": tabs_snapshot(), "max_tabs": MAX_TABS}
 
781
 
782
 
783
  # ──────────────────────────── 背景安裝任務 ────────────────────────────
@@ -967,6 +968,9 @@ def dummy_gpu():
967
  @app.on_event("startup")
968
  async def startup_event():
969
  _load_tabs()
 
 
 
970
  dummy_gpu()
971
  if SKIP_INSTALL:
972
  log.info("WEBTERM_SKIP_INSTALL=1:跳過 opencode / 編輯器安裝")
@@ -981,18 +985,26 @@ async def startup_event():
981
  asyncio.create_task(install_editors())
982
 
983
 
984
- # ──────────────────────────── Terminal Session 管理 ──────────────────────────────
985
- # 核心概念:pty(bash 進程)的生命週期跟 WebSocket 連線脫鉤,而且**所有分頁**都是
986
- # 共用、長存的:WebSocket 斷線/頁面重新整理只是少了一個「訂閱者」,背後的 bash
987
- # 依然在跑。只有使用者明確關閉分頁(DELETE /api/tabs/{id})才會真正砍掉該 session。
 
988
 
989
- SESSIONS: dict[str, "TerminalSession"] = {}
 
 
 
990
  SESSIONS_LOCK = asyncio.Lock()
 
 
 
991
 
992
  # 共用分頁清單(順序即顯示順序),持久化到 TABS_FILE。
993
  TABS: list[str] = []
994
  TABS_LOCK = asyncio.Lock()
995
  TAB_CREATE_LOCK = asyncio.Lock()
 
996
 
997
 
998
  def _tab_title(tab_id: str) -> str:
@@ -1032,9 +1044,8 @@ def _save_tabs():
1032
 
1033
 
1034
  def _new_tab_id() -> str:
1035
- used = set(TABS) | set(SESSIONS)
1036
  n = 2
1037
- while f"tab-{n}" in used:
1038
  n += 1
1039
  return f"tab-{n}"
1040
 
@@ -1042,38 +1053,162 @@ def _new_tab_id() -> str:
1042
  def tabs_snapshot() -> list[dict]:
1043
  out = []
1044
  for tab_id in TABS:
1045
- sess = SESSIONS.get(tab_id)
1046
  out.append({
1047
  "id": tab_id,
1048
  "title": _tab_title(tab_id),
1049
- "alive": sess is not None,
1050
- "subscribers": len(sess.subscribers) if sess else 0,
1051
- "pid": sess.pid if sess else None,
1052
- "created_at": round(sess.created_at, 3) if sess else None,
1053
- "buffer_bytes": len(sess.buffer) if sess else 0,
 
1054
  })
1055
  return out
1056
 
1057
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1058
  class TerminalSession:
1059
- def __init__(self, session_id: str, pid: int, fd: int, cols: int = 120, rows: int = 30):
 
 
 
1060
  self.id = session_id
 
1061
  self.pid = pid
1062
  self.fd = fd
1063
  self.cols = cols
1064
  self.rows = rows
1065
- self.persistent = True # 所有分頁都是共用長存,永不閒置清除
1066
  self.created_at = time.time()
1067
  self.last_active = self.created_at
1068
- self.buffer = bytearray() # 畫面回放緩衝區,供重連時還原終端機畫面
1069
  self.subscribers: dict[int, asyncio.Queue] = {}
1070
  self._next_sub_id = 0
 
 
 
1071
 
1072
  def add_subscriber(self):
1073
  self.last_active = time.time()
1074
  sid = self._next_sub_id
1075
  self._next_sub_id += 1
1076
  q: asyncio.Queue = asyncio.Queue()
 
 
 
1077
  self.subscribers[sid] = q
1078
  return sid, q
1079
 
@@ -1082,10 +1217,12 @@ class TerminalSession:
1082
  self.last_active = time.time()
1083
 
1084
  def feed(self, data: bytes):
1085
- self.buffer.extend(data)
1086
- overflow = len(self.buffer) - SESSION_BUFFER_MAX
1087
- if overflow > 0:
1088
- del self.buffer[:overflow]
 
 
1089
  dead = []
1090
  for sid, q in self.subscribers.items():
1091
  try:
@@ -1100,35 +1237,39 @@ def _set_winsize(fd: int, cols: int, rows: int):
1100
  fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
1101
 
1102
 
1103
- def _fork_shell():
1104
  working_dir = os.path.join(HOME, "app")
1105
  os.makedirs(working_dir, exist_ok=True)
1106
  pid, fd = pty.fork()
1107
  if pid == 0:
1108
- os.chdir(working_dir)
1109
- os.environ["TERM"] = "xterm-256color"
1110
- os.environ["COLORTERM"] = "truecolor"
1111
- os.environ.setdefault("EDITOR", "vim")
1112
-
1113
- opencode_bin = os.path.expanduser("~/.opencode/bin")
1114
- current_path = os.environ.get("PATH", "")
1115
- if opencode_bin not in current_path:
1116
- os.environ["PATH"] = f"{current_path}:{opencode_bin}"
1117
-
1118
- bash_cmd = (
1119
- "export PROMPT_COMMAND='echo -ne \"\\033]0;PWD:$PWD\\007\"'; "
1120
- "exec bash --login"
1121
- )
1122
- os.execvp("bash", ["bash", "-c", bash_cmd])
1123
  return pid, fd
1124
 
1125
 
1126
- async def create_session(cols: int = 120, rows: int = 30,
1127
- session_id: str | None = None) -> TerminalSession:
1128
- pid, fd = _fork_shell()
1129
 
1130
- session_id = session_id or uuid.uuid4().hex[:12]
1131
- sess = TerminalSession(session_id, pid, fd, cols, rows)
 
 
 
 
1132
 
1133
  _set_winsize(fd, cols, rows)
1134
  fl = fcntl.fcntl(fd, fcntl.F_GETFL)
@@ -1142,7 +1283,7 @@ async def create_session(cols: int = 120, rows: int = 30,
1142
  except (BlockingIOError, OSError):
1143
  return
1144
  if not data:
1145
- # bash 行程已結束(例如使用者在終端機內打了 exit)
1146
  try:
1147
  loop.remove_reader(fd)
1148
  except Exception:
@@ -1155,48 +1296,50 @@ async def create_session(cols: int = 120, rows: int = 30,
1155
 
1156
  async with SESSIONS_LOCK:
1157
  SESSIONS[session_id] = sess
 
1158
  return sess
1159
 
1160
 
1161
- async def get_or_create_tab(tab_id: str, cols: int = 120,
1162
- rows: int = 30) -> tuple[TerminalSession | None, bool]:
1163
- """回傳(共用分頁的 session, 是否為接回)。分頁不存在於清單時回傳 (None, False)。"""
1164
- async with TAB_CREATE_LOCK:
1165
- sess = SESSIONS.get(tab_id)
1166
- if sess is not None:
1167
- return sess, True
1168
- if tab_id not in TABS:
1169
- return None, False
1170
- sess = await create_session(cols, rows, session_id=tab_id)
1171
- if tab_id not in TABS: # 建立期間被其他裝置關閉
1172
- await kill_session(tab_id, asyncio.get_running_loop())
1173
- return None, False
1174
- log.info("已建立共用分頁 session(id=%s)", tab_id)
1175
- return sess, False
1176
-
1177
-
1178
- async def create_shared_tab(cols: int = 120, rows: int = 30) -> TerminalSession:
1179
  async with TABS_LOCK:
1180
  if len(TABS) >= MAX_TABS:
1181
  raise ValueError(f"分頁數量已達上限({MAX_TABS})")
1182
  tab_id = _new_tab_id()
1183
  TABS.append(tab_id)
1184
  _save_tabs()
1185
- sess, _ = await get_or_create_tab(tab_id, cols, rows)
1186
- if sess is None: # 極端競態:清單剛被刪掉
1187
- raise OSError("分頁建立失敗")
 
 
 
 
 
1188
  log.info("已建立共用分頁 %s(共 %d 頁)", tab_id, len(TABS))
1189
- return sess
1190
 
1191
 
1192
  async def delete_shared_tab(tab_id: str) -> bool:
1193
- """明確關閉分頁:從清單移除並終止 PTY(所有裝置都會一起消失)。"""
1194
  async with TABS_LOCK:
1195
  if tab_id not in TABS or len(TABS) <= 1:
1196
  return False
1197
  TABS.remove(tab_id)
1198
  _save_tabs()
1199
- await kill_session(tab_id, asyncio.get_running_loop())
 
 
 
 
 
 
 
 
 
 
 
 
 
1200
  log.info("已關閉共用分頁 %s(剩 %d 頁)", tab_id, len(TABS))
1201
  return True
1202
 
@@ -1225,6 +1368,12 @@ async def _reap_process(pid: int, loop: asyncio.AbstractEventLoop):
1225
  async def kill_session(session_id: str, loop: asyncio.AbstractEventLoop, already_dead: bool = False):
1226
  async with SESSIONS_LOCK:
1227
  sess = SESSIONS.pop(session_id, None)
 
 
 
 
 
 
1228
  if not sess:
1229
  return
1230
  try:
@@ -1242,7 +1391,7 @@ async def kill_session(session_id: str, loop: asyncio.AbstractEventLoop, already
1242
  q.put_nowait(None)
1243
  except Exception:
1244
  pass
1245
- log.info("session %s 已清除", session_id)
1246
 
1247
 
1248
  # ──────────────────────────── Terminal WebSocket ──────────────────────────────
@@ -1261,7 +1410,7 @@ async def terminal_ws(websocket: WebSocket):
1261
 
1262
  # 共用分頁:
1263
  # * 沒有帶 session_id(新裝置/新瀏覽器)→ 接到清單第一頁
1264
- # * 帶清單內的 id → 接回;PTY 不在了(app 重啟/exit)→ 用同一個 id 重建
1265
  # * id 已不在清單(被其他裝置關閉)→ 告知前端收掉這一頁,不再重連
1266
  # * session_id=__new__(舊前端按 +)→ 直接開一個新的共用分頁
1267
  if not requested_id:
@@ -1269,7 +1418,7 @@ async def terminal_ws(websocket: WebSocket):
1269
 
1270
  if requested_id == NEW_SESSION_ID:
1271
  try:
1272
- sess = await create_shared_tab(cols, rows)
1273
  except (OSError, ValueError) as e:
1274
  await websocket.send_text(json.dumps({
1275
  "type": "system",
@@ -1277,43 +1426,44 @@ async def terminal_ws(websocket: WebSocket):
1277
  }))
1278
  await websocket.close()
1279
  return
1280
- reattached = False
1281
  else:
1282
- sess, reattached = await get_or_create_tab(requested_id, cols, rows)
 
 
 
 
 
 
 
 
1283
 
1284
- if sess is None:
1285
- try:
1286
- await websocket.send_text(json.dumps({"type": "deleted", "id": requested_id}))
1287
- except Exception:
1288
- pass
 
 
1289
  await websocket.close()
1290
  return
1291
 
1292
- # 告知前端這次連線對應的 session id,讓前端存起來,日後斷線重連 / 重新整理都能接回同一個
1293
  await websocket.send_text(json.dumps({
1294
- "type": "session", "id": sess.id, "reattached": reattached,
1295
- "primary": sess.id == PRIMARY_SESSION_ID,
1296
  }))
1297
 
1298
- if reattached:
1299
- if sess.buffer:
1300
- try:
1301
- # 先清畫面再回放,避免新裝置接到半個畫面
1302
- await websocket.send_text(json.dumps({
1303
- "type": "output",
1304
- "data": "\x1b[2J\x1b[3J\x1b[H" + bytes(sess.buffer).decode("utf-8", errors="replace"),
1305
- }))
1306
- except Exception:
1307
- pass
1308
  try:
1309
  await websocket.send_text(json.dumps({
1310
  "type": "system",
1311
- "data": "\r\n\x1b[32m[✅ 已重新連線,畫面已還原]\x1b[0m\r\n",
1312
  }))
1313
  except Exception:
1314
  pass
1315
  elif requested_id != NEW_SESSION_ID:
1316
- # 分頁還在清單裡,但先前的 PTY 已結束(exit/app 重啟),已用同一個分頁重建
1317
  try:
1318
  await websocket.send_text(json.dumps({
1319
  "type": "system",
@@ -1324,14 +1474,6 @@ async def terminal_ws(websocket: WebSocket):
1324
 
1325
  sub_id, queue = sess.add_subscriber()
1326
 
1327
- if reattached:
1328
- # 觸發 SIGWINCH,讓 TUI(opencode 等)重畫目前畫面;新裝置才不會只看到殘缺的回放
1329
- try:
1330
- _set_winsize(sess.fd, sess.cols, max(1, sess.rows - 1))
1331
- _set_winsize(sess.fd, sess.cols, sess.rows)
1332
- except Exception:
1333
- pass
1334
-
1335
  async def _pty_to_ws():
1336
  while True:
1337
  chunk = await queue.get()
@@ -1357,6 +1499,10 @@ async def terminal_ws(websocket: WebSocket):
1357
  mtype = msg.get("type")
1358
 
1359
  if mtype == "input":
 
 
 
 
1360
  try:
1361
  os.write(sess.fd, msg["data"].encode("utf-8"))
1362
  except OSError:
@@ -1364,8 +1510,9 @@ async def terminal_ws(websocket: WebSocket):
1364
 
1365
  elif mtype == "resize":
1366
  try:
1367
- sess.cols, sess.rows = msg["cols"], msg["rows"]
1368
- _set_winsize(sess.fd, msg["cols"], msg["rows"])
 
1369
  except Exception:
1370
  pass
1371
 
@@ -1395,7 +1542,7 @@ async def terminal_ws(websocket: WebSocket):
1395
  elif mtype == "kill":
1396
  # 明確關閉分頁 = 所有裝置一起關閉(分頁清單同步移除)。
1397
  # 若只剩最後一頁則不關,只解除這條連線的訂閱。
1398
- if not await delete_shared_tab(sess.id):
1399
  try:
1400
  await websocket.send_text(json.dumps({
1401
  "type": "system",
@@ -1411,9 +1558,10 @@ async def terminal_ws(websocket: WebSocket):
1411
  log.exception("terminal_ws 循環發生未預期錯誤")
1412
  finally:
1413
  sender.cancel()
1414
- # 注意:這裡「不」殺掉 pty/bash,只是移除這個訂閱者,
1415
- # 讓 session 保留在 SESSIONS 裡,等待同一個分頁重連接回。
1416
  sess.remove_subscriber(sub_id, loop)
 
1417
 
1418
 
1419
  if __name__ == "__main__":
 
50
  NEW_SESSION_ID = "__new__" # 舊前端要求「開新分頁」時仍相容
51
  MAX_TABS = int(os.environ.get("WEBTERM_MAX_TABS", "12"))
52
  TABS_FILE = os.path.join(HOME, ".webterm_tabs.json")
 
 
53
  # 本機測試時可跳過 opencode / 編輯器安裝
54
  SKIP_INSTALL = os.environ.get("WEBTERM_SKIP_INSTALL", "") == "1"
55
  # ──────────────────────────── Frontend ────────────────────────────
 
738
  async with SESSIONS_LOCK:
739
  items = [{
740
  "id": s.id,
741
+ "tab_id": s.tab_id,
742
+ "primary": s.tab_id == PRIMARY_SESSION_ID,
743
  "pid": s.pid,
744
  "cols": s.cols,
745
  "rows": s.rows,
 
747
  "created_at": round(s.created_at, 3),
748
  "last_active": round(s.last_active, 3),
749
  "idle_seconds": round(now - s.last_active, 3),
 
750
  } for s in SESSIONS.values()]
751
+ return {"primary": PRIMARY_SESSION_ID, "max_tabs": MAX_TABS,
752
+ "tmux": bool(shutil.which("tmux")), "sessions": items}
753
 
754
 
755
  @app.get("/api/tabs")
756
  async def api_tabs():
757
  """共用分頁清單:所有裝置都以此為準。"""
758
+ return {"tabs": tabs_snapshot(), "max_tabs": MAX_TABS,
759
+ "tmux": bool(shutil.which("tmux"))}
760
 
761
 
762
  @app.post("/api/tabs")
 
767
  return JSONResponse({"error": str(exc)}, status_code=409)
768
  except OSError as exc:
769
  return JSONResponse({"error": f"無法建立終端機:{exc}"}, status_code=500)
770
+ return {"tabs": tabs_snapshot(), "max_tabs": MAX_TABS,
771
+ "tmux": bool(shutil.which("tmux"))}
772
 
773
 
774
  @app.delete("/api/tabs/{tab_id}")
 
777
  return JSONResponse({"error": "找不到分頁"}, status_code=404)
778
  if not await delete_shared_tab(tab_id):
779
  return JSONResponse({"error": "至少要保留一個分頁"}, status_code=409)
780
+ return {"tabs": tabs_snapshot(), "max_tabs": MAX_TABS,
781
+ "tmux": bool(shutil.which("tmux"))}
782
 
783
 
784
  # ──────────────────────────── 背景安裝任務 ────────────────────────────
 
968
  @app.on_event("startup")
969
  async def startup_event():
970
  _load_tabs()
971
+ _write_shell_launcher()
972
+ await ensure_tmux()
973
+ _reconcile_tmux()
974
  dummy_gpu()
975
  if SKIP_INSTALL:
976
  log.info("WEBTERM_SKIP_INSTALL=1:跳過 opencode / 編輯器安裝")
 
985
  asyncio.create_task(install_editors())
986
 
987
 
988
+ # ──────────────────────────── Terminal Session 管理(tmux)──────────────────────────────
989
+ # 每個分頁 = 一個 tmux session(真正共用、長存的 shell);每個瀏覽器分頁 = 一條獨立的
990
+ # tmux client attach。不同裝置可以有不同終端機大小,由 tmux 針對每個 client 重畫,
991
+ # 所以不會再出現「手機把電腦畫面擠歪」或「重新整理後亂碼」。
992
+ # WebSocket 斷線只會 detach 該 client,tmux session(opencode)繼續跑。
993
 
994
+ TMUX_SOCKET = "webterm"
995
+ TMUX_PREFIX = "wt_"
996
+
997
+ SESSIONS: dict[str, "TerminalSession"] = {} # 每條 WebSocket 連線一個 attach pty
998
  SESSIONS_LOCK = asyncio.Lock()
999
+ ATTACHMENTS: dict[str, set[str]] = {} # tab_id -> {session_id}
1000
+ LIVE_TABS: set[str] = set() # 已知存在的 tmux session
1001
+ WINDOW_SIZES: dict[str, tuple[int, int]] = {} # 目前 tmux window 大小
1002
 
1003
  # 共用分頁清單(順序即顯示順序),持久化到 TABS_FILE。
1004
  TABS: list[str] = []
1005
  TABS_LOCK = asyncio.Lock()
1006
  TAB_CREATE_LOCK = asyncio.Lock()
1007
+ SHELL_LAUNCHER = os.path.join(HOME, ".webterm_shell.sh")
1008
 
1009
 
1010
  def _tab_title(tab_id: str) -> str:
 
1044
 
1045
 
1046
  def _new_tab_id() -> str:
 
1047
  n = 2
1048
+ while f"tab-{n}" in TABS:
1049
  n += 1
1050
  return f"tab-{n}"
1051
 
 
1053
  def tabs_snapshot() -> list[dict]:
1054
  out = []
1055
  for tab_id in TABS:
1056
+ attached = ATTACHMENTS.get(tab_id, set())
1057
  out.append({
1058
  "id": tab_id,
1059
  "title": _tab_title(tab_id),
1060
+ "alive": tab_id in LIVE_TABS,
1061
+ "subscribers": len(attached),
1062
+ "pid": next((SESSIONS[s].pid for s in attached if s in SESSIONS), None),
1063
+ "cols": WINDOW_SIZES.get(tab_id, (None, None))[0],
1064
+ "rows": WINDOW_SIZES.get(tab_id, (None, None))[1],
1065
+ "buffer_bytes": 0,
1066
  })
1067
  return out
1068
 
1069
 
1070
+ # ── tmux 輔助函式 ────────────────────────────────────────────────────────────
1071
+
1072
+ def _tmux(*args, timeout: float = 5) -> subprocess.CompletedProcess:
1073
+ return subprocess.run(
1074
+ ["tmux", "-L", TMUX_SOCKET, *args],
1075
+ capture_output=True, text=True, timeout=timeout,
1076
+ )
1077
+
1078
+
1079
+ def _tmux_name(tab_id: str) -> str:
1080
+ return TMUX_PREFIX + tab_id
1081
+
1082
+
1083
+ def _reconcile_tmux():
1084
+ """app 重啟後,把仍然存活的 tmux session 接回分頁清單(opencode 不會被重啟)。"""
1085
+ if not shutil.which("tmux"):
1086
+ return
1087
+ try:
1088
+ r = _tmux("list-sessions", "-F", "#S")
1089
+ except (OSError, subprocess.SubprocessError):
1090
+ return
1091
+ if r.returncode != 0: # 沒有任何 session
1092
+ return
1093
+ names = set((r.stdout or "").split())
1094
+ for name in names:
1095
+ if not name.startswith(TMUX_PREFIX):
1096
+ continue
1097
+ tab_id = name[len(TMUX_PREFIX):]
1098
+ if tab_id in TABS:
1099
+ LIVE_TABS.add(tab_id)
1100
+ else:
1101
+ try:
1102
+ _tmux("kill-session", "-t", name)
1103
+ except (OSError, subprocess.SubprocessError):
1104
+ pass
1105
+
1106
+
1107
+ def _write_shell_launcher():
1108
+ """建立 tmux 內 shell 的啟動腳本(保留 PWD 提示,讓上傳功能知道目前目錄)。"""
1109
+ content = (
1110
+ "#!/bin/bash\n"
1111
+ "export PROMPT_COMMAND='echo -ne \"\\033]0;PWD:$PWD\\007\"'\n"
1112
+ "exec bash --login\n"
1113
+ )
1114
+ try:
1115
+ old = ""
1116
+ if os.path.isfile(SHELL_LAUNCHER):
1117
+ with open(SHELL_LAUNCHER) as f:
1118
+ old = f.read()
1119
+ if old != content:
1120
+ with open(SHELL_LAUNCHER, "w") as f:
1121
+ f.write(content)
1122
+ os.chmod(SHELL_LAUNCHER, 0o755)
1123
+ except OSError as exc:
1124
+ log.warning("無法建立 shell launcher %s: %s", SHELL_LAUNCHER, exc)
1125
+
1126
+
1127
+ def _ensure_tmux_session(tab_id: str) -> bool:
1128
+ """確保分頁對應的 tmux session 存在(不存在就建立)。"""
1129
+ if not shutil.which("tmux"):
1130
+ return False
1131
+ name = _tmux_name(tab_id)
1132
+ working_dir = os.path.join(HOME, "app")
1133
+ os.makedirs(working_dir, exist_ok=True)
1134
+ try:
1135
+ if _tmux("has-session", "-t", name).returncode == 0:
1136
+ LIVE_TABS.add(tab_id)
1137
+ return True
1138
+ r = _tmux("new-session", "-d", "-s", name, "-c", working_dir,
1139
+ "-x", "120", "-y", "30", SHELL_LAUNCHER)
1140
+ if r.returncode != 0:
1141
+ log.warning("tmux new-session(%s) 失敗: %s", tab_id, (r.stderr or "").strip()[:300])
1142
+ return False
1143
+ # 由我們明確控制 window 大小(attach / resize / 輸入時套用該 client 的尺寸),
1144
+ # 避免 tmux 自己挑到另一台裝置的尺寸。
1145
+ _tmux("set-option", "-t", name, "window-size", "manual")
1146
+ _tmux("set-option", "-t", name, "aggressive-resize", "on")
1147
+ _tmux("set-option", "-t", name, "history-limit", "10000")
1148
+ LIVE_TABS.add(tab_id)
1149
+ return True
1150
+ except (OSError, subprocess.SubprocessError) as exc:
1151
+ log.warning("tmux 操作失敗(%s): %s", tab_id, exc)
1152
+ return False
1153
+
1154
+
1155
+ def _tmux_resize(tab_id: str, cols: int, rows: int):
1156
+ try:
1157
+ _tmux("resize-window", "-t", _tmux_name(tab_id),
1158
+ "-x", str(max(2, cols)), "-y", str(max(2, rows)))
1159
+ except (OSError, subprocess.SubprocessError):
1160
+ pass
1161
+
1162
+
1163
+ async def _apply_window_size(tab_id: str, cols: int, rows: int):
1164
+ cols, rows = max(2, int(cols)), max(2, int(rows))
1165
+ if WINDOW_SIZES.get(tab_id) == (cols, rows):
1166
+ return
1167
+ WINDOW_SIZES[tab_id] = (cols, rows)
1168
+ await asyncio.to_thread(_tmux_resize, tab_id, cols, rows)
1169
+
1170
+
1171
+ async def ensure_tmux() -> bool:
1172
+ """確保 tmux 可用(Space 由 packages.txt 預裝;缺少時嘗試 apt 安裝)。"""
1173
+ if shutil.which("tmux"):
1174
+ return True
1175
+ log.warning("找不到 tmux,嘗試安裝 ...")
1176
+ for prefix in ("", "sudo "):
1177
+ rc, _out, err = await _run(f"{prefix}apt-get update -y && {prefix}apt-get install -y tmux")
1178
+ if rc == 0 and shutil.which("tmux"):
1179
+ log.info("✅ tmux 安裝成功")
1180
+ return True
1181
+ log.error("❌ tmux 安裝失敗,終端機分頁無法使用")
1182
+ return False
1183
+
1184
+
1185
  class TerminalSession:
1186
+ """一條 WebSocket 連線對應的 tmux client attach(不是共用 shell 本體)。"""
1187
+
1188
+ def __init__(self, session_id: str, tab_id: str, pid: int, fd: int,
1189
+ cols: int = 120, rows: int = 30):
1190
  self.id = session_id
1191
+ self.tab_id = tab_id
1192
  self.pid = pid
1193
  self.fd = fd
1194
  self.cols = cols
1195
  self.rows = rows
 
1196
  self.created_at = time.time()
1197
  self.last_active = self.created_at
 
1198
  self.subscribers: dict[int, asyncio.Queue] = {}
1199
  self._next_sub_id = 0
1200
+ # 這條 attach 在 WebSocket 訂閱者就緒前先收到的畫面(tmux 一 attach 就會重畫)。
1201
+ # 只屬於這條連線、尺寸一致,回放不會造成別台裝置的亂碼。
1202
+ self.buffer = bytearray()
1203
 
1204
  def add_subscriber(self):
1205
  self.last_active = time.time()
1206
  sid = self._next_sub_id
1207
  self._next_sub_id += 1
1208
  q: asyncio.Queue = asyncio.Queue()
1209
+ if self.buffer:
1210
+ q.put_nowait(bytes(self.buffer))
1211
+ self.buffer.clear()
1212
  self.subscribers[sid] = q
1213
  return sid, q
1214
 
 
1217
  self.last_active = time.time()
1218
 
1219
  def feed(self, data: bytes):
1220
+ if not self.subscribers:
1221
+ self.buffer.extend(data)
1222
+ overflow = len(self.buffer) - 300_000
1223
+ if overflow > 0:
1224
+ del self.buffer[:overflow]
1225
+ return
1226
  dead = []
1227
  for sid, q in self.subscribers.items():
1228
  try:
 
1237
  fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
1238
 
1239
 
1240
+ def _fork_tmux_attach(tab_id: str):
1241
  working_dir = os.path.join(HOME, "app")
1242
  os.makedirs(working_dir, exist_ok=True)
1243
  pid, fd = pty.fork()
1244
  if pid == 0:
1245
+ try:
1246
+ os.chdir(working_dir)
1247
+ os.environ["TERM"] = "xterm-256color"
1248
+ os.environ["COLORTERM"] = "truecolor"
1249
+ os.environ.setdefault("EDITOR", "vim")
1250
+
1251
+ opencode_bin = os.path.expanduser("~/.opencode/bin")
1252
+ current_path = os.environ.get("PATH", "")
1253
+ if opencode_bin not in current_path:
1254
+ os.environ["PATH"] = f"{current_path}:{opencode_bin}"
1255
+
1256
+ os.execvp("tmux", ["tmux", "-L", TMUX_SOCKET,
1257
+ "attach-session", "-t", _tmux_name(tab_id)])
1258
+ except Exception:
1259
+ os._exit(127)
1260
  return pid, fd
1261
 
1262
 
1263
+ async def create_attachment(tab_id: str, cols: int = 120, rows: int = 30) -> TerminalSession:
1264
+ if not await asyncio.to_thread(_ensure_tmux_session, tab_id):
1265
+ raise OSError("tmux 無法啟動(請確認已安裝 tmux)")
1266
 
1267
+ # 先把 tmux window 調成這台裝置的大小,TUI(opencode)才會用正確尺寸重畫。
1268
+ await _apply_window_size(tab_id, cols, rows)
1269
+
1270
+ pid, fd = _fork_tmux_attach(tab_id)
1271
+ session_id = uuid.uuid4().hex[:12]
1272
+ sess = TerminalSession(session_id, tab_id, pid, fd, cols, rows)
1273
 
1274
  _set_winsize(fd, cols, rows)
1275
  fl = fcntl.fcntl(fd, fcntl.F_GETFL)
 
1283
  except (BlockingIOError, OSError):
1284
  return
1285
  if not data:
1286
+ # tmux client 結束(detach/session 被關)
1287
  try:
1288
  loop.remove_reader(fd)
1289
  except Exception:
 
1296
 
1297
  async with SESSIONS_LOCK:
1298
  SESSIONS[session_id] = sess
1299
+ ATTACHMENTS.setdefault(tab_id, set()).add(session_id)
1300
  return sess
1301
 
1302
 
1303
+ async def create_shared_tab(cols: int = 120, rows: int = 30) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1304
  async with TABS_LOCK:
1305
  if len(TABS) >= MAX_TABS:
1306
  raise ValueError(f"分頁數量已達上限({MAX_TABS})")
1307
  tab_id = _new_tab_id()
1308
  TABS.append(tab_id)
1309
  _save_tabs()
1310
+
1311
+ if not await asyncio.to_thread(_ensure_tmux_session, tab_id):
1312
+ async with TABS_LOCK:
1313
+ if tab_id in TABS:
1314
+ TABS.remove(tab_id)
1315
+ _save_tabs()
1316
+ raise OSError("tmux 無法啟動(請確認已安裝 tmux)")
1317
+
1318
  log.info("已建立共用分頁 %s(共 %d 頁)", tab_id, len(TABS))
1319
+ return tab_id
1320
 
1321
 
1322
  async def delete_shared_tab(tab_id: str) -> bool:
1323
+ """明確關閉分頁:從清單移除、殺掉 tmux session,所有裝置一起消失。"""
1324
  async with TABS_LOCK:
1325
  if tab_id not in TABS or len(TABS) <= 1:
1326
  return False
1327
  TABS.remove(tab_id)
1328
  _save_tabs()
1329
+
1330
+ LIVE_TABS.discard(tab_id)
1331
+ WINDOW_SIZES.pop(tab_id, None)
1332
+
1333
+ if shutil.which("tmux"):
1334
+ try:
1335
+ await asyncio.to_thread(lambda: _tmux("kill-session", "-t", _tmux_name(tab_id)))
1336
+ except (OSError, subprocess.SubprocessError):
1337
+ pass
1338
+
1339
+ loop = asyncio.get_running_loop()
1340
+ for sid in list(ATTACHMENTS.get(tab_id, ())):
1341
+ await kill_session(sid, loop)
1342
+ ATTACHMENTS.pop(tab_id, None)
1343
  log.info("已關閉共用分頁 %s(剩 %d 頁)", tab_id, len(TABS))
1344
  return True
1345
 
 
1368
  async def kill_session(session_id: str, loop: asyncio.AbstractEventLoop, already_dead: bool = False):
1369
  async with SESSIONS_LOCK:
1370
  sess = SESSIONS.pop(session_id, None)
1371
+ if sess is not None:
1372
+ attached = ATTACHMENTS.get(sess.tab_id)
1373
+ if attached is not None:
1374
+ attached.discard(session_id)
1375
+ if not attached:
1376
+ ATTACHMENTS.pop(sess.tab_id, None)
1377
  if not sess:
1378
  return
1379
  try:
 
1391
  q.put_nowait(None)
1392
  except Exception:
1393
  pass
1394
+ log.info("tmux attach %s(分頁 %s)已清除", session_id, sess.tab_id)
1395
 
1396
 
1397
  # ──────────────────────────── Terminal WebSocket ──────────────────────────────
 
1410
 
1411
  # 共用分頁:
1412
  # * 沒有帶 session_id(新裝置/新瀏覽器)→ 接到清單第一頁
1413
+ # * 帶清單內的 id → attach 到該分頁的 tmux session(不存在就建立)
1414
  # * id 已不在清單(被其他裝置關閉)→ 告知前端收掉這一頁,不再重連
1415
  # * session_id=__new__(舊前端按 +)→ 直接開一個新的共用分頁
1416
  if not requested_id:
 
1418
 
1419
  if requested_id == NEW_SESSION_ID:
1420
  try:
1421
+ tab_id = await create_shared_tab(cols, rows)
1422
  except (OSError, ValueError) as e:
1423
  await websocket.send_text(json.dumps({
1424
  "type": "system",
 
1426
  }))
1427
  await websocket.close()
1428
  return
1429
+ was_live = False
1430
  else:
1431
+ tab_id = requested_id
1432
+ if tab_id not in TABS:
1433
+ try:
1434
+ await websocket.send_text(json.dumps({"type": "deleted", "id": tab_id}))
1435
+ except Exception:
1436
+ pass
1437
+ await websocket.close()
1438
+ return
1439
+ was_live = tab_id in LIVE_TABS
1440
 
1441
+ try:
1442
+ sess = await create_attachment(tab_id, cols, rows)
1443
+ except OSError as e:
1444
+ await websocket.send_text(json.dumps({
1445
+ "type": "system",
1446
+ "data": f"\r\n\x1b[31m[❌ 無法連接終端機:{e}]\x1b[0m\r\n",
1447
+ }))
1448
  await websocket.close()
1449
  return
1450
 
1451
+ # 告知前端這次連線對應的分頁 id(前端用它接回同一個 tmux session)
1452
  await websocket.send_text(json.dumps({
1453
+ "type": "session", "id": tab_id, "reattached": was_live,
1454
+ "primary": tab_id == PRIMARY_SESSION_ID,
1455
  }))
1456
 
1457
+ if was_live:
 
 
 
 
 
 
 
 
 
1458
  try:
1459
  await websocket.send_text(json.dumps({
1460
  "type": "system",
1461
+ "data": "\r\n\x1b[32m[✅ 已接回原工作階段]\x1b[0m\r\n",
1462
  }))
1463
  except Exception:
1464
  pass
1465
  elif requested_id != NEW_SESSION_ID:
1466
+ # 分頁還在清單裡,但 tmux session 已結束(exit/app 重啟),已重建
1467
  try:
1468
  await websocket.send_text(json.dumps({
1469
  "type": "system",
 
1474
 
1475
  sub_id, queue = sess.add_subscriber()
1476
 
 
 
 
 
 
 
 
 
1477
  async def _pty_to_ws():
1478
  while True:
1479
  chunk = await queue.get()
 
1499
  mtype = msg.get("type")
1500
 
1501
  if mtype == "input":
1502
+ # 誰在輸入,tmux window 就切成誰的尺寸:這樣兩台裝置大小不同時,
1503
+ # 正在操作的那台 TUI(opencode)一定正確,另一台只會被裁切、不會亂碼。
1504
+ if WINDOW_SIZES.get(tab_id) != (sess.cols, sess.rows):
1505
+ await _apply_window_size(tab_id, sess.cols, sess.rows)
1506
  try:
1507
  os.write(sess.fd, msg["data"].encode("utf-8"))
1508
  except OSError:
 
1510
 
1511
  elif mtype == "resize":
1512
  try:
1513
+ sess.cols, sess.rows = int(msg["cols"]), int(msg["rows"])
1514
+ _set_winsize(sess.fd, sess.cols, sess.rows)
1515
+ await _apply_window_size(tab_id, sess.cols, sess.rows)
1516
  except Exception:
1517
  pass
1518
 
 
1542
  elif mtype == "kill":
1543
  # 明確關閉分頁 = 所有裝置一起關閉(分頁清單同步移除)。
1544
  # 若只剩最後一頁則不關,只解除這條連線的訂閱。
1545
+ if not await delete_shared_tab(tab_id):
1546
  try:
1547
  await websocket.send_text(json.dumps({
1548
  "type": "system",
 
1558
  log.exception("terminal_ws 循環發生未預期錯誤")
1559
  finally:
1560
  sender.cancel()
1561
+ # 只結束「這條 WebSocket 的 tmux client attach」,tmux session(opencode)
1562
+ # 本身保留,其他裝置或重新整理後仍可接回同一個分頁。
1563
  sess.remove_subscriber(sub_id, loop)
1564
+ await kill_session(sess.id, loop)
1565
 
1566
 
1567
  if __name__ == "__main__":