diff --git a/PLAN.md b/PLAN.md index 8f0aa42..76d7ce3 100644 --- a/PLAN.md +++ b/PLAN.md @@ -27,6 +27,19 @@ --- +## 0.3.1 修复(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 代理 | 支持 `http://`、`https://`(`HttpClient.findProxy`)与 `socks5://`、`socks5h://`(`socks5_proxy` 包为 `HttpClient` 建 SOCKS 隧道,统一在代理解析域名),可带 `user:pass@`。此前 `socks5` 直接塞进 `findProxy` 导致 “Invalid proxy configuration”,`socks5h` 被当成 HTTP 代理导致 “Invalid request method” | +| 验证 | `tool/proxy_probe.dart` 对本机服务器 + 本地 SOCKS5(1080)/HTTP(8081) 测试代理跑通 direct / socks5 / socks5h / http 与 SSE;模拟器上分别用 `socks5://127.0.0.1:1080` 和 `http://127.0.0.1:8081` 连上并列出会话 | +| 失败不落库 | 连接成功才保存(`_connected` upsert);失败的尝试留在表单并显示简短原因(如「连接被拒绝:服务器或代理未启动,或端口不对」),返回列表后不残留错误 | +| 包名 | `net.blumia.openchamber.flutter`(namespace、applicationId、MainActivity、iOS bundle id 同步) | +| 版本 | **0.3.1(code 301)** | +| 小改进 | 实例/服务器列表显示「经由 <代理>」,区分同地址不同代理;连接错误中文化 | + +--- + ## 0.2 迁移到 MyGo(2026-11-18,分支 `mygo`,0.3.0) **背景**:Asuka 0.2 把应用语言从 Go 换成了自研 Asuka 语言(C 内核、无 Go 运行时),继续留在 Go 线已没有上游维护; diff --git a/README.md b/README.md index db9a3eb..d399200 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.3.0 — servers (passwordless / password login, HTTP/SOCKS5 proxy, -self-signed certificates and pinning), session list with search and live +Status: 0.3.1 — servers (passwordless / password login, HTTP/HTTPS and +SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live events, chat with streaming Markdown, tool rows with image previews, a context usage ring with a detail sheet, model/agent switching, copy / fork / revert, attachments (photos/files), permissions. Android 7.0 (API 24)+. @@ -15,7 +15,7 @@ revert, attachments (photos/files), permissions. Android 7.0 (API 24)+. | Path | What | | --- | --- | -| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP proxy via `HttpClient.findProxy`, SOCKS5 via dart:io's SOCKS, pinning/self-signed via `badCertificateCallback` | +| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback` | | `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) | | `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding | | `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets) | @@ -46,9 +46,15 @@ flutter test flutter build apk --release # dist artifacts in build/app/outputs/flutter-apk ``` -`android/app/build.gradle.kts` sets `minSdk 24` and signs releases with +`android/app/build.gradle.kts` sets the application id +`net.blumia.openchamber.flutter`, `minSdk 24`, and signs releases with `~/SDK/test-upload.jks` (override via `OPENCHAMBER_KEYSTORE*` env). Dart's `HttpClient` dials sockets itself, so plain `http://` LAN servers work in -release without a cleartext manifest flag, as with the Go clients. +release without a cleartext manifest flag, as with the Go clients. Only a +working connection is saved: a failed attempt stays in the form. + +Proxies accept `http://`, `https://`, `socks5://` and `socks5h://` (the +last two resolve names at the proxy). `tool/proxy_probe.dart` checks the +client against a live server through local test proxies. Earlier attempts: `main` (Asuka/Go, 0.2.x) and `mygo` (MyGo, 0.3.0). diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 9a2d6e8..41832f4 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -5,7 +5,7 @@ plugins { } android { - namespace = "com.openchamber.openchamber" + namespace = "net.blumia.openchamber.flutter" compileSdk = flutter.compileSdkVersion ndkVersion = flutter.ndkVersion @@ -15,7 +15,7 @@ android { } defaultConfig { - applicationId = "com.openchamber.native" + applicationId = "net.blumia.openchamber.flutter" minSdk = 24 targetSdk = flutter.targetSdkVersion // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION diff --git a/android/app/src/main/kotlin/com/openchamber/openchamber/MainActivity.kt b/android/app/src/main/kotlin/net/blumia/openchamber/flutter/MainActivity.kt similarity index 70% rename from android/app/src/main/kotlin/com/openchamber/openchamber/MainActivity.kt rename to android/app/src/main/kotlin/net/blumia/openchamber/flutter/MainActivity.kt index 6b4e4c3..283d70a 100644 --- a/android/app/src/main/kotlin/com/openchamber/openchamber/MainActivity.kt +++ b/android/app/src/main/kotlin/net/blumia/openchamber/flutter/MainActivity.kt @@ -1,4 +1,4 @@ -package com.openchamber.openchamber +package net.blumia.openchamber.flutter import io.flutter.embedding.android.FlutterActivity diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index d71bcb4..d9aa618 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -383,7 +383,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber; + PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -399,7 +399,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -416,7 +416,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; @@ -431,7 +431,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; @@ -564,7 +564,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber; + PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -586,7 +586,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber; + PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; diff --git a/lib/api/client.dart b/lib/api/client.dart index f1079c1..2aab13f 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -6,6 +6,8 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'package:socks5_proxy/socks_client.dart'; + import 'models.dart'; class ApiError implements Exception { @@ -16,6 +18,48 @@ class ApiError implements Exception { String toString() => message.isEmpty ? 'HTTP $status' : message; } +/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one. +class _ProxyConfig { + final String scheme; // http | https | socks5 | socks5h + final String host; + final int port; + final String? username; + final String? password; + _ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]); + + bool get socks => scheme.startsWith('socks'); +} + +_ProxyConfig? _parseProxy(String? raw) { + final s = raw?.trim() ?? ''; + if (s.isEmpty) return null; + var normalized = s; + if (!normalized.contains('://')) normalized = 'http://$normalized'; + final uri = Uri.tryParse(normalized); + if (uri == null || uri.host.isEmpty) { + throw ArgumentError('代理地址无效:$raw'); + } + final scheme = uri.scheme.toLowerCase(); + final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h'; + final http = scheme == 'http' || scheme == 'https'; + if (!socks && !http) { + throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)'); + } + String? user; + String? pass; + if (uri.userInfo.isNotEmpty) { + final i = uri.userInfo.indexOf(':'); + if (i >= 0) { + user = Uri.decodeComponent(uri.userInfo.substring(0, i)); + pass = Uri.decodeComponent(uri.userInfo.substring(i + 1)); + } else { + user = Uri.decodeComponent(uri.userInfo); + } + } + final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080); + return _ProxyConfig(scheme, uri.host, port, user, pass); +} + class Client { final Uri base; final String? proxy; // http://host:port or socks5://host:port @@ -23,6 +67,8 @@ class Client { final String? fingerprint; String? token; late HttpClient _http; + _ProxyConfig? _proxyConfig; + InternetAddress? _proxyAddress; Client( this.base, { @@ -32,23 +78,50 @@ class Client { }) { _http = HttpClient(); _http.connectionTimeout = const Duration(seconds: 20); - if (proxy != null && proxy!.isNotEmpty) { - _http.findProxy = (uri) { - final u = Uri.parse(proxy!); - final scheme = u.scheme.toLowerCase(); - if (scheme == 'socks5' || scheme == 'socks') { - return 'SOCKS ${u.host}:${u.port}'; + _proxyConfig = _parseProxy(proxy); + if (_proxyConfig != null && _proxyConfig!.socks) { + // Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy + // package tunnels the socket and hands a Socket back to the client. + _http.connectionFactory = (uri, _, __) async { + final address = await _resolveProxyAddress(); + final settings = ProxySettings(address, _proxyConfig!.port, + username: _proxyConfig!.username, password: _proxyConfig!.password); + final tunnel = SocksTCPClient.connect( + [settings], + // A unix-type address carries the host name, so the proxy resolves + // it (socks5h semantics) instead of resolving it here. + InternetAddress(uri.host, type: InternetAddressType.unix), + uri.port, + ); + if (uri.scheme == 'https') { + final secure = tunnel.then( + (s) => s.secure(uri.host, onBadCertificate: _badCertificate)); + return ConnectionTask.fromSocket(secure, () {}); } - return 'PROXY ${u.host}:${u.port}'; + return ConnectionTask.fromSocket(tunnel, () {}); }; + } else if (_proxyConfig != null) { + _http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}'; } - if (insecure || (fingerprint != null && fingerprint!.isNotEmpty)) { - _http.badCertificateCallback = (cert, host, port) { - if (insecure) return true; - final der = _sha256(cert.der); - return der == fingerprint!.replaceAll(':', ''); - }; + _http.badCertificateCallback = (cert, host, port) => _badCertificate(cert); + } + + Future _resolveProxyAddress() async { + if (_proxyAddress != null) return _proxyAddress!; + final addresses = await InternetAddress.lookup(_proxyConfig!.host); + if (addresses.isEmpty) { + throw const SocketException('无法解析代理主机'); } + return _proxyAddress = addresses.first; + } + + /// True for a certificate the app was told to accept: the user trusts any + /// (insecure), or its SHA-256 matches the pinned fingerprint. + bool _badCertificate(X509Certificate cert) { + if (insecure) return true; + final pinned = fingerprint?.replaceAll(':', '').toLowerCase(); + if (pinned == null || pinned.isEmpty) return false; + return _sha256(cert.der) == pinned; } String get baseUrl => base.toString(); diff --git a/lib/screens/servers_screen.dart b/lib/screens/servers_screen.dart index 49b0573..ce4829b 100644 --- a/lib/screens/servers_screen.dart +++ b/lib/screens/servers_screen.dart @@ -92,7 +92,17 @@ class _ServersScreenState extends State { margin: const EdgeInsets.only(bottom: 10), child: ListTile( title: Text(c.label, style: const TextStyle(fontWeight: FontWeight.w600)), - subtitle: Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis), + if (c.proxy.isNotEmpty) + Text('经由 ${c.proxy}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: theme.hintColor)), + ], + ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ @@ -146,6 +156,8 @@ class _ServersScreenState extends State { } void _startEdit(Connection? c) { + widget.app.error = null; + widget.app.clearLastError(); setState(() { _editing = true; _editNew = c == null; @@ -166,7 +178,11 @@ class _ServersScreenState extends State { appBar: AppBar( leading: IconButton( icon: const Icon(Icons.arrow_back), - onPressed: () => setState(() => _editing = false), + onPressed: () { + widget.app.error = null; + widget.app.clearLastError(); + setState(() => _editing = false); + }, ), title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'), ), @@ -257,19 +273,8 @@ class _ServersScreenState extends State { insecure: _insecure, fingerprint: _fingerprint, ); - if (_editNew) { - await widget.app.saveConnection(c); - } else { - final list = [...widget.app.connections]; - for (var i = 0; i < list.length; i++) { - if (list[i].id == c.id) { - list[i] = c; - break; - } - } - widget.app.connections = list; - await widget.app.storage.saveConnections(list); - } + // Only a connection that works is saved (AppState saves it on success), + // so failed attempts do not pile up in the server list. await widget.app.connect(c, password: _password); if (mounted) { if (widget.app.client != null) { diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index 77f15dc..c146f9c 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -304,7 +304,7 @@ class _SessionsScreenState extends State { for (final c in app.connections) ...[ ListTile( title: Text(c.label), - subtitle: Text(c.url), + subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), trailing: app.conn?.id == c.id ? Text('已连接', style: TextStyle(color: Theme.of(context).colorScheme.primary)) : null, diff --git a/lib/state.dart b/lib/state.dart index 138f5a8..a066dd7 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -3,6 +3,7 @@ library; import 'dart:async'; +import 'dart:io'; import 'package:flutter/foundation.dart'; @@ -109,15 +110,37 @@ class AppState extends ChangeNotifier { _connected(cl, c); } catch (e) { busy = false; - error = e.toString(); + error = friendlyConnectError(e); if (!silent) { // Surface in the form: the UI reads error itself. - _lastError = e.toString(); + _lastError = error; } notifyListeners(); } } + /// A short, actionable message for a failed connect. + String friendlyConnectError(Object e) { + if (e is ApiError) return e.message; + if (e is ArgumentError) return e.message?.toString() ?? e.toString(); + if (e is TimeoutException) return '连接超时:检查服务器与代理地址'; + final s = e.toString(); + if (e is SocketException) { + if (s.contains('Connection refused')) { + return '连接被拒绝:服务器或代理未启动,或端口不对'; + } + if (s.contains('Failed host lookup') || s.contains('nodename nor servname')) { + return '无法解析地址:检查服务器或代理主机名'; + } + if (s.contains('Network is unreachable')) return '网络不可达'; + if (s.contains('Connection closed') || s.contains('reset by peer')) { + return '连接被断开:检查代理是否可用'; + } + return '网络错误:$s'; + } + return s; + } + String? _lastError; String? get lastError => _lastError; void clearLastError() => _lastError = null; diff --git a/pubspec.lock b/pubspec.lock index 420a018..c7d4d82 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -594,6 +594,14 @@ packages: description: flutter source: sdk version: "0.0.0" + socks5_proxy: + dependency: "direct main" + description: + name: socks5_proxy + sha256: a4b95506cbd962fa403e862777432671d36511230c4aedd125a28ddb922e6399 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.2" source_span: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 0ff6210..5790e68 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.3.0+300 +version: 0.3.1+301 environment: sdk: ^3.14.0 @@ -16,6 +16,7 @@ dependencies: file_picker: ^13.0.0 path_provider: ^2.1.0 gpt_markdown: ^1.4.0 + socks5_proxy: ^2.1.2 dev_dependencies: flutter_test: diff --git a/tool/proxy_probe.dart b/tool/proxy_probe.dart new file mode 100644 index 0000000..c4e6b8e --- /dev/null +++ b/tool/proxy_probe.dart @@ -0,0 +1,52 @@ +// A probe for the Dart client's proxy support, run with: +// dart run tool/proxy_probe.dart +// It talks to a local OpenChamber server directly and through the local +// SOCKS5 (1080) and HTTP (8081) test proxies. +import 'dart:io'; + +import 'package:openchamber/api/client.dart'; + +Future probe(String? proxy) async { + final label = proxy ?? 'direct'; + final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy); + final sw = Stopwatch()..start(); + try { + final status = await client.sessionStatus().timeout(const Duration(seconds: 15)); + final page = await client + .listSessions(limit: 3) + .timeout(const Duration(seconds: 15)); + print('OK $label auth=${status['authenticated']} ' + 'sessions=${page.data.length} ${sw.elapsedMilliseconds}ms'); + } on Object catch (e) { + print('FAIL $label ${e.toString().split('\n').first}'); + } finally { + client.close(); + } +} + +Future probeStream(String? proxy) async { + final label = proxy ?? 'direct'; + final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy); + try { + final ev = await client + .streamEvents(types: ['session.execution.started']) + .first + .timeout(const Duration(seconds: 10)); + print('OK sse $label ${ev['type']}'); + } on Object catch (e) { + print('FAIL sse $label ${e.toString().split('\n').first}'); + } finally { + client.close(); + } +} + +Future main() async { + await probe(null); + await probe('socks5://127.0.0.1:1080'); + await probe('socks5h://127.0.0.1:1080'); + await probe('http://127.0.0.1:8081'); + await probe('socks5://127.0.0.1:1'); + await probeStream('socks5://127.0.0.1:1080'); + await probeStream('http://127.0.0.1:8081'); + exit(0); +}