chahuadev-dev-launcher / web /renderer.js
chahuadev's picture
fix: remove ineffective sandbox on home/support iframes (allow-scripts+allow-same-origin defeats sandbox per spec)
b92316a verified
'use strict'
// ── SVG icon map ─────────────────────────────────────────────────────────────
const ICONS = {
expo: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,
android: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 16.5v2a1 1 0 002 0v-2M17 16.5v2a1 1 0 002 0v-2"/><rect x="5" y="8" width="14" height="11" rx="3"/><circle cx="9" cy="14" r="1" fill="currentColor" stroke="none"/><circle cx="15" cy="14" r="1" fill="currentColor" stroke="none"/><line x1="8.5" y1="8" x2="6" y2="4"/><line x1="15.5" y1="8" x2="18" y2="4"/></svg>`,
adb: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 9 10 15 4 21"/><line x1="13" y1="21" x2="21" y2="21"/></svg>`,
electron: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>`,
nextjs: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L22 21H2L12 2z"/></svg>`,
vite: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,
scripts: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>`,
npm: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>`,
}
// ── Page navigation ─────────────────────────────────────────────────────────
function showPage(name) {
document.getElementById('page-home').classList.toggle('active', name === 'home')
document.getElementById('page-run').classList.toggle('active', name === 'run')
const pageR2 = document.getElementById('page-r2')
if (pageR2) pageR2.classList.toggle('active', name === 'r2')
document.getElementById('page-support').classList.toggle('active', name === 'support')
document.getElementById('tab-home').classList.toggle('active', name === 'home')
document.getElementById('tab-run').classList.toggle('active', name === 'run')
const tabR2 = document.getElementById('tab-r2')
if (tabR2) tabR2.classList.toggle('active', name === 'r2')
document.getElementById('support-btn').classList.toggle('active', name === 'support')
if (name === 'run') {
ensureTerminalInitialized()
}
if (name === 'run' && term && fitAddon) {
requestAnimationFrame(() => {
setTimeout(() => {
fitAddon.fit()
notifyPtyResize()
}, 20)
})
}
}
// iframe pages call these parent functions
window.showView = showPage
window.r2OpenConfig = () => {}
window.r2OpenUpload = () => {}
window.r2OpenCloudflare = () => {}
window.r2GetStatus = async () => ({ ok: false, error: 'R2 moved to chahuadev-R2 app' })
window.r2Logout = async () => ({ ok: true })
// ── State ─────────────────────────────────────────────────────────────────────
let runningBtn = null
let mainRunning = false
let currentMainCmdKey = null
const popupRunningByCmd = new Map()
const cmdButtonByKey = new Map()
const GROUP_COLOR_CLASS = {
expo: 'group-color-expo',
android: 'group-color-android',
adb: 'group-color-adb',
electron: 'group-color-electron',
nextjs: 'group-color-nextjs',
vite: 'group-color-vite',
scripts: 'group-color-scripts',
npm: 'group-color-npm',
}
// ── Elements ──────────────────────────────────────────────────────────────────
const elGroups = document.getElementById('cmd-groups')
const elOutput = document.getElementById('term-output')
const elName = document.getElementById('project-name')
const elPath = document.getElementById('project-path')
const elBadge = document.getElementById('type-badge')
const elKill = document.getElementById('btn-kill')
const elClear = document.getElementById('btn-clear')
const elStreamMode = document.getElementById('stream-mode')
const elDot = document.getElementById('status-dot')
const elStatus = document.getElementById('status-text')
const elRunning = document.getElementById('running-label')
const elDevQuickPanel = document.getElementById('dev-quick-panel')
const elDevMainTools = document.getElementById('btn-dev-main-tools')
const elDevPopupTools = document.getElementById('btn-dev-popup-tools')
const elDevSecurityStatus = document.getElementById('btn-dev-security-status')
let term = null
let fitAddon = null
let resizeObserver = null
let terminalInitialized = false
let currentAppIsDev = false
function ensureTerminalInitialized() {
if (terminalInitialized) return
initTerminal()
installTerminalShortcuts()
terminalInitialized = true
}
function isTermNearBottom() {
if (!term || !term.buffer || !term.buffer.active) return true
const b = term.buffer.active
return b.viewportY >= b.baseY
}
function initTerminal() {
if (!elOutput || !window.Terminal) return
const FitAddonCtor = (window.FitAddon && window.FitAddon.FitAddon) ? window.FitAddon.FitAddon : null
term = new window.Terminal({
cursorBlink: false,
disableStdin: true,
// Keep raw stream untouched and let xterm handle EOL visually.
convertEol: true,
scrollback: 100000,
fontFamily: 'Cascadia Code, Consolas, monospace',
fontSize: 12,
theme: {
background: '#080812',
foreground: '#e6e8ff',
red: '#ff6b6b',
green: '#37d67a',
yellow: '#ffd166',
blue: '#6ea8ff',
magenta: '#d291ff',
cyan: '#5fe3ff',
white: '#f4f6ff',
brightRed: '#ff8a8a',
brightGreen: '#69f0a6',
brightYellow: '#ffe08a',
brightBlue: '#9fc0ff',
brightMagenta: '#e3b7ff',
brightCyan: '#99f0ff'
}
})
if (FitAddonCtor) {
fitAddon = new FitAddonCtor()
term.loadAddon(fitAddon)
}
term.open(elOutput)
if (fitAddon) fitAddon.fit()
notifyPtyResize()
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(() => {
if (fitAddon) fitAddon.fit()
notifyPtyResize()
})
resizeObserver.observe(elOutput)
} else {
window.addEventListener('resize', () => {
if (fitAddon) fitAddon.fit()
notifyPtyResize()
})
}
}
function notifyPtyResize() {
if (!term || !api || typeof api.resizeProcPty !== 'function') return
const cols = Number(term.cols || 0)
const rows = Number(term.rows || 0)
if (!cols || !rows) return
api.resizeProcPty({ cols, rows })
}
async function copyTermSelection() {
if (!term) return false
const selected = term.getSelection()
if (!selected) return false
try {
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
await navigator.clipboard.writeText(selected)
return true
}
const ta = document.createElement('textarea')
ta.value = selected
ta.setAttribute('readonly', 'readonly')
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.focus()
ta.select()
const ok = document.execCommand('copy')
document.body.removeChild(ta)
if (!ok) return false
return true
} catch {
return false
}
}
function installTerminalShortcuts() {
if (elOutput) {
const _onTermMousedown = () => {
if (term && typeof term.focus === 'function') term.focus()
}
elOutput.addEventListener('mousedown', _onTermMousedown)
window.addEventListener('beforeunload', () => {
elOutput.removeEventListener('mousedown', _onTermMousedown)
}, { once: true })
}
document.addEventListener('keydown', async (e) => {
const isCtrlOrMeta = e.ctrlKey || e.metaKey
if (!isCtrlOrMeta) return
const key = String(e.key || '').toLowerCase()
// Ctrl/Cmd + A => select all terminal output
if (key === 'a') {
if (!term) return
e.preventDefault()
term.selectAll()
return
}
// Ctrl/Cmd + C (and Ctrl/Cmd + Shift + C) => copy selected terminal text
if (key === 'c') {
if (!term || !term.hasSelection()) return
e.preventDefault()
await copyTermSelection()
term.clearSelection()
return
}
// Ctrl/Cmd + L => clear terminal
if (key === 'l') {
if (!term) return
e.preventDefault()
term.reset()
}
})
}
const r2ConfigBackdrop = document.getElementById('r2-config-backdrop')
const r2UploadBackdrop = document.getElementById('r2-upload-backdrop')
function openModal(el) {
if (!el) return
el.classList.add('show')
}
function closeModal(el) {
if (!el) return
el.classList.remove('show')
}
function showSecurityBlockModal(payload = {}) {
const backdrop = document.getElementById('security-block-backdrop')
const msg = document.getElementById('security-block-message')
const pathEl = document.getElementById('security-block-path')
if (!backdrop || !msg || !pathEl) return
const text = String(payload.message ||
'SECURITY POLICY NOTICE\n\nThe selected folder is part of operating system directories.\nAccess is blocked to protect system integrity and user data.\n\nPlease select a project folder outside protected OS locations.')
msg.textContent = text
const selectedPath = String(payload.selectedPath || '')
pathEl.textContent = selectedPath ? `Blocked path: ${selectedPath}` : ''
openModal(backdrop)
}
function setTone(el, tone, text) {
if (!el) return
el.classList.remove('text-ok', 'text-warn', 'text-err', 'text-info')
if (tone) el.classList.add(`text-${tone}`)
if (typeof text === 'string') el.textContent = text
}
async function configureR2() {
const status = await api.r2GetConfigStatus()
const st = document.getElementById('r2-config-status')
const accountHint = document.getElementById('r2-account-hint')
const bucketHint = document.getElementById('r2-bucket-hint')
const accessHint = document.getElementById('r2-access-hint')
document.getElementById('r2-account-id').value = ''
document.getElementById('r2-bucket').value = status.bucket || ''
document.getElementById('r2-access-key').value = ''
document.getElementById('r2-secret-key').value = ''
if (!status.ok) {
setTone(st, 'err', `Config unavailable: ${status.error}`)
} else {
setTone(st, 'info', status.hasConfig ? 'Config already exists. Fill all fields to update.' : 'No config found. Enter credentials to save.')
}
accountHint.textContent = status.accountIdMasked ? `Current: ${status.accountIdMasked}` : ''
bucketHint.textContent = status.bucket ? `Current: ${status.bucket}` : ''
accessHint.textContent = status.accessKeyMasked ? `Current: ${status.accessKeyMasked}` : ''
openModal(r2ConfigBackdrop)
}
async function saveR2FromModal() {
const accountId = document.getElementById('r2-account-id').value.trim()
const bucket = document.getElementById('r2-bucket').value.trim()
const accessKeyId = document.getElementById('r2-access-key').value.trim()
const secretAccessKey = document.getElementById('r2-secret-key').value.trim()
const st = document.getElementById('r2-config-status')
if (!accountId || !bucket || !accessKeyId || !secretAccessKey) {
setTone(st, 'err', 'All fields are required.')
return
}
setTone(st, 'info', 'Validating credentials with R2...')
const testRes = await api.r2TestConfig({ accountId, bucket, accessKeyId, secretAccessKey })
if (!testRes.ok) {
setTone(st, 'err', `Validation failed: ${testRes.error}`)
return
}
const res = await api.r2SaveConfig({ accountId, bucket, accessKeyId, secretAccessKey })
if (!res.ok) {
setTone(st, 'err', `Save failed: ${res.error}`)
return
}
closeModal(r2ConfigBackdrop)
}
async function clearSavedR2Config() {
const st = document.getElementById('r2-config-status')
const ok = window.confirm('Clear saved R2 credentials on this machine?')
if (!ok) return
const res = await api.r2ClearConfig()
if (!res.ok) {
setTone(st, 'err', `Clear failed: ${res.error}`)
return
}
document.getElementById('r2-account-id').value = ''
document.getElementById('r2-bucket').value = ''
document.getElementById('r2-access-key').value = ''
document.getElementById('r2-secret-key').value = ''
document.getElementById('r2-account-hint').textContent = ''
document.getElementById('r2-bucket-hint').textContent = ''
document.getElementById('r2-access-hint').textContent = ''
setTone(st, 'info', 'Saved config cleared.')
}
async function uploadDistToR2() {
showPage('run')
const st = document.getElementById('r2-upload-status')
const list = document.getElementById('r2-target-list')
const input = document.getElementById('r2-target-folder')
const note = document.getElementById('r2-upload-note')
st.textContent = ''
list.innerHTML = ''
const suggest = await api.r2SuggestTarget()
if (!suggest.ok) {
setTone(st, 'err', `Upload unavailable: ${suggest.error}`)
openModal(r2UploadBackdrop)
return
}
note.textContent = `Bucket: ${suggest.bucket}`
input.value = suggest.target || suggest.appBase || ''
setTone(st, 'info', 'Review target folder and start upload.')
;(suggest.folders || []).forEach(name => {
const chip = document.createElement('button')
chip.className = 'target-chip'
chip.type = 'button'
chip.textContent = name
chip.addEventListener('click', () => { input.value = name })
list.appendChild(chip)
})
openModal(r2UploadBackdrop)
}
async function runR2UploadFromModal() {
const target = document.getElementById('r2-target-folder').value.trim()
const st = document.getElementById('r2-upload-status')
if (!target) {
setTone(st, 'err', 'Target folder is required.')
return
}
closeModal(r2UploadBackdrop)
elKill.disabled = false
elDot.className = 'running'
elStatus.textContent = 'Uploading R2'
elRunning.textContent = `dist -> ${target}`
const res = await api.r2UploadDist({ target })
}
// ── ANSI → HTML ───────────────────────────────────────────────────────────────
// ── Terminal output ───────────────────────────────────────────────────────────
function appendOutput(text) {
if (typeof text !== 'string' || text.length === 0) return
if (term) {
const shouldFollow = isTermNearBottom()
term.write(text)
if (shouldFollow) term.scrollToBottom()
return
}
elOutput.appendChild(document.createTextNode(text))
elOutput.scrollTop = elOutput.scrollHeight
}
function termHeader(label) {
appendOutput('\n▶ ' + label + '\n' + '─'.repeat(60) + '\n')
}
function getSelectedStreamMode() {
const mode = String(elStreamMode?.value || 'realtime').toLowerCase()
return mode === 'stable' ? 'stable' : 'realtime'
}
function isBuildLikeCommandRenderer(cmdDef) {
const cmd = String(cmdDef?.cmd || '').toLowerCase()
const args = (cmdDef?.args || []).map(x => String(x || '').toLowerCase())
const joined = [cmd, ...args].join(' ')
if (/electron-builder|gradlew/.test(cmd)) return true
if (/\b(build|dist|pack|release|assemble|bundle|nsis|msi|portable|appimage)\b/.test(joined)) return true
return false
}
function isNpmRunDevRenderer(cmdDef) {
const cmd = String(cmdDef && cmdDef.cmd ? cmdDef.cmd : '').trim().toLowerCase()
const args = (cmdDef && cmdDef.args ? cmdDef.args : []).map(x => String(x || '').trim().toLowerCase())
return (cmd === 'npm' || cmd === 'npm.cmd') && args.length === 2 && args[0] === 'run' && args[1] === 'dev'
}
function clearR2UiValues() {
const ids = ['r2-account-id', 'r2-bucket', 'r2-access-key', 'r2-secret-key', 'r2-target-folder']
ids.forEach(id => {
const el = document.getElementById(id)
if (el) el.value = ''
})
const texts = ['r2-account-hint', 'r2-bucket-hint', 'r2-access-hint', 'r2-config-status', 'r2-upload-status', 'r2-upload-note']
texts.forEach(id => {
const el = document.getElementById(id)
if (el) el.textContent = ''
})
const list = document.getElementById('r2-target-list')
if (list) list.innerHTML = ''
}
function appendSecurityStatusLines(status) {
const lines = []
lines.push('\n[DEV SECURITY STATUS]')
lines.push(`mode=${status.appMode}`)
lines.push(`requestGuardInstalled=${status.requestGuardInstalled}`)
lines.push(`externalRequestBlockActive=${status.externalRequestBlockActive}`)
lines.push(`shortcutDevtoolsBlockedInProduction=${status.shortcutDevtoolsBlockedInProduction}`)
lines.push(`mainWindowDevtoolsCapable=${status.mainWindowDevtoolsCapable}`)
lines.push(`popupWindowDevtoolsCapable=${status.popupWindowDevtoolsCapable}`)
lines.push(`popupCspInlineStyleAllowed=${status.popupCspInlineStyleAllowed}`)
lines.push(`popupRunCount=${status.popupRunCount}`)
lines.push(`note=${status.securityNote}`)
appendOutput(lines.join('\n') + '\n')
}
function commandButtonKey(cmdDef) {
const cmd = String(cmdDef && cmdDef.cmd ? cmdDef.cmd : '').trim().toLowerCase()
const args = (cmdDef && cmdDef.args ? cmdDef.args : []).map(x => String(x || '').trim().toLowerCase())
const cwd = String(cmdDef && cmdDef.cwd ? cmdDef.cwd : '').trim().toLowerCase()
return `${cmd}${args.join('␟')}${cwd}`
}
function buildCommandHint(cmdDef, group, typeInfo) {
const label = String(cmdDef?.label || '').toLowerCase()
const cmdLine = [cmdDef.cmd, ...(cmdDef.args || [])].join(' ')
const projectType = String(typeInfo?.label || 'Project').trim()
const projectTypeLower = projectType.toLowerCase()
const lines = []
if (/expo start/.test(label)) {
lines.push('Step 1: Start Expo development server.')
lines.push('Use this first for local mobile development.')
} else if (/expo run:android/.test(label)) {
lines.push('Step 2: Build and run the app on Android device/emulator.')
lines.push('Use after Expo server is ready.')
} else if (/expo prebuild/.test(label)) {
lines.push('Prepare native Android project files from Expo config.')
lines.push('Use when native config changed or Android folder is missing.')
} else if (/installdebug/.test(label)) {
lines.push('Install debug APK to connected Android device/emulator.')
lines.push('Recommended after clean build or code changes.')
} else if (/assemblerelease|build[-\s]?exe|build[-\s]?win|build[-\s]?msi|build[-\s]?nsis|build[-\s]?linux|dist|pack/.test(label)) {
lines.push('Create a production build artifact.')
lines.push('Use when you want distributable output files.')
} else if (/assembledebug/.test(label)) {
lines.push('Compile a debug build without installing it.')
} else if (/clean\s*\+\s*install/.test(label)) {
lines.push('Step 1+2: Clean old build files, then install fresh debug app.')
lines.push('Good first fix when build output is inconsistent.')
} else if (/^clean$/.test(label)) {
lines.push('Step 1: Remove cached build artifacts.')
lines.push('Run before rebuild if Gradle behaves unexpectedly.')
} else if (/adb devices/.test(label)) {
lines.push('Check if Android devices/emulators are connected.')
lines.push('Run this before install commands.')
} else if (/adb logcat/.test(label)) {
lines.push('Open real-time Android logs for debugging.')
} else if (/adb reverse/.test(label)) {
lines.push('Forward Metro port to device (8081 -> 8081).')
lines.push('Use when device cannot reach local dev server.')
} else if (/npm install\s*--legacy-peer-deps/.test(label)) {
lines.push('Install dependencies with legacy peer dependency resolution.')
lines.push('Use only when normal install fails due to peer conflicts.')
} else if (/npm install/.test(label)) {
lines.push('Step 1: Install project dependencies.')
} else if (/npm ci/.test(label)) {
lines.push('Install dependencies from lockfile for clean reproducible setup.')
} else if (/npm run dev/.test(label)) {
lines.push('Start development mode (hot reload/watch if supported).')
} else if (/npm run start/.test(label)) {
lines.push('Start app in normal run mode.')
} else if (/npm run android/.test(label)) {
lines.push('Run Android target from package scripts.')
} else if (/npm run ios/.test(label)) {
lines.push('Run iOS target from package scripts.')
} else if (/npm run web/.test(label)) {
lines.push('Run web target from package scripts.')
} else if (/npm run build/.test(label)) {
lines.push('Build production assets for this project.')
} else if (/npm run preview/.test(label)) {
lines.push('Preview the production build locally.')
} else if (/npm run lint/.test(label)) {
lines.push('Run lint checks to catch code issues.')
} else if (/npm run test/.test(label)) {
lines.push('Run test suite for this project.')
} else {
lines.push('Run this command for the current project.')
}
let flow = ''
if (projectTypeLower.includes('expo') || projectTypeLower.includes('react native')) {
flow = 'Recommended order: npm install -> expo start -> expo run:android (or installDebug).'
} else if (projectTypeLower.includes('electron')) {
flow = 'Recommended order: npm install -> npm run dev (or start) -> npm run build-exe/build-win for release.'
} else if (projectTypeLower.includes('next.js') || projectTypeLower.includes('next')) {
flow = 'Recommended order: npm install -> npm run dev -> npm run build -> npm run start.'
} else if (projectTypeLower.includes('vite')) {
flow = 'Recommended order: npm install -> npm run dev -> npm run build -> npm run preview.'
} else {
flow = 'Recommended order: npm install -> npm run dev/start -> npm run build (when ready to release).'
}
lines.push(`Project type: ${projectType}.`)
lines.push(flow)
lines.push(`Group: ${group.label}.`)
lines.push(`Command: ${cmdLine}.`)
return lines.join('\n')
}
// ── Render command groups ─────────────────────────────────────────────────────
function renderGroups(groups, typeInfo) {
elGroups.innerHTML = ''
cmdButtonByKey.clear()
groups.forEach(group => {
const div = document.createElement('div')
div.className = 'cmd-group'
const lbl = document.createElement('div')
lbl.className = 'cmd-group-label'
const colorClass = GROUP_COLOR_CLASS[group.icon] || 'group-color-default'
const iconHtml = ICONS[group.icon]
? `<span class="cmd-group-icon ${colorClass}">${ICONS[group.icon]}</span>`
: ''
lbl.innerHTML = `${iconHtml}<span class="${colorClass}">${group.label}</span>`
div.appendChild(lbl)
group.cmds.forEach(cmdDef => {
const btn = document.createElement('button')
btn.className = 'cmd-btn'
btn.textContent = cmdDef.label
const hint = buildCommandHint(cmdDef, group, typeInfo)
btn.title = hint
btn.setAttribute('aria-label', hint)
const cmdKey = commandButtonKey(cmdDef)
cmdButtonByKey.set(cmdKey, btn)
if (popupRunningByCmd.has(cmdKey)) {
btn.classList.add('running-popup')
}
if (mainRunning && currentMainCmdKey === cmdKey) {
btn.classList.add('running')
runningBtn = btn
}
btn.addEventListener('click', () => runCommand(btn, cmdDef))
div.appendChild(btn)
})
elGroups.appendChild(div)
})
}
// ── Run a command ─────────────────────────────────────────────────────────────
async function runCommand(btn, cmdDef) {
showPage('run')
if (currentAppIsDev && isNpmRunDevRenderer(cmdDef) && api && typeof api.openDevToolsForCommand === 'function') {
await api.openDevToolsForCommand({ cmd: cmdDef.cmd, args: cmdDef.args || [] })
}
ensureTerminalInitialized()
const cmdKey = commandButtonKey(cmdDef)
const streamMode = getSelectedStreamMode()
const preferPopup = isBuildLikeCommandRenderer(cmdDef)
if (!preferPopup && (!mainRunning || currentMainCmdKey === cmdKey)) {
if (runningBtn && runningBtn !== btn) {
runningBtn.classList.remove('running')
}
btn.classList.remove('done-ok', 'done-err', 'running-popup')
btn.classList.add('running')
runningBtn = btn
mainRunning = true
currentMainCmdKey = cmdKey
elKill.disabled = false
elDot.className = 'running'
elStatus.textContent = 'Running'
elRunning.textContent = `${btn.textContent} [${streamMode}]`
// Wait a moment for the Run page layout to settle before fitting and running.
setTimeout(async () => {
if (fitAddon) fitAddon.fit()
notifyPtyResize()
const _termCols = term ? (term.cols || 120) : 120
const _termRows = term ? (term.rows || 30) : 30
if (term) term.reset()
const res = await api.runCmd({
cmd: cmdDef.cmd,
args: cmdDef.args,
cwd: cmdDef.cwd,
streamMode,
cols: _termCols,
rows: _termRows,
})
if (!res || !res.ok) {
mainRunning = false
currentMainCmdKey = null
elKill.disabled = true
}
}, 50)
return
}
if (preferPopup) {
appendOutput(`\n[POPUP] Build-like command routed to Sandbox Terminal: ${btn.textContent}\n`)
}
btn.classList.remove('done-ok', 'done-err')
btn.classList.add('running-popup')
popupRunningByCmd.set(cmdKey, true)
const realCols = term ? (term.cols || 120) : 120
const realRows = term ? (term.rows || 30) : 30
const popupRes = await api.runCmdPopup({
cmd: cmdDef.cmd,
args: cmdDef.args,
cwd: cmdDef.cwd,
label: btn.textContent,
streamMode,
cols: realCols,
rows: realRows,
})
if (!popupRes || !popupRes.ok) {
popupRunningByCmd.delete(cmdKey)
btn.classList.remove('running-popup')
btn.classList.add('done-err')
appendOutput(`\n[POPUP ERROR] ${popupRes && popupRes.error ? popupRes.error : 'Failed to start popup'}\n`)
return
}
appendOutput(`\n[POPUP] ${popupRes.restarted ? 'Restarted' : 'Started'}: ${btn.textContent}\n`)
}
function bootstrapProjectInBackground() {
// Wait until first paint so users can interact with Home immediately.
requestAnimationFrame(() => {
setTimeout(() => {
loadProject().catch((e) => {
elName.textContent = 'Failed to load project'
elPath.textContent = e && e.message ? e.message : String(e || 'Unknown error')
})
}, 0)
})
}
// ── Load project ──────────────────────────────────────────────────────────────
async function loadProject() {
elName.textContent = 'Loading…'
elBadge.textContent = ''
elPath.textContent = ''
elGroups.innerHTML = ''
const data = await api.getProject()
currentAppIsDev = !!data?.isDev
const tabR2 = document.getElementById('tab-r2')
const pageR2 = document.getElementById('page-r2')
if (!currentAppIsDev) {
if (tabR2) tabR2.style.display = 'none'
if (pageR2) pageR2.style.display = 'none'
if (elDevQuickPanel) elDevQuickPanel.style.display = 'none'
} else {
if (tabR2) tabR2.style.display = ''
if (pageR2) pageR2.style.display = ''
if (elDevQuickPanel) elDevQuickPanel.style.display = ''
}
if (!data.ok) {
const blocked = !!data.blocked || /protected OS location/i.test(String(data.error || ''))
elName.textContent = blocked ? 'Security policy blocked this location' : 'No package.json found'
elPath.textContent = data.projectRoot
if (blocked) {
elGroups.innerHTML = `<div id="error-msg">
Project root is blocked by security policy:<br><b>${data.projectRoot}</b><br><br>
Use <b>Select Project</b> to choose a safe project folder outside OS protected paths.
</div>`
} else {
elGroups.innerHTML = `<div id="error-msg">
No <code>package.json</code> found in:<br><b>${data.projectRoot}</b><br><br>
Place the launcher inside your project folder and restart.
</div>`
}
return
}
const { projectRoot, projectName, typeInfo, groups, isDev } = data
currentAppIsDev = !!isDev
const osLabel = data && data.runtimeOs && data.runtimeOs.label
? String(data.runtimeOs.label)
: 'Unknown OS'
elName.textContent = projectName || 'Unnamed Project'
elPath.textContent = projectRoot
elBadge.textContent = `${typeInfo.label}${osLabel}`
elBadge.className = `type-badge ${typeInfo.badgeClass}`
document.title = `Dev Launcher — ${projectName || projectRoot}`
if (!isDev) {
if (tabR2) tabR2.style.display = 'none'
if (pageR2) pageR2.style.display = 'none'
if (elDevQuickPanel) elDevQuickPanel.style.display = 'none'
} else {
if (tabR2) tabR2.style.display = ''
if (pageR2) pageR2.style.display = ''
if (elDevQuickPanel) elDevQuickPanel.style.display = ''
}
renderGroups(groups, typeInfo)
}
// ── Events ────────────────────────────────────────────────────────────────────
document.getElementById('tab-home').addEventListener('click', () => showPage('home'))
document.getElementById('tab-run').addEventListener('click', () => showPage('run'))
const tabR2Btn = document.getElementById('tab-r2')
if (tabR2Btn) {
tabR2Btn.addEventListener('click', () => showPage('r2'))
}
document.getElementById('support-btn').addEventListener('click', () => {
showPage('support')
})
document.getElementById('btn-select-project').addEventListener('click', async () => {
await api.selectProjectFolder('full-project')
})
document.getElementById('btn-use-launcher-project').addEventListener('click', async () => {
await api.useLauncherProject()
})
const btnR2ConfigClose = document.getElementById('btn-r2-config-close')
if (btnR2ConfigClose) btnR2ConfigClose.addEventListener('click', () => closeModal(r2ConfigBackdrop))
const btnR2ConfigCancel = document.getElementById('btn-r2-config-cancel')
if (btnR2ConfigCancel) btnR2ConfigCancel.addEventListener('click', () => closeModal(r2ConfigBackdrop))
const btnR2ConfigClear = document.getElementById('btn-r2-config-clear')
if (btnR2ConfigClear) btnR2ConfigClear.addEventListener('click', clearSavedR2Config)
const btnR2ConfigSave = document.getElementById('btn-r2-config-save')
if (btnR2ConfigSave) btnR2ConfigSave.addEventListener('click', saveR2FromModal)
const btnR2UploadClose = document.getElementById('btn-r2-upload-close')
if (btnR2UploadClose) btnR2UploadClose.addEventListener('click', () => closeModal(r2UploadBackdrop))
const btnR2UploadCancel = document.getElementById('btn-r2-upload-cancel')
if (btnR2UploadCancel) btnR2UploadCancel.addEventListener('click', () => closeModal(r2UploadBackdrop))
const btnR2UploadRun = document.getElementById('btn-r2-upload-run')
if (btnR2UploadRun) btnR2UploadRun.addEventListener('click', runR2UploadFromModal)
document.getElementById('security-block-close').addEventListener('click', () => {
const backdrop = document.getElementById('security-block-backdrop')
if (backdrop) closeModal(backdrop)
})
if (elDevMainTools) {
elDevMainTools.addEventListener('click', async () => {
const res = await api.openMainDevTools()
if (!res || !res.ok) {
appendOutput(`\n[DEV] Main DevTools: ${res && res.error ? res.error : 'failed'}\n`)
}
})
}
if (elDevPopupTools) {
elDevPopupTools.addEventListener('click', async () => {
const res = await api.openPopupDevTools()
if (!res || !res.ok) {
appendOutput(`\n[DEV] Popup DevTools: ${res && res.error ? res.error : 'failed'}\n`)
return
}
appendOutput(`\n[DEV] Popup DevTools opened (runId=${res.runId || 'unknown'})\n`)
})
}
if (elDevSecurityStatus) {
elDevSecurityStatus.addEventListener('click', async () => {
const status = await api.getDevSecurityStatus()
if (!status || !status.ok) {
appendOutput(`\n[DEV] Security status unavailable\n`)
return
}
appendSecurityStatusLines(status)
})
}
document.addEventListener('keydown', (e) => {
if (e.key !== 'Escape') return
closeModal(r2ConfigBackdrop)
closeModal(r2UploadBackdrop)
})
elKill.addEventListener('click', async () => {
await api.killProc()
})
elClear.addEventListener('click', () => {
if (term) {
term.reset()
} else {
elOutput.innerHTML = ''
}
})
if (elStreamMode) {
const saved = String(localStorage.getItem('streamMode') || '').toLowerCase()
elStreamMode.value = saved === 'stable' ? 'stable' : 'realtime'
elStreamMode.addEventListener('change', () => {
localStorage.setItem('streamMode', getSelectedStreamMode())
})
}
// ── IPC listeners ─────────────────────────────────────────────────────────────
api.onOutput((data) => appendOutput(data))
api.onDone((code) => {
mainRunning = false
currentMainCmdKey = null
elKill.disabled = true
elDot.className = code === 0 ? '' : 'error'
elStatus.textContent = code === 0 ? 'Done ✓' : `Exited (${code})`
elRunning.textContent = ''
if (runningBtn) {
runningBtn.classList.remove('running')
runningBtn.classList.add(code === 0 ? 'done-ok' : 'done-err')
runningBtn = null
}
})
api.onPopupRunState((state) => {
if (!state || !state.cmdKey) return
const btn = cmdButtonByKey.get(state.cmdKey)
const status = String(state.status || '')
if (status === 'started' || status === 'restarted') {
popupRunningByCmd.set(state.cmdKey, true)
if (btn) {
btn.classList.remove('done-ok', 'done-err')
btn.classList.add('running-popup')
}
return
}
if (status === 'done' || status === 'closed' || status === 'closed-restart') {
popupRunningByCmd.delete(state.cmdKey)
if (btn) {
btn.classList.remove('running-popup')
if (status === 'done') {
btn.classList.add(Number(state.exitCode) === 0 ? 'done-ok' : 'done-err')
}
}
}
})
api.onProjectChanged(() => {
loadProject()
})
api.onProjectSelectionBlocked((payload) => {
showSecurityBlockModal(payload)
})
// ── Init ──────────────────────────────────────────────────────────────────────
bootstrapProjectInBackground()