@pixelbyte-software/pixcode 1.35.2 → 1.35.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-D1-AIL_5.js → index-D8z78r_D.js} +57 -57
  11. package/dist/assets/{index-B8w57E1r.css → index-DmchzORZ.css} +1 -1
  12. package/dist/clear-cache.html +85 -85
  13. package/dist/convert-icons.md +52 -52
  14. package/dist/favicon.svg +8 -8
  15. package/dist/generate-icons.js +48 -48
  16. package/dist/icons/codex-white.svg +3 -3
  17. package/dist/icons/codex.svg +3 -3
  18. package/dist/icons/cursor-white.svg +11 -11
  19. package/dist/icons/icon-128x128.svg +9 -9
  20. package/dist/icons/icon-144x144.svg +9 -9
  21. package/dist/icons/icon-152x152.svg +9 -9
  22. package/dist/icons/icon-192x192.svg +9 -9
  23. package/dist/icons/icon-384x384.svg +9 -9
  24. package/dist/icons/icon-512x512.svg +9 -9
  25. package/dist/icons/icon-72x72.svg +9 -9
  26. package/dist/icons/icon-96x96.svg +9 -9
  27. package/dist/icons/icon-template.svg +9 -9
  28. package/dist/icons/qwen-logo.svg +14 -14
  29. package/dist/index.html +59 -59
  30. package/dist/logo.svg +12 -12
  31. package/dist/manifest.json +60 -60
  32. package/dist/openapi.yaml +1693 -1693
  33. package/dist/sw.js +124 -124
  34. package/dist-server/server/cli.js +96 -96
  35. package/dist-server/server/daemon/manager.js +33 -33
  36. package/dist-server/server/daemon-manager.js +64 -64
  37. package/dist-server/server/routes/commands.js +25 -25
  38. package/dist-server/server/routes/git.js +17 -17
  39. package/dist-server/server/routes/taskmaster.js +419 -419
  40. package/package.json +180 -180
  41. package/scripts/fix-node-pty.js +67 -67
  42. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  43. package/scripts/smoke/orchestration-api.mjs +172 -172
  44. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  45. package/server/claude-sdk.js +898 -898
  46. package/server/cli.js +935 -935
  47. package/server/constants/config.js +4 -4
  48. package/server/cursor-cli.js +342 -342
  49. package/server/daemon/manager.js +564 -564
  50. package/server/daemon-manager.js +959 -959
  51. package/server/database/db.js +794 -794
  52. package/server/database/json-store.js +197 -197
  53. package/server/gemini-cli.js +535 -535
  54. package/server/gemini-response-handler.js +79 -79
  55. package/server/index.js +3135 -3135
  56. package/server/load-env.js +34 -34
  57. package/server/middleware/auth.js +173 -173
  58. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  59. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  60. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  61. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  62. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  63. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  64. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  65. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  66. package/server/modules/orchestration/a2a/routes.ts +577 -577
  67. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  68. package/server/modules/orchestration/a2a/types.ts +125 -125
  69. package/server/modules/orchestration/a2a/validator.ts +113 -113
  70. package/server/modules/orchestration/index.ts +66 -66
  71. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  72. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  73. package/server/modules/orchestration/preview/types.ts +19 -19
  74. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  75. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  76. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  77. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  78. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  79. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  80. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  81. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  82. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  83. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  84. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  85. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  86. package/server/modules/orchestration/workspace/types.ts +52 -52
  87. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  88. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  89. package/server/modules/providers/index.ts +2 -2
  90. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  91. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  92. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  93. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  94. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  95. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  96. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  97. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  98. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  99. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  100. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  101. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  102. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  103. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  104. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  105. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  106. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  107. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  108. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  109. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  110. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  111. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  112. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  113. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  114. package/server/modules/providers/provider.registry.ts +40 -40
  115. package/server/modules/providers/provider.routes.ts +819 -819
  116. package/server/modules/providers/services/mcp.service.ts +86 -86
  117. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  118. package/server/modules/providers/services/sessions.service.ts +45 -45
  119. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  120. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  121. package/server/modules/providers/shared/provider-configs.ts +142 -142
  122. package/server/modules/providers/tests/mcp.test.ts +293 -293
  123. package/server/openai-codex.js +462 -462
  124. package/server/opencode-cli.js +459 -459
  125. package/server/opencode-response-handler.js +107 -107
  126. package/server/projects.js +3105 -3105
  127. package/server/qwen-code-cli.js +395 -395
  128. package/server/qwen-response-handler.js +73 -73
  129. package/server/routes/agent.js +1365 -1365
  130. package/server/routes/auth.js +138 -138
  131. package/server/routes/codex.js +19 -19
  132. package/server/routes/commands.js +554 -554
  133. package/server/routes/cursor.js +52 -52
  134. package/server/routes/gemini.js +24 -24
  135. package/server/routes/git.js +1488 -1488
  136. package/server/routes/mcp-utils.js +31 -31
  137. package/server/routes/messages.js +61 -61
  138. package/server/routes/network.js +120 -120
  139. package/server/routes/plugins.js +318 -318
  140. package/server/routes/projects.js +915 -915
  141. package/server/routes/qwen.js +27 -27
  142. package/server/routes/settings.js +286 -286
  143. package/server/routes/taskmaster.js +1496 -1496
  144. package/server/routes/telegram.js +125 -125
  145. package/server/routes/user.js +123 -123
  146. package/server/services/external-access.js +171 -171
  147. package/server/services/install-jobs.js +571 -571
  148. package/server/services/notification-orchestrator.js +242 -242
  149. package/server/services/provider-credentials.js +189 -189
  150. package/server/services/provider-models.js +381 -381
  151. package/server/services/telegram/bot.js +279 -279
  152. package/server/services/telegram/telegram-http-client.js +130 -130
  153. package/server/services/telegram/translations.js +170 -170
  154. package/server/services/vapid-keys.js +36 -36
  155. package/server/sessionManager.js +225 -225
  156. package/server/shared/interfaces.ts +54 -54
  157. package/server/shared/types.ts +172 -172
  158. package/server/shared/utils.ts +193 -193
  159. package/server/tsconfig.json +36 -36
  160. package/server/utils/colors.js +21 -21
  161. package/server/utils/commandParser.js +303 -303
  162. package/server/utils/frontmatter.js +18 -18
  163. package/server/utils/gitConfig.js +34 -34
  164. package/server/utils/mcp-detector.js +147 -147
  165. package/server/utils/plugin-loader.js +457 -457
  166. package/server/utils/plugin-process-manager.js +184 -184
  167. package/server/utils/port-access.js +209 -209
  168. package/server/utils/runtime-paths.js +37 -37
  169. package/server/utils/taskmaster-websocket.js +128 -128
  170. package/server/utils/url-detection.js +71 -71
  171. package/server/vite-daemon.js +78 -78
  172. package/shared/modelConstants.js +162 -162
  173. package/shared/networkHosts.js +22 -22
