HelloSun commited on
Commit
645251f
·
verified ·
1 Parent(s): f3b4dc5

Fix multi-client tmux rendering: smallest window-size, attach only visible tab, reset xterm on reattach

Browse files
Files changed (2) hide show
  1. README.md +10 -2
  2. app.py +71 -38
README.md CHANGED
@@ -29,8 +29,16 @@ OpenCode 在啟動時安裝,並重設使用者層級設定為預設值。
29
  - **每個分頁 = 一個 tmux session**:真正共用的 shell 在 tmux 裡,每個瀏覽器分頁只是
30
  一條 tmux client attach。因此不同裝置可以有不同終端機大小,tmux 會針對每個 client
31
  重畫畫面:
32
- - 手機接進來不會再把電腦的畫面擠歪;誰在輸入,tmux window 就切成誰的尺寸。
33
- - 重新整理/重連時由 tmux 直接重畫,不再回放舊的 raw bytes,所以不會出現亂碼。
 
 
 
 
 
 
 
 
34
  - 斷線只會 detach 該 client,`opencode` 與所有程序都留在 tmux session 裡。
35
  - **分頁清單由伺服器統一管理**:`GET /api/tabs` 回傳目前所有共用分頁,所有裝置看到的
36
  分頁完全相同。按 `+` 開的新分頁(`POST /api/tabs`)會出現在每一台裝置上。
 
29
  - **每個分頁 = 一個 tmux session**:真正共用的 shell 在 tmux 裡,每個瀏覽器分頁只是
30
  一條 tmux client attach。因此不同裝置可以有不同終端機大小,tmux 會針對每個 client
31
  重畫畫面:
32
+ - window 大小由 tmux 依**所有目前附掛的 client 自動計算(`window-size smallest`)**,
33
+ 取最小的那台,並自動扣掉狀態列。window 一定放得進每台裝置的可視區域,因此不會有
34
+ 錯位、殘影或亂碼。較大的裝置會看到 tmux 以 `·` 填滿、外框標出 window 範圍。
35
+ - 輸入、重連都**不會**改動 window 大小(舊版每次按鍵都會切換尺寸,多裝置會互相拉扯)。
36
+ 手機/小視窗離線後,window 會自動放大回剩下那台的尺寸。
37
+ - 每條連線在 URL 帶上自己的 `cols`/`rows`,第一次重畫就是正確大小。
38
+ - 前端只有**可見的分頁**會保持連線;切走的分頁立即 detach,不以錯誤尺寸拖累其他裝置。
39
+ - 每次(重新)附掛,前端都會 `term.reset()` 清空本機畫面後再接收 tmux 的完整重畫,
40
+ 重連或重新整理不會把新舊畫面疊在一起。
41
+ - 多位元組字元(中文)用增量 UTF-8 解碼,不會在切斷處產生亂碼。
42
  - 斷線只會 detach 該 client,`opencode` 與所有程序都留在 tmux session 裡。
43
  - **分頁清單由伺服器統一管理**:`GET /api/tabs` 回傳目前所有共用分頁,所有裝置看到的
44
  分頁完全相同。按 `+` 開的新分頁(`POST /api/tabs`)會出現在每一台裝置上。
app.py CHANGED
@@ -10,6 +10,7 @@ import struct
10
  import fcntl
11
  import termios
12
  import asyncio
 
13
  import json
14
  import base64
15
  import logging
@@ -260,10 +261,14 @@ function setAppStatus(message, kind = 'info') {
260
  appStatus.title = clean;
261
  }
262
 
263
- function wsUrl(sessionId) {
264
  const p = location.protocol === 'https:' ? 'wss:' : 'ws:';
265
  let url = `${p}//${location.host}/ws`;
266
- if (sessionId) url += `?session_id=${encodeURIComponent(sessionId)}`;
 
 
 
 
267
  return url;
268
  }
269
 
@@ -303,12 +308,31 @@ async function apiDeleteTab(id) {
303
  return data;
304
  }
