Add Opencode (opencode.ai) integration via SSH tunnel

Features:
- Opencode AI chat interface
- SSH tunnel for secure API communication
- Auto-install Opencode on remote servers
- API key management with server-side storage
- Session history and management
- Integration with flutter_server_box server list
This commit is contained in:
root
2026-04-03 00:41:32 +08:00
parent 1d3534242c
commit 0f4fe33003
10 changed files with 2500 additions and 1 deletions

View File

@@ -0,0 +1,485 @@
import 'dart:async';
import 'package:fl_lib/fl_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:server_box/data/model/opencode/models.dart';
import 'package:server_box/data/provider/opencode/opencode.dart';
import 'package:server_box/data/provider/server/single.dart';
import 'package:server_box/data/res/store.dart';
/// Opencode 聊天页面
class OpencodeChatPage extends ConsumerStatefulWidget {
final String serverId;
final String? sessionId;
const OpencodeChatPage({
super.key,
required this.serverId,
this.sessionId,
});
@override
ConsumerState<OpencodeChatPage> createState() => _OpencodeChatPageState();
}
class _OpencodeChatPageState extends ConsumerState<OpencodeChatPage> {
final TextEditingController _messageController = TextEditingController();
final ScrollController _scrollController = ScrollController();
final List<OpencodeMessage> _messages = [];
bool _isSending = false;
StreamSubscription? _outputSubscription;
String _streamingContent = '';
@override
void initState() {
super.initState();
_initSession();
_listenToOutput();
}
@override
void dispose() {
_messageController.dispose();
_scrollController.dispose();
_outputSubscription?.cancel();
super.dispose();
}
void _initSession() {
WidgetsBinding.instance.addPostFrameCallback((_) {
final sessionManager = ref.read(opencodeSessionManagerProvider.notifier);
if (widget.sessionId != null) {
sessionManager.loadSession(widget.sessionId!);
} else {
final serverState = ref.read(serverProvider(widget.serverId));
sessionManager.createSession(
serverId: widget.serverId,
serverName: serverState.spi.name,
);
}
});
}
void _listenToOutput() {
final outputStream = ref.read(opencodeOutputStreamProvider);
_outputSubscription = outputStream.listen((data) {
setState(() {
_streamingContent += data;
});
_scrollToBottom();
});
}
void _scrollToBottom() {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
}
Future<void> _sendMessage() async {
final text = _messageController.text.trim();
if (text.isEmpty || _isSending) return;
_messageController.clear();
final message = OpencodeMessage.user(text);
setState(() {
_messages.add(message);
_isSending = true;
_streamingContent = '';
});
await ref.read(opencodeSessionManagerProvider.notifier).addMessage(message);
try {
final connection = ref.read(opencodeConnectionProvider.notifier);
await connection.sendMessage(message, _messages);
await Future.delayed(const Duration(seconds: 2));
if (_streamingContent.isNotEmpty) {
final responseMessage = OpencodeMessage.assistant(_streamingContent);
setState(() {
_messages.add(responseMessage);
});
await ref.read(opencodeSessionManagerProvider.notifier).addMessage(responseMessage);
}
} catch (e) {
final errorMessage = OpencodeMessage.assistant('Error: $e');
setState(() {
_messages.add(errorMessage);
});
} finally {
setState(() {
_isSending = false;
_streamingContent = '';
});
_scrollToBottom();
}
}
@override
Widget build(BuildContext context) {
final sessionState = ref.watch(opencodeSessionManagerProvider);
final connectionState = ref.watch(opencodeConnectionProvider);
return Scaffold(
appBar: CustomAppBar(
title: Text(sessionState.currentSession?.title ?? 'Opencode Chat'),
actions: [
IconButton(
icon: const Icon(Icons.history),
onPressed: _showSessionHistory,
),
IconButton(
icon: const Icon(Icons.settings),
onPressed: _showSettings,
),
],
),
body: Column(
children: [
if (connectionState.status != OpencodeConnectionStatus.connected)
_buildStatusBar(connectionState),
Expanded(
child: _buildMessageList(sessionState),
),
_buildInputArea(),
],
),
);
}
Widget _buildStatusBar(OpencodeConnectionState state) {
Color color;
String text;
IconData icon;
switch (state.status) {
case OpencodeConnectionStatus.connecting:
color = Colors.orange;
text = 'Connecting...';
icon = Icons.sync;
case OpencodeConnectionStatus.checkingInstallation:
color = Colors.blue;
text = 'Checking Opencode...';
icon = Icons.search;
case OpencodeConnectionStatus.installing:
color = Colors.purple;
text = 'Installing Opencode...';
icon = Icons.download;
case OpencodeConnectionStatus.startingServer:
color = Colors.teal;
text = 'Starting API server...';
icon = Icons.play_arrow;
case OpencodeConnectionStatus.error:
color = Colors.red;
text = state.error ?? 'Connection error';
icon = Icons.error;
default:
return const SizedBox.shrink();
}
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
color: color.withOpacity(0.1),
child: Row(
children: [
Icon(icon, color: color, size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
text,
style: TextStyle(color: color, fontSize: 13),
),
),
if (state.status == OpencodeConnectionStatus.error)
TextButton(
onPressed: _retryConnection,
child: const Text('Retry'),
),
],
),
);
}
Widget _buildMessageList(OpencodeSessionState sessionState) {
final allMessages = [...sessionState.currentSession?.messages ?? [], ..._messages];
if (allMessages.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.chat_bubble_outline,
size: 64,
color: Colors.grey[400],
),
const SizedBox(height: 16),
Text(
'Start a conversation with Opencode',
style: TextStyle(
color: Colors.grey[600],
fontSize: 16,
),
),
],
),
);
}
return ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: allMessages.length + (_isSending ? 1 : 0),
itemBuilder: (context, index) {
if (index == allMessages.length) {
return _buildStreamingIndicator();
}
final message = allMessages[index];
return _buildMessageBubble(message);
},
);
}
Widget _buildMessageBubble(OpencodeMessage message) {
final isUser = message.role == 'user';
final isSystem = message.role == 'system';
if (isSystem) {
return const SizedBox.shrink();
}
return Align(
alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.8,
),
decoration: BoxDecoration(
color: isUser ? UIs.primaryColor : Colors.grey[200],
borderRadius: BorderRadius.circular(16).copyWith(
bottomRight: isUser ? const Radius.circular(4) : null,
bottomLeft: !isUser ? const Radius.circular(4) : null,
),
),
child: Text(
message.content,
style: TextStyle(
color: isUser ? Colors.white : Colors.black87,
fontSize: 15,
),
),
),
);
}
Widget _buildStreamingIndicator() {
return Align(
alignment: Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(16).copyWith(
bottomLeft: const Radius.circular(4),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_streamingContent.isEmpty ? 'Thinking' : _streamingContent,
style: TextStyle(
color: Colors.black87,
fontSize: 15,
),
),
if (_streamingContent.isEmpty) ...[
const SizedBox(width: 4),
SizedBox(
width: 12,
height: 12,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.grey[600]!,
),
),
),
],
],
),
),
);
}
Widget _buildInputArea() {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 10,
offset: const Offset(0, -5),
),
],
),
child: SafeArea(
child: Row(
children: [
Expanded(
child: TextField(
controller: _messageController,
decoration: InputDecoration(
hintText: 'Message Opencode...',
filled: true,
fillColor: Colors.grey[100],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 14,
),
),
onSubmitted: (_) => _sendMessage(),
),
),
const SizedBox(width: 8),
FloatingActionButton(
mini: true,
onPressed: _isSending ? null : _sendMessage,
child: _isSending
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Icon(Icons.send),
),
],
),
),
);
}
void _showSessionHistory() {
final sessionManager = ref.read(opencodeSessionManagerProvider.notifier);
final sessions = ref.read(opencodeSessionManagerProvider).sessions
.where((s) => s.serverId == widget.serverId)
.toList();
showModalBottomSheet(
context: context,
builder: (context) => Container(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Session History',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 16),
Expanded(
child: ListView.builder(
itemCount: sessions.length,
itemBuilder: (context, index) {
final session = sessions[index];
return ListTile(
title: Text(session.title ?? 'Untitled Session'),
subtitle: Text(
'${session.messages.length} messages • ${_formatDate(session.updatedAt)}',
),
onTap: () {
Navigator.pop(context);
sessionManager.loadSession(session.id);
},
trailing: IconButton(
icon: const Icon(Icons.delete, size: 20),
onPressed: () async {
await sessionManager.deleteSession(session.id);
Navigator.pop(context);
},
),
);
},
),
),
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () {
Navigator.pop(context);
final serverState = ref.read(serverProvider(widget.serverId));
sessionManager.createSession(
serverId: widget.serverId,
serverName: serverState.spi.name,
);
},
icon: const Icon(Icons.add),
label: const Text('New Session'),
),
),
],
),
),
);
}
void _showSettings() {
context.push('/opencode/settings/${widget.serverId}');
}
void _retryConnection() {
final connection = ref.read(opencodeConnectionProvider.notifier);
final serverState = ref.read(serverProvider(widget.serverId));
final pki = serverState.spi.keyId != null
? Stores.key.get(serverState.spi.keyId!)
: null;
connection.connect(
serverState.spi,
privateKey: pki?.key,
passphrase: pki?.password,
);
}
String _formatDate(DateTime date) {
final now = DateTime.now();
final diff = now.difference(date);
if (diff.inDays == 0) {
return '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
} else if (diff.inDays == 1) {
return 'Yesterday';
} else {
return '${date.month}/${date.day}';
}
}
}

