File size: 5,518 Bytes
cfeb3a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# πŸš€ Manus AI-Style Terminal Integration

This document explains the real-time terminal streaming functionality added to the Data Extractor application.

## πŸ“‹ Overview

The terminal integration provides a **Manus AI-style terminal interface** with real-time command execution and streaming output, seamlessly integrated into the existing Gradio application.

## πŸ—οΈ Architecture

### Components

1. **WebSocket Server** (`terminal_stream.py`)
   - Handles real-time communication between frontend and backend
   - Manages command execution with streaming output
   - Supports multiple concurrent connections
   - Runs on port 8765

2. **Frontend Terminal** (`static/terminal.html`)
   - Beautiful Manus AI-inspired terminal interface
   - Real-time output streaming via WebSocket
   - Command history navigation
   - Keyboard shortcuts and controls

3. **Gradio Integration** (Modified `app.py`)
   - Added terminal tab to existing interface
   - Embedded terminal as iframe component
   - Auto-starts WebSocket server on application launch

## 🎨 Features

### Terminal Interface
- **Real-time Streaming**: Live command output as it happens
- **Command History**: Navigate with ↑/↓ arrow keys
- **Interrupt Support**: Ctrl+C to stop running commands
- **Auto-reconnect**: Automatically reconnects on connection loss
- **Status Indicators**: Visual connection and execution status
- **Responsive Design**: Works on desktop and mobile

### Security
- **Command Sanitization**: Uses `shlex.split()` for safe command parsing
- **Process Isolation**: Commands run in separate processes
- **Error Handling**: Robust error handling and logging

## πŸš€ Usage

### Starting the Application
```bash
python app.py
```

The terminal WebSocket server automatically starts on port 8765.

### Accessing the Terminal
1. Open the Gradio interface (usually http://localhost:7860)
2. Click on the "πŸ’» Terminal" tab
3. Start typing commands in the terminal interface

### Keyboard Shortcuts
- **Enter**: Execute command
- **↑/↓**: Navigate command history
- **Ctrl+C**: Interrupt running command
- **Ctrl+L**: Clear terminal screen
- **Tab**: Command completion (planned feature)

## πŸ”§ Configuration

### WebSocket Server Settings
```python
# In terminal_stream.py
WEBSOCKET_HOST = 'localhost'
WEBSOCKET_PORT = 8765
```

### Terminal Appearance
Customize the terminal appearance by modifying the CSS in `static/terminal.html`:

```css
/* Main terminal colors */
.terminal-container {
    background: linear-gradient(135deg, #0d1117 0%, #161b22 100%);
}

/* Command prompt */
.prompt {
    color: #58a6ff;
}
```

## πŸ“‘ WebSocket API

### Client β†’ Server Messages

#### Execute Command
```json
{
    "type": "command",
    "command": "ls -la"
}
```

#### Interrupt Command
```json
{
    "type": "interrupt"
}
```

### Server β†’ Client Messages

#### Command Output
```json
{
    "type": "output",
    "data": "file1.txt\nfile2.txt",
    "stream": "stdout",
    "timestamp": "2024-01-01T12:00:00.000Z"
}
```

#### Command Completion
```json
{
    "type": "command_complete",
    "exit_code": 0,
    "message": "Process exited with code 0",
    "timestamp": "2024-01-01T12:00:00.000Z"
}
```

## πŸ› οΈ Development

### Adding New Features

1. **Server-side**: Modify `terminal_stream.py`
2. **Client-side**: Update `static/terminal.html`
3. **Integration**: Adjust `app.py` if needed

### Testing

```bash
# Test WebSocket server independently
python -c "from terminal_stream import run_websocket_server; run_websocket_server()"

# Test terminal interface
# Open static/terminal.html in browser
```

## πŸ” Troubleshooting

### Common Issues

1. **WebSocket Connection Failed**
   - Check if port 8765 is available
   - Verify firewall settings
   - Check server logs for errors

2. **Commands Not Executing**
   - Verify WebSocket connection status
   - Check terminal logs for errors
   - Ensure proper command syntax

3. **Terminal Not Loading**
   - Check if `static/terminal.html` exists
   - Verify Gradio file serving configuration
   - Check browser console for errors

### Debug Mode

Enable debug logging:
```python
import logging
logging.getLogger('terminal_stream').setLevel(logging.DEBUG)
```

## πŸš€ Advanced Usage

### Custom Commands

Add custom command handlers in `terminal_stream.py`:

```python
async def handle_custom_command(self, command):
    if command.startswith('custom:'):
        # Handle custom command
        await self.broadcast({
            'type': 'output',
            'data': 'Custom command executed',
            'stream': 'stdout'
        })
        return True
    return False
```

### Integration with Workflow

Stream workflow logs to terminal:

```python
# In workflow code
from terminal_stream import terminal_manager

async def log_to_terminal(message):
    await terminal_manager.broadcast({
        'type': 'output',
        'data': message,
        'stream': 'workflow'
    })
```

## πŸ“š Dependencies

- `websockets`: WebSocket server implementation
- `asyncio`: Async programming support
- `subprocess`: Command execution
- `shlex`: Safe command parsing

## 🎯 Future Enhancements

- [ ] Command auto-completion
- [ ] File upload/download via terminal
- [ ] Terminal themes and customization
- [ ] Multi-session support
- [ ] Terminal recording and playback
- [ ] Integration with workflow logging
- [ ] SSH/remote terminal support

## πŸ“„ License

This terminal implementation is part of the Data Extractor project and follows the same license terms.