From 93b4656939c2bcad1bf11df48f36051db7df9884 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 12:37:49 +0800 Subject: [PATCH 1/9] feat(cli): add daemon mode and stop, logs, restart subcommands --- apps/agent/src/index.ts | 3 +- apps/transcode/src/index.ts | 3 +- apps/web/src/index.ts | 191 +++++++++--------- packages/core/src/utils/daemon.test.ts | 133 +++++++++++++ packages/core/src/utils/daemon.ts | 263 +++++++++++++++++++++++++ scripts/build-npm.ts | 3 +- 6 files changed, 502 insertions(+), 94 deletions(-) create mode 100644 packages/core/src/utils/daemon.test.ts create mode 100644 packages/core/src/utils/daemon.ts diff --git a/apps/agent/src/index.ts b/apps/agent/src/index.ts index 66dd1be9..64f174e7 100644 --- a/apps/agent/src/index.ts +++ b/apps/agent/src/index.ts @@ -4,6 +4,7 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production') import { workflowService } from '@shumai/workflow-core' import { TaskQueueAgent } from '@shumai/workflow-core' import { initAgentWorkflows } from '@shumai/agent' +import { handleDaemonCommands } from '@shumai/core/src/utils/daemon' if (process.argv.includes('--check')) { console.log('āœ… Agent worker evaluated successfully!') @@ -28,7 +29,7 @@ async function run() { await workflowService.startWorkers(TaskQueueAgent, options) } -run().catch((err) => { +handleDaemonCommands('shumai-agent', run).catch((err) => { console.error(err) process.exit(1) }) diff --git a/apps/transcode/src/index.ts b/apps/transcode/src/index.ts index 915b3692..cd020430 100644 --- a/apps/transcode/src/index.ts +++ b/apps/transcode/src/index.ts @@ -3,6 +3,7 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production') import { initTranscodeWorkflows } from '@shumai/transcode' import { TaskQueueTranscode, workflowService } from '@shumai/workflow-core' +import { handleDaemonCommands } from '@shumai/core/src/utils/daemon' if (process.argv.includes('--check')) { console.log('āœ… Transcode worker evaluated successfully!') @@ -27,7 +28,7 @@ async function run() { await workflowService.startWorkers(TaskQueueTranscode, options) } -run().catch((err) => { +handleDaemonCommands('shumai-transcode', run).catch((err) => { console.error(err) process.exit(1) }) diff --git a/apps/web/src/index.ts b/apps/web/src/index.ts index d5860a94..465f497d 100644 --- a/apps/web/src/index.ts +++ b/apps/web/src/index.ts @@ -11,118 +11,127 @@ import { initTranscodeWorkflows } from '@shumai/transcode' import { workflowService } from '@shumai/workflow-core' import { app } from '@shumai/api' +import { handleDaemonCommands } from '@shumai/core/src/utils/daemon' + if (process.argv.includes('--check')) { console.log('āœ… Web app evaluated successfully!') process.exit(0) } -// Initialize workflows and activities for local executor mode -initAgentWorkflows() -initTranscodeWorkflows() +async function run() { + // Initialize workflows and activities for local executor mode + initAgentWorkflows() + initTranscodeWorkflows() -// Start services -await metadataService.syncSystemFields().catch(console.error) -assetService.startCleanupJob() -workflowService.start() -if (process.env.WORKFLOW_EXECUTOR === 'temporal') { - const args = process.argv.slice(2) - let workersOption = '' - for (let i = 0; i < args.length; i++) { - if (args[i] === '--workers') { - workersOption = args[i + 1] || '' - } else if (args[i].startsWith('--workers=')) { - workersOption = args[i].split('=')[1] + // Start services + await metadataService.syncSystemFields().catch(console.error) + assetService.startCleanupJob() + workflowService.start() + if (process.env.WORKFLOW_EXECUTOR === 'temporal') { + const args = process.argv.slice(2) + let workersOption = '' + for (let i = 0; i < args.length; i++) { + if (args[i] === '--workers') { + workersOption = args[i + 1] || '' + } else if (args[i].startsWith('--workers=')) { + workersOption = args[i].split('=')[1] + } } + + const queuesToStart: string[] = [] + if (workersOption === 'agent' || workersOption === 'ai') { + queuesToStart.push('agent_queue') + } else if (workersOption === 'transcode') { + queuesToStart.push('transcode_queue') + } else if (workersOption === 'all') { + queuesToStart.push('agent_queue', 'transcode_queue') + } + + Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error) } - const queuesToStart: string[] = [] - if (workersOption === 'agent' || workersOption === 'ai') { - queuesToStart.push('agent_queue') - } else if (workersOption === 'transcode') { - queuesToStart.push('transcode_queue') - } else if (workersOption === 'all') { - queuesToStart.push('agent_queue', 'transcode_queue') - } + const isProd = process.env.NODE_ENV === 'production' - Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error) -} + const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000 -const isProd = process.env.NODE_ENV === 'production' + const server = Bun.serve( + isProd + ? { + port, + maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE + ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) + : 1024 * 1024 * 1024 * 10, // Default 10GB + development: false, + async fetch(req) { + const url = new URL(req.url) -const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000 - -const server = Bun.serve( - isProd - ? { - port, - maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE - ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) - : 1024 * 1024 * 1024 * 10, // Default 10GB - development: false, - async fetch(req) { - const url = new URL(req.url) - - if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/files/')) { - const filepath = join(import.meta.dir, url.pathname) - const file = Bun.file(filepath) - if (await file.exists()) { - try { - const stat = await file.stat() - if (stat.isFile()) { - return new Response(file) + if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/files/')) { + const filepath = join(import.meta.dir, url.pathname) + const file = Bun.file(filepath) + if (await file.exists()) { + try { + const stat = await file.stat() + if (stat.isFile()) { + return new Response(file) + } + } catch { + // ignore stat errors } - } catch { - // ignore stat errors + } + + const htmlFile = Bun.file(join(import.meta.dir, 'index.html')) + if (await htmlFile.exists()) { + return new Response(htmlFile, { + headers: { 'Content-Type': 'text/html' }, + }) + } + + const htmlFileNpm = Bun.file(join(import.meta.dir, 'shumai-app.html')) + if (await htmlFileNpm.exists()) { + return new Response(htmlFileNpm, { + headers: { 'Content-Type': 'text/html' }, + }) } } - const htmlFile = Bun.file(join(import.meta.dir, 'index.html')) - if (await htmlFile.exists()) { - return new Response(htmlFile, { - headers: { 'Content-Type': 'text/html' }, - }) - } + return app.fetch(req) + }, + } + : { + port, + maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE + ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) + : 1024 * 1024 * 1024 * 10, // Default 10GB + development: true, + fetch: app.fetch, + routes: { + // Serve index.html for root + '/': index, - const htmlFileNpm = Bun.file(join(import.meta.dir, 'shumai-app.html')) - if (await htmlFileNpm.exists()) { - return new Response(htmlFileNpm, { - headers: { 'Content-Type': 'text/html' }, - }) - } - } + // Proxy API requests to Hono + '/api/*': app.fetch, + '/files/*': app.fetch, - return app.fetch(req) + // Catch-all for SPA routing (fallback to index.html) + '/*': index, + }, }, - } - : { - port, - maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE - ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) - : 1024 * 1024 * 1024 * 10, // Default 10GB - development: true, - fetch: app.fetch, - routes: { - // Serve index.html for root - '/': index, + ) - // Proxy API requests to Hono - '/api/*': app.fetch, - '/files/*': app.fetch, + console.log(`šŸš€ Server running at ${server.url}`) - // Catch-all for SPA routing (fallback to index.html) - '/*': index, - }, - }, -) + const shutdown = () => { + console.log('\nShutting down gracefully...') + assetService.stopCleanupJob() + server.stop(true) + process.exit(0) + } -console.log(`šŸš€ Server running at ${server.url}`) - -const shutdown = () => { - console.log('\nShutting down gracefully...') - assetService.stopCleanupJob() - server.stop(true) - process.exit(0) + process.on('SIGINT', shutdown) + process.on('SIGTERM', shutdown) } -process.on('SIGINT', shutdown) -process.on('SIGTERM', shutdown) +handleDaemonCommands('shumai', run).catch((err) => { + console.error(err) + process.exit(1) +}) diff --git a/packages/core/src/utils/daemon.test.ts b/packages/core/src/utils/daemon.test.ts new file mode 100644 index 00000000..526431e0 --- /dev/null +++ b/packages/core/src/utils/daemon.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it, vi, beforeEach, afterEach, type MockInstance } from 'vitest' +import { existsSync, writeFileSync, readFileSync, rmSync, mkdirSync, createWriteStream } from 'node:fs' +import { join } from 'node:path' +import { handleDaemonCommands } from './daemon' +import { spawn } from 'node:child_process' +import { Writable } from 'node:stream' + +// Mock os.homedir to return a temporary directory for test isolation +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal() + const mockTempDir = `${actual.tmpdir()}/shumai-test-daemon-${Math.random().toString(36).substring(2)}` + return { + ...actual, + homedir: () => mockTempDir, + } +}) + +// Mock node:child_process for spawn tests +vi.mock('node:child_process', () => { + return { + spawn: vi.fn(() => { + return { + pid: 99999, + unref: vi.fn(), + } + }), + } +}) + +// Mock node:fs to mock createWriteStream for ESM safety +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + const { Writable } = require('node:stream') + return { + ...actual, + createWriteStream: vi.fn(() => { + return new Writable({ + write(_chunk: unknown, _encoding: string, callback: (error?: Error | null) => void) { + callback() + }, + }) + }), + } +}) + +import { homedir } from 'node:os' + +describe('handleDaemonCommands', () => { + const appName = 'test-app' + const mockTempDir = homedir() + const pidFile = join(mockTempDir, '.shumai', 'pids', `${appName}.pid`) + + let mockExit: MockInstance + let mockKill: MockInstance + const originalArgv = process.argv + + beforeEach(() => { + mkdirSync(mockTempDir, { recursive: true }) + mockExit = vi.spyOn(process, 'exit').mockImplementation(() => { + throw new Error('process.exit') + }) + mockKill = vi.spyOn(process, 'kill').mockImplementation(() => true) + + vi.mocked(spawn).mockClear() + vi.mocked(createWriteStream).mockClear() + }) + + afterEach(() => { + process.argv = originalArgv + vi.restoreAllMocks() + try { + rmSync(mockTempDir, { recursive: true, force: true }) + } catch { + // Ignore + } + }) + + it('runs the runFn on normal startup', async () => { + process.argv = ['node', 'script.js'] + const runFn = vi.fn().mockResolvedValue(undefined) + + await handleDaemonCommands(appName, runFn) + + expect(runFn).toHaveBeenCalled() + expect(existsSync(pidFile)).toBe(true) + expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString()) + }) + + it('stops the process if stop command is passed', async () => { + process.argv = ['node', 'script.js', 'stop'] + const runFn = vi.fn().mockResolvedValue(undefined) + + // Write a dummy PID file + mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true }) + writeFileSync(pidFile, '12345') + + await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit') + + expect(runFn).not.toHaveBeenCalled() + expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM') + expect(mockExit).toHaveBeenCalledWith(0) + expect(createWriteStream).not.toHaveBeenCalled() + }) + + it('daemonizes the process if -d is passed', async () => { + process.argv = ['node', 'script.js', '-d'] + const runFn = vi.fn().mockResolvedValue(undefined) + + await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit') + + expect(runFn).not.toHaveBeenCalled() + expect(spawn).toHaveBeenCalled() + expect(existsSync(pidFile)).toBe(true) + expect(readFileSync(pidFile, 'utf8').trim()).toBe('99999') + expect(mockExit).toHaveBeenCalledWith(0) + }) + + it('restarts the process if restart command is passed', async () => { + process.argv = ['node', 'script.js', 'restart'] + const runFn = vi.fn().mockResolvedValue(undefined) + + // Write a dummy PID file + mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true }) + writeFileSync(pidFile, '12345') + + await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit') + + expect(runFn).not.toHaveBeenCalled() + expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM') + expect(spawn).toHaveBeenCalled() + expect(mockExit).toHaveBeenCalledWith(0) + }) +}) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts new file mode 100644 index 00000000..c8d16865 --- /dev/null +++ b/packages/core/src/utils/daemon.ts @@ -0,0 +1,263 @@ +import { spawn } from 'node:child_process' +import { + existsSync, + writeFileSync, + readFileSync, + unlinkSync, + mkdirSync, + watch, + statSync, + createReadStream, + createWriteStream, +} from 'node:fs' +import { join } from 'node:path' +import { homedir } from 'node:os' + +const SHUMAI_DIR = join(homedir(), '.shumai') +const PID_DIR = join(SHUMAI_DIR, 'pids') +const LOG_DIR = join(SHUMAI_DIR, 'logs') + +async function stopProcess(appName: string, pidFile: string): Promise { + if (!existsSync(pidFile)) { + console.log(`No running instance of ${appName} found.`) + return false + } + + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + if (isNaN(pid)) { + console.log(`Invalid PID found in ${pidFile}. Cleaning up file.`) + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + return false + } + + let isRunning = false + try { + process.kill(pid, 0) + isRunning = true + } catch { + // Not running + } + + if (!isRunning) { + console.log(`Process ${pid} is not running. Cleaning up PID file.`) + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + return false + } + + console.log(`Stopping ${appName} (PID: ${pid})...`) + try { + process.kill(pid, 'SIGTERM') + } catch (err) { + console.error(`Failed to send SIGTERM to process ${pid}:`, err) + return false + } + + // Wait for it to stop + for (let i = 0; i < 30; i++) { + try { + process.kill(pid, 0) + await new Promise((resolve) => setTimeout(resolve, 100)) + } catch { + isRunning = false + break + } + } + + if (isRunning) { + console.log(`Process ${pid} did not stop gracefully. Sending SIGKILL...`) + try { + process.kill(pid, 'SIGKILL') + } catch (err) { + console.error(`Failed to send SIGKILL to process ${pid}:`, err) + } + } + + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + + console.log(`Successfully stopped ${appName}.`) + return true +} + +function startDaemon(appName: string, pidFile: string, logFile: string): void { + // Check if already running + if (existsSync(pidFile)) { + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + if (!isNaN(pid)) { + try { + process.kill(pid, 0) + console.error(`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`) + process.exit(1) + } catch { + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + } + } + } + + console.log(`Starting ${appName} in background...`) + const logStream = createWriteStream(logFile, { flags: 'a' }) + + const childArgs = process.argv.slice(1).filter((arg) => arg !== '-d' && arg !== 'restart') + + const child = spawn(process.argv[0], childArgs, { + detached: true, + stdio: ['ignore', logStream, logStream], + env: { + ...process.env, + SHUMAI_DAEMONIZED: 'true', + }, + }) + + if (child.pid === undefined) { + console.error(`Failed to spawn background process for ${appName}.`) + process.exit(1) + } + + child.unref() + writeFileSync(pidFile, child.pid.toString(), 'utf8') + console.log(`šŸš€ Started ${appName} in background (PID: ${child.pid}).`) + console.log(`šŸ“„ Logs are being written to ${logFile}`) + process.exit(0) +} + +function viewLogs(appName: string, logFile: string): void { + if (!existsSync(logFile)) { + console.log(`No log file found for ${appName}.`) + process.exit(0) + } + + // Print existing content (last 100 lines) + const content = readFileSync(logFile, 'utf8') + const lines = content.split('\n') + const lastLines = lines.slice(-100).join('\n') + process.stdout.write(lastLines + '\n') + + let cursor = statSync(logFile).size + const watcher = watch(logFile, (event) => { + if (event === 'change') { + try { + const stats = statSync(logFile) + if (stats.size > cursor) { + const stream = createReadStream(logFile, { start: cursor, end: stats.size - 1 }) + stream.pipe(process.stdout, { end: false }) + cursor = stats.size + } else if (stats.size < cursor) { + cursor = stats.size + } + } catch { + // Ignore read errors + } + } + }) + + const cleanup = () => { + watcher.close() + process.exit(0) + } + process.on('SIGINT', cleanup) + process.on('SIGTERM', cleanup) +} + +export async function handleDaemonCommands(appName: string, runFn: () => Promise): Promise { + const pidFile = join(PID_DIR, `${appName}.pid`) + const logFile = join(LOG_DIR, `${appName}.log`) + + // Ensure directories exist + mkdirSync(PID_DIR, { recursive: true }) + mkdirSync(LOG_DIR, { recursive: true }) + + const args = process.argv.slice(2) + const isStop = args.includes('stop') + const isRestart = args.includes('restart') + const isLogs = args.includes('logs') + const isDaemon = args.includes('-d') && process.env.SHUMAI_DAEMONIZED !== 'true' + + if (isStop) { + await stopProcess(appName, pidFile) + process.exit(0) + } + + if (isRestart) { + await stopProcess(appName, pidFile) + await new Promise((resolve) => setTimeout(resolve, 500)) + startDaemon(appName, pidFile, logFile) + process.exit(0) + } + + if (isLogs) { + viewLogs(appName, logFile) + // Keep process open for logs tailing + return new Promise(() => {}) + } + + if (isDaemon) { + startDaemon(appName, pidFile, logFile) + process.exit(0) + } + + // Normal Startup logic: check if already running + if (existsSync(pidFile)) { + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + if (!isNaN(pid)) { + try { + process.kill(pid, 0) + console.error(`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`) + process.exit(1) + } catch { + // Process is dead, clean up PID file + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + } + } + } + + // Write the PID file + writeFileSync(pidFile, process.pid.toString(), 'utf8') + + const cleanPidFile = () => { + try { + if (existsSync(pidFile)) { + const pidStr = readFileSync(pidFile, 'utf8').trim() + if (parseInt(pidStr, 10) === process.pid) { + unlinkSync(pidFile) + } + } + } catch { + // Ignore + } + } + + // Register cleanups + process.on('exit', cleanPidFile) + + const handleSignal = (signal: string) => { + cleanPidFile() + if (process.listenerCount(signal) === 1) { + process.exit(0) + } + } + + process.on('SIGINT', () => handleSignal('SIGINT')) + process.on('SIGTERM', () => handleSignal('SIGTERM')) + + // Run the main app + await runFn() +} diff --git a/scripts/build-npm.ts b/scripts/build-npm.ts index 46f0296d..a9ecf3bf 100644 --- a/scripts/build-npm.ts +++ b/scripts/build-npm.ts @@ -373,7 +373,8 @@ console.log(\`ā„¹ļø [${appName}] Running from CWD: \${process.cwd()}\`) console.log(\`ā„¹ļø [${appName}] DATABASE_URL is: \${process.env.DATABASE_URL ? '(defined)' : '(undefined)'}\`) const prismaSchemaPath = join(__dirname, '..', 'prisma', 'schema.prisma') -if (existsSync(prismaSchemaPath)) { +const isUtilityCommand = process.argv.includes('stop') || process.argv.includes('logs') +if (existsSync(prismaSchemaPath) && !isUtilityCommand) { console.log('šŸ”„ Running database migrations...') activeProcess = spawn( binaryPath, From 463cd61cfd722cbab5efe6bce7531b3825fd1553 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 12:40:14 +0800 Subject: [PATCH 2/9] test(cli): resolve lint violations in daemon test file --- packages/core/src/utils/daemon.test.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/core/src/utils/daemon.test.ts b/packages/core/src/utils/daemon.test.ts index 526431e0..1a281435 100644 --- a/packages/core/src/utils/daemon.test.ts +++ b/packages/core/src/utils/daemon.test.ts @@ -1,9 +1,15 @@ import { describe, expect, it, vi, beforeEach, afterEach, type MockInstance } from 'vitest' -import { existsSync, writeFileSync, readFileSync, rmSync, mkdirSync, createWriteStream } from 'node:fs' +import { + existsSync, + writeFileSync, + readFileSync, + rmSync, + mkdirSync, + createWriteStream, +} from 'node:fs' import { join } from 'node:path' import { handleDaemonCommands } from './daemon' import { spawn } from 'node:child_process' -import { Writable } from 'node:stream' // Mock os.homedir to return a temporary directory for test isolation vi.mock('node:os', async (importOriginal) => { @@ -30,7 +36,7 @@ vi.mock('node:child_process', () => { // Mock node:fs to mock createWriteStream for ESM safety vi.mock('node:fs', async (importOriginal) => { const actual = await importOriginal() - const { Writable } = require('node:stream') + const { Writable } = await import('node:stream') return { ...actual, createWriteStream: vi.fn(() => { @@ -60,7 +66,7 @@ describe('handleDaemonCommands', () => { throw new Error('process.exit') }) mockKill = vi.spyOn(process, 'kill').mockImplementation(() => true) - + vi.mocked(spawn).mockClear() vi.mocked(createWriteStream).mockClear() }) From d4a1eff715d38252b83c26c6bde0c71743e0d9ff Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 12:49:05 +0800 Subject: [PATCH 3/9] fix(cli): resolve Bun compatibility issue with WriteStream stdio redirection --- packages/core/src/utils/daemon.test.ts | 24 +++++------------------- packages/core/src/utils/daemon.ts | 19 +++++++++++++------ 2 files changed, 18 insertions(+), 25 deletions(-) diff --git a/packages/core/src/utils/daemon.test.ts b/packages/core/src/utils/daemon.test.ts index 1a281435..4bfc6287 100644 --- a/packages/core/src/utils/daemon.test.ts +++ b/packages/core/src/utils/daemon.test.ts @@ -1,12 +1,5 @@ import { describe, expect, it, vi, beforeEach, afterEach, type MockInstance } from 'vitest' -import { - existsSync, - writeFileSync, - readFileSync, - rmSync, - mkdirSync, - createWriteStream, -} from 'node:fs' +import { existsSync, writeFileSync, readFileSync, rmSync, mkdirSync, openSync } from 'node:fs' import { join } from 'node:path' import { handleDaemonCommands } from './daemon' import { spawn } from 'node:child_process' @@ -33,19 +26,12 @@ vi.mock('node:child_process', () => { } }) -// Mock node:fs to mock createWriteStream for ESM safety +// Mock node:fs to mock openSync for ESM safety vi.mock('node:fs', async (importOriginal) => { const actual = await importOriginal() - const { Writable } = await import('node:stream') return { ...actual, - createWriteStream: vi.fn(() => { - return new Writable({ - write(_chunk: unknown, _encoding: string, callback: (error?: Error | null) => void) { - callback() - }, - }) - }), + openSync: vi.fn(() => 42), } }) @@ -68,7 +54,7 @@ describe('handleDaemonCommands', () => { mockKill = vi.spyOn(process, 'kill').mockImplementation(() => true) vi.mocked(spawn).mockClear() - vi.mocked(createWriteStream).mockClear() + vi.mocked(openSync).mockClear() }) afterEach(() => { @@ -105,7 +91,7 @@ describe('handleDaemonCommands', () => { expect(runFn).not.toHaveBeenCalled() expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM') expect(mockExit).toHaveBeenCalledWith(0) - expect(createWriteStream).not.toHaveBeenCalled() + expect(openSync).not.toHaveBeenCalled() }) it('daemonizes the process if -d is passed', async () => { diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts index c8d16865..25b08dd6 100644 --- a/packages/core/src/utils/daemon.ts +++ b/packages/core/src/utils/daemon.ts @@ -8,7 +8,7 @@ import { watch, statSync, createReadStream, - createWriteStream, + openSync, } from 'node:fs' import { join } from 'node:path' import { homedir } from 'node:os' @@ -97,7 +97,9 @@ function startDaemon(appName: string, pidFile: string, logFile: string): void { if (!isNaN(pid)) { try { process.kill(pid, 0) - console.error(`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`) + console.error( + `${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`, + ) process.exit(1) } catch { try { @@ -110,13 +112,13 @@ function startDaemon(appName: string, pidFile: string, logFile: string): void { } console.log(`Starting ${appName} in background...`) - const logStream = createWriteStream(logFile, { flags: 'a' }) + const logFd = openSync(logFile, 'a') const childArgs = process.argv.slice(1).filter((arg) => arg !== '-d' && arg !== 'restart') const child = spawn(process.argv[0], childArgs, { detached: true, - stdio: ['ignore', logStream, logStream], + stdio: ['ignore', logFd, logFd], env: { ...process.env, SHUMAI_DAEMONIZED: 'true', @@ -173,7 +175,10 @@ function viewLogs(appName: string, logFile: string): void { process.on('SIGTERM', cleanup) } -export async function handleDaemonCommands(appName: string, runFn: () => Promise): Promise { +export async function handleDaemonCommands( + appName: string, + runFn: () => Promise, +): Promise { const pidFile = join(PID_DIR, `${appName}.pid`) const logFile = join(LOG_DIR, `${appName}.log`) @@ -216,7 +221,9 @@ export async function handleDaemonCommands(appName: string, runFn: () => Promise if (!isNaN(pid)) { try { process.kill(pid, 0) - console.error(`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`) + console.error( + `${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`, + ) process.exit(1) } catch { // Process is dead, clean up PID file From c6527650d0e9fb7dadc6680dce4137432adf495a Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 12:53:14 +0800 Subject: [PATCH 4/9] fix(cli): bypass already running check if matching current process pid --- packages/core/src/utils/daemon.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts index 25b08dd6..02ac84a7 100644 --- a/packages/core/src/utils/daemon.ts +++ b/packages/core/src/utils/daemon.ts @@ -94,7 +94,7 @@ function startDaemon(appName: string, pidFile: string, logFile: string): void { // Check if already running if (existsSync(pidFile)) { const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) - if (!isNaN(pid)) { + if (!isNaN(pid) && pid !== process.pid) { try { process.kill(pid, 0) console.error( @@ -218,7 +218,7 @@ export async function handleDaemonCommands( // Normal Startup logic: check if already running if (existsSync(pidFile)) { const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) - if (!isNaN(pid)) { + if (!isNaN(pid) && pid !== process.pid) { try { process.kill(pid, 0) console.error( From 4bd5083ac1b7d9c32a07f73f4d5bc600ef87ea40 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 12:56:15 +0800 Subject: [PATCH 5/9] fix(cli): remove unused watch import in daemon utility --- packages/core/src/utils/daemon.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts index 02ac84a7..98458ca2 100644 --- a/packages/core/src/utils/daemon.ts +++ b/packages/core/src/utils/daemon.ts @@ -5,7 +5,6 @@ import { readFileSync, unlinkSync, mkdirSync, - watch, statSync, createReadStream, openSync, @@ -150,9 +149,9 @@ function viewLogs(appName: string, logFile: string): void { process.stdout.write(lastLines + '\n') let cursor = statSync(logFile).size - const watcher = watch(logFile, (event) => { - if (event === 'change') { - try { + const interval = setInterval(() => { + try { + if (existsSync(logFile)) { const stats = statSync(logFile) if (stats.size > cursor) { const stream = createReadStream(logFile, { start: cursor, end: stats.size - 1 }) @@ -161,14 +160,14 @@ function viewLogs(appName: string, logFile: string): void { } else if (stats.size < cursor) { cursor = stats.size } - } catch { - // Ignore read errors } + } catch { + // Ignore read errors } - }) + }, 250) const cleanup = () => { - watcher.close() + clearInterval(interval) process.exit(0) } process.on('SIGINT', cleanup) From c8b1d521d80b59f8a393457e958238b70218fd8c Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 12:59:58 +0800 Subject: [PATCH 6/9] fix(cli): open log files in write mode to truncate on startup --- packages/core/src/utils/daemon.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts index 98458ca2..134e0f25 100644 --- a/packages/core/src/utils/daemon.ts +++ b/packages/core/src/utils/daemon.ts @@ -111,7 +111,7 @@ function startDaemon(appName: string, pidFile: string, logFile: string): void { } console.log(`Starting ${appName} in background...`) - const logFd = openSync(logFile, 'a') + const logFd = openSync(logFile, 'w') const childArgs = process.argv.slice(1).filter((arg) => arg !== '-d' && arg !== 'restart') From ca0c2ece75f3c11db77b7815af870a1cfc1335bb Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 13:02:06 +0800 Subject: [PATCH 7/9] fix(cli): handle EPERM signal errors in isProcessRunning helper --- packages/core/src/utils/daemon.ts | 37 ++++++++++++++++--------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts index 134e0f25..0fabb36d 100644 --- a/packages/core/src/utils/daemon.ts +++ b/packages/core/src/utils/daemon.ts @@ -16,6 +16,18 @@ const SHUMAI_DIR = join(homedir(), '.shumai') const PID_DIR = join(SHUMAI_DIR, 'pids') const LOG_DIR = join(SHUMAI_DIR, 'logs') +function isProcessRunning(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (err) { + if (err && typeof err === 'object' && 'code' in err && err.code === 'EPERM') { + return true + } + return false + } +} + async function stopProcess(appName: string, pidFile: string): Promise { if (!existsSync(pidFile)) { console.log(`No running instance of ${appName} found.`) @@ -33,14 +45,7 @@ async function stopProcess(appName: string, pidFile: string): Promise { return false } - let isRunning = false - try { - process.kill(pid, 0) - isRunning = true - } catch { - // Not running - } - + let isRunning = isProcessRunning(pid) if (!isRunning) { console.log(`Process ${pid} is not running. Cleaning up PID file.`) try { @@ -61,13 +66,11 @@ async function stopProcess(appName: string, pidFile: string): Promise { // Wait for it to stop for (let i = 0; i < 30; i++) { - try { - process.kill(pid, 0) - await new Promise((resolve) => setTimeout(resolve, 100)) - } catch { + if (!isProcessRunning(pid)) { isRunning = false break } + await new Promise((resolve) => setTimeout(resolve, 100)) } if (isRunning) { @@ -94,13 +97,12 @@ function startDaemon(appName: string, pidFile: string, logFile: string): void { if (existsSync(pidFile)) { const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) if (!isNaN(pid) && pid !== process.pid) { - try { - process.kill(pid, 0) + if (isProcessRunning(pid)) { console.error( `${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`, ) process.exit(1) - } catch { + } else { try { unlinkSync(pidFile) } catch { @@ -218,13 +220,12 @@ export async function handleDaemonCommands( if (existsSync(pidFile)) { const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) if (!isNaN(pid) && pid !== process.pid) { - try { - process.kill(pid, 0) + if (isProcessRunning(pid)) { console.error( `${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`, ) process.exit(1) - } catch { + } else { // Process is dead, clean up PID file try { unlinkSync(pidFile) From b5ff76960f00977dc880988b5c82306b85cae1e2 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 13:05:50 +0800 Subject: [PATCH 8/9] fix(cli): defer PID file cleanup to process exit event for graceful shutdowns --- packages/core/src/utils/daemon.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts index 0fabb36d..e4b3e360 100644 --- a/packages/core/src/utils/daemon.ts +++ b/packages/core/src/utils/daemon.ts @@ -256,7 +256,6 @@ export async function handleDaemonCommands( process.on('exit', cleanPidFile) const handleSignal = (signal: string) => { - cleanPidFile() if (process.listenerCount(signal) === 1) { process.exit(0) } From efa0e75a065e90ed1c006f5e6be7fbeab0e8bce4 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 20 Jun 2026 14:39:43 +0800 Subject: [PATCH 9/9] fix(release): bundle zod for shumai webapp and keep it external for workers --- scripts/build-npm.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/scripts/build-npm.ts b/scripts/build-npm.ts index a9ecf3bf..467d663d 100644 --- a/scripts/build-npm.ts +++ b/scripts/build-npm.ts @@ -165,6 +165,7 @@ async function buildPlatformPackages( entrypoint: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any plugins: any[] = [], + external?: string[], ) { for (const target of targets) { const dirName = `${appName}-${target.platform}-${target.arch}` @@ -180,6 +181,7 @@ async function buildPlatformPackages( binaryName, bunTarget: target.bunTarget, plugins, + external, }) // Generate package.json for platform-specific package @@ -209,6 +211,7 @@ async function buildMainPackage({ entrypoint, plugins = [], extraDependencies = {}, + external = commonExternal, }: { appName: string description: string @@ -217,6 +220,7 @@ async function buildMainPackage({ // eslint-disable-next-line @typescript-eslint/no-explicit-any plugins?: any[] extraDependencies?: Record + external?: string[] }) { console.log(`\nšŸ“„ Packaging wrapper app ${appName}...`) const mainOutDir = path.join(distDir, appName) @@ -235,7 +239,7 @@ async function buildMainPackage({ minify: true, naming: `${appName}-app.[ext]`, plugins, - external: commonExternal, + external, define: { 'process.env.NODE_ENV': JSON.stringify('production'), }, @@ -489,13 +493,15 @@ const shumaiPlugins = [ }), tailwindPlugin, ] -await buildPlatformPackages('shumai', dummyRunnerPath) +const shumaiExternal = commonExternal.filter((dep) => dep !== 'zod') +await buildPlatformPackages('shumai', dummyRunnerPath, shumaiPlugins, shumaiExternal) await buildMainPackage({ appName: 'shumai', description: 'A fullstack AI-powered media workspace and workflow engine', hasPrisma: true, entrypoint: './apps/web/src/index.ts', plugins: shumaiPlugins, + external: shumaiExternal, }) // 3. Build shumai-agent (Agent app & platform binaries)