diff --git a/src/gateway/pty-store.ts b/src/gateway/pty-store.ts index 26ea3b7..38774f0 100644 --- a/src/gateway/pty-store.ts +++ b/src/gateway/pty-store.ts @@ -7,6 +7,9 @@ export interface PtyEntry { ws: any | null; // 현재 붙어 있는 연결(없으면 null) buf: string; // 최근 출력(재접속 시 재생) idle: NodeJS.Timeout | null; + key?: string; // 클라이언트가 붙인 이름표(예: 'ws:<프로젝트id>', 'pcb:<이름>') — 다른 기기에서 세션을 찾을 때 쓴다 + mode?: string; // claude | claude-chrome | claude-ollama | shell + startedAt?: number; } export const PTY_BUF_MAX = 256 * 1024; export const PTY_IDLE_MS = 6 * 60 * 60 * 1000; // 연결 없이 6시간 @@ -26,3 +29,14 @@ export function ptyAttach(e: PtyEntry, ws: any): void { if (e.idle) { clearTimeout(e.idle); e.idle = null; } e.ws = ws; } + +const KEY_RE = /^(ws|pcb):[\w .\-가-힣]{1,80}$/; +const MODES = new Set(['claude', 'claude-chrome', 'claude-ollama', 'shell']); +export function cleanPtyKey(v: unknown): string | undefined { return typeof v === 'string' && KEY_RE.test(v) ? v : undefined; } +export function cleanPtyMode(v: unknown): string | undefined { return typeof v === 'string' && MODES.has(v) ? v : undefined; } +/** 한 사용자의 실행 중 세션 목록(최근 시작 순). 출력 버퍼는 싣지 않는다. */ +export function listPtySessions(username: string): { shellId: string; key?: string; mode?: string; startedAt?: number; attached: boolean }[] { + const out: { shellId: string; key?: string; mode?: string; startedAt?: number; attached: boolean }[] = []; + for (const [shellId, e] of ptyStore) if (e.username === username) out.push({ shellId, key: e.key, mode: e.mode, startedAt: e.startedAt, attached: !!e.ws }); + return out.sort((a, b) => (b.startedAt || 0) - (a.startedAt || 0)); +} diff --git a/src/gateway/server.ts b/src/gateway/server.ts index 5df7647..222659f 100644 --- a/src/gateway/server.ts +++ b/src/gateway/server.ts @@ -62,7 +62,7 @@ import { registerCodeRoutes } from './routes/routes-code'; import { registerClaudeFsRoutes } from './routes/routes-claude-fs'; import { getBuildInfo, buildLabel } from './build-info'; import { skillContextBudget } from './chat/skill-context-budget'; -import { ptyStore, ptyAppend, ptyAttach, ptyDetach } from './pty-store'; +import { ptyStore, ptyAppend, ptyAttach, ptyDetach, cleanPtyKey, cleanPtyMode, listPtySessions } from './pty-store'; import { ptyAccessDecision, resolveWorkshopCwd, resolvePcbCwd, allowedAutorun } from './pty-guard'; import { ensureSharedClaudeMemory, ensureProjectClaudeMd, ensurePcbClaudeMd } from './claude-memory'; import { loadWorkshop } from './routes/workshop-storage'; @@ -4798,7 +4798,7 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => { cwd: wsCwd || msg.cwd || user?.workspace || process.cwd(), env: { ...process.env, TERM: 'xterm-256color' } as any, }); - const entry = { proc, username: ptyOwner, ws: ws as any, buf: '', idle: null as NodeJS.Timeout | null }; + const entry = { proc, username: ptyOwner, ws: ws as any, buf: '', idle: null as NodeJS.Timeout | null, key: cleanPtyKey(msg.key), mode: cleanPtyMode(msg.autorun) || 'shell', startedAt: Date.now() }; 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 가 끝나면 셸로 돌아온다). @@ -4829,6 +4829,9 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => { if (e.idle) clearTimeout(e.idle); ptyStore.delete(msg.shellId); } + } else if (msg.type === 'pty_list') { + // 다른 기기·브라우저가 서버에 남은 내 세션을 찾아 이어받을 수 있게 목록을 준다. + try { ws.send(JSON.stringify({ type: 'pty_sessions', sessions: listPtySessions(ptyOwner) })); } catch {} } else if (msg.type === 'pty_attach') { // 끊어졌다 다시 연결한 클라이언트가 같은 세션을 이어받는다(출력 버퍼 재생). const e = mine(msg.shellId); diff --git a/tests/pty-store-list.test.ts b/tests/pty-store-list.test.ts new file mode 100644 index 0000000..314e9fe --- /dev/null +++ b/tests/pty-store-list.test.ts @@ -0,0 +1,35 @@ +/** + * 웹 터미널 세션 목록(pty_list) — 소유자별 필터와 이름표 검증 + */ +import { test, describe, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { ptyStore, listPtySessions, cleanPtyKey, cleanPtyMode } from '../src/gateway/pty-store'; + +describe('listPtySessions', () => { + beforeEach(() => ptyStore.clear()); + const mk = (username: string, extra: any = {}) => ({ proc: {}, username, ws: null, buf: 'SECRET', idle: null, ...extra }); + + test('내 세션만, 최근 시작 순으로, 출력 버퍼는 싣지 않는다', () => { + ptyStore.set('a', mk('kim', { key: 'ws:proj_1', mode: 'claude', startedAt: 100 })); + ptyStore.set('b', mk('kim', { key: 'pcb:smps', mode: 'shell', startedAt: 200, ws: {} })); + ptyStore.set('c', mk('papa', { key: 'ws:proj_1', startedAt: 300 })); + const l = listPtySessions('kim'); + assert.deepEqual(l.map(x => x.shellId), ['b', 'a']); + assert.equal(l[0].attached, true); + assert.equal(l[1].attached, false); + assert.ok(!JSON.stringify(l).includes('SECRET')); + }); +}); + +describe('이름표 검증', () => { + test('올바른 key만 통과', () => { + assert.equal(cleanPtyKey('ws:proj_m5j2c2bp'), 'ws:proj_m5j2c2bp'); + assert.equal(cleanPtyKey('pcb:smps 전원'), 'pcb:smps 전원'); + for (const bad of ['', 'x:y', 'ws:', 'ws:../..', 'ws:a/b', 'ws:a\nb', undefined, 5, {}]) assert.equal(cleanPtyKey(bad), undefined, JSON.stringify(bad)); + }); + test('mode는 허용 목록만', () => { + assert.equal(cleanPtyMode('claude-ollama'), 'claude-ollama'); + assert.equal(cleanPtyMode('rm -rf /'), undefined); + assert.equal(cleanPtyMode(undefined), undefined); + }); +}); diff --git a/web-ui/js/app/workshop-console.js b/web-ui/js/app/workshop-console.js index 04c1049..f146f1b 100644 --- a/web-ui/js/app/workshop-console.js +++ b/web-ui/js/app/workshop-console.js @@ -51,13 +51,14 @@ function consoleWsConnect() { }; ws.onmessage = ev => { let m; try { m = JSON.parse(ev.data); } catch { return; } + if (m.type === 'pty_sessions') { consoleOnSessions(m.sessions || []); 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_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_gone') { const k = consoleKeyStr; consoleStore(k, null); consoleShellId = null; consoleStatus('이전 세션이 끝났습니다 — 다시 시작하세요'); consoleAskServer(k); } 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'); } }; @@ -77,11 +78,53 @@ async function consoleReattach() { // 이 프로젝트에 서버에 남아 있는 세션이 있으면 이어붙는다. async function consoleResume() { const proj = currentProject(); if (!proj || consoleShellId) return; - const key = consoleKeyOf(proj), st = consoleStored(key); if (!st || !st.shellId) return; + const key = consoleKeyOf(proj), st = consoleStored(key); + if (!st || !st.shellId) { consoleAskServer(key); return; } // 이 브라우저는 기억이 없다 — 서버에 남은 세션이 있는지 물어본다 consoleKeyStr = key; consoleProjId = proj.id; consoleShellId = st.shellId; consoleRetry = 0; consoleStatus('이전 세션에 이어붙는 중…', '#f59e0b'); await consoleReattach(); } +// ── 다른 기기·브라우저에서 시작한 세션 이어받기 ── +// 서버 목록(pty_list)에서 이 프로젝트(key)의 세션이 있으면 "이어받기 / 새로 시작"을 묻는다. +let consoleAskKey = ''; +async function consoleAskServer(key) { + if (!consoleOpen && !consoleTerm) return; + consoleAskKey = key; + try { await consoleWsConnect(); } catch { return; } + consoleSend({ type: 'pty_list' }); +} +function consoleOnSessions(list) { + const key = consoleAskKey, proj = currentProject(); + if (!key || !proj || consoleShellId || consoleKeyOf(proj) !== key) return; + consoleAskKey = ''; + const s = list.find(x => x.key === key); + if (!s) return; + const MODE = { claude: 'Claude Code', 'claude-chrome': 'Claude Code + 크롬', 'claude-ollama': 'Claude Code (올라마)', shell: '셸' }; + const when = s.startedAt ? new Date(s.startedAt).toLocaleString('ko-KR', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : ''; + consolePrompt((MODE[s.mode] || '세션') + ' 세션이 서버에서 실행 중입니다' + (when ? ' (' + when + ' 시작)' : '') + (s.attached ? ' — 다른 화면에서 사용 중이면 그쪽 연결이 끊깁니다' : ''), s, key); +} +function consolePrompt(text, s, key) { + consolePromptClose(); + const host = document.getElementById('console-term'); if (!host) return; + const bar = document.createElement('div'); bar.id = 'console-adopt'; + bar.style.cssText = 'position:absolute;left:8px;right:8px;top:8px;z-index:5;display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:8px 10px;border-radius:8px;background:#1f2937;border:1px solid #3b82f6;color:#e5e7eb;font-size:13px'; + const t = document.createElement('span'); t.textContent = '🔗 ' + text; t.style.flex = '1 1 240px'; + const b1 = document.createElement('button'); b1.className = 'rb-mini-btn'; b1.textContent = '이어받기'; + const b2 = document.createElement('button'); b2.className = 'rb-mini-btn'; b2.textContent = '그대로 두기'; + b1.onclick = () => { consolePromptClose(); consoleAdopt(s, key); }; + b2.onclick = consolePromptClose; + bar.append(t, b1, b2); + if (getComputedStyle(host).position === 'static') host.style.position = 'relative'; + host.appendChild(bar); +} +function consolePromptClose() { const e = document.getElementById('console-adopt'); if (e) e.remove(); } +async function consoleAdopt(s, key) { + const proj = currentProject(); if (!proj || consoleKeyOf(proj) !== key || consoleShellId) return; + consoleKeyStr = key; consoleProjId = proj.id; consoleShellId = s.shellId; consoleRetry = 0; + consoleStore(key, { shellId: s.shellId, mode: s.mode }); + consoleStatus('세션에 이어붙는 중…', '#f59e0b'); + await consoleReattach(); +} function consoleSend(obj) { if (consoleWs && consoleWs.readyState === WebSocket.OPEN) consoleWs.send(JSON.stringify(obj)); } // 콘솔 탭이 열릴 때(switchTab). 터미널 요소만 만들고 세션은 사용자가 시작 버튼을 눌러야 시작한다(실수로 claude가 뜨지 않게). @@ -121,7 +164,7 @@ async function consoleStart(mode) { consoleTerm.reset(); consoleRefit(); const autorun = (mode === 'claude' || mode === 'claude-chrome' || mode === 'claude-ollama') ? mode : null; - consoleSend({ type: 'pty_spawn', shellId: consoleShellId, cols: consoleTerm.cols, rows: consoleTerm.rows, + consoleSend({ type: 'pty_spawn', shellId: consoleShellId, key: consoleKeyStr, cols: consoleTerm.cols, rows: consoleTerm.rows, ...(proj.pcb ? { pcbProject: proj.name } : { workshopProjectId: proj.id }), ...(autorun ? { autorun } : {}) }); consoleStatus((mode === 'claude' ? 'Claude Code' : mode === 'claude-chrome' ? 'Claude Code + 크롬' : mode === 'claude-ollama' ? 'Claude Code (올라마 모델)' : '셸') + ' 실행 중 — ' + proj.name, '#22c55e'); consoleTerm.focus(); @@ -148,4 +191,5 @@ function consoleOnProjectChange(fromOpen) { if (consoleTerm) consoleTerm.write('\r\n\x1b[33m[프로젝트가 바뀌어 세션을 종료했습니다 — 다시 시작하세요]\x1b[0m\r\n'); consoleStatus('프로젝트가 바뀌어 종료됨'); } + if (!fromOpen && consoleOpen && !consoleShellId) consoleResume(); // 새 프로젝트에 서버에 남은 세션이 있으면 이어받기를 묻는다 }