Compare commits

...

4 Commits

Author SHA1 Message Date
86a91469be organize --help 2026-02-09 20:47:17 -08:00
9517f6d4b2 kill errant newline 2026-02-09 20:37:24 -08:00
d43e1c1c17 simpler sync 2026-02-09 20:36:58 -08:00
1685cc135d show cron errors 2026-02-09 20:36:46 -08:00
7 changed files with 342 additions and 110 deletions

View File

@ -190,13 +190,111 @@ const CancelButton = define('CancelButton', {
},
})
const BackLink = define('BackLink', {
base: 'a',
fontSize: '13px',
color: theme('colors-textMuted'),
textDecoration: 'none',
states: {
':hover': { color: theme('colors-text') },
},
})
const DetailHeader = define('DetailHeader', {
display: 'flex',
alignItems: 'center',
gap: '12px',
marginBottom: '20px',
})
const DetailTitle = define('DetailTitle', {
base: 'h1',
fontFamily: theme('fonts-mono'),
fontSize: '18px',
fontWeight: 600,
margin: 0,
flex: 1,
})
const DetailMeta = define('DetailMeta', {
display: 'flex',
gap: '20px',
marginBottom: '20px',
fontSize: '13px',
color: theme('colors-textMuted'),
})
const MetaItem = define('MetaItem', {
display: 'flex',
gap: '6px',
})
const MetaLabel = define('MetaLabel', {
fontWeight: 500,
color: theme('colors-text'),
})
const OutputSection = define('OutputSection', {
marginTop: '20px',
})
const OutputLabel = define('OutputLabel', {
fontSize: '13px',
fontWeight: 500,
marginBottom: '8px',
})
const OutputBlock = define('OutputBlock', {
base: 'pre',
fontFamily: theme('fonts-mono'),
fontSize: '12px',
lineHeight: 1.5,
padding: '12px',
backgroundColor: theme('colors-bgElement'),
border: `1px solid ${theme('colors-border')}`,
borderRadius: theme('radius-md'),
overflowX: 'auto',
overflowY: 'auto',
maxHeight: '60vh',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
margin: 0,
})
const ErrorBlock = define('ErrorBlock', {
base: 'pre',
fontFamily: theme('fonts-mono'),
fontSize: '12px',
lineHeight: 1.5,
padding: '12px',
backgroundColor: theme('colors-bgElement'),
border: `1px solid ${theme('colors-error')}`,
borderRadius: theme('radius-md'),
color: theme('colors-error'),
overflowX: 'auto',
overflowY: 'auto',
maxHeight: '60vh',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
margin: 0,
})
const StatusBadge = define('StatusBadge', {
base: 'span',
fontSize: '12px',
padding: '2px 8px',
borderRadius: '9999px',
fontWeight: 500,
})
// Layout
function Layout({ title, children }: { title: string; children: Child }) {
function Layout({ title, children, refresh }: { title: string; children: Child; refresh?: boolean }) {
return (
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{refresh && <meta http-equiv="refresh" content="2" />}
<title>{title}</title>
<link rel="stylesheet" href="/styles.css" />
</head>
@ -255,9 +353,10 @@ app.get('/', async c => {
invalid.sort((a, b) => a.id.localeCompare(b.id))
const hasAny = jobs.length > 0 || invalid.length > 0
const anyRunning = jobs.some(j => j.state === 'running')
return c.html(
<Layout title="Cron Jobs">
<Layout title="Cron Jobs" refresh={anyRunning}>
<ActionRow>
<NewButton href={`/new?app=${appFilter || ''}`}>New Job</NewButton>
</ActionRow>
@ -272,7 +371,11 @@ app.get('/', async c => {
{jobs.map(job => (
<JobItem>
<StatusDot style={{ backgroundColor: statusColor(job) }} />
<JobName>{job.app}/{job.name}</JobName>
<JobName>
<a href={`/job/${job.app}/${job.name}${appFilter ? `?app=${appFilter}` : ''}`} style={{ color: 'inherit', textDecoration: 'none' }}>
{job.app}/{job.name}
</a>
</JobName>
<Schedule>{job.schedule}</Schedule>
<Time title="Last run">{formatRelative(job.lastRun)}</Time>
<Time title="Next run">{formatRelative(job.nextRun)}</Time>
@ -296,6 +399,81 @@ app.get('/', async c => {
)
})
function statusBadgeStyle(job: CronJob): Record<string, string> {
if (job.state === 'running') return { backgroundColor: theme('colors-statusRunning'), color: 'white' }
if (job.lastExitCode !== undefined && job.lastExitCode !== 0) return { backgroundColor: theme('colors-error'), color: 'white' }
return { backgroundColor: theme('colors-bgElement'), color: theme('colors-textMuted') }
}
function statusLabel(job: CronJob): string {
if (job.state === 'running') return 'running'
if (job.lastExitCode !== undefined && job.lastExitCode !== 0) return `exit ${job.lastExitCode}`
if (job.lastRun) return 'ok'
return 'idle'
}
function formatDuration(ms?: number): string {
if (!ms) return '-'
if (ms < 1000) return `${ms}ms`
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
return `${Math.round(ms / 60000)}m`
}
app.get('/job/:app/:name', async c => {
const id = `${c.req.param('app')}:${c.req.param('name')}`
const job = getJob(id)
const appFilter = c.req.query('app')
const backUrl = appFilter ? `/?app=${appFilter}` : '/'
if (!job) {
return c.html(
<Layout title="Job Not Found">
<BackLink href={backUrl}>&#8592; Back</BackLink>
<EmptyState>Job not found: {id}</EmptyState>
</Layout>
)
}
return c.html(
<Layout title={`${job.app}/${job.name}`} refresh={job.state === 'running'}>
<BackLink href={backUrl}>&#8592; Back</BackLink>
<DetailHeader>
<StatusDot style={{ backgroundColor: statusColor(job) }} />
<DetailTitle>{job.app}/{job.name}</DetailTitle>
<StatusBadge style={statusBadgeStyle(job)}>{statusLabel(job)}</StatusBadge>
<form method="post" action={`/run/${job.app}/${job.name}?return=detail&app=${appFilter || ''}`}>
<RunButton type="submit" disabled={job.state === 'running'}>
{job.state === 'running' ? 'Running...' : 'Run Now'}
</RunButton>
</form>
</DetailHeader>
<DetailMeta>
<MetaItem><MetaLabel>Schedule</MetaLabel> {job.schedule}</MetaItem>
<MetaItem><MetaLabel>Last run</MetaLabel> {formatRelative(job.lastRun)}</MetaItem>
<MetaItem><MetaLabel>Duration</MetaLabel> {formatDuration(job.lastDuration)}</MetaItem>
<MetaItem><MetaLabel>Next run</MetaLabel> {formatRelative(job.nextRun)}</MetaItem>
</DetailMeta>
{job.lastError && (
<OutputSection>
<OutputLabel>Error</OutputLabel>
<ErrorBlock>{job.lastError}</ErrorBlock>
</OutputSection>
)}
{job.lastOutput && (
<OutputSection>
<OutputLabel>Output</OutputLabel>
<OutputBlock>{job.lastOutput}</OutputBlock>
</OutputSection>
)}
{!job.lastError && !job.lastOutput && job.lastRun && (
<OutputSection>
<EmptyState>No output</EmptyState>
</OutputSection>
)}
</Layout>
)
})
app.get('/new', async c => {
const appName = c.req.query('app') || ''
@ -387,9 +565,14 @@ app.post('/run/:app/:name', async c => {
return c.redirect('/?error=not-found')
}
await executeJob(job, broadcast)
// Fire-and-forget so the redirect happens immediately
executeJob(job, broadcast)
const returnTo = c.req.query('return')
const appFilter = c.req.query('app')
if (returnTo === 'detail') {
return c.redirect(`/job/${job.app}/${job.name}${appFilter ? `?app=${appFilter}` : ''}`)
}
return c.redirect(appFilter ? `/?app=${appFilter}` : '/')
})
@ -438,6 +621,7 @@ async function rediscover() {
job.lastDuration = old.lastDuration
job.lastExitCode = old.lastExitCode
job.lastError = old.lastError
job.lastOutput = old.lastOutput
job.nextRun = old.nextRun
}
}

View File

@ -3,6 +3,7 @@ import type { CronJob } from './schedules'
import { getNextRun } from './scheduler'
const APPS_DIR = process.env.APPS_DIR!
const RUNNER = join(import.meta.dir, 'runner.ts')
export async function executeJob(job: CronJob, onUpdate: () => void): Promise<void> {
if (job.state === 'disabled') return
@ -14,7 +15,7 @@ export async function executeJob(job: CronJob, onUpdate: () => void): Promise<vo
const cwd = join(APPS_DIR, job.app, 'current')
try {
const proc = Bun.spawn(['bun', 'run', job.file], {
const proc = Bun.spawn(['bun', 'run', RUNNER, job.file], {
cwd,
env: { ...process.env },
stdout: 'pipe',
@ -31,6 +32,7 @@ export async function executeJob(job: CronJob, onUpdate: () => void): Promise<vo
job.lastDuration = Date.now() - job.lastRun
job.lastExitCode = code
job.lastError = code !== 0 ? stderr || 'Non-zero exit' : undefined
job.lastOutput = stdout || undefined
job.state = 'idle'
job.nextRun = getNextRun(job.id)

View File

@ -0,0 +1,16 @@
export {}
Error.stackTraceLimit = 50
const file = process.argv[2]!
const { default: fn } = await import(file)
try {
await fn()
} catch (e) {
if (e instanceof Error) {
console.error(e.stack || e.message)
} else {
console.error(e)
}
process.exit(1)
}

View File

@ -17,6 +17,7 @@ export type CronJob = {
lastDuration?: number
lastExitCode?: number
lastError?: string
lastOutput?: string
nextRun?: number
}

View File

@ -1,9 +1,9 @@
import type { Manifest } from '@types'
import { loadGitignore } from '@gitignore'
import { computeHash, generateManifest } from '%sync'
import { generateManifest } from '%sync'
import color from 'kleur'
import { diffLines } from 'diff'
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from 'fs'
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, unlinkSync, watch, writeFileSync } from 'fs'
import { dirname, join } from 'path'
import { del, download, get, getManifest, handleError, makeUrl, post, put } from '../http'
import { confirm, prompt } from '../prompts'
@ -64,7 +64,7 @@ export async function getApp(name: string) {
console.log(color.green(`✓ Downloaded ${name}`))
}
export async function pushApp() {
export async function pushApp(options: { quiet?: boolean } = {}) {
if (!isApp()) {
console.error(notAppError())
return
@ -98,10 +98,16 @@ export async function pushApp() {
}
}
// Note: We don't delete files in versioned deployments - new version is separate directory
// Files to delete (exist on server but not locally)
const toDelete: string[] = []
for (const file of remoteFiles) {
if (!localFiles.has(file)) {
toDelete.push(file)
}
}
if (toUpload.length === 0) {
console.log('Already up to date')
if (toUpload.length === 0 && toDelete.length === 0) {
if (!options.quiet) console.log('Already up to date')
return
}
@ -141,7 +147,20 @@ export async function pushApp() {
}
}
// 3. Activate new version (updates symlink and restarts app)
// 3. Delete files that no longer exist locally
if (toDelete.length > 0) {
console.log(`Deleting ${toDelete.length} files...`)
for (const file of toDelete) {
const success = await del(`/api/sync/apps/${appName}/files/${file}?version=${version}`)
if (success) {
console.log(` ${color.red('✗')} ${file}`)
} else {
console.log(` ${color.red('✗')} ${file} (failed)`)
}
}
}
// 4. Activate new version (updates symlink and restarts app)
type ActivateResponse = { ok: boolean }
const activateRes = await post<ActivateResponse>(`/api/sync/apps/${appName}/activate?version=${version}`)
if (!activateRes?.ok) {
@ -152,7 +171,7 @@ export async function pushApp() {
console.log(color.green(`✓ Deployed and activated version ${version}`))
}
export async function pullApp(options: { force?: boolean } = {}) {
export async function pullApp(options: { force?: boolean, quiet?: boolean } = {}) {
if (!isApp()) {
console.error(notAppError())
return
@ -188,7 +207,7 @@ export async function pullApp(options: { force?: boolean } = {}) {
const toDelete = localOnly
if (toDownload.length === 0 && toDelete.length === 0) {
console.log('Already up to date')
if (!options.quiet) console.log('Already up to date')
return
}
@ -379,39 +398,32 @@ export async function syncApp() {
}
const appName = getAppName()
const gitignore = loadGitignore(process.cwd())
const localHashes = new Map<string, string>()
// Initialize local hashes
const manifest = generateManifest(process.cwd(), appName)
for (const [path, info] of Object.entries(manifest.files)) {
localHashes.set(path, info.hash)
// Verify app exists on server
const result = await getManifest(appName)
if (result === null) return
if (!result.exists) {
console.error(`App ${color.bold(appName)} doesn't exist on server. Run ${color.bold('toes push')} first.`)
return
}
console.log(`Syncing ${color.bold(appName)}...`)
// Watch local files
const watcher = watch(process.cwd(), { recursive: true }, async (_event, filename) => {
// Initial sync: pull remote changes, then push local changes
await pullApp({ force: true, quiet: true })
await pushApp({ quiet: true })
const gitignore = loadGitignore(process.cwd())
// Watch local files with debounce → push
let pushTimer: Timer | null = null
const watcher = watch(process.cwd(), { recursive: true }, (_event, filename) => {
if (!filename || gitignore.shouldExclude(filename)) return
const fullPath = join(process.cwd(), filename)
if (existsSync(fullPath) && statSync(fullPath).isFile()) {
const content = readFileSync(fullPath)
const hash = computeHash(content)
if (localHashes.get(filename) !== hash) {
localHashes.set(filename, hash)
await put(`/api/sync/apps/${appName}/files/${filename}`, content)
console.log(` ${color.green('↑')} ${filename}`)
}
} else if (!existsSync(fullPath)) {
localHashes.delete(filename)
await del(`/api/sync/apps/${appName}/files/${filename}`)
console.log(` ${color.red('✗')} ${filename}`)
}
if (pushTimer) clearTimeout(pushTimer)
pushTimer = setTimeout(() => pushApp({ quiet: true }), 500)
})
// Connect to SSE for remote changes
// Connect to SSE for remote changes → pull
const url = makeUrl(`/api/sync/apps/${appName}/watch`)
let res: Response
try {
@ -433,11 +445,12 @@ export async function syncApp() {
return
}
console.log(` Connected to server, watching for changes...`)
console.log(` Connected, watching for changes...`)
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
let pullTimer: Timer | null = null
try {
while (true) {
@ -450,30 +463,13 @@ export async function syncApp() {
for (const line of lines) {
if (!line.startsWith('data: ')) continue
const event = JSON.parse(line.slice(6)) as { type: 'change' | 'delete', path: string, hash?: string }
if (event.type === 'change') {
// Skip if we already have this version (handles echo from our own changes)
if (localHashes.get(event.path) === event.hash) continue
const content = await download(`/api/sync/apps/${appName}/files/${event.path}`)
if (content) {
const fullPath = join(process.cwd(), event.path)
mkdirSync(dirname(fullPath), { recursive: true })
writeFileSync(fullPath, content)
localHashes.set(event.path, event.hash!)
console.log(` ${color.green('↓')} ${event.path}`)
}
} else if (event.type === 'delete') {
const fullPath = join(process.cwd(), event.path)
if (existsSync(fullPath)) {
unlinkSync(fullPath)
localHashes.delete(event.path)
console.log(` ${color.red('✗')} ${event.path} (remote)`)
}
}
if (pullTimer) clearTimeout(pullTimer)
pullTimer = setTimeout(() => pullApp({ force: true, quiet: true }), 500)
}
}
} finally {
if (pushTimer) clearTimeout(pushTimer)
if (pullTimer) clearTimeout(pullTimer)
watcher.close()
}
}

View File

@ -1,6 +1,7 @@
import { program } from 'commander'
import color from 'kleur'
import pkg from '../../package.json'
import {
cleanApp,
@ -37,17 +38,15 @@ program
.version(`v${pkg.version}`, '-v, --version')
.addHelpText('beforeAll', (ctx) => {
if (ctx.command === program) {
return color.bold().cyan('\n🐾 Toes') + color.gray(' - personal web appliance\n')
return color.bold().cyan('🐾 Toes') + color.gray(' - personal web appliance\n')
}
return ''
})
.addHelpCommand(false)
.configureOutput({
writeOut: (str) => {
const colored = str
.replace(/^(Usage:)/gm, color.yellow('$1'))
.replace(/^(Commands:)/gm, color.yellow('$1'))
.replace(/^(Options:)/gm, color.yellow('$1'))
.replace(/^(Arguments:)/gm, color.yellow('$1'))
.replace(/^([A-Z][\w ]*:)/gm, color.yellow('$1'))
process.stdout.write(colored)
},
})
@ -56,44 +55,88 @@ program
.command('version', { hidden: true })
.action(() => console.log(program.version()))
program
.command('config')
.description('Show current host configuration')
.action(configShow)
program
.command('info')
.description('Show info for an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(infoApp)
// Apps
program
.command('list')
.helpGroup('Apps:')
.description('List all apps')
.option('-t, --tools', 'show only tools')
.option('-a, --apps', 'show only apps (exclude tools)')
.action(listApps)
program
.command('info')
.helpGroup('Apps:')
.description('Show info for an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(infoApp)
program
.command('new')
.helpGroup('Apps:')
.description('Create a new toes app')
.argument('[name]', 'app name (uses current directory if omitted)')
.option('--ssr', 'SSR template with pages directory (default)')
.option('--bare', 'minimal template with no pages')
.option('--spa', 'single-page app with client-side rendering')
.action(newApp)
program
.command('get')
.helpGroup('Apps:')
.description('Download an app from server')
.argument('<name>', 'app name')
.action(getApp)
program
.command('open')
.helpGroup('Apps:')
.description('Open an app in browser')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(openApp)
program
.command('rename')
.helpGroup('Apps:')
.description('Rename an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.argument('<new-name>', 'new app name')
.action(renameApp)
program
.command('rm')
.helpGroup('Apps:')
.description('Remove an app from the server')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(rmApp)
// Lifecycle
program
.command('start')
.helpGroup('Lifecycle:')
.description('Start an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(startApp)
program
.command('stop')
.helpGroup('Lifecycle:')
.description('Stop an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(stopApp)
program
.command('restart')
.helpGroup('Lifecycle:')
.description('Restart an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(restartApp)
program
.command('logs')
.helpGroup('Lifecycle:')
.description('Show logs for an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.option('-f, --follow', 'follow log output')
@ -113,59 +156,47 @@ program
program
.command('stats')
.helpGroup('Lifecycle:')
.description('Show CPU and memory stats for apps')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(statsApp)
program
.command('open')
.description('Open an app in browser')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(openApp)
program
.command('get')
.description('Download an app from server')
.argument('<name>', 'app name')
.action(getApp)
program
.command('new')
.description('Create a new toes app')
.argument('[name]', 'app name (uses current directory if omitted)')
.option('--ssr', 'SSR template with pages directory (default)')
.option('--bare', 'minimal template with no pages')
.option('--spa', 'single-page app with client-side rendering')
.action(newApp)
// Sync
program
.command('push')
.helpGroup('Sync:')
.description('Push local changes to server')
.action(pushApp)
program
.command('pull')
.helpGroup('Sync:')
.description('Pull changes from server')
.option('-f, --force', 'overwrite local changes')
.action(pullApp)
program
.command('status')
.helpGroup('Sync:')
.description('Show what would be pushed/pulled')
.action(statusApp)
program
.command('diff')
.helpGroup('Sync:')
.description('Show diff of changed files')
.action(diffApp)
program
.command('sync')
.helpGroup('Sync:')
.description('Watch and sync changes bidirectionally')
.action(syncApp)
program
.command('clean')
.helpGroup('Sync:')
.description('Remove local files not on server')
.option('-f, --force', 'skip confirmation')
.option('-n, --dry-run', 'show what would be removed')
@ -173,6 +204,7 @@ program
const stash = program
.command('stash')
.helpGroup('Sync:')
.description('Stash local changes')
.action(stashApp)
@ -186,8 +218,17 @@ stash
.description('List all stashes')
.action(stashListApp)
// Config
program
.command('config')
.helpGroup('Config:')
.description('Show current host configuration')
.action(configShow)
const env = program
.command('env')
.helpGroup('Config:')
.description('Manage environment variables')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(envList)
@ -209,28 +250,17 @@ env
program
.command('versions')
.helpGroup('Config:')
.description('List deployed versions')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(versionsApp)
program
.command('rollback')
.helpGroup('Config:')
.description('Rollback to a previous version')
.argument('[name]', 'app name (uses current directory if omitted)')
.option('-v, --version <version>', 'version to rollback to (prompts if omitted)')
.action((name, options) => rollbackApp(name, options.version))
program
.command('rm')
.description('Remove an app from the server')
.argument('[name]', 'app name (uses current directory if omitted)')
.action(rmApp)
program
.command('rename')
.description('Rename an app')
.argument('[name]', 'app name (uses current directory if omitted)')
.argument('<new-name>', 'new app name')
.action(renameApp)
export { program }

View File

@ -126,10 +126,13 @@ router.delete('/apps/:app', c => {
router.delete('/apps/:app/files/:path{.+}', c => {
const appName = c.req.param('app')
const filePath = c.req.param('path')
const version = c.req.query('version')
if (!appName || !filePath) return c.json({ error: 'Invalid path' }, 400)
const basePath = join(APPS_DIR, appName, 'current')
const basePath = version
? join(APPS_DIR, appName, version)
: join(APPS_DIR, appName, 'current')
const fullPath = safePath(basePath, filePath)
if (!fullPath) return c.json({ error: 'Invalid path' }, 400)