305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  function connect(tabObj) {
307
- const ws = new WebSocket(wsUrl(tabObj.sessionId));
308
  tabObj.ws = ws;
309
  tabObj.reconnectDelay = tabObj.reconnectDelay || 500;
310
 
311
  ws.onopen = () => {
 
312
  const wasDown = tabObj.el.querySelector('.status-dot').classList.contains('down');
313
  tabObj.reconnectDelay = 500;
314
  tabObj.el.querySelector('.status-dot').classList.remove('down');
@@ -317,12 +341,16 @@ function connect(tabObj) {
317
  };
318
 
319
  ws.onmessage = e => {
 
320
  try {
321
  const m = JSON.parse(e.data);
322
  if (m.type === 'session') {
323
  // 伺服器告訴我們這條連線對應的 session id:記住它,下次斷線/重整才能接回同一個終端機
324
  tabObj.sessionId = m.id;
325
  tabObj.shared = true;
 
 
 
326
  const titleEl = tabObj.el.querySelector('.tab-title');
327
  if (titleEl) titleEl.textContent = tabTitle(m.id);
328
  if (m.reattached) setAppStatus(`${tabTitle(m.id)} 已接回原工作階段`, 'success');
@@ -348,11 +376,12 @@ function connect(tabObj) {
348
  };
349
 
350
  ws.onclose = () => {
351
- if (tabObj.closed) return;
 
352
  tabObj.el.querySelector('.status-dot').classList.add('down');
353
  setAppStatus(`終端機 ${tabObj.id} 連線中斷,${(tabObj.reconnectDelay/1000).toFixed(1)} 秒後自動重連`, 'error');
354
  setTimeout(() => {
355
- if (!tabObj.closed) connect(tabObj);
356
  }, tabObj.reconnectDelay);
357
  tabObj.reconnectDelay = Math.min(tabObj.reconnectDelay * 1.7, 8000);
358
  };
@@ -433,9 +462,9 @@ function createTab(sessionId = null, title = null, activateIt = true) {
433
  term.open(wrap);
434
  fit.fit();
435
 
436
- const obj = {id, type: 'terminal', el, wrap, term, fit, ws: null, closed: false, currentDir: '~', sessionId: sessionId || null, shared: true};
437
  tabs.push(obj);
438
- connect(obj);
439
  saveActive();
440
 
441
  term.attachCustomKeyEventHandler(e => {
@@ -559,6 +588,10 @@ function activate(id) {
559
  const on = t.id === id;
560
  t.el.classList.toggle('active', on);
561
  t.wrap.classList.toggle('active', on);
 
 
 
 
562
  if (on && t.type === 'desktop') {
563
  setTimeout(() => {
564
  try {
@@ -2720,7 +2753,7 @@ SESSIONS: dict[str, "TerminalSession"] = {} # 每條 WebSocket 連線一個 at
2720
  SESSIONS_LOCK = asyncio.Lock()
2721
  ATTACHMENTS: dict[str, set[str]] = {} # tab_id -> {session_id}
2722
  LIVE_TABS: set[str] = set() # 已知存在的 tmux session
2723
- WINDOW_SIZES: dict[str, tuple[int, int]] = {} # 目前 tmux window 大小
2724
 
2725
  # 共用分頁清單(順序即顯示順序),持久化到 TABS_FILE。
2726
  TABS: list[str] = []
@@ -2848,6 +2881,19 @@ def _write_shell_launcher():
2848
  log.warning("無法建立 shell launcher %s: %s", SHELL_LAUNCHER, exc)
2849
 
2850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2851
  def _ensure_tmux_session(tab_id: str) -> bool:
2852
  """確保分頁對應的 tmux session 存在(不存在就建立)。"""
2853
  if not shutil.which("tmux"):
@@ -2857,6 +2903,7 @@ def _ensure_tmux_session(tab_id: str) -> bool:
2857
  os.makedirs(working_dir, exist_ok=True)
2858
  try:
2859
  if _tmux("has-session", "-t", name).returncode == 0:
 
2860
  LIVE_TABS.add(tab_id)
2861
  return True
2862
  r = _tmux("new-session", "-d", "-s", name, "-c", working_dir,
@@ -2864,11 +2911,7 @@ def _ensure_tmux_session(tab_id: str) -> bool:
2864
  if r.returncode != 0:
2865
  log.warning("tmux new-session(%s) 失敗: %s", tab_id, (r.stderr or "").strip()[:300])
2866
  return False
2867
- # 由我們明確控制 window 大小(attach / resize / 輸入時套用該 client 的尺寸),
2868
- # 避免 tmux 自己挑到另一台裝置的尺寸。
2869
- _tmux("set-option", "-t", name, "window-size", "manual")
2870
- _tmux("set-option", "-t", name, "aggressive-resize", "on")
2871
- _tmux("set-option", "-t", name, "history-limit", "10000")
2872
  LIVE_TABS.add(tab_id)
2873
  return True
2874
  except (OSError, subprocess.SubprocessError) as exc:
@@ -2876,20 +2919,9 @@ def _ensure_tmux_session(tab_id: str) -> bool:
2876
  return False
2877
 
2878
 
2879
- def _tmux_resize(tab_id: str, cols: int, rows: int):
2880
- try:
2881
- _tmux("resize-window", "-t", _tmux_name(tab_id),
2882
- "-x", str(max(2, cols)), "-y", str(max(2, rows)))
2883
- except (OSError, subprocess.SubprocessError):
2884
- pass
2885
-
2886
-
2887
- async def _apply_window_size(tab_id: str, cols: int, rows: int):
2888
- cols, rows = max(2, int(cols)), max(2, int(rows))
2889
- if WINDOW_SIZES.get(tab_id) == (cols, rows):
2890
- return
2891
- WINDOW_SIZES[tab_id] = (cols, rows)
2892
- await asyncio.to_thread(_tmux_resize, tab_id, cols, rows)
2893
 
2894
 
2895
  async def ensure_tmux() -> bool:
@@ -2988,8 +3020,9 @@ async def create_attachment(tab_id: str, cols: int = 120, rows: int = 30) -> Ter
2988
  if not await asyncio.to_thread(_ensure_tmux_session, tab_id):
2989
  raise OSError("tmux 無法啟動(請確認已安裝 tmux)")
2990
 
2991
- # 先把 tmux window 調成這台裝置的大小,TUI(opencode)才會用正確尺寸重畫。
2992
- await _apply_window_size(tab_id, cols, rows)
 
2993
 
2994
  pid, fd = _fork_tmux_attach(tab_id)
2995
  session_id = uuid.uuid4().hex[:12]
@@ -3199,14 +3232,17 @@ async def terminal_ws(websocket: WebSocket):
3199
  sub_id, queue = sess.add_subscriber()
3200
 
3201
  async def _pty_to_ws():
 
 
3202
  while True:
3203
  chunk = await queue.get()
3204
  if chunk is None:
3205
  break
 
 
 
3206
  try:
3207
- await websocket.send_text(
3208
- json.dumps({"type": "output", "data": chunk.decode("utf-8", errors="replace")})
3209
- )
3210
  except Exception:
3211
  break
3212
 
@@ -3223,10 +3259,7 @@ async def terminal_ws(websocket: WebSocket):
3223
  mtype = msg.get("type")
3224
 
3225
  if mtype == "input":
3226
- # ��在輸入,tmux window 就切成誰的尺寸:這樣兩台裝置大小不同時,
3227
- # 正在操作的那台 TUI(opencode)一定正確,另一台只會被裁切、不會亂碼。
3228
- if WINDOW_SIZES.get(tab_id) != (sess.cols, sess.rows):
3229
- await _apply_window_size(tab_id, sess.cols, sess.rows)
3230
  try:
3231
  os.write(sess.fd, msg["data"].encode("utf-8"))
3232
  except OSError:
@@ -3235,8 +3268,8 @@ async def terminal_ws(websocket: WebSocket):
3235
  elif mtype == "resize":
3236
  try:
3237
  sess.cols, sess.rows = int(msg["cols"]), int(msg["rows"])
3238
- _set_winsize(sess.fd, sess.cols, sess.rows)
3239
- await _apply_window_size(tab_id, sess.cols, sess.rows)
3240
  except Exception:
3241
  pass
3242
 
 
10
  import fcntl
11
  import termios
12
  import asyncio
13
+ import codecs
14
  import json
15
  import base64
16
  import logging
 
261
  appStatus.title = clean;
262
  }
263
 
264
+ function wsUrl(sessionId, cols, rows) {
265
  const p = location.protocol === 'https:' ? 'wss:' : 'ws:';
266
  let url = `${p}//${location.host}/ws`;
267
+ const q = [];
268
+ if (sessionId) q.push(`session_id=${encodeURIComponent(sessionId)}`);
269
+ // 附掛時就帶上這台裝置的可視尺寸,伺服器據此建立 tmux client,第一次重畫就是正確大小。
270
+ if (cols && rows) q.push(`cols=${cols}`, `rows=${rows}`);
271
+ if (q.length) url += '?' + q.join('&');
272
  return url;
273
  }
274
 
 
308
  return data;
309
  }
310
 
311
+ // 附掛(attach)分頁:只有「目前可見」的終端機分頁會保持連線。
312
+ // 背景分頁不連線,所以它的尺寸不會被 tmux 算進 window-size(smallest)去拖累其他裝置。
313
+ function attachTab(t) {
314
+ if (t.type !== 'terminal' || t.closed) return;
315
+ t.detached = false;
316
+ if (t.ws && (t.ws.readyState === WebSocket.OPEN || t.ws.readyState === WebSocket.CONNECTING)) return;
317
+ t.fit.fit(); // 先量測實際可視區域,讓 URL 帶上正確尺寸
318
+ connect(t);
319
+ }
320
+
321
+ function detachTab(t) {
322
+ if (t.type !== 'terminal') return;
323
+ t.detached = true;
324
+ const ws = t.ws;
325
+ t.ws = null;
326
+ if (ws) { try { ws.close(); } catch (e) { /* ignore */ } }
327
+ }
328
+
329
  function connect(tabObj) {
330
+ const ws = new WebSocket(wsUrl(tabObj.sessionId, tabObj.term.cols, tabObj.term.rows));
331
  tabObj.ws = ws;
332
  tabObj.reconnectDelay = tabObj.reconnectDelay || 500;
333
 
334
  ws.onopen = () => {
335
+ if (tabObj.ws !== ws) return;
336
  const wasDown = tabObj.el.querySelector('.status-dot').classList.contains('down');
337
  tabObj.reconnectDelay = 500;
338
  tabObj.el.querySelector('.status-dot').classList.remove('down');
 
341
  };
342
 
343
  ws.onmessage = e => {
344
+ if (tabObj.ws !== ws) return; // 舊連線(已 detach 或已被新連線取代)的訊息一律忽略
345
  try {
346
  const m = JSON.parse(e.data);
347
  if (m.type === 'session') {
348
  // 伺服器告訴我們這條連線對應的 session id:記住它,下次斷線/重整才能接回同一個終端機
349
  tabObj.sessionId = m.id;
350
  tabObj.shared = true;
351
+ // 每次(重新)附掛,tmux 都會從頭重畫整個畫面。先清空本機 xterm(含捲動緩衝),
352
+ // 否則新畫面會疊在舊畫面上,這就是重連後「畫面混亂」的來源。
353
+ tabObj.term.reset();
354
  const titleEl = tabObj.el.querySelector('.tab-title');
355
  if (titleEl) titleEl.textContent = tabTitle(m.id);
356
  if (m.reattached) setAppStatus(`${tabTitle(m.id)} 已接回原工作階段`, 'success');
 
376
  };
377
 
378
  ws.onclose = () => {
379
+ // 已被 detach、已關閉,或已被新連線取代:不做自動重連
380
+ if (tabObj.closed || tabObj.detached || tabObj.ws !== ws) return;
381
  tabObj.el.querySelector('.status-dot').classList.add('down');
382
  setAppStatus(`終端機 ${tabObj.id} 連線中斷,${(tabObj.reconnectDelay/1000).toFixed(1)} 秒後自動重連`, 'error');
383
  setTimeout(() => {
384
+ if (!tabObj.closed && !tabObj.detached && tabObj.ws === ws) connect(tabObj);
385
  }, tabObj.reconnectDelay);
386
  tabObj.reconnectDelay = Math.min(tabObj.reconnectDelay * 1.7, 8000);
387
  };
 
462
  term.open(wrap);
463
  fit.fit();
464
 
465
+ const obj = {id, type: 'terminal', el, wrap, term, fit, ws: null, closed: false, detached: true, currentDir: '~', sessionId: sessionId || null, shared: true};
466
  tabs.push(obj);
467
+ // 不在這裡連線:只有分頁可見(activate)時才 attach,見 attachTab()。
468
  saveActive();
469
 
470
  term.attachCustomKeyEventHandler(e => {
 
588
  const on = t.id === id;
589
  t.el.classList.toggle('active', on);
590
  t.wrap.classList.toggle('active', on);
591
+ if (t.type === 'terminal') {
592
+ // 只有可見的終端機分頁保持連線;切走的分頁立即 detach
593
+ if (on) attachTab(t); else detachTab(t);
594
+ }
595
  if (on && t.type === 'desktop') {
596
  setTimeout(() => {
597
  try {
 
2753
  SESSIONS_LOCK = asyncio.Lock()
2754
  ATTACHMENTS: dict[str, set[str]] = {} # tab_id -> {session_id}
2755
  LIVE_TABS: set[str] = set() # 已知存在的 tmux session
2756
+ WINDOW_SIZES: dict[str, tuple[int, int]] = {} # 最近一次附掛的 client 尺寸(僅除錯用)
2757
 
2758
  # 共用分頁清單(順序即顯示順序),持久化到 TABS_FILE。
2759
  TABS: list[str] = []
 
2881
  log.warning("無法建立 shell launcher %s: %s", SHELL_LAUNCHER, exc)
2882
 
2883
 
2884
+ def _tmux_apply_options(name: str):
2885
+ """每次附掛前都套用(舊版留下的 session 也會被修正)。
2886
+
2887
+ window-size smallest:tmux 依「所有目前附掛的 client」計算 window 大小,取最小值,
2888
+ 並自動扣掉每台裝置自己的狀態列。這樣任何一台 client 的可視區域都一定放得下
2889
+ window,不會出現「window 比畫面大」造成的上下錯位、殘影與亂碼。
2890
+ 不再用 resize-window 手動指定尺寸,也不會因為某台裝置按鍵就切換整個 window 的大小。
2891
+ """
2892
+ _tmux("set-option", "-w", "-t", name, "window-size", "smallest")
2893
+ _tmux("set-option", "-w", "-t", name, "aggressive-resize", "off")
2894
+ _tmux("set-option", "-t", name, "history-limit", "10000")
2895
+
2896
+
2897
  def _ensure_tmux_session(tab_id: str) -> bool:
2898
  """確保分頁對應的 tmux session 存在(不存在就建立)。"""
2899
  if not shutil.which("tmux"):
 
2903
  os.makedirs(working_dir, exist_ok=True)
2904
  try:
2905
  if _tmux("has-session", "-t", name).returncode == 0:
2906
+ _tmux_apply_options(name)
2907
  LIVE_TABS.add(tab_id)
2908
  return True
2909
  r = _tmux("new-session", "-d", "-s", name, "-c", working_dir,
 
2911
  if r.returncode != 0:
2912
  log.warning("tmux new-session(%s) 失敗: %s", tab_id, (r.stderr or "").strip()[:300])
2913
  return False
2914
+ _tmux_apply_options(name)
 
 
 
 
2915
  LIVE_TABS.add(tab_id)
2916
  return True
2917
  except (OSError, subprocess.SubprocessError) as exc:
 
2919
  return False
2920
 
2921
 
2922
+ def _remember_client_size(tab_id: str, cols: int, rows: int):
2923
+ """只記錄最近一次附掛的 client 尺寸(除錯用)。實際 window 尺寸由 tmux 依 client 計算。"""
2924
+ WINDOW_SIZES[tab_id] = (max(2, int(cols)), max(2, int(rows)))
 
 
 
 
 
 
 
 
 
 
 
2925
 
2926
 
2927
  async def ensure_tmux() -> bool:
 
3020
  if not await asyncio.to_thread(_ensure_tmux_session, tab_id):
3021
  raise OSError("tmux 無法啟動(請確認已安裝 tmux)")
3022
 
3023
+ # 不手動調整 tmux window:附掛的 pty 尺寸就是這台裝置的可視區域,
3024
+ # tmux 會依所有 client 自動計算 window 大小並重畫這台的畫面。
3025
+ _remember_client_size(tab_id, cols, rows)
3026
 
3027
  pid, fd = _fork_tmux_attach(tab_id)
3028
  session_id = uuid.uuid4().hex[:12]
 
3232
  sub_id, queue = sess.add_subscriber()
3233
 
3234
  async def _pty_to_ws():
3235
+ # 增量解碼:tmux 的輸出可能在多位元組字元(中文)中間切斷,逐塊 decode 會變成亂碼。
3236
+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
3237
  while True:
3238
  chunk = await queue.get()
3239
  if chunk is None:
3240
  break
3241
+ text = decoder.decode(chunk)
3242
+ if not text:
3243
+ continue
3244
  try:
3245
+ await websocket.send_text(json.dumps({"type": "output", "data": text}))
 
 
3246
  except Exception:
3247
  break
3248
 
 
3259
  mtype = msg.get("type")
3260
 
3261
  if mtype == "input":
3262
+ # 只轉送按鍵。window 大小由 tmux 依所有 client 計算,輸入不會改動大小。
 
 
 
3263
  try:
3264
  os.write(sess.fd, msg["data"].encode("utf-8"))
3265
  except OSError:
 
3268
  elif mtype == "resize":
3269
  try:
3270
  sess.cols, sess.rows = int(msg["cols"]), int(msg["rows"])
3271
+ _set_winsize(sess.fd, sess.cols, sess.rows) # tmux 收到 SIGWINCH 後自行重算
3272
+ _remember_client_size(tab_id, sess.cols, sess.rows)
3273
  except Exception:
3274
  pass
3275