veltrixcode commited on
Commit
5780ed6
·
verified ·
1 Parent(s): 847e4ab

Upload 16 files

Browse files
client/public/index.html CHANGED
@@ -1,190 +1,187 @@
1
  <!doctype html>
2
  <html lang="en">
 
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>Python IDE</title>
7
  <link rel="stylesheet" href="/styles.css">
 
 
8
  <script>/* WARNING: Hardcoding secrets is unsafe. Use env vars in production. */</script>
9
  <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/loader.min.js"></script>
10
  <script>
11
- window.MonacoEnvironment = { getWorkerUrl: () => proxy }; let proxy = URL.createObjectURL(new Blob([`self.MonacoEnvironment={baseUrl:'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/'};importScripts('https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/base/worker/workerMain.min.js');`],{type:'text/javascript'}));
12
- </script>
13
- <script defer src="/script.js"></script>
14
- <style>body{margin:0}</style>
15
- <meta name="color-scheme" content="dark light">
16
- <link rel="icon" href="data:,">
17
- <script>
18
- // Use relative API base so reverse proxies work: same origin by default
19
  window.API_BASE = '';
20
  </script>
21
- <style>
22
- :root { --bg: #0b0e17; --panel:#141827; --panel2:#0f1320; --text:#e8e8ef; --muted:#9095a3; --accent:#4f8cff; --success:#2bb673; --shadow: 0 8px 32px rgba(0,0,0,.35); }
23
- body { background: radial-gradient(1200px 800px at 80% -10%, rgba(79,140,255,.12), transparent), var(--bg); color: var(--text); font-family: -apple-system, system-ui, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, sans-serif; }
24
- .app { display: grid; grid-template-rows: 52px 1fr 220px; height: 100vh; }
25
- .topbar { display:flex; align-items:center; gap:12px; padding:0 16px; border-bottom:1px solid #1f2433; background:linear-gradient(180deg, #0f1320, #0d101a); position:sticky; top:0; z-index:3 }
26
- .brand { font-weight:600; letter-spacing:.3px; }
27
- .top { display: grid; grid-template-columns: 280px 1fr; min-height: 0; gap: 10px; padding:10px }
28
- .sidebar { background: var(--panel); border:1px solid #1f2433; border-radius:12px; overflow:auto; box-shadow: var(--shadow); }
29
- .editor { min-width: 0; min-height: 0; background: var(--panel); border:1px solid #1f2433; border-radius:12px; box-shadow: var(--shadow) }
30
- #editor { width: 100%; height: 100%; }
31
- .terminal { margin:10px; background: #0a0c12; border:1px solid #1f2433; border-radius:12px; display:flex; flex-direction:column; box-shadow: var(--shadow) }
32
- .term-chrome { display:flex; align-items:center; gap:8px; padding:8px 10px; border-bottom:1px solid #1f2433; background: linear-gradient(180deg, #0f1320, #0b0f1a); border-top-left-radius:12px; border-top-right-radius:12px }
33
- .dots { display:flex; gap:6px }
34
- .dot { width:10px; height:10px; border-radius:50%; }
35
- .dot.red { background:#ff5f56 }
36
- .dot.yellow { background:#ffbd2e }
37
- .dot.green { background:#27c93f }
38
- .term-title { color:#9aa2b2; font-size:12px }
39
- #output { flex:1; overflow:auto; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; padding: 12px; white-space: pre-wrap; color:#e6e6e6; background:#0a0c12 }
40
- #output .line { line-height: 1.45 }
41
- #output .ansi-gray { color:#8a8f98 }
42
- #output .ansi-red { color:#ff6b6b }
43
- #output .ansi-green { color:#2ecc71 }
44
- #output .ansi-yellow { color:#f1c40f }
45
- #output .ansi-blue { color:#4f8cff }
46
- #output .ansi-magenta { color:#c678dd }
47
- #output .ansi-cyan { color:#56b6c2 }
48
- #output .ansi-bold { font-weight:600 }
49
- .prompt { display:flex; gap:8px; align-items:center; padding-top:4px }
50
- .ps1 { color:#9aa2b2 }
51
- .prompt input { flex:1; background:transparent; border:0; outline:none; color:#e6e6e6; font-family: inherit; font-size: 12px }
52
- .term-input input { flex:1; background:#0f1320; border:1px solid #1f2433; color:var(--text); padding:10px; border-radius:8px; outline:none }
53
- .term-input button, .toolbar button, .topbar button { background:linear-gradient(180deg, #2a6bff, #1f56d6); color:#fff; border:0; padding:8px 12px; border-radius:8px; font-weight:600; letter-spacing:.2px }
54
- .topbar #runBtnTop { background: linear-gradient(180deg, var(--success), #1f9a60) }
55
- .file-list { list-style:none; margin:0; padding:8px; font-size: 12px; }
56
- .file-item { padding:6px 8px; cursor:pointer; border-radius:8px; display:flex; align-items:center; gap:8px }
57
- .file-item:hover { background:#1a2133 }
58
- .toolbar { display:flex; gap:8px; padding:8px; border-bottom:1px solid #1f2433 }
59
- .toolbar button { background:#23283b; color:var(--text); border:1px solid #1f2433; padding:8px 10px; border-radius:8px; font-size:12px }
60
- .auth-modal { position:fixed; inset:0; background:rgba(0,0,0,.6); display:flex; align-items:center; justify-content:center; }
61
- .auth-card { background:#161925; padding:20px; border-radius:12px; width:90%; max-width:360px; box-shadow: var(--shadow) }
62
- .auth-card input { width:100%; margin:6px 0; padding:10px; background:#0f1320; border:1px solid #1f2433; color:var(--text); border-radius:8px }
63
- .auth-card button { width:100%; padding:12px; margin-top:8px; background:linear-gradient(180deg, #2a6bff, #1f56d6); border:0; color:white; border-radius:10px }
64
- .ai-fix { position:absolute; left:50%; transform:translateX(-50%); bottom:260px; z-index:5 }
65
- .ai-fix button { background:#ff5c5c; color:white; padding:12px 16px; border:0; border-radius:12px; font-weight:600 }
66
- @media (max-width: 800px) { .top { grid-template-columns: 1fr } .sidebar { height: 160px } .app { grid-template-rows: 44px 1fr 40vh } }
67
- .ctx { position:fixed; background:#111422; border:1px solid #2a2f3a; border-radius:8px; box-shadow:0 4px 24px rgba(0,0,0,.4); padding:6px; display:none; z-index:10 }
68
- .ctx button { display:block; width:100%; text-align:left; background:transparent; border:0; color:#e6e6e6; padding:8px 10px; border-radius:6px; font-size:12px }
69
- .ctx button:hover { background:#23283b }
70
- </style>
71
- <style>
72
- .diff-modal { position:fixed; inset:0; background:rgba(0,0,0,.6); display:none; align-items:center; justify-content:center; }
73
- .diff-card { background:#161925; padding:16px; border-radius:12px; width:95%; max-width:800px; max-height:80vh; overflow:auto }
74
- .diff-card pre { white-space:pre-wrap; background:#0f1320; padding:12px; border-radius:8px; font-size:12px }
75
- .loading { position:fixed; inset:0; background:rgba(0,0,0,.5); display:none; align-items:center; justify-content:center; z-index:20 }
76
- .loading .card { background:#121624; padding:16px 20px; border-radius:12px; color:#e6e6e6; display:flex; align-items:center; gap:12px; box-shadow: var(--shadow) }
77
- .spinner { width:18px; height:18px; border:3px solid #2b2f45; border-top-color:#4f8cff; border-radius:50%; animation:spin 1s linear infinite }
78
- @keyframes spin { to { transform: rotate(360deg) } }
79
- </style>
80
- </head>
81
  <body>
82
  <div class="app">
 
83
  <div class="topbar">
84
- <div class="brand">PyRunner</div>
85
- <div style="flex:1"></div>
86
- <button id="artBtn" style="background:#3a87f7; color:#fff; border:0; padding:6px 10px; border-radius:8px; font-size:12px">Artifacts</button>
87
- <button id="genBtn" style="background:#4f8cff; color:#fff; border:0; padding:6px 10px; border-radius:8px; font-size:12px">Generate with AI</button>
88
- <button id="editBtn" style="background:#8a5cff; color:#fff; border:0; padding:6px 10px; border-radius:8px; font-size:12px">Edit with AI</button>
89
- <button id="runBtnTop" style="background:#2bb673; color:#fff; border:0; padding:6px 10px; border-radius:8px; font-size:12px">Run main.py</button>
 
 
 
 
 
 
 
 
90
  </div>
 
 
91
  <div class="top">
 
92
  <div class="sidebar">
93
  <div class="toolbar">
94
- <button id="newFileBtn">New</button>
95
- <button id="deleteFileBtn">Delete</button>
96
- <button id="runBtn">Run current</button>
97
  </div>
98
  <ul id="files" class="file-list"></ul>
99
  </div>
100
- <div class="editor"><div id="editor"></div></div>
 
 
 
 
 
 
 
 
 
 
 
101
  </div>
 
 
102
  <div class="terminal">
103
- <div class="term-chrome" id="termChrome">
104
- <div class="dots"><div class="dot red"></div><div class="dot yellow"></div><div class="dot green"></div></div>
105
- <div class="term-title" id="termTitle">bash — /workspace</div>
 
 
 
 
106
  </div>
107
  <div id="output"></div>
108
  </div>
109
  </div>
110
- <div class="ctx" id="ctxMenu"></div>
111
- <div class="loading" id="loading"><div class="card"><div class="spinner"></div><div id="loadingMsg">Working…</div></div></div>
112
- <div class="ai-fix" style="display:none" id="aiFix"><button>GET FIX WITH AI</button></div>
113
- <div id="authModal" class="auth-modal" style="display:flex">
114
- <div class="auth-card" style="width:90%;max-width:420px">
115
- <h3 style="margin-top:0;margin-bottom:10px">Welcome</h3>
116
- <p style="margin:0 0 12px;color:#9095a3;font-size:13px">Sign in or create an account to continue. For signup, please provide your details.</p>
117
- <div style="display:grid; grid-template-columns: 1fr 1fr; gap:8px">
118
- <input id="authName" placeholder="Full name" type="text"/>
119
- <input id="authClass" placeholder="Class" type="text"/>
120
- <input id="authSection" placeholder="Section" type="text"/>
121
- <span></span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  </div>
123
- <input id="email" placeholder="Email" type="email"/>
124
- <input id="password" placeholder="Password" type="password"/>
125
- <div style="display:flex; gap:8px; margin-top:8px">
126
- <button id="signin" style="flex:1">Sign In</button>
127
- <button id="signup" style="flex:1; background:#2bb673">Sign Up</button>
128
  </div>
129
- <small style="color:var(--muted); display:block; margin-top:8px">Your session uses a secure cookie. Name/Class/Section appear in your terminal prompt.</small>
 
 
 
 
 
 
 
 
 
 
 
130
  </div>
131
  </div>
132
 
133
- <div id="diffModal" class="diff-modal">
134
- <div class="diff-card">
135
- <h3>AI Fix Preview</h3>
136
- <div id="aiReason" style="color:#9095a3; font-size:12px; margin-bottom:8px"></div>
137
- <div id="diffBody"></div>
138
- <div style="display:flex; gap:8px; margin-top:8px">
139
- <button id="applyFix" style="background:#2bb673; color:#fff; border:0; padding:8px 12px; border-radius:8px">Apply Fix</button>
140
- <button id="closeDiff" style="background:#23283b; color:#fff; border:0; padding:8px 12px; border-radius:8px">Close</button>
 
141
  </div>
142
  </div>
143
  </div>
144
- <!-- AI Generate Modal -->
145
- <div id="genModal" class="diff-modal" style="display:none">
146
- <div class="diff-card" style="max-width:720px">
147
- <div style="display:flex;align-items:center;justify-content:space-between;gap:8px">
148
- <h3 style="margin:0">Generate Code with AI</h3>
149
- <button id="genClose" style="background:#23283b; color:#fff; border:0; padding:6px 10px; border-radius:8px">Close</button>
150
- </div>
151
- <p style="margin:10px 0 6px;color:#9095a3">Provide a file path (optional) and describe what to create. The model may create multiple files.</p>
152
- <input id="genTarget" placeholder="Target path (optional, e.g., utils.py)" style="width:100%;margin:6px 0;padding:12px;background:#0f1320;border:1px solid #2a2f3a;color:#e6e6e6;border-radius:10px"/>
153
- <textarea id="genPrompt" placeholder="Describe what to generate (e.g., create a CLI parser and tests)" style="width:100%;height:180px;margin:6px 0;padding:12px;background:#0f1320;border:1px solid #2a2f3a;color:#e6e6e6;border-radius:10px"></textarea>
154
- <div style="display:flex; gap:8px; margin-top:10px;justify-content:flex-end">
155
- <button id="genSubmit" style="background:#4f8cff; color:#fff; border:0; padding:10px 14px; border-radius:10px;font-weight:600">Generate</button>
 
 
156
  </div>
157
  </div>
158
  </div>
159
 
160
- <!-- AI Edit Modal -->
161
- <div id="editModal" class="diff-modal" style="display:none">
162
- <div class="diff-card" style="max-width:720px">
163
- <div style="display:flex;align-items:center;justify-content:space-between;gap:8px">
164
- <h3 style="margin:0">Edit with AI</h3>
165
- <button id="editClose" style="background:#23283b; color:#fff; border:0; padding:6px 10px; border-radius:8px">Close</button>
166
- </div>
167
- <p style="margin:10px 0 6px;color:#9095a3">Describe changes. The model will edit the whole codebase and may modify multiple files.</p>
168
- <textarea id="editInstruction" placeholder="e.g., convert print statements to logging and add config" style="width:100%;height:200px;margin:6px 0;padding:12px;background:#0f1320;border:1px solid #2a2f3a;color:#e6e6e6;border-radius:10px"></textarea>
169
- <div style="display:flex; gap:8px; margin-top:10px;justify-content:flex-end">
170
- <button id="editSubmit" style="background:#4f8cff; color:#fff; border:0; padding:10px 14px; border-radius:10px;font-weight:600">Apply Edit</button>
171
  </div>
172
  </div>
173
  </div>
174
 
175
  <!-- Artifacts Modal -->
176
- <div id="artModal" class="diff-modal" style="display:none">
177
- <div class="diff-card" style="max-width:720px">
178
- <div style="display:flex;align-items:center;justify-content:space-between;gap:8px">
179
- <h3 style="margin:0">Artifacts</h3>
180
- <button id="artClose" style="background:#23283b; color:#fff; border:0; padding:6px 10px; border-radius:8px">Close</button>
 
 
 
 
 
181
  </div>
182
- <div id="artList" style="display:grid; grid-template-columns: 1fr auto auto; gap:8px; margin-top:10px"></div>
183
- <div id="artPreview" style="margin-top:10px; border-top:1px solid #2a2f3a; padding-top:10px"></div>
184
  </div>
185
  </div>
186
 
187
  </body>
188
- </html>
189
-
190
 
 
 
1
  <!doctype html>
2
  <html lang="en">
3
+
4
  <head>
5
  <meta charset="utf-8">
6
  <meta name="viewport" content="width=device-width, initial-scale=1">
7
  <title>Python IDE</title>
8
  <link rel="stylesheet" href="/styles.css">
9
+ <link rel="icon" href="data:,">
10
+
11
  <script>/* WARNING: Hardcoding secrets is unsafe. Use env vars in production. */</script>
12
  <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/loader.min.js"></script>
13
  <script>
14
+ window.MonacoEnvironment = { getWorkerUrl: () => proxy };
15
+ let proxy = URL.createObjectURL(new Blob([`self.MonacoEnvironment={baseUrl:'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/'};importScripts('https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/base/worker/workerMain.min.js');`], { type: 'text/javascript' }));
 
 
 
 
 
 
16
  window.API_BASE = '';
17
  </script>
18
+ <script defer src="/script.js"></script>
19
+ </head>
20
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  <body>
22
  <div class="app">
23
+ <!-- Topbar -->
24
  <div class="topbar">
25
+ <div class="brand">Antigravity IDE</div>
26
+
27
+ <div class="topbar-actions">
28
+ <button id="artBtn" class="btn btn-secondary">Artifacts</button>
29
+ <button id="genBtn" class="btn btn-primary">
30
+ <span>✨</span> Generate
31
+ </button>
32
+ <button id="editBtn" class="btn btn-secondary">
33
+ <span>✎</span> Edit
34
+ </button>
35
+ <button id="runBtnTop" class="btn btn-success">
36
+ <span>▶</span> Run
37
+ </button>
38
+ </div>
39
  </div>
40
+
41
+ <!-- Main Workspace -->
42
  <div class="top">
43
+ <!-- Sidebar -->
44
  <div class="sidebar">
45
  <div class="toolbar">
46
+ <button id="newFileBtn" class="btn btn-ghost" title="New File">+ New</button>
47
+ <button id="deleteFileBtn" class="btn btn-ghost" title="Delete File">🗑</button>
48
+ <button id="runBtn" class="btn btn-ghost" title="Run Script">▶</button>
49
  </div>
50
  <ul id="files" class="file-list"></ul>
51
  </div>
52
+
53
+ <!-- Editor -->
54
+ <div class="editor">
55
+ <div id="editor"></div>
56
+
57
+ <!-- Floating AI Fix Action -->
58
+ <div id="aiFix" class="hidden" style="position: absolute; bottom: 20px; right: 20px; z-index: 5;">
59
+ <button class="btn btn-danger" style="box-shadow: 0 4px 12px rgba(239,68,68,0.4)">
60
+ Fix Error with AI
61
+ </button>
62
+ </div>
63
+ </div>
64
  </div>
65
+
66
+ <!-- Terminal -->
67
  <div class="terminal">
68
+ <div class="term-chrome" id="termChrome">
69
+ <div class="traffic-lights">
70
+ <div class="traffic-light red"></div>
71
+ <div class="traffic-light yellow"></div>
72
+ <div class="traffic-light green"></div>
73
+ </div>
74
+ <div class="term-title" id="termTitle">terminal — /workspace</div>
75
  </div>
76
  <div id="output"></div>
77
  </div>
78
  </div>
79
+
80
+ <!-- Context Menu -->
81
+ <div id="ctxMenu" class="hidden"></div>
82
+
83
+ <!-- Loading Overlay -->
84
+ <div id="loading" class="modal-overlay">
85
+ <div class="loading-card">
86
+ <div class="spinner spin"
87
+ style="width:20px;height:20px;border:2px solid #3b82f6;border-top-color:transparent;border-radius:50%"></div>
88
+ <div id="loadingMsg">Processing...</div>
89
+ </div>
90
+ </div>
91
+
92
+ <!-- Auth Modal -->
93
+ <div id="authModal" class="modal-overlay open">
94
+ <div class="modal">
95
+ <h3>Welcome Back</h3>
96
+ <p>Sign in to access your workspace. Your data is secure.</p>
97
+
98
+ <div id="signupFields" class="hidden">
99
+ <div style="display:grid; grid-template-columns: 1fr 1fr; gap:12px; margin-bottom:12px">
100
+ <input id="authName" class="input" placeholder="Full name" type="text" />
101
+ <div style="display:flex; gap:8px">
102
+ <input id="authClass" class="input" placeholder="Class" type="text" />
103
+ <input id="authSection" class="input" placeholder="Sec" type="text" />
104
+ </div>
105
+ </div>
106
  </div>
107
+ <div class="input-group">
108
+ <input id="email" class="input" placeholder="Email address" type="email" />
 
 
 
109
  </div>
110
+ <div class="input-group">
111
+ <input id="password" class="input" placeholder="Password" type="password" />
112
+ </div>
113
+
114
+ <div class="modal-footer" style="flex-direction: column; gap: 10px;">
115
+ <button id="authSubmit" class="btn btn-primary" style="width:100%">Sign In</button>
116
+ <button id="authSwitch" class="btn btn-ghost" style="width:100%; font-size:12px">Need an account? Create
117
+ one</button>
118
+ </div>
119
+ <small style="display:block; margin-top:16px; color:var(--text-muted); text-align:center; font-size:11px">
120
+ Secure session established.
121
+ </small>
122
  </div>
123
  </div>
124
 
125
+ <!-- Diff Modal -->
126
+ <div id="diffModal" class="modal-overlay">
127
+ <div class="modal diff-modal">
128
+ <h3>Review Changes</h3>
129
+ <div id="aiReason" style="color:var(--text-muted); font-size:13px; margin-bottom:12px"></div>
130
+ <div id="diffBody" class="diff-content" style="flex:1"></div>
131
+ <div class="modal-footer">
132
+ <button id="closeDiff" class="btn btn-secondary">Cancel</button>
133
+ <button id="applyFix" class="btn btn-success">Apply Changes</button>
134
  </div>
135
  </div>
136
  </div>
137
+
138
+ <!-- Generate Modal -->
139
+ <div id="genModal" class="modal-overlay">
140
+ <div class="modal" style="max-width: 600px;">
141
+ <h3>Generate Code</h3>
142
+ <p>Describe what you want to build. I'll create the files for you.</p>
143
+ <input id="genTarget" class="input" placeholder="Target file (optional, e.g., utils.py)"
144
+ style="margin-bottom:12px" />
145
+ <textarea id="genPrompt" class="input" placeholder="Describe the functionality..."
146
+ style="height:120px; resize:none"></textarea>
147
+
148
+ <div class="modal-footer">
149
+ <button id="genClose" class="btn btn-secondary">Cancel</button>
150
+ <button id="genSubmit" class="btn btn-primary">Generate</button>
151
  </div>
152
  </div>
153
  </div>
154
 
155
+ <!-- Edit Modal -->
156
+ <div id="editModal" class="modal-overlay">
157
+ <div class="modal" style="max-width: 600px;">
158
+ <h3>Refactor Code</h3>
159
+ <p>Describe how you want to modify the current codebase.</p>
160
+ <textarea id="editInstruction" class="input" placeholder="e.g., Add error handling to all API calls..."
161
+ style="height:140px; resize:none"></textarea>
162
+
163
+ <div class="modal-footer">
164
+ <button id="editClose" class="btn btn-secondary">Cancel</button>
165
+ <button id="editSubmit" class="btn btn-primary">Apply Edits</button>
166
  </div>
167
  </div>
168
  </div>
169
 
170
  <!-- Artifacts Modal -->
171
+ <div id="artModal" class="modal-overlay">
172
+ <div class="modal" style="max-width: 700px; height:80vh">
173
+ <h3>Artifacts</h3>
174
+ <div id="artList"
175
+ style="display:grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap:8px; margin-top:10px">
176
+ </div>
177
+ <div id="artPreview"
178
+ style="margin-top:16px; border-top:1px solid var(--border); padding-top:16px; flex:1; overflow:auto"></div>
179
+ <div class="modal-footer" style="margin-top:auto">
180
+ <button id="artClose" class="btn btn-secondary">Close</button>
181
  </div>
 
 
182
  </div>
183
  </div>
184
 
185
  </body>
 
 
186
 
187
+ </html>
client/public/script.js CHANGED
@@ -1,13 +1,17 @@
1
  let editor; let currentPath = 'main.py'; let files = []; let autosaveTimer; let lastCommand = ''; let openSeq = 0; let currentUser = null;
2
 
3
- async function api(path, opts={}) {
4
  const base = window.API_BASE || '';
5
- const res = await fetch(base + path, { credentials:'include', headers:{'Content-Type':'application/json'}, ...opts });
6
  if (!res.ok) throw new Error(await res.text());
7
  return res.json();
8
  }
9
 
10
- function setAuthModal(visible) { document.getElementById('authModal').style.display = visible ? 'flex' : 'none'; }
 
 
 
 
11
 
12
  async function ensureAuth() {
13
  try {
@@ -21,7 +25,7 @@ async function ensureAuth() {
21
  }
22
 
23
  function initMonaco() {
24
- require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' }});
25
  require(['vs/editor/editor.main'], function () {
26
  editor = monaco.editor.create(document.getElementById('editor'), {
27
  value: '', language: 'python', theme: 'vs-dark', fontSize: 12
@@ -33,53 +37,53 @@ function initMonaco() {
33
  async function loadFiles() {
34
  const data = await api('/api/files/list'); files = data.files || []; renderFileList();
35
  // Open main.py by default
36
- const hasMain = files.find(f=>f.path==='main.py'); openFile(hasMain? 'main.py' : (files[0]?.path || 'main.py'));
37
  }
38
 
39
  function renderFileList() {
40
- const ul = document.getElementById('files'); ul.innerHTML='';
41
- files.forEach(f=>{ const li=document.createElement('li'); li.className='file-item'; if (f.path===currentPath) li.style.background='#1a2133'; li.textContent=f.path; li.onclick=()=>openFile(f.path); li.oncontextmenu=(e)=>showCtx(e, f.path); ul.appendChild(li); });
42
  }
43
 
44
  async function openFile(path) {
45
  currentPath = path; renderFileList();
46
  const seq = ++openSeq;
47
  try {
48
- const data = await api('/api/files/read?path='+encodeURIComponent(path));
49
  if (seq !== openSeq || path !== currentPath) return; // stale response
50
  if (editor) {
51
  editor.setValue(data.content || '');
52
  // Ensure layout in case container size changed
53
- setTimeout(()=>{ try { editor.layout(); } catch {} }, 0);
54
  }
55
  } catch (e) {
56
- appendOutput('Failed to open '+path, 'err');
57
  }
58
  }
59
 
60
  async function writeCurrentFile() {
61
  if (!editor) return; const content = editor.getValue();
62
- await api('/api/files/write', { method:'POST', body: JSON.stringify({ path: currentPath, content }) });
63
  }
64
 
65
  function scheduleAutosave() { clearTimeout(autosaveTimer); autosaveTimer = setTimeout(writeCurrentFile, 2000); }
66
 
67
  function appendOutput(line, cls) {
68
  const out = document.getElementById('output');
69
- const div = document.createElement('div'); div.className='line';
70
  if (cls) div.classList.add(cls);
71
  // Basic ANSI colorization
72
  div.textContent = line;
73
  div.innerHTML = div.innerHTML
74
- .replace(/\x1b\[90m/g,'<span class="ansi-gray">')
75
- .replace(/\x1b\[91m/g,'<span class="ansi-red">')
76
- .replace(/\x1b\[92m/g,'<span class="ansi-green">')
77
- .replace(/\x1b\[93m/g,'<span class="ansi-yellow">')
78
- .replace(/\x1b\[94m/g,'<span class="ansi-blue">')
79
- .replace(/\x1b\[95m/g,'<span class="ansi-magenta">')
80
- .replace(/\x1b\[96m/g,'<span class="ansi-cyan">')
81
- .replace(/\x1b\[1m/g,'<span class="ansi-bold">')
82
- .replace(/\x1b\[0m/g,'</span>');
83
  out.appendChild(div); out.scrollTop = out.scrollHeight;
84
  }
85
 
@@ -87,10 +91,10 @@ function ensurePrompt() {
87
  const out = document.getElementById('output');
88
  let p = document.getElementById('promptLine');
89
  if (!p) {
90
- p = document.createElement('div'); p.id='promptLine'; p.className='prompt';
91
- const ps1 = document.createElement('span'); ps1.className='ps1'; ps1.id='ps1'; ps1.textContent=getPromptText();
92
- const input = document.createElement('input'); input.id='cmdInline'; input.placeholder='Type commands like: python3 main.py';
93
- input.addEventListener('keydown', (e)=>{ if (e.key==='Enter') { const v=input.value.trim(); if(v){ runCommandSSE(v); input.value=''; } } });
94
  p.appendChild(ps1); p.appendChild(input); out.appendChild(p);
95
  } else {
96
  const ps1 = document.getElementById('ps1'); if (ps1) ps1.textContent = getPromptText();
@@ -102,27 +106,27 @@ function ensurePrompt() {
102
  function setAIFixVisible(v) { document.getElementById('aiFix').style.display = v ? 'block' : 'none'; }
103
 
104
  async function runCommand(cmd) {
105
- lastCommand = cmd; appendOutput('$ '+cmd); setAIFixVisible(false);
106
- const res = await fetch(window.API_BASE + '/api/terminal/run', { method:'POST', credentials:'include', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ command: cmd }) });
107
  if (!res.ok) { appendOutput('Failed to start command', 'err'); return; }
108
  const es = new EventSource(window.API_BASE + '/api/terminal/run', { withCredentials: true });
109
  }
110
 
111
  async function runCommandSSE(cmd) {
112
  // Start SSE by posting first to initiate process and then listening via fetch stream endpoint. We instead reuse the POST endpoint that streams directly.
113
- const res = await fetch(window.API_BASE + '/api/terminal/run', { method:'POST', credentials:'include', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ command: cmd }) });
114
  if (!res.ok || !res.body) { appendOutput('Command not allowed', 'err'); return; }
115
  appendOutput(getPromptText() + ' ' + cmd, 'ansi-gray');
116
- const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer=''; let hadError=false; let exitCode=0;
117
  while (true) {
118
- const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream:true });
119
  const parts = buffer.split('\n\n'); buffer = parts.pop();
120
  for (const part of parts) {
121
- const lines = part.split('\n'); const evt = lines.find(l=>l.startsWith('event: '))?.slice(7).trim();
122
- const dataLine = lines.find(l=>l.startsWith('data: ')); if (!evt || !dataLine) continue; const payload = JSON.parse(dataLine.slice(6));
123
- if (evt==='stdout') appendOutput(payload.chunk);
124
- if (evt==='stderr') { appendOutput(payload.chunk, 'err'); hadError=true; }
125
- if (evt==='exit') { exitCode = payload.code; if (exitCode!==0 || hadError) setAIFixVisible(true); }
126
  }
127
  }
128
  ensurePrompt();
@@ -135,22 +139,22 @@ async function proposeFix() {
135
  btn.querySelector('button').textContent = 'Thinking…';
136
  try {
137
  showLoading('Proposing AI fix…');
138
- const { id, proposed } = await api('/api/ai/propose-fix', { method:'POST', body: JSON.stringify({ errorOutput: out }) });
139
  document.getElementById('aiReason').textContent = proposed.reason ? ('Reason: ' + proposed.reason) : '';
140
- const body = document.getElementById('diffBody'); body.innerHTML='';
141
- (proposed.changes||[]).forEach(ch=>{
142
- const pre = document.createElement('pre'); pre.textContent = `# ${ch.path}\n` + (ch.newContent||''); body.appendChild(pre);
143
  });
144
- document.getElementById('diffModal').style.display='flex';
145
- document.getElementById('applyFix').onclick = async ()=>{
146
  showLoading('Applying fix…');
147
- await api('/api/ai/apply-fix', { method:'POST', body: JSON.stringify({ id }) });
148
- document.getElementById('diffModal').style.display='none';
149
  setAIFixVisible(false);
150
  await loadFiles();
151
  if (lastCommand) runCommandSSE(lastCommand);
152
  // hide button after accept
153
- document.getElementById('aiFix').style.display='none';
154
  hideLoading();
155
  };
156
  } catch (e) {
@@ -163,122 +167,173 @@ async function proposeFix() {
163
  }
164
 
165
  function initUI() {
166
- document.getElementById('signin').onclick = async ()=>{ try { await api('/api/auth/signin', { method:'POST', body: JSON.stringify({ email: email.value, password: password.value }) }); setAuthModal(false); const me = await api('/api/auth/me'); currentUser = me?.user || null; updateTerminalTitle(currentUser); ensurePrompt(); await loadFiles(); } catch(e){ alert('Signin failed'); } };
167
- document.getElementById('signup').onclick = async ()=>{ try { const name = document.getElementById('authName').value.trim(); const klass = document.getElementById('authClass').value.trim(); const section = document.getElementById('authSection').value.trim(); if(!name||!klass||!section) return alert('Please enter name, class, section'); await api('/api/auth/signup', { method:'POST', body: JSON.stringify({ email: email.value, password: password.value, name, class: klass, section }) }); setAuthModal(false); const me = await api('/api/auth/me'); currentUser = me?.user || null; updateTerminalTitle(currentUser); ensurePrompt(); await loadFiles(); } catch(e){ alert('Signup failed'); } };
168
- document.getElementById('runBtn').onclick = ()=>{ runCommandSSE('python3 ' + currentPath); };
169
- const rtop = document.getElementById('runBtnTop'); if (rtop) rtop.onclick = ()=>{ runCommandSSE('python3 main.py'); };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  // Buttons are bound in bindModals; ensure no duplicate handlers here
171
  document.getElementById('aiFix').onclick = proposeFix;
172
- document.getElementById('closeDiff').onclick = ()=>{ document.getElementById('diffModal').style.display='none'; document.getElementById('aiFix').style.display='none'; };
173
- document.getElementById('newFileBtn').onclick = async ()=>{ const p = prompt('New file path'); if (p) { await api('/api/files/write', { method:'POST', body: JSON.stringify({ path:p, content:'' }) }); await loadFiles(); } };
174
- document.getElementById('deleteFileBtn').onclick = async ()=>{ if (confirm('Delete '+currentPath+'?')) { await api('/api/files/delete', { method:'POST', body: JSON.stringify({ path: currentPath }) }); await loadFiles(); } };
175
  // Artifacts list open button and shortcut
176
- document.getElementById('artBtn').onclick = ()=>openArtifacts();
177
- document.addEventListener('keydown', async (e)=>{ if (e.ctrlKey && e.key.toLowerCase()==='o'){ e.preventDefault(); await openArtifacts(); } });
178
  }
179
 
180
- window.addEventListener('DOMContentLoaded', ()=>{ patchModifierState(); initMonaco(); initUI(); bindModals(); ensureAuth(); ensurePrompt(); });
181
 
182
  // Context menu
183
- function hideCtx(){ const c=document.getElementById('ctxMenu'); c.style.display='none'; }
184
- function showCtx(e, path){ e.preventDefault(); const c=document.getElementById('ctxMenu'); c.innerHTML='';
185
- const mk=(label,fn)=>{ const b=document.createElement('button'); b.textContent=label; b.onclick=()=>{ hideCtx(); fn(); }; return b; };
186
- c.appendChild(mk('Open', ()=>openFile(path)));
187
- c.appendChild(mk('Rename', async()=>{ const np=prompt('Rename to', path); if(np && np!==path){ await api('/api/files/rename',{method:'POST',body:JSON.stringify({oldPath:path,newPath:np})}); await loadFiles(); openFile(np);} }));
188
- c.appendChild(mk('New File', async()=>{ const p=prompt('New file path'); if(p){ await api('/api/files/write',{method:'POST',body:JSON.stringify({path:p,content:''})}); await loadFiles(); openFile(p);} }));
189
- c.appendChild(mk('New Folder (placeholder)', ()=>{}));
190
- c.appendChild(mk('Delete', async()=>{ if(confirm('Delete '+path+'?')){ await api('/api/files/delete',{method:'POST',body:JSON.stringify({path})}); await loadFiles(); } }));
191
- c.appendChild(mk('Refresh', ()=>loadFiles()));
192
- c.style.left=e.pageX+'px'; c.style.top=e.pageY+'px'; c.style.display='block';
 
193
  }
194
  window.addEventListener('click', hideCtx);
195
 
196
  // AI generate modal (prompt → file)
197
- function bindModals(){
 
 
 
 
 
198
  // Generate modal
199
  const gm = document.getElementById('genModal');
200
- document.getElementById('genBtn').onclick = ()=>{ gm.style.display='flex'; };
201
- document.getElementById('genClose').onclick = ()=>{ gm.style.display='none'; };
202
- document.getElementById('genSubmit').onclick = async ()=>{
203
  const target = document.getElementById('genTarget').value.trim();
204
  const promptText = document.getElementById('genPrompt').value.trim();
205
  if (!promptText) return alert('Prompt required');
206
  try {
207
  showLoading('Generating code…');
208
- await api('/api/ai/generate-code', { method:'POST', body: JSON.stringify({ prompt: promptText, targetPath: target||undefined }) });
209
- gm.style.display='none';
210
  await loadFiles();
211
  if (target) openFile(target);
212
- } catch(e){ alert('Generate failed'); }
213
  finally { hideLoading(); }
214
  };
215
 
216
  // Edit modal
217
  const em = document.getElementById('editModal');
218
- document.getElementById('editBtn').onclick = ()=>{ em.style.display='flex'; };
219
- document.getElementById('editClose').onclick = ()=>{ em.style.display='none'; };
220
- document.getElementById('editSubmit').onclick = async ()=>{
221
  const instruction = document.getElementById('editInstruction').value.trim();
222
  if (!instruction) return alert('Instruction required');
223
  try {
224
  showLoading('Applying edits…');
225
- await api('/api/ai/edit-code', { method:'POST', body: JSON.stringify({ instruction }) });
226
- em.style.display='none';
227
  await loadFiles();
228
- } catch(e){ alert('Edit failed'); }
229
  finally { hideLoading(); }
230
  };
231
 
232
  // Artifacts modal
233
- document.getElementById('artClose').onclick = ()=>{ document.getElementById('artModal').style.display='none'; };
234
  }
235
 
236
- async function openArtifacts(){
237
- try{
238
  showLoading('Loading artifacts…');
239
  const { items } = await api('/api/root');
240
- const list = document.getElementById('artList'); list.innerHTML='';
241
- const preview = document.getElementById('artPreview'); preview.innerHTML='';
242
- items.forEach(it=>{
243
- const name = document.createElement('div'); name.textContent = it.name + (it.isDir ? '/' : '');
244
  const view = document.createElement('div'); const actions = document.createElement('div');
245
  if (!it.isDir) {
246
- const viewBtn = document.createElement('button'); viewBtn.textContent='View'; viewBtn.style.cssText='background:#23283b;color:#fff;border:0;padding:6px 10px;border-radius:8px;font-size:12px;margin-right:6px';
247
- viewBtn.onclick = ()=>{
 
248
  const url = `${window.API_BASE}/api/root/get?path=${encodeURIComponent(it.name)}`;
249
  const ext = it.name.toLowerCase();
250
  if (/(png|jpg|jpeg|gif|svg|webp)$/.test(ext)) {
251
- preview.innerHTML = ''; const img = new Image(); img.src = url; img.style.maxWidth='100%'; preview.appendChild(img);
252
  } else if (/(mp4|webm|ogg)$/.test(ext)) {
253
- preview.innerHTML = ''; const v = document.createElement('video'); v.controls=true; v.src=url; v.style.maxWidth='100%'; preview.appendChild(v);
254
  } else if (/(txt|log|json|csv|md)$/.test(ext)) {
255
- preview.innerHTML='Loading…'; fetch(url, { credentials:'include' }).then(r=>r.text()).then(t=>{ const pre=document.createElement('pre'); pre.textContent=t; preview.innerHTML=''; preview.appendChild(pre); });
256
  } else {
257
  preview.innerHTML = 'Preview not available.';
258
  }
259
  };
260
- const openBtn = document.createElement('button'); openBtn.textContent='Open'; openBtn.style.cssText='background:#2bb673;color:#fff;border:0;padding:6px 10px;border-radius:8px;font-size:12px';
261
- openBtn.onclick = ()=>{ const url = `${window.API_BASE}/api/root/get?path=${encodeURIComponent(it.name)}`; window.open(url, '_blank'); };
 
262
  view.appendChild(viewBtn); actions.appendChild(openBtn);
263
  }
264
  list.appendChild(name); list.appendChild(view); list.appendChild(actions);
265
  });
266
- document.getElementById('artModal').style.display='flex';
267
  } finally { hideLoading(); }
268
  }
269
 
270
  // Patch for environments where KeyboardEvent.getModifierState may be missing on dispatched events
271
- function patchModifierState(){
272
- const types = ['keydown','keyup','mousedown','mouseup','mousemove'];
273
- const add = (e)=>{ if (typeof e.getModifierState !== 'function') { e.getModifierState = function(){ return false; }; } };
274
- types.forEach(t=> document.addEventListener(t, add, true));
275
  }
276
 
277
- function showLoading(msg){ const l=document.getElementById('loading'); document.getElementById('loadingMsg').textContent=msg||'Working…'; l.style.display='flex'; }
278
- function hideLoading(){ const l=document.getElementById('loading'); l.style.display='none'; }
279
-
280
- function updateTerminalTitle(user){
281
- if(!user) return;
282
  const title = document.getElementById('termTitle');
283
  if (user.name && user.class && user.section) {
284
  const display = `${user.name}@${user.class}-${user.section}`;
@@ -286,7 +341,7 @@ function updateTerminalTitle(user){
286
  }
287
  }
288
 
289
- function getPromptText(){
290
  const u = currentUser;
291
  if (!u || !u.name || !u.class || !u.section) return '$';
292
  return `${u.name}@${u.class}-${u.section} %`;
 
1
  let editor; let currentPath = 'main.py'; let files = []; let autosaveTimer; let lastCommand = ''; let openSeq = 0; let currentUser = null;
2
 
3
+ async function api(path, opts = {}) {
4
  const base = window.API_BASE || '';
5
+ const res = await fetch(base + path, { credentials: 'include', headers: { 'Content-Type': 'application/json' }, ...opts });
6
  if (!res.ok) throw new Error(await res.text());
7
  return res.json();
8
  }
9
 
10
+ function setAuthModal(visible) {
11
+ const el = document.getElementById('authModal');
12
+ if (visible) el.classList.add('open');
13
+ else el.classList.remove('open');
14
+ }
15
 
16
  async function ensureAuth() {
17
  try {
 
25
  }
26
 
27
  function initMonaco() {
28
+ require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' } });
29
  require(['vs/editor/editor.main'], function () {
30
  editor = monaco.editor.create(document.getElementById('editor'), {
31
  value: '', language: 'python', theme: 'vs-dark', fontSize: 12
 
37
  async function loadFiles() {
38
  const data = await api('/api/files/list'); files = data.files || []; renderFileList();
39
  // Open main.py by default
40
+ const hasMain = files.find(f => f.path === 'main.py'); openFile(hasMain ? 'main.py' : (files[0]?.path || 'main.py'));
41
  }
42
 
43
  function renderFileList() {
44
+ const ul = document.getElementById('files'); ul.innerHTML = '';
45
+ files.forEach(f => { const li = document.createElement('li'); li.className = 'file-item'; if (f.path === currentPath) li.style.background = '#1a2133'; li.textContent = f.path; li.onclick = () => openFile(f.path); li.oncontextmenu = (e) => showCtx(e, f.path); ul.appendChild(li); });
46
  }
47
 
48
  async function openFile(path) {
49
  currentPath = path; renderFileList();
50
  const seq = ++openSeq;
51
  try {
52
+ const data = await api('/api/files/read?path=' + encodeURIComponent(path));
53
  if (seq !== openSeq || path !== currentPath) return; // stale response
54
  if (editor) {
55
  editor.setValue(data.content || '');
56
  // Ensure layout in case container size changed
57
+ setTimeout(() => { try { editor.layout(); } catch { } }, 0);
58
  }
59
  } catch (e) {
60
+ appendOutput('Failed to open ' + path, 'err');
61
  }
62
  }
63
 
64
  async function writeCurrentFile() {
65
  if (!editor) return; const content = editor.getValue();
66
+ await api('/api/files/write', { method: 'POST', body: JSON.stringify({ path: currentPath, content }) });
67
  }
68
 
69
  function scheduleAutosave() { clearTimeout(autosaveTimer); autosaveTimer = setTimeout(writeCurrentFile, 2000); }
70
 
71
  function appendOutput(line, cls) {
72
  const out = document.getElementById('output');
73
+ const div = document.createElement('div'); div.className = 'line';
74
  if (cls) div.classList.add(cls);
75
  // Basic ANSI colorization
76
  div.textContent = line;
77
  div.innerHTML = div.innerHTML
78
+ .replace(/\x1b\[90m/g, '<span class="ansi-gray">')
79
+ .replace(/\x1b\[91m/g, '<span class="ansi-red">')
80
+ .replace(/\x1b\[92m/g, '<span class="ansi-green">')
81
+ .replace(/\x1b\[93m/g, '<span class="ansi-yellow">')
82
+ .replace(/\x1b\[94m/g, '<span class="ansi-blue">')
83
+ .replace(/\x1b\[95m/g, '<span class="ansi-magenta">')
84
+ .replace(/\x1b\[96m/g, '<span class="ansi-cyan">')
85
+ .replace(/\x1b\[1m/g, '<span class="ansi-bold">')
86
+ .replace(/\x1b\[0m/g, '</span>');
87
  out.appendChild(div); out.scrollTop = out.scrollHeight;
88
  }
89
 
 
91
  const out = document.getElementById('output');
92
  let p = document.getElementById('promptLine');
93
  if (!p) {
94
+ p = document.createElement('div'); p.id = 'promptLine'; p.className = 'prompt';
95
+ const ps1 = document.createElement('span'); ps1.className = 'ps1'; ps1.id = 'ps1'; ps1.textContent = getPromptText();
96
+ const input = document.createElement('input'); input.id = 'cmdInline'; input.placeholder = 'Type commands like: python3 main.py';
97
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { const v = input.value.trim(); if (v) { runCommandSSE(v); input.value = ''; } } });
98
  p.appendChild(ps1); p.appendChild(input); out.appendChild(p);
99
  } else {
100
  const ps1 = document.getElementById('ps1'); if (ps1) ps1.textContent = getPromptText();
 
106
  function setAIFixVisible(v) { document.getElementById('aiFix').style.display = v ? 'block' : 'none'; }
107
 
108
  async function runCommand(cmd) {
109
+ lastCommand = cmd; appendOutput('$ ' + cmd); setAIFixVisible(false);
110
+ const res = await fetch(window.API_BASE + '/api/terminal/run', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: cmd }) });
111
  if (!res.ok) { appendOutput('Failed to start command', 'err'); return; }
112
  const es = new EventSource(window.API_BASE + '/api/terminal/run', { withCredentials: true });
113
  }
114
 
115
  async function runCommandSSE(cmd) {
116
  // Start SSE by posting first to initiate process and then listening via fetch stream endpoint. We instead reuse the POST endpoint that streams directly.
117
+ const res = await fetch(window.API_BASE + '/api/terminal/run', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: cmd }) });
118
  if (!res.ok || !res.body) { appendOutput('Command not allowed', 'err'); return; }
119
  appendOutput(getPromptText() + ' ' + cmd, 'ansi-gray');
120
+ const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; let hadError = false; let exitCode = 0;
121
  while (true) {
122
+ const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true });
123
  const parts = buffer.split('\n\n'); buffer = parts.pop();
124
  for (const part of parts) {
125
+ const lines = part.split('\n'); const evt = lines.find(l => l.startsWith('event: '))?.slice(7).trim();
126
+ const dataLine = lines.find(l => l.startsWith('data: ')); if (!evt || !dataLine) continue; const payload = JSON.parse(dataLine.slice(6));
127
+ if (evt === 'stdout') appendOutput(payload.chunk);
128
+ if (evt === 'stderr') { appendOutput(payload.chunk, 'err'); hadError = true; }
129
+ if (evt === 'exit') { exitCode = payload.code; if (exitCode !== 0 || hadError) setAIFixVisible(true); }
130
  }
131
  }
132
  ensurePrompt();
 
139
  btn.querySelector('button').textContent = 'Thinking…';
140
  try {
141
  showLoading('Proposing AI fix…');
142
+ const { id, proposed } = await api('/api/ai/propose-fix', { method: 'POST', body: JSON.stringify({ errorOutput: out }) });
143
  document.getElementById('aiReason').textContent = proposed.reason ? ('Reason: ' + proposed.reason) : '';
144
+ const body = document.getElementById('diffBody'); body.innerHTML = '';
145
+ (proposed.changes || []).forEach(ch => {
146
+ const pre = document.createElement('pre'); pre.textContent = `# ${ch.path}\n` + (ch.newContent || ''); body.appendChild(pre);
147
  });
148
+ document.getElementById('diffModal').classList.add('open');
149
+ document.getElementById('applyFix').onclick = async () => {
150
  showLoading('Applying fix…');
151
+ await api('/api/ai/apply-fix', { method: 'POST', body: JSON.stringify({ id }) });
152
+ document.getElementById('diffModal').classList.remove('open');
153
  setAIFixVisible(false);
154
  await loadFiles();
155
  if (lastCommand) runCommandSSE(lastCommand);
156
  // hide button after accept
157
+ document.getElementById('aiFix').style.display = 'none';
158
  hideLoading();
159
  };
160
  } catch (e) {
 
167
  }
168
 
169
  function initUI() {
170
+ // Auth logic
171
+ let isSignup = false;
172
+ const toggleAuth = () => {
173
+ isSignup = !isSignup;
174
+ const fields = document.getElementById('signupFields');
175
+ const btn = document.getElementById('authSubmit');
176
+ const sw = document.getElementById('authSwitch');
177
+ const title = document.querySelector('#authModal h3');
178
+
179
+ if (isSignup) {
180
+ fields.classList.remove('hidden');
181
+ btn.textContent = 'Create Account';
182
+ sw.textContent = 'Already have an account? Sign In';
183
+ title.textContent = 'Create Account';
184
+ } else {
185
+ fields.classList.add('hidden');
186
+ btn.textContent = 'Sign In';
187
+ sw.textContent = 'Need an account? Create one';
188
+ title.textContent = 'Welcome Back';
189
+ }
190
+ };
191
+ document.getElementById('authSwitch').onclick = toggleAuth;
192
+
193
+ document.getElementById('authSubmit').onclick = async () => {
194
+ const emailVal = document.getElementById('email').value;
195
+ const passVal = document.getElementById('password').value;
196
+ if (!emailVal || !passVal) return alert('Email and Password required');
197
+
198
+ try {
199
+ if (isSignup) {
200
+ const name = document.getElementById('authName').value.trim();
201
+ const klass = document.getElementById('authClass').value.trim();
202
+ const section = document.getElementById('authSection').value.trim();
203
+ if (!name || !klass || !section) return alert('Please enter name, class, section');
204
+ await api('/api/auth/signup', { method: 'POST', body: JSON.stringify({ email: emailVal, password: passVal, name, class: klass, section }) });
205
+ } else {
206
+ await api('/api/auth/signin', { method: 'POST', body: JSON.stringify({ email: emailVal, password: passVal }) });
207
+ }
208
+ setAuthModal(false);
209
+ const me = await api('/api/auth/me');
210
+ currentUser = me?.user || null;
211
+ updateTerminalTitle(currentUser);
212
+ ensurePrompt();
213
+ await loadFiles();
214
+ } catch (e) {
215
+ alert((isSignup ? 'Signup' : 'Signin') + ' failed: ' + e.message);
216
+ }
217
+ };
218
+ document.getElementById('runBtn').onclick = () => { runCommandSSE('python3 ' + currentPath); };
219
+ const rtop = document.getElementById('runBtnTop'); if (rtop) rtop.onclick = () => { runCommandSSE('python3 main.py'); };
220
  // Buttons are bound in bindModals; ensure no duplicate handlers here
221
  document.getElementById('aiFix').onclick = proposeFix;
222
+ document.getElementById('closeDiff').onclick = () => { document.getElementById('diffModal').classList.remove('open'); document.getElementById('aiFix').style.display = 'none'; };
223
+ document.getElementById('newFileBtn').onclick = async () => { const p = prompt('New file path'); if (p) { await api('/api/files/write', { method: 'POST', body: JSON.stringify({ path: p, content: '' }) }); await loadFiles(); } };
224
+ document.getElementById('deleteFileBtn').onclick = async () => { if (confirm('Delete ' + currentPath + '?')) { await api('/api/files/delete', { method: 'POST', body: JSON.stringify({ path: currentPath }) }); await loadFiles(); } };
225
  // Artifacts list open button and shortcut
226
+ document.getElementById('artBtn').onclick = () => openArtifacts();
227
+ document.addEventListener('keydown', async (e) => { if (e.ctrlKey && e.key.toLowerCase() === 'o') { e.preventDefault(); await openArtifacts(); } });
228
  }
229
 
230
+ window.addEventListener('DOMContentLoaded', () => { patchModifierState(); initMonaco(); initUI(); bindModals(); ensureAuth(); ensurePrompt(); });
231
 
232
  // Context menu
233
+ function hideCtx() { const c = document.getElementById('ctxMenu'); c.style.display = 'none'; }
234
+ function showCtx(e, path) {
235
+ e.preventDefault(); const c = document.getElementById('ctxMenu'); c.innerHTML = '';
236
+ const mk = (label, fn) => { const b = document.createElement('button'); b.textContent = label; b.onclick = () => { hideCtx(); fn(); }; return b; };
237
+ c.appendChild(mk('Open', () => openFile(path)));
238
+ c.appendChild(mk('Rename', async () => { const np = prompt('Rename to', path); if (np && np !== path) { await api('/api/files/rename', { method: 'POST', body: JSON.stringify({ oldPath: path, newPath: np }) }); await loadFiles(); openFile(np); } }));
239
+ c.appendChild(mk('New File', async () => { const p = prompt('New file path'); if (p) { await api('/api/files/write', { method: 'POST', body: JSON.stringify({ path: p, content: '' }) }); await loadFiles(); openFile(p); } }));
240
+ c.appendChild(mk('New Folder (placeholder)', () => { }));
241
+ c.appendChild(mk('Delete', async () => { if (confirm('Delete ' + path + '?')) { await api('/api/files/delete', { method: 'POST', body: JSON.stringify({ path }) }); await loadFiles(); } }));
242
+ c.appendChild(mk('Refresh', () => loadFiles()));
243
+ c.style.left = e.pageX + 'px'; c.style.top = e.pageY + 'px'; c.classList.add('open');
244
  }
245
  window.addEventListener('click', hideCtx);
246
 
247
  // AI generate modal (prompt → file)
248
+ // Replaces showLoading/hideLoading
249
+ function showLoading(msg) { const l = document.getElementById('loading'); document.getElementById('loadingMsg').textContent = msg || 'Working…'; l.classList.add('open'); }
250
+ function hideLoading() { document.getElementById('loading').classList.remove('open'); }
251
+
252
+ // Update bindModals to use classList
253
+ function bindModals() {
254
  // Generate modal
255
  const gm = document.getElementById('genModal');
256
+ document.getElementById('genBtn').onclick = () => { gm.classList.add('open'); };
257
+ document.getElementById('genClose').onclick = () => { gm.classList.remove('open'); };
258
+ document.getElementById('genSubmit').onclick = async () => {
259
  const target = document.getElementById('genTarget').value.trim();
260
  const promptText = document.getElementById('genPrompt').value.trim();
261
  if (!promptText) return alert('Prompt required');
262
  try {
263
  showLoading('Generating code…');
264
+ await api('/api/ai/generate-code', { method: 'POST', body: JSON.stringify({ prompt: promptText, targetPath: target || undefined }) });
265
+ gm.classList.remove('open');
266
  await loadFiles();
267
  if (target) openFile(target);
268
+ } catch (e) { alert('Generate failed'); }
269
  finally { hideLoading(); }
270
  };
271
 
272
  // Edit modal
273
  const em = document.getElementById('editModal');
274
+ document.getElementById('editBtn').onclick = () => { em.classList.add('open'); };
275
+ document.getElementById('editClose').onclick = () => { em.classList.remove('open'); };
276
+ document.getElementById('editSubmit').onclick = async () => {
277
  const instruction = document.getElementById('editInstruction').value.trim();
278
  if (!instruction) return alert('Instruction required');
279
  try {
280
  showLoading('Applying edits…');
281
+ await api('/api/ai/edit-code', { method: 'POST', body: JSON.stringify({ instruction }) });
282
+ em.classList.remove('open');
283
  await loadFiles();
284
+ } catch (e) { alert('Edit failed'); }
285
  finally { hideLoading(); }
286
  };
287
 
288
  // Artifacts modal
289
+ document.getElementById('artClose').onclick = () => { document.getElementById('artModal').classList.remove('open'); };
290
  }
291
 
292
+ async function openArtifacts() {
293
+ try {
294
  showLoading('Loading artifacts…');
295
  const { items } = await api('/api/root');
296
+ const list = document.getElementById('artList'); list.innerHTML = '';
297
+ const preview = document.getElementById('artPreview'); preview.innerHTML = '';
298
+ items.forEach(it => {
299
+ const name = document.createElement('div'); name.textContent = it.name + (it.isDir ? '/' : ''); name.style.fontSize = '13px'; name.style.color = '#e4e4e7';
300
  const view = document.createElement('div'); const actions = document.createElement('div');
301
  if (!it.isDir) {
302
+ const viewBtn = document.createElement('button'); viewBtn.textContent = 'View';
303
+ viewBtn.className = 'btn btn-secondary'; viewBtn.style.padding = '4px 8px'; viewBtn.style.fontSize = '11px'; viewBtn.style.marginRight = '4px';
304
+ viewBtn.onclick = () => {
305
  const url = `${window.API_BASE}/api/root/get?path=${encodeURIComponent(it.name)}`;
306
  const ext = it.name.toLowerCase();
307
  if (/(png|jpg|jpeg|gif|svg|webp)$/.test(ext)) {
308
+ preview.innerHTML = ''; const img = new Image(); img.src = url; img.style.maxWidth = '100%'; preview.appendChild(img);
309
  } else if (/(mp4|webm|ogg)$/.test(ext)) {
310
+ preview.innerHTML = ''; const v = document.createElement('video'); v.controls = true; v.src = url; v.style.maxWidth = '100%'; preview.appendChild(v);
311
  } else if (/(txt|log|json|csv|md)$/.test(ext)) {
312
+ preview.innerHTML = 'Loading…'; fetch(url, { credentials: 'include' }).then(r => r.text()).then(t => { const pre = document.createElement('pre'); pre.textContent = t; preview.innerHTML = ''; preview.appendChild(pre); });
313
  } else {
314
  preview.innerHTML = 'Preview not available.';
315
  }
316
  };
317
+ const openBtn = document.createElement('button'); openBtn.textContent = 'Open';
318
+ openBtn.className = 'btn btn-primary'; openBtn.style.padding = '4px 8px'; openBtn.style.fontSize = '11px';
319
+ openBtn.onclick = () => { const url = `${window.API_BASE}/api/root/get?path=${encodeURIComponent(it.name)}`; window.open(url, '_blank'); };
320
  view.appendChild(viewBtn); actions.appendChild(openBtn);
321
  }
322
  list.appendChild(name); list.appendChild(view); list.appendChild(actions);
323
  });
324
+ document.getElementById('artModal').classList.add('open');
325
  } finally { hideLoading(); }
326
  }
327
 
328
  // Patch for environments where KeyboardEvent.getModifierState may be missing on dispatched events
329
+ function patchModifierState() {
330
+ const types = ['keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove'];
331
+ const add = (e) => { if (typeof e.getModifierState !== 'function') { e.getModifierState = function () { return false; }; } };
332
+ types.forEach(t => document.addEventListener(t, add, true));
333
  }
334
 
335
+ function updateTerminalTitle(user) {
336
+ if (!user) return;
 
 
 
337
  const title = document.getElementById('termTitle');
338
  if (user.name && user.class && user.section) {
339
  const display = `${user.name}@${user.class}-${user.section}`;
 
341
  }
342
  }
343
 
344
+ function getPromptText() {
345
  const u = currentUser;
346
  if (!u || !u.name || !u.class || !u.section) return '$';
347
  return `${u.name}@${u.class}-${u.section} %`;
client/public/styles.css CHANGED
@@ -1,3 +1,459 @@
1
- /* Styles are inlined in index.html for faster first paint; keep file for overrides */
2
 
 
 
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
2
 
3
+ :root {
4
+ --bg-dark: #09090b;
5
+ --bg-card: #141419;
6
+ /* #18181b; */
7
+ --bg-sidebar: #0f1014;
8
+ --bg-hover: #27272a;
9
 
10
+ --border: #27272a;
11
+ --border-light: #3f3f46;
12
+
13
+ --text-main: #e4e4e7;
14
+ --text-muted: #a1a1aa;
15
+
16
+ --primary: #3b82f6;
17
+ --primary-hover: #2563eb;
18
+
19
+ --success: #22c55e;
20
+ --danger: #ef4444;
21
+ --warning: #f59e0b;
22
+
23
+ --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
24
+ --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
25
+ --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
26
+ --shadow-glow: 0 0 20px rgba(59, 130, 246, 0.15);
27
+
28
+ --radius-sm: 6px;
29
+ --radius: 8px;
30
+ --radius-lg: 12px;
31
+
32
+ --font-sans: 'Inter', sans-serif;
33
+ --font-mono: 'JetBrains Mono', monospace;
34
+ }
35
+
36
+ /* Reset & Base */
37
+ *,
38
+ *::before,
39
+ *::after {
40
+ box-sizing: border-box;
41
+ }
42
+
43
+ body {
44
+ margin: 0;
45
+ background-color: var(--bg-dark);
46
+ color: var(--text-main);
47
+ font-family: var(--font-sans);
48
+ -webkit-font-smoothing: antialiased;
49
+ height: 100vh;
50
+ overflow: hidden;
51
+ }
52
+
53
+ /* Layout */
54
+ .app {
55
+ display: grid;
56
+ grid-template-rows: 56px 1fr 240px;
57
+ height: 100vh;
58
+ }
59
+
60
+ @media (max-width: 800px) {
61
+ .app {
62
+ grid-template-rows: 50px 1fr 35vh;
63
+ }
64
+
65
+ .top {
66
+ grid-template-columns: 1fr !important;
67
+ }
68
+
69
+ .sidebar {
70
+ display: none;
71
+ }
72
+
73
+ /* Hide sidebar on mobile for now or make it a drawer */
74
+ }
75
+
76
+ /* Topbar */
77
+ .topbar {
78
+ display: flex;
79
+ align-items: center;
80
+ gap: 16px;
81
+ padding: 0 20px;
82
+ background: var(--bg-sidebar);
83
+ border-bottom: 1px solid var(--border);
84
+ z-index: 10;
85
+ }
86
+
87
+ .brand {
88
+ font-weight: 700;
89
+ font-size: 18px;
90
+ background: linear-gradient(135deg, #fff, #a1a1aa);
91
+ background-clip: text;
92
+ -webkit-background-clip: text;
93
+ -webkit-text-fill-color: transparent;
94
+ letter-spacing: -0.5px;
95
+ }
96
+
97
+ .topbar-actions {
98
+ margin-left: auto;
99
+ display: flex;
100
+ gap: 10px;
101
+ }
102
+
103
+ /* Buttons */
104
+ button {
105
+ cursor: pointer;
106
+ border: none;
107
+ font-family: var(--font-sans);
108
+ transition: all 0.2s ease;
109
+ }
110
+
111
+ .btn {
112
+ padding: 8px 14px;
113
+ border-radius: var(--radius);
114
+ font-size: 13px;
115
+ font-weight: 500;
116
+ display: inline-flex;
117
+ align-items: center;
118
+ justify-content: center;
119
+ gap: 6px;
120
+ }
121
+
122
+ .btn-primary {
123
+ background: var(--primary);
124
+ color: white;
125
+ box-shadow: 0 0 10px rgba(59, 130, 246, 0.2);
126
+ }
127
+
128
+ .btn-primary:hover {
129
+ background: var(--primary-hover);
130
+ transform: translateY(-1px);
131
+ }
132
+
133
+ .btn-primary:active {
134
+ transform: translateY(0);
135
+ }
136
+
137
+ .btn-secondary {
138
+ background: var(--bg-hover);
139
+ color: var(--text-main);
140
+ border: 1px solid var(--border);
141
+ }
142
+
143
+ .btn-secondary:hover {
144
+ background: var(--border-light);
145
+ }
146
+
147
+ .btn-success {
148
+ background: var(--success);
149
+ color: white;
150
+ }
151
+
152
+ .btn-success:hover {
153
+ filter: brightness(1.1);
154
+ }
155
+
156
+ .btn-danger {
157
+ background: var(--danger);
158
+ color: white;
159
+ }
160
+
161
+ .btn-ghost {
162
+ background: transparent;
163
+ color: var(--text-muted);
164
+ }
165
+
166
+ .btn-ghost:hover {
167
+ color: var(--text-main);
168
+ background: rgba(255, 255, 255, 0.05);
169
+ }
170
+
171
+ /* Main Area */
172
+ .top {
173
+ display: grid;
174
+ grid-template-columns: 260px 1fr;
175
+ overflow: hidden;
176
+ }
177
+
178
+ /* Sidebar */
179
+ .sidebar {
180
+ background: var(--bg-sidebar);
181
+ border-right: 1px solid var(--border);
182
+ display: flex;
183
+ flex-direction: column;
184
+ }
185
+
186
+ .toolbar {
187
+ padding: 12px;
188
+ border-bottom: 1px solid var(--border);
189
+ display: flex;
190
+ gap: 8px;
191
+ }
192
+
193
+ .toolbar .btn {
194
+ flex: 1;
195
+ padding: 6px;
196
+ font-size: 12px;
197
+ }
198
+
199
+ .file-list {
200
+ list-style: none;
201
+ margin: 0;
202
+ padding: 8px;
203
+ overflow-y: auto;
204
+ flex: 1;
205
+ }
206
+
207
+ .file-item {
208
+ padding: 8px 12px;
209
+ margin-bottom: 2px;
210
+ border-radius: var(--radius);
211
+ display: flex;
212
+ align-items: center;
213
+ gap: 10px;
214
+ color: var(--text-muted);
215
+ cursor: pointer;
216
+ font-size: 13px;
217
+ transition: background 0.15s;
218
+ }
219
+
220
+ .file-item:hover,
221
+ .file-item.active {
222
+ background: var(--bg-hover);
223
+ color: var(--text-main);
224
+ }
225
+
226
+ .file-item.active {
227
+ font-weight: 500;
228
+ border-left: 2px solid var(--primary);
229
+ border-top-left-radius: 2px;
230
+ border-bottom-left-radius: 2px;
231
+ }
232
+
233
+ /* Editor */
234
+ .editor {
235
+ position: relative;
236
+ background: var(--bg-card);
237
+ }
238
+
239
+ #editor {
240
+ width: 100%;
241
+ height: 100%;
242
+ }
243
+
244
+ /* Terminal */
245
+ .terminal {
246
+ background: var(--bg-dark);
247
+ border-top: 1px solid var(--border);
248
+ display: flex;
249
+ flex-direction: column;
250
+ box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.2);
251
+ }
252
+
253
+ .term-chrome {
254
+ height: 36px;
255
+ display: flex;
256
+ align-items: center;
257
+ padding: 0 16px;
258
+ background: var(--bg-sidebar);
259
+ border-bottom: 1px solid var(--border);
260
+ gap: 10px;
261
+ }
262
+
263
+ .traffic-lights {
264
+ display: flex;
265
+ gap: 6px;
266
+ }
267
+
268
+ .traffic-light {
269
+ width: 10px;
270
+ height: 10px;
271
+ border-radius: 50%;
272
+ }
273
+
274
+ .traffic-light.red {
275
+ background: #ff5f57;
276
+ }
277
+
278
+ .traffic-light.yellow {
279
+ background: #febc2e;
280
+ }
281
+
282
+ .traffic-light.green {
283
+ background: #28c840;
284
+ }
285
+
286
+ .term-title {
287
+ font-size: 12px;
288
+ color: var(--text-muted);
289
+ font-family: var(--font-mono);
290
+ opacity: 0.7;
291
+ }
292
+
293
+ #output {
294
+ flex: 1;
295
+ padding: 16px;
296
+ /* increased padding */
297
+ font-family: var(--font-mono);
298
+ font-size: 13px;
299
+ color: var(--text-main);
300
+ overflow-y: auto;
301
+ line-height: 1.5;
302
+ }
303
+
304
+ #output .line {
305
+ min-height: 1.5em;
306
+ }
307
+
308
+ /* Components */
309
+ .modal-overlay {
310
+ position: fixed;
311
+ inset: 0;
312
+ background: rgba(0, 0, 0, 0.7);
313
+ backdrop-filter: blur(4px);
314
+ z-index: 100;
315
+ display: flex;
316
+ align-items: center;
317
+ justify-content: center;
318
+ opacity: 0;
319
+ pointer-events: none;
320
+ transition: opacity 0.2s;
321
+ }
322
+
323
+ .modal-overlay.open {
324
+ opacity: 1;
325
+ pointer-events: auto;
326
+ }
327
+
328
+ .modal {
329
+ background: #18181b;
330
+ border: 1px solid var(--border);
331
+ border-radius: var(--radius-lg);
332
+ padding: 24px;
333
+ width: 90%;
334
+ max-width: 420px;
335
+ box-shadow: var(--shadow-lg);
336
+ transform: scale(0.95);
337
+ transition: transform 0.2s;
338
+ }
339
+
340
+ .modal-overlay.open .modal {
341
+ transform: scale(1);
342
+ }
343
+
344
+ .modal h3 {
345
+ margin-top: 0;
346
+ font-size: 18px;
347
+ font-weight: 600;
348
+ margin-bottom: 8px;
349
+ }
350
+
351
+ .modal p {
352
+ color: var(--text-muted);
353
+ font-size: 14px;
354
+ margin-bottom: 20px;
355
+ line-height: 1.5;
356
+ }
357
+
358
+ .input-group {
359
+ margin-bottom: 16px;
360
+ }
361
+
362
+ .input {
363
+ width: 100%;
364
+ padding: 10px 12px;
365
+ background: var(--bg-hover);
366
+ border: 1px solid var(--border);
367
+ border-radius: var(--radius);
368
+ color: var(--text-main);
369
+ font-family: var(--font-sans);
370
+ font-size: 14px;
371
+ transition: border-color 0.2s, box-shadow 0.2s;
372
+ }
373
+
374
+ .input:focus {
375
+ outline: none;
376
+ border-color: var(--primary);
377
+ box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
378
+ }
379
+
380
+ .modal-footer {
381
+ display: flex;
382
+ gap: 12px;
383
+ margin-top: 24px;
384
+ }
385
+
386
+ .modal-footer .btn {
387
+ flex: 1;
388
+ }
389
+
390
+ .diff-modal .modal {
391
+ max-width: 800px;
392
+ max-height: 85vh;
393
+ display: flex;
394
+ flex-direction: column;
395
+ }
396
+
397
+ .diff-content {
398
+ overflow-y: auto;
399
+ background: var(--bg-dark);
400
+ border-radius: var(--radius);
401
+ padding: 12px;
402
+ font-family: var(--font-mono);
403
+ font-size: 12px;
404
+ border: 1px solid var(--border);
405
+ }
406
+
407
+ /* Utilities */
408
+ .hidden {
409
+ display: none !important;
410
+ }
411
+
412
+ .spin {
413
+ animation: spin 1s linear infinite;
414
+ }
415
+
416
+ @keyframes spin {
417
+ 100% {
418
+ transform: rotate(360deg);
419
+ }
420
+ }
421
+
422
+ /* Context Menu */
423
+ #ctxMenu {
424
+ background: var(--bg-card);
425
+ border: 1px solid var(--border-light);
426
+ border-radius: var(--radius);
427
+ padding: 4px;
428
+ box-shadow: var(--shadow-lg);
429
+ position: fixed;
430
+ z-index: 100;
431
+ min-width: 160px;
432
+ }
433
+
434
+ #ctxMenu button {
435
+ width: 100%;
436
+ text-align: left;
437
+ padding: 8px 12px;
438
+ background: transparent;
439
+ color: var(--text-main);
440
+ font-size: 13px;
441
+ border-radius: 4px;
442
+ }
443
+
444
+ #ctxMenu button:hover {
445
+ background: var(--primary);
446
+ color: white;
447
+ }
448
+
449
+ /* Loading */
450
+ .loading-card {
451
+ background: var(--bg-card);
452
+ padding: 16px 24px;
453
+ border-radius: var(--radius-lg);
454
+ display: flex;
455
+ align-items: center;
456
+ gap: 16px;
457
+ border: 1px solid var(--border);
458
+ box-shadow: var(--shadow-glow);
459
+ }
server/package-lock.json CHANGED
@@ -17,6 +17,7 @@
17
  "express": "^5.1.0",
18
  "express-rate-limit": "^8.1.0",
19
  "jsonwebtoken": "^9.0.2",
 
20
  "pg": "^8.16.3",
21
  "uuid": "^13.0.0"
22
  },
@@ -51,6 +52,15 @@
51
  "node": ">= 8"
52
  }
53
  },
 
 
 
 
 
 
 
 
 
54
  "node_modules/balanced-match": {
55
  "version": "1.0.2",
56
  "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -303,6 +313,15 @@
303
  }
304
  }
305
  },
 
 
 
 
 
 
 
 
 
306
  "node_modules/depd": {
307
  "version": "2.0.0",
308
  "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -536,6 +555,15 @@
536
  "url": "https://github.com/sponsors/ljharb"
537
  }
538
  },
 
 
 
 
 
 
 
 
 
539
  "node_modules/get-intrinsic": {
540
  "version": "1.3.0",
541
  "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -752,6 +780,12 @@
752
  "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
753
  "license": "MIT"
754
  },
 
 
 
 
 
 
755
  "node_modules/jsonwebtoken": {
756
  "version": "9.0.2",
757
  "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
@@ -837,6 +871,27 @@
837
  "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
838
  "license": "MIT"
839
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840
  "node_modules/math-intrinsics": {
841
  "version": "1.1.0",
842
  "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -907,6 +962,54 @@
907
  "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
908
  "license": "MIT"
909
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
910
  "node_modules/negotiator": {
911
  "version": "1.0.0",
912
  "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
@@ -1341,6 +1444,11 @@
1341
  "node": ">= 18"
1342
  }
1343
  },
 
 
 
 
 
1344
  "node_modules/serve-static": {
1345
  "version": "2.2.0",
1346
  "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
@@ -1456,6 +1564,15 @@
1456
  "node": ">= 10.x"
1457
  }
1458
  },
 
 
 
 
 
 
 
 
 
1459
  "node_modules/statuses": {
1460
  "version": "2.0.2",
1461
  "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
 
17
  "express": "^5.1.0",
18
  "express-rate-limit": "^8.1.0",
19
  "jsonwebtoken": "^9.0.2",
20
+ "mysql2": "^3.15.3",
21
  "pg": "^8.16.3",
22
  "uuid": "^13.0.0"
23
  },
 
52
  "node": ">= 8"
53
  }
54
  },
55
+ "node_modules/aws-ssl-profiles": {
56
+ "version": "1.1.2",
57
+ "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
58
+ "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
59
+ "license": "MIT",
60
+ "engines": {
61
+ "node": ">= 6.0.0"
62
+ }
63
+ },
64
  "node_modules/balanced-match": {
65
  "version": "1.0.2",
66
  "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
 
313
  }
314
  }
315
  },
316
+ "node_modules/denque": {
317
+ "version": "2.1.0",
318
+ "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
319
+ "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
320
+ "license": "Apache-2.0",
321
+ "engines": {
322
+ "node": ">=0.10"
323
+ }
324
+ },
325
  "node_modules/depd": {
326
  "version": "2.0.0",
327
  "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
 
555
  "url": "https://github.com/sponsors/ljharb"
556
  }
557
  },
558
+ "node_modules/generate-function": {
559
+ "version": "2.3.1",
560
+ "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
561
+ "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
562
+ "license": "MIT",
563
+ "dependencies": {
564
+ "is-property": "^1.0.2"
565
+ }
566
+ },
567
  "node_modules/get-intrinsic": {
568
  "version": "1.3.0",
569
  "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
 
780
  "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
781
  "license": "MIT"
782
  },
783
+ "node_modules/is-property": {
784
+ "version": "1.0.2",
785
+ "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
786
+ "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
787
+ "license": "MIT"
788
+ },
789
  "node_modules/jsonwebtoken": {
790
  "version": "9.0.2",
791
  "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
 
871
  "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
872
  "license": "MIT"
873
  },
874
+ "node_modules/long": {
875
+ "version": "5.3.2",
876
+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
877
+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
878
+ "license": "Apache-2.0"
879
+ },
880
+ "node_modules/lru.min": {
881
+ "version": "1.1.3",
882
+ "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.3.tgz",
883
+ "integrity": "sha512-Lkk/vx6ak3rYkRR0Nhu4lFUT2VDnQSxBe8Hbl7f36358p6ow8Bnvr8lrLt98H8J1aGxfhbX4Fs5tYg2+FTwr5Q==",
884
+ "license": "MIT",
885
+ "engines": {
886
+ "bun": ">=1.0.0",
887
+ "deno": ">=1.30.0",
888
+ "node": ">=8.0.0"
889
+ },
890
+ "funding": {
891
+ "type": "github",
892
+ "url": "https://github.com/sponsors/wellwelwel"
893
+ }
894
+ },
895
  "node_modules/math-intrinsics": {
896
  "version": "1.1.0",
897
  "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
 
962
  "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
963
  "license": "MIT"
964
  },
965
+ "node_modules/mysql2": {
966
+ "version": "3.15.3",
967
+ "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.15.3.tgz",
968
+ "integrity": "sha512-FBrGau0IXmuqg4haEZRBfHNWB5mUARw6hNwPDXXGg0XzVJ50mr/9hb267lvpVMnhZ1FON3qNd4Xfcez1rbFwSg==",
969
+ "license": "MIT",
970
+ "dependencies": {
971
+ "aws-ssl-profiles": "^1.1.1",
972
+ "denque": "^2.1.0",
973
+ "generate-function": "^2.3.1",
974
+ "iconv-lite": "^0.7.0",
975
+ "long": "^5.2.1",
976
+ "lru.min": "^1.0.0",
977
+ "named-placeholders": "^1.1.3",
978
+ "seq-queue": "^0.0.5",
979
+ "sqlstring": "^2.3.2"
980
+ },
981
+ "engines": {
982
+ "node": ">= 8.0"
983
+ }
984
+ },
985
+ "node_modules/mysql2/node_modules/iconv-lite": {
986
+ "version": "0.7.0",
987
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz",
988
+ "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==",
989
+ "license": "MIT",
990
+ "dependencies": {
991
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
992
+ },
993
+ "engines": {
994
+ "node": ">=0.10.0"
995
+ },
996
+ "funding": {
997
+ "type": "opencollective",
998
+ "url": "https://opencollective.com/express"
999
+ }
1000
+ },
1001
+ "node_modules/named-placeholders": {
1002
+ "version": "1.1.4",
1003
+ "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.4.tgz",
1004
+ "integrity": "sha512-/qfG0Kk/bLJIvej4FcPQ2KYUJP8iQdU1CTxysNb/U2wUNb+/4K485yeio8iNoiwfqJnsTInXoRPTza0dZWHVJQ==",
1005
+ "license": "MIT",
1006
+ "dependencies": {
1007
+ "lru.min": "^1.1.0"
1008
+ },
1009
+ "engines": {
1010
+ "node": ">=8.0.0"
1011
+ }
1012
+ },
1013
  "node_modules/negotiator": {
1014
  "version": "1.0.0",
1015
  "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
 
1444
  "node": ">= 18"
1445
  }
1446
  },
1447
+ "node_modules/seq-queue": {
1448
+ "version": "0.0.5",
1449
+ "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz",
1450
+ "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q=="
1451
+ },
1452
  "node_modules/serve-static": {
1453
  "version": "2.2.0",
1454
  "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
 
1564
  "node": ">= 10.x"
1565
  }
1566
  },
1567
+ "node_modules/sqlstring": {
1568
+ "version": "2.3.3",
1569
+ "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
1570
+ "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==",
1571
+ "license": "MIT",
1572
+ "engines": {
1573
+ "node": ">= 0.6"
1574
+ }
1575
+ },
1576
  "node_modules/statuses": {
1577
  "version": "2.0.2",
1578
  "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
server/package.json CHANGED
@@ -18,6 +18,7 @@
18
  "express": "^5.1.0",
19
  "express-rate-limit": "^8.1.0",
20
  "jsonwebtoken": "^9.0.2",
 
21
  "pg": "^8.16.3",
22
  "uuid": "^13.0.0"
23
  },
 
18
  "express": "^5.1.0",
19
  "express-rate-limit": "^8.1.0",
20
  "jsonwebtoken": "^9.0.2",
21
+ "mysql2": "^3.15.3",
22
  "pg": "^8.16.3",
23
  "uuid": "^13.0.0"
24
  },
server/src/ai.js CHANGED
@@ -2,44 +2,48 @@ const { getPool } = require('./db');
2
  const { authMiddleware } = require('./auth');
3
  const { v4: uuidv4 } = require('uuid');
4
 
 
 
 
5
  async function getCodebase(db, userId) {
6
- const { rows } = await db.query('SELECT path, content, is_binary FROM files WHERE user_id=$1 ORDER BY path', [userId]);
7
  return rows.map(r => ({ path: r.path, content: Buffer.from(r.content).toString(r.is_binary ? 'base64' : 'utf8'), isBinary: r.is_binary }));
8
  }
9
 
10
  function buildPrompt(codebase, errorOutput) {
11
- const index = codebase.map(f=>`- ${f.path}`).join('\n');
12
- return `You are an expert Python developer. Analyze the following codebase and error output. Return a JSON object with keys:\n- reason: short plain-text root cause analysis (1-3 sentences)\n- changes: array where each item is {path, newContent, isBinary:false}. Only propose safe fixes.\n\nFILE INDEX (paths only):\n${index}\n\nERROR OUTPUT:\n${errorOutput}\n\nCODEBASE FILES (path then content):\n${codebase.map(f=>`# ${f.path}\n${f.isBinary ? '(binary omitted)' : f.content}`).join('\n\n')}`;
13
  }
14
 
15
- async function callGemini(apiKey, prompt) {
16
- // WARNING: Hardcoding secrets is unsafe. Use environment variables in production.
17
- const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' + 'AIzaSyCx5FWyytL-KTd92v8ZDcYPPFl2N0fZaIc';
18
- const resp = await fetch(url, {
19
- method: 'POST',
20
- headers: { 'Content-Type': 'application/json' },
21
- body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
22
- });
23
- if (!resp.ok) throw new Error('Gemini request failed: ' + resp.status);
24
- const data = await resp.json();
25
- const text = data?.candidates?.[0]?.content?.parts?.[0]?.text || '';
26
- return text;
 
 
 
 
27
  }
28
 
29
  function tryParseJsonFromText(text) {
30
  if (!text) return null;
31
- // Prefer ```json fenced blocks
32
  const fence = text.match(/```json\s*([\s\S]*?)```/i);
33
  if (fence && fence[1]) {
34
- try { return JSON.parse(fence[1]); } catch {}
35
  }
36
- // Fallback: first code fence
37
  const anyFence = text.match(/```\s*([\s\S]*?)```/);
38
  if (anyFence && anyFence[1]) {
39
- try { return JSON.parse(anyFence[1]); } catch {}
40
  }
41
- // Last resort: direct parse
42
- try { return JSON.parse(text); } catch {}
43
  return null;
44
  }
45
 
@@ -53,47 +57,43 @@ function register(app) {
53
  const prompt = buildPrompt(codebase, errorOutput);
54
  let parsed = { changes: [], reason: '' };
55
  try {
56
- const text = await callGemini(app.get('config').GEMINI_API_KEY, prompt);
57
  const maybe = tryParseJsonFromText(text);
58
- if (maybe && Array.isArray(maybe.changes)) parsed = { changes: maybe.changes, reason: String(maybe.reason||'') };
59
- } catch (e) {
60
- console.error('AI error', e);
61
- // keep parsed as empty
62
- }
63
  const id = uuidv4();
64
- await db().query('INSERT INTO ai_fixes (id, user_id, request_json, proposed_diff) VALUES ($1, $2, $3, $4)', [id, req.user.id, JSON.stringify({ errorOutput }), JSON.stringify(parsed)]);
65
  res.json({ id, proposed: parsed });
66
  });
67
 
68
  app.post('/api/ai/apply-fix', authMiddleware, async (req, res) => {
69
  const { id } = req.body || {};
70
  if (!id) return res.status(400).json({ error: 'id required' });
71
- const { rows } = await db().query('SELECT proposed_diff FROM ai_fixes WHERE id=$1 AND user_id=$2', [id, req.user.id]);
72
  if (!rows[0]) return res.status(404).json({ error: 'Not found' });
73
  const diff = rows[0].proposed_diff || { changes: [] };
74
- const client = await db().connect();
75
  try {
76
- await client.query('BEGIN');
77
  for (const c of diff.changes || []) {
78
  const contentBuf = Buffer.from(c.newContent || '', 'utf8');
79
- const r = await client.query('SELECT id FROM files WHERE user_id=$1 AND path=$2', [req.user.id, c.path]);
80
- if (r.rows[0]) {
81
- await client.query('UPDATE files SET content=$1, is_binary=false, updated_at=NOW() WHERE id=$2', [contentBuf, r.rows[0].id]);
82
  } else {
83
- const { v4: uuidv4 } = require('uuid');
84
  const fileId = uuidv4();
85
- await client.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES ($1, $2, $3, $4, false)', [fileId, req.user.id, c.path, contentBuf]);
86
  }
87
  }
88
- await client.query('UPDATE ai_fixes SET applied=true WHERE id=$1', [id]);
89
- await client.query('COMMIT');
90
  res.json({ ok: true });
91
  } catch (e) {
92
- await client.query('ROLLBACK');
93
  console.error(e);
94
  res.status(500).json({ error: 'Internal error' });
95
  } finally {
96
- client.release();
97
  }
98
  });
99
 
@@ -101,40 +101,36 @@ function register(app) {
101
  const { prompt, targetPath } = req.body || {};
102
  if (!prompt) return res.status(400).json({ error: 'prompt required' });
103
  const codebase = await getCodebase(db(), req.user.id);
104
- const guide = `You are an expert coder. Based on the existing codebase, generate or edit files.
105
- Return JSON strictly as {changes:[{path,newContent,isBinary:false}]}. Respond with multiple files if needed.
106
- Preserve style and do not include explanations.`;
107
- const index = codebase.map(f=>`- ${f.path}`).join('\n');
108
- const context = codebase.map(f=>`# ${f.path}\n${f.isBinary ? '(binary omitted)' : f.content}`).join('\n\n');
109
- const text = await callGemini(app.get('config').GEMINI_API_KEY, `${guide}\nTARGET: ${targetPath||'(may create multiple)'}\nPROMPT: ${prompt}\n\nFILE INDEX:\n${index}\n\nFILES (path then content):\n${context}`);
110
  let parsed = tryParseJsonFromText(text);
111
  if (!parsed || !Array.isArray(parsed.changes)) {
112
- // Fallback to single target or abort
113
  if (!targetPath) return res.status(400).json({ error: 'AI did not return valid changes; specify targetPath' });
114
  parsed = { changes: [{ path: targetPath, newContent: text, isBinary: false }] };
115
  }
116
- // Apply result immediately
117
- const client = await db().connect();
118
  try {
119
- await client.query('BEGIN');
120
  for (const c of parsed.changes || []) {
121
  const contentBuf = Buffer.from(c.newContent || '', 'utf8');
122
- const r = await client.query('SELECT id FROM files WHERE user_id=$1 AND path=$2', [req.user.id, c.path]);
123
- if (r.rows[0]) {
124
- await client.query('UPDATE files SET content=$1, is_binary=false, updated_at=NOW() WHERE id=$2', [contentBuf, r.rows[0].id]);
125
  } else {
126
- const fileId = require('uuid').v4();
127
- await client.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES ($1, $2, $3, $4, false)', [fileId, req.user.id, c.path, contentBuf]);
128
  }
129
  }
130
- await client.query('COMMIT');
131
  res.json({ ok: true, applied: parsed });
132
  } catch (e) {
133
- await client.query('ROLLBACK');
134
  console.error(e);
135
  res.status(500).json({ error: 'Internal error' });
136
  } finally {
137
- client.release();
138
  }
139
  });
140
 
@@ -144,31 +140,31 @@ Preserve style and do not include explanations.`;
144
  try {
145
  const codebase = await getCodebase(db(), req.user.id);
146
  const guide = `You will propose safe edits to an existing codebase. Return JSON {changes:[{path,newContent,isBinary:false}]}. Only include files that change. Preserve formatting.`;
147
- const index = codebase.map(f=>`- ${f.path}`).join('\n');
148
- const context = codebase.map(f=>`# ${f.path}\n${f.isBinary ? '(binary omitted)' : f.content}`).join('\n\n');
149
- const text = await callGemini(app.get('config').GEMINI_API_KEY, `${guide}\nTARGET: ${targetPath||'(auto)'}\nINSTRUCTION: ${instruction}\n\nFILE INDEX:\n${index}\n\nFILES (path then content):\n${context}`);
150
  const parsed = tryParseJsonFromText(text) || { changes: [] };
151
- const client = await db().connect();
152
  try {
153
- await client.query('BEGIN');
154
  for (const c of parsed.changes || []) {
155
  const contentBuf = Buffer.from(c.newContent || '', 'utf8');
156
- const r = await client.query('SELECT id FROM files WHERE user_id=$1 AND path=$2', [req.user.id, c.path]);
157
- if (r.rows[0]) {
158
- await client.query('UPDATE files SET content=$1, is_binary=false, updated_at=NOW() WHERE id=$2', [contentBuf, r.rows[0].id]);
159
  } else {
160
- const fileId = require('uuid').v4();
161
- await client.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES ($1, $2, $3, $4, false)', [fileId, req.user.id, c.path, contentBuf]);
162
  }
163
  }
164
- await client.query('COMMIT');
165
  res.json({ ok: true, applied: parsed });
166
  } catch (e) {
167
- await client.query('ROLLBACK');
168
  console.error(e);
169
  res.status(500).json({ error: 'Internal error' });
170
  } finally {
171
- client.release();
172
  }
173
  } catch (e) {
174
  console.error('AI edit error', e);
 
2
  const { authMiddleware } = require('./auth');
3
  const { v4: uuidv4 } = require('uuid');
4
 
5
+ // Cloudflare AI Worker Config
6
+ const CF_AI_URL = 'https://rough-thunder-e62d.veltrix620.workers.dev/fast';
7
+
8
  async function getCodebase(db, userId) {
9
+ const [rows] = await db.query('SELECT path, content, is_binary FROM files WHERE user_id=? ORDER BY path', [userId]);
10
  return rows.map(r => ({ path: r.path, content: Buffer.from(r.content).toString(r.is_binary ? 'base64' : 'utf8'), isBinary: r.is_binary }));
11
  }
12
 
13
  function buildPrompt(codebase, errorOutput) {
14
+ const index = codebase.map(f => `- ${f.path}`).join('\n');
15
+ return `You are an expert Python developer. Analyze the following codebase and error output. Return a JSON object with keys:\n- reason: short plain-text root cause analysis (1-3 sentences)\n- changes: array where each item is {path, newContent, isBinary:false}. Only propose safe fixes.\n\nFILE INDEX (paths only):\n${index}\n\nERROR OUTPUT:\n${errorOutput}\n\nCODEBASE FILES (path then content):\n${codebase.map(f => `# ${f.path}\n${f.isBinary ? '(binary omitted)' : f.content}`).join('\n\n')}`;
16
  }
17
 
18
+ async function callAI(prompt) {
19
+ try {
20
+ // Attempting POST to the worker assuming it can handle the body
21
+ const resp = await fetch(CF_AI_URL, {
22
+ method: 'POST',
23
+ headers: { 'Content-Type': 'application/json' },
24
+ body: JSON.stringify({ message: prompt }) // Mapping prompt to 'message' as per user hint
25
+ });
26
+ if (!resp.ok) throw new Error('AI request failed: ' + resp.status);
27
+ const data = await resp.json();
28
+ return data.response || '';
29
+ } catch (e) {
30
+ // Fallback just in case
31
+ console.error('AI Call failed, trying simple', e);
32
+ throw e;
33
+ }
34
  }
35
 
36
  function tryParseJsonFromText(text) {
37
  if (!text) return null;
 
38
  const fence = text.match(/```json\s*([\s\S]*?)```/i);
39
  if (fence && fence[1]) {
40
+ try { return JSON.parse(fence[1]); } catch { }
41
  }
 
42
  const anyFence = text.match(/```\s*([\s\S]*?)```/);
43
  if (anyFence && anyFence[1]) {
44
+ try { return JSON.parse(anyFence[1]); } catch { }
45
  }
46
+ try { return JSON.parse(text); } catch { }
 
47
  return null;
48
  }
49
 
 
57
  const prompt = buildPrompt(codebase, errorOutput);
58
  let parsed = { changes: [], reason: '' };
59
  try {
60
+ const text = await callAI(prompt);
61
  const maybe = tryParseJsonFromText(text);
62
+ if (maybe && Array.isArray(maybe.changes)) parsed = { changes: maybe.changes, reason: String(maybe.reason || '') };
63
+ } catch (e) { console.error('AI error', e); }
 
 
 
64
  const id = uuidv4();
65
+ await db().query('INSERT INTO ai_fixes (id, user_id, request_json, proposed_diff) VALUES (?, ?, ?, ?)', [id, req.user.id, JSON.stringify({ errorOutput }), JSON.stringify(parsed)]);
66
  res.json({ id, proposed: parsed });
67
  });
68
 
69
  app.post('/api/ai/apply-fix', authMiddleware, async (req, res) => {
70
  const { id } = req.body || {};
71
  if (!id) return res.status(400).json({ error: 'id required' });
72
+ const [rows] = await db().query('SELECT proposed_diff FROM ai_fixes WHERE id=? AND user_id=?', [id, req.user.id]);
73
  if (!rows[0]) return res.status(404).json({ error: 'Not found' });
74
  const diff = rows[0].proposed_diff || { changes: [] };
75
+ const conn = await db().getConnection();
76
  try {
77
+ await conn.beginTransaction();
78
  for (const c of diff.changes || []) {
79
  const contentBuf = Buffer.from(c.newContent || '', 'utf8');
80
+ const [r] = await conn.query('SELECT id FROM files WHERE user_id=? AND path=?', [req.user.id, c.path]);
81
+ if (r[0]) {
82
+ await conn.query('UPDATE files SET content=?, is_binary=false, updated_at=NOW() WHERE id=?', [contentBuf, r[0].id]);
83
  } else {
 
84
  const fileId = uuidv4();
85
+ await conn.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES (?, ?, ?, ?, false)', [fileId, req.user.id, c.path, contentBuf]);
86
  }
87
  }
88
+ await conn.query('UPDATE ai_fixes SET applied=true WHERE id=?', [id]);
89
+ await conn.commit();
90
  res.json({ ok: true });
91
  } catch (e) {
92
+ await conn.rollback();
93
  console.error(e);
94
  res.status(500).json({ error: 'Internal error' });
95
  } finally {
96
+ conn.release();
97
  }
98
  });
99
 
 
101
  const { prompt, targetPath } = req.body || {};
102
  if (!prompt) return res.status(400).json({ error: 'prompt required' });
103
  const codebase = await getCodebase(db(), req.user.id);
104
+ const guide = `You are an expert coder. Based on the existing codebase, generate or edit files.\nReturn JSON strictly as {changes:[{path,newContent,isBinary:false}]}. Respond with multiple files if needed.\nPreserve style and do not include explanations.`;
105
+ const index = codebase.map(f => `- ${f.path}`).join('\n');
106
+ const context = codebase.map(f => `# ${f.path}\n${f.isBinary ? '(binary omitted)' : f.content}`).join('\n\n');
107
+ const text = await callAI(`${guide}\nTARGET: ${targetPath || '(may create multiple)'}\nPROMPT: ${prompt}\n\nFILE INDEX:\n${index}\n\nFILES (path then content):\n${context}`);
 
 
108
  let parsed = tryParseJsonFromText(text);
109
  if (!parsed || !Array.isArray(parsed.changes)) {
 
110
  if (!targetPath) return res.status(400).json({ error: 'AI did not return valid changes; specify targetPath' });
111
  parsed = { changes: [{ path: targetPath, newContent: text, isBinary: false }] };
112
  }
113
+ const conn = await db().getConnection();
 
114
  try {
115
+ await conn.beginTransaction();
116
  for (const c of parsed.changes || []) {
117
  const contentBuf = Buffer.from(c.newContent || '', 'utf8');
118
+ const [r] = await conn.query('SELECT id FROM files WHERE user_id=? AND path=?', [req.user.id, c.path]);
119
+ if (r[0]) {
120
+ await conn.query('UPDATE files SET content=?, is_binary=false, updated_at=NOW() WHERE id=?', [contentBuf, r[0].id]);
121
  } else {
122
+ const fileId = uuidv4();
123
+ await conn.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES (?, ?, ?, ?, false)', [fileId, req.user.id, c.path, contentBuf]);
124
  }
125
  }
126
+ await conn.commit();
127
  res.json({ ok: true, applied: parsed });
128
  } catch (e) {
129
+ await conn.rollback();
130
  console.error(e);
131
  res.status(500).json({ error: 'Internal error' });
132
  } finally {
133
+ conn.release();
134
  }
135
  });
136
 
 
140
  try {
141
  const codebase = await getCodebase(db(), req.user.id);
142
  const guide = `You will propose safe edits to an existing codebase. Return JSON {changes:[{path,newContent,isBinary:false}]}. Only include files that change. Preserve formatting.`;
143
+ const index = codebase.map(f => `- ${f.path}`).join('\n');
144
+ const context = codebase.map(f => `# ${f.path}\n${f.isBinary ? '(binary omitted)' : f.content}`).join('\n\n');
145
+ const text = await callAI(`${guide}\nTARGET: ${targetPath || '(auto)'}\nINSTRUCTION: ${instruction}\n\nFILE INDEX:\n${index}\n\nFILES (path then content):\n${context}`);
146
  const parsed = tryParseJsonFromText(text) || { changes: [] };
147
+ const conn = await db().getConnection();
148
  try {
149
+ await conn.beginTransaction();
150
  for (const c of parsed.changes || []) {
151
  const contentBuf = Buffer.from(c.newContent || '', 'utf8');
152
+ const [r] = await conn.query('SELECT id FROM files WHERE user_id=? AND path=?', [req.user.id, c.path]);
153
+ if (r[0]) {
154
+ await conn.query('UPDATE files SET content=?, is_binary=false, updated_at=NOW() WHERE id=?', [contentBuf, r[0].id]);
155
  } else {
156
+ const fileId = uuidv4();
157
+ await conn.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES (?, ?, ?, ?, false)', [fileId, req.user.id, c.path, contentBuf]);
158
  }
159
  }
160
+ await conn.commit();
161
  res.json({ ok: true, applied: parsed });
162
  } catch (e) {
163
+ await conn.rollback();
164
  console.error(e);
165
  res.status(500).json({ error: 'Internal error' });
166
  } finally {
167
+ conn.release();
168
  }
169
  } catch (e) {
170
  console.error('AI edit error', e);
server/src/auth.js CHANGED
@@ -21,38 +21,44 @@ function register(app) {
21
  const { email, password, name, class: klass, section } = req.body || {};
22
  if (!email || !password || !name || !klass || !section) return res.status(400).json({ error: 'name, class, section, email and password required' });
23
  const db = getPool(app.get('config'));
24
- const client = await db.connect();
25
  try {
26
  // Determine users.id data type to insert appropriately
27
- const { rows: typeRows } = await client.query("SELECT data_type FROM information_schema.columns WHERE table_name='users' AND column_name='id'");
28
- const idType = (typeRows[0]?.data_type || '').toLowerCase();
29
  let userId;
30
  const wsId = uuidv4();
31
  const passwordHash = await bcrypt.hash(password, 10);
32
- await client.query('BEGIN');
33
- if (idType === 'uuid') {
 
34
  userId = uuidv4();
35
- await client.query('INSERT INTO users (id, email, password_hash, name, class, section) VALUES ($1, $2, $3, $4, $5, $6)', [userId, email, passwordHash, name, klass, section]);
36
  } else {
37
- const inserted = await client.query('INSERT INTO users (email, password_hash, name, class, section) VALUES ($1, $2, $3, $4, $5) RETURNING id', [email, passwordHash, name, klass, section]);
38
- userId = inserted.rows[0].id;
 
39
  }
40
- await client.query('INSERT INTO workspaces (id, user_id) VALUES ($1, $2)', [wsId, userId]);
 
 
 
41
  // Default main.py
42
  const fileId = uuidv4();
43
  const content = Buffer.from('print("HELLO FROM SHASHWAT")\n');
44
- await client.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES ($1, $2, $3, $4, false)', [fileId, userId, 'main.py', content]);
45
- await client.query('COMMIT');
 
46
  const token = jwt.sign({ id: userId, email }, app.get('config').JWT_SECRET, { expiresIn: '7d' });
47
  res.cookie('token', token, { httpOnly: true, sameSite: 'lax' });
48
  res.json({ ok: true });
49
  } catch (e) {
50
- await client.query('ROLLBACK');
51
- if (e.code === '23505') return res.status(409).json({ error: 'Email already in use' });
52
  console.error(e);
53
  res.status(500).json({ error: 'Internal error' });
54
  } finally {
55
- client.release();
56
  }
57
  });
58
 
@@ -60,7 +66,7 @@ function register(app) {
60
  const { email, password } = req.body || {};
61
  if (!email || !password) return res.status(400).json({ error: 'email and password required' });
62
  const db = getPool(app.get('config'));
63
- const { rows } = await db.query('SELECT id, password_hash, name, class, section FROM users WHERE email=$1', [email]);
64
  if (!rows[0]) return res.status(401).json({ error: 'Invalid credentials' });
65
  const valid = await bcrypt.compare(password, rows[0].password_hash);
66
  if (!valid) return res.status(401).json({ error: 'Invalid credentials' });
@@ -72,7 +78,7 @@ function register(app) {
72
  app.get('/api/auth/me', authMiddleware, async (req, res) => {
73
  // Hydrate name/class/section from DB in case token is old
74
  const db = getPool(app.get('config'));
75
- const { rows } = await db.query('SELECT email, name, class, section FROM users WHERE id=$1', [req.user.id]);
76
  const u = rows[0] || {};
77
  res.json({ user: { id: req.user.id, email: u.email || req.user.email, name: u.name, class: u.class, section: u.section } });
78
  });
 
21
  const { email, password, name, class: klass, section } = req.body || {};
22
  if (!email || !password || !name || !klass || !section) return res.status(400).json({ error: 'name, class, section, email and password required' });
23
  const db = getPool(app.get('config'));
24
+ const conn = await db.getConnection();
25
  try {
26
  // Determine users.id data type to insert appropriately
27
+ const [typeRows] = await conn.query("SELECT COLUMN_TYPE FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='users' AND column_name='id'");
28
+ const idType = (typeRows[0]?.COLUMN_TYPE || '').toLowerCase();
29
  let userId;
30
  const wsId = uuidv4();
31
  const passwordHash = await bcrypt.hash(password, 10);
32
+ await conn.beginTransaction();
33
+
34
+ if (idType.includes('char') || idType.includes('text') || idType.includes('uuid')) {
35
  userId = uuidv4();
36
+ await conn.query('INSERT INTO users (id, email, password_hash, name, class, section) VALUES (?, ?, ?, ?, ?, ?)', [userId, email, passwordHash, name, klass, section]);
37
  } else {
38
+ // Integer auto-increment
39
+ const [res] = await conn.query('INSERT INTO users (email, password_hash, name, class, section) VALUES (?, ?, ?, ?, ?)', [email, passwordHash, name, klass, section]);
40
+ userId = res.insertId;
41
  }
42
+
43
+ // Workspaces with ON DUPLICATE KEY UPDATE or generic insert
44
+ await conn.query('INSERT INTO workspaces (id, user_id) VALUES (?, ?)', [wsId, userId]);
45
+
46
  // Default main.py
47
  const fileId = uuidv4();
48
  const content = Buffer.from('print("HELLO FROM SHASHWAT")\n');
49
+ await conn.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES (?, ?, ?, ?, false)', [fileId, userId, 'main.py', content]);
50
+
51
+ await conn.commit();
52
  const token = jwt.sign({ id: userId, email }, app.get('config').JWT_SECRET, { expiresIn: '7d' });
53
  res.cookie('token', token, { httpOnly: true, sameSite: 'lax' });
54
  res.json({ ok: true });
55
  } catch (e) {
56
+ await conn.rollback();
57
+ if (e.code === 'ER_DUP_ENTRY') return res.status(409).json({ error: 'Email already in use' });
58
  console.error(e);
59
  res.status(500).json({ error: 'Internal error' });
60
  } finally {
61
+ conn.release();
62
  }
63
  });
64
 
 
66
  const { email, password } = req.body || {};
67
  if (!email || !password) return res.status(400).json({ error: 'email and password required' });
68
  const db = getPool(app.get('config'));
69
+ const [rows] = await db.query('SELECT id, password_hash, name, class, section FROM users WHERE email=?', [email]);
70
  if (!rows[0]) return res.status(401).json({ error: 'Invalid credentials' });
71
  const valid = await bcrypt.compare(password, rows[0].password_hash);
72
  if (!valid) return res.status(401).json({ error: 'Invalid credentials' });
 
78
  app.get('/api/auth/me', authMiddleware, async (req, res) => {
79
  // Hydrate name/class/section from DB in case token is old
80
  const db = getPool(app.get('config'));
81
+ const [rows] = await db.query('SELECT email, name, class, section FROM users WHERE id=?', [req.user.id]);
82
  const u = rows[0] || {};
83
  res.json({ user: { id: req.user.id, email: u.email || req.user.email, name: u.name, class: u.class, section: u.section } });
84
  });
server/src/db.js CHANGED
@@ -1,124 +1,142 @@
1
- const { Pool } = require('pg');
2
 
3
  let pool;
4
 
5
  function getPool(config) {
6
  if (!pool) {
7
- // WARNING: Hardcoding secrets is unsafe. Use environment variables in production.
8
- pool = new Pool({ connectionString: config?.DATABASE_URL || process.env.DATABASE_URL });
 
 
 
 
 
 
 
 
 
 
9
  }
10
  return pool;
11
  }
12
 
13
  async function ensureSchema(config) {
14
  const db = getPool(config);
15
- const client = await db.connect();
16
  try {
17
- await client.query('BEGIN');
18
 
19
- // Detect existing users.id type (uuid/integer/bigint). If users doesn't exist, create with UUID.
20
- const col = await client.query(
21
- "SELECT data_type FROM information_schema.columns WHERE table_name='users' AND column_name='id'"
22
  );
23
- let userIdSqlType;
24
- if (!col.rows[0]) {
25
- // users table doesn't exist: create with UUID id
26
- await client.query(`
 
 
27
  CREATE TABLE IF NOT EXISTS users (
28
- id UUID PRIMARY KEY,
29
- email TEXT UNIQUE NOT NULL,
30
  password_hash TEXT NOT NULL,
31
- created_at TIMESTAMPTZ DEFAULT NOW()
 
32
  );
33
  `);
34
- userIdSqlType = 'UUID';
35
  } else {
36
- const t = (col.rows[0].data_type || '').toLowerCase();
37
- if (t === 'uuid') userIdSqlType = 'UUID';
38
- else if (t === 'bigint') userIdSqlType = 'BIGINT';
39
- else userIdSqlType = 'INTEGER';
40
-
41
- // Ensure required columns exist on existing users table
42
- await client.query(`
43
- ALTER TABLE users
44
- ADD COLUMN IF NOT EXISTS email TEXT,
45
- ADD COLUMN IF NOT EXISTS password_hash TEXT,
46
- ADD COLUMN IF NOT EXISTS name TEXT,
47
- ADD COLUMN IF NOT EXISTS class TEXT,
48
- ADD COLUMN IF NOT EXISTS section TEXT,
49
- ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW();
50
- `);
51
- // Ensure unique index on email
52
- await client.query(`
53
- DO $$
54
- BEGIN
55
- IF NOT EXISTS (
56
- SELECT 1 FROM pg_indexes WHERE schemaname = 'public' AND indexname = 'users_email_key'
57
- ) THEN
58
- CREATE UNIQUE INDEX users_email_key ON users(email);
59
- END IF;
60
- END $$;
61
- `);
62
 
63
- // If legacy username column exists and is NOT NULL, relax it to allow NULLs
64
- const uname = await client.query("SELECT is_nullable FROM information_schema.columns WHERE table_name='users' AND column_name='username'");
65
- if (uname.rows[0] && uname.rows[0].is_nullable === 'NO') {
66
- await client.query('ALTER TABLE users ALTER COLUMN username DROP NOT NULL');
67
- }
 
 
 
68
 
69
- // Relax NOT NULL on any unexpected legacy columns (e.g., phone_no) to avoid insert failures
70
- const legacyCols = await client.query(`
71
- SELECT column_name FROM information_schema.columns
72
- WHERE table_name='users' AND is_nullable='NO'
73
- AND column_name NOT IN ('id','email','password_hash','created_at')
74
- `);
75
- for (const r of legacyCols.rows) {
76
- try { await client.query(`ALTER TABLE users ALTER COLUMN ${r.column_name} DROP NOT NULL`); } catch {}
 
 
 
 
 
 
 
 
 
 
 
77
  }
 
 
 
78
  }
79
 
80
- // Create dependent tables using detected user id type
81
- await client.query(`
82
  CREATE TABLE IF NOT EXISTS workspaces (
83
- id UUID PRIMARY KEY,
84
- user_id ${userIdSqlType} REFERENCES users(id) ON DELETE CASCADE,
85
- created_at TIMESTAMPTZ DEFAULT NOW()
 
86
  );
 
 
 
 
87
  CREATE TABLE IF NOT EXISTS files (
88
- id UUID PRIMARY KEY,
89
- user_id ${userIdSqlType} REFERENCES users(id) ON DELETE CASCADE,
90
  path TEXT NOT NULL,
91
- content BYTEA NOT NULL,
92
  is_binary BOOLEAN DEFAULT FALSE,
93
- updated_at TIMESTAMPTZ DEFAULT NOW(),
94
- UNIQUE(user_id, path)
 
95
  );
 
 
 
96
  CREATE TABLE IF NOT EXISTS file_versions (
97
- id UUID PRIMARY KEY,
98
- file_id UUID REFERENCES files(id) ON DELETE CASCADE,
99
- content BYTEA NOT NULL,
100
- created_at TIMESTAMPTZ DEFAULT NOW()
 
101
  );
 
 
 
102
  CREATE TABLE IF NOT EXISTS ai_fixes (
103
- id UUID PRIMARY KEY,
104
- user_id ${userIdSqlType} REFERENCES users(id) ON DELETE CASCADE,
105
- request_json JSONB NOT NULL,
106
- proposed_diff JSONB,
107
  applied BOOLEAN DEFAULT FALSE,
108
- created_at TIMESTAMPTZ DEFAULT NOW()
 
109
  );
110
- CREATE INDEX IF NOT EXISTS idx_files_user_path ON files(user_id, path);
111
  `);
112
 
113
- await client.query('COMMIT');
114
  } catch (e) {
115
- await client.query('ROLLBACK');
116
  throw e;
117
  } finally {
118
- client.release();
119
  }
120
  }
121
 
122
  module.exports = { pool: { get: getPool }, getPool, ensureSchema };
123
-
124
-
 
1
+ const mysql = require('mysql2/promise');
2
 
3
  let pool;
4
 
5
  function getPool(config) {
6
  if (!pool) {
7
+ const dbUrl = config?.DATABASE_URL || process.env.DATABASE_URL;
8
+ // mysql2 handles the connection string parsing including ssl params if formatted correctly,
9
+ // or we might need to parse it if the driver is picky.
10
+ // Usually 'mysql://user:pass@host:port/db?ssl={"rejectUnauthorized":true}' works with mysql2.
11
+ pool = mysql.createPool({
12
+ uri: dbUrl,
13
+ waitForConnections: true,
14
+ connectionLimit: 10,
15
+ queueLimit: 0,
16
+ // handling potential SSL JSON parsing if the driver doesn't do it automatically from string
17
+ ssl: dbUrl.includes('ssl=') ? { rejectUnauthorized: true } : undefined
18
+ });
19
  }
20
  return pool;
21
  }
22
 
23
  async function ensureSchema(config) {
24
  const db = getPool(config);
25
+ const conn = await db.getConnection();
26
  try {
27
+ await conn.beginTransaction();
28
 
29
+ // Check if users table exists
30
+ const [rows] = await conn.query(
31
+ "SELECT COLUMN_TYPE FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='users' AND column_name='id'"
32
  );
33
+
34
+ let userIdSqlType = 'CHAR(36)'; // Default for new tables
35
+
36
+ if (rows.length === 0) {
37
+ // Create users table
38
+ await conn.query(`
39
  CREATE TABLE IF NOT EXISTS users (
40
+ id CHAR(36) PRIMARY KEY,
41
+ email TEXT NOT NULL,
42
  password_hash TEXT NOT NULL,
43
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
44
+ UNIQUE(email(255))
45
  );
46
  `);
 
47
  } else {
48
+ // Detect existing ID type
49
+ const t = (rows[0].COLUMN_TYPE || '').toLowerCase();
50
+ if (t.includes('int')) userIdSqlType = 'INT';
51
+ else if (t.includes('bigint')) userIdSqlType = 'BIGINT';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ // Ensure columns exist
54
+ // MySQL doesn't support IF NOT EXISTS in ALTER TABLE easily, so we check first or use ignore pattern
55
+ // Simplified approach: Try adding columns and ignore "Duplicate column" error
56
+ const addCol = async (sql) => {
57
+ try { await conn.query(sql); } catch (e) {
58
+ if (e.code !== 'ER_DUP_FIELDNAME') throw e;
59
+ }
60
+ };
61
 
62
+ await addCol("ALTER TABLE users ADD COLUMN email TEXT");
63
+ await addCol("ALTER TABLE users ADD COLUMN password_hash TEXT");
64
+ await addCol("ALTER TABLE users ADD COLUMN name TEXT");
65
+ await addCol("ALTER TABLE users ADD COLUMN class TEXT");
66
+ await addCol("ALTER TABLE users ADD COLUMN section TEXT");
67
+ await addCol("ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
68
+
69
+ // Ensure unique index on email
70
+ // In MySQL email TEXT can't be unique without length. We used `email(255)` in CREATE.
71
+ // Checking if index exists:
72
+ const [idx] = await conn.query("SHOW INDEX FROM users WHERE Key_name='users_email_key'");
73
+ if (idx.length === 0) {
74
+ // We need to cast text to length for index
75
+ try {
76
+ await conn.query("CREATE UNIQUE INDEX users_email_key ON users(email(255))");
77
+ } catch (e) {
78
+ // Ignore if email content is too long for unique constraint (unlikely for valid emails)
79
+ console.warn("Could not create unique index on email:", e.message);
80
+ }
81
  }
82
+
83
+ // legacy username column nullable
84
+ try { await conn.query("ALTER TABLE users MODIFY COLUMN username TEXT NULL"); } catch { }
85
  }
86
 
87
+ // Create dependent tables
88
+ await conn.query(`
89
  CREATE TABLE IF NOT EXISTS workspaces (
90
+ id CHAR(36) PRIMARY KEY,
91
+ user_id ${userIdSqlType},
92
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
93
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
94
  );
95
+ `);
96
+
97
+ // Files table (content is LONGBLOB for binary safety)
98
+ await conn.query(`
99
  CREATE TABLE IF NOT EXISTS files (
100
+ id CHAR(36) PRIMARY KEY,
101
+ user_id ${userIdSqlType},
102
  path TEXT NOT NULL,
103
+ content LONGBLOB NOT NULL,
104
  is_binary BOOLEAN DEFAULT FALSE,
105
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
106
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
107
+ UNIQUE KEY idx_files_user_path (user_id, path(255))
108
  );
109
+ `);
110
+
111
+ await conn.query(`
112
  CREATE TABLE IF NOT EXISTS file_versions (
113
+ id CHAR(36) PRIMARY KEY,
114
+ file_id CHAR(36),
115
+ content LONGBLOB NOT NULL,
116
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
117
+ FOREIGN KEY (file_id) REFERENCES files(id) ON DELETE CASCADE
118
  );
119
+ `);
120
+
121
+ await conn.query(`
122
  CREATE TABLE IF NOT EXISTS ai_fixes (
123
+ id CHAR(36) PRIMARY KEY,
124
+ user_id ${userIdSqlType},
125
+ request_json JSON NOT NULL,
126
+ proposed_diff JSON,
127
  applied BOOLEAN DEFAULT FALSE,
128
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
129
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
130
  );
 
131
  `);
132
 
133
+ await conn.commit();
134
  } catch (e) {
135
+ await conn.rollback();
136
  throw e;
137
  } finally {
138
+ conn.release();
139
  }
140
  }
141
 
142
  module.exports = { pool: { get: getPool }, getPool, ensureSchema };
 
 
server/src/files.js CHANGED
@@ -12,14 +12,14 @@ function register(app) {
12
  const db = () => getPool(app.get('config'));
13
 
14
  app.get('/api/files/list', authMiddleware, async (req, res) => {
15
- const { rows } = await db().query('SELECT path, octet_length(content) AS size FROM files WHERE user_id=$1 ORDER BY path', [req.user.id]);
16
  res.json({ files: rows });
17
  });
18
 
19
  app.get('/api/files/read', authMiddleware, async (req, res) => {
20
  const path = req.query.path;
21
  if (!path) return res.status(400).json({ error: 'path required' });
22
- const { rows } = await db().query('SELECT content, is_binary FROM files WHERE user_id=$1 AND path=$2', [req.user.id, path]);
23
  if (!rows[0]) return res.status(404).json({ error: 'Not found' });
24
  const content = rows[0].content.toString(rows[0].is_binary ? 'binary' : 'utf8');
25
  res.json({ path, content, isBinary: rows[0].is_binary });
@@ -29,34 +29,34 @@ function register(app) {
29
  const { path, content, isBinary } = req.body || {};
30
  if (!path) return res.status(400).json({ error: 'path required' });
31
  const data = bufferFromMaybeString(content || '');
32
- const client = await db().connect();
33
  try {
34
- await client.query('BEGIN');
35
- const { rows } = await client.query('SELECT id FROM files WHERE user_id=$1 AND path=$2', [req.user.id, path]);
36
  if (rows[0]) {
37
  const fileId = rows[0].id;
38
- await client.query('UPDATE files SET content=$1, is_binary=$2, updated_at=NOW() WHERE id=$3', [data, !!isBinary, fileId]);
39
- await client.query('INSERT INTO file_versions (id, file_id, content) VALUES ($1, $2, $3)', [uuidv4(), fileId, data]);
40
  } else {
41
  const fileId = uuidv4();
42
- await client.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES ($1, $2, $3, $4, $5)', [fileId, req.user.id, path, data, !!isBinary]);
43
- await client.query('INSERT INTO file_versions (id, file_id, content) VALUES ($1, $2, $3)', [uuidv4(), fileId, data]);
44
  }
45
- await client.query('COMMIT');
46
  res.json({ ok: true });
47
  } catch (e) {
48
- await client.query('ROLLBACK');
49
  console.error(e);
50
  res.status(500).json({ error: 'Internal error' });
51
  } finally {
52
- client.release();
53
  }
54
  });
55
 
56
  app.post('/api/files/delete', authMiddleware, async (req, res) => {
57
  const { path } = req.body || {};
58
  if (!path) return res.status(400).json({ error: 'path required' });
59
- await db().query('DELETE FROM files WHERE user_id=$1 AND path=$2', [req.user.id, path]);
60
  res.json({ ok: true });
61
  });
62
 
@@ -64,11 +64,11 @@ function register(app) {
64
  const { oldPath, newPath } = req.body || {};
65
  if (!oldPath || !newPath) return res.status(400).json({ error: 'oldPath and newPath required' });
66
  try {
67
- const { rowCount } = await db().query('UPDATE files SET path=$1, updated_at=NOW() WHERE user_id=$2 AND path=$3', [newPath, req.user.id, oldPath]);
68
- if (!rowCount) return res.status(404).json({ error: 'Not found' });
69
  res.json({ ok: true });
70
  } catch (e) {
71
- if (e.code === '23505') return res.status(409).json({ error: 'File with newPath already exists' });
72
  console.error(e);
73
  res.status(500).json({ error: 'Internal error' });
74
  }
 
12
  const db = () => getPool(app.get('config'));
13
 
14
  app.get('/api/files/list', authMiddleware, async (req, res) => {
15
+ const [rows] = await db().query('SELECT path, octet_length(content) AS size FROM files WHERE user_id=? ORDER BY path', [req.user.id]);
16
  res.json({ files: rows });
17
  });
18
 
19
  app.get('/api/files/read', authMiddleware, async (req, res) => {
20
  const path = req.query.path;
21
  if (!path) return res.status(400).json({ error: 'path required' });
22
+ const [rows] = await db().query('SELECT content, is_binary FROM files WHERE user_id=? AND path=?', [req.user.id, path]);
23
  if (!rows[0]) return res.status(404).json({ error: 'Not found' });
24
  const content = rows[0].content.toString(rows[0].is_binary ? 'binary' : 'utf8');
25
  res.json({ path, content, isBinary: rows[0].is_binary });
 
29
  const { path, content, isBinary } = req.body || {};
30
  if (!path) return res.status(400).json({ error: 'path required' });
31
  const data = bufferFromMaybeString(content || '');
32
+ const conn = await db().getConnection();
33
  try {
34
+ await conn.beginTransaction();
35
+ const [rows] = await conn.query('SELECT id FROM files WHERE user_id=? AND path=?', [req.user.id, path]);
36
  if (rows[0]) {
37
  const fileId = rows[0].id;
38
+ await conn.query('UPDATE files SET content=?, is_binary=?, updated_at=NOW() WHERE id=?', [data, !!isBinary, fileId]);
39
+ await conn.query('INSERT INTO file_versions (id, file_id, content) VALUES (?, ?, ?)', [uuidv4(), fileId, data]);
40
  } else {
41
  const fileId = uuidv4();
42
+ await conn.query('INSERT INTO files (id, user_id, path, content, is_binary) VALUES (?, ?, ?, ?, ?)', [fileId, req.user.id, path, data, !!isBinary]);
43
+ await conn.query('INSERT INTO file_versions (id, file_id, content) VALUES (?, ?, ?)', [uuidv4(), fileId, data]);
44
  }
45
+ await conn.commit();
46
  res.json({ ok: true });
47
  } catch (e) {
48
+ await conn.rollback();
49
  console.error(e);
50
  res.status(500).json({ error: 'Internal error' });
51
  } finally {
52
+ conn.release();
53
  }
54
  });
55
 
56
  app.post('/api/files/delete', authMiddleware, async (req, res) => {
57
  const { path } = req.body || {};
58
  if (!path) return res.status(400).json({ error: 'path required' });
59
+ await db().query('DELETE FROM files WHERE user_id=? AND path=?', [req.user.id, path]);
60
  res.json({ ok: true });
61
  });
62
 
 
64
  const { oldPath, newPath } = req.body || {};
65
  if (!oldPath || !newPath) return res.status(400).json({ error: 'oldPath and newPath required' });
66
  try {
67
+ const [resDb] = await db().query('UPDATE files SET path=?, updated_at=NOW() WHERE user_id=? AND path=?', [newPath, req.user.id, oldPath]);
68
+ if (resDb.affectedRows === 0) return res.status(404).json({ error: 'Not found' });
69
  res.json({ ok: true });
70
  } catch (e) {
71
+ if (e.code === 'ER_DUP_ENTRY') return res.status(409).json({ error: 'File with newPath already exists' });
72
  console.error(e);
73
  res.status(500).json({ error: 'Internal error' });
74
  }
server/src/server.js CHANGED
@@ -18,7 +18,7 @@ const app = express();
18
  const CONFIG = {
19
  JWT_SECRET: 'itsecret',
20
  GEMINI_API_KEY: 'AIzaSyCx5FWyytL-KTd92v8ZDcYPPFl2N0fZaIc',
21
- DATABASE_URL: 'postgresql://neondb_owner:npg_6HZhlNMniv1k@ep-gentle-surf-a18bsxtn-pooler.ap-southeast-1.aws.neon.tech/neondb?sslmode=require&channel_binding=require',
22
  };
23
 
24
  app.use(cors({ origin: true, credentials: true }));
 
18
  const CONFIG = {
19
  JWT_SECRET: 'itsecret',
20
  GEMINI_API_KEY: 'AIzaSyCx5FWyytL-KTd92v8ZDcYPPFl2N0fZaIc',
21
+ DATABASE_URL: 'mysql://6bPC9jTdNcRiz6M.root:MiPm6uxTWh8AIje3@gateway01.ap-southeast-1.prod.aws.tidbcloud.com:4000/test?ssl={"rejectUnauthorized":true}',
22
  };
23
 
24
  app.use(cors({ origin: true, credentials: true }));
server/src/terminal.js CHANGED
@@ -16,7 +16,7 @@ function isCommandAllowed(cmd) {
16
  }
17
 
18
  async function materializeWorkspace(db, userId, targetDir) {
19
- const { rows } = await db.query('SELECT path, content, is_binary FROM files WHERE user_id=$1', [userId]);
20
  for (const f of rows) {
21
  const abs = path.join(targetDir, f.path);
22
  const dir = path.dirname(abs);
@@ -96,7 +96,7 @@ function register(app) {
96
  const timeoutMs = 60 * 1000;
97
  const killer = setTimeout(() => {
98
  hadError = true;
99
- try { child.kill('SIGKILL'); } catch {}
100
  send('exit', { code: 124, signal: 'SIGKILL', timeout: true });
101
  res.end();
102
  }, timeoutMs);
 
16
  }
17
 
18
  async function materializeWorkspace(db, userId, targetDir) {
19
+ const [rows] = await db.query('SELECT path, content, is_binary FROM files WHERE user_id=?', [userId]);
20
  for (const f of rows) {
21
  const abs = path.join(targetDir, f.path);
22
  const dir = path.dirname(abs);
 
96
  const timeoutMs = 60 * 1000;
97
  const killer = setTimeout(() => {
98
  hadError = true;
99
+ try { child.kill('SIGKILL'); } catch { }
100
  send('exit', { code: 124, signal: 'SIGKILL', timeout: true });
101
  res.end();
102
  }, timeoutMs);
server/src/test_db.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { ensureSchema } = require('./db');
2
+ const path = require('path');
3
+
4
+ // Mock config with the actual URL from server.js (or we could require it, but strict dependency is better)
5
+ const CONFIG = {
6
+ DATABASE_URL: 'mysql://6bPC9jTdNcRiz6M.root:MiPm6uxTWh8AIje3@gateway01.ap-southeast-1.prod.aws.tidbcloud.com:4000/test?ssl={"rejectUnauthorized":true}',
7
+ };
8
+
9
+ async function test() {
10
+ console.log('Testing DB conection...');
11
+ try {
12
+ await ensureSchema(CONFIG);
13
+ console.log('Schema ensured successfully!');
14
+ process.exit(0);
15
+ } catch (err) {
16
+ console.error('DB Connection Failed:', err);
17
+ process.exit(1);
18
+ }
19
+ }
20
+
21
+ test();