-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCOMPLETE_BUILD_INSTRUCTIONS_FOR_THE_ENTIRE_JAEGIS_WEB_OS.docx
More file actions
2138 lines (1829 loc) · 74.5 KB
/
COMPLETE_BUILD_INSTRUCTIONS_FOR_THE_ENTIRE_JAEGIS_WEB_OS.docx
File metadata and controls
2138 lines (1829 loc) · 74.5 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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
🚀 JAEGIS OS v2.2.0 - Unified AI Developer Implementation Prompt
Objective: Implement the JAEGIS AI-Powered Web OS (v2.2.0) from scratch. This document provides the complete, step-by-step instructions, including all code, configurations, dependencies, and critical fixes. The final application must be fully functional, error-free, and production-ready.
Project Start Date: 06 AUGUST 2025 (This should adapt automatically with each new day).
Core Principles:
No Mock Data or Placeholders: All code and configuration must be complete and directly usable.
Error-Free Implementation: The final code must be free of linting, syntax, runtime, and module errors.
Self-Contained: This document is the single source of truth. No external file access is required.
Phase 1: Project Initialization & Setup
This phase is foundational. It covers the initial setup of the Next.js 15 project, the installation of all necessary dependencies to build a modern, interactive web application, and the complete configuration of the database using Prisma ORM. Following these steps precisely is crucial for a stable and scalable system.
Task 1.1: Initialize Next.js 15 Project
Subtask 1.1.1: Create the Project
Initialize a new Next.js 15 project. We will use TypeScript for type safety, Tailwind CSS for styling, and ESLint for code quality, all configured with the modern App Router.
npx create-next-app@latest jaegis-os --typescript --tailwind --eslint --app
cd jaegis-os
Subtask 1.1.2: Install All Dependencies
Install all required production and development dependencies. This curated list includes packages for state management (zustand), animations (framer-motion), UI components (shadcn/ui dependencies), security (bcryptjs, jsonwebtoken), and AI integration (z-ai-web-dev-sdk).
npm install zustand framer-motion lucide-react @radix-ui/react-slot class-variance-authority clsx tailwind-merge socket.io socket.io-client bcryptjs jsonwebtoken z-ai-web-dev-sdk @prisma/client
npm install -D @types/node @types/bcryptjs @types/jsonwebtoken prisma
Subtask 1.1.3: Initialize Shadcn/UI
Set up the shadcn/ui component library, which provides a set of reusable and accessible components that we will use to build the OS interface.
npx shadcn-ui@latest init
When prompted, accept the default configuration. Then, add the necessary components which will form the building blocks of our UI, from simple buttons to complex dialogs.
npx shadcn-ui@latest add button card input label tabs alert dialog toast
Task 1.2: Database Setup with Prisma
Subtask 1.2.1: Initialize Prisma
Initialize Prisma in the project. This will create the prisma directory containing the schema file and set up the project for database access using SQLite for simplicity in development.
npx prisma init --datasource-provider sqlite
Subtask 1.2.2: Define the Database Schema
Replace the contents of prisma/schema.prisma with the complete schema below. This schema defines the core data models for our application: User for account information, Session for managing persistent logins with refresh tokens, and Application for defining the apps within the OS.
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = "file:./dev.db" // Specifies the local SQLite database file
}
// User model defines the structure for user accounts
model User {
id String @id @default(cuid())
username String @unique
email String @unique
password String // Hashed password
role UserRole @default(USER)
permissions Json // Flexible JSON field for a permission system
isActive Boolean @default(true)
lastLogin DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Establishes a one-to-many relationship with Session and Application models
sessions Session[]
applications Application[]
}
// Session model tracks user login sessions for persistent authentication
model Session {
id String @id @default(cuid())
userId String
refreshToken String @unique // The secure refresh token
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Defines the many-to-one relationship back to the User
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
// Application model defines the applications available within the OS
model Application {
id String @id @default(cuid())
name String
description String
icon String
category ApplicationCategory
version String
author String
windowType WindowType // Defines the type of window to open
permissions Json
isSystemApp Boolean @default(false)
config Json // Application-specific configuration
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Each application is associated with a user (e.g., creator)
userId String
user User @relation(fields: [userId], references: [id])
}
// Enumerations for structured, predefined roles and categories
enum UserRole {
ADMIN
USER
RESEARCHER
}
enum ApplicationCategory {
SYSTEM
UTILITY
PRODUCTIVITY
DEVELOPMENT
AI_SERVICE
}
enum WindowType {
FILE_EXPLORER
MONITORING
TERMINAL
SETTINGS
TASK_MANAGER
AGENT_MANAGER
SERVICE_MANAGER
CUSTOM
}
Subtask 1.2.3: Generate Prisma Client and Push Schema
Generate the Prisma client based on the schema and apply (push) these definitions to the SQLite database, creating the necessary tables.
npx prisma generate
npx prisma db push
Subtask 1.2.4: Create Database Seeder
Create a script to seed the database with default admin and user accounts for immediate testing and development. Create prisma/seed.ts.
// prisma/seed.ts
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
const prisma = new PrismaClient();
async function main() {
console.log('Start seeding database...');
// Hash passwords securely using bcrypt
const adminPassword = await bcrypt.hash('admin123', 10);
const userPassword = await bcrypt.hash('user123', 10);
// Create an Admin User with full permissions
await prisma.user.upsert({
where: { username: 'admin' },
update: {}, // Do nothing if user exists
create: {
username: 'admin',
email: 'admin@jaegis.os',
password: adminPassword,
role: 'ADMIN',
permissions: [
'system_access', 'agent_management', 'nlds_access',
'data_processing', 'llm_access', 'ai_processing',
'deployment_access', 'system_config', 'forge_access',
'tool_management', 'file_system_access', 'command_execution',
'system_monitoring', 'performance_data'
],
},
});
// Create a Standard User with limited permissions
await prisma.user.upsert({
where: { username: 'user' },
update: {},
create: {
username: 'user',
email: 'user@jaegis.os',
password: userPassword,
role: 'USER',
permissions: ['system_access', 'file_system_access'],
},
});
console.log('Seeding finished successfully.');
}
main()
.catch((e) => {
console.error('An error occurred during seeding:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
Subtask 1.2.5: Update package.json with Seed Command
Add the seed script to your package.json for easy execution. This requires ts-node to run the TypeScript seed file directly.
npm install -D ts-node
```json
// package.json
{
// ... other properties
"prisma": {
"seed": "ts-node --compiler-options '{\"module\":\"CommonJS\"}' prisma/seed.ts"
},
"scripts": {
// ... other scripts
"db:seed": "npx prisma db seed"
},
// ... other properties
}
Subtask 1.2.6: Run the Seed Script
Execute the seed command to populate the database with the default users.
npm run db:seed
Task 1.3: Project Configuration
Subtask 1.3.1: Configure next.config.mjs
Replace the content of next.config.mjs with the optimized configuration below to enhance performance and manage build settings.
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
typescript: {
// Prevent build failures due to third-party type issues, useful in complex projects.
ignoreBuildErrors: true,
},
// Set to false to prevent components from rendering twice in development, which can be helpful for debugging.
reactStrictMode: false,
experimental: {
serverActions: {
allowedOrigins: ['localhost:3000'],
},
// Reduces bundle size by optimizing imports from these libraries.
optimizePackageImports: ['lucide-react', 'framer-motion'],
},
images: {
// Enables modern image formats for better performance.
formats: ['image/webp', 'image/avif'],
},
// Enables gzip compression for smaller asset sizes.
compress: true,
// Disables the "Powered by Next.js" header for security.
poweredByHeader: false,
eslint: {
// Speeds up production builds by skipping linting.
ignoreDuringBuilds: true,
},
};
export default nextConfig;
Subtask 1.3.2: Configure Environment Variables
Create a .env.local file in the root of your project for sensitive keys and environment-specific settings.
# .env.local
# Authentication secrets. Use strong, randomly generated strings in production.
JWT_SECRET="JAEGIS-!s-a-s3cr3t-k3y-f0r-d3v"
REFRESH_TOKEN_SECRET="JAEGIS-!s-a-s3cr3t-r3fr3sh-k3y-f0r-d3v"
# AI Services (Replace with your actual key from the AI service provider)
ZAI_API_KEY="your-zai-api-key-here"
# Application settings
NODE_ENV="development"
PORT="3000"
NEXT_PUBLIC_SOCKET_URL="http://localhost:3000"
Phase 2: Core System Implementation
This phase involves defining the core data structures for the entire application in a central location and setting up the global state management using Zustand, a lightweight and powerful state management library.
Task 2.1: Create Core Type Definitions
Create the file src/core/types.ts to house all shared TypeScript interfaces and types. This promotes consistency and reusability across the codebase.
// src/core/types.ts
// Defines the shape of a user object, used throughout the application.
export interface User {
id: string;
username: string;
email: string;
role: UserRole;
permissions: Permission[];
isActive: boolean;
createdAt: Date;
updatedAt: Date;
lastLogin?: Date;
}
// Defines the available user roles in the system.
export type UserRole = 'ADMIN' | 'USER' | 'RESEARCHER';
// Defines a comprehensive list of permissions for role-based access control.
export type Permission =
| 'system_access' | 'agent_management' | 'nlds_access' | 'data_processing'
| 'llm_access' | 'ai_processing' | 'deployment_access' | 'system_config'
| 'forge_access' | 'tool_management' | 'file_system_access'
| 'command_execution' | 'system_monitoring' | 'performance_data';
// Describes an application that can be run within the OS.
export interface Application {
id: string;
name: string;
description: string;
icon: string;
category: ApplicationCategory;
version: string;
author: string;
windowType: WindowType;
permissions: Permission[];
isSystemApp: boolean;
config: any;
createdAt: Date;
updatedAt: Date;
}
// Categories for organizing applications.
export type ApplicationCategory =
| 'SYSTEM' | 'UTILITY' | 'PRODUCTIVITY' | 'DEVELOPMENT' | 'AI_SERVICE';
// Defines the type of content a window will render.
export type WindowType =
| 'FILE_EXPLORER' | 'MONITORING' | 'TERMINAL' | 'SETTINGS' | 'TASK_MANAGER'
| 'AGENT_MANAGER' | 'SERVICE_MANAGER' | 'CUSTOM';
// Represents the state of a single window on the desktop.
export interface WindowState {
id: string;
title: string;
type: WindowType;
content: WindowContent;
position: { x: number; y: number };
size: { width: number; height: number };
isMinimized: boolean;
isMaximized: boolean;
isActive: boolean;
zIndex: number;
}
// Defines the content to be displayed within a window.
export interface WindowContent {
type: 'component' | 'url' | 'custom';
component?: string; // Name of the React component to render
url?: string;
data?: any; // Props or data to pass to the component
}
// Represents a system notification.
export interface Notification {
id: string;
title: string;
message: string;
type: NotificationType;
priority: NotificationPriority;
isRead: boolean;
timestamp: Date;
action?: {
label: string;
callback: () => void;
};
}
export type NotificationType = 'system' | 'service' | 'alert' | 'info';
export type NotificationPriority = 'low' | 'medium' | 'high' | 'critical';
// Represents real-time system performance metrics.
export interface SystemMetrics {
cpu: { usage: number; temperature: number; };
memory: { total: number; used: number; percentage: number; };
disk: { total: number; used: number; percentage: number; };
network: { latency: number; bandwidth: number; };
agents: { active: number; total: number; };
uptime: number;
}
// Defines an AI tool that can be used by AI agents.
export interface AITool {
id: string;
name: string;
description: string;
category: string;
version: string;
parameters: ToolParameter[];
capabilities: string[];
status: 'active' | 'inactive' | 'deprecated';
createdAt: Date;
updatedAt: Date;
}
// Defines a parameter for an AI tool.
export interface ToolParameter {
name: string;
type: 'string' | 'number' | 'boolean' | 'object' | 'array';
description: string;
required: boolean;
defaultValue?: any;
}
// Defines an AI agent.
export interface AIAgent {
id: string;
name: string;
description: string;
type: 'chat' | 'task' | 'analysis' | 'automation';
model: string;
tools: string[];
capabilities: string[];
status: 'active' | 'inactive' | 'training';
performance: {
accuracy: number;
speed: number;
reliability: number;
};
createdAt: Date;
updatedAt: Date;
}
// Represents a node in the Neural Logic Distribution System (NLDS).
export interface NLDSNode {
id: string;
name: string;
type: 'input' | 'processing' | 'output' | 'memory';
connections: string[];
state: any;
performance: {
throughput: number;
latency: number;
accuracy: number;
};
status: 'active' | 'inactive' | 'error';
}
// Represents a cognitive operation performed by the AI.
export interface CognitiveOperation {
id: string;
name: string;
type: 'analysis' | 'synthesis' | 'prediction' | 'optimization';
input: any;
output?: any;
status: 'pending' | 'processing' | 'completed' | 'error';
progress: number;
startTime: Date;
endTime?: Date;
error?: string;
}
Task 2.2: Implement Zustand State Management
Create the directory src/lib/stores and add the following store files. These stores are optimized to prevent common performance issues like infinite re-renders.
Subtask 2.2.1: auth-store.ts
// src/lib/stores/auth-store.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { User } from '@/core/types';
interface AuthState {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
login: (username: string, password: string) => Promise<void>;
register: (data: { username: string; email: string; password: string }) => Promise<void>;
logout: () => Promise<void>;
refresh: () => Promise<void>;
clearError: () => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
isAuthenticated: false,
isLoading: true, // Start with loading true to check session on app load
error: null,
login: async (username, password) => {
set({ isLoading: true, error: null });
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (!response.ok) throw new Error('Login failed');
const { user } = await response.json();
set({ user, isAuthenticated: true, isLoading: false });
} catch (error) {
set({ error: error instanceof Error ? error.message : 'Login failed', isLoading: false });
}
},
register: async (data) => {
set({ isLoading: true, error: null });
try {
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!response.ok) throw new Error('Registration failed');
const { user } = await response.json();
set({ user, isAuthenticated: true, isLoading: false });
} catch (error) {
set({ error: error instanceof Error ? error.message : 'Registration failed', isLoading: false });
}
},
logout: async () => {
try {
await fetch('/api/auth/logout', { method: 'POST' });
} catch (error) {
console.error('Logout error:', error);
}
set({ user: null, isAuthenticated: false, error: null });
},
refresh: async () => {
set({ isLoading: true });
try {
const response = await fetch('/api/auth/refresh', { method: 'POST' });
if (response.ok) {
const { user } = await response.json();
set({ user, isAuthenticated: true });
} else {
set({ user: null, isAuthenticated: false });
}
} catch (error) {
console.error('Refresh error:', error);
set({ user: null, isAuthenticated: false });
} finally {
set({ isLoading: false });
}
},
clearError: () => set({ error: null }),
}),
{
name: 'jaegis-auth-storage', // Key for localStorage persistence
partialize: (state) => ({ user: state.user, isAuthenticated: state.isAuthenticated }),
}
)
);
Subtask 2.2.2: window-store.ts
// src/lib/stores/window-store.ts
import { create } from 'zustand';
import { WindowState, WindowType, WindowContent } from '@/core/types';
interface WindowManagerStore {
windows: WindowState[];
activeWindowId: string | null;
nextZIndex: number;
openWindow: (config: Omit<WindowState, 'id' | 'isMinimized' | 'isMaximized' | 'isActive' | 'zIndex'>) => string;
closeWindow: (windowId: string) => void;
minimizeWindow: (windowId: string) => void;
maximizeWindow: (windowId: string) => void;
restoreWindow: (windowId: string) => void;
focusWindow: (windowId: string) => void;
updateWindowPosition: (windowId: string, position: { x: number; y: number }) => void;
updateWindowSize: (windowId: string, size: { width: number; height: number }) => void;
}
export const useWindowManager = create<WindowManagerStore>((set, get) => ({
windows: [],
activeWindowId: null,
nextZIndex: 100,
openWindow: (config) => {
const newWindowId = `window-${Date.now()}`;
const nextZIndex = get().nextZIndex;
const newWindow: WindowState = {
id: newWindowId,
...config,
position: config.position || { x: Math.random() * 200 + 50, y: Math.random() * 200 + 50 },
size: config.size || { width: 800, height: 600 },
isMinimized: false,
isMaximized: false,
isActive: true,
zIndex: nextZIndex + 1,
};
set((state) => ({
windows: state.windows.map(w => ({ ...w, isActive: false })).concat(newWindow),
activeWindowId: newWindowId,
nextZIndex: nextZIndex + 1,
}));
return newWindowId;
},
closeWindow: (windowId) => {
set((state) => ({
windows: state.windows.filter((w) => w.id !== windowId),
activeWindowId: state.activeWindowId === windowId ? null : state.activeWindowId,
}));
},
focusWindow: (windowId) => {
const state = get();
if (state.activeWindowId === windowId) return;
const nextZIndex = state.nextZIndex;
set({
windows: state.windows.map((w) => ({
...w,
isActive: w.id === windowId,
zIndex: w.id === windowId ? nextZIndex + 1 : w.zIndex,
})),
activeWindowId: windowId,
nextZIndex: nextZIndex + 1,
});
},
minimizeWindow: (windowId) => {
set((state) => ({
windows: state.windows.map((w) =>
w.id === windowId ? { ...w, isMinimized: true, isActive: false } : w
),
activeWindowId: state.activeWindowId === windowId ? null : state.activeWindowId,
}));
},
maximizeWindow: (windowId) => {
get().focusWindow(windowId);
set((state) => ({
windows: state.windows.map((w) =>
w.id === windowId ? { ...w, isMaximized: true, isMinimized: false } : w
),
}));
},
restoreWindow: (windowId) => {
get().focusWindow(windowId);
set((state) => ({
windows: state.windows.map((w) =>
w.id === windowId ? { ...w, isMaximized: false, isMinimized: false } : w
),
}));
},
updateWindowPosition: (windowId, position) => {
set(state => ({
windows: state.windows.map(w => w.id === windowId ? { ...w, position } : w)
}));
},
updateWindowSize: (windowId, size) => {
set(state => ({
windows: state.windows.map(w => w.id === windowId ? { ...w, size } : w)
}));
},
}));
Subtask 2.2.3: notification-store.ts
// src/lib/stores/notification-store.ts
import { create } from 'zustand';
import { Notification } from '@/core/types';
interface NotificationState {
notifications: Notification[];
addNotification: (notification: Omit<Notification, 'id' | 'timestamp' | 'isRead'>) => string;
removeNotification: (notificationId: string) => void;
markAsRead: (notificationId: string) => void;
clearAll: () => void;
}
export const useNotificationStore = create<NotificationState>((set) => ({
notifications: [],
addNotification: (notification) => {
const newNotification: Notification = {
...notification,
id: `notification-${Date.now()}`,
timestamp: new Date(),
isRead: false,
};
set((state) => ({
notifications: [newNotification, ...state.notifications].slice(0, 20), // Limit to 20 notifications
}));
return newNotification.id;
},
removeNotification: (notificationId) => {
set((state) => ({
notifications: state.notifications.filter((n) => n.id !== notificationId),
}));
},
markAsRead: (notificationId) => {
set((state) => ({
notifications: state.notifications.map((n) =>
n.id === notificationId ? { ...n, isRead: true } : n
),
}));
},
clearAll: () => {
set({ notifications: [] });
},
}));
Subtask 2.2.4: system-store.ts
// src/lib/stores/system-store.ts
import { create } from 'zustand';
import { SystemMetrics } from '@/core/types';
interface SystemState {
systemMetrics: SystemMetrics | null;
isOnline: boolean;
updateSystemMetrics: (metrics: SystemMetrics) => void;
setOnlineStatus: (isOnline: boolean) => void;
}
export const useSystemStore = create<SystemState>((set) => ({
systemMetrics: {
cpu: { usage: 0, temperature: 0 },
memory: { total: 0, used: 0, percentage: 0 },
disk: { total: 0, used: 0, percentage: 0 },
network: { latency: 0, bandwidth: 0 },
agents: { active: 0, total: 0 },
uptime: 0,
},
isOnline: true,
updateSystemMetrics: (metrics) => set({ systemMetrics: metrics }),
setOnlineStatus: (isOnline) => set({ isOnline }),
}));
Task 2.3: Create Database Client Singleton
Create the file src/lib/db.ts to ensure only one instance of PrismaClient is used across the application, preventing connection pool exhaustion.
// src/lib/db.ts
import { PrismaClient } from '@prisma/client';
// Add prisma to the NodeJS global type
declare global {
var prisma: PrismaClient | undefined;
}
// Prevent multiple instances of Prisma Client in development
export const db = globalThis.prisma || new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
if (process.env.NODE_ENV !== 'production') {
globalThis.prisma = db;
}
Phase 3: Authentication System
This phase focuses on building the backend API routes for user authentication, including login, registration, session refresh, and logout functionalities. This is a critical step to secure the application.
Task 3.1: Create Authentication API Routes
Create the directory src/app/api/auth and add the following route handler files.
Subtask 3.1.1: Login Route (src/app/api/auth/login/route.ts)
This endpoint handles user login, verifies credentials, and returns JWT access and refresh tokens.
// src/app/api/auth/login/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { cookies } from 'next/headers';
const JWT_SECRET = process.env.JWT_SECRET!;
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET!;
export async function POST(request: NextRequest) {
try {
const { username, password } = await request.json();
if (!username || !password) {
return NextResponse.json({ error: 'Username and password are required' }, { status: 400 });
}
const user = await db.user.findUnique({ where: { username } });
if (!user || !user.isActive) {
return NextResponse.json({ error: 'Invalid credentials or inactive user' }, { status: 401 });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
JWT_SECRET,
{ expiresIn: '15m' }
);
const refreshToken = jwt.sign(
{ userId: user.id },
REFRESH_TOKEN_SECRET,
{ expiresIn: '7d' }
);
// Store refresh token in a secure, httpOnly cookie
cookies().set('refreshToken', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60, // 7 days
path: '/',
});
// Store session in database for server-side validation
await db.session.create({
data: {
userId: user.id,
refreshToken,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
},
});
await db.user.update({
where: { id: user.id },
data: { lastLogin: new Date() },
});
const { password: _, ...userWithoutPassword } = user;
return NextResponse.json({ user: userWithoutPassword, accessToken });
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
Subtask 3.1.2: Registration Route (src/app/api/auth/register/route.ts)
This endpoint handles new user registration, hashes the password, and stores the user in the database.
// src/app/api/auth/register/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import bcrypt from 'bcryptjs';
export async function POST(request: NextRequest) {
try {
const { username, email, password } = await request.json();
if (!username || !email || !password) {
return NextResponse.json({ error: 'All fields are required' }, { status: 400 });
}
const existingUser = await db.user.findFirst({
where: { OR: [{ username }, { email }] },
});
if (existingUser) {
return NextResponse.json({ error: 'User with this username or email already exists' }, { status: 409 });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await db.user.create({
data: {
username,
email,
password: hashedPassword,
role: 'USER', // Default role
permissions: ['system_access'], // Default permissions
},
});
const { password: _, ...userWithoutPassword } = user;
return NextResponse.json({ user: userWithoutPassword }, { status: 201 });
} catch (error) {
console.error('Registration error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
Subtask 3.1.3: Refresh Token Route (src/app/api/auth/refresh/route.ts)
This endpoint uses the httpOnly refresh token to issue a new access token, allowing the user to stay logged in.
// src/app/api/auth/refresh/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import jwt from 'jsonwebtoken';
import { cookies } from 'next/headers';
const JWT_SECRET = process.env.JWT_SECRET!;
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET!;
export async function POST(request: NextRequest) {
try {
const cookieStore = cookies();
const refreshToken = cookieStore.get('refreshToken')?.value;
if (!refreshToken) {
return NextResponse.json({ error: 'Refresh token not found' }, { status: 401 });
}
let decoded: any;
try {
decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET);
} catch (error) {
return NextResponse.json({ error: 'Invalid refresh token' }, { status: 401 });
}
const session = await db.session.findFirst({
where: {
userId: decoded.userId,
refreshToken,
expiresAt: { gt: new Date() },
},
});
if (!session) {
return NextResponse.json({ error: 'Session not found or expired' }, { status: 401 });
}
const user = await db.user.findUnique({ where: { id: decoded.userId } });
if (!user || !user.isActive) {
return NextResponse.json({ error: 'User not found or inactive' }, { status: 401 });
}
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
JWT_SECRET,
{ expiresIn: '15m' }
);
const { password: _, ...userWithoutPassword } = user;
return NextResponse.json({ user: userWithoutPassword, accessToken });
} catch (error) {
console.error('Refresh token error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
Subtask 3.1.4: Logout Route (src/app/api/auth/logout/route.ts)
This endpoint clears the user's session from the database and removes the httpOnly cookie.
// src/app/api/auth/logout/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { cookies } from 'next/headers';
export async function POST(request: NextRequest) {
try {
const cookieStore = cookies();
const refreshToken = cookieStore.get('refreshToken')?.value;
if (refreshToken) {
await db.session.deleteMany({
where: { refreshToken },
});
}
cookieStore.delete('refreshToken');
return NextResponse.json({ message: 'Logged out successfully' });
} catch (error) {
console.error('Logout error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
Phase 4: UI and Desktop Environment
This phase involves building the frontend components that create the JAEGIS OS desktop experience, including the main layout, login forms, and the desktop environment itself.
Task 4.1: Global Layout and Styles
Subtask 4.1.1: Update Global Styles (src/app/globals.css)
Add base styles for the application, including a dark theme and custom scrollbars.
/* src/app/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;