-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmultipass-refactored.js
More file actions
executable file
·338 lines (281 loc) · 9.86 KB
/
Copy pathmultipass-refactored.js
File metadata and controls
executable file
·338 lines (281 loc) · 9.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env node
// Multipass - Terminal for AI with per-project AI Offices
require('dotenv').config();
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const WebSocket = require('ws');
const pty = require('node-pty');
const app = express();
const PORT = process.env.PORT || 9999;
const HOST = process.env.HOST || '0.0.0.0';
app.use(express.json());
app.use(express.static(path.join(__dirname, 'src/public')));
// Serve .tmux.conf file
app.get('/.tmux.conf', (req, res) => {
res.sendFile(path.join(__dirname, '.tmux.conf'));
});
// In-memory storage
const sessions = new Map();
const terminals = new Map();
const projects = new Map();
// Load configuration
const { LLM_CONFIG, PROJECTS_FILE } = require('./src/utils/constants');
// Import error handling
const { errorMiddleware } = require('./src/utils/errorHandler');
// Load projects from file
async function loadProjects() {
try {
const data = await fs.readFile(PROJECTS_FILE, 'utf8');
const saved = JSON.parse(data);
saved.forEach(p => projects.set(p.id, p));
console.log(`Loaded ${projects.size} projects from ${PROJECTS_FILE}`);
} catch (e) {
console.error('Error loading projects:', e.message);
// Default projects
projects.set('default', { id: 'default', name: 'Default', path: process.cwd() });
console.log('Created default project');
}
}
async function saveProjects() {
const data = Array.from(projects.values());
await fs.writeFile(PROJECTS_FILE, JSON.stringify(data, null, 2));
}
// Load sessions metadata from file
async function loadSessions() {
try {
const data = await fs.readFile('multipass-sessions.json', 'utf8');
const saved = JSON.parse(data);
Object.entries(saved).forEach(([name, metadata]) => sessions.set(name, metadata));
} catch (e) {
// No saved sessions
}
}
async function saveSessions() {
const data = Object.fromEntries(sessions);
await fs.writeFile('multipass-sessions.json', JSON.stringify(data, null, 2));
}
// Initialize and start server
async function initialize() {
// Load data
await loadProjects();
await loadSessions();
// Set up routes
const projectsRouter = require('./src/routes/projects');
const sessionsRouter = require('./src/routes/sessions');
const browseRouter = require('./src/routes/browse');
app.use('/api/projects', projectsRouter(projects, sessions, saveProjects));
app.use('/api/sessions', sessionsRouter(sessions, projects, saveSessions));
app.use('/api/browse', browseRouter);
// Configuration endpoint
app.get('/api/config', (req, res) => {
const currentLLM = LLM_CONFIG.llms[LLM_CONFIG.default];
res.json({
currentLLM: {
name: currentLLM.name,
command: currentLLM.command,
sessionPrefix: currentLLM.sessionPrefix,
exitSequence: currentLLM.exitSequence,
exitDelay: currentLLM.exitDelay
},
ui: LLM_CONFIG.ui,
availableLLMs: Object.keys(LLM_CONFIG.llms)
});
});
// AI Modes endpoint
app.get('/api/ai-modes', (req, res) => {
const aiModes = require('./config/ai-modes');
res.json(aiModes);
});
// Button Configuration endpoints
app.get('/api/button-config', (req, res) => {
// Clear require cache to get latest config
delete require.cache[require.resolve('./config/buttons.config')];
const buttonConfig = require('./config/buttons.config');
res.json(buttonConfig);
});
app.post('/api/button-config', async (req, res) => {
try {
const newConfig = req.body;
// Validate the configuration
if (!newConfig || typeof newConfig !== 'object') {
return res.status(400).json({ error: 'Invalid configuration' });
}
// Write the configuration to file
const configPath = path.join(__dirname, 'config', 'buttons.config.js');
const configContent = `// Button Configuration for Multipass Terminal
// This file controls the quick command buttons that appear below the terminal
// This file is auto-generated by the UI settings. Edit with caution.
module.exports = ${JSON.stringify(newConfig, null, 2)};`;
await fs.writeFile(configPath, configContent);
// Clear require cache
delete require.cache[require.resolve('./config/buttons.config')];
res.json({ success: true });
} catch (error) {
console.error('Error saving button config:', error);
res.status(500).json({ error: 'Failed to save configuration' });
}
});
// Get home directory
app.get('/api/home', (req, res) => {
res.json({ home: process.env.HOME || '/home/user' });
});
// Tmux config endpoint
app.post('/api/tmux-config', async (req, res) => {
const { config } = req.body;
if (!config) {
return res.status(400).json({ error: 'No configuration provided' });
}
try {
// Create temporary tmux config file
const tmpFile = path.join(require('os').tmpdir(), `tmux-${Date.now()}.conf`);
await fs.writeFile(tmpFile, config);
// Apply the config to all active tmux sessions
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);
// Get all active sessions
const { stdout: sessionList } = await execPromise('tmux list-sessions -F "#{session_name}" 2>/dev/null || echo ""');
const sessions = sessionList.trim().split('\n').filter(Boolean);
// Apply config to each session
for (const session of sessions) {
try {
await execPromise(`tmux source-file ${tmpFile} -t "${session}"`);
} catch (e) {
console.error(`Failed to apply config to session ${session}:`, e.message);
}
}
// Also update the default .tmux.conf
const tmuxConfPath = path.join(process.env.HOME || '/home/user', '.tmux.conf');
await fs.writeFile(tmuxConfPath, config);
// Clean up temp file
await fs.unlink(tmpFile).catch(() => {});
res.json({
success: true,
message: `Configuration applied to ${sessions.length} active sessions`,
sessions: sessions.length
});
} catch (error) {
console.error('Error applying tmux config:', error);
res.status(500).json({ error: 'Failed to apply configuration' });
}
});
// Get current tmux config
app.get('/api/tmux-config', async (req, res) => {
try {
const tmuxConfPath = path.join(process.env.HOME || '/home/user', '.tmux.conf');
const config = await fs.readFile(tmuxConfPath, 'utf8');
res.json({ config });
} catch (error) {
// If file doesn't exist, return the default config
const defaultConfig = await fs.readFile(path.join(__dirname, '.tmux.conf'), 'utf8');
res.json({ config: defaultConfig });
}
});
// Error handling middleware (must be last)
app.use(errorMiddleware);
}
// WebSocket for terminal
const server = require('http').createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws, req) => {
const sessionName = req.url.replace('/terminal/', '');
console.log('WebSocket connection for session:', sessionName);
// Parse initial dimensions from query params or use defaults
const url = new URL(req.url, `http://${req.headers.host}`);
const cols = parseInt(url.searchParams.get('cols')) || 80;
const rows = parseInt(url.searchParams.get('rows')) || 30;
// Create a PTY that attaches to tmux session with proper dimensions
const term = pty.spawn('tmux', ['attach-session', '-t', sessionName], {
name: 'xterm-256color',
cols: cols,
rows: rows,
cwd: process.env.HOME,
env: process.env
});
// Store terminal reference
terminals.set(sessionName, term);
// Buffer for incomplete escape sequences
let buffer = '';
const BUFFER_TIMEOUT = 10; // ms
let bufferTimer = null;
// Function to send buffered data
const flushBuffer = () => {
if (buffer && ws.readyState === WebSocket.OPEN) {
ws.send(buffer);
buffer = '';
}
bufferTimer = null;
};
term.on('data', (data) => {
// Add data to buffer
buffer += data;
// Clear existing timer
if (bufferTimer) {
clearTimeout(bufferTimer);
}
// Check if we have complete escape sequences
const escapeMatch = buffer.match(/\x1b\[[0-9;]*$/); // Incomplete escape sequence at end
if (escapeMatch) {
// We have an incomplete escape sequence, wait for more data
bufferTimer = setTimeout(flushBuffer, BUFFER_TIMEOUT);
} else {
// No incomplete sequences, send immediately
flushBuffer();
}
});
term.on('exit', () => {
console.log('Terminal exited for session:', sessionName);
terminals.delete(sessionName);
ws.close();
});
ws.on('message', (msg) => {
try {
const data = JSON.parse(msg);
if (data.type === 'resize' && data.cols && data.rows) {
// Handle terminal resize
term.resize(data.cols, data.rows);
console.log(`Resized terminal ${sessionName} to ${data.cols}x${data.rows}`);
} else if (data.type === 'input') {
// Handle terminal input
term.write(data.data);
}
} catch (e) {
// Fallback for raw string messages (backward compatibility)
term.write(msg.toString());
}
});
ws.on('close', () => {
// Flush any remaining buffer
if (bufferTimer) {
clearTimeout(bufferTimer);
}
if (terminals.has(sessionName)) {
term.kill();
terminals.delete(sessionName);
}
});
});
// Start server
initialize().then(() => {
server.listen(PORT, HOST, () => {
console.log(`
🚀 Multipass - Terminal for AI
Access: http://${HOST}:${PORT}
Features:
✓ Project management with per-project AI Offices
✓ AI Office: Multiple cubicle terminals per project
✓ Consolidated AI Offices view
✓ Full terminal access in browser
✓ Session management
✓ Mobile optimized
✓ NO AUTHENTICATION - Direct access!
`);
}).on('error', (err) => {
console.error('Failed to start server:', err);
process.exit(1);
});
}).catch(err => {
console.error('Failed to initialize:', err);
process.exit(1);
});