@@ -1,959 +1,959 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import os from 'os';
4
- import { spawnSync } from 'child_process';
5
- import { request } from 'node:http';
6
- import net from 'node:net';
7
-
8
- const DAEMON_SERVICE_NAME = 'pixcode.service';
9
- const FRONTEND_DAEMON_SERVICE_NAME = 'pixcode-frontend.service';
10
- const DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', DAEMON_SERVICE_NAME);
11
- const DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', DAEMON_SERVICE_NAME);
12
- const FRONTEND_DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', FRONTEND_DAEMON_SERVICE_NAME);
13
- const FRONTEND_DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', FRONTEND_DAEMON_SERVICE_NAME);
14
- const DEFAULT_FRONTEND_PORT = 5173;
15
- const DAEMON_HEALTH_TIMEOUT_MS = 60000;
16
- const DAEMON_HEALTH_REQUEST_TIMEOUT_MS = 4000;
17
- const DAEMON_HEALTH_RETRY_INTERVAL_MS = 1000;
18
-
19
- const DAEMON_SUBCOMMANDS = new Set([
20
- 'install',
21
- 'start',
22
- 'stop',
23
- 'restart',
24
- 'status',
25
- 'logs',
26
- 'enable',
27
- 'disable',
28
- 'uninstall',
29
- 'doctor',
30
- 'help',
31
- ]);
32
-
33
- const DAEMON_MODES = new Set(['auto', 'user', 'system']);
34
- const SYSTEM_MUTATING_DAEMON_SUBCOMMANDS = new Set([
35
- 'install',
36
- 'start',
37
- 'stop',
38
- 'restart',
39
- 'enable',
40
- 'disable',
41
- 'uninstall',
42
- 'logs',
43
- ]);
44
- let pixcodeBinaryAvailableCache = null;
45
-
46
- function passthroughColor(text) {
47
- return text;
48
- }
49
-
50
- function getColorHelpers(color) {
51
- if (color) {
52
- return color;
53
- }
54
- return {
55
- info: passthroughColor,
56
- ok: passthroughColor,
57
- warn: passthroughColor,
58
- error: passthroughColor,
59
- tip: passthroughColor,
60
- bright: passthroughColor,
61
- dim: passthroughColor,
62
- };
63
- }
64
-
65
- function runCommand(bin, args, opts = {}) {
66
- const stdio = opts.inherit ? 'inherit' : 'pipe';
67
- return spawnSync(bin, args, {
68
- encoding: 'utf8',
69
- stdio,
70
- });
71
- }
72
-
73
- function extractCommandError(result, fallbackMessage) {
74
- if (!result) return fallbackMessage;
75
- const fromError = result.error?.message?.trim();
76
- if (fromError) return fromError;
77
- const fromStd = (result.stderr || result.stdout || '').trim();
78
- if (fromStd) return fromStd;
79
- return fallbackMessage;
80
- }
81
-
82
- function isRootUser() {
83
- return typeof process.getuid === 'function' && process.getuid() === 0;
84
- }
85
-
86
- function quoteShellArg(arg) {
87
- const value = String(arg);
88
- if (/^[A-Za-z0-9_./:=+-]+$/.test(value)) {
89
- return value;
90
- }
91
- return `'${value.replace(/'/g, `'\\''`)}'`;
92
- }
93
-
94
- function quoteSystemdArg(arg) {
95
- return `"${String(arg).replace(/(["\\$`])/g, '\\$1')}"`;
96
- }
97
-
98
- function resolveDaemonCliEntryPath(context = {}) {
99
- const appRoot = context.appRoot || process.cwd();
100
- const explicitCliEntry = context.cliEntry ? path.resolve(context.cliEntry) : null;
101
- const argvCliEntry = process.argv[1] ? path.resolve(process.argv[1]) : null;
102
- const candidatePaths = [
103
- explicitCliEntry,
104
- argvCliEntry,
105
- path.join(appRoot, 'dist-server', 'server', 'cli.js'),
106
- path.join(appRoot, 'server', 'cli.js'),
107
- ].filter(Boolean);
108
-
109
- const existingPath = candidatePaths.find(candidate => fs.existsSync(candidate));
110
- if (existingPath) {
111
- return existingPath;
112
- }
113
-
114
- return explicitCliEntry || argvCliEntry || path.join(appRoot, 'server', 'cli.js');
115
- }
116
-
117
- function hasPixcodeBinary() {
118
- if (pixcodeBinaryAvailableCache !== null) {
119
- return pixcodeBinaryAvailableCache;
120
- }
121
-
122
- const probe = runCommand('pixcode', ['--version']);
123
- pixcodeBinaryAvailableCache = probe.status === 0;
124
- return pixcodeBinaryAvailableCache;
125
- }
126
-
127
- function getDaemonCommandPrefix(context = {}, { forceLocal = false } = {}) {
128
- if (!forceLocal && hasPixcodeBinary()) {
129
- return 'pixcode';
130
- }
131
-
132
- const nodeExec = context.nodeExecPath || process.execPath || 'node';
133
- const cliEntry = resolveDaemonCliEntryPath(context);
134
- return `${quoteShellArg(nodeExec)} ${quoteShellArg(cliEntry)}`;
135
- }
136
-
137
- export function buildDaemonCliCommand({ subcommand, mode = 'system', extraArgs = [] }, context = {}) {
138
- const normalizedSubcommand = String(subcommand || 'status').trim() || 'status';
139
- const normalizedMode = String(mode || 'system').trim() || 'system';
140
- const args = ['daemon', normalizedSubcommand, '--mode', normalizedMode, ...extraArgs.map(value => String(value))];
141
- const needsSudo =
142
- normalizedMode === 'system' &&
143
- SYSTEM_MUTATING_DAEMON_SUBCOMMANDS.has(normalizedSubcommand) &&
144
- !isRootUser();
145
- const prefix = getDaemonCommandPrefix(context, { forceLocal: needsSudo });
146
- const command = `${prefix} ${args.map(quoteShellArg).join(' ')}`;
147
- return needsSudo ? `sudo ${command}` : command;
148
- }
149
-
150
- function getDaemonServicePath(mode) {
151
- return mode === 'system' ? DAEMON_SYSTEM_SERVICE_PATH : DAEMON_USER_SERVICE_PATH;
152
- }
153
-
154
- function getFrontendServicePath(mode) {
155
- return mode === 'system' ? FRONTEND_DAEMON_SYSTEM_SERVICE_PATH : FRONTEND_DAEMON_USER_SERVICE_PATH;
156
- }
157
-
158
- function getSystemctlArgs(mode, commandArgs) {
159
- return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
160
- }
161
-
162
- function getJournalctlArgs(mode, commandArgs) {
163
- return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
164
- }
165
-
166
- function parseDaemonArgs(args) {
167
- const parsed = {
168
- subcommand: 'status',
169
- options: {
170
- mode: 'system',
171
- },
172
- };
173
-
174
- let i = 0;
175
- if (args[0] && DAEMON_SUBCOMMANDS.has(args[0])) {
176
- parsed.subcommand = args[0];
177
- i = 1;
178
- }
179
-
180
- for (; i < args.length; i++) {
181
- const arg = args[i];
182
- if (arg === '--port' || arg === '-p') {
183
- parsed.options.serverPort = args[++i];
184
- } else if (arg.startsWith('--port=')) {
185
- parsed.options.serverPort = arg.split('=')[1];
186
- } else if (arg === '--frontend-port') {
187
- parsed.options.frontendPort = args[++i];
188
- } else if (arg.startsWith('--frontend-port=')) {
189
- parsed.options.frontendPort = arg.split('=')[1];
190
- } else if (arg === '--no-frontend' || arg === '--single-port') {
191
- parsed.options.noFrontend = true;
192
- } else if (arg === '--mode' || arg === '-m') {
193
- parsed.options.mode = (args[++i] || '').toLowerCase();
194
- } else if (arg.startsWith('--mode=')) {
195
- parsed.options.mode = (arg.split('=')[1] || '').toLowerCase();
196
- } else if (arg === '--database-path') {
197
- parsed.options.databasePath = args[++i];
198
- } else if (arg.startsWith('--database-path=')) {
199
- parsed.options.databasePath = arg.split('=')[1];
200
- } else if (arg === '--help' || arg === '-h') {
201
- parsed.subcommand = 'help';
202
- } else {
203
- parsed.options.extraArgs = parsed.options.extraArgs || [];
204
- parsed.options.extraArgs.push(arg);
205
- }
206
- }
207
-
208
- return parsed;
209
- }
210
-
211
- function buildDaemonExecStart({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
212
- const nodeExec = nodeExecPath || process.execPath || 'node';
213
- const cliCandidate = cliEntry
214
- ? path.resolve(cliEntry)
215
- : (process.argv[1] ? path.resolve(process.argv[1]) : path.join(appRoot, 'dist-server', 'server', 'cli.js'));
216
- const resolvedCliEntry = fs.existsSync(cliCandidate)
217
- ? cliCandidate
218
- : path.join(appRoot, 'dist-server', 'server', 'cli.js');
219
-
220
- const args = [nodeExec, resolvedCliEntry, 'start', '--port', String(serverPort)];
221
- if (databasePath) {
222
- args.push('--database-path', databasePath);
223
- }
224
-
225
- return args.map(quoteSystemdArg).join(' ');
226
- }
227
-
228
- function buildDaemonServiceUnit({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
229
- const execStart = buildDaemonExecStart({
230
- appRoot,
231
- serverPort,
232
- databasePath,
233
- nodeExecPath,
234
- cliEntry,
235
- });
236
- return `[Unit]
237
- Description=Pixcode Server
238
- After=network.target
239
-
240
- [Service]
241
- Type=simple
242
- WorkingDirectory=${appRoot}
243
- ExecStart=${execStart}
244
- Environment=HOST=0.0.0.0
245
- Environment=CI=true
246
- Environment=PIXCODE_DAEMON_MANAGED=1
247
- Restart=always
248
- RestartSec=2
249
-
250
- [Install]
251
- WantedBy=default.target
252
- `;
253
- }
254
-
255
- function resolveFrontendDaemonEntry(appRoot, cliEntry) {
256
- const cliCandidate = cliEntry
257
- ? path.resolve(cliEntry)
258
- : (process.argv[1] ? path.resolve(process.argv[1]) : '');
259
- const candidates = [];
260
- if (cliCandidate) {
261
- candidates.push(path.join(path.dirname(cliCandidate), 'vite-daemon.js'));
262
- }
263
- candidates.push(path.join(appRoot, 'dist-server', 'server', 'vite-daemon.js'));
264
- candidates.push(path.join(appRoot, 'server', 'vite-daemon.js'));
265
-
266
- const resolved = candidates.find(candidate => fs.existsSync(candidate));
267
- if (!resolved) {
268
- throw new Error(
269
- `Frontend daemon entry was not found. Checked: ${candidates.join(', ')}. ` +
270
- `Run "npm run build:server" or ensure server/vite-daemon.js exists.`
271
- );
272
- }
273
- return resolved;
274
- }
275
-
276
- function buildFrontendDaemonExecStart({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
277
- const nodeExec = nodeExecPath || process.execPath || 'node';
278
- const frontendEntry = resolveFrontendDaemonEntry(appRoot, cliEntry);
279
- const args = [
280
- nodeExec,
281
- frontendEntry,
282
- '--host',
283
- '0.0.0.0',
284
- '--port',
285
- String(frontendPort),
286
- '--strictPort',
287
- ];
288
- return args.map(quoteSystemdArg).join(' ');
289
- }
290
-
291
- function buildFrontendDaemonServiceUnit({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
292
- const execStart = buildFrontendDaemonExecStart({
293
- appRoot,
294
- frontendPort,
295
- nodeExecPath,
296
- cliEntry,
297
- });
298
- return `[Unit]
299
- Description=Pixcode Frontend (Vite Dev Server)
300
- After=network.target
301
-
302
- [Service]
303
- Type=simple
304
- WorkingDirectory=${appRoot}
305
- ExecStart=${execStart}
306
- Environment=HOST=0.0.0.0
307
- Environment=CI=true
308
- Environment=PIXCODE_DAEMON_MANAGED=1
309
- Restart=always
310
- RestartSec=2
311
-
312
- [Install]
313
- WantedBy=default.target
314
- `;
315
- }
316
-
317
- function normalizeState(value) {
318
- const text = (value || '').trim();
319
- if (!text) return 'unknown';
320
- if (/No such file or directory/i.test(text)) return 'not-found';
321
- return text;
322
- }
323
-
324
- function getServiceState(mode, serviceName) {
325
- const activeRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-active', serviceName]));
326
- const enabledRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-enabled', serviceName]));
327
-
328
- return {
329
- active: normalizeState(activeRes.stdout || activeRes.stderr),
330
- enabled: normalizeState(enabledRes.stdout || enabledRes.stderr),
331
- };
332
- }
333
-
334
- function readLogs(mode, lines = 100, inherit = false, serviceNames = [DAEMON_SERVICE_NAME]) {
335
- const unitArgs = serviceNames.flatMap((serviceName) => ['-u', serviceName]);
336
- const args = [...getJournalctlArgs(mode, unitArgs), '-n', String(lines), '--no-pager'];
337
- return runCommand('journalctl', args, { inherit });
338
- }
339
-
340
- function getPortFromServiceUnit(servicePath) {
341
- if (!fs.existsSync(servicePath)) return null;
342
- try {
343
- const content = fs.readFileSync(servicePath, 'utf8');
344
- const quoted = content.match(/"--port"\s+"(\d+)"/);
345
- if (quoted) return Number(quoted[1]);
346
- const plain = content.match(/--port(?:\s+|=)(\d+)/);
347
- if (plain) return Number(plain[1]);
348
- } catch {
349
- // Ignore parse errors and use fallback port.
350
- }
351
- return null;
352
- }
353
-
354
- function findLatestErrorLine(logText) {
355
- if (!logText) return '';
356
- const lines = logText.split('\n').map(line => line.trim()).filter(Boolean);
357
- const errorLine = [...lines].reverse().find(line => /(error|failed|exception|denied|cannot|traceback)/i.test(line));
358
- return errorLine || '';
359
- }
360
-
361
- function probeUserBus() {
362
- const result = runCommand('systemctl', ['--user', 'show-environment']);
363
- return {
364
- ok: result.status === 0,
365
- detail: extractCommandError(result, 'systemd user bus is not reachable'),
366
- };
367
- }
368
-
369
- function probeLinger() {
370
- const result = runCommand('loginctl', ['show-user', os.userInfo().username, '-p', 'Linger']);
371
- if (result.status !== 0) {
372
- return {
373
- value: 'unknown',
374
- detail: extractCommandError(result, 'Could not read linger status'),
375
- };
376
- }
377
- const output = (result.stdout || '').trim();
378
- const value = output.includes('=') ? output.split('=')[1].trim().toLowerCase() : output.toLowerCase();
379
- return {
380
- value: value || 'unknown',
381
- detail: '',
382
- };
383
- }
384
-
385
- function resolveDaemonMode({ requestedMode, subcommand, userBusAvailable }) {
386
- if (requestedMode !== 'auto') {
387
- return requestedMode;
388
- }
389
-
390
- // Auto mode is intentionally system-first to guarantee boot-time startup
391
- // even without an interactive user session.
392
- const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
393
- const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
394
-
395
- if (systemUnitInstalled) return 'system';
396
- if (subcommand === 'install') return 'system';
397
- if (userUnitInstalled && userBusAvailable) return 'user';
398
- return 'system';
399
- }
400
-
401
- function runSystemctl(mode, commandArgs, opts = {}) {
402
- const result = runCommand('systemctl', getSystemctlArgs(mode, commandArgs), { inherit: opts.inherit });
403
- if (result.status !== 0 && !opts.allowFailure) {
404
- let errorText = extractCommandError(result, `systemctl ${commandArgs.join(' ')} failed`);
405
- if (mode === 'system' && /(access denied|permission denied|must be root|interactive authentication required|not permitted)/i.test(errorText)) {
406
- errorText += '\nTry rerunning this daemon operation with elevated privileges (sudo).';
407
- }
408
- throw new Error(errorText);
409
- }
410
- return result;
411
- }
412
-
413
- async function sleep(ms) {
414
- await new Promise(resolve => setTimeout(resolve, ms));
415
- }
416
-
417
- async function isPortReachable(port, timeoutMs = 1000) {
418
- return await new Promise(resolve => {
419
- const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
420
- let settled = false;
421
- const done = (value) => {
422
- if (settled) return;
423
- settled = true;
424
- socket.destroy();
425
- resolve(value);
426
- };
427
- socket.setTimeout(timeoutMs);
428
- socket.once('connect', () => done(true));
429
- socket.once('timeout', () => done(false));
430
- socket.once('error', () => done(false));
431
- });
432
- }
433
-
434
- async function requestHealthOnce(port, timeoutMs = DAEMON_HEALTH_REQUEST_TIMEOUT_MS) {
435
- return await new Promise((resolve, reject) => {
436
- const req = request({
437
- host: '127.0.0.1',
438
- port: Number(port),
439
- method: 'GET',
440
- path: '/health',
441
- timeout: timeoutMs,
442
- }, (res) => {
443
- res.resume();
444
- resolve({ ok: true, statusCode: res.statusCode });
445
- });
446
-
447
- req.on('timeout', () => req.destroy(new Error(`Health check timed out after ${timeoutMs}ms`)));
448
- req.on('error', reject);
449
- req.end();
450
- });
451
- }
452
-
453
- async function waitForHealth(port, timeoutMs = DAEMON_HEALTH_TIMEOUT_MS) {
454
- const deadline = Date.now() + timeoutMs;
455
- let lastError = null;
456
- while (Date.now() < deadline) {
457
- try {
458
- return await requestHealthOnce(port);
459
- } catch (error) {
460
- lastError = error;
461
- if (await isPortReachable(port, 700)) {
462
- return { ok: true, statusCode: null, probe: 'tcp' };
463
- }
464
- await sleep(DAEMON_HEALTH_RETRY_INTERVAL_MS);
465
- }
466
- }
467
- throw new Error(lastError?.message || `Service did not become healthy on port ${port}`);
468
- }
469
-
470
- async function healthCheckOrThrow(mode, serviceName, port, c) {
471
- const state = getServiceState(mode, serviceName);
472
- if (state.active !== 'active' && state.active !== 'activating') {
473
- throw new Error(`Service ${serviceName} is not active (state: ${state.active})`);
474
- }
475
-
476
- try {
477
- const health = await waitForHealth(port);
478
- if (health.probe === 'tcp') {
479
- console.log(`${c.warn('[WARN]')} HTTP /health probe delayed; TCP port ${port} is already accepting connections.`);
480
- }
481
- } catch (healthError) {
482
- const logsResult = readLogs(mode, 50, false, [serviceName]);
483
- const logText = (logsResult.stdout || logsResult.stderr || '').trim();
484
- const lastErrorLine = findLatestErrorLine(logText);
485
-
486
- if (logText) {
487
- console.log(`\n${c.warn('[WARN]')} Last 50 log lines for ${serviceName}:`);
488
- console.log(logText);
489
- }
490
-
491
- if (lastErrorLine) {
492
- throw new Error(`Health check failed for ${serviceName}: ${healthError.message}\nLikely cause: ${lastErrorLine}`);
493
- }
494
- throw new Error(`Health check failed for ${serviceName}: ${healthError.message}`);
495
- }
496
- }
497
-
498
- function ensureLinux() {
499
- if (process.platform !== 'linux') {
500
- throw new Error('The daemon command is supported on Linux only.');
501
- }
502
- }
503
-
504
- function ensureSystemctl() {
505
- const probe = runCommand('systemctl', ['--version']);
506
- if (probe.status !== 0) {
507
- throw new Error(extractCommandError(probe, 'systemctl is not available in this environment'));
508
- }
509
- }
510
-
511
- function showDaemonHelp(c, context = {}) {
512
- const usagePrefix = getDaemonCommandPrefix(context);
513
- const installExample = buildDaemonCliCommand(
514
- {
515
- subcommand: 'install',
516
- mode: 'system',
517
- extraArgs: ['--port', '3001', '--single-port'],
518
- },
519
- context
520
- );
521
- const statusExample = buildDaemonCliCommand({ subcommand: 'status', mode: 'system' }, context);
522
- const doctorExample = buildDaemonCliCommand({ subcommand: 'doctor', mode: 'auto' }, context);
523
- const logsExample = buildDaemonCliCommand({ subcommand: 'logs', mode: 'system' }, context);
524
- console.log(`
525
- ${c.bright('Pixcode Daemon')} - Persistent Linux service manager
526
-
527
- Usage:
528
- ${usagePrefix} daemon [subcommand] [options]
529
-
530
- Subcommands:
531
- ${c.bright('install')} Install/update unit, reload daemon, enable and start now
532
- ${c.bright('start')} Start the service
533
- ${c.bright('stop')} Stop the service (temporary; auto-start remains enabled)
534
- ${c.bright('restart')} Restart the service
535
- ${c.bright('status')} Show active/enabled state
536
- ${c.bright('logs')} Show recent service logs
537
- ${c.bright('enable')} Enable auto-start at boot
538
- ${c.bright('disable')} Disable auto-start at boot
539
- ${c.bright('uninstall')} Stop, disable, and remove the service unit
540
- ${c.bright('doctor')} Run diagnostics (bus, linger, units, state, port, logs)
541
- ${c.bright('help')} Show this help
542
-
543
- Options:
544
- -p, --port <port> Set service server port (default: 3001)
545
- --frontend-port <port> Start a separate frontend Vite service on this port (legacy/dev)
546
- --single-port, --no-frontend
547
- Serve the built UI from the backend port only (default)
548
- -m, --mode <mode> Service mode: user | system | auto (default: system)
549
- --database-path <path> Set service database path
550
-
551
- Examples:
552
- $ ${installExample}
553
- $ ${statusExample}
554
- $ ${doctorExample}
555
- $ ${logsExample}
556
- `);
557
- }
558
-
559
- export function hasInstalledDaemonUnit() {
560
- return (
561
- fs.existsSync(DAEMON_USER_SERVICE_PATH) ||
562
- fs.existsSync(DAEMON_SYSTEM_SERVICE_PATH) ||
563
- fs.existsSync(FRONTEND_DAEMON_USER_SERVICE_PATH) ||
564
- fs.existsSync(FRONTEND_DAEMON_SYSTEM_SERVICE_PATH)
565
- );
566
- }
567
-
568
- export async function handleDaemonCommand(args, context = {}) {
569
- const c = getColorHelpers(context.color);
570
- const parsed = parseDaemonArgs(args);
571
- const appRoot = context.appRoot || process.cwd();
572
- const daemonCommandContext = {
573
- appRoot,
574
- cliEntry: context.cliEntry,
575
- nodeExecPath: context.nodeExecPath,
576
- };
577
-
578
- if (parsed.options.extraArgs?.length) {
579
- showDaemonHelp(c, daemonCommandContext);
580
- throw new Error(`Unknown daemon arguments: ${parsed.options.extraArgs.join(' ')}`);
581
- }
582
-
583
- if (parsed.subcommand === 'help') {
584
- showDaemonHelp(c, daemonCommandContext);
585
- return;
586
- }
587
-
588
- if (!DAEMON_MODES.has(parsed.options.mode)) {
589
- throw new Error(`Invalid daemon mode "${parsed.options.mode}". Use one of: auto, user, system.`);
590
- }
591
-
592
- ensureLinux();
593
- ensureSystemctl();
594
-
595
- const defaultPort = context.defaultPort || process.env.SERVER_PORT || process.env.PORT || '3001';
596
- const defaultFrontendPort = context.defaultFrontendPort || process.env.VITE_PORT || String(DEFAULT_FRONTEND_PORT);
597
- const configuredPort = parsed.options.serverPort || defaultPort;
598
- const configuredFrontendPort = parsed.options.frontendPort || defaultFrontendPort;
599
- const frontendEnabled = parsed.options.noFrontend !== true &&
600
- (Boolean(parsed.options.frontendPort) || process.env.PIXCODE_SEPARATE_FRONTEND === '1');
601
- const databasePath = parsed.options.databasePath || process.env.DATABASE_PATH || '';
602
-
603
- const portNum = Number(configuredPort);
604
- if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
605
- throw new Error(`Invalid port "${configuredPort}". Expected an integer between 1 and 65535.`);
606
- }
607
- const frontendPortNum = Number(configuredFrontendPort);
608
- if (frontendEnabled && (!Number.isInteger(frontendPortNum) || frontendPortNum < 1 || frontendPortNum > 65535)) {
609
- throw new Error(`Invalid frontend port "${configuredFrontendPort}". Expected an integer between 1 and 65535.`);
610
- }
611
-
612
- const userBus = probeUserBus();
613
- const mode = resolveDaemonMode({
614
- requestedMode: parsed.options.mode,
615
- subcommand: parsed.subcommand,
616
- userBusAvailable: userBus.ok,
617
- });
618
- const servicePath = getDaemonServicePath(mode);
619
- const frontendServicePath = getFrontendServicePath(mode);
620
- const effectivePort = getPortFromServiceUnit(servicePath) || portNum;
621
- const effectiveFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
622
-
623
- if (mode === 'user' && !userBus.ok) {
624
- const installSystemCommand = buildDaemonCliCommand(
625
- { subcommand: 'install', mode: 'system' },
626
- daemonCommandContext
627
- );
628
- throw new Error(
629
- `Could not connect to your systemd user session.\n${userBus.detail}\n` +
630
- `Try ${c.bright(installSystemCommand)} or enable user linger: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`
631
- );
632
- }
633
-
634
- if (parsed.subcommand === 'doctor') {
635
- const linger = probeLinger();
636
- const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
637
- const userFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('user'));
638
- const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
639
- const systemFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('system'));
640
- const selectedModePort = getPortFromServiceUnit(servicePath) || portNum;
641
- const selectedModeFrontendPort = frontendEnabled
642
- ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
643
- : undefined;
644
- const portReachable = await isPortReachable(selectedModePort);
645
- const frontendPortReachable = selectedModeFrontendPort
646
- ? await isPortReachable(selectedModeFrontendPort)
647
- : false;
648
- const userState = userBus.ok
649
- ? {
650
- backend: getServiceState('user', DAEMON_SERVICE_NAME),
651
- frontend: getServiceState('user', FRONTEND_DAEMON_SERVICE_NAME),
652
- }
653
- : {
654
- backend: { active: 'unavailable', enabled: 'unavailable' },
655
- frontend: { active: 'unavailable', enabled: 'unavailable' },
656
- };
657
- const systemState = {
658
- backend: getServiceState('system', DAEMON_SERVICE_NAME),
659
- frontend: getServiceState('system', FRONTEND_DAEMON_SERVICE_NAME),
660
- };
661
- const logsResult = readLogs(mode, 50, false, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
662
- const logsText = (logsResult.stdout || logsResult.stderr || '').trim();
663
- const lastErrorLine = findLatestErrorLine(logsText);
664
-
665
- console.log(`\n${c.bright('Pixcode Daemon Doctor')}\n`);
666
- console.log(`${c.info('[INFO]')} Requested mode: ${c.bright(parsed.options.mode)}`);
667
- console.log(`${c.info('[INFO]')} Resolved mode: ${c.bright(mode)}`);
668
- console.log(`${c.info('[INFO]')} user-bus: ${userBus.ok ? c.ok('ok') : c.warn('unavailable')}`);
669
- if (!userBus.ok) {
670
- console.log(` ${c.dim(userBus.detail)}`);
671
- }
672
- console.log(`${c.info('[INFO]')} linger: ${c.bright(linger.value)}${linger.detail ? ` ${c.dim(`(${linger.detail})`)}` : ''}`);
673
- console.log(`${c.info('[INFO]')} user backend: ${userUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('user'))})`);
674
- console.log(`${c.info('[INFO]')} user frontend: ${userFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('user'))})`);
675
- console.log(`${c.info('[INFO]')} system backend: ${systemUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('system'))})`);
676
- console.log(`${c.info('[INFO]')} system frontend:${systemFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('system'))})`);
677
- console.log(`${c.info('[INFO]')} user state: backend active=${c.bright(userState.backend.active)} enabled=${c.bright(userState.backend.enabled)} | frontend active=${c.bright(userState.frontend.active)} enabled=${c.bright(userState.frontend.enabled)}`);
678
- console.log(`${c.info('[INFO]')} system state: backend active=${c.bright(systemState.backend.active)} enabled=${c.bright(systemState.backend.enabled)} | frontend active=${c.bright(systemState.frontend.active)} enabled=${c.bright(systemState.frontend.enabled)}`);
679
- console.log(`${c.info('[INFO]')} backend port: ${c.bright(String(selectedModePort))} (${portReachable ? c.ok('reachable') : c.warn('not reachable')})`);
680
- console.log(`${c.info('[INFO]')} frontend mode: ${frontendEnabled ? c.bright('separate Vite service') : c.bright('single backend port')}`);
681
- if (frontendEnabled) {
682
- console.log(`${c.info('[INFO]')} frontend port: ${c.bright(String(selectedModeFrontendPort))} (${frontendPortReachable ? c.ok('reachable') : c.warn('not reachable')})`);
683
- }
684
- if (lastErrorLine) {
685
- console.log(`${c.warn('[WARN]')} Latest error: ${lastErrorLine}`);
686
- }
687
-
688
- console.log(`\n${c.bright('Machine Readable')}`);
689
- console.log(`MODE_REQUESTED=${parsed.options.mode}`);
690
- console.log(`MODE_RESOLVED=${mode}`);
691
- console.log(`USER_BUS_OK=${userBus.ok}`);
692
- console.log(`LINGER=${linger.value}`);
693
- console.log(`USER_BACKEND_UNIT_INSTALLED=${userUnitInstalled}`);
694
- console.log(`USER_FRONTEND_UNIT_INSTALLED=${userFrontendUnitInstalled}`);
695
- console.log(`SYSTEM_BACKEND_UNIT_INSTALLED=${systemUnitInstalled}`);
696
- console.log(`SYSTEM_FRONTEND_UNIT_INSTALLED=${systemFrontendUnitInstalled}`);
697
- console.log(`USER_BACKEND_ACTIVE=${userState.backend.active}`);
698
- console.log(`USER_BACKEND_ENABLED=${userState.backend.enabled}`);
699
- console.log(`USER_FRONTEND_ACTIVE=${userState.frontend.active}`);
700
- console.log(`USER_FRONTEND_ENABLED=${userState.frontend.enabled}`);
701
- console.log(`SYSTEM_BACKEND_ACTIVE=${systemState.backend.active}`);
702
- console.log(`SYSTEM_BACKEND_ENABLED=${systemState.backend.enabled}`);
703
- console.log(`SYSTEM_FRONTEND_ACTIVE=${systemState.frontend.active}`);
704
- console.log(`SYSTEM_FRONTEND_ENABLED=${systemState.frontend.enabled}`);
705
- console.log(`BACKEND_PORT=${selectedModePort}`);
706
- console.log(`BACKEND_PORT_REACHABLE=${portReachable}`);
707
- console.log(`FRONTEND_ENABLED=${frontendEnabled}`);
708
- console.log(`FRONTEND_PORT=${selectedModeFrontendPort ?? ''}`);
709
- console.log(`FRONTEND_PORT_REACHABLE=${frontendPortReachable}`);
710
- console.log(`LAST_ERROR_LINE=${JSON.stringify(lastErrorLine || '')}\n`);
711
- return;
712
- }
713
-
714
- const serviceDefs = [{ servicePath }];
715
- if (frontendEnabled) {
716
- serviceDefs.push({ servicePath: frontendServicePath });
717
- }
718
-
719
- switch (parsed.subcommand) {
720
- case 'install': {
721
- if (parsed.options.mode === 'auto' && mode === 'system' && !userBus.ok) {
722
- console.log(`${c.warn('[WARN]')} User mode is unavailable; auto mode is falling back to system mode.`);
723
- }
724
-
725
- try {
726
- fs.mkdirSync(path.dirname(servicePath), { recursive: true });
727
- if (frontendEnabled) {
728
- fs.mkdirSync(path.dirname(frontendServicePath), { recursive: true });
729
- }
730
-
731
- const backendUnitContent = buildDaemonServiceUnit({
732
- appRoot,
733
- serverPort: portNum,
734
- databasePath,
735
- nodeExecPath: context.nodeExecPath,
736
- cliEntry: context.cliEntry,
737
- });
738
- fs.writeFileSync(servicePath, backendUnitContent, 'utf8');
739
-
740
- if (frontendEnabled) {
741
- const frontendUnitContent = buildFrontendDaemonServiceUnit({
742
- appRoot,
743
- frontendPort: frontendPortNum,
744
- nodeExecPath: context.nodeExecPath,
745
- cliEntry: context.cliEntry,
746
- });
747
- fs.writeFileSync(frontendServicePath, frontendUnitContent, 'utf8');
748
- }
749
- } catch (fileError) {
750
- if (mode === 'system' && (fileError.code === 'EACCES' || fileError.code === 'EPERM')) {
751
- const installHint = buildDaemonCliCommand(
752
- {
753
- subcommand: 'install',
754
- mode: 'system',
755
- extraArgs: frontendEnabled
756
- ? ['--port', String(portNum), '--frontend-port', String(frontendPortNum)]
757
- : ['--port', String(portNum), '--single-port'],
758
- },
759
- daemonCommandContext
760
- );
761
- throw new Error(
762
- `Permission denied writing daemon unit files (${servicePath}, ${frontendServicePath}). ` +
763
- `Try: ${installHint}`
764
- );
765
- }
766
- throw fileError;
767
- }
768
-
769
- runSystemctl(mode, ['daemon-reload']);
770
- runSystemctl(mode, ['enable', '--now', DAEMON_SERVICE_NAME]);
771
- if (frontendEnabled) {
772
- runSystemctl(mode, ['enable', '--now', FRONTEND_DAEMON_SERVICE_NAME]);
773
- } else {
774
- runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
775
- runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
776
- }
777
-
778
- if (mode === 'user') {
779
- const lingerResult = runCommand('loginctl', ['enable-linger', os.userInfo().username]);
780
- if (lingerResult.status !== 0) {
781
- console.log(`${c.warn('[WARN]')} Could not enable linger automatically.`);
782
- console.log(` ${c.dim(extractCommandError(lingerResult, 'Unknown linger error'))}`);
783
- console.log(` ${c.tip('[TIP]')} Run with sufficient privileges: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
784
- }
785
- }
786
-
787
- const installedPort = getPortFromServiceUnit(servicePath) || portNum;
788
- await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, installedPort, c);
789
- const installedFrontendPort = frontendEnabled
790
- ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
791
- : undefined;
792
- if (frontendEnabled && installedFrontendPort) {
793
- await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, installedFrontendPort, c);
794
- }
795
-
796
- const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
797
- const frontendState = frontendEnabled
798
- ? getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME)
799
- : { active: 'disabled', enabled: 'disabled' };
800
- console.log(`\n${c.ok('✔')} Daemon installed and started.`);
801
- console.log(` Mode: ${c.bright(mode)}`);
802
- console.log(` Backend Unit: ${c.dim(servicePath)}`);
803
- console.log(` Frontend Mode: ${c.bright(frontendEnabled ? 'separate service' : 'single backend port')}`);
804
- console.log(` Backend Active: ${c.bright(backendState.active)}`);
805
- console.log(` Backend Enabled:${c.bright(backendState.enabled)}`);
806
- console.log(` Backend URL: ${c.bright(`http://localhost:${installedPort}`)}`);
807
- if (frontendEnabled) {
808
- console.log(` Frontend Unit: ${c.dim(frontendServicePath)}`);
809
- console.log(` Frontend Active:${c.bright(frontendState.active)}`);
810
- console.log(` Frontend Enabled:${c.bright(frontendState.enabled)}`);
811
- console.log(` Frontend URL: ${c.bright(`http://localhost:${installedFrontendPort}`)}`);
812
- }
813
- console.log('');
814
- if (mode === 'system') {
815
- const statusCommand = buildDaemonCliCommand(
816
- { subcommand: 'status', mode: 'system' },
817
- daemonCommandContext
818
- );
819
- const stopCommand = buildDaemonCliCommand(
820
- { subcommand: 'stop', mode: 'system' },
821
- daemonCommandContext
822
- );
823
- const logsCommand = buildDaemonCliCommand(
824
- { subcommand: 'logs', mode: 'system' },
825
- daemonCommandContext
826
- );
827
- console.log(`${c.ok('[OK]')} System daemon is active.`);
828
- console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
829
- console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${installedPort}/`)}`);
830
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
831
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
832
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}\n`);
833
- } else {
834
- const linger = probeLinger();
835
- const statusCommand = buildDaemonCliCommand(
836
- { subcommand: 'status', mode: 'user' },
837
- daemonCommandContext
838
- );
839
- const stopCommand = buildDaemonCliCommand(
840
- { subcommand: 'stop', mode: 'user' },
841
- daemonCommandContext
842
- );
843
- const logsCommand = buildDaemonCliCommand(
844
- { subcommand: 'logs', mode: 'user' },
845
- daemonCommandContext
846
- );
847
- console.log(`${c.ok('[OK]')} User daemon is active.`);
848
- console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
849
- console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${installedPort}/`)}`);
850
- console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
851
- console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
852
- console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
853
- if (linger.value !== 'yes') {
854
- console.log(`${c.tip('[TIP]')} Enable linger for reboot/login persistence: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}\n`);
855
- } else {
856
- console.log('');
857
- }
858
- }
859
- break;
860
- }
861
-
862
- case 'start':
863
- runSystemctl(mode, ['start', DAEMON_SERVICE_NAME]);
864
- if (frontendEnabled) runSystemctl(mode, ['start', FRONTEND_DAEMON_SERVICE_NAME]);
865
- await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
866
- if (frontendEnabled) await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
867
- console.log(`${c.ok('[OK]')} Pixcode service started.`);
868
- break;
869
-
870
- case 'stop':
871
- runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
872
- runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME]);
873
- console.log(`${c.ok('[OK]')} Pixcode service stopped (auto-start remains enabled).`);
874
- break;
875
-
876
- case 'restart':
877
- runSystemctl(mode, ['restart', DAEMON_SERVICE_NAME]);
878
- if (frontendEnabled) runSystemctl(mode, ['restart', FRONTEND_DAEMON_SERVICE_NAME]);
879
- await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
880
- if (frontendEnabled) await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
881
- console.log(`${c.ok('[OK]')} Pixcode service restarted.`);
882
- break;
883
-
884
- case 'enable':
885
- runSystemctl(mode, ['enable', DAEMON_SERVICE_NAME]);
886
- if (frontendEnabled) runSystemctl(mode, ['enable', FRONTEND_DAEMON_SERVICE_NAME]);
887
- console.log(`${c.ok('[OK]')} Pixcode service enabled for auto-start.`);
888
- break;
889
-
890
- case 'disable':
891
- runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME]);
892
- runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME]);
893
- console.log(`${c.ok('[OK]')} Pixcode service disabled for auto-start.`);
894
- break;
895
-
896
- case 'logs': {
897
- const logsResult = readLogs(mode, 100, true, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
898
- if (logsResult.status !== 0) {
899
- throw new Error(extractCommandError(logsResult, 'Unable to read daemon logs'));
900
- }
901
- break;
902
- }
903
-
904
- case 'uninstall': {
905
- runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
906
- runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
907
- runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME], { allowFailure: true });
908
- runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME], { allowFailure: true });
909
-
910
- for (const def of serviceDefs) {
911
- if (!fs.existsSync(def.servicePath)) continue;
912
- try {
913
- fs.unlinkSync(def.servicePath);
914
- } catch (unlinkError) {
915
- if (mode === 'system' && (unlinkError.code === 'EACCES' || unlinkError.code === 'EPERM')) {
916
- const uninstallHint = buildDaemonCliCommand(
917
- { subcommand: 'uninstall', mode: 'system' },
918
- daemonCommandContext
919
- );
920
- throw new Error(`Permission denied removing ${def.servicePath}. Try: ${uninstallHint}`);
921
- }
922
- throw unlinkError;
923
- }
924
- }
925
- runSystemctl(mode, ['daemon-reload'], { allowFailure: true });
926
- console.log(`${c.ok('[OK]')} Backend and frontend daemons uninstalled.`);
927
- break;
928
- }
929
-
930
- case 'status':
931
- default: {
932
- const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
933
- const frontendState = getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME);
934
- const backendUnitExists = fs.existsSync(servicePath);
935
- const frontendUnitExists = fs.existsSync(frontendServicePath);
936
- const selectedPort = getPortFromServiceUnit(servicePath) || portNum;
937
- const selectedFrontendPort = frontendEnabled
938
- ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
939
- : undefined;
940
- console.log(`\n${c.bright('Pixcode Daemon Status')}\n`);
941
- console.log(`${c.info('[INFO]')} Mode: ${c.bright(mode)} ${parsed.options.mode === 'auto' ? c.dim('(resolved from auto)') : ''}`);
942
- console.log(`${c.info('[INFO]')} Backend Unit: ${c.dim(servicePath)} ${backendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
943
- console.log(`${c.info('[INFO]')} Backend Active: ${c.bright(backendState.active)}`);
944
- console.log(`${c.info('[INFO]')} Backend Enabled:${c.bright(backendState.enabled)}`);
945
- console.log(`${c.info('[INFO]')} Backend Port: ${c.bright(String(selectedPort))}`);
946
- console.log(`${c.info('[INFO]')} UI URL: ${c.bright(`http://localhost:${selectedPort}/`)}`);
947
- console.log(`${c.info('[INFO]')} Frontend Mode: ${frontendEnabled ? c.bright('separate Vite service') : c.bright('single backend port')}`);
948
- if (frontendEnabled) {
949
- console.log(`${c.info('[INFO]')} Frontend Unit: ${c.dim(frontendServicePath)} ${frontendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
950
- console.log(`${c.info('[INFO]')} Frontend Active:${c.bright(frontendState.active)}`);
951
- console.log(`${c.info('[INFO]')} Frontend Enabled:${c.bright(frontendState.enabled)}`);
952
- console.log(`${c.info('[INFO]')} Frontend Port: ${c.bright(String(selectedFrontendPort))}`);
953
- } else if (frontendUnitExists) {
954
- console.log(`${c.info('[INFO]')} Legacy Frontend:${c.dim(frontendServicePath)} active=${c.bright(frontendState.active)} enabled=${c.bright(frontendState.enabled)}`);
955
- }
956
- console.log('');
957
- }
958
- }
959
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { spawnSync } from 'child_process';
5
+ import { request } from 'node:http';
6
+ import net from 'node:net';
7
+
8
+ const DAEMON_SERVICE_NAME = 'pixcode.service';
9
+ const FRONTEND_DAEMON_SERVICE_NAME = 'pixcode-frontend.service';
10
+ const DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', DAEMON_SERVICE_NAME);
11
+ const DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', DAEMON_SERVICE_NAME);
12
+ const FRONTEND_DAEMON_USER_SERVICE_PATH = path.join(os.homedir(), '.config', 'systemd', 'user', FRONTEND_DAEMON_SERVICE_NAME);
13
+ const FRONTEND_DAEMON_SYSTEM_SERVICE_PATH = path.join('/etc', 'systemd', 'system', FRONTEND_DAEMON_SERVICE_NAME);
14
+ const DEFAULT_FRONTEND_PORT = 5173;
15
+ const DAEMON_HEALTH_TIMEOUT_MS = 60000;
16
+ const DAEMON_HEALTH_REQUEST_TIMEOUT_MS = 4000;
17
+ const DAEMON_HEALTH_RETRY_INTERVAL_MS = 1000;
18
+
19
+ const DAEMON_SUBCOMMANDS = new Set([
20
+ 'install',
21
+ 'start',
22
+ 'stop',
23
+ 'restart',
24
+ 'status',
25
+ 'logs',
26
+ 'enable',
27
+ 'disable',
28
+ 'uninstall',
29
+ 'doctor',
30
+ 'help',
31
+ ]);
32
+
33
+ const DAEMON_MODES = new Set(['auto', 'user', 'system']);
34
+ const SYSTEM_MUTATING_DAEMON_SUBCOMMANDS = new Set([
35
+ 'install',
36
+ 'start',
37
+ 'stop',
38
+ 'restart',
39
+ 'enable',
40
+ 'disable',
41
+ 'uninstall',
42
+ 'logs',
43
+ ]);
44
+ let pixcodeBinaryAvailableCache = null;
45
+
46
+ function passthroughColor(text) {
47
+ return text;
48
+ }
49
+
50
+ function getColorHelpers(color) {
51
+ if (color) {
52
+ return color;
53
+ }
54
+ return {
55
+ info: passthroughColor,
56
+ ok: passthroughColor,
57
+ warn: passthroughColor,
58
+ error: passthroughColor,
59
+ tip: passthroughColor,
60
+ bright: passthroughColor,
61
+ dim: passthroughColor,
62
+ };
63
+ }
64
+
65
+ function runCommand(bin, args, opts = {}) {
66
+ const stdio = opts.inherit ? 'inherit' : 'pipe';
67
+ return spawnSync(bin, args, {
68
+ encoding: 'utf8',
69
+ stdio,
70
+ });
71
+ }
72
+
73
+ function extractCommandError(result, fallbackMessage) {
74
+ if (!result) return fallbackMessage;
75
+ const fromError = result.error?.message?.trim();
76
+ if (fromError) return fromError;
77
+ const fromStd = (result.stderr || result.stdout || '').trim();
78
+ if (fromStd) return fromStd;
79
+ return fallbackMessage;
80
+ }
81
+
82
+ function isRootUser() {
83
+ return typeof process.getuid === 'function' && process.getuid() === 0;
84
+ }
85
+
86
+ function quoteShellArg(arg) {
87
+ const value = String(arg);
88
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(value)) {
89
+ return value;
90
+ }
91
+ return `'${value.replace(/'/g, `'\\''`)}'`;
92
+ }
93
+
94
+ function quoteSystemdArg(arg) {
95
+ return `"${String(arg).replace(/(["\\$`])/g, '\\$1')}"`;
96
+ }
97
+
98
+ function resolveDaemonCliEntryPath(context = {}) {
99
+ const appRoot = context.appRoot || process.cwd();
100
+ const explicitCliEntry = context.cliEntry ? path.resolve(context.cliEntry) : null;
101
+ const argvCliEntry = process.argv[1] ? path.resolve(process.argv[1]) : null;
102
+ const candidatePaths = [
103
+ explicitCliEntry,
104
+ argvCliEntry,
105
+ path.join(appRoot, 'dist-server', 'server', 'cli.js'),
106
+ path.join(appRoot, 'server', 'cli.js'),
107
+ ].filter(Boolean);
108
+
109
+ const existingPath = candidatePaths.find(candidate => fs.existsSync(candidate));
110
+ if (existingPath) {
111
+ return existingPath;
112
+ }
113
+
114
+ return explicitCliEntry || argvCliEntry || path.join(appRoot, 'server', 'cli.js');
115
+ }
116
+
117
+ function hasPixcodeBinary() {
118
+ if (pixcodeBinaryAvailableCache !== null) {
119
+ return pixcodeBinaryAvailableCache;
120
+ }
121
+
122
+ const probe = runCommand('pixcode', ['--version']);
123
+ pixcodeBinaryAvailableCache = probe.status === 0;
124
+ return pixcodeBinaryAvailableCache;
125
+ }
126
+
127
+ function getDaemonCommandPrefix(context = {}, { forceLocal = false } = {}) {
128
+ if (!forceLocal && hasPixcodeBinary()) {
129
+ return 'pixcode';
130
+ }
131
+
132
+ const nodeExec = context.nodeExecPath || process.execPath || 'node';
133
+ const cliEntry = resolveDaemonCliEntryPath(context);
134
+ return `${quoteShellArg(nodeExec)} ${quoteShellArg(cliEntry)}`;
135
+ }
136
+
137
+ export function buildDaemonCliCommand({ subcommand, mode = 'system', extraArgs = [] }, context = {}) {
138
+ const normalizedSubcommand = String(subcommand || 'status').trim() || 'status';
139
+ const normalizedMode = String(mode || 'system').trim() || 'system';
140
+ const args = ['daemon', normalizedSubcommand, '--mode', normalizedMode, ...extraArgs.map(value => String(value))];
141
+ const needsSudo =
142
+ normalizedMode === 'system' &&
143
+ SYSTEM_MUTATING_DAEMON_SUBCOMMANDS.has(normalizedSubcommand) &&
144
+ !isRootUser();
145
+ const prefix = getDaemonCommandPrefix(context, { forceLocal: needsSudo });
146
+ const command = `${prefix} ${args.map(quoteShellArg).join(' ')}`;
147
+ return needsSudo ? `sudo ${command}` : command;
148
+ }
149
+
150
+ function getDaemonServicePath(mode) {
151
+ return mode === 'system' ? DAEMON_SYSTEM_SERVICE_PATH : DAEMON_USER_SERVICE_PATH;
152
+ }
153
+
154
+ function getFrontendServicePath(mode) {
155
+ return mode === 'system' ? FRONTEND_DAEMON_SYSTEM_SERVICE_PATH : FRONTEND_DAEMON_USER_SERVICE_PATH;
156
+ }
157
+
158
+ function getSystemctlArgs(mode, commandArgs) {
159
+ return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
160
+ }
161
+
162
+ function getJournalctlArgs(mode, commandArgs) {
163
+ return mode === 'user' ? ['--user', ...commandArgs] : commandArgs;
164
+ }
165
+
166
+ function parseDaemonArgs(args) {
167
+ const parsed = {
168
+ subcommand: 'status',
169
+ options: {
170
+ mode: 'system',
171
+ },
172
+ };
173
+
174
+ let i = 0;
175
+ if (args[0] && DAEMON_SUBCOMMANDS.has(args[0])) {
176
+ parsed.subcommand = args[0];
177
+ i = 1;
178
+ }
179
+
180
+ for (; i < args.length; i++) {
181
+ const arg = args[i];
182
+ if (arg === '--port' || arg === '-p') {
183
+ parsed.options.serverPort = args[++i];
184
+ } else if (arg.startsWith('--port=')) {
185
+ parsed.options.serverPort = arg.split('=')[1];
186
+ } else if (arg === '--frontend-port') {
187
+ parsed.options.frontendPort = args[++i];
188
+ } else if (arg.startsWith('--frontend-port=')) {
189
+ parsed.options.frontendPort = arg.split('=')[1];
190
+ } else if (arg === '--no-frontend' || arg === '--single-port') {
191
+ parsed.options.noFrontend = true;
192
+ } else if (arg === '--mode' || arg === '-m') {
193
+ parsed.options.mode = (args[++i] || '').toLowerCase();
194
+ } else if (arg.startsWith('--mode=')) {
195
+ parsed.options.mode = (arg.split('=')[1] || '').toLowerCase();
196
+ } else if (arg === '--database-path') {
197
+ parsed.options.databasePath = args[++i];
198
+ } else if (arg.startsWith('--database-path=')) {
199
+ parsed.options.databasePath = arg.split('=')[1];
200
+ } else if (arg === '--help' || arg === '-h') {
201
+ parsed.subcommand = 'help';
202
+ } else {
203
+ parsed.options.extraArgs = parsed.options.extraArgs || [];
204
+ parsed.options.extraArgs.push(arg);
205
+ }
206
+ }
207
+
208
+ return parsed;
209
+ }
210
+
211
+ function buildDaemonExecStart({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
212
+ const nodeExec = nodeExecPath || process.execPath || 'node';
213
+ const cliCandidate = cliEntry
214
+ ? path.resolve(cliEntry)
215
+ : (process.argv[1] ? path.resolve(process.argv[1]) : path.join(appRoot, 'dist-server', 'server', 'cli.js'));
216
+ const resolvedCliEntry = fs.existsSync(cliCandidate)
217
+ ? cliCandidate
218
+ : path.join(appRoot, 'dist-server', 'server', 'cli.js');
219
+
220
+ const args = [nodeExec, resolvedCliEntry, 'start', '--port', String(serverPort)];
221
+ if (databasePath) {
222
+ args.push('--database-path', databasePath);
223
+ }
224
+
225
+ return args.map(quoteSystemdArg).join(' ');
226
+ }
227
+
228
+ function buildDaemonServiceUnit({ appRoot, serverPort, databasePath, nodeExecPath, cliEntry }) {
229
+ const execStart = buildDaemonExecStart({
230
+ appRoot,
231
+ serverPort,
232
+ databasePath,
233
+ nodeExecPath,
234
+ cliEntry,
235
+ });
236
+ return `[Unit]
237
+ Description=Pixcode Server
238
+ After=network.target
239
+
240
+ [Service]
241
+ Type=simple
242
+ WorkingDirectory=${appRoot}
243
+ ExecStart=${execStart}
244
+ Environment=HOST=0.0.0.0
245
+ Environment=CI=true
246
+ Environment=PIXCODE_DAEMON_MANAGED=1
247
+ Restart=always
248
+ RestartSec=2
249
+
250
+ [Install]
251
+ WantedBy=default.target
252
+ `;
253
+ }
254
+
255
+ function resolveFrontendDaemonEntry(appRoot, cliEntry) {
256
+ const cliCandidate = cliEntry
257
+ ? path.resolve(cliEntry)
258
+ : (process.argv[1] ? path.resolve(process.argv[1]) : '');
259
+ const candidates = [];
260
+ if (cliCandidate) {
261
+ candidates.push(path.join(path.dirname(cliCandidate), 'vite-daemon.js'));
262
+ }
263
+ candidates.push(path.join(appRoot, 'dist-server', 'server', 'vite-daemon.js'));
264
+ candidates.push(path.join(appRoot, 'server', 'vite-daemon.js'));
265
+
266
+ const resolved = candidates.find(candidate => fs.existsSync(candidate));
267
+ if (!resolved) {
268
+ throw new Error(
269
+ `Frontend daemon entry was not found. Checked: ${candidates.join(', ')}. ` +
270
+ `Run "npm run build:server" or ensure server/vite-daemon.js exists.`
271
+ );
272
+ }
273
+ return resolved;
274
+ }
275
+
276
+ function buildFrontendDaemonExecStart({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
277
+ const nodeExec = nodeExecPath || process.execPath || 'node';
278
+ const frontendEntry = resolveFrontendDaemonEntry(appRoot, cliEntry);
279
+ const args = [
280
+ nodeExec,
281
+ frontendEntry,
282
+ '--host',
283
+ '0.0.0.0',
284
+ '--port',
285
+ String(frontendPort),
286
+ '--strictPort',
287
+ ];
288
+ return args.map(quoteSystemdArg).join(' ');
289
+ }
290
+
291
+ function buildFrontendDaemonServiceUnit({ appRoot, frontendPort, nodeExecPath, cliEntry }) {
292
+ const execStart = buildFrontendDaemonExecStart({
293
+ appRoot,
294
+ frontendPort,
295
+ nodeExecPath,
296
+ cliEntry,
297
+ });
298
+ return `[Unit]
299
+ Description=Pixcode Frontend (Vite Dev Server)
300
+ After=network.target
301
+
302
+ [Service]
303
+ Type=simple
304
+ WorkingDirectory=${appRoot}
305
+ ExecStart=${execStart}
306
+ Environment=HOST=0.0.0.0
307
+ Environment=CI=true
308
+ Environment=PIXCODE_DAEMON_MANAGED=1
309
+ Restart=always
310
+ RestartSec=2
311
+
312
+ [Install]
313
+ WantedBy=default.target
314
+ `;
315
+ }
316
+
317
+ function normalizeState(value) {
318
+ const text = (value || '').trim();
319
+ if (!text) return 'unknown';
320
+ if (/No such file or directory/i.test(text)) return 'not-found';
321
+ return text;
322
+ }
323
+
324
+ function getServiceState(mode, serviceName) {
325
+ const activeRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-active', serviceName]));
326
+ const enabledRes = runCommand('systemctl', getSystemctlArgs(mode, ['is-enabled', serviceName]));
327
+
328
+ return {
329
+ active: normalizeState(activeRes.stdout || activeRes.stderr),
330
+ enabled: normalizeState(enabledRes.stdout || enabledRes.stderr),
331
+ };
332
+ }
333
+
334
+ function readLogs(mode, lines = 100, inherit = false, serviceNames = [DAEMON_SERVICE_NAME]) {
335
+ const unitArgs = serviceNames.flatMap((serviceName) => ['-u', serviceName]);
336
+ const args = [...getJournalctlArgs(mode, unitArgs), '-n', String(lines), '--no-pager'];
337
+ return runCommand('journalctl', args, { inherit });
338
+ }
339
+
340
+ function getPortFromServiceUnit(servicePath) {
341
+ if (!fs.existsSync(servicePath)) return null;
342
+ try {
343
+ const content = fs.readFileSync(servicePath, 'utf8');
344
+ const quoted = content.match(/"--port"\s+"(\d+)"/);
345
+ if (quoted) return Number(quoted[1]);
346
+ const plain = content.match(/--port(?:\s+|=)(\d+)/);
347
+ if (plain) return Number(plain[1]);
348
+ } catch {
349
+ // Ignore parse errors and use fallback port.
350
+ }
351
+ return null;
352
+ }
353
+
354
+ function findLatestErrorLine(logText) {
355
+ if (!logText) return '';
356
+ const lines = logText.split('\n').map(line => line.trim()).filter(Boolean);
357
+ const errorLine = [...lines].reverse().find(line => /(error|failed|exception|denied|cannot|traceback)/i.test(line));
358
+ return errorLine || '';
359
+ }
360
+
361
+ function probeUserBus() {
362
+ const result = runCommand('systemctl', ['--user', 'show-environment']);
363
+ return {
364
+ ok: result.status === 0,
365
+ detail: extractCommandError(result, 'systemd user bus is not reachable'),
366
+ };
367
+ }
368
+
369
+ function probeLinger() {
370
+ const result = runCommand('loginctl', ['show-user', os.userInfo().username, '-p', 'Linger']);
371
+ if (result.status !== 0) {
372
+ return {
373
+ value: 'unknown',
374
+ detail: extractCommandError(result, 'Could not read linger status'),
375
+ };
376
+ }
377
+ const output = (result.stdout || '').trim();
378
+ const value = output.includes('=') ? output.split('=')[1].trim().toLowerCase() : output.toLowerCase();
379
+ return {
380
+ value: value || 'unknown',
381
+ detail: '',
382
+ };
383
+ }
384
+
385
+ function resolveDaemonMode({ requestedMode, subcommand, userBusAvailable }) {
386
+ if (requestedMode !== 'auto') {
387
+ return requestedMode;
388
+ }
389
+
390
+ // Auto mode is intentionally system-first to guarantee boot-time startup
391
+ // even without an interactive user session.
392
+ const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
393
+ const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
394
+
395
+ if (systemUnitInstalled) return 'system';
396
+ if (subcommand === 'install') return 'system';
397
+ if (userUnitInstalled && userBusAvailable) return 'user';
398
+ return 'system';
399
+ }
400
+
401
+ function runSystemctl(mode, commandArgs, opts = {}) {
402
+ const result = runCommand('systemctl', getSystemctlArgs(mode, commandArgs), { inherit: opts.inherit });
403
+ if (result.status !== 0 && !opts.allowFailure) {
404
+ let errorText = extractCommandError(result, `systemctl ${commandArgs.join(' ')} failed`);
405
+ if (mode === 'system' && /(access denied|permission denied|must be root|interactive authentication required|not permitted)/i.test(errorText)) {
406
+ errorText += '\nTry rerunning this daemon operation with elevated privileges (sudo).';
407
+ }
408
+ throw new Error(errorText);
409
+ }
410
+ return result;
411
+ }
412
+
413
+ async function sleep(ms) {
414
+ await new Promise(resolve => setTimeout(resolve, ms));
415
+ }
416
+
417
+ async function isPortReachable(port, timeoutMs = 1000) {
418
+ return await new Promise(resolve => {
419
+ const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
420
+ let settled = false;
421
+ const done = (value) => {
422
+ if (settled) return;
423
+ settled = true;
424
+ socket.destroy();
425
+ resolve(value);
426
+ };
427
+ socket.setTimeout(timeoutMs);
428
+ socket.once('connect', () => done(true));
429
+ socket.once('timeout', () => done(false));
430
+ socket.once('error', () => done(false));
431
+ });
432
+ }
433
+
434
+ async function requestHealthOnce(port, timeoutMs = DAEMON_HEALTH_REQUEST_TIMEOUT_MS) {
435
+ return await new Promise((resolve, reject) => {
436
+ const req = request({
437
+ host: '127.0.0.1',
438
+ port: Number(port),
439
+ method: 'GET',
440
+ path: '/health',
441
+ timeout: timeoutMs,
442
+ }, (res) => {
443
+ res.resume();
444
+ resolve({ ok: true, statusCode: res.statusCode });
445
+ });
446
+
447
+ req.on('timeout', () => req.destroy(new Error(`Health check timed out after ${timeoutMs}ms`)));
448
+ req.on('error', reject);
449
+ req.end();
450
+ });
451
+ }
452
+
453
+ async function waitForHealth(port, timeoutMs = DAEMON_HEALTH_TIMEOUT_MS) {
454
+ const deadline = Date.now() + timeoutMs;
455
+ let lastError = null;
456
+ while (Date.now() < deadline) {
457
+ try {
458
+ return await requestHealthOnce(port);
459
+ } catch (error) {
460
+ lastError = error;
461
+ if (await isPortReachable(port, 700)) {
462
+ return { ok: true, statusCode: null, probe: 'tcp' };
463
+ }
464
+ await sleep(DAEMON_HEALTH_RETRY_INTERVAL_MS);
465
+ }
466
+ }
467
+ throw new Error(lastError?.message || `Service did not become healthy on port ${port}`);
468
+ }
469
+
470
+ async function healthCheckOrThrow(mode, serviceName, port, c) {
471
+ const state = getServiceState(mode, serviceName);
472
+ if (state.active !== 'active' && state.active !== 'activating') {
473
+ throw new Error(`Service ${serviceName} is not active (state: ${state.active})`);
474
+ }
475
+
476
+ try {
477
+ const health = await waitForHealth(port);
478
+ if (health.probe === 'tcp') {
479
+ console.log(`${c.warn('[WARN]')} HTTP /health probe delayed; TCP port ${port} is already accepting connections.`);
480
+ }
481
+ } catch (healthError) {
482
+ const logsResult = readLogs(mode, 50, false, [serviceName]);
483
+ const logText = (logsResult.stdout || logsResult.stderr || '').trim();
484
+ const lastErrorLine = findLatestErrorLine(logText);
485
+
486
+ if (logText) {
487
+ console.log(`\n${c.warn('[WARN]')} Last 50 log lines for ${serviceName}:`);
488
+ console.log(logText);
489
+ }
490
+
491
+ if (lastErrorLine) {
492
+ throw new Error(`Health check failed for ${serviceName}: ${healthError.message}\nLikely cause: ${lastErrorLine}`);
493
+ }
494
+ throw new Error(`Health check failed for ${serviceName}: ${healthError.message}`);
495
+ }
496
+ }
497
+
498
+ function ensureLinux() {
499
+ if (process.platform !== 'linux') {
500
+ throw new Error('The daemon command is supported on Linux only.');
501
+ }
502
+ }
503
+
504
+ function ensureSystemctl() {
505
+ const probe = runCommand('systemctl', ['--version']);
506
+ if (probe.status !== 0) {
507
+ throw new Error(extractCommandError(probe, 'systemctl is not available in this environment'));
508
+ }
509
+ }
510
+
511
+ function showDaemonHelp(c, context = {}) {
512
+ const usagePrefix = getDaemonCommandPrefix(context);
513
+ const installExample = buildDaemonCliCommand(
514
+ {
515
+ subcommand: 'install',
516
+ mode: 'system',
517
+ extraArgs: ['--port', '3001', '--single-port'],
518
+ },
519
+ context
520
+ );
521
+ const statusExample = buildDaemonCliCommand({ subcommand: 'status', mode: 'system' }, context);
522
+ const doctorExample = buildDaemonCliCommand({ subcommand: 'doctor', mode: 'auto' }, context);
523
+ const logsExample = buildDaemonCliCommand({ subcommand: 'logs', mode: 'system' }, context);
524
+ console.log(`
525
+ ${c.bright('Pixcode Daemon')} - Persistent Linux service manager
526
+
527
+ Usage:
528
+ ${usagePrefix} daemon [subcommand] [options]
529
+
530
+ Subcommands:
531
+ ${c.bright('install')} Install/update unit, reload daemon, enable and start now
532
+ ${c.bright('start')} Start the service
533
+ ${c.bright('stop')} Stop the service (temporary; auto-start remains enabled)
534
+ ${c.bright('restart')} Restart the service
535
+ ${c.bright('status')} Show active/enabled state
536
+ ${c.bright('logs')} Show recent service logs
537
+ ${c.bright('enable')} Enable auto-start at boot
538
+ ${c.bright('disable')} Disable auto-start at boot
539
+ ${c.bright('uninstall')} Stop, disable, and remove the service unit
540
+ ${c.bright('doctor')} Run diagnostics (bus, linger, units, state, port, logs)
541
+ ${c.bright('help')} Show this help
542
+
543
+ Options:
544
+ -p, --port <port> Set service server port (default: 3001)
545
+ --frontend-port <port> Start a separate frontend Vite service on this port (legacy/dev)
546
+ --single-port, --no-frontend
547
+ Serve the built UI from the backend port only (default)
548
+ -m, --mode <mode> Service mode: user | system | auto (default: system)
549
+ --database-path <path> Set service database path
550
+
551
+ Examples:
552
+ $ ${installExample}
553
+ $ ${statusExample}
554
+ $ ${doctorExample}
555
+ $ ${logsExample}
556
+ `);
557
+ }
558
+
559
+ export function hasInstalledDaemonUnit() {
560
+ return (
561
+ fs.existsSync(DAEMON_USER_SERVICE_PATH) ||
562
+ fs.existsSync(DAEMON_SYSTEM_SERVICE_PATH) ||
563
+ fs.existsSync(FRONTEND_DAEMON_USER_SERVICE_PATH) ||
564
+ fs.existsSync(FRONTEND_DAEMON_SYSTEM_SERVICE_PATH)
565
+ );
566
+ }
567
+
568
+ export async function handleDaemonCommand(args, context = {}) {
569
+ const c = getColorHelpers(context.color);
570
+ const parsed = parseDaemonArgs(args);
571
+ const appRoot = context.appRoot || process.cwd();
572
+ const daemonCommandContext = {
573
+ appRoot,
574
+ cliEntry: context.cliEntry,
575
+ nodeExecPath: context.nodeExecPath,
576
+ };
577
+
578
+ if (parsed.options.extraArgs?.length) {
579
+ showDaemonHelp(c, daemonCommandContext);
580
+ throw new Error(`Unknown daemon arguments: ${parsed.options.extraArgs.join(' ')}`);
581
+ }
582
+
583
+ if (parsed.subcommand === 'help') {
584
+ showDaemonHelp(c, daemonCommandContext);
585
+ return;
586
+ }
587
+
588
+ if (!DAEMON_MODES.has(parsed.options.mode)) {
589
+ throw new Error(`Invalid daemon mode "${parsed.options.mode}". Use one of: auto, user, system.`);
590
+ }
591
+
592
+ ensureLinux();
593
+ ensureSystemctl();
594
+
595
+ const defaultPort = context.defaultPort || process.env.SERVER_PORT || process.env.PORT || '3001';
596
+ const defaultFrontendPort = context.defaultFrontendPort || process.env.VITE_PORT || String(DEFAULT_FRONTEND_PORT);
597
+ const configuredPort = parsed.options.serverPort || defaultPort;
598
+ const configuredFrontendPort = parsed.options.frontendPort || defaultFrontendPort;
599
+ const frontendEnabled = parsed.options.noFrontend !== true &&
600
+ (Boolean(parsed.options.frontendPort) || process.env.PIXCODE_SEPARATE_FRONTEND === '1');
601
+ const databasePath = parsed.options.databasePath || process.env.DATABASE_PATH || '';
602
+
603
+ const portNum = Number(configuredPort);
604
+ if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
605
+ throw new Error(`Invalid port "${configuredPort}". Expected an integer between 1 and 65535.`);
606
+ }
607
+ const frontendPortNum = Number(configuredFrontendPort);
608
+ if (frontendEnabled && (!Number.isInteger(frontendPortNum) || frontendPortNum < 1 || frontendPortNum > 65535)) {
609
+ throw new Error(`Invalid frontend port "${configuredFrontendPort}". Expected an integer between 1 and 65535.`);
610
+ }
611
+
612
+ const userBus = probeUserBus();
613
+ const mode = resolveDaemonMode({
614
+ requestedMode: parsed.options.mode,
615
+ subcommand: parsed.subcommand,
616
+ userBusAvailable: userBus.ok,
617
+ });
618
+ const servicePath = getDaemonServicePath(mode);
619
+ const frontendServicePath = getFrontendServicePath(mode);
620
+ const effectivePort = getPortFromServiceUnit(servicePath) || portNum;
621
+ const effectiveFrontendPort = getPortFromServiceUnit(frontendServicePath) || frontendPortNum;
622
+
623
+ if (mode === 'user' && !userBus.ok) {
624
+ const installSystemCommand = buildDaemonCliCommand(
625
+ { subcommand: 'install', mode: 'system' },
626
+ daemonCommandContext
627
+ );
628
+ throw new Error(
629
+ `Could not connect to your systemd user session.\n${userBus.detail}\n` +
630
+ `Try ${c.bright(installSystemCommand)} or enable user linger: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`
631
+ );
632
+ }
633
+
634
+ if (parsed.subcommand === 'doctor') {
635
+ const linger = probeLinger();
636
+ const userUnitInstalled = fs.existsSync(getDaemonServicePath('user'));
637
+ const userFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('user'));
638
+ const systemUnitInstalled = fs.existsSync(getDaemonServicePath('system'));
639
+ const systemFrontendUnitInstalled = fs.existsSync(getFrontendServicePath('system'));
640
+ const selectedModePort = getPortFromServiceUnit(servicePath) || portNum;
641
+ const selectedModeFrontendPort = frontendEnabled
642
+ ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
643
+ : undefined;
644
+ const portReachable = await isPortReachable(selectedModePort);
645
+ const frontendPortReachable = selectedModeFrontendPort
646
+ ? await isPortReachable(selectedModeFrontendPort)
647
+ : false;
648
+ const userState = userBus.ok
649
+ ? {
650
+ backend: getServiceState('user', DAEMON_SERVICE_NAME),
651
+ frontend: getServiceState('user', FRONTEND_DAEMON_SERVICE_NAME),
652
+ }
653
+ : {
654
+ backend: { active: 'unavailable', enabled: 'unavailable' },
655
+ frontend: { active: 'unavailable', enabled: 'unavailable' },
656
+ };
657
+ const systemState = {
658
+ backend: getServiceState('system', DAEMON_SERVICE_NAME),
659
+ frontend: getServiceState('system', FRONTEND_DAEMON_SERVICE_NAME),
660
+ };
661
+ const logsResult = readLogs(mode, 50, false, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
662
+ const logsText = (logsResult.stdout || logsResult.stderr || '').trim();
663
+ const lastErrorLine = findLatestErrorLine(logsText);
664
+
665
+ console.log(`\n${c.bright('Pixcode Daemon Doctor')}\n`);
666
+ console.log(`${c.info('[INFO]')} Requested mode: ${c.bright(parsed.options.mode)}`);
667
+ console.log(`${c.info('[INFO]')} Resolved mode: ${c.bright(mode)}`);
668
+ console.log(`${c.info('[INFO]')} user-bus: ${userBus.ok ? c.ok('ok') : c.warn('unavailable')}`);
669
+ if (!userBus.ok) {
670
+ console.log(` ${c.dim(userBus.detail)}`);
671
+ }
672
+ console.log(`${c.info('[INFO]')} linger: ${c.bright(linger.value)}${linger.detail ? ` ${c.dim(`(${linger.detail})`)}` : ''}`);
673
+ console.log(`${c.info('[INFO]')} user backend: ${userUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('user'))})`);
674
+ console.log(`${c.info('[INFO]')} user frontend: ${userFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('user'))})`);
675
+ console.log(`${c.info('[INFO]')} system backend: ${systemUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getDaemonServicePath('system'))})`);
676
+ console.log(`${c.info('[INFO]')} system frontend:${systemFrontendUnitInstalled ? c.ok('installed') : c.warn('missing')} (${c.dim(getFrontendServicePath('system'))})`);
677
+ console.log(`${c.info('[INFO]')} user state: backend active=${c.bright(userState.backend.active)} enabled=${c.bright(userState.backend.enabled)} | frontend active=${c.bright(userState.frontend.active)} enabled=${c.bright(userState.frontend.enabled)}`);
678
+ console.log(`${c.info('[INFO]')} system state: backend active=${c.bright(systemState.backend.active)} enabled=${c.bright(systemState.backend.enabled)} | frontend active=${c.bright(systemState.frontend.active)} enabled=${c.bright(systemState.frontend.enabled)}`);
679
+ console.log(`${c.info('[INFO]')} backend port: ${c.bright(String(selectedModePort))} (${portReachable ? c.ok('reachable') : c.warn('not reachable')})`);
680
+ console.log(`${c.info('[INFO]')} frontend mode: ${frontendEnabled ? c.bright('separate Vite service') : c.bright('single backend port')}`);
681
+ if (frontendEnabled) {
682
+ console.log(`${c.info('[INFO]')} frontend port: ${c.bright(String(selectedModeFrontendPort))} (${frontendPortReachable ? c.ok('reachable') : c.warn('not reachable')})`);
683
+ }
684
+ if (lastErrorLine) {
685
+ console.log(`${c.warn('[WARN]')} Latest error: ${lastErrorLine}`);
686
+ }
687
+
688
+ console.log(`\n${c.bright('Machine Readable')}`);
689
+ console.log(`MODE_REQUESTED=${parsed.options.mode}`);
690
+ console.log(`MODE_RESOLVED=${mode}`);
691
+ console.log(`USER_BUS_OK=${userBus.ok}`);
692
+ console.log(`LINGER=${linger.value}`);
693
+ console.log(`USER_BACKEND_UNIT_INSTALLED=${userUnitInstalled}`);
694
+ console.log(`USER_FRONTEND_UNIT_INSTALLED=${userFrontendUnitInstalled}`);
695
+ console.log(`SYSTEM_BACKEND_UNIT_INSTALLED=${systemUnitInstalled}`);
696
+ console.log(`SYSTEM_FRONTEND_UNIT_INSTALLED=${systemFrontendUnitInstalled}`);
697
+ console.log(`USER_BACKEND_ACTIVE=${userState.backend.active}`);
698
+ console.log(`USER_BACKEND_ENABLED=${userState.backend.enabled}`);
699
+ console.log(`USER_FRONTEND_ACTIVE=${userState.frontend.active}`);
700
+ console.log(`USER_FRONTEND_ENABLED=${userState.frontend.enabled}`);
701
+ console.log(`SYSTEM_BACKEND_ACTIVE=${systemState.backend.active}`);
702
+ console.log(`SYSTEM_BACKEND_ENABLED=${systemState.backend.enabled}`);
703
+ console.log(`SYSTEM_FRONTEND_ACTIVE=${systemState.frontend.active}`);
704
+ console.log(`SYSTEM_FRONTEND_ENABLED=${systemState.frontend.enabled}`);
705
+ console.log(`BACKEND_PORT=${selectedModePort}`);
706
+ console.log(`BACKEND_PORT_REACHABLE=${portReachable}`);
707
+ console.log(`FRONTEND_ENABLED=${frontendEnabled}`);
708
+ console.log(`FRONTEND_PORT=${selectedModeFrontendPort ?? ''}`);
709
+ console.log(`FRONTEND_PORT_REACHABLE=${frontendPortReachable}`);
710
+ console.log(`LAST_ERROR_LINE=${JSON.stringify(lastErrorLine || '')}\n`);
711
+ return;
712
+ }
713
+
714
+ const serviceDefs = [{ servicePath }];
715
+ if (frontendEnabled) {
716
+ serviceDefs.push({ servicePath: frontendServicePath });
717
+ }
718
+
719
+ switch (parsed.subcommand) {
720
+ case 'install': {
721
+ if (parsed.options.mode === 'auto' && mode === 'system' && !userBus.ok) {
722
+ console.log(`${c.warn('[WARN]')} User mode is unavailable; auto mode is falling back to system mode.`);
723
+ }
724
+
725
+ try {
726
+ fs.mkdirSync(path.dirname(servicePath), { recursive: true });
727
+ if (frontendEnabled) {
728
+ fs.mkdirSync(path.dirname(frontendServicePath), { recursive: true });
729
+ }
730
+
731
+ const backendUnitContent = buildDaemonServiceUnit({
732
+ appRoot,
733
+ serverPort: portNum,
734
+ databasePath,
735
+ nodeExecPath: context.nodeExecPath,
736
+ cliEntry: context.cliEntry,
737
+ });
738
+ fs.writeFileSync(servicePath, backendUnitContent, 'utf8');
739
+
740
+ if (frontendEnabled) {
741
+ const frontendUnitContent = buildFrontendDaemonServiceUnit({
742
+ appRoot,
743
+ frontendPort: frontendPortNum,
744
+ nodeExecPath: context.nodeExecPath,
745
+ cliEntry: context.cliEntry,
746
+ });
747
+ fs.writeFileSync(frontendServicePath, frontendUnitContent, 'utf8');
748
+ }
749
+ } catch (fileError) {
750
+ if (mode === 'system' && (fileError.code === 'EACCES' || fileError.code === 'EPERM')) {
751
+ const installHint = buildDaemonCliCommand(
752
+ {
753
+ subcommand: 'install',
754
+ mode: 'system',
755
+ extraArgs: frontendEnabled
756
+ ? ['--port', String(portNum), '--frontend-port', String(frontendPortNum)]
757
+ : ['--port', String(portNum), '--single-port'],
758
+ },
759
+ daemonCommandContext
760
+ );
761
+ throw new Error(
762
+ `Permission denied writing daemon unit files (${servicePath}, ${frontendServicePath}). ` +
763
+ `Try: ${installHint}`
764
+ );
765
+ }
766
+ throw fileError;
767
+ }
768
+
769
+ runSystemctl(mode, ['daemon-reload']);
770
+ runSystemctl(mode, ['enable', '--now', DAEMON_SERVICE_NAME]);
771
+ if (frontendEnabled) {
772
+ runSystemctl(mode, ['enable', '--now', FRONTEND_DAEMON_SERVICE_NAME]);
773
+ } else {
774
+ runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
775
+ runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
776
+ }
777
+
778
+ if (mode === 'user') {
779
+ const lingerResult = runCommand('loginctl', ['enable-linger', os.userInfo().username]);
780
+ if (lingerResult.status !== 0) {
781
+ console.log(`${c.warn('[WARN]')} Could not enable linger automatically.`);
782
+ console.log(` ${c.dim(extractCommandError(lingerResult, 'Unknown linger error'))}`);
783
+ console.log(` ${c.tip('[TIP]')} Run with sufficient privileges: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
784
+ }
785
+ }
786
+
787
+ const installedPort = getPortFromServiceUnit(servicePath) || portNum;
788
+ await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, installedPort, c);
789
+ const installedFrontendPort = frontendEnabled
790
+ ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
791
+ : undefined;
792
+ if (frontendEnabled && installedFrontendPort) {
793
+ await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, installedFrontendPort, c);
794
+ }
795
+
796
+ const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
797
+ const frontendState = frontendEnabled
798
+ ? getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME)
799
+ : { active: 'disabled', enabled: 'disabled' };
800
+ console.log(`\n${c.ok('✔')} Daemon installed and started.`);
801
+ console.log(` Mode: ${c.bright(mode)}`);
802
+ console.log(` Backend Unit: ${c.dim(servicePath)}`);
803
+ console.log(` Frontend Mode: ${c.bright(frontendEnabled ? 'separate service' : 'single backend port')}`);
804
+ console.log(` Backend Active: ${c.bright(backendState.active)}`);
805
+ console.log(` Backend Enabled:${c.bright(backendState.enabled)}`);
806
+ console.log(` Backend URL: ${c.bright(`http://localhost:${installedPort}`)}`);
807
+ if (frontendEnabled) {
808
+ console.log(` Frontend Unit: ${c.dim(frontendServicePath)}`);
809
+ console.log(` Frontend Active:${c.bright(frontendState.active)}`);
810
+ console.log(` Frontend Enabled:${c.bright(frontendState.enabled)}`);
811
+ console.log(` Frontend URL: ${c.bright(`http://localhost:${installedFrontendPort}`)}`);
812
+ }
813
+ console.log('');
814
+ if (mode === 'system') {
815
+ const statusCommand = buildDaemonCliCommand(
816
+ { subcommand: 'status', mode: 'system' },
817
+ daemonCommandContext
818
+ );
819
+ const stopCommand = buildDaemonCliCommand(
820
+ { subcommand: 'stop', mode: 'system' },
821
+ daemonCommandContext
822
+ );
823
+ const logsCommand = buildDaemonCliCommand(
824
+ { subcommand: 'logs', mode: 'system' },
825
+ daemonCommandContext
826
+ );
827
+ console.log(`${c.ok('[OK]')} System daemon is active.`);
828
+ console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
829
+ console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${installedPort}/`)}`);
830
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
831
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
832
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}\n`);
833
+ } else {
834
+ const linger = probeLinger();
835
+ const statusCommand = buildDaemonCliCommand(
836
+ { subcommand: 'status', mode: 'user' },
837
+ daemonCommandContext
838
+ );
839
+ const stopCommand = buildDaemonCliCommand(
840
+ { subcommand: 'stop', mode: 'user' },
841
+ daemonCommandContext
842
+ );
843
+ const logsCommand = buildDaemonCliCommand(
844
+ { subcommand: 'logs', mode: 'user' },
845
+ daemonCommandContext
846
+ );
847
+ console.log(`${c.ok('[OK]')} User daemon is active.`);
848
+ console.log(`${c.info('[INFO]')} Backend health: ${c.bright(`http://localhost:${installedPort}/health`)}`);
849
+ console.log(`${c.info('[INFO]')} UI: ${c.bright(`http://localhost:${installedPort}/`)}`);
850
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
851
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
852
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
853
+ if (linger.value !== 'yes') {
854
+ console.log(`${c.tip('[TIP]')} Enable linger for reboot/login persistence: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}\n`);
855
+ } else {
856
+ console.log('');
857
+ }
858
+ }
859
+ break;
860
+ }
861
+
862
+ case 'start':
863
+ runSystemctl(mode, ['start', DAEMON_SERVICE_NAME]);
864
+ if (frontendEnabled) runSystemctl(mode, ['start', FRONTEND_DAEMON_SERVICE_NAME]);
865
+ await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
866
+ if (frontendEnabled) await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
867
+ console.log(`${c.ok('[OK]')} Pixcode service started.`);
868
+ break;
869
+
870
+ case 'stop':
871
+ runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
872
+ runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME]);
873
+ console.log(`${c.ok('[OK]')} Pixcode service stopped (auto-start remains enabled).`);
874
+ break;
875
+
876
+ case 'restart':
877
+ runSystemctl(mode, ['restart', DAEMON_SERVICE_NAME]);
878
+ if (frontendEnabled) runSystemctl(mode, ['restart', FRONTEND_DAEMON_SERVICE_NAME]);
879
+ await healthCheckOrThrow(mode, DAEMON_SERVICE_NAME, effectivePort, c);
880
+ if (frontendEnabled) await healthCheckOrThrow(mode, FRONTEND_DAEMON_SERVICE_NAME, effectiveFrontendPort, c);
881
+ console.log(`${c.ok('[OK]')} Pixcode service restarted.`);
882
+ break;
883
+
884
+ case 'enable':
885
+ runSystemctl(mode, ['enable', DAEMON_SERVICE_NAME]);
886
+ if (frontendEnabled) runSystemctl(mode, ['enable', FRONTEND_DAEMON_SERVICE_NAME]);
887
+ console.log(`${c.ok('[OK]')} Pixcode service enabled for auto-start.`);
888
+ break;
889
+
890
+ case 'disable':
891
+ runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME]);
892
+ runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME]);
893
+ console.log(`${c.ok('[OK]')} Pixcode service disabled for auto-start.`);
894
+ break;
895
+
896
+ case 'logs': {
897
+ const logsResult = readLogs(mode, 100, true, [DAEMON_SERVICE_NAME, FRONTEND_DAEMON_SERVICE_NAME]);
898
+ if (logsResult.status !== 0) {
899
+ throw new Error(extractCommandError(logsResult, 'Unable to read daemon logs'));
900
+ }
901
+ break;
902
+ }
903
+
904
+ case 'uninstall': {
905
+ runSystemctl(mode, ['stop', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
906
+ runSystemctl(mode, ['disable', FRONTEND_DAEMON_SERVICE_NAME], { allowFailure: true });
907
+ runSystemctl(mode, ['stop', DAEMON_SERVICE_NAME], { allowFailure: true });
908
+ runSystemctl(mode, ['disable', DAEMON_SERVICE_NAME], { allowFailure: true });
909
+
910
+ for (const def of serviceDefs) {
911
+ if (!fs.existsSync(def.servicePath)) continue;
912
+ try {
913
+ fs.unlinkSync(def.servicePath);
914
+ } catch (unlinkError) {
915
+ if (mode === 'system' && (unlinkError.code === 'EACCES' || unlinkError.code === 'EPERM')) {
916
+ const uninstallHint = buildDaemonCliCommand(
917
+ { subcommand: 'uninstall', mode: 'system' },
918
+ daemonCommandContext
919
+ );
920
+ throw new Error(`Permission denied removing ${def.servicePath}. Try: ${uninstallHint}`);
921
+ }
922
+ throw unlinkError;
923
+ }
924
+ }
925
+ runSystemctl(mode, ['daemon-reload'], { allowFailure: true });
926
+ console.log(`${c.ok('[OK]')} Backend and frontend daemons uninstalled.`);
927
+ break;
928
+ }
929
+
930
+ case 'status':
931
+ default: {
932
+ const backendState = getServiceState(mode, DAEMON_SERVICE_NAME);
933
+ const frontendState = getServiceState(mode, FRONTEND_DAEMON_SERVICE_NAME);
934
+ const backendUnitExists = fs.existsSync(servicePath);
935
+ const frontendUnitExists = fs.existsSync(frontendServicePath);
936
+ const selectedPort = getPortFromServiceUnit(servicePath) || portNum;
937
+ const selectedFrontendPort = frontendEnabled
938
+ ? getPortFromServiceUnit(frontendServicePath) || frontendPortNum
939
+ : undefined;
940
+ console.log(`\n${c.bright('Pixcode Daemon Status')}\n`);
941
+ console.log(`${c.info('[INFO]')} Mode: ${c.bright(mode)} ${parsed.options.mode === 'auto' ? c.dim('(resolved from auto)') : ''}`);
942
+ console.log(`${c.info('[INFO]')} Backend Unit: ${c.dim(servicePath)} ${backendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
943
+ console.log(`${c.info('[INFO]')} Backend Active: ${c.bright(backendState.active)}`);
944
+ console.log(`${c.info('[INFO]')} Backend Enabled:${c.bright(backendState.enabled)}`);
945
+ console.log(`${c.info('[INFO]')} Backend Port: ${c.bright(String(selectedPort))}`);
946
+ console.log(`${c.info('[INFO]')} UI URL: ${c.bright(`http://localhost:${selectedPort}/`)}`);
947
+ console.log(`${c.info('[INFO]')} Frontend Mode: ${frontendEnabled ? c.bright('separate Vite service') : c.bright('single backend port')}`);
948
+ if (frontendEnabled) {
949
+ console.log(`${c.info('[INFO]')} Frontend Unit: ${c.dim(frontendServicePath)} ${frontendUnitExists ? c.ok('[OK]') : c.warn('[MISSING]')}`);
950
+ console.log(`${c.info('[INFO]')} Frontend Active:${c.bright(frontendState.active)}`);
951
+ console.log(`${c.info('[INFO]')} Frontend Enabled:${c.bright(frontendState.enabled)}`);
952
+ console.log(`${c.info('[INFO]')} Frontend Port: ${c.bright(String(selectedFrontendPort))}`);
953
+ } else if (frontendUnitExists) {
954
+ console.log(`${c.info('[INFO]')} Legacy Frontend:${c.dim(frontendServicePath)} active=${c.bright(frontendState.active)} enabled=${c.bright(frontendState.enabled)}`);
955
+ }
956
+ console.log('');
957
+ }
958
+ }
959
+ }