196 lines
13 KiB
JavaScript
196 lines
13 KiB
JavaScript
// 작업실 콘솔 탭(2026-10-02) — 프로젝트 폴더에서 Claude Code(`claude`)나 셸을 웹 터미널로 쓴다.
|
|
// 서버의 기존 PTY 웹소켓(/ws, pty_*)을 그대로 쓰며, 서버가 workshopProjectId로 시작 폴더를 정하고(경로를 클라이언트가 못 정함)
|
|
// autorun은 'claude'만 허용한다. 터미널은 로그인한 관리자 + 같은 Origin만(pty-guard.ts) — 아니면 pty_error가 온다.
|
|
// PCB 앱도 재사용한다: currentProject() 가 {pcb:true, name} 을 돌려주면 서버가 workspace/pcb/<name> 에서 시작한다.
|
|
// 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) => {
|
|
if ([...document.scripts].some(s => s.src.endsWith(src))) return resolve();
|
|
const s = document.createElement('script'); s.src = src; s.onload = resolve; s.onerror = () => reject(new Error(src + ' 로드 실패'));
|
|
document.head.appendChild(s);
|
|
});
|
|
}
|
|
async function consoleEnsureXterm() {
|
|
if (!document.getElementById('xterm-css')) {
|
|
const l = document.createElement('link'); l.id = 'xterm-css'; l.rel = 'stylesheet'; l.href = '/vendor/xterm.css'; document.head.appendChild(l);
|
|
}
|
|
if (typeof Terminal === 'undefined') await consoleLoadScript('/vendor/xterm.js');
|
|
if (typeof FitAddon === 'undefined') await consoleLoadScript('/vendor/addon-fit.js');
|
|
}
|
|
function consoleStatus(text, color) {
|
|
const el = document.getElementById('console-status');
|
|
if (el) { el.textContent = text; el.style.color = color || 'var(--muted)'; }
|
|
}
|
|
function consoleCookie(name) {
|
|
const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
|
|
return m ? decodeURIComponent(m[1]) : '';
|
|
}
|
|
function consoleWsConnect() {
|
|
return new Promise((resolve, reject) => {
|
|
if (consoleWs && consoleWs.readyState === WebSocket.OPEN) return resolve();
|
|
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
let url = `${proto}//${location.host}/ws`;
|
|
let token = ''; try { token = sessionStorage.getItem('smallclaw_token') || ''; } catch {}
|
|
token = token || consoleCookie('smallclaw_session');
|
|
if (token) url += `?token=${encodeURIComponent(token)}`;
|
|
const ws = new WebSocket(url);
|
|
ws.onopen = () => { consoleWs = ws; resolve(); };
|
|
ws.onerror = () => reject(new Error('웹소켓 연결 실패'));
|
|
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 === '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') { 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'); }
|
|
};
|
|
});
|
|
}
|
|
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) { 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가 뜨지 않게).
|
|
async function openConsole() {
|
|
consoleOpen = true;
|
|
const proj = currentProject();
|
|
document.getElementById('console-proj').textContent = proj ? '📁 ' + proj.name : '프로젝트 없음';
|
|
await consoleEnsureXterm();
|
|
if (!consoleTerm) {
|
|
consoleTerm = new Terminal({ fontSize: 13, cursorBlink: true, convertEol: false, scrollback: 5000,
|
|
fontFamily: "'D2Coding','IBM Plex Mono',monospace", theme: { background: '#0d1117' } });
|
|
consoleFit = new FitAddon.FitAddon();
|
|
consoleTerm.loadAddon(consoleFit);
|
|
consoleTerm.open(document.getElementById('console-term'));
|
|
consoleTerm.onData(d => { if (consoleShellId) consoleSend({ type: 'pty_input', shellId: consoleShellId, data: d }); });
|
|
consoleTerm.onResize(({ cols, rows }) => { if (consoleShellId) consoleSend({ type: 'pty_resize', shellId: consoleShellId, cols, rows }); });
|
|
window.addEventListener('resize', () => { if (consoleOpen) consoleRefit(); });
|
|
consoleTerm.write(CONSOLE_HINT);
|
|
}
|
|
consoleOnProjectChange(true);
|
|
setTimeout(consoleRefit, 50);
|
|
consoleResume();
|
|
consoleTerm.focus();
|
|
}
|
|
function closeConsoleTab() { consoleOpen = false; } // 세션은 유지(탭만 숨김) — 다시 열면 이어서 쓴다
|
|
function consoleRefit() { try { if (consoleFit) consoleFit.fit(); } catch {} }
|
|
|
|
async function consoleStart(mode) {
|
|
const proj = currentProject();
|
|
if (!proj) { consoleStatus('프로젝트를 먼저 고르세요', '#ef4444'); return; }
|
|
await openConsole();
|
|
consoleStop(true);
|
|
try { await consoleWsConnect(); } catch (e) { consoleStatus(e.message, '#ef4444'); return; }
|
|
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;
|
|
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();
|
|
}
|
|
const CONSOLE_HINT = '\x1b[90m▶ claude 시작을 누르면 이 프로젝트 폴더에서 Claude Code가 실행됩니다.\x1b[0m\r\n';
|
|
function consoleClear() {
|
|
if (!consoleTerm) return;
|
|
consoleTerm.reset(); // 화면과 스크롤 기록을 모두 지운다
|
|
consoleTerm.write(CONSOLE_HINT);
|
|
}
|
|
function consoleStop(silent) {
|
|
clearTimeout(consoleRetryTimer);
|
|
if (consoleShellId) { consoleSend({ type: 'pty_kill', shellId: consoleShellId }); consoleShellId = null; consoleStore(consoleKeyStr, null); }
|
|
// 사용자가 ■ 종료를 눌렀을 때는 화면을 비운다(다시 시작할 때 이전 세션 내용과 섞이지 않게). silent는 재시작·프로젝트 전환 내부 호출.
|
|
if (!silent) { consoleClear(); consoleStatus('종료됨'); }
|
|
}
|
|
// 프로젝트를 바꾸면 실행 중인 세션은 이전 프로젝트 폴더 기준이라 혼동되므로 종료하고 안내한다.
|
|
function consoleOnProjectChange(fromOpen) {
|
|
const proj = currentProject();
|
|
const lbl = document.getElementById('console-proj');
|
|
if (lbl) lbl.textContent = proj ? '📁 ' + proj.name : '프로젝트 없음';
|
|
if (consoleShellId && proj && consoleProjId && proj.id !== consoleProjId) {
|
|
consoleStop(true);
|
|
if (consoleTerm) consoleTerm.write('\r\n\x1b[33m[프로젝트가 바뀌어 세션을 종료했습니다 — 다시 시작하세요]\x1b[0m\r\n');
|
|
consoleStatus('프로젝트가 바뀌어 종료됨');
|
|
}
|
|
if (!fromOpen && consoleOpen && !consoleShellId) consoleResume(); // 새 프로젝트에 서버에 남은 세션이 있으면 이어받기를 묻는다
|
|
}
|