fix(console): 웹 터미널 세션을 연결과 분리 — 탭 전환·새로고침·연결 끊김에도 셸/Claude가 서버에 남고 pty_attach 로 이어받음(출력 256KB 재생, 자동 재연결, 6시간 방치 시 정리)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-04 15:06:11 +09:00
1 parent 406068949b
commit 63ad050970
3 files changed
+97 -22

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
// 웹 터미널(pty) 세션 저장소 — 세션은 웹소켓 연결이 아니라 서버에 속한다.
// 탭 전환·페이지 이동·네트워크 끊김으로 연결이 닫혀도 셸/Claude Code 는 계속 돌고(출력은 뒤쪽 일부를 버퍼링),
// 새 연결이 pty_attach 로 같은 shellId 를 이어받는다. 연결 없이 IDLE_MS 지나면 정리한다. 게이트웨이 재시작은 세션을 끝낸다.
export interface PtyEntry {
proc: any;
username: string;
ws: any | null; // 현재 붙어 있는 연결(없으면 null)
buf: string; // 최근 출력(재접속 시 재생)
idle: NodeJS.Timeout | null;
}
export const PTY_BUF_MAX = 256 * 1024;
export const PTY_IDLE_MS = 6 * 60 * 60 * 1000; // 연결 없이 6시간
export const ptyStore = new Map<string, PtyEntry>();
export function ptyAppend(e: PtyEntry, data: string): void {
e.buf += data;
if (e.buf.length > PTY_BUF_MAX) e.buf = e.buf.slice(e.buf.length - PTY_BUF_MAX);
}
export function ptyDetach(e: PtyEntry, shellId: string): void {
e.ws = null;
if (e.idle) clearTimeout(e.idle);
e.idle = setTimeout(() => { try { e.proc.kill(); } catch { /* 이미 끝남 */ } ptyStore.delete(shellId); }, PTY_IDLE_MS);
e.idle.unref?.();
}
export function ptyAttach(e: PtyEntry, ws: any): void {
if (e.idle) { clearTimeout(e.idle); e.idle = null; }
e.ws = ws;
}
+28 -17
View File
@@ -61,6 +61,7 @@ import { registerSkillsRoutes } from './routes/routes-skills';
import { registerCodeRoutes } from './routes/routes-code';
import { registerClaudeFsRoutes } from './routes/routes-claude-fs';
import { getBuildInfo, buildLabel } from './build-info';
import { ptyStore, ptyAppend, ptyAttach, ptyDetach } from './pty-store';
import { ptyAccessDecision, resolveWorkshopCwd, resolvePcbCwd, allowedAutorun } from './pty-guard';
import { ensureSharedClaudeMemory, ensureProjectClaudeMd, ensurePcbClaudeMd } from './claude-memory';
import { loadWorkshop } from './routes/workshop-storage';
@@ -4741,7 +4742,8 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
}
// ── PTY terminal support ──
const ptySessions = new Map<string, any>(); // shellId → node-pty process
const ptyOwner = user?.username || ''; // 세션은 서버 전역(ptyStore)에 두고, 소유자만 이어받을 수 있다
const mine = (id: unknown) => { const e = typeof id === 'string' ? ptyStore.get(id) : undefined; return e && e.username === ptyOwner ? e : undefined; };
const ptyImport = import('node-pty').catch(() => null);
// 터미널(pty_*)은 로그인한 관리자 + 같은 Origin 의 연결만 — 아니면 어떤 pty 메시지도 처리하지 않는다.
@@ -4761,7 +4763,7 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
if (msg.type === 'pty_spawn') {
const shellId = msg.shellId;
if (!shellId || typeof shellId !== 'string') return;
if (ptySessions.has(shellId)) return; // already spawned
if (ptyStore.has(shellId)) return; // already spawned
try {
if (user?.username) { try { ensureUserWorkspace(user.username); } catch {} }
const ptyModule = await ptyImport;
@@ -4795,42 +4797,51 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
cwd: wsCwd || msg.cwd || user?.workspace || process.cwd(),
env: { ...process.env, TERM: 'xterm-256color' } as any,
});
ptySessions.set(shellId, proc);
const entry = { proc, username: ptyOwner, ws: ws as any, buf: '', idle: null as NodeJS.Timeout | null };
ptyStore.set(shellId, entry);
console.log(`[pty] open user=${user?.username} shell=${shellId} pid=${proc.pid}${wsCwd ? ` ${pcbCwd ? ` pcb=${msg.pcbProject}` : ` workshop=${msg.workshopProjectId}`}` : ''}`);
// 허용 목록의 명령만 셸이 뜬 직후 입력해 준다(claude 가 끝나면 셸로 돌아온다).
const auto = allowedAutorun(msg.autorun);
if (auto) setTimeout(() => { try { proc.write(auto + '\r'); } catch {} }, 500);
proc.onData((data: string) => {
try { ws.send(JSON.stringify({ type: 'pty_output', shellId, data })); } catch {}
ptyAppend(entry, data);
try { if (entry.ws) entry.ws.send(JSON.stringify({ type: 'pty_output', shellId, data })); } catch {}
});
proc.onExit(({ exitCode }: { exitCode: number }) => {
ptySessions.delete(shellId);
try { ws.send(JSON.stringify({ type: 'pty_exit', shellId, exitCode })); } catch {}
if (entry.idle) clearTimeout(entry.idle);
ptyStore.delete(shellId);
try { if (entry.ws) entry.ws.send(JSON.stringify({ type: 'pty_exit', shellId, exitCode })); } catch {}
});
} catch (err: any) {
try { ws.send(JSON.stringify({ type: 'pty_error', shellId, error: err.message })); } catch {}
}
} else if (msg.type === 'pty_input') {
const proc = ptySessions.get(msg.shellId);
const proc = mine(msg.shellId)?.proc;
if (proc) { try { proc.write(msg.data || ''); } catch {} }
} else if (msg.type === 'pty_resize') {
const proc = ptySessions.get(msg.shellId);
const proc = mine(msg.shellId)?.proc;
if (proc) { try { proc.resize(msg.cols || 120, msg.rows || 30); } catch {} }
} else if (msg.type === 'pty_kill') {
const proc = ptySessions.get(msg.shellId);
if (proc) {
try { proc.kill(); } catch {}
ptySessions.delete(msg.shellId);
const e = mine(msg.shellId);
if (e) {
try { e.proc.kill(); } catch {}
if (e.idle) clearTimeout(e.idle);
ptyStore.delete(msg.shellId);
}
} else if (msg.type === 'pty_attach') {
// 끊어졌다 다시 연결한 클라이언트가 같은 세션을 이어받는다(출력 버퍼 재생).
const e = mine(msg.shellId);
if (!e) { try { ws.send(JSON.stringify({ type: 'pty_gone', shellId: msg.shellId })); } catch {} return; }
if (e.ws && e.ws !== ws) { try { e.ws.send(JSON.stringify({ type: 'pty_error', shellId: msg.shellId, error: '다른 화면에서 이 세션을 이어받았습니다.' })); } catch {} }
ptyAttach(e, ws);
try { e.proc.resize(msg.cols || 120, msg.rows || 30); } catch {}
try { ws.send(JSON.stringify({ type: 'pty_attached', shellId: msg.shellId, buffer: e.buf })); } catch {}
}
});
ws.on('close', () => {
// Kill all PTY sessions for this connection
for (const [shellId, proc] of ptySessions) {
try { proc.kill(); } catch {}
}
ptySessions.clear();
// 터미널 세션은 죽이지 않고 떼어 둔다(다시 연결하면 pty_attach 로 이어받음, 오래 방치되면 정리).
for (const [shellId, e] of ptyStore) if (e.ws === ws) ptyDetach(e, shellId);
console.log(`[v2] WS disconnected${user ? ` (user: ${user.username})` : ''}`);
});
});
+41 -5
View File
@@ -5,6 +5,11 @@
// classic script — 작업실 전역(currentProject, authH …)을 공유한다. 처음 콘솔 탭을 열 때만 로드된다(switchTab → withLazyModule).
let consoleWs = null, consoleTerm = null, consoleFit = null;
let consoleShellId = null, consoleProjId = null, consoleOpen = false;
let consoleKeyStr = '', consoleRetry = 0, consoleRetryTimer = null;
// 세션은 서버에 남는다(2026-10-04): 탭 전환·페이지 이동·연결 끊김 뒤에도 같은 shellId 로 pty_attach 해 이어받는다.
function consoleKeyOf(proj) { return proj ? (proj.pcb ? 'pcb:' + proj.name : 'ws:' + proj.id) : ''; }
function consoleStored(key) { try { return JSON.parse(localStorage.getItem('console-session:' + key) || 'null'); } catch { return null; } }
function consoleStore(key, v) { try { if (v) localStorage.setItem('console-session:' + key, JSON.stringify(v)); else localStorage.removeItem('console-session:' + key); } catch {} }
function consoleLoadScript(src) {
return new Promise((resolve, reject) => {
@@ -39,16 +44,44 @@ function consoleWsConnect() {
const ws = new WebSocket(url);
ws.onopen = () => { consoleWs = ws; resolve(); };
ws.onerror = () => reject(new Error('웹소켓 연결 실패'));
ws.onclose = () => { if (consoleWs === ws) { consoleWs = null; if (consoleShellId) { consoleShellId = null; consoleStatus('연결이 끊어짐', '#ef4444'); } } };
ws.onclose = () => {
if (consoleWs !== ws) return;
consoleWs = null;
if (consoleShellId) { consoleStatus('연결 끊김 — 다시 연결하는 중…', '#f59e0b'); consoleScheduleReattach(); } // 세션은 서버에 살아 있다
};
ws.onmessage = ev => {
let m; try { m = JSON.parse(ev.data); } catch { return; }
if (!m.type || !m.type.startsWith('pty_') || m.shellId !== consoleShellId) return;
if (m.type === 'pty_output') consoleTerm.write(m.data);
else if (m.type === 'pty_exit') { consoleTerm.write('\r\n\x1b[90m[종료됨]\x1b[0m\r\n'); consoleShellId = null; consoleStatus('종료됨'); }
else if (m.type === 'pty_error') { consoleTerm.write('\r\n\x1b[31m터미널 오류: ' + (m.error || '?') + '\x1b[0m\r\n'); consoleShellId = null; consoleStatus('오류', '#ef4444'); }
else if (m.type === 'pty_attached') {
consoleRetry = 0; consoleTerm.reset(); consoleTerm.write(m.buffer || ''); consoleRefit();
consoleStatus('이어서 실행 중 — ' + ((currentProject() || {}).name || ''), '#22c55e'); consoleTerm.focus();
}
else if (m.type === 'pty_gone') { consoleStore(consoleKeyStr, null); consoleShellId = null; consoleStatus('이전 세션이 끝났습니다 — 다시 시작하세요'); }
else if (m.type === 'pty_exit') { consoleTerm.write('\r\n\x1b[90m[종료됨]\x1b[0m\r\n'); consoleStore(consoleKeyStr, null); consoleShellId = null; consoleStatus('종료됨'); }
else if (m.type === 'pty_error') { consoleTerm.write('\r\n\x1b[31m터미널 오류: ' + (m.error || '?') + '\x1b[0m\r\n'); if (!/이어받았/.test(m.error || '')) consoleStore(consoleKeyStr, null); consoleShellId = null; consoleStatus('오류', '#ef4444'); }
};
});
}
function consoleScheduleReattach() {
clearTimeout(consoleRetryTimer);
if (!consoleShellId || consoleRetry >= 20) { if (consoleShellId) consoleStatus('연결이 끊어짐 — 콘솔 탭을 다시 열면 이어붙습니다', '#ef4444'); return; }
consoleRetry++;
consoleRetryTimer = setTimeout(() => consoleReattach(), Math.min(1500 * consoleRetry, 10000));
}
async function consoleReattach() {
if (!consoleShellId || !consoleTerm) return;
try { await consoleWsConnect(); } catch { consoleScheduleReattach(); return; }
consoleSend({ type: 'pty_attach', shellId: consoleShellId, cols: consoleTerm.cols, rows: consoleTerm.rows });
}
// 이 프로젝트에 서버에 남아 있는 세션이 있으면 이어붙는다.
async function consoleResume() {
const proj = currentProject(); if (!proj || consoleShellId) return;
const key = consoleKeyOf(proj), st = consoleStored(key); if (!st || !st.shellId) return;
consoleKeyStr = key; consoleProjId = proj.id; consoleShellId = st.shellId; consoleRetry = 0;
consoleStatus('이전 세션에 이어붙는 중…', '#f59e0b');
await consoleReattach();
}
function consoleSend(obj) { if (consoleWs && consoleWs.readyState === WebSocket.OPEN) consoleWs.send(JSON.stringify(obj)); }
// 콘솔 탭이 열릴 때(switchTab). 터미널 요소만 만들고 세션은 사용자가 시작 버튼을 눌러야 시작한다(실수로 claude가 뜨지 않게).
@@ -70,6 +103,7 @@ async function openConsole() {
}
consoleOnProjectChange(true);
setTimeout(consoleRefit, 50);
consoleResume();
consoleTerm.focus();
}
function closeConsoleTab() { consoleOpen = false; } // 세션은 유지(탭만 숨김) — 다시 열면 이어서 쓴다
@@ -81,8 +115,9 @@ async function consoleStart(mode) {
await openConsole();
consoleStop(true);
try { await consoleWsConnect(); } catch (e) { consoleStatus(e.message, '#ef4444'); return; }
consoleProjId = proj.id;
consoleProjId = proj.id; consoleKeyStr = consoleKeyOf(proj); consoleRetry = 0;
consoleShellId = 'wsc_' + Date.now().toString(36);
consoleStore(consoleKeyStr, { shellId: consoleShellId, mode });
consoleTerm.reset();
consoleRefit();
const autorun = (mode === 'claude' || mode === 'claude-chrome' || mode === 'claude-ollama') ? mode : null;
@@ -98,7 +133,8 @@ function consoleClear() {
consoleTerm.write(CONSOLE_HINT);
}
function consoleStop(silent) {
if (consoleShellId) { consoleSend({ type: 'pty_kill', shellId: consoleShellId }); consoleShellId = null; }
clearTimeout(consoleRetryTimer);
if (consoleShellId) { consoleSend({ type: 'pty_kill', shellId: consoleShellId }); consoleShellId = null; consoleStore(consoleKeyStr, null); }
// 사용자가 ■ 종료를 눌렀을 때는 화면을 비운다(다시 시작할 때 이전 세션 내용과 섞이지 않게). silent는 재시작·프로젝트 전환 내부 호출.
if (!silent) { consoleClear(); consoleStatus('종료됨'); }
}