-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
963 lines (844 loc) · 29.9 KB
/
Copy pathserver.js
File metadata and controls
963 lines (844 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
import express from 'express';
import cors from 'cors';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import chokidar from 'chokidar';
import { resolveTaskmasterPaths } from './utils/paths.js';
// Path validation utility to prevent directory traversal attacks
class PathValidator {
static validatePath(inputPath) {
if (!inputPath || typeof inputPath !== 'string') {
throw new Error('Path must be a non-empty string');
}
const trimmedPath = inputPath.trim();
if (trimmedPath.length === 0) {
throw new Error('Path cannot be empty');
}
// Check for directory traversal attempts
if (trimmedPath.includes('..')) {
throw new Error('Path contains directory traversal attempts');
}
// Check for invalid characters
if (/[<>:"|?*]/.test(trimmedPath)) {
throw new Error('Path contains invalid characters');
}
// Resolve and normalize the path
try {
const resolvedPath = path.resolve(trimmedPath);
// Additional safety check
if (resolvedPath.includes('..')) {
throw new Error('Resolved path contains directory traversal');
}
return resolvedPath;
} catch (error) {
throw new Error(`Failed to resolve path: ${error.message}`);
}
}
static validateTasksDirectory(projectPath) {
const safeProjectPath = this.validatePath(projectPath);
const tasksPath = path.join(safeProjectPath, 'tasks');
// Validate the tasks path as well
const safeTasksPath = this.validatePath(tasksPath);
return { projectPath: safeProjectPath, tasksPath: safeTasksPath };
}
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3001;
app.use(cors());
app.use(express.json());
// Store active SSE connections
const sseConnections = new Map();
let connectionId = 0;
// Store file watchers
const fileWatchers = new Map();
// Store retry counts and backoff timers per project path
const watchRetries = new Map();
const backoffTimers = new Map();
// Maximum number of retry attempts
const MAX_RETRY_ATTEMPTS = 3;
// Initial backoff delay in milliseconds
const INITIAL_BACKOFF_DELAY = 1000;
// Maximum backoff delay in milliseconds
const MAX_BACKOFF_DELAY = 30000;
// Serve static files from the dist directory when built
const distPath = path.join(__dirname, 'dist');
const publicPath = path.join(__dirname, 'public');
if (fs.existsSync(distPath)) {
app.use(express.static(distPath));
console.log('✅ Serving built application from dist/');
} else {
console.warn('⚠️ No dist/ directory found. Run "npm run build" first.');
}
// Always serve public assets (favicons, etc.) even in development
if (fs.existsSync(publicPath)) {
app.use(express.static(publicPath));
console.log('✅ Serving public assets from public/');
}
// Health check endpoint
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
version: process.env.npm_package_version || '1.0.0',
timestamp: new Date().toISOString()
});
});
// Provide default project path and compatibility info
app.get('/api/default-path', (req, res) => {
let compatibility = null;
try {
const pkgPath = path.join(__dirname, 'package.json');
if (fs.existsSync(pkgPath)) {
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
compatibility = pkg.taskmasterCompatibility || null;
}
} catch {}
res.json({ defaultPath: process.env.DEFAULT_PROJECT_PATH || null, compatibility });
});
// Server-Sent Events endpoint for live updates
app.get('/api/live-updates', (req, res) => {
const currentConnectionId = ++connectionId;
// Set headers for SSE
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control'
});
// Store the connection
sseConnections.set(currentConnectionId, res);
// Send initial connection event
res.write(`data: ${JSON.stringify({ type: 'connected', id: currentConnectionId })}\n\n`);
// Handle client disconnect
req.on('close', () => {
sseConnections.delete(currentConnectionId);
console.log(`SSE connection ${currentConnectionId} closed`);
});
req.on('error', () => {
sseConnections.delete(currentConnectionId);
});
});
// Start watching a project directory for changes
app.post('/api/watch-project', async (req, res) => {
try {
const { projectPath } = req.body;
if (!projectPath) {
return res.status(400).json({ error: 'Project path is required' });
}
// Validate and sanitize paths
let { tasksDir, mode } = resolveTaskmasterPaths(projectPath);
let safeProjectPath = path.resolve(projectPath);
// Validate project path
try {
const validatedPaths = PathValidator.validateTasksDirectory(projectPath);
safeProjectPath = validatedPaths.projectPath;
// Use validated paths as fallback
tasksDir = tasksDir || validatedPaths.tasksPath;
} catch (validationError) {
console.warn(`Path validation failed for ${projectPath}:`, validationError.message);
return res.status(400).json({
error: 'Invalid project path',
details: validationError.message,
watching: false
});
}
// Stop existing watcher for this path if any
if (fileWatchers.has(safeProjectPath)) {
fileWatchers.get(safeProjectPath).close();
fileWatchers.delete(safeProjectPath);
}
// Watch the resolved tasks directory
let directoriesToWatch = [tasksDir];
// If unknown mode, attempt to watch both potential locations
if (mode === 'legacy') {
// already legacy path in tasksDir
} else if (mode === 'unknown') {
directoriesToWatch = [
path.join(safeProjectPath, '.taskmaster', 'tasks'),
path.join(safeProjectPath, 'tasks')
];
}
const existingDirs = directoriesToWatch.filter(dir => fs.existsSync(dir));
if (existingDirs.length === 0) {
const retryCount = watchRetries.get(safeProjectPath) || 0;
if (retryCount >= MAX_RETRY_ATTEMPTS) {
watchRetries.delete(safeProjectPath);
return res.status(400).json({
error: 'Tasks directory not accessible',
message: `No tasks directory found in any of the expected locations. Maximum retry attempts exceeded.`,
watching: false,
suggestion: 'Please create a \'tasks\' or \'.taskmaster/tasks\' directory in your project.',
});
}
watchRetries.set(safeProjectPath, retryCount + 1);
return res.status(404).json({
error: 'Tasks directory not accessible',
message: `No tasks directory found in any of the expected locations.`,
watching: false,
retryCount: retryCount + 1,
maxRetries: MAX_RETRY_ATTEMPTS,
suggestion: 'Create a \'tasks\' or \'.taskmaster/tasks\' directory in your project root to enable file watching.',
});
}
// Watch the existing directories
directoriesToWatch = existingDirs;
watchRetries.delete(safeProjectPath);
const watcher = chokidar.watch(directoriesToWatch, {
// Improved watching options merging previous logic
persistent: true,
ignoreInitial: true,
depth: 1,
ignorePermissionErrors: true,
usePolling: false,
interval: 1000,
binaryInterval: 5000
});
watcher.on('change', async (filePath) => {
console.log(`📄 File changed: ${filePath}`);
try {
// Validate the changed file path for security
const safeFilePath = PathValidator.validatePath(filePath);
// Ensure the changed file is within the expected tasks directory
// Check if file is within any of the watched directories
const isInWatchedDir = directoriesToWatch.some(dir => safeFilePath.startsWith(dir));
if (!isInWatchedDir) {
console.warn(`⚠️ File change detected outside watched directories: ${filePath}`);
return;
}
// Load updated tasks
const updatedTasks = await loadTasksFromPath(safeProjectPath);
// Broadcast to all SSE connections
const updateEvent = {
type: 'tasks-updated',
data: updatedTasks,
timestamp: new Date().toISOString(),
changedFile: path.basename(filePath),
mode: mode
};
broadcastToSSE(updateEvent);
console.log(`✅ Successfully updated tasks after file change: ${path.basename(safeFilePath)}`);
} catch (error) {
console.error('❌ Error loading updated tasks:', error);
broadcastToSSE({
type: 'error',
message: 'Failed to load updated tasks',
timestamp: new Date().toISOString(),
details: error.message,
errorType: error.name || 'UnknownError'
});
}
});
watcher.on('add', async (filePath) => {
console.log(`➕ File added: ${filePath}`);
try {
const updatedTasks = await loadTasksFromPath(safeProjectPath);
broadcastToSSE({
type: 'tasks-updated',
data: updatedTasks,
timestamp: new Date().toISOString(),
changedFile: path.basename(filePath),
action: 'added'
});
console.log(`✅ Successfully updated tasks after file add: ${path.basename(filePath)}`);
} catch (error) {
console.error('❌ Error loading tasks after file add:', error);
broadcastToSSE({
type: 'error',
message: 'Failed to load tasks after file addition',
timestamp: new Date().toISOString(),
details: error.message
});
}
});
watcher.on('unlink', async (filePath) => {
console.log(`➖ File removed: ${filePath}`);
try {
const updatedTasks = await loadTasksFromPath(safeProjectPath);
broadcastToSSE({
type: 'tasks-updated',
data: updatedTasks,
timestamp: new Date().toISOString(),
changedFile: path.basename(filePath),
action: 'removed'
});
console.log(`✅ Successfully updated tasks after file removal: ${path.basename(filePath)}`);
} catch (error) {
console.error('❌ Error loading tasks after file removal:', error);
broadcastToSSE({
type: 'error',
message: 'Failed to load tasks after file removal',
timestamp: new Date().toISOString(),
details: error.message
});
}
});
// Add error handler for the watcher itself
watcher.on('error', (error) => {
console.error(`❌ File watcher error for ${safeProjectPath}:`, error);
// Clean up failed watcher
if (fileWatchers.has(safeProjectPath)) {
try {
fileWatchers.get(safeProjectPath).close();
} catch (closeError) {
console.error('Error closing failed watcher:', closeError);
}
fileWatchers.delete(safeProjectPath);
}
// Broadcast error to clients
broadcastToSSE({
type: 'watcher-error',
message: 'File watcher encountered an error',
projectPath: safeProjectPath,
timestamp: new Date().toISOString(),
details: error.message
});
});
fileWatchers.set(safeProjectPath, watcher);
console.log(`✅ Started watching project: ${safeProjectPath}`);
console.log(`📂 Watching directories: ${directoriesToWatch.join(', ')}`);
res.json({
message: 'Started watching project for changes',
projectPath: safeProjectPath,
watchedDirectories: directoriesToWatch,
mode: mode,
watching: true
});
} catch (error) {
console.error('❌ Watch project error:', error);
// Clean up any partial state
const safeProjectPath = req.body.projectPath ? path.resolve(req.body.projectPath) : null;
if (safeProjectPath) {
if (fileWatchers.has(safeProjectPath)) {
try {
fileWatchers.get(safeProjectPath).close();
} catch (closeError) {
console.error('Error cleaning up watcher after error:', closeError);
}
fileWatchers.delete(safeProjectPath);
}
if (backoffTimers.has(safeProjectPath)) {
clearTimeout(backoffTimers.get(safeProjectPath));
backoffTimers.delete(safeProjectPath);
}
}
res.status(500).json({
error: 'Failed to start watching project',
details: error.message,
watching: false
});
}
});
// Stop watching a project directory
app.post('/api/unwatch-project', (req, res) => {
try {
const { projectPath } = req.body;
if (!projectPath) {
return res.status(400).json({ error: 'Project path is required' });
}
const safeProjectPath = path.resolve(projectPath);
if (fileWatchers.has(safeProjectPath)) {
fileWatchers.get(safeProjectPath).close();
fileWatchers.delete(safeProjectPath);
res.json({
message: 'Stopped watching project',
projectPath: safeProjectPath,
watching: false
});
} else {
res.json({
message: 'Project was not being watched',
projectPath: safeProjectPath,
watching: false
});
}
} catch (error) {
console.error('Unwatch project error:', error);
res.status(500).json({ error: 'Failed to stop watching project' });
}
});
// Helper function to broadcast to all SSE connections
function broadcastToSSE(data) {
const message = `data: ${JSON.stringify(data)}\n\n`;
for (const [connectionId, res] of sseConnections) {
try {
res.write(message);
} catch (error) {
console.error(`Failed to send SSE message to connection ${connectionId}:`, error);
sseConnections.delete(connectionId);
}
}
}
// Helper function to load tasks from a project path using the resolver utility
async function loadTasksFromPath(projectPath) {
let safeProjectPath;
try {
// Validate paths
const validatedPaths = PathValidator.validateTasksDirectory(projectPath);
safeProjectPath = validatedPaths.projectPath;
} catch (validationError) {
throw new Error(`Path validation failed: ${validationError.message}`);
}
// Use the resolver utility to determine paths
const paths = resolveTaskmasterPaths(safeProjectPath);
// Check if .taskmaster exists
if (!paths.exists) {
return {
tasks: [],
projectPath: safeProjectPath,
mode: paths.mode,
message: `No .taskmaster directory found. Please ensure this is a valid TaskMaster project.`
};
}
let tasks = [];
let config = null;
let state = null;
let report = null;
let currentTag = 'master'; // default tag
// Load state.json to determine current tag
if (paths.stateJson && fs.existsSync(paths.stateJson)) {
try {
const stateData = await fs.readFile(paths.stateJson, 'utf8');
state = JSON.parse(stateData);
currentTag = state.currentTag || 'master';
console.log(`Current TaskMaster tag: ${currentTag}`);
} catch (error) {
console.warn(`Failed to read state.json: ${error.message}`);
}
}
// Load tasks.json which contains multi-tag structure
let parsedData = null;
if (fs.existsSync(paths.tasksJson)) {
try {
console.log(`Loading tasks.json from: ${paths.tasksJson}`);
const tasksJsonData = await fs.readFile(paths.tasksJson, 'utf8');
parsedData = JSON.parse(tasksJsonData);
// New multi-tag structure
if (parsedData[currentTag]) {
const tagData = parsedData[currentTag];
tasks = tagData.tasks || [];
console.log(`Loaded ${tasks.length} tasks for tag '${currentTag}'`);
} else {
console.warn(`No tasks found for tag '${currentTag}' in tasks.json`);
// Try to fallback to 'master' tag
if (parsedData.master) {
tasks = parsedData.master.tasks || [];
console.log(`Fallback: Loaded ${tasks.length} tasks from 'master' tag`);
}
}
} catch (error) {
console.error(`Failed to read or parse tasks.json: ${error.message}`);
throw new Error(`Failed to load tasks: ${error.message}`);
}
} else {
throw new Error(`No tasks.json found at ${paths.tasksJson}`);
}
// Process subtasks to ensure they have proper structure
tasks = tasks.map(task => {
// Process subtasks if they exist
if (task.subtasks && Array.isArray(task.subtasks)) {
task.subtasks = task.subtasks.map((subtask, index) => {
// Ensure subtask has all required fields
return {
id: subtask.id || index + 1,
title: subtask.title || 'Untitled Subtask',
description: subtask.description || '',
status: subtask.status || 'pending',
dependencies: subtask.dependencies || [],
details: subtask.details || '',
priority: subtask.priority || task.priority || 'medium'
};
});
}
// Ensure task has all required properties
return {
...task,
subtasks: task.subtasks || [],
dependencies: task.dependencies || [],
status: task.status || 'pending',
priority: task.priority || 'medium',
description: task.description || 'No description available',
details: task.details || '',
testStrategy: task.testStrategy || ''
};
});
// Load config.json
if (paths.configJson && fs.existsSync(paths.configJson)) {
try {
const configData = await fs.readFile(paths.configJson, 'utf8');
config = JSON.parse(configData);
// Transform config to match expected format for UI
// Extract model names from the models object
if (config.models) {
const modelNames = [];
for (const [role, modelConfig] of Object.entries(config.models)) {
if (modelConfig && modelConfig.modelId) {
modelNames.push(`${role}: ${modelConfig.modelId}`);
}
}
config.modelNames = modelNames; // For UI display
}
} catch (error) {
console.warn(`Failed to read config.json: ${error.message}`);
}
}
// Load the latest report from reports/ directory
if (paths.reportsDir && fs.existsSync(paths.reportsDir)) {
try {
const reportFiles = await fs.readdir(paths.reportsDir);
const jsonReports = reportFiles
.filter(file => file.endsWith('.json'))
.map(file => ({
name: file,
path: path.join(paths.reportsDir, file),
stats: fs.statSync(path.join(paths.reportsDir, file))
}))
.sort((a, b) => b.stats.mtime - a.stats.mtime); // Sort by modification time, newest first
if (jsonReports.length > 0) {
const latestReport = jsonReports[0];
const reportData = await fs.readFile(latestReport.path, 'utf8');
report = JSON.parse(reportData);
}
} catch (error) {
console.warn(`Failed to read reports: ${error.message}`);
}
}
return {
tasks: tasks,
projectPath: safeProjectPath,
mode: paths.mode,
currentTag: currentTag,
availableTags: parsedData ? Object.keys(parsedData) : ['master'],
...(config && { config }),
...(state && { state }),
...(report && { report })
};
}
// Get directory contents
app.get('/api/browse', async (req, res) => {
try {
const { dir = '/' } = req.query;
// Validate and sanitize the directory path
let safePath;
try {
safePath = PathValidator.validatePath(dir);
} catch (validationError) {
console.warn(`Path validation failed for browse request: ${dir}`, validationError.message);
return res.status(400).json({
error: 'Invalid directory path',
details: validationError.message
});
}
// Check if directory exists and is accessible
let stats;
try {
stats = await fs.stat(safePath);
if (!stats.isDirectory()) {
return res.status(400).json({ error: 'Path is not a directory' });
}
} catch (error) {
console.warn(`Directory access failed: ${safePath}`, error.message);
return res.status(404).json({
error: 'Directory not accessible',
details: error.code === 'ENOENT' ? 'Directory does not exist' : 'Permission denied or other access error',
errorCode: error.code
});
}
const items = await fs.readdir(safePath);
const result = [];
for (const item of items) {
try {
const itemPath = path.join(safePath, item);
const itemStats = await fs.stat(itemPath);
// Skip hidden files and system files
if (item.startsWith('.')) continue;
result.push({
name: item,
path: itemPath,
isDirectory: itemStats.isDirectory(),
size: itemStats.isDirectory() ? null : itemStats.size,
modified: itemStats.mtime
});
} catch (error) {
// Skip files we can't access
continue;
}
}
// Sort directories first, then files
result.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1;
}
return a.name.localeCompare(b.name);
});
res.json({
currentPath: safePath,
parent: path.dirname(safePath),
items: result
});
} catch (error) {
console.error('Browse error:', error);
res.status(500).json({ error: 'Failed to browse directory' });
}
});
// Load tasks from a project directory
app.get('/api/tasks', async (req, res) => {
try {
const { projectPath } = req.query;
if (!projectPath) {
return res.status(400).json({ error: 'Project path is required' });
}
// Validate the project path
let safeProjectPath;
try {
const validatedPaths = PathValidator.validateTasksDirectory(projectPath);
safeProjectPath = validatedPaths.projectPath;
} catch (validationError) {
console.warn(`Path validation failed for tasks request: ${projectPath}`, validationError.message);
return res.status(400).json({
error: 'Invalid project path',
details: validationError.message
});
}
const result = await loadTasksFromPath(safeProjectPath);
res.json(result);
} catch (error) {
console.error('Tasks loading error:', error);
res.status(500).json({
error: 'Failed to load tasks from project directory',
details: error.message,
errorType: error.name || 'UnknownError'
});
}
});
// Get system drives/roots (for cross-platform support)
app.get('/api/drives', async (req, res) => {
try {
const platform = process.platform;
const os = await import('os');
const homeDir = os.homedir();
if (platform === 'win32') {
// Windows: Get available drives
const drives = [];
for (let i = 65; i <= 90; i++) {
const drive = `${String.fromCharCode(i)}:\\`;
try {
await fs.access(drive);
drives.push({
name: drive,
path: drive,
isDirectory: true
});
} catch {
// Drive not available
}
}
// Add user home directory
if (homeDir) {
drives.unshift({
name: 'Home',
path: homeDir,
isDirectory: true
});
}
res.json({ drives, homeDirectory: homeDir });
} else {
// Unix-like systems: Start from root and user home
const drives = [
{ name: '/', path: '/', isDirectory: true },
{ name: 'home', path: '/home', isDirectory: true }
];
// Add user home directory at the beginning for easy access
if (homeDir) {
drives.unshift({
name: 'Home',
path: homeDir,
isDirectory: true
});
}
res.json({
drives,
homeDirectory: homeDir
});
}
} catch (error) {
console.error('Drives error:', error);
res.status(500).json({ error: 'Failed to get system drives' });
}
});
// Create sample tasks for a project
app.post('/api/create-sample-tasks', async (req, res) => {
try {
const { projectPath } = req.body;
if (!projectPath) {
return res.status(400).json({ error: 'Project path is required' });
}
// Validate the project path
let safeProjectPath;
try {
safeProjectPath = path.resolve(projectPath);
if (!safeProjectPath.startsWith('/') && !safeProjectPath.match(/^[A-Z]:/)) {
throw new Error('Invalid project path');
}
} catch (validationError) {
return res.status(400).json({
error: 'Invalid project path',
details: validationError.message
});
}
// Ensure the project directory exists
try {
await fs.access(safeProjectPath);
} catch (error) {
return res.status(404).json({
error: 'Project directory does not exist',
path: safeProjectPath
});
}
// Create tasks directory if it doesn't exist
const tasksDir = path.join(safeProjectPath, 'tasks');
await fs.mkdir(tasksDir, { recursive: true });
// Sample tasks data
const sampleTasks = {
tasks: [
{
id: 1,
title: "Project Setup",
description: "Set up the basic project structure and development environment",
status: "done",
priority: "high",
dependencies: [],
subtasks: [
{ id: 1, title: "Initialize repository", status: "done" },
{ id: 2, title: "Install dependencies", status: "done" },
{ id: 3, title: "Configure build tools", status: "done" }
]
},
{
id: 2,
title: "User Interface Development",
description: "Design and implement the main user interface components",
status: "in-progress",
priority: "high",
dependencies: [1],
subtasks: [
{ id: 1, title: "Create wireframes", status: "done" },
{ id: 2, title: "Implement layout components", status: "in-progress" },
{ id: 3, title: "Add styling and themes", status: "pending" }
]
},
{
id: 3,
title: "Backend API Development",
description: "Develop the server-side API endpoints and database integration",
status: "pending",
priority: "medium",
dependencies: [1],
subtasks: [
{ id: 1, title: "Design database schema", status: "pending" },
{ id: 2, title: "Implement API routes", status: "pending" },
{ id: 3, title: "Add authentication", status: "pending" }
]
},
{
id: 4,
title: "Testing and Quality Assurance",
description: "Comprehensive testing of all application features",
status: "pending",
priority: "medium",
dependencies: [2, 3],
subtasks: [
{ id: 1, title: "Unit tests", status: "pending" },
{ id: 2, title: "Integration tests", status: "pending" },
{ id: 3, title: "User acceptance testing", status: "pending" }
]
},
{
id: 5,
title: "Documentation",
description: "Create comprehensive documentation for users and developers",
status: "pending",
priority: "low",
dependencies: [4],
subtasks: [
{ id: 1, title: "User guide", status: "pending" },
{ id: 2, title: "API documentation", status: "pending" },
{ id: 3, title: "Developer setup guide", status: "pending" }
]
}
]
};
// Write the sample tasks file
const tasksFilePath = path.join(tasksDir, 'tasks.json');
await fs.writeFile(tasksFilePath, JSON.stringify(sampleTasks, null, 2));
res.json({
success: true,
message: 'Sample tasks created successfully',
tasksPath: tasksFilePath,
taskCount: sampleTasks.tasks.length
});
} catch (error) {
console.error('Create sample tasks error:', error);
res.status(500).json({
error: 'Failed to create sample tasks',
details: error.message
});
}
});
// Handle user feedback
app.post('/api/feedback', async (req, res) => {
try {
const { feedback, context, projectPath, timestamp } = req.body;
if (!feedback || !feedback.trim()) {
return res.status(400).json({ error: 'Feedback content is required' });
}
// Create feedback entry
const feedbackEntry = {
id: Date.now().toString(),
feedback: feedback.trim(),
context: context || 'general',
projectPath: projectPath || null,
timestamp: timestamp || new Date().toISOString(),
userAgent: req.headers['user-agent'] || 'unknown',
ip: req.ip || req.connection.remoteAddress || 'unknown'
};
// Log feedback to console (in a real app, you'd save to a database)
console.log('📝 User Feedback Received:', {
...feedbackEntry,
ip: '[REDACTED]' // Don't log IP for privacy
});
// You could save to a file or database here
// For now, we'll just acknowledge receipt
res.json({
success: true,
message: 'Feedback received successfully',
id: feedbackEntry.id
});
} catch (error) {
console.error('Feedback submission error:', error);
res.status(500).json({
error: 'Failed to submit feedback',
details: error.message
});
}
});
// Fallback for SPA routing - must have dist directory
app.get('*', (req, res) => {
const indexPath = path.join(__dirname, 'dist', 'index.html');
if (fs.existsSync(indexPath)) {
res.sendFile(indexPath);
} else {
res.status(500).json({
error: 'Application not built. Please build the UI first.',
hint: 'Run "pnpm build" (or "npm run build") to generate dist/. If using npx tmvisuals, the build should happen automatically in dev.'
});
}
});
app.listen(PORT, () => {
console.log(`\n🚀 TaskMaster Visualizer Server`);
console.log(`🌐 App and API running on: http://localhost:${PORT}`);
console.log(`⚡ Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`📁 Serving from: ${distPath}`);
});