View File

@@ -0,0 +1,328 @@
import 'package:fl_lib/fl_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:server_box/data/provider/server/single.dart';
import 'package:server_box/data/store/opencode_store.dart';
/// Opencode API 密钥管理页面
class OpencodeKeyManagerPage extends ConsumerStatefulWidget {
final String serverId;
const OpencodeKeyManagerPage({
super.key,
required this.serverId,
});
@override
ConsumerState<OpencodeKeyManagerPage> createState() => _OpencodeKeyManagerPageState();
}
class _OpencodeKeyManagerPageState extends ConsumerState<OpencodeKeyManagerPage> {
final _keyController = TextEditingController();
final _descController = TextEditingController();
bool _isSaving = false;
bool _obscureKey = true;
@override
void initState() {
super.initState();
_loadExistingKey();
}
@override
void dispose() {
_keyController.dispose();
_descController.dispose();
super.dispose();
}
void _loadExistingKey() {
final keyInfo = OpencodeKeyStore().getServerKeyInfo(widget.serverId);
if (keyInfo != null) {
_descController.text = keyInfo['description'] ?? '';
}
}
Future<void> _saveKey() async {
if (_keyController.text.trim().isEmpty) {
context.showSnackBar('Please enter an API key');
return;
}
setState(() {
_isSaving = true;
});
try {
final apiKey = _keyController.text.trim();
// 保存到本地存储(明文)
await OpencodeKeyStore().saveServerKey(
widget.serverId,
apiKey: apiKey,
description: _descController.text,
);
// 通过 SSH 上传到服务器
final tunnel = ref.read(opencodeConnectionProvider.notifier).tunnel;
if (tunnel != null && tunnel.isConnected) {
await tunnel.execute('mkdir -p ~/.config/opencode');
final escapedKey = apiKey.replaceAll("'", "'\\''");
await tunnel.execute("echo '$escapedKey' \u003e ~/.config/opencode/api_key.txt");
await tunnel.execute('chmod 600 ~/.config/opencode/api_key.txt');
}
if (mounted) {
context.showSnackBar('API key saved successfully');
Navigator.pop(context);
}
} catch (e) {
if (mounted) {
context.showSnackBar('Failed to save key: $e');
}
} finally {
if (mounted) {
setState(() {
_isSaving = false;
});
}
}
}
Future<void> _deleteKey() async {
final confirmed = await context.showRoundDialog<bool>(
title: 'Delete API Key',
child: const Text('Are you sure you want to delete this API key?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('Delete'),
),
],
);
if (confirmed == true) {
try {
final tunnel = ref.read(opencodeConnectionProvider.notifier).tunnel;
if (tunnel != null && tunnel.isConnected) {
await tunnel.execute('rm -f ~/.config/opencode/api_key.txt');
}
await OpencodeKeyStore().deleteServerKey(widget.serverId);
if (mounted) {
context.showSnackBar('API key deleted');
setState(() {
_keyController.clear();
_descController.clear();
});
}
} catch (e) {
if (mounted) {
context.showSnackBar('Failed to delete key: $e');
}
}
}
}
@override
Widget build(BuildContext context) {
final serverState = ref.watch(serverProvider(widget.serverId));
final existingKey = OpencodeKeyStore().getServerKeyInfo(widget.serverId);
return Scaffold(
appBar: CustomAppBar(
title: Text('Opencode API Key - ${serverState.spi.name}'),
actions: [
if (existingKey != null)
IconButton(
icon: const Icon(Icons.delete),
onPressed: _deleteKey,
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildSecurityCard(),
const SizedBox(height: 24),
Text(
'API Key Configuration',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
TextFormField(
controller: _keyController,
obscureText: _obscureKey,
decoration: InputDecoration(
labelText: 'Opencode API Key',
hintText: existingKey != null
? 'Enter new key to replace existing one'
: 'opc_...',
prefixIcon: const Icon(Icons.vpn_key),
suffixIcon: IconButton(
icon: Icon(
_obscureKey ? Icons.visibility_off : Icons.visibility,
),
onPressed: () {
setState(() {
_obscureKey = !_obscureKey;
});
},
),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextFormField(
controller: _descController,
decoration: const InputDecoration(
labelText: 'Description (Optional)',
hintText: 'e.g., Production API key',
prefixIcon: Icon(Icons.description),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 24),
if (existingKey != null)
_buildStorageInfo(existingKey),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _isSaving ? null : _saveKey,
icon: _isSaving
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Icon(Icons.save),
label: Text(_isSaving ? 'Saving...' : 'Save API Key'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
],
),
),
);
}
Widget _buildSecurityCard() {
return Card(
elevation: 0,
color: Colors.orange.withOpacity(0.1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(color: Colors.orange.withOpacity(0.3)),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.security, color: Colors.orange[700]),
const SizedBox(width: 8),
Text(
'Security Notice',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.orange[700],
),
),
],
),
const SizedBox(height: 12),
const Text(
'• API keys are stored in plaintext on the server\n'
'• Keys are saved in ~/.config/opencode/api_key.txt with 600 permissions\n'
'• Make sure your server is secure and only accessible to you\n'
'• Consider using environment-specific keys',
style: TextStyle(fontSize: 13),
),
],
),
),
);
}
Widget _buildStorageInfo(Map<String, dynamic> keyInfo) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Current Key Info',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.grey[700],
),
),
const SizedBox(height: 8),
if (keyInfo['description'] != null)
_buildInfoRow('Description', keyInfo['description']),
_buildInfoRow(
'Last Updated',
keyInfo['updated_at'] != null
? keyInfo['updated_at'].toString().substring(0, 16)
: 'Unknown',
),
],
),
);
}
Widget _buildInfoRow(String label, String value) {
return Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 100,
child: Text(
'$label:',
style: TextStyle(
color: Colors.grey[600],
fontSize: 13,
),
),
),
Expanded(
child: Text(
value,
style: const TextStyle(fontSize: 13),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,390 @@
import 'package:fl_lib/fl_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:server_box/data/model/opencode/models.dart';
import 'package:server_box/data/provider/opencode/opencode.dart';
import 'package:server_box/data/provider/server/single.dart';
import 'package:server_box/data/res/store.dart';
import 'package:server_box/data/store/opencode_store.dart';
/// Opencode 连接/安装向导页面
class OpencodeSetupPage extends ConsumerStatefulWidget {
final String serverId;
const OpencodeSetupPage({
super.key,
required this.serverId,
});
@override
ConsumerState<OpencodeSetupPage> createState() => _OpencodeSetupPageState();
}
class _OpencodeSetupPageState extends ConsumerState<OpencodeSetupPage> {
final _formKey = GlobalKey<FormState>();
final _pathController = TextEditingController(text: '/usr/local/bin/opencode');
final _configController = TextEditingController(text: '~/.config/opencode');
final _portController = TextEditingController(text: '8080');
final _apiKeyController = TextEditingController();
bool _autoStart = true;
bool _isConnecting = false;
String? _statusMessage;
@override
void initState() {
super.initState();
_loadExistingConfig();
}
@override
void dispose() {
_pathController.dispose();
_configController.dispose();
_portController.dispose();
_apiKeyController.dispose();
super.dispose();
}
void _loadExistingConfig() {
final config = OpencodeConfigStore().getConfig(widget.serverId);
_pathController.text = config.opencodePath;
_configController.text = config.configPath;
_portController.text = config.apiPort;
_autoStart = config.autoStart;
if (config.apiKey != null) {
_apiKeyController.text = config.apiKey!;
}
}
Future<void> _connect() async {
if (_isConnecting) return;
setState(() {
_isConnecting = true;
_statusMessage = 'Connecting to server...';
});
try {
final serverState = ref.read(serverProvider(widget.serverId));
final connection = ref.read(opencodeConnectionProvider.notifier);
final pki = serverState.spi.keyId != null
? Stores.key.get(serverState.spi.keyId!)
: null;
await connection.connect(
serverState.spi,
privateKey: pki?.key,
passphrase: pki?.password,
);
if (mounted) {
setState(() {
_statusMessage = 'Connected! Checking Opencode installation...';
});
final config = OpencodeServerConfig(
serverId: widget.serverId,
opencodePath: _pathController.text,
configPath: _configController.text,
apiPort: _portController.text,
autoStart: _autoStart,
apiKey: _apiKeyController.text.isNotEmpty ? _apiKeyController.text : null,
);
await OpencodeConfigStore().saveConfig(config);
await connection.checkAndInstall(config: config);
}
} catch (e) {
if (mounted) {
setState(() {
_statusMessage = 'Error: $e';
});
context.showSnackBar('Connection failed: $e');
}
} finally {
if (mounted) {
setState(() {
_isConnecting = false;
});
}
}
}
Future<void> _quickInstall() async {
setState(() {
_isConnecting = true;
_statusMessage = 'Starting automatic installation...';
});
try {
final connection = ref.read(opencodeConnectionProvider.notifier);
final config = OpencodeServerConfig(
serverId: widget.serverId,
opencodePath: _pathController.text,
configPath: _configController.text,
apiPort: _portController.text,
autoStart: _autoStart,
apiKey: _apiKeyController.text.isNotEmpty ? _apiKeyController.text : null,
);
await connection.checkAndInstall(config: config);
if (mounted) {
setState(() {
_statusMessage = 'Installation complete!';
});
await Future.delayed(const Duration(seconds: 1));
if (mounted) {
context.pushReplacement('/opencode/chat/${widget.serverId}');
}
}
} catch (e) {
if (mounted) {
setState(() {
_statusMessage = 'Installation failed: $e';
});
}
} finally {
if (mounted) {
setState(() {
_isConnecting = false;
});
}
}
}
@override
Widget build(BuildContext context) {
final connectionState = ref.watch(opencodeConnectionProvider);
final serverState = ref.watch(serverProvider(widget.serverId));
if (connectionState.status == OpencodeConnectionStatus.connected) {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.pushReplacement('/opencode/chat/${widget.serverId}');
});
}
return Scaffold(
appBar: CustomAppBar(
title: Text('Setup Opencode - ${serverState.spi.name}'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildInfoCard(),
const SizedBox(height: 24),
Text(
'Configuration',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
TextFormField(
controller: _pathController,
decoration: const InputDecoration(
labelText: 'Opencode Binary Path',
hintText: '/usr/local/bin/opencode',
prefixIcon: Icon(Icons.file_present),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter the path';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _configController,
decoration: const InputDecoration(
labelText: 'Config Directory',
hintText: '~/.config/opencode',
prefixIcon: Icon(Icons.folder),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextFormField(
controller: _portController,
decoration: const InputDecoration(
labelText: 'API Port',
hintText: '8080',
prefixIcon: Icon(Icons.settings_ethernet),
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter the port';
}
final port = int.tryParse(value);
if (port == null || port < 1 || port > 65535) {
return 'Invalid port number';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _apiKeyController,
decoration: const InputDecoration(
labelText: 'Opencode API Key (Optional)',
hintText: 'opc_...',
prefixIcon: Icon(Icons.key),
border: OutlineInputBorder(),
),
obscureText: true,
),
const SizedBox(height: 16),
SwitchListTile(
title: const Text('Auto-start API Server'),
subtitle: const Text('Automatically start Opencode server on connection'),
value: _autoStart,
onChanged: (value) {
setState(() {
_autoStart = value;
});
},
),
const SizedBox(height: 24),
if (_statusMessage != null) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: _getStatusColor(connectionState.status).withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Column(
children: [
if (_isConnecting)
const Padding(
padding: EdgeInsets.only(bottom: 8),
child: SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
Text(
_statusMessage!,
textAlign: TextAlign.center,
style: TextStyle(
color: _getStatusColor(connectionState.status),
),
),
],
),
),
const SizedBox(height: 24),
],
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _isConnecting ? null : _quickInstall,
icon: _isConnecting
? const SizedBox.shrink()
: const Icon(Icons.rocket_launch),
label: Text(_isConnecting ? 'Please wait...' : 'Quick Install & Connect'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: _isConnecting ? null : _connect,
icon: const Icon(Icons.link),
label: const Text('Connect Only'),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
],
),
),
),
);
}
Widget _buildInfoCard() {
return Card(
elevation: 0,
color: UIs.primaryColor.withOpacity(0.1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.info, color: UIs.primaryColor),
const SizedBox(width: 8),
Text(
'About Opencode',
style: TextStyle(
fontWeight: FontWeight.bold,
color: UIs.primaryColor,
),
),
],
),
const SizedBox(height: 12),
const Text(
'Opencode (opencode.ai) is an AI assistant for developers. '
'This app connects to your server via SSH to provide AI assistance.',
style: TextStyle(fontSize: 14),
),
const SizedBox(height: 12),
const Text(
'• If Opencode is not installed, the app can auto-install it\n'
'• Your API key is saved in plaintext on the server\n'
'• All communication is encrypted via SSH tunnel',
style: TextStyle(fontSize: 13, color: Colors.black87),
),
],
),
),
);
}
Color _getStatusColor(OpencodeConnectionStatus status) {
switch (status) {
case OpencodeConnectionStatus.connected:
return Colors.green;
case OpencodeConnectionStatus.error:
return Colors.red;
case OpencodeConnectionStatus.installing:
case OpencodeConnectionStatus.startingServer:
return Colors.orange;
default:
return UIs.primaryColor;
}
}
}

View File

@@ -212,6 +212,10 @@ void _onTapMoreBtns(ServerFuncBtn value, Spi spi, BuildContext context, WidgetRe
final args = SpiRequiredArgs(spi);
PortForwardPage.route.go(context, args);
break;
case ServerFuncBtn.opencode:
// Opencode AI Assistant
context.push('/opencode/setup/${spi.id}');
break;
}
}