feat: port the client to Flutter (0.3.0)
Replace the MyGo/Go app with a Flutter client that keeps the feature set: - servers: saved servers, passwordless and password login, HTTP/SOCKS5 proxy via dart:io, self-signed certificates and pinning, tokens in flutter_secure_storage (Keystore) - sessions: list with live events, search, new/rename/archive/delete, instance sheet - chat: streaming Markdown (flutter_markdown), reasoning and tool rows, image previews, context usage ring and sheet, model/agent switching, fork/revert, attachments (file_picker), permissions - Android 7.0 (API 24)+, plain http:// works in release (Dart dials sockets directly) - build: China mirrors for Gradle/NDK, Aliyun Maven repositories, and the Gradle distribution pre-seeded; release signed with the test keystore Read-aloud is dropped as requested. Version 0.3.0.
No files matched your search
@@ -1,4 +1,22 @@
|
|||||||
/build/
|
# Flutter / Dart
|
||||||
/.mygo/
|
.dart_tool/
|
||||||
|
.flutter-plugins
|
||||||
|
.flutter-plugins-dependencies
|
||||||
|
.packages
|
||||||
|
build/
|
||||||
/dist/
|
/dist/
|
||||||
mygo_windows_*.syso
|
|
||||||
|
# Android
|
||||||
|
android/local.properties
|
||||||
|
android/.gradle/
|
||||||
|
android/app/.cxx/
|
||||||
|
android/captures/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
*.iws
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# This file tracks properties of this Flutter project.
|
||||||
|
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||||
|
#
|
||||||
|
# This file should be version controlled and should not be manually edited.
|
||||||
|
|
||||||
|
version:
|
||||||
|
revision: "ab2912035e160d9cad6306df307576da6128ebdb"
|
||||||
|
channel: "stable"
|
||||||
|
|
||||||
|
project_type: app
|
||||||
|
|
||||||
|
# Tracks metadata for the flutter migrate command
|
||||||
|
migration:
|
||||||
|
platforms:
|
||||||
|
- platform: root
|
||||||
|
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
|
||||||
|
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
|
||||||
|
- platform: android
|
||||||
|
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
|
||||||
|
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
|
||||||
|
- platform: ios
|
||||||
|
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
|
||||||
|
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
|
||||||
|
|
||||||
|
# User provided section
|
||||||
|
|
||||||
|
# List of Local paths (relative to this file) that should be
|
||||||
|
# ignored by the migrate tool.
|
||||||
|
#
|
||||||
|
# Files that are not part of the templates will be ignored by default.
|
||||||
|
unmanaged_files:
|
||||||
|
- 'lib/main.dart'
|
||||||
|
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
#Wed Nov 18 12:18:36 CST 2026
|
||||||
|
gradle.version=8.14.3
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
// Written by mygo build: the plugins the app's packages name.
|
||||||
|
package dev.mygo
|
||||||
|
|
||||||
|
internal fun registerPlugins() {
|
||||||
|
PluginHost.register("tts", TTSPlugin())
|
||||||
|
}
|
||||||
@@ -1,10 +1,29 @@
|
|||||||
# OpenChamber 手机客户端(MyGo/Go)开发计划
|
# OpenChamber 手机客户端(Flutter / Dart)开发计划
|
||||||
|
|
||||||
> 调研对象:MyGo 0.10.0(Go + 自绘原生 UI)、OpenChamber 2.7.0、opencode v2.2.7
|
> 调研对象:Flutter 3.50(stable)、OpenChamber 2.7.0、opencode v2.2.7
|
||||||
> 目标:Android 优先的手机客户端,MVP = 输入地址 + 密码连接(可选 http/socks5 代理),浏览并操作现有会话
|
> 目标:Android 优先的手机客户端,MVP = 输入地址 + 密码连接(可选 http/socks5 代理),浏览并操作现有会话
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
|
||||||
|
|
||||||
|
**背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo;
|
||||||
|
按评估结论改用 Flutter 做同功能重写,验证其移动端 UI 成熟度。
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 环境 | Flutter **3.50.0 stable** 装在 `~/SDK/flutter`;`FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn`、`PUB_HOSTED_URL=https://pub.flutter-io.cn` |
|
||||||
|
| 构建坑 | Gradle 发行包(gradle-9.5.0-all,230MB)从 services.gradle.org/GitHub 下载一小时级 → 用腾讯镜像预置;AGP 又重装 NDK 28.2(688MB,dl.google.com 慢)→ 腾讯 AndroidSDK 镜像重装完整 NDK;另在 settings/build.gradle.kts 前加**阿里云 Maven 镜像** |
|
||||||
|
| 依赖坑 | file_picker 8.x 硬编码 compileSdk 34,与 flutter_plugin_android_lifecycle 要求的 36 冲突 → 升 file_picker 13.4(联邦版 API)+ flutter_secure_storage 11.2 |
|
||||||
|
| 复用 | Go 客户端无法复用;`lib/api/` 按同一协议重写(HTTP/SOCKS5 代理、自签/pinning、SSE、part-shells) |
|
||||||
|
| 最低 Android | **24(7.0)** |
|
||||||
|
| 明文 HTTP | Dart `HttpClient` 直接建 socket,release 连 `http://` 无需 cleartext 开关(已实测) |
|
||||||
|
| 模拟器实测 | 服务器列表→添加/连接(无密码自动跳过)→会话列表(运行点/模型·时间)→聊天:流式 Markdown、思考/工具行、页脚、上下文占用环(65%/18%)、输入区;发送与回复正常 |
|
||||||
|
| 产物 | `dist/OpenChamber-0.3.0-flutter-release.apk`(0.3.0 / code 300,`~/SDK/test-upload.jks` 签名,`OPENCHAMBER_KEYSTORE*` 可覆盖) |
|
||||||
|
| 未做 | 朗读(按需求去掉)、附件/图片预览虽已实现但未在模拟器逐项点验、i18n、启动图 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 0.2 迁移到 MyGo(2026-11-18,分支 `mygo`,0.3.0)
|
## 0.2 迁移到 MyGo(2026-11-18,分支 `mygo`,0.3.0)
|
||||||
|
|
||||||
**背景**:Asuka 0.2 把应用语言从 Go 换成了自研 Asuka 语言(C 内核、无 Go 运行时),继续留在 Go 线已没有上游维护;
|
**背景**:Asuka 0.2 把应用语言从 Go 换成了自研 Asuka 语言(C 内核、无 Go 运行时),继续留在 Go 线已没有上游维护;
|
||||||
|
|||||||
@@ -1,71 +1,48 @@
|
|||||||
# OpenChamber Native
|
# OpenChamber Native
|
||||||
|
|
||||||
A lightweight OpenChamber client for phones, written in Go with
|
A lightweight OpenChamber client for phones, written in **Flutter** (Dart).
|
||||||
[MyGo](https://mygo.run/)'s native UI. Android first.
|
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 — multiple saved servers with a connect list (add, edit,
|
Status: 0.3.0 — servers (passwordless / password login, HTTP/SOCKS5 proxy,
|
||||||
delete, switch; passwordless and password login; HTTP or SOCKS5 proxy and
|
self-signed certificates and pinning), session list with search and live
|
||||||
self-signed certificates per server), session search, live session list,
|
events, chat with streaming Markdown, tool rows with image previews, a
|
||||||
chat with streaming Markdown, image and file attachments with inline
|
context usage ring with a detail sheet, model/agent switching, copy / fork /
|
||||||
previews, a context usage ring with a detail sheet, previews of images
|
revert, attachments (photos/files), permissions. Android 7.0 (API 24)+.
|
||||||
named by tool calls, permissions, model/agent switching, turn and prompt
|
|
||||||
actions (copy, fork, revert, read aloud), new sessions,
|
|
||||||
archive/delete/rename, the OpenChamber icon, and a UI-independent API
|
|
||||||
client. Android 7.0 (API 24) and later.
|
|
||||||
|
|
||||||
## What is here
|
## What is here
|
||||||
|
|
||||||
| Path | What |
|
| Path | What |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `internal/ocapi/` | OpenChamber HTTP client: auth (password → device token), sessions, messages, prompt/interrupt/model/agent, permissions, SSE events, HTTP/SOCKS5 proxy, certificate pinning |
|
| `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` |
|
||||||
| `internal/storage/` | Saved servers in `connections.json` (app data), one device token per server in `mygo.Secrets` (Android Keystore), per-install id for device dedupe |
|
| `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) |
|
||||||
| `internal/appui/` | Screens: servers, sessions, chat (streaming Markdown via `ui/markdown`, reasoning/tool folding, permissions, context usage, previews) |
|
| `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding |
|
||||||
| `internal/tts/` | A Kotlin TextToSpeech plugin (read-aloud), compiled into the app by `mygo build` |
|
| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `flutter_markdown`, composer, sheets) |
|
||||||
| `third_party/mygo/` | A small local fork of MyGo 0.10.0: its Android host's `minSdk` reads the `mygoMinSdk` property (24), and notifications are guarded for API < 26 |
|
| `lib/widgets/` | The context usage ring |
|
||||||
| `cmd/ocprobe/` | Terminal probe used to validate the API without a device |
|
|
||||||
| `PLAN.md` | Research, API contract, architecture, milestones, risks |
|
Read-aloud (TTS) is intentionally **not** implemented (matching the original).
|
||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
MyGo requires **Go 1.27.3+**; install it with mise (`mise install go@1.27.4`),
|
Flutter 3.50 (stable) lives at `~/SDK/flutter`; artifacts use the China
|
||||||
and make sure a stale `GOROOT` env var is not set. The `mygo` CLI is pinned as
|
mirrors.
|
||||||
a Go tool in `go.mod` and builds from the local fork.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# terminal probe against a running server
|
export PATH=$HOME/SDK/flutter/bin:$PATH
|
||||||
go run ./cmd/ocprobe -url http://127.0.0.1:3000 health
|
export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn
|
||||||
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -limit 5 sessions
|
export PUB_HOSTED_URL=https://pub.flutter-io.cn
|
||||||
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -password secret sessions
|
|
||||||
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -seconds 20 events
|
|
||||||
|
|
||||||
# headless tests, including the UI
|
|
||||||
go test ./... -race
|
|
||||||
```
|
|
||||||
|
|
||||||
## Android
|
|
||||||
|
|
||||||
The SDK lives at `~/SDK/AndroidSDK`, the JDK for Gradle at `~/SDK/jdk-21`.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
export PATH=$HOME/.local/share/mise/installs/go/1.27.4/bin:$PATH
|
|
||||||
unset GOROOT
|
|
||||||
export ANDROID_HOME=$HOME/SDK/AndroidSDK
|
export ANDROID_HOME=$HOME/SDK/AndroidSDK
|
||||||
export JAVA_HOME=$HOME/SDK/jdk-21
|
export JAVA_HOME=$HOME/SDK/jdk-21
|
||||||
export PATH=$ANDROID_HOME/platform-tools:$JAVA_HOME/bin:$PATH
|
|
||||||
|
|
||||||
go tool mygo dev -platform android --device emulator-5554 # live reload
|
flutter pub get
|
||||||
|
flutter test
|
||||||
# release: dist/android/openchamber-0.3.0.apk and .aab
|
flutter build apk --release # dist artifacts in build/app/outputs/flutter-apk
|
||||||
export MYGO_ANDROID_KEYSTORE_PASSWORD=… MYGO_ANDROID_KEY_PASSWORD=…
|
|
||||||
go tool mygo build -platform android
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`android.minSdk` is 24 (Android 7.0). Release builds talk to plain `http://`
|
`android/app/build.gradle.kts` sets `minSdk 24` and signs releases with
|
||||||
LAN servers: the Go HTTP client dials sockets itself, so Android's cleartext
|
`~/SDK/test-upload.jks` (override via `OPENCHAMBER_KEYSTORE*` env). Dart's
|
||||||
policy (which applies to platform HTTP libraries) never sees the traffic —
|
`HttpClient` dials sockets itself, so plain `http://` LAN servers work in
|
||||||
no manifest flag is needed. The local fork exists only to let the MyGo host
|
release without a cleartext manifest flag, as with the Go clients.
|
||||||
build with `minSdk 24` (upstream pins 26) and to guard its notification code
|
|
||||||
on API < 26.
|
|
||||||
|
|
||||||
The earlier Asuka version of this app lived on the `main` branch; this
|
Earlier attempts: `main` (Asuka/Go, 0.2.x) and `mygo` (MyGo, 0.3.0).
|
||||||
branch (`mygo`) is the 0.3 rewrite.
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# This file configures the analyzer, which statically analyzes Dart code to
|
||||||
|
# check for errors, warnings, and lints.
|
||||||
|
#
|
||||||
|
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
|
||||||
|
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
|
||||||
|
# invoked from the command line by running `flutter analyze`.
|
||||||
|
|
||||||
|
# The following line activates a set of recommended lints for Flutter apps,
|
||||||
|
# packages, and plugins designed to encourage good coding practices.
|
||||||
|
include: package:flutter_lints/flutter.yaml
|
||||||
|
|
||||||
|
analyzer:
|
||||||
|
exclude:
|
||||||
|
- build/**
|
||||||
|
- android/**
|
||||||
|
- ios/**
|
||||||
|
|
||||||
|
linter:
|
||||||
|
# The lint rules applied to this project can be customized in the
|
||||||
|
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
|
||||||
|
# included above or to enable additional rules. A list of all available lints
|
||||||
|
# and their documentation is published at https://dart.dev/lints.
|
||||||
|
#
|
||||||
|
# Instead of disabling a lint rule for the entire project in the
|
||||||
|
# section below, it can also be suppressed for a single line of code
|
||||||
|
# or a specific dart file by using the `// ignore: name_of_lint` and
|
||||||
|
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
|
||||||
|
# producing the lint.
|
||||||
|
rules:
|
||||||
|
# avoid_print: false # Uncomment to disable the `avoid_print` rule
|
||||||
|
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
|
||||||
|
|
||||||
|
# Additional information about this file can be found at
|
||||||
|
# https://dart.dev/guides/language/analysis-options
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
gradle-wrapper.jar
|
||||||
|
/.gradle
|
||||||
|
/captures/
|
||||||
|
/gradlew
|
||||||
|
/gradlew.bat
|
||||||
|
/local.properties
|
||||||
|
GeneratedPluginRegistrant.java
|
||||||
|
.cxx/
|
||||||
|
|
||||||
|
# Remember to never publicly share your keystore.
|
||||||
|
# See https://flutter.dev/to/reference-keystore
|
||||||
|
key.properties
|
||||||
|
**/*.keystore
|
||||||
|
**/*.jks
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||||
|
id("dev.flutter.flutter-gradle-plugin")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.openchamber.openchamber"
|
||||||
|
compileSdk = flutter.compileSdkVersion
|
||||||
|
ndkVersion = flutter.ndkVersion
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.openchamber.native"
|
||||||
|
minSdk = 24
|
||||||
|
targetSdk = flutter.targetSdkVersion
|
||||||
|
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
|
||||||
|
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
|
||||||
|
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
|
||||||
|
// flag during build.
|
||||||
|
versionCode = flutter.versionCode
|
||||||
|
versionName = flutter.versionName
|
||||||
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
create("release") {
|
||||||
|
storeFile = file(System.getenv("OPENCHAMBER_KEYSTORE") ?: "/home/blumia/SDK/test-upload.jks")
|
||||||
|
storePassword = System.getenv("OPENCHAMBER_KEYSTORE_PASSWORD") ?: "testpass"
|
||||||
|
keyAlias = System.getenv("OPENCHAMBER_KEY_ALIAS") ?: "upload"
|
||||||
|
keyPassword = System.getenv("OPENCHAMBER_KEY_PASSWORD") ?: "testpass"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
signingConfig = signingConfigs.getByName("release")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
compilerOptions {
|
||||||
|
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
flutter {
|
||||||
|
source = "../.."
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<!-- The INTERNET permission is required for development. Specifically,
|
||||||
|
the Flutter tool needs it to communicate with the running application
|
||||||
|
to allow setting breakpoints, to provide hot reload, etc.
|
||||||
|
-->
|
||||||
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
<application
|
||||||
|
android:label="OpenChamber"
|
||||||
|
android:name="${applicationName}"
|
||||||
|
android:icon="@mipmap/ic_launcher">
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:launchMode="singleTop"
|
||||||
|
android:taskAffinity=""
|
||||||
|
android:theme="@style/LaunchTheme"
|
||||||
|
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||||
|
android:hardwareAccelerated="true"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<!-- Specifies an Android theme to apply to this Activity as soon as
|
||||||
|
the Android process has started. This theme is visible to the user
|
||||||
|
while the Flutter UI initializes. After that, this theme continues
|
||||||
|
to determine the Window background behind the Flutter UI. -->
|
||||||
|
<meta-data
|
||||||
|
android:name="io.flutter.embedding.android.NormalTheme"
|
||||||
|
android:resource="@style/NormalTheme"
|
||||||
|
/>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN"/>
|
||||||
|
<category android:name="android.intent.category.LAUNCHER"/>
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<!-- Don't delete the meta-data below.
|
||||||
|
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||||
|
<meta-data
|
||||||
|
android:name="flutterEmbedding"
|
||||||
|
android:value="2" />
|
||||||
|
</application>
|
||||||
|
<!-- Required to query activities that can process text, see:
|
||||||
|
https://developer.android.com/training/package-visibility and
|
||||||
|
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
|
||||||
|
|
||||||
|
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
|
||||||
|
<queries>
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
||||||
|
<data android:mimeType="text/plain"/>
|
||||||
|
</intent>
|
||||||
|
</queries>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.openchamber.openchamber
|
||||||
|
|
||||||
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
|
|
||||||
|
class MainActivity : FlutterActivity()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Modify this file to customize your launch splash screen -->
|
||||||
|
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item android:drawable="?android:colorBackground" />
|
||||||
|
|
||||||
|
<!-- You can insert your own image assets here -->
|
||||||
|
<!-- <item>
|
||||||
|
<bitmap
|
||||||
|
android:gravity="center"
|
||||||
|
android:src="@mipmap/launch_image" />
|
||||||
|
</item> -->
|
||||||
|
</layer-list>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Modify this file to customize your launch splash screen -->
|
||||||
|
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item android:drawable="@android:color/white" />
|
||||||
|
|
||||||
|
<!-- You can insert your own image assets here -->
|
||||||
|
<!-- <item>
|
||||||
|
<bitmap
|
||||||
|
android:gravity="center"
|
||||||
|
android:src="@mipmap/launch_image" />
|
||||||
|
</item> -->
|
||||||
|
</layer-list>
|
||||||
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 5.1 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,18 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
||||||
|
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
|
<!-- Show a splash screen on the activity. Automatically removed when
|
||||||
|
the Flutter engine draws its first frame -->
|
||||||
|
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||||
|
</style>
|
||||||
|
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||||
|
This theme determines the color of the Android Window while your
|
||||||
|
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||||
|
running.
|
||||||
|
|
||||||
|
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||||
|
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
|
<item name="android:windowBackground">?android:colorBackground</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
|
||||||
|
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||||
|
<!-- Show a splash screen on the activity. Automatically removed when
|
||||||
|
the Flutter engine draws its first frame -->
|
||||||
|
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||||
|
</style>
|
||||||
|
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||||
|
This theme determines the color of the Android Window while your
|
||||||
|
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||||
|
running.
|
||||||
|
|
||||||
|
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||||
|
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||||
|
<item name="android:windowBackground">?android:colorBackground</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<!-- The INTERNET permission is required for development. Specifically,
|
||||||
|
the Flutter tool needs it to communicate with the running application
|
||||||
|
to allow setting breakpoints, to provide hot reload, etc.
|
||||||
|
-->
|
||||||
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
allprojects {
|
||||||
|
repositories {
|
||||||
|
// China mirrors first, then the canonical repositories.
|
||||||
|
maven { url = uri("https://maven.aliyun.com/repository/google") }
|
||||||
|
maven { url = uri("https://maven.aliyun.com/repository/central") }
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val newBuildDir: Directory =
|
||||||
|
rootProject.layout.buildDirectory
|
||||||
|
.dir("../../build")
|
||||||
|
.get()
|
||||||
|
rootProject.layout.buildDirectory.value(newBuildDir)
|
||||||
|
|
||||||
|
subprojects {
|
||||||
|
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
|
||||||
|
project.layout.buildDirectory.value(newSubprojectBuildDir)
|
||||||
|
}
|
||||||
|
subprojects {
|
||||||
|
project.evaluationDependsOn(":app")
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register<Delete>("clean") {
|
||||||
|
delete(rootProject.layout.buildDirectory)
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||||
|
android.useAndroidX=true
|
||||||
|
# This newDsl flag was added by the Flutter template
|
||||||
|
android.newDsl=false
|
||||||
|
# This builtInKotlin flag was added by the Flutter template
|
||||||
|
android.builtInKotlin=false
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
pluginManagement {
|
||||||
|
val flutterSdkPath =
|
||||||
|
run {
|
||||||
|
val properties = java.util.Properties()
|
||||||
|
file("local.properties").inputStream().use { properties.load(it) }
|
||||||
|
val flutterSdkPath = properties.getProperty("flutter.sdk")
|
||||||
|
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
|
||||||
|
flutterSdkPath
|
||||||
|
}
|
||||||
|
|
||||||
|
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
// China mirrors first, then the canonical repositories.
|
||||||
|
maven { url = uri("https://maven.aliyun.com/repository/google") }
|
||||||
|
maven { url = uri("https://maven.aliyun.com/repository/central") }
|
||||||
|
maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") }
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||||
|
id("com.android.application") version "9.3.1" apply false
|
||||||
|
id("org.jetbrains.kotlin.android") version "2.4.20" apply false
|
||||||
|
}
|
||||||
|
|
||||||
|
include(":app")
|
||||||
@@ -1,222 +0,0 @@
|
|||||||
// Command ocprobe exercises the OpenChamber API from a terminal. It is the
|
|
||||||
// M0 probe: no UI, just the same client the app uses.
|
|
||||||
//
|
|
||||||
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 health
|
|
||||||
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 -password secret sessions
|
|
||||||
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 messages ses_123
|
|
||||||
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 events -seconds 20
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"os/signal"
|
|
||||||
"strings"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
var (
|
|
||||||
base = flag.String("url", "http://127.0.0.1:3000", "OpenChamber server URL")
|
|
||||||
password = flag.String("password", "", "UI password (empty for a passwordless server)")
|
|
||||||
proxy = flag.String("proxy", "", "optional HTTP(S) or SOCKS5 proxy URL")
|
|
||||||
insecure = flag.Bool("insecure", false, "skip TLS verification")
|
|
||||||
fp = flag.String("fingerprint", "", "pin the server certificate (SHA-256 hex)")
|
|
||||||
timeout = flag.Duration("timeout", 20*time.Second, "request timeout")
|
|
||||||
limit = flag.Int("limit", 20, "page size for sessions/messages")
|
|
||||||
seconds = flag.Int("seconds", 10, "how long to watch events")
|
|
||||||
types = flag.String("types", "", "comma-separated event types for events")
|
|
||||||
)
|
|
||||||
flag.Parse()
|
|
||||||
if flag.NArg() == 0 {
|
|
||||||
usage()
|
|
||||||
}
|
|
||||||
cmd := flag.Arg(0)
|
|
||||||
|
|
||||||
client, err := ocapi.New(*base, ocapi.Options{
|
|
||||||
Proxy: *proxy,
|
|
||||||
InsecureSkipVerify: *insecure,
|
|
||||||
CertFingerprint: *fp,
|
|
||||||
Timeout: *timeout,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
||||||
defer stop()
|
|
||||||
|
|
||||||
// Every command except health authenticates first.
|
|
||||||
if cmd != "health" {
|
|
||||||
if err := authenticate(ctx, client, *password); err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch cmd {
|
|
||||||
case "health":
|
|
||||||
h, err := client.Health(ctx)
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
printJSON(h)
|
|
||||||
fmt.Fprintf(os.Stderr, "server %s, openchamber %s, opencode ready=%v\n", client.BaseURL(), h.OpenChamberVersion, h.IsOpenCodeReady)
|
|
||||||
|
|
||||||
case "status":
|
|
||||||
st, err := client.SessionStatus(ctx)
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
printJSON(st)
|
|
||||||
|
|
||||||
case "sessions":
|
|
||||||
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: *limit, Order: "desc"})
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
printJSON(page)
|
|
||||||
fmt.Fprintf(os.Stderr, "%d sessions, next=%q\n", len(page.Data), page.Cursor.Next)
|
|
||||||
|
|
||||||
case "messages":
|
|
||||||
if flag.NArg() < 2 {
|
|
||||||
fail(fmt.Errorf("messages needs a session id"))
|
|
||||||
}
|
|
||||||
page, err := client.ListMessages(ctx, flag.Arg(1), ocapi.ListMessagesOptions{Limit: *limit, Order: "desc"})
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
printJSON(page)
|
|
||||||
fmt.Fprintf(os.Stderr, "%d messages, next=%q\n", len(page.Data), page.Cursor.Next)
|
|
||||||
|
|
||||||
case "raw":
|
|
||||||
if flag.NArg() < 2 {
|
|
||||||
fail(fmt.Errorf("raw needs an absolute file path, and optionally a directory"))
|
|
||||||
}
|
|
||||||
dir := ""
|
|
||||||
if flag.NArg() > 2 {
|
|
||||||
dir = flag.Arg(2)
|
|
||||||
}
|
|
||||||
data, mime, err := client.RawFile(ctx, flag.Arg(1), dir)
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
fmt.Fprintf(os.Stderr, "%d bytes, %s\n", len(data), mime)
|
|
||||||
|
|
||||||
case "prompt":
|
|
||||||
if flag.NArg() < 3 {
|
|
||||||
fail(fmt.Errorf("prompt needs a session id and text"))
|
|
||||||
}
|
|
||||||
if err := client.Prompt(ctx, flag.Arg(1), ocapi.PromptOptions{Text: strings.Join(flag.Args()[2:], " ")}); err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
fmt.Fprintln(os.Stderr, "prompt accepted; watch `events` for the reply")
|
|
||||||
|
|
||||||
case "interrupt":
|
|
||||||
if flag.NArg() < 2 {
|
|
||||||
fail(fmt.Errorf("interrupt needs a session id"))
|
|
||||||
}
|
|
||||||
ok, err := client.Interrupt(ctx, flag.Arg(1), "")
|
|
||||||
if err != nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
fmt.Fprintf(os.Stderr, "interrupted=%v\n", ok)
|
|
||||||
|
|
||||||
case "events":
|
|
||||||
var list []string
|
|
||||||
if strings.TrimSpace(*types) != "" {
|
|
||||||
for _, t := range strings.Split(*types, ",") {
|
|
||||||
if t = strings.TrimSpace(t); t != "" {
|
|
||||||
list = append(list, t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ectx, cancel := context.WithTimeout(ctx, time.Duration(*seconds)*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
fmt.Fprintf(os.Stderr, "watching events for %ds…\n", *seconds)
|
|
||||||
err := client.StreamEvents(ectx, list, func(ev ocapi.Event) error {
|
|
||||||
fmt.Printf("%s %s %s\n", time.UnixMilli(ev.Created).Format("15:04:05"), ev.Type, string(ev.Data))
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil && ectx.Err() == nil {
|
|
||||||
fail(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
usage()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func authenticate(ctx context.Context, c *ocapi.Client, password string) error {
|
|
||||||
st, err := c.SessionStatus(ctx)
|
|
||||||
if err == nil {
|
|
||||||
if !st.Authenticated {
|
|
||||||
return fmt.Errorf("server did not accept the request")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if !ocapi.IsUnauthorized(err) {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(password) == "" {
|
|
||||||
return fmt.Errorf("this server requires a password; pass -password")
|
|
||||||
}
|
|
||||||
res, err := c.Login(ctx, ocapi.LoginRequest{
|
|
||||||
Password: password,
|
|
||||||
DedupeKey: probeDedupeKey(),
|
|
||||||
ClientLabel: "OpenChamber Probe",
|
|
||||||
ClientKind: "desktop",
|
|
||||||
DevicePlatform: "cli",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
if wait, ok := ocapi.IsRateLimited(err); ok {
|
|
||||||
return fmt.Errorf("%w (retry after %s)", err, wait)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if res.ClientToken == "" {
|
|
||||||
return fmt.Errorf("login returned no client token")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func probeDedupeKey() string {
|
|
||||||
host, err := os.Hostname()
|
|
||||||
if err != nil || host == "" {
|
|
||||||
return "ocprobe"
|
|
||||||
}
|
|
||||||
return "ocprobe-" + host
|
|
||||||
}
|
|
||||||
|
|
||||||
func printJSON(v any) {
|
|
||||||
enc := json.NewEncoder(os.Stdout)
|
|
||||||
enc.SetIndent("", " ")
|
|
||||||
_ = enc.Encode(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
func usage() {
|
|
||||||
fmt.Fprint(os.Stderr, `usage: ocprobe [flags] <command>
|
|
||||||
|
|
||||||
commands:
|
|
||||||
health server health (no auth)
|
|
||||||
status probe /auth/session
|
|
||||||
sessions list sessions (newest first)
|
|
||||||
messages <session-id> latest messages of a session
|
|
||||||
raw <path> [directory] fetch a file the server can read
|
|
||||||
prompt <session-id> <text> send a message
|
|
||||||
interrupt <session-id> stop the running turn
|
|
||||||
events watch the event stream
|
|
||||||
`)
|
|
||||||
flag.PrintDefaults()
|
|
||||||
os.Exit(2)
|
|
||||||
}
|
|
||||||
|
|
||||||
func fail(err error) {
|
|
||||||
fmt.Fprintln(os.Stderr, "ocprobe:", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
module github.com/openchamber/openchamber-native
|
|
||||||
|
|
||||||
go 1.27.4
|
|
||||||
|
|
||||||
tool github.com/egoist/mygo/cmd/mygo
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/egoist/mygo v0.10.0
|
|
||||||
golang.org/x/net v0.59.0
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/ProtonMail/go-crypto v1.4.1 // indirect
|
|
||||||
github.com/cloudflare/circl v1.6.2 // indirect
|
|
||||||
github.com/ebitengine/purego v0.11.1 // indirect
|
|
||||||
github.com/go-text/typesetting v0.3.5 // indirect
|
|
||||||
github.com/klauspost/compress v1.18.6 // indirect
|
|
||||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
|
||||||
go.digitalxero.dev/rpm v0.3.4 // indirect
|
|
||||||
golang.org/x/crypto v0.57.0 // indirect
|
|
||||||
golang.org/x/image v0.46.0 // indirect
|
|
||||||
golang.org/x/sys v0.48.0 // indirect
|
|
||||||
golang.org/x/text v0.43.0 // indirect
|
|
||||||
)
|
|
||||||
|
|
||||||
replace github.com/egoist/mygo => ./third_party/mygo
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
|
|
||||||
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
|
|
||||||
github.com/cloudflare/circl v1.6.2 h1:hL7VBpHHKzrV5WTfHCaBsgx/HGbBYlgrwvNXEVDYYsQ=
|
|
||||||
github.com/cloudflare/circl v1.6.2/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
|
|
||||||
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
|
|
||||||
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
|
|
||||||
github.com/go-text/typesetting v0.3.5/go.mod h1:XZO1hD+nQVyvVa5IicQk7FsCa4PFQaJ2soWAP1f//68=
|
|
||||||
github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc h1:8FGo2It5K75XkavhTiCKExUfVaVDS1feBnLCru5qeoY=
|
|
||||||
github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
|
|
||||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
|
||||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
|
||||||
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
|
||||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
|
||||||
go.digitalxero.dev/rpm v0.3.4 h1:iq+rx7zB6wQeNhLQ1mcvW92v9ZqNaxCvuu0+nPVit4w=
|
|
||||||
go.digitalxero.dev/rpm v0.3.4/go.mod h1:45EsEzHamzqInyWQx9vpj7OYpL0BrkbQF87VdrLn5wo=
|
|
||||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
|
||||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
|
||||||
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
|
||||||
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
|
||||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
|
||||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
|
||||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
|
||||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
|
||||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
|
||||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
@@ -1,478 +0,0 @@
|
|||||||
// Package appui is the MyGo client: the windows, screens and state of the
|
|
||||||
// OpenChamber app.
|
|
||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/storage"
|
|
||||||
)
|
|
||||||
|
|
||||||
// App is the whole application's state. Its view functions build the
|
|
||||||
// windows' interfaces from it, on the main thread, whenever a frame is
|
|
||||||
// needed.
|
|
||||||
type App struct {
|
|
||||||
store storage.Store
|
|
||||||
|
|
||||||
// Windows.
|
|
||||||
win *mygo.Window // the root window: servers or sessions
|
|
||||||
chatWin *mygo.Window // the pushed chat window, when a session is open
|
|
||||||
|
|
||||||
// The active connection.
|
|
||||||
client *ocapi.Client
|
|
||||||
conn storage.Connection
|
|
||||||
busy bool // a connect is in progress
|
|
||||||
|
|
||||||
// Server list / connect form state.
|
|
||||||
phase string // "" = disconnected, "form" = editing/adding, else connected
|
|
||||||
formTitle string
|
|
||||||
formLabel string
|
|
||||||
formURL string
|
|
||||||
formProxy string
|
|
||||||
formInsecure bool
|
|
||||||
formFinger string
|
|
||||||
formPassword string
|
|
||||||
formEditing *storage.Connection
|
|
||||||
formError string
|
|
||||||
|
|
||||||
// Sessions list state.
|
|
||||||
sessions []ocapi.Session
|
|
||||||
sessionsCursor string
|
|
||||||
sessionsLoad bool
|
|
||||||
searchOpen bool
|
|
||||||
searchText string
|
|
||||||
searchTimer *time.Timer
|
|
||||||
errorText string
|
|
||||||
|
|
||||||
// Live state from the event stream.
|
|
||||||
active map[string]bool
|
|
||||||
perms []ocapi.PermissionRequest
|
|
||||||
|
|
||||||
// The open chat, if any.
|
|
||||||
chat *chat
|
|
||||||
|
|
||||||
sessionListState ui.ListState
|
|
||||||
|
|
||||||
instancesOpen bool
|
|
||||||
|
|
||||||
serverActionOpen *bool
|
|
||||||
serverActionTarget *storage.Connection
|
|
||||||
confirmDelete bool
|
|
||||||
deleteTarget *storage.Connection
|
|
||||||
|
|
||||||
// Session list sheet state.
|
|
||||||
newOpen bool
|
|
||||||
newTitle string
|
|
||||||
sessionActionOpen bool
|
|
||||||
sessionActionTarget ocapi.Session
|
|
||||||
renameOpen bool
|
|
||||||
renameTarget ocapi.Session
|
|
||||||
renameText string
|
|
||||||
sessionDeleteOpen bool
|
|
||||||
sessionDeleteTarget *ocapi.Session
|
|
||||||
|
|
||||||
// Tables the UI needs on the main thread.
|
|
||||||
modelNames map[string]string
|
|
||||||
|
|
||||||
// The event stream.
|
|
||||||
streamCancel context.CancelFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
// New makes the app. Call it before mygo.App.Run. A nil store makes the
|
|
||||||
// persistent store on Ready, once the app can name its data directory.
|
|
||||||
func New(store storage.Store) *App {
|
|
||||||
if store == nil {
|
|
||||||
store = &lazyStore{}
|
|
||||||
}
|
|
||||||
return &App{
|
|
||||||
store: store,
|
|
||||||
active: map[string]bool{},
|
|
||||||
modelNames: map[string]string{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// lazyStore creates the persistent store on first use, on the main thread.
|
|
||||||
type lazyStore struct{ s storage.Store }
|
|
||||||
|
|
||||||
func (l *lazyStore) get() storage.Store {
|
|
||||||
if l.s == nil {
|
|
||||||
l.s = storage.New()
|
|
||||||
}
|
|
||||||
return l.s
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *lazyStore) Connections() []storage.Connection { return l.get().Connections() }
|
|
||||||
func (l *lazyStore) SaveConnections(c []storage.Connection) { l.get().SaveConnections(c) }
|
|
||||||
func (l *lazyStore) InstallID() string { return l.get().InstallID() }
|
|
||||||
func (l *lazyStore) LoadToken(c storage.Connection) (string, bool, error) {
|
|
||||||
return l.get().LoadToken(c)
|
|
||||||
}
|
|
||||||
func (l *lazyStore) SaveToken(id, token string) error { return l.get().SaveToken(id, token) }
|
|
||||||
func (l *lazyStore) ClearToken(c storage.Connection) error { return l.get().ClearToken(c) }
|
|
||||||
|
|
||||||
// Ready runs when the app is ready (mygo.App.WhenReady): it makes the root
|
|
||||||
// window and reconnects to the most recently used server.
|
|
||||||
func (a *App) Ready() {
|
|
||||||
a.win = mygo.NewWindow(mygo.WindowOptions{
|
|
||||||
Title: "OpenChamber",
|
|
||||||
Content: ui.View(a.view),
|
|
||||||
})
|
|
||||||
a.reconnectLast()
|
|
||||||
}
|
|
||||||
|
|
||||||
// view is the root window's interface: the server list when disconnected,
|
|
||||||
// the sessions list when connected.
|
|
||||||
func (a *App) view(c *ui.Context) {
|
|
||||||
if a.client == nil {
|
|
||||||
a.serversView(c)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.sessionsView(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// post runs fn on the main thread and redraws the root window.
|
|
||||||
func (a *App) post(fn func()) {
|
|
||||||
if a.win != nil {
|
|
||||||
a.win.Update(fn)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// chatPost runs fn on the main thread and redraws the chat window.
|
|
||||||
func (a *App) chatPost(fn func()) {
|
|
||||||
if a.chat != nil && a.chatWin != nil {
|
|
||||||
a.chatWin.Update(fn)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.post(fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) reconnectLast() {
|
|
||||||
conns := a.store.Connections()
|
|
||||||
if len(conns) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
conn := conns[0]
|
|
||||||
a.connectTo(conn, "", true)
|
|
||||||
}
|
|
||||||
|
|
||||||
// connectTo builds a client for conn and authenticates. When password is
|
|
||||||
// empty it tries the saved device token first. Silent connections (the
|
|
||||||
// recent server on startup) show errors in the server list instead of a
|
|
||||||
// modal form.
|
|
||||||
func (a *App) connectTo(conn storage.Connection, password string, silent bool) {
|
|
||||||
if a.busy {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.busy = true
|
|
||||||
a.errorText = ""
|
|
||||||
go func() {
|
|
||||||
client, err := ocapi.New(conn.URL, ocapi.Options{
|
|
||||||
Proxy: conn.Proxy,
|
|
||||||
InsecureSkipVerify: conn.Insecure,
|
|
||||||
CertFingerprint: conn.Fingerprint,
|
|
||||||
Timeout: 20 * time.Second,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.failConnect(conn, silent, friendlyError(err))
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
token, ok, err := a.store.LoadToken(conn)
|
|
||||||
if err == nil && !ok {
|
|
||||||
// No saved token: a passwordless server needs none. Probe it.
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
||||||
st, serr := client.SessionStatus(ctx)
|
|
||||||
cancel()
|
|
||||||
if serr == nil && st.Disabled && !st.Locked {
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.connected(client, conn, silent)
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil || (!ok && password == "") {
|
|
||||||
if ok {
|
|
||||||
err = fmt.Errorf("无法读取已保存的凭据")
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.failConnect(conn, silent, friendlyError(err))
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Needs a password: ask in the form.
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.promptPassword(conn)
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
client.SetToken(token)
|
|
||||||
if err := a.verifyConnection(client); err != nil {
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.failConnect(conn, silent, friendlyError(err))
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.post(func() { a.connected(client, conn, silent) })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Login with the password the form gave.
|
|
||||||
res, err := client.Login(context.Background(), ocapi.LoginRequest{
|
|
||||||
Password: password,
|
|
||||||
DedupeKey: a.store.InstallID(),
|
|
||||||
ClientLabel: "OpenChamber Native",
|
|
||||||
ClientKind: "mobile",
|
|
||||||
DevicePlatform: "android",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.failConnect(conn, false, friendlyError(err))
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if res.ClientToken == "" {
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.failConnect(conn, false, "登录成功但没有返回令牌")
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
client.SetToken(res.ClientToken)
|
|
||||||
if err := a.store.SaveToken(conn.ID, res.ClientToken); err != nil {
|
|
||||||
log.Printf("appui: save token: %v", err)
|
|
||||||
}
|
|
||||||
a.post(func() {
|
|
||||||
a.busy = false
|
|
||||||
a.connected(client, conn, silent)
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// verifyConnection checks the device token is accepted.
|
|
||||||
func (a *App) verifyConnection(client *ocapi.Client) error {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
st, err := client.SessionStatus(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if !st.Authenticated {
|
|
||||||
return fmt.Errorf("已保存的凭据已失效,请重新登录")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// connected switches to the sessions list and starts the event stream.
|
|
||||||
func (a *App) connected(client *ocapi.Client, conn storage.Connection, silent bool) {
|
|
||||||
a.client = client
|
|
||||||
a.conn = conn
|
|
||||||
a.phase = "connected"
|
|
||||||
conns := a.store.Connections()
|
|
||||||
found := false
|
|
||||||
for i := range conns {
|
|
||||||
if conns[i].ID == conn.ID {
|
|
||||||
conns[i].LastUsedAt = time.Now().UnixMilli()
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
conn.LastUsedAt = time.Now().UnixMilli()
|
|
||||||
conns = append([]storage.Connection{conn}, conns...)
|
|
||||||
}
|
|
||||||
a.store.SaveConnections(conns)
|
|
||||||
a.startStream()
|
|
||||||
a.loadSessions()
|
|
||||||
a.loadActive()
|
|
||||||
a.loadPerms()
|
|
||||||
a.loadModels()
|
|
||||||
}
|
|
||||||
|
|
||||||
// failConnect surfaces a connect error: the connect form when not silent.
|
|
||||||
func (a *App) failConnect(conn storage.Connection, silent bool, msg string) {
|
|
||||||
a.client = nil
|
|
||||||
a.conn = storage.Connection{}
|
|
||||||
a.phase = ""
|
|
||||||
if silent {
|
|
||||||
a.errorText = fmt.Sprintf("无法连接 %s:%s", conn.Label, msg)
|
|
||||||
} else {
|
|
||||||
a.promptPassword(conn)
|
|
||||||
a.formError = msg
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// promptPassword shows the connect form for conn with its password field.
|
|
||||||
func (a *App) promptPassword(conn storage.Connection) {
|
|
||||||
a.phase = "form"
|
|
||||||
a.formEditing = &conn
|
|
||||||
a.formTitle = "连接 " + conn.Label
|
|
||||||
a.formLabel = conn.Label
|
|
||||||
a.formURL = conn.URL
|
|
||||||
a.formProxy = conn.Proxy
|
|
||||||
a.formInsecure = conn.Insecure
|
|
||||||
a.formFinger = conn.Fingerprint
|
|
||||||
a.formPassword = ""
|
|
||||||
a.formError = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// disconnect drops the connection and returns to the server list.
|
|
||||||
func (a *App) disconnect() {
|
|
||||||
a.stopStream()
|
|
||||||
a.client = nil
|
|
||||||
a.conn = storage.Connection{}
|
|
||||||
a.phase = ""
|
|
||||||
a.sessions = nil
|
|
||||||
a.errorText = ""
|
|
||||||
if a.chat != nil {
|
|
||||||
a.closeChat()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- sessions
|
|
||||||
|
|
||||||
func (a *App) loadSessions() {
|
|
||||||
if a.client == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.sessionsLoad = true
|
|
||||||
go func() {
|
|
||||||
page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{
|
|
||||||
Limit: 50,
|
|
||||||
Order: "desc",
|
|
||||||
})
|
|
||||||
a.post(func() {
|
|
||||||
a.sessionsLoad = false
|
|
||||||
if err != nil {
|
|
||||||
a.errorText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.sessions = page.Data
|
|
||||||
a.sessionsCursor = page.Cursor.Next
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) searchSessions(q string) {
|
|
||||||
if a.client == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.sessionsLoad = true
|
|
||||||
dir := ""
|
|
||||||
if len(a.sessions) > 0 && a.sessions[0].Location != nil {
|
|
||||||
dir = a.sessions[0].Location.Directory
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
page, err := a.client.ListSessions(context.Background(), ocapi.ListSessionsOptions{
|
|
||||||
Limit: 50, Order: "desc", Search: q, Directory: dir,
|
|
||||||
})
|
|
||||||
a.post(func() {
|
|
||||||
a.sessionsLoad = false
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.sessions = page.Data
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) loadActive() {
|
|
||||||
go func() {
|
|
||||||
m, err := a.client.ActiveSessions(context.Background())
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next := map[string]bool{}
|
|
||||||
for id := range m {
|
|
||||||
next[id] = true
|
|
||||||
}
|
|
||||||
a.active = next
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) loadPerms() {
|
|
||||||
go func() {
|
|
||||||
list, err := a.client.PendingPermissions(context.Background(), a.dir())
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.perms = list
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) loadModels() {
|
|
||||||
go func() {
|
|
||||||
models, err := a.client.Models(context.Background(), a.dir())
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
names := map[string]string{}
|
|
||||||
for _, m := range models {
|
|
||||||
name := m.Name
|
|
||||||
if name == "" {
|
|
||||||
name = m.ID
|
|
||||||
}
|
|
||||||
names[m.ProviderID+"/"+m.ID] = name
|
|
||||||
names[m.ID] = name
|
|
||||||
}
|
|
||||||
a.modelNames = names
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) dir() string {
|
|
||||||
if len(a.sessions) > 0 && a.sessions[0].Location != nil {
|
|
||||||
return a.sessions[0].Location.Directory
|
|
||||||
}
|
|
||||||
if a.chat != nil {
|
|
||||||
return a.chat.dir
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) modelName(m *ocapi.ModelRef) string {
|
|
||||||
if m == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if name := a.modelNames[m.ProviderID+"/"+m.ID]; name != "" {
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
if name := a.modelNames[m.ID]; name != "" {
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
return m.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
func friendlyError(err error) string {
|
|
||||||
if err == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
msg := err.Error()
|
|
||||||
msg = strings.TrimSpace(msg)
|
|
||||||
if msg == "" {
|
|
||||||
return "请求失败"
|
|
||||||
}
|
|
||||||
if len(msg) > 300 {
|
|
||||||
msg = msg[:300] + "…"
|
|
||||||
}
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/storage"
|
|
||||||
)
|
|
||||||
|
|
||||||
// memStore is a Store that keeps its values in memory, for tests.
|
|
||||||
type memStore struct {
|
|
||||||
conns []storage.Connection
|
|
||||||
installID string
|
|
||||||
tokens map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memStore) Connections() []storage.Connection { return m.conns }
|
|
||||||
func (m *memStore) SaveConnections(c []storage.Connection) { m.conns = c }
|
|
||||||
func (m *memStore) InstallID() string {
|
|
||||||
if m.installID == "" {
|
|
||||||
m.installID = "test-install"
|
|
||||||
}
|
|
||||||
return m.installID
|
|
||||||
}
|
|
||||||
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
|
|
||||||
if t, ok := m.tokens[c.ID]; ok {
|
|
||||||
return t, true, nil
|
|
||||||
}
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
func (m *memStore) SaveToken(id, token string) error {
|
|
||||||
if m.tokens == nil {
|
|
||||||
m.tokens = map[string]string{}
|
|
||||||
}
|
|
||||||
m.tokens[id] = token
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (m *memStore) ClearToken(c storage.Connection) error {
|
|
||||||
delete(m.tokens, c.ID)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestServersViewRenders mounts the disconnected first screen.
|
|
||||||
func TestServersViewRenders(t *testing.T) {
|
|
||||||
a := New(&memStore{})
|
|
||||||
tt := ui.NewTester(a.view, 400, 800)
|
|
||||||
if !tt.HasText("OpenChamber") {
|
|
||||||
t.Fatalf("servers view missing title: %q", tt.Texts())
|
|
||||||
}
|
|
||||||
if !tt.HasText("添加服务器") {
|
|
||||||
t.Fatalf("servers view missing add button: %q", tt.Texts())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestServersViewListsSaved mounts with one saved server.
|
|
||||||
func TestServersViewListsSaved(t *testing.T) {
|
|
||||||
a := New(&memStore{conns: []storage.Connection{
|
|
||||||
{ID: "s1", Label: "Home", URL: "http://10.0.0.2:3000"},
|
|
||||||
}})
|
|
||||||
tt := ui.NewTester(a.view, 400, 800)
|
|
||||||
if !tt.HasText("Home") || !tt.HasText("http://10.0.0.2:3000") {
|
|
||||||
t.Fatalf("saved server not shown: %q", tt.Texts())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
|
||||||
"mime"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
)
|
|
||||||
|
|
||||||
// keepImage copies a picked image into the app's data directory so the sent
|
|
||||||
// message can show it inline after a reload clears the picker's copy.
|
|
||||||
func keepImage(source, name string) string {
|
|
||||||
dir, err := mygo.App.Path(mygo.PathUserData)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
dir = filepath.Join(dir, "attachments")
|
|
||||||
_ = os.MkdirAll(dir, 0o700)
|
|
||||||
dst := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), sanitizeName(name)))
|
|
||||||
if err := copyFile(source, dst); err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return dst
|
|
||||||
}
|
|
||||||
|
|
||||||
func sanitizeName(name string) string {
|
|
||||||
clean := strings.Map(func(r rune) rune {
|
|
||||||
switch r {
|
|
||||||
case '/', '\\', ':', '*', '?', '"', '<', '>', '|':
|
|
||||||
return '_'
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}, name)
|
|
||||||
if clean == "" {
|
|
||||||
return "image"
|
|
||||||
}
|
|
||||||
return clean
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyFile(src, dst string) error {
|
|
||||||
data, err := os.ReadFile(src)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return os.WriteFile(dst, data, 0o600)
|
|
||||||
}
|
|
||||||
|
|
||||||
func mimeByExt(path string) string {
|
|
||||||
if m := mime.TypeByExtension(filepath.Ext(path)); m != "" {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
return "application/octet-stream"
|
|
||||||
}
|
|
||||||
|
|
||||||
func base64URL(data []byte) string {
|
|
||||||
return base64.StdEncoding.EncodeToString(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func humanSize(bytes int64) string {
|
|
||||||
switch {
|
|
||||||
case bytes >= 1<<20:
|
|
||||||
return fmt.Sprintf("%.1fMB", float64(bytes)/(1<<20))
|
|
||||||
case bytes >= 1<<10:
|
|
||||||
return fmt.Sprintf("%.0fKB", float64(bytes)/(1<<10))
|
|
||||||
default:
|
|
||||||
return fmt.Sprintf("%dB", bytes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,810 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/markdown"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// chat is one open session: its messages and its composer.
|
|
||||||
type chat struct {
|
|
||||||
a *App
|
|
||||||
id string
|
|
||||||
dir string
|
|
||||||
|
|
||||||
msgs []ocapi.Message
|
|
||||||
byID map[string]ocapi.Message
|
|
||||||
running bool
|
|
||||||
loading bool
|
|
||||||
draft string
|
|
||||||
expanded map[string]bool
|
|
||||||
errText string
|
|
||||||
|
|
||||||
olderCursor string
|
|
||||||
hasMore bool
|
|
||||||
|
|
||||||
textSlots map[string]map[int]int
|
|
||||||
reasoningSlots map[string]map[int]int
|
|
||||||
|
|
||||||
modelLimits map[string]modelLimit
|
|
||||||
imagePaths map[string][]string
|
|
||||||
|
|
||||||
// Composer attachments (data URLs plus local copies for previews).
|
|
||||||
attachments []attachment
|
|
||||||
attachBusy bool
|
|
||||||
|
|
||||||
// Sheets.
|
|
||||||
footerOpen bool
|
|
||||||
footerID string
|
|
||||||
userOpen bool
|
|
||||||
userID string
|
|
||||||
usageOpen bool
|
|
||||||
pickerOpen bool
|
|
||||||
pickerKind string
|
|
||||||
pickerFilter string
|
|
||||||
pickerItems []pickerItem
|
|
||||||
previewOpen bool
|
|
||||||
previewLoading bool
|
|
||||||
previewPath string
|
|
||||||
previewTitle string
|
|
||||||
previewCache map[string]string
|
|
||||||
previewSeq int
|
|
||||||
attachOpen bool
|
|
||||||
confirmRevert bool
|
|
||||||
revertID string
|
|
||||||
|
|
||||||
listState ui.ListState
|
|
||||||
mdOptions markdown.Options
|
|
||||||
|
|
||||||
loadingOnce bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type pickerItem struct {
|
|
||||||
Key string
|
|
||||||
Title string
|
|
||||||
Subtitle string
|
|
||||||
Model *ocapi.ModelRef
|
|
||||||
Agent string
|
|
||||||
}
|
|
||||||
|
|
||||||
// attachment is one file riding with the next prompt.
|
|
||||||
type attachment struct {
|
|
||||||
Name string
|
|
||||||
MIME string
|
|
||||||
DataURL string
|
|
||||||
Size int64
|
|
||||||
LocalPath string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) openChat(s ocapi.Session) {
|
|
||||||
dir := ""
|
|
||||||
if s.Location != nil {
|
|
||||||
dir = s.Location.Directory
|
|
||||||
}
|
|
||||||
ch := &chat{
|
|
||||||
a: a,
|
|
||||||
id: s.ID,
|
|
||||||
dir: dir,
|
|
||||||
byID: map[string]ocapi.Message{},
|
|
||||||
expanded: map[string]bool{},
|
|
||||||
textSlots: map[string]map[int]int{},
|
|
||||||
reasoningSlots: map[string]map[int]int{},
|
|
||||||
modelLimits: map[string]modelLimit{},
|
|
||||||
imagePaths: map[string][]string{},
|
|
||||||
previewCache: map[string]string{},
|
|
||||||
running: a.active[s.ID],
|
|
||||||
}
|
|
||||||
ch.mdOptions = markdown.Options{}
|
|
||||||
a.chat = ch
|
|
||||||
a.modelNames = map[string]string{}
|
|
||||||
a.loadModels()
|
|
||||||
a.loadModelLimits()
|
|
||||||
a.loadPerms()
|
|
||||||
ch.load()
|
|
||||||
a.chatWin = mygo.NewWindow(mygo.WindowOptions{
|
|
||||||
Title: s.Title,
|
|
||||||
Hidden: true,
|
|
||||||
Content: ui.View(a.chatView),
|
|
||||||
})
|
|
||||||
a.win.Push(a.chatWin)
|
|
||||||
a.setChatBar()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) closeChat() {
|
|
||||||
if a.chatWin != nil {
|
|
||||||
a.chatWin.Pop()
|
|
||||||
}
|
|
||||||
a.chat = nil
|
|
||||||
a.chatWin = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// setChatBar sets the pushed chat window's system bar buttons.
|
|
||||||
func (a *App) setChatBar() {
|
|
||||||
if a.chatWin == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mygo.SetBarItems(a.chatWin,
|
|
||||||
mygo.BarItem{Title: "模型与智能体", Icon: barIcon("robot"),
|
|
||||||
OnClick: func() { a.chat.openPicker("model") }},
|
|
||||||
mygo.BarItem{Title: "更多操作", Icon: barIcon("more"),
|
|
||||||
OnClick: func() { a.chat.openFooter() }},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// chatView is the chat window's interface.
|
|
||||||
func (a *App) chatView(c *ui.Context) {
|
|
||||||
ch := a.chat
|
|
||||||
if ch == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t := c.Theme()
|
|
||||||
ui.Column(c).Fill().Background(t.Background).Children(func() {
|
|
||||||
if ch.errText != "" {
|
|
||||||
ui.Row(c).FillWidth().Gap(8).Padding(4, 12).AlignItems(ui.Center).Children(func() {
|
|
||||||
ui.Text(c, ch.errText).FontSize(13).TextColor(t.Danger).Grow(1)
|
|
||||||
if ui.Button(c, "重试").Clicked() {
|
|
||||||
ch.errText = ""
|
|
||||||
ch.load()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if ch.loading && len(ch.msgs) == 0 {
|
|
||||||
ui.Column(c).Fill().Center().Children(func() { ui.Spinner(c) })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.messageList(c)
|
|
||||||
ch.permissionSection(c)
|
|
||||||
ch.composer(c)
|
|
||||||
})
|
|
||||||
ch.sheets(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// rows derives the message rows, like the Asuka version: one per user
|
|
||||||
// message, one per assistant part, a footer at a finished turn's end.
|
|
||||||
type chatRow struct {
|
|
||||||
Key string
|
|
||||||
Kind string // user | thinking | text | reasoning | tool | shell | footer | useractions
|
|
||||||
MsgID string
|
|
||||||
Part int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) rows() []chatRow {
|
|
||||||
var out []chatRow
|
|
||||||
for msgIdx, m := range ch.msgs {
|
|
||||||
switch m.Type {
|
|
||||||
case "user":
|
|
||||||
out = append(out, chatRow{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
|
|
||||||
out = append(out, chatRow{Key: "ua/" + m.ID, Kind: "useractions", MsgID: m.ID})
|
|
||||||
case "assistant":
|
|
||||||
if len(m.Content) == 0 && m.Time.Completed == 0 {
|
|
||||||
out = append(out, chatRow{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for i, p := range m.Content {
|
|
||||||
kind := p.Type
|
|
||||||
switch kind {
|
|
||||||
case "text", "reasoning", "tool":
|
|
||||||
default:
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, chatRow{
|
|
||||||
Key: fmt.Sprintf("a/%s/%s/%d", m.ID, kind, i),
|
|
||||||
Kind: kind,
|
|
||||||
MsgID: m.ID,
|
|
||||||
Part: i,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if m.Time.Completed > 0 && turnEndsAt(ch.msgs, msgIdx) {
|
|
||||||
out = append(out, chatRow{Key: "f/" + m.ID, Kind: "footer", MsgID: m.ID})
|
|
||||||
}
|
|
||||||
case "shell":
|
|
||||||
out = append(out, chatRow{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
|
|
||||||
case "synthetic":
|
|
||||||
out = append(out, chatRow{Key: "sy/" + m.ID, Kind: "note", MsgID: m.ID})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// turnEndsAt reports whether the assistant message at i ends its turn.
|
|
||||||
func turnEndsAt(msgs []ocapi.Message, i int) bool {
|
|
||||||
for j := i + 1; j < len(msgs); j++ {
|
|
||||||
switch msgs[j].Type {
|
|
||||||
case "assistant":
|
|
||||||
return false
|
|
||||||
case "user", "synthetic":
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) messageList(c *ui.Context) {
|
|
||||||
rows := ch.rows()
|
|
||||||
ch.listState.FollowEnd = true
|
|
||||||
list := ui.List(c, &ch.listState, len(rows))
|
|
||||||
list.ItemKey(func(i int) any { return rows[i].Key })
|
|
||||||
list.Rows(func(r ui.ListRow) {
|
|
||||||
row := rows[r.Index]
|
|
||||||
switch row.Kind {
|
|
||||||
case "user":
|
|
||||||
ch.userRow(c, row.MsgID)
|
|
||||||
case "useractions":
|
|
||||||
ch.userActionsRow(c, row.MsgID)
|
|
||||||
case "thinking":
|
|
||||||
ui.Text(c, "正在思考…").TextColor(c.Theme().TextMuted).FontSize(13).Padding(6, 16)
|
|
||||||
case "text":
|
|
||||||
ui.Row(c).FillWidth().PaddingX(16).Children(func() {
|
|
||||||
markdown.View(c, ch.partText(row.MsgID, row.Part), &ch.mdOptions)
|
|
||||||
})
|
|
||||||
case "reasoning":
|
|
||||||
ch.reasoningRow(c, row.MsgID, row.Part)
|
|
||||||
case "tool":
|
|
||||||
ch.toolRow(c, row.MsgID, row.Part)
|
|
||||||
case "footer":
|
|
||||||
ch.footerRow(c, row.MsgID)
|
|
||||||
case "shell":
|
|
||||||
ui.Text(c, ch.shellText(row.MsgID)).TextColor(c.Theme().TextMuted).FontSize(13).Padding(4, 16)
|
|
||||||
case "note":
|
|
||||||
ui.Text(c, ch.textOf(row.MsgID)).TextColor(c.Theme().TextMuted).FontSize(13).Padding(4, 16)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) userRow(c *ui.Context, id string) {
|
|
||||||
t := c.Theme()
|
|
||||||
m := ch.byID[id]
|
|
||||||
ui.Row(c).FillWidth().Padding(4, 12).Justify(ui.End).Children(func() {
|
|
||||||
ui.Column(c).MaxWidth(300).Gap(4).Padding(8, 12).Background(t.Accent).Radius(16).Children(func() {
|
|
||||||
ui.Text(c, m.Text).TextColor(t.AccentText)
|
|
||||||
for _, p := range ch.imagePaths[id] {
|
|
||||||
bmp := loadImageFile(p)
|
|
||||||
if bmp != nil {
|
|
||||||
ui.Image(c, bmp).Size(200, 150).Radius(10).Clip()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(m.Files) > 0 {
|
|
||||||
ui.Text(c, ch.filesText(id)).TextColor(t.AccentText).FontSize(13)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) userActionsRow(c *ui.Context, id string) {
|
|
||||||
t := c.Theme()
|
|
||||||
m := ch.byID[id]
|
|
||||||
stamp := ""
|
|
||||||
if m.Time.Created > 0 {
|
|
||||||
stamp = time.UnixMilli(m.Time.Created).Format("15:04")
|
|
||||||
}
|
|
||||||
ui.Row(c).FillWidth().Padding(2, 12).Gap(10).Justify(ui.End).AlignItems(ui.Center).Children(func() {
|
|
||||||
ui.Text(c, stamp).FontSize(12).TextColor(t.TextMuted)
|
|
||||||
if ui.Button(c, "复制").Clicked() {
|
|
||||||
ch.copyText(m.Text)
|
|
||||||
}
|
|
||||||
if ui.Button(c, "⋯").Label("消息操作").Width(40).Clicked() {
|
|
||||||
ch.userOpen = true
|
|
||||||
ch.userID = id
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) reasoningRow(c *ui.Context, id string, part int) {
|
|
||||||
t := c.Theme()
|
|
||||||
key := fmt.Sprintf("reasoning/%s/%d", id, part)
|
|
||||||
open := ch.expanded[key]
|
|
||||||
ui.Row(c).FillWidth().Padding(4, 16).Gap(6).Children(func() {
|
|
||||||
ui.Text(c, "已思考").TextColor(t.TextMuted).FontSize(13)
|
|
||||||
if ui.Button(c, "展开").Clicked() {
|
|
||||||
ch.expanded[key] = true
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if open {
|
|
||||||
ui.Text(c, ch.partText(id, part)).TextColor(t.TextMuted).FontSize(13).Padding(4, 16, 4, 20)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) toolRow(c *ui.Context, id string, part int) {
|
|
||||||
t := c.Theme()
|
|
||||||
key := fmt.Sprintf("tool/%s/%d", id, part)
|
|
||||||
open := ch.expanded[key]
|
|
||||||
p := ch.part(id, part)
|
|
||||||
status := ""
|
|
||||||
if p.State != nil {
|
|
||||||
status = p.State.Status
|
|
||||||
}
|
|
||||||
icon := "●"
|
|
||||||
switch status {
|
|
||||||
case "running", "streaming":
|
|
||||||
icon = "◌"
|
|
||||||
case "completed":
|
|
||||||
icon = "✓"
|
|
||||||
case "error":
|
|
||||||
icon = "✕"
|
|
||||||
}
|
|
||||||
headline := fmt.Sprintf("%s %s", icon, strings.TrimSpace(p.Name))
|
|
||||||
ui.Column(c).FillWidth().Padding(4, 16).Gap(4).Children(func() {
|
|
||||||
row := ui.Row(c).FillWidth().Gap(6).AlignItems(ui.Center).Role(ui.RoleButton)
|
|
||||||
row.Children(func() {
|
|
||||||
ui.Text(c, headline).FontSize(13).TextColor(t.TextMuted).Grow(1).MaxLines(1)
|
|
||||||
if ui.Button(c, openLabel(open)).Clicked() {
|
|
||||||
ch.expanded[key] = !open
|
|
||||||
if !open {
|
|
||||||
ch.ensureToolLoaded(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if row.Clicked() {
|
|
||||||
ch.expanded[key] = !open
|
|
||||||
if !open {
|
|
||||||
ch.ensureToolLoaded(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, ref := range ch.toolImages(p) {
|
|
||||||
link := ui.Row(c).Gap(6).AlignItems(ui.Center).Role(ui.RoleButton).Label("预览 " + ref.Label)
|
|
||||||
link.Children(func() {
|
|
||||||
ui.Text(c, "🖼").FontSize(12)
|
|
||||||
ui.Text(c, ref.Label).FontSize(12).TextColor(t.Accent).MaxLines(1)
|
|
||||||
})
|
|
||||||
if link.Clicked() {
|
|
||||||
ch.previewImage(ref)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if open {
|
|
||||||
if p.State != nil {
|
|
||||||
if buf, err := json.MarshalIndent(p.State.Input, "", " "); err == nil {
|
|
||||||
ui.Text(c, string(buf)).FontSize(12).TextColor(t.TextMuted).Padding(8, 10).Background(t.Surface).Radius(8)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ui.Text(c, toolOutput(p)).FontSize(12).TextColor(t.TextMuted).Padding(8, 10).Background(t.Surface).Radius(8)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func openLabel(open bool) string {
|
|
||||||
if open {
|
|
||||||
return "收起"
|
|
||||||
}
|
|
||||||
return "展开"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) footerRow(c *ui.Context, id string) {
|
|
||||||
t := c.Theme()
|
|
||||||
m := ch.byID[id]
|
|
||||||
parts := []string{}
|
|
||||||
if m.Model != nil {
|
|
||||||
parts = append(parts, ch.a.modelName(m.Model))
|
|
||||||
}
|
|
||||||
if m.Agent != "" {
|
|
||||||
parts = append(parts, m.Agent)
|
|
||||||
}
|
|
||||||
if m.Time.Completed > 0 {
|
|
||||||
parts = append(parts, ch.turnDuration(id))
|
|
||||||
}
|
|
||||||
ui.Row(c).FillWidth().Padding(4, 16).Gap(8).AlignItems(ui.Center).Children(func() {
|
|
||||||
ui.Text(c, strings.Join(parts, " · ")).FontSize(13).TextColor(t.TextMuted).Grow(1)
|
|
||||||
if ui.Button(c, "⋯").Label("更多操作").Width(40).Clicked() {
|
|
||||||
ch.footerOpen = true
|
|
||||||
ch.footerID = id
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) turnDuration(id string) string {
|
|
||||||
idx := -1
|
|
||||||
for i := range ch.msgs {
|
|
||||||
if ch.msgs[i].ID == id {
|
|
||||||
idx = i
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if idx < 0 || ch.msgs[idx].Time.Completed <= 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
start := int64(0)
|
|
||||||
for i := idx - 1; i >= 0; i-- {
|
|
||||||
if ch.msgs[i].Type == "user" {
|
|
||||||
start = ch.msgs[i].Time.Created
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if start <= 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
secs := (ch.msgs[idx].Time.Completed - start) / 1000
|
|
||||||
if secs < 60 {
|
|
||||||
return fmt.Sprintf("%d 秒", secs)
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%d:%02d", secs/60, secs%60)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) composer(c *ui.Context) {
|
|
||||||
ui.Column(c).FillWidth().Gap(6).Padding(8, 8, 8, 0).Children(func() {
|
|
||||||
ch.attachmentRow(c)
|
|
||||||
ui.Row(c).FillWidth().Gap(8).AlignItems(ui.End).Children(func() {
|
|
||||||
if ch.attachBusy {
|
|
||||||
ui.Spinner(c)
|
|
||||||
} else if ui.Button(c, "📎").Label("添加附件").Width(44).Clicked() {
|
|
||||||
ch.attachOpen = true
|
|
||||||
}
|
|
||||||
ui.TextArea(c, &ch.draft).Placeholder("发消息…").Grow(1).MaxHeight(140)
|
|
||||||
ch.usageButton(c)
|
|
||||||
if ch.running {
|
|
||||||
if ui.Button(c, "停止").Clicked() {
|
|
||||||
ch.stop()
|
|
||||||
}
|
|
||||||
} else if ui.PrimaryButton(c, "发送").Clicked() {
|
|
||||||
ch.send()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) attachmentRow(c *ui.Context) {
|
|
||||||
if len(ch.attachments) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ui.Row(c).FillWidth().Gap(6).PaddingX(4).Children(func() {
|
|
||||||
for i := range ch.attachments {
|
|
||||||
att := &ch.attachments[i]
|
|
||||||
chip := ui.Row(c).Gap(4).AlignItems(ui.Center).Padding(6, 10).Background(c.Theme().Surface).Radius(12)
|
|
||||||
chip.Children(func() {
|
|
||||||
ui.Text(c, att.Name).FontSize(13).MaxLines(1)
|
|
||||||
if ui.Button(c, "×").Width(24).Clicked() {
|
|
||||||
ch.attachments = append(ch.attachments[:i], ch.attachments[i+1:]...)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) permissionSection(c *ui.Context) {
|
|
||||||
t := c.Theme()
|
|
||||||
for i := range ch.a.perms {
|
|
||||||
p := &ch.a.perms[i]
|
|
||||||
if p.SessionID != "" && p.SessionID != ch.id {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
card := ui.Column(c).FillWidth().Padding(10, 12).Background(t.Surface).Radius(12).Gap(6)
|
|
||||||
card.Children(func() {
|
|
||||||
ui.Text(c, "请求权限: "+p.Action).FontSize(14).FontWeight(600)
|
|
||||||
ui.Text(c, strings.Join(p.Resources, "、")).FontSize(13).TextColor(t.TextMuted)
|
|
||||||
ui.Row(c).FillWidth().Gap(8).Children(func() {
|
|
||||||
if ui.Button(c, "允许一次").Clicked() {
|
|
||||||
ch.replyPermission(p.ID, "allowOnce", "")
|
|
||||||
}
|
|
||||||
if ui.Button(c, "总是允许").Clicked() {
|
|
||||||
ch.replyPermission(p.ID, "allow", "")
|
|
||||||
}
|
|
||||||
if ui.Button(c, "拒绝").Clicked() {
|
|
||||||
ch.replyPermission(p.ID, "deny", "")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) replyPermission(id, decision, msg string) {
|
|
||||||
var d ocapi.PermissionDecision
|
|
||||||
switch decision {
|
|
||||||
case "allowOnce":
|
|
||||||
d = ocapi.PermissionOnce
|
|
||||||
case "allow":
|
|
||||||
d = ocapi.PermissionAlways
|
|
||||||
default:
|
|
||||||
d = ocapi.PermissionReject
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
err := ch.a.client.ReplyPermission(ctx, ch.id, id, d, msg)
|
|
||||||
ch.a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------ data access
|
|
||||||
|
|
||||||
func (ch *chat) textOf(id string) string { return ch.byID[id].Text }
|
|
||||||
|
|
||||||
func (ch *chat) part(id string, index int) ocapi.ContentPart {
|
|
||||||
m := ch.byID[id]
|
|
||||||
if index < 0 || index >= len(m.Content) {
|
|
||||||
return ocapi.ContentPart{}
|
|
||||||
}
|
|
||||||
return m.Content[index]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) partText(id string, index int) string {
|
|
||||||
m := ch.byID[id]
|
|
||||||
if index < 0 || index >= len(m.Content) {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return m.Content[index].Text
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) shellText(id string) string {
|
|
||||||
m := ch.byID[id]
|
|
||||||
if m.Exit != nil && *m.Exit == 0 {
|
|
||||||
return "✓ " + m.Command
|
|
||||||
}
|
|
||||||
return "$ " + m.Command
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) filesText(id string) string {
|
|
||||||
m := ch.byID[id]
|
|
||||||
names := make([]string, 0, len(m.Files))
|
|
||||||
for _, f := range m.Files {
|
|
||||||
if f.Name != "" {
|
|
||||||
names = append(names, "📎 "+f.Name)
|
|
||||||
} else {
|
|
||||||
names = append(names, "📎 附件")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return strings.Join(names, "\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) copyText(s string) {
|
|
||||||
if s == "" {
|
|
||||||
ch.a.post(func() { ch.errText = "没有可复制的文字" })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mygo.Clipboard.WriteText(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------ send / stop
|
|
||||||
|
|
||||||
func (ch *chat) send() {
|
|
||||||
text := strings.TrimSpace(ch.draft)
|
|
||||||
if text == "" && len(ch.attachments) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id := newMessageID()
|
|
||||||
files := ch.filesPayload()
|
|
||||||
msg := ocapi.Message{
|
|
||||||
ID: id,
|
|
||||||
Type: "user",
|
|
||||||
Text: text,
|
|
||||||
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
|
|
||||||
}
|
|
||||||
if len(ch.attachments) > 0 {
|
|
||||||
msg.Files = make([]ocapi.FileAttachment, len(ch.attachments))
|
|
||||||
for i, a := range ch.attachments {
|
|
||||||
msg.Files[i] = ocapi.FileAttachment{Name: a.Name, MIME: a.MIME}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ch.a.post(func() {
|
|
||||||
for _, a := range ch.attachments {
|
|
||||||
if a.LocalPath != "" {
|
|
||||||
ch.imagePaths[id] = append(ch.imagePaths[id], a.LocalPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ch.draft = ""
|
|
||||||
ch.attachments = nil
|
|
||||||
ch.addMessage(msg)
|
|
||||||
})
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
err := ch.a.client.Prompt(ctx, ch.id, ocapi.PromptOptions{
|
|
||||||
Directory: ch.dir,
|
|
||||||
MessageID: id,
|
|
||||||
Text: text,
|
|
||||||
Files: files,
|
|
||||||
})
|
|
||||||
ch.a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) filesPayload() []ocapi.PromptFile {
|
|
||||||
out := make([]ocapi.PromptFile, 0, len(ch.attachments))
|
|
||||||
for _, a := range ch.attachments {
|
|
||||||
out = append(out, ocapi.PromptFile{URI: a.DataURL, Name: a.Name})
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) stop() {
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
_, err := ch.a.client.Interrupt(ctx, ch.id, ch.dir)
|
|
||||||
ch.a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func newMessageID() string {
|
|
||||||
var b [8]byte
|
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
|
||||||
return "msg_" + hex.EncodeToString(b[:4])
|
|
||||||
}
|
|
||||||
return "msg_" + hex.EncodeToString(b[:])
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------- messages
|
|
||||||
|
|
||||||
func (ch *chat) load() {
|
|
||||||
ch.loading = true
|
|
||||||
ch.loadingOnce = false
|
|
||||||
go func() {
|
|
||||||
page, err := ch.a.client.ListMessages(context.Background(), ch.id, ocapi.ListMessagesOptions{
|
|
||||||
Limit: 30,
|
|
||||||
Order: "desc",
|
|
||||||
Directory: ch.dir,
|
|
||||||
PartShells: true,
|
|
||||||
})
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
ch.loading = false
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.setMessages(page.Data)
|
|
||||||
ch.olderCursor = page.Cursor.Previous
|
|
||||||
ch.hasMore = page.Cursor.Previous != ""
|
|
||||||
ch.listState.ScrollToEnd()
|
|
||||||
if len(ch.msgs) > 0 {
|
|
||||||
ch.reloadTail()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) reloadTail() {
|
|
||||||
if ch.loadingOnce {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.loadingOnce = true
|
|
||||||
go func() {
|
|
||||||
page, err := ch.a.client.ListMessages(context.Background(), ch.id, ocapi.ListMessagesOptions{
|
|
||||||
Limit: 30,
|
|
||||||
Order: "desc",
|
|
||||||
Directory: ch.dir,
|
|
||||||
PartShells: true,
|
|
||||||
})
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.setMessages(page.Data)
|
|
||||||
ch.listState.ScrollToEnd()
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) loadOlder() {
|
|
||||||
if !ch.hasMore || ch.loading {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.loading = true
|
|
||||||
cursor := ch.olderCursor
|
|
||||||
go func() {
|
|
||||||
page, err := ch.a.client.ListMessages(context.Background(), ch.id, ocapi.ListMessagesOptions{
|
|
||||||
Limit: 30,
|
|
||||||
Cursor: cursor,
|
|
||||||
Order: "desc",
|
|
||||||
Directory: ch.dir,
|
|
||||||
PartShells: true,
|
|
||||||
})
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
ch.loading = false
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.prepend(page.Data)
|
|
||||||
ch.olderCursor = page.Cursor.Previous
|
|
||||||
ch.hasMore = page.Cursor.Previous != ""
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) setMessages(list []ocapi.Message) {
|
|
||||||
index := map[string]ocapi.Message{}
|
|
||||||
for _, m := range list {
|
|
||||||
index[m.ID] = m
|
|
||||||
}
|
|
||||||
ch.byID = index
|
|
||||||
ch.msgs = list
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) addMessage(m ocapi.Message) {
|
|
||||||
ch.msgs = append(ch.msgs, m)
|
|
||||||
ch.sortMsgs()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) updateMessage(id string, fn func(*ocapi.Message)) {
|
|
||||||
for i := range ch.msgs {
|
|
||||||
if ch.msgs[i].ID == id {
|
|
||||||
fn(&ch.msgs[i])
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ch.reindex()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) reindex() {
|
|
||||||
index := make(map[string]ocapi.Message, len(ch.msgs))
|
|
||||||
for _, m := range ch.msgs {
|
|
||||||
index[m.ID] = m
|
|
||||||
}
|
|
||||||
ch.byID = index
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) prepend(list []ocapi.Message) {
|
|
||||||
seen := map[string]bool{}
|
|
||||||
for _, m := range ch.msgs {
|
|
||||||
seen[m.ID] = true
|
|
||||||
}
|
|
||||||
next := make([]ocapi.Message, 0, len(ch.msgs)+len(list))
|
|
||||||
for _, m := range list {
|
|
||||||
if !seen[m.ID] {
|
|
||||||
next = append(next, m)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
next = append(next, ch.msgs...)
|
|
||||||
ch.msgs = next
|
|
||||||
ch.sortMsgs()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) sortMsgs() {
|
|
||||||
sort.SliceStable(ch.msgs, func(i, j int) bool {
|
|
||||||
if ch.msgs[i].Time.Created == ch.msgs[j].Time.Created {
|
|
||||||
return ch.msgs[i].ID < ch.msgs[j].ID
|
|
||||||
}
|
|
||||||
return ch.msgs[i].Time.Created < ch.msgs[j].Time.Created
|
|
||||||
})
|
|
||||||
index := make(map[string]ocapi.Message, len(ch.msgs))
|
|
||||||
for _, m := range ch.msgs {
|
|
||||||
index[m.ID] = m
|
|
||||||
}
|
|
||||||
ch.byID = index
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) ensureToolLoaded(id string) {
|
|
||||||
m := ch.byID[id]
|
|
||||||
for i := range m.Content {
|
|
||||||
p := &m.Content[i]
|
|
||||||
if p.Type == "tool" && p.State != nil && p.State.Metadata != nil {
|
|
||||||
if _, ok := p.State.Metadata["openchamberContentShell"]; ok {
|
|
||||||
ch.fetchFull(id)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) fetchFull(id string) {
|
|
||||||
go func() {
|
|
||||||
msg, err := ch.a.client.GetMessage(context.Background(), ch.id, id, ch.dir)
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.updateMessage(id, func(m *ocapi.Message) { *m = msg })
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// turnEndsAt defined above. handleEvent lives in events_chat.go.
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"math"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/mobile"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// modelLimit is a model's context and output window.
|
|
||||||
type modelLimit struct {
|
|
||||||
Context int
|
|
||||||
Output int
|
|
||||||
}
|
|
||||||
|
|
||||||
// usageReading is the context window of the last assistant message that
|
|
||||||
// reported tokens.
|
|
||||||
type usageReading struct {
|
|
||||||
Used int
|
|
||||||
Limit int
|
|
||||||
Output int
|
|
||||||
Pct float64
|
|
||||||
Known bool
|
|
||||||
Cost float64
|
|
||||||
Model string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
|
|
||||||
var last *ocapi.Message
|
|
||||||
for i := len(msgs) - 1; i >= 0; i-- {
|
|
||||||
if msgs[i].Type == "assistant" && msgs[i].Tokens != nil {
|
|
||||||
last = &msgs[i]
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if last == nil {
|
|
||||||
return usageReading{}
|
|
||||||
}
|
|
||||||
model := last.Model
|
|
||||||
for i := len(msgs) - 1; i >= 0 && model == nil; i-- {
|
|
||||||
if msgs[i].Type == "assistant" && msgs[i].Model != nil {
|
|
||||||
model = msgs[i].Model
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if model == nil {
|
|
||||||
return usageReading{}
|
|
||||||
}
|
|
||||||
var r usageReading
|
|
||||||
t := last.Tokens
|
|
||||||
if t.Total > 0 {
|
|
||||||
r.Used = int(t.Total)
|
|
||||||
} else {
|
|
||||||
r.Used = int(t.Input + t.Output + t.Reasoning + t.Cache.Read + t.Cache.Write)
|
|
||||||
}
|
|
||||||
lim := ch.modelLimit(model)
|
|
||||||
r.Limit, r.Output = lim.Context, lim.Output
|
|
||||||
r.Model = ch.a.modelName(model)
|
|
||||||
for i := len(msgs) - 1; i >= 0; i-- {
|
|
||||||
if msgs[i].Type == "user" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if msgs[i].Type == "assistant" {
|
|
||||||
r.Cost += msgs[i].Cost
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if r.Limit <= 0 || r.Used <= 0 {
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
reserve := r.Output
|
|
||||||
if reserve > 32000 {
|
|
||||||
reserve = 32000
|
|
||||||
}
|
|
||||||
threshold := r.Limit - reserve
|
|
||||||
if threshold < 1 {
|
|
||||||
threshold = 1
|
|
||||||
}
|
|
||||||
r.Pct = math.Min(100, float64(r.Used)/float64(threshold)*100)
|
|
||||||
r.Known = true
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) modelLimit(m *ocapi.ModelRef) modelLimit {
|
|
||||||
if m == nil {
|
|
||||||
return modelLimit{}
|
|
||||||
}
|
|
||||||
if l, ok := ch.modelLimits[m.ProviderID+"/"+m.ID]; ok {
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
return ch.modelLimits[m.ID]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) loadModelLimits() {
|
|
||||||
go func() {
|
|
||||||
models, err := a.client.Models(context.Background(), a.dir())
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
limits := map[string]modelLimit{}
|
|
||||||
for _, m := range models {
|
|
||||||
lim := modelLimit{Context: m.Limit.Context, Output: m.Limit.Output}
|
|
||||||
limits[m.ProviderID+"/"+m.ID] = lim
|
|
||||||
limits[m.ID] = lim
|
|
||||||
}
|
|
||||||
if a.chat != nil {
|
|
||||||
a.chat.modelLimits = limits
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatTokens(n int) string {
|
|
||||||
switch {
|
|
||||||
case n >= 1_000_000:
|
|
||||||
return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
|
|
||||||
case n >= 1_000:
|
|
||||||
return fmt.Sprintf("%.1fK", float64(n)/1_000)
|
|
||||||
default:
|
|
||||||
return fmt.Sprintf("%d", n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatCost(v float64) string {
|
|
||||||
if v < 0.01 {
|
|
||||||
return fmt.Sprintf("$%.4f", v)
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("$%.2f", v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// usageButton is the composer's context ring and percentage.
|
|
||||||
func (ch *chat) usageButton(c *ui.Context) {
|
|
||||||
t := c.Theme()
|
|
||||||
r := ch.usageReading(ch.msgs)
|
|
||||||
if !r.Known {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
btn := ui.Row(c).Gap(4).AlignItems(ui.Center).Padding(4, 4).Role(ui.RoleButton).Label("上下文占用")
|
|
||||||
btn.Children(func() {
|
|
||||||
ui.Text(c, fmt.Sprintf("%.0f%%", r.Pct)).FontSize(13).TextColor(t.TextMuted)
|
|
||||||
})
|
|
||||||
if btn.Clicked() {
|
|
||||||
ch.usageOpen = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// usageSheet shows the context detail.
|
|
||||||
func (ch *chat) usageSheet(c *ui.Context) {
|
|
||||||
if !ch.usageOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t := c.Theme()
|
|
||||||
mobileSheet(c, &ch.usageOpen, 0.5, func() {
|
|
||||||
r := ch.usageReading(ch.msgs)
|
|
||||||
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
|
|
||||||
ui.Text(c, "上下文占用").FontSize(20).Bold()
|
|
||||||
usageRow(c, t, "模型", r.Model)
|
|
||||||
if r.Known {
|
|
||||||
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
|
|
||||||
usageRow(c, t, "上下文上限", formatTokens(r.Limit))
|
|
||||||
usageRow(c, t, "输出预留", formatTokens(r.Output))
|
|
||||||
usageRow(c, t, "占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)))
|
|
||||||
} else {
|
|
||||||
usageRow(c, t, "已用 tokens", formatTokens(r.Used))
|
|
||||||
usageRow(c, t, "上下文上限", "未知")
|
|
||||||
}
|
|
||||||
if r.Cost > 0 {
|
|
||||||
usageRow(c, t, "本轮费用", formatCost(r.Cost))
|
|
||||||
}
|
|
||||||
ui.Text(c, "输出预留按最多 32K tokens 计算,与官方客户端一致。").FontSize(12).TextColor(t.TextMuted)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func usageRow(c *ui.Context, t *ui.Theme, label, value string) ui.Element {
|
|
||||||
row := ui.Row(c).FillWidth().Gap(12).AlignItems(ui.Center)
|
|
||||||
row.Children(func() {
|
|
||||||
ui.Text(c, label).FontSize(14).TextColor(t.TextMuted).Grow(1)
|
|
||||||
ui.Text(c, value).FontSize(14)
|
|
||||||
})
|
|
||||||
return row
|
|
||||||
}
|
|
||||||
|
|
||||||
// mobileSheet shows a sheet of a detent.
|
|
||||||
func mobileSheet(c *ui.Context, open *bool, detent float32, content func()) {
|
|
||||||
mobile.Sheet(c, open, mobile.SheetOptions{Detents: []float32{detent}}, content)
|
|
||||||
}
|
|
||||||
@@ -1,269 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// eventTypes are the event kinds the list and chat read. Sending the
|
|
||||||
// filter keeps a phone's stream small; server.connected always arrives.
|
|
||||||
var eventTypes = []string{
|
|
||||||
"session.created",
|
|
||||||
"session.renamed",
|
|
||||||
"session.archived",
|
|
||||||
"session.unarchived",
|
|
||||||
"session.deleted",
|
|
||||||
"session.moved",
|
|
||||||
"session.model.selected",
|
|
||||||
"session.agent.selected",
|
|
||||||
"session.metadata.updated",
|
|
||||||
"session.execution.started",
|
|
||||||
"session.execution.succeeded",
|
|
||||||
"session.execution.failed",
|
|
||||||
"session.execution.interrupted",
|
|
||||||
"session.step.started",
|
|
||||||
"session.step.ended",
|
|
||||||
"session.step.failed",
|
|
||||||
"session.text.started",
|
|
||||||
"session.text.delta",
|
|
||||||
"session.text.ended",
|
|
||||||
"session.reasoning.started",
|
|
||||||
"session.reasoning.delta",
|
|
||||||
"session.reasoning.ended",
|
|
||||||
"session.tool.called",
|
|
||||||
"session.tool.success",
|
|
||||||
"session.tool.failed",
|
|
||||||
"permission.asked",
|
|
||||||
"permission.replied",
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionCreatedData struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
ProjectID string `json:"projectID"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Agent string `json:"agent"`
|
|
||||||
Model *ocapi.ModelRef `json:"model"`
|
|
||||||
Location *ocapi.Location `json:"location"`
|
|
||||||
Subpath string `json:"subpath"`
|
|
||||||
Metadata json.RawMessage `json:"metadata"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionRenamedData struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionRefData struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionModelData struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
Model *ocapi.ModelRef `json:"model"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionAgentData struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
Agent string `json:"agent"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type permissionData struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
Action string `json:"action"`
|
|
||||||
Resources []string `json:"resources"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// startStream subscribes to the server's event stream. Call it on the main
|
|
||||||
// thread; the stream runs on a goroutine and posts events back.
|
|
||||||
func (a *App) startStream() {
|
|
||||||
if a.client == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.stopStream()
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
a.streamCancel = cancel
|
|
||||||
wasDown := false
|
|
||||||
client := a.client
|
|
||||||
sub := ocapi.Subscription{
|
|
||||||
Types: eventTypes,
|
|
||||||
OnEvent: func(ev ocapi.Event) {
|
|
||||||
a.post(func() {
|
|
||||||
if a.client != client {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.applyEvent(ev)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
OnState: func(st ocapi.SubscriptionState, err error) {
|
|
||||||
switch st {
|
|
||||||
case ocapi.Disconnected:
|
|
||||||
wasDown = true
|
|
||||||
a.post(func() {
|
|
||||||
if a.client != client {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.errorText = "连接中断,正在重连…"
|
|
||||||
})
|
|
||||||
case ocapi.Subscribed:
|
|
||||||
if !wasDown {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
wasDown = false
|
|
||||||
a.post(func() {
|
|
||||||
if a.client != client {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.errorText = ""
|
|
||||||
a.loadSessions()
|
|
||||||
a.loadPerms()
|
|
||||||
if a.chat != nil {
|
|
||||||
a.chat.reloadTail()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
go client.Subscribe(ctx, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) stopStream() {
|
|
||||||
if a.streamCancel != nil {
|
|
||||||
a.streamCancel()
|
|
||||||
a.streamCancel = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// applyEvent folds one server event into the list and, when it belongs to
|
|
||||||
// the open chat, into the chat. Main thread.
|
|
||||||
func (a *App) applyEvent(ev ocapi.Event) {
|
|
||||||
if a.chat != nil {
|
|
||||||
var ref struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
}
|
|
||||||
if ev.UnmarshalData(&ref) == nil && ref.SessionID == a.chat.id {
|
|
||||||
a.chat.handleEvent(ev)
|
|
||||||
}
|
|
||||||
if a.chatWin != nil {
|
|
||||||
a.chatWin.Update(func() {})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
switch ev.Type {
|
|
||||||
case "session.created":
|
|
||||||
var d sessionCreatedData
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.SessionID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, s := range a.sessions {
|
|
||||||
if s.ID == d.SessionID {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sess := ocapi.Session{
|
|
||||||
ID: d.SessionID,
|
|
||||||
ProjectID: d.ProjectID,
|
|
||||||
Title: d.Title,
|
|
||||||
Agent: d.Agent,
|
|
||||||
Model: d.Model,
|
|
||||||
Location: d.Location,
|
|
||||||
Time: ocapi.SessionTime{Created: ev.Created, Updated: ev.Created},
|
|
||||||
}
|
|
||||||
a.sessions = append([]ocapi.Session{sess}, a.sessions...)
|
|
||||||
|
|
||||||
case "session.renamed":
|
|
||||||
var d sessionRenamedData
|
|
||||||
if ev.UnmarshalData(&d) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title })
|
|
||||||
|
|
||||||
case "session.model.selected":
|
|
||||||
var d sessionModelData
|
|
||||||
if ev.UnmarshalData(&d) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model })
|
|
||||||
|
|
||||||
case "session.agent.selected":
|
|
||||||
var d sessionAgentData
|
|
||||||
if ev.UnmarshalData(&d) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent })
|
|
||||||
|
|
||||||
case "session.archived", "session.deleted":
|
|
||||||
var d sessionRefData
|
|
||||||
if ev.UnmarshalData(&d) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.removeSession(d.SessionID)
|
|
||||||
|
|
||||||
case "session.unarchived", "session.moved":
|
|
||||||
// The event carries no full record; a list read is the truth.
|
|
||||||
a.loadSessions()
|
|
||||||
|
|
||||||
case "session.execution.started":
|
|
||||||
var d sessionRefData
|
|
||||||
if ev.UnmarshalData(&d) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.active[d.SessionID] = true
|
|
||||||
|
|
||||||
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
|
|
||||||
var d sessionRefData
|
|
||||||
if ev.UnmarshalData(&d) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.active[d.SessionID] = false
|
|
||||||
|
|
||||||
case "permission.asked":
|
|
||||||
var d permissionData
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.ID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, p := range a.perms {
|
|
||||||
if p.ID == d.ID {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a.perms = append(a.perms, ocapi.PermissionRequest{
|
|
||||||
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
|
|
||||||
})
|
|
||||||
|
|
||||||
case "permission.replied":
|
|
||||||
var d struct {
|
|
||||||
RequestID string `json:"requestID"`
|
|
||||||
}
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.RequestID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next := a.perms[:0]
|
|
||||||
for _, p := range a.perms {
|
|
||||||
if p.ID != d.RequestID {
|
|
||||||
next = append(next, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a.perms = next
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) patchSession(id string, patch func(*ocapi.Session)) {
|
|
||||||
for i := range a.sessions {
|
|
||||||
if a.sessions[i].ID == id {
|
|
||||||
patch(&a.sessions[i])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) removeSession(id string) {
|
|
||||||
next := a.sessions[:0]
|
|
||||||
for _, s := range a.sessions {
|
|
||||||
if s.ID != id {
|
|
||||||
next = append(next, s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a.sessions = next
|
|
||||||
}
|
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// handleEvent folds a session's own events into its messages. Main thread.
|
|
||||||
func (ch *chat) handleEvent(ev ocapi.Event) {
|
|
||||||
switch ev.Type {
|
|
||||||
case "session.execution.started":
|
|
||||||
ch.running = true
|
|
||||||
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
|
|
||||||
ch.running = false
|
|
||||||
case "session.step.started":
|
|
||||||
var d struct {
|
|
||||||
AssistantMessageID string `json:"assistantMessageID"`
|
|
||||||
}
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
|
||||||
ch.running = true
|
|
||||||
case "session.step.ended", "session.step.failed":
|
|
||||||
ch.applyStepEnd(ev)
|
|
||||||
case "session.text.started", "session.text.delta", "session.text.ended":
|
|
||||||
ch.applyDelta(ev, "text", ch.textSlots)
|
|
||||||
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
|
|
||||||
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
|
|
||||||
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
|
|
||||||
"session.tool.success", "session.tool.failed", "session.tool.progress":
|
|
||||||
ch.applyToolEvent(ev)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type deltaData struct {
|
|
||||||
AssistantMessageID string `json:"assistantMessageID"`
|
|
||||||
Ordinal int `json:"ordinal"`
|
|
||||||
Delta string `json:"delta"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type toolEventData struct {
|
|
||||||
AssistantMessageID string `json:"assistantMessageID"`
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Input map[string]any `json:"input"`
|
|
||||||
Executed bool `json:"executed"`
|
|
||||||
Content []ocapi.ContentPart `json:"content"`
|
|
||||||
Metadata map[string]any `json:"metadata"`
|
|
||||||
Error json.RawMessage `json:"error"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// applyToolEvent folds a tool call's events into its part.
|
|
||||||
func (ch *chat) applyToolEvent(ev ocapi.Event) {
|
|
||||||
var d toolEventData
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" || d.ID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
|
||||||
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
|
|
||||||
part := ch.findToolPart(m, d.ID)
|
|
||||||
if part == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch ev.Type {
|
|
||||||
case "session.tool.input.started", "session.tool.input.ended":
|
|
||||||
part.State.Status = "streaming"
|
|
||||||
case "session.tool.called":
|
|
||||||
part.State.Status = "running"
|
|
||||||
part.State.Input = d.Input
|
|
||||||
case "session.tool.progress":
|
|
||||||
if d.Metadata != nil {
|
|
||||||
part.State.Metadata = d.Metadata
|
|
||||||
}
|
|
||||||
case "session.tool.success":
|
|
||||||
part.State.Status = "completed"
|
|
||||||
part.State.Input = d.Input
|
|
||||||
part.State.Content = d.Content
|
|
||||||
part.State.Metadata = d.Metadata
|
|
||||||
case "session.tool.failed":
|
|
||||||
part.State.Status = "error"
|
|
||||||
part.State.Input = d.Input
|
|
||||||
part.State.Content = d.Content
|
|
||||||
part.State.Metadata = d.Metadata
|
|
||||||
part.State.Error = d.Error
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// findToolPart finds a tool part by its call id, creating one if the page
|
|
||||||
// does not have it yet.
|
|
||||||
func (ch *chat) findToolPart(m *ocapi.Message, id string) *ocapi.ContentPart {
|
|
||||||
for i := range m.Content {
|
|
||||||
p := &m.Content[i]
|
|
||||||
if p.Type == "tool" && p.ID == id {
|
|
||||||
if p.State == nil {
|
|
||||||
p.State = &ocapi.ToolState{}
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The message's first tool part with no id yet is the running call.
|
|
||||||
for i := range m.Content {
|
|
||||||
p := &m.Content[i]
|
|
||||||
if p.Type == "tool" && p.ID == "" {
|
|
||||||
p.ID = id
|
|
||||||
if p.State == nil {
|
|
||||||
p.State = &ocapi.ToolState{}
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A call the page never saw: append it.
|
|
||||||
m.Content = append(m.Content, ocapi.ContentPart{
|
|
||||||
Type: "tool", ID: id, State: &ocapi.ToolState{Status: "running"},
|
|
||||||
})
|
|
||||||
return &m.Content[len(m.Content)-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
type stepEndData struct {
|
|
||||||
AssistantMessageID string `json:"assistantMessageID"`
|
|
||||||
Finish string `json:"finish"`
|
|
||||||
Cost float64 `json:"cost"`
|
|
||||||
Tokens *ocapi.TokenUsage `json:"tokens"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) applyStepEnd(ev ocapi.Event) {
|
|
||||||
var d stepEndData
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
|
||||||
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
|
|
||||||
if d.Finish != "" {
|
|
||||||
m.Finish = d.Finish
|
|
||||||
}
|
|
||||||
m.Cost = d.Cost
|
|
||||||
m.Tokens = d.Tokens
|
|
||||||
m.Time.Completed = ev.Created
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) applyDelta(ev ocapi.Event, kind string, slots map[string]map[int]int) {
|
|
||||||
var d deltaData
|
|
||||||
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
|
|
||||||
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
|
|
||||||
idx := slotFor(slots, m, d.Ordinal, kind)
|
|
||||||
if idx < 0 || idx >= len(m.Content) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
part := &m.Content[idx]
|
|
||||||
switch {
|
|
||||||
case strings.HasSuffix(ev.Type, ".started"):
|
|
||||||
part.Type = kind
|
|
||||||
case strings.HasSuffix(ev.Type, ".delta"):
|
|
||||||
part.Text += d.Delta
|
|
||||||
case strings.HasSuffix(ev.Type, ".ended"):
|
|
||||||
part.Text = d.Text
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func slotFor(slots map[string]map[int]int, m *ocapi.Message, ordinal int, kind string) int {
|
|
||||||
byOrdinal := slots[m.ID]
|
|
||||||
if byOrdinal == nil {
|
|
||||||
byOrdinal = map[int]int{}
|
|
||||||
slots[m.ID] = byOrdinal
|
|
||||||
}
|
|
||||||
if idx, ok := byOrdinal[ordinal]; ok && idx < len(m.Content) {
|
|
||||||
return idx
|
|
||||||
}
|
|
||||||
m.Content = append(m.Content, ocapi.ContentPart{Type: kind})
|
|
||||||
idx := len(m.Content) - 1
|
|
||||||
byOrdinal[ordinal] = idx
|
|
||||||
return idx
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) ensureAssistant(id string, created int64) {
|
|
||||||
if _, ok := ch.byID[id]; ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
|
|
||||||
}
|
|
||||||
|
|
||||||
// toolOutput is a tool call's result text.
|
|
||||||
func toolOutput(p ocapi.ContentPart) string {
|
|
||||||
if p.State == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
var out []string
|
|
||||||
for _, c := range p.State.Content {
|
|
||||||
if c.Type == "text" {
|
|
||||||
out = append(out, c.Text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(out) == 0 {
|
|
||||||
if p.State.Error != nil && len(p.State.Error) > 0 {
|
|
||||||
return string(p.State.Error)
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return strings.Join(out, "\n")
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"embed"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:embed icons/*.png
|
|
||||||
var iconFiles embed.FS
|
|
||||||
|
|
||||||
// iconBitmaps decodes the PNG icons once, on the main thread.
|
|
||||||
var iconBitmaps sync.Map // name -> *ui.Bitmap
|
|
||||||
|
|
||||||
func iconBitmap(name string) *ui.Bitmap {
|
|
||||||
if v, ok := iconBitmaps.Load(name); ok {
|
|
||||||
return v.(*ui.Bitmap)
|
|
||||||
}
|
|
||||||
data, err := iconFiles.ReadFile("icons/" + name + ".png")
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
bmp, err := ui.DecodeBitmap(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
iconBitmaps.Store(name, bmp)
|
|
||||||
return bmp
|
|
||||||
}
|
|
||||||
|
|
||||||
// barIcon is the PNG a system navigation bar button takes on Android.
|
|
||||||
func barIcon(name string) []byte {
|
|
||||||
data, err := iconFiles.ReadFile("icons/" + name + ".png")
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
Before Width: | Height: | Size: 326 B |
|
Before Width: | Height: | Size: 168 B |
|
Before Width: | Height: | Size: 228 B |
|
Before Width: | Height: | Size: 302 B |
|
Before Width: | Height: | Size: 327 B |
|
Before Width: | Height: | Size: 271 B |
@@ -1,268 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha1"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/mobile"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
var imagePathPattern = regexp.MustCompile(`(/[^\s"'` + "`" + `()\[\]{}<>]+\.(?:png|jpg|jpeg|gif|webp|bmp|avif))`)
|
|
||||||
|
|
||||||
var imageExtensions = map[string]bool{
|
|
||||||
".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
|
|
||||||
".webp": true, ".bmp": true, ".avif": true,
|
|
||||||
}
|
|
||||||
|
|
||||||
// imageRef is one previewable image a tool call names.
|
|
||||||
type imageRef struct {
|
|
||||||
Source string
|
|
||||||
Label string
|
|
||||||
}
|
|
||||||
|
|
||||||
func isImagePath(path string) bool {
|
|
||||||
return imageExtensions[strings.ToLower(filepath.Ext(path))]
|
|
||||||
}
|
|
||||||
|
|
||||||
// toolImages lists the images a tool call names: its file input, file
|
|
||||||
// parts in its output, and paths in its text output.
|
|
||||||
func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
|
|
||||||
seen := map[string]bool{}
|
|
||||||
out := make([]imageRef, 0, 2)
|
|
||||||
hasLabel := func(label string) bool {
|
|
||||||
for _, ref := range out {
|
|
||||||
if ref.Label == label {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
add := func(source, label string) {
|
|
||||||
source = strings.TrimSpace(source)
|
|
||||||
if strings.HasPrefix(source, "file://") {
|
|
||||||
source = strings.TrimPrefix(source, "file://")
|
|
||||||
}
|
|
||||||
if source == "" || seen[source] {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(source, "data:") {
|
|
||||||
if strings.Contains(source, "://") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(source, "/") {
|
|
||||||
if ch.dir == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
source = filepath.Join(ch.dir, source)
|
|
||||||
}
|
|
||||||
if !isImagePath(source) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if label == "" {
|
|
||||||
label = filepath.Base(source)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if label == "" {
|
|
||||||
label = "图片"
|
|
||||||
}
|
|
||||||
seen[source] = true
|
|
||||||
out = append(out, imageRef{Source: source, Label: label})
|
|
||||||
}
|
|
||||||
addPath := func(path string) {
|
|
||||||
path = strings.TrimSpace(path)
|
|
||||||
if strings.HasPrefix(path, "file://") {
|
|
||||||
path = strings.TrimPrefix(path, "file://")
|
|
||||||
} else if strings.Contains(path, "://") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(path, "/") {
|
|
||||||
if ch.dir == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
path = filepath.Join(ch.dir, path)
|
|
||||||
}
|
|
||||||
if !isImagePath(path) || hasLabel(filepath.Base(path)) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
add(path, "")
|
|
||||||
}
|
|
||||||
attachments := 0
|
|
||||||
if p.State != nil {
|
|
||||||
for _, group := range [][]ocapi.ContentPart{p.State.Attachments, p.State.Content} {
|
|
||||||
for _, c := range group {
|
|
||||||
switch c.Type {
|
|
||||||
case "file":
|
|
||||||
source := c.URL
|
|
||||||
if source == "" {
|
|
||||||
source = c.URI
|
|
||||||
}
|
|
||||||
if source != "" && strings.HasPrefix(c.MIME, "image/") {
|
|
||||||
attachments++
|
|
||||||
add(source, c.Filename)
|
|
||||||
}
|
|
||||||
case "text":
|
|
||||||
for _, m := range imagePathPattern.FindAllString(c.Text, -1) {
|
|
||||||
addPath(m)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if attachments == 0 {
|
|
||||||
for _, key := range []string{"filePath", "path", "file", "file_path", "sourcePath"} {
|
|
||||||
if v, ok := p.State.Input[key].(string); ok {
|
|
||||||
addPath(v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------- preview
|
|
||||||
|
|
||||||
func previewKey(source string) string {
|
|
||||||
sum := sha1.Sum([]byte(source))
|
|
||||||
return hex.EncodeToString(sum[:])
|
|
||||||
}
|
|
||||||
|
|
||||||
// previewDir is where fetched previews are kept.
|
|
||||||
func previewDir() string {
|
|
||||||
dir, err := mygo.App.Path(mygo.PathUserData)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return filepath.Join(dir, "previews")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) previewImage(ref imageRef) {
|
|
||||||
ch.previewSeq++
|
|
||||||
seq := ch.previewSeq
|
|
||||||
ch.previewTitle = ref.Label
|
|
||||||
ch.previewPath = ""
|
|
||||||
ch.previewLoading = true
|
|
||||||
ch.previewOpen = true
|
|
||||||
key := previewKey(ref.Source)
|
|
||||||
if local, ok := ch.previewCache[key]; ok {
|
|
||||||
ch.previewPath = local
|
|
||||||
ch.previewLoading = false
|
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
data, err := ch.loadPreview(ref.Source)
|
|
||||||
if err != nil {
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if seq != ch.previewSeq {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.previewLoading = false
|
|
||||||
ch.previewOpen = false
|
|
||||||
ch.errText = "无法预览:" + friendlyError(err)
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
dir := previewDir()
|
|
||||||
_ = os.MkdirAll(dir, 0o700)
|
|
||||||
name := strings.Map(func(r rune) rune {
|
|
||||||
if r == '/' || r == '\\' || r == ':' || r < ' ' {
|
|
||||||
return '_'
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}, ref.Label)
|
|
||||||
local := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), name))
|
|
||||||
if err := os.WriteFile(local, data, 0o600); err != nil {
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if seq != ch.previewSeq {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.previewLoading = false
|
|
||||||
ch.previewOpen = false
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if seq != ch.previewSeq {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.previewCache[key] = local
|
|
||||||
ch.previewPath = local
|
|
||||||
ch.previewLoading = false
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadPreview reads a data URL itself or asks the server for the file.
|
|
||||||
func (ch *chat) loadPreview(source string) ([]byte, error) {
|
|
||||||
if strings.HasPrefix(source, "data:") {
|
|
||||||
comma := strings.IndexByte(source, ',')
|
|
||||||
if comma < 0 {
|
|
||||||
return nil, fmt.Errorf("malformed data URL")
|
|
||||||
}
|
|
||||||
meta := source[len("data:"):comma]
|
|
||||||
if !strings.Contains(meta, ";base64") {
|
|
||||||
return nil, fmt.Errorf("unsupported data URL")
|
|
||||||
}
|
|
||||||
return base64.StdEncoding.DecodeString(source[comma+1:])
|
|
||||||
}
|
|
||||||
client := ch.a.client
|
|
||||||
if client == nil {
|
|
||||||
return nil, fmt.Errorf("未连接")
|
|
||||||
}
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
data, _, err := client.RawFile(ctx, source, ch.dir)
|
|
||||||
return data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// previewSheet shows the fetched image.
|
|
||||||
func (ch *chat) previewSheet(c *ui.Context) {
|
|
||||||
if !ch.previewOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.Sheet(c, &ch.previewOpen, mobile.SheetOptions{Detents: []float32{0.92}}, func() {
|
|
||||||
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
|
|
||||||
ui.Text(c, ch.previewTitle).FontSize(16).FontWeight(600).MaxLines(2)
|
|
||||||
if ch.previewLoading {
|
|
||||||
ui.Column(c).Fill().Center().Height(300).Children(func() { ui.Spinner(c) })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
bmp := loadImageFile(ch.previewPath)
|
|
||||||
if bmp != nil {
|
|
||||||
ui.Image(c, bmp).FillWidth().Height(420).Radius(10).Clip()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadImageFile decodes a local image file into a bitmap, caching it.
|
|
||||||
var imageCache sync.Map // path -> *ui.Bitmap
|
|
||||||
|
|
||||||
func loadImageFile(path string) *ui.Bitmap {
|
|
||||||
if path == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if v, ok := imageCache.Load(path); ok {
|
|
||||||
return v.(*ui.Bitmap)
|
|
||||||
}
|
|
||||||
data, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
bmp, err := ui.DecodeBitmap(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
imageCache.Store(path, bmp)
|
|
||||||
return bmp
|
|
||||||
}
|
|
||||||
@@ -1,299 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/url"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/mobile"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/storage"
|
|
||||||
)
|
|
||||||
|
|
||||||
// serversView is the first screen: the list of saved servers, or the
|
|
||||||
// connect form when one is being edited or needs a password.
|
|
||||||
func (a *App) serversView(c *ui.Context) {
|
|
||||||
t := c.Theme()
|
|
||||||
if a.phase == "form" {
|
|
||||||
a.connectFormView(c)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ui.Column(c).Fill().Background(t.Background).Children(func() {
|
|
||||||
header := ui.Column(c).FillWidth().Padding(16, 20, 8, 20)
|
|
||||||
header.Children(func() {
|
|
||||||
ui.Text(c, "OpenChamber").FontSize(28).Bold().Role(ui.RoleHeading).Level(1)
|
|
||||||
ui.Text(c, "连接你的 OpenChamber 服务器").FontSize(14).TextColor(t.TextMuted)
|
|
||||||
})
|
|
||||||
if a.errorText != "" {
|
|
||||||
ui.Text(c, a.errorText).FontSize(13).TextColor(t.Danger).Padding(12, 16, 4, 16)
|
|
||||||
}
|
|
||||||
scroll := ui.Scroll(c).Grow(1).PaddingX(16)
|
|
||||||
scroll.Children(func() {
|
|
||||||
ui.Column(c).FillWidth().Gap(10).Children(func() {
|
|
||||||
conns := a.store.Connections()
|
|
||||||
for i := range conns {
|
|
||||||
conn := &conns[i]
|
|
||||||
a.serverCard(c, conn)
|
|
||||||
}
|
|
||||||
add := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(14, 14).
|
|
||||||
Radius(14).Border(0.5, t.Border).Role(ui.RoleButton).Label("添加服务器")
|
|
||||||
add.Children(func() {
|
|
||||||
ui.Text(c, "+").FontSize(20).TextColor(t.Accent).Width(30).TextAlign(ui.Center)
|
|
||||||
ui.Text(c, "添加服务器").FontSize(16)
|
|
||||||
})
|
|
||||||
if add.Clicked() {
|
|
||||||
a.newServerForm()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) serverCard(c *ui.Context, conn *storage.Connection) {
|
|
||||||
t := c.Theme()
|
|
||||||
connected := a.client != nil && a.conn.ID == conn.ID
|
|
||||||
card := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(14, 14).
|
|
||||||
Background(t.Surface).Radius(14).Role(ui.RoleButton).Label("服务器 " + conn.Label)
|
|
||||||
card.Children(func() {
|
|
||||||
info := ui.Column(c).Grow(1).Basis(0).Gap(2)
|
|
||||||
info.Children(func() {
|
|
||||||
ui.Text(c, conn.Label).FontSize(16).FontWeight(600).MaxLines(1)
|
|
||||||
ui.Text(c, conn.URL).FontSize(13).TextColor(t.TextMuted).MaxLines(1)
|
|
||||||
})
|
|
||||||
if connected {
|
|
||||||
ui.Text(c, "已连接").FontSize(13).TextColor(t.Accent)
|
|
||||||
} else if ui.Button(c, "连接").Clicked() {
|
|
||||||
a.connectTo(*conn, "", false)
|
|
||||||
}
|
|
||||||
if ui.Button(c, "⋯").Label("服务器选项").Width(40).Clicked() {
|
|
||||||
a.serverActions(conn)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// serverActions opens a connection's menu: connect, edit, delete.
|
|
||||||
func (a *App) serverActions(conn *storage.Connection) {
|
|
||||||
open := true
|
|
||||||
a.serverActionOpen = &open
|
|
||||||
a.serverActionTarget = conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// serverActionSheet draws the open connection menu.
|
|
||||||
func (a *App) serverActionSheet(c *ui.Context) {
|
|
||||||
if a.serverActionOpen == nil || !*a.serverActionOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
conn := a.serverActionTarget
|
|
||||||
if conn == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.ActionSheet(c, a.serverActionOpen, mobile.ActionSheetOptions{
|
|
||||||
Title: conn.Label,
|
|
||||||
Cancel: "取消",
|
|
||||||
}, mobile.Action{
|
|
||||||
Label: "连接",
|
|
||||||
OnTap: func() { a.connectTo(*conn, "", false) },
|
|
||||||
}, mobile.Action{
|
|
||||||
Label: "编辑",
|
|
||||||
OnTap: func() { a.editServerForm(conn) },
|
|
||||||
}, mobile.Action{
|
|
||||||
Label: "删除",
|
|
||||||
Destructive: true,
|
|
||||||
OnTap: func() { a.deleteServer(conn) },
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// deleteServer asks and removes a saved server.
|
|
||||||
func (a *App) deleteServer(conn *storage.Connection) {
|
|
||||||
a.confirmDelete = true
|
|
||||||
a.deleteTarget = conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// deleteConfirmSheet asks "删除服务器?".
|
|
||||||
func (a *App) deleteConfirmSheet(c *ui.Context) {
|
|
||||||
if !a.confirmDelete {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
buttons := ui.AlertDialog(c, &a.confirmDelete, "删除服务器?",
|
|
||||||
"“"+a.deleteTarget.Label+"”将从列表移除,设备令牌也会删除。", "取消", "删除")
|
|
||||||
if buttons == 1 {
|
|
||||||
if a.client != nil && a.conn.ID == a.deleteTarget.ID {
|
|
||||||
a.disconnect()
|
|
||||||
}
|
|
||||||
_ = a.store.ClearToken(*a.deleteTarget)
|
|
||||||
conns := a.store.Connections()
|
|
||||||
next := conns[:0]
|
|
||||||
for _, x := range conns {
|
|
||||||
if x.ID != a.deleteTarget.ID {
|
|
||||||
next = append(next, x)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
a.store.SaveConnections(next)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// connectFormView is the add/edit form with the password field.
|
|
||||||
func (a *App) connectFormView(c *ui.Context) {
|
|
||||||
t := c.Theme()
|
|
||||||
ui.Column(c).Fill().Background(t.Background).Children(func() {
|
|
||||||
head := ui.Row(c).FillWidth().Padding(12, 12).AlignItems(ui.Center).Gap(8)
|
|
||||||
head.Children(func() {
|
|
||||||
if ui.Button(c, "‹").Label("返回").Width(40).Clicked() {
|
|
||||||
a.phase = ""
|
|
||||||
a.formEditing = nil
|
|
||||||
a.formError = ""
|
|
||||||
}
|
|
||||||
ui.Text(c, a.formTitle).FontSize(18).FontWeight(600).Grow(1)
|
|
||||||
})
|
|
||||||
scroll := ui.Scroll(c).Grow(1).PaddingX(16)
|
|
||||||
scroll.Children(func() {
|
|
||||||
ui.Column(c).FillWidth().Gap(10).Children(func() {
|
|
||||||
a.fieldLabel(c, "名称")
|
|
||||||
ui.TextInput(c, &a.formLabel).Placeholder("如 我的电脑")
|
|
||||||
a.fieldLabel(c, "服务器地址")
|
|
||||||
ui.TextInput(c, &a.formURL).Placeholder("http://192.168.1.10:3000").Keyboard(ui.KeyboardURL)
|
|
||||||
a.fieldLabel(c, "代理(可选)")
|
|
||||||
ui.TextInput(c, &a.formProxy).Placeholder("http://… 或 socks5://…").Keyboard(ui.KeyboardURL)
|
|
||||||
a.fieldLabel(c, "自签证书指纹(可选)")
|
|
||||||
ui.TextInput(c, &a.formFinger).Placeholder("SHA-256 十六进制")
|
|
||||||
row := ui.Row(c).FillWidth().AlignItems(ui.Center)
|
|
||||||
row.Children(func() {
|
|
||||||
ui.Text(c, "信任自签名证书").Grow(1).FontSize(15)
|
|
||||||
ui.Switch(c, &a.formInsecure)
|
|
||||||
})
|
|
||||||
if a.formEditing != nil {
|
|
||||||
a.fieldLabel(c, "密码")
|
|
||||||
ui.TextInput(c, &a.formPassword).Password().Placeholder("服务器密码")
|
|
||||||
}
|
|
||||||
if a.formError != "" {
|
|
||||||
ui.Text(c, a.formError).FontSize(13).TextColor(t.Danger)
|
|
||||||
}
|
|
||||||
if a.busy {
|
|
||||||
ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(4, 0).Children(func() {
|
|
||||||
ui.Spinner(c)
|
|
||||||
ui.Text(c, "连接中…").TextColor(t.TextMuted)
|
|
||||||
})
|
|
||||||
} else if ui.PrimaryButton(c, "连接").FillWidth().Padding(8, 0).Clicked() {
|
|
||||||
a.submitForm()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) fieldLabel(c *ui.Context, s string) {
|
|
||||||
t := c.Theme()
|
|
||||||
ui.Text(c, s).FontSize(13).TextColor(t.TextMuted)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) submitForm() {
|
|
||||||
conn := a.formEditing
|
|
||||||
if conn == nil {
|
|
||||||
conn = &storage.Connection{ID: storage.NewID()}
|
|
||||||
}
|
|
||||||
conn.Label = trimOr(a.formLabel, hostOf(a.formURL))
|
|
||||||
conn.URL = a.formURL
|
|
||||||
conn.Proxy = a.formProxy
|
|
||||||
conn.Insecure = a.formInsecure
|
|
||||||
conn.Fingerprint = a.formFinger
|
|
||||||
a.connectTo(*conn, a.formPassword, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) editServerForm(conn *storage.Connection) {
|
|
||||||
a.phase = "form"
|
|
||||||
a.formEditing = conn
|
|
||||||
a.formTitle = "编辑 " + conn.Label
|
|
||||||
a.formLabel = conn.Label
|
|
||||||
a.formURL = conn.URL
|
|
||||||
a.formProxy = conn.Proxy
|
|
||||||
a.formInsecure = conn.Insecure
|
|
||||||
a.formFinger = conn.Fingerprint
|
|
||||||
a.formPassword = ""
|
|
||||||
a.formError = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) newServerForm() {
|
|
||||||
a.phase = "form"
|
|
||||||
a.formEditing = nil
|
|
||||||
a.formTitle = "添加服务器"
|
|
||||||
a.formLabel = ""
|
|
||||||
a.formURL = ""
|
|
||||||
a.formProxy = ""
|
|
||||||
a.formInsecure = false
|
|
||||||
a.formFinger = ""
|
|
||||||
a.formPassword = ""
|
|
||||||
a.formError = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------------------------------------- instances
|
|
||||||
|
|
||||||
// instancesSheet shows the instance list: switch servers, disconnect, add.
|
|
||||||
func (a *App) instancesSheet(c *ui.Context) {
|
|
||||||
if !a.instancesOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t := c.Theme()
|
|
||||||
mobile.Sheet(c, &a.instancesOpen, mobile.SheetOptions{
|
|
||||||
Detents: []float32{0.6},
|
|
||||||
Label: "服务器",
|
|
||||||
}, func() {
|
|
||||||
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(2).Children(func() {
|
|
||||||
ui.Text(c, "服务器").FontSize(20).Bold().Padding(0, 0, 0, 6)
|
|
||||||
conns := a.store.Connections()
|
|
||||||
for i := range conns {
|
|
||||||
conn := &conns[i]
|
|
||||||
connected := a.client != nil && a.conn.ID == conn.ID
|
|
||||||
row := mobile.ListRow(c, mobile.RowOptions{
|
|
||||||
Title: conn.Label,
|
|
||||||
Subtitle: conn.URL,
|
|
||||||
Trailing: func() {
|
|
||||||
if connected {
|
|
||||||
ui.Text(c, "已连接").FontSize(13).TextColor(t.Accent)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if row.Clicked() && !connected {
|
|
||||||
a.instancesOpen = false
|
|
||||||
a.switchTo(*conn)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
row := mobile.ListRow(c, mobile.RowOptions{Title: "+ 添加服务器"})
|
|
||||||
if row.Clicked() {
|
|
||||||
a.instancesOpen = false
|
|
||||||
a.newServerForm()
|
|
||||||
}
|
|
||||||
if a.client != nil {
|
|
||||||
row := mobile.ListRow(c, mobile.RowOptions{Title: "断开当前连接"})
|
|
||||||
if row.Clicked() {
|
|
||||||
a.instancesOpen = false
|
|
||||||
a.disconnect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) switchTo(conn storage.Connection) {
|
|
||||||
if a.chat != nil {
|
|
||||||
a.closeChat()
|
|
||||||
}
|
|
||||||
a.stopStream()
|
|
||||||
a.client = nil
|
|
||||||
a.conn = storage.Connection{}
|
|
||||||
a.phase = ""
|
|
||||||
a.sessions = nil
|
|
||||||
a.connectTo(conn, "", true)
|
|
||||||
}
|
|
||||||
|
|
||||||
func trimOr(s, fallback string) string {
|
|
||||||
if s == "" {
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
func hostOf(raw string) string {
|
|
||||||
u, err := url.Parse(raw)
|
|
||||||
if err != nil || u.Host == "" {
|
|
||||||
return raw
|
|
||||||
}
|
|
||||||
return u.Host
|
|
||||||
}
|
|
||||||
@@ -1,152 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/mobile"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// sessionsView is the connected screen: the sessions list with its header.
|
|
||||||
func (a *App) sessionsView(c *ui.Context) {
|
|
||||||
t := c.Theme()
|
|
||||||
ui.Column(c).Fill().Background(t.Background).Children(func() {
|
|
||||||
mobile.TopBar(c, mobile.TopBarOptions{
|
|
||||||
Title: "会话",
|
|
||||||
Leading: func() {
|
|
||||||
// The single server entry: opens the instance list.
|
|
||||||
if a.iconButton(c, "server", "服务器").Clicked() {
|
|
||||||
a.instancesOpen = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Trailing: func() {
|
|
||||||
if a.iconButton(c, "search", "搜索").Clicked() {
|
|
||||||
a.searchOpen = !a.searchOpen
|
|
||||||
if !a.searchOpen {
|
|
||||||
a.searchText = ""
|
|
||||||
a.loadSessions()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if a.iconButton(c, "plus", "新建会话").Clicked() {
|
|
||||||
a.newSessionForm()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if a.searchOpen {
|
|
||||||
ui.TextInput(c, &a.searchText).Placeholder("搜索会话").PaddingX(16).AutoFocus()
|
|
||||||
a.scheduleSearch()
|
|
||||||
}
|
|
||||||
if a.errorText != "" {
|
|
||||||
ui.Text(c, a.errorText).FontSize(13).TextColor(t.Danger).Padding(8, 16, 0, 16)
|
|
||||||
}
|
|
||||||
a.sessionList(c)
|
|
||||||
})
|
|
||||||
a.instancesSheet(c)
|
|
||||||
a.serverActionSheet(c)
|
|
||||||
a.deleteConfirmSheet(c)
|
|
||||||
a.newSessionSheet(c)
|
|
||||||
a.sessionActionSheet(c)
|
|
||||||
a.renameSheet(c)
|
|
||||||
a.sessionDeleteConfirm(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// iconButton is a small square button with an icon.
|
|
||||||
func (a *App) iconButton(c *ui.Context, icon, label string) ui.Element {
|
|
||||||
btn := ui.Button(c, "").Width(44).Height(44).Padding(0, 0)
|
|
||||||
btn.Children(func() {
|
|
||||||
bmp := iconBitmap(icon)
|
|
||||||
if bmp != nil {
|
|
||||||
ui.Image(c, bmp).Size(22, 22)
|
|
||||||
} else {
|
|
||||||
ui.Text(c, icon).FontSize(18)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
_ = label
|
|
||||||
return btn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) sessionList(c *ui.Context) {
|
|
||||||
if a.sessionsLoad && len(a.sessions) == 0 {
|
|
||||||
ui.Column(c).Fill().Center().Children(func() {
|
|
||||||
ui.Spinner(c)
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(a.sessions) == 0 && !a.sessionsLoad {
|
|
||||||
ui.Column(c).Fill().Center().Gap(8).Children(func() {
|
|
||||||
ui.Text(c, "暂无会话")
|
|
||||||
if ui.PrimaryButton(c, "新建会话").Clicked() {
|
|
||||||
a.newSessionForm()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
list := ui.List(c, &a.sessionListState, len(a.sessions))
|
|
||||||
list.ItemKey(func(i int) any { return a.sessions[i].ID })
|
|
||||||
list.Rows(func(r ui.ListRow) {
|
|
||||||
i := r.Index
|
|
||||||
s := a.sessions[i]
|
|
||||||
row := ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Padding(12, 16).
|
|
||||||
Role(ui.RoleButton).Label(s.Title)
|
|
||||||
row.Children(func() {
|
|
||||||
col := ui.Column(c).Grow(1).Basis(0).Gap(2)
|
|
||||||
col.Children(func() {
|
|
||||||
title := s.Title
|
|
||||||
if title == "" {
|
|
||||||
title = "(无标题会话)"
|
|
||||||
}
|
|
||||||
ui.Text(c, title).FontSize(16).FontWeight(600).MaxLines(1)
|
|
||||||
ui.Text(c, a.sessionSubtitle(s)).FontSize(13).TextColor(t(c).TextMuted).MaxLines(1)
|
|
||||||
})
|
|
||||||
if a.active[s.ID] {
|
|
||||||
ui.Text(c, "●").TextColor(t(c).Accent).FontSize(10)
|
|
||||||
}
|
|
||||||
if ui.Button(c, "⋯").Label("会话操作").Width(40).Clicked() {
|
|
||||||
a.openSessionActions(s)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
if row.Clicked() {
|
|
||||||
a.openChat(s)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func t(c *ui.Context) *ui.Theme { return c.Theme() }
|
|
||||||
|
|
||||||
func (a *App) sessionSubtitle(s ocapi.Session) string {
|
|
||||||
parts := []string{}
|
|
||||||
if s.Agent != "" {
|
|
||||||
parts = append(parts, s.Agent)
|
|
||||||
}
|
|
||||||
if s.Model != nil {
|
|
||||||
parts = append(parts, a.modelName(s.Model))
|
|
||||||
}
|
|
||||||
if s.Time.Updated > 0 {
|
|
||||||
parts = append(parts, time.UnixMilli(s.Time.Updated).Format("01-02 15:04"))
|
|
||||||
}
|
|
||||||
out := ""
|
|
||||||
for i, p := range parts {
|
|
||||||
if i > 0 {
|
|
||||||
out += " · "
|
|
||||||
}
|
|
||||||
out += p
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// scheduleSearch debounces search input.
|
|
||||||
func (a *App) scheduleSearch() {
|
|
||||||
if a.searchTimer != nil {
|
|
||||||
a.searchTimer.Stop()
|
|
||||||
}
|
|
||||||
a.searchTimer = time.AfterFunc(350*time.Millisecond, func() {
|
|
||||||
a.win.Update(func() {
|
|
||||||
if a.searchText != "" {
|
|
||||||
a.searchSessions(a.searchText)
|
|
||||||
} else {
|
|
||||||
a.loadSessions()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/mobile"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
// new session -----------------------------------------------------------
|
|
||||||
|
|
||||||
func (a *App) newSessionForm() {
|
|
||||||
a.newTitle = ""
|
|
||||||
a.newOpen = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) newSessionSheet(c *ui.Context) {
|
|
||||||
if !a.newOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.Sheet(c, &a.newOpen, mobile.SheetOptions{Detents: []float32{0.4}}, func() {
|
|
||||||
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(10).Children(func() {
|
|
||||||
ui.Text(c, "新建会话").FontSize(20).Bold()
|
|
||||||
ui.TextInput(c, &a.newTitle).Placeholder("标题(可选)").AutoFocus()
|
|
||||||
if ui.PrimaryButton(c, "创建").FillWidth().Clicked() {
|
|
||||||
a.newOpen = false
|
|
||||||
a.createSession()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) createSession() {
|
|
||||||
dir := a.dir()
|
|
||||||
title := a.newTitle
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
sess, err := a.client.CreateSession(ctx, ocapi.CreateSessionOptions{Title: title, Directory: dir})
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
a.errorText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.sessions = append([]ocapi.Session{sess}, a.sessions...)
|
|
||||||
a.openChat(sess)
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// session actions -------------------------------------------------------
|
|
||||||
|
|
||||||
func (a *App) openSessionActions(s ocapi.Session) {
|
|
||||||
a.sessionActionOpen = true
|
|
||||||
a.sessionActionTarget = s
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) sessionActionSheet(c *ui.Context) {
|
|
||||||
if !a.sessionActionOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
s := a.sessionActionTarget
|
|
||||||
mobile.ActionSheet(c, &a.sessionActionOpen, mobile.ActionSheetOptions{Title: s.Title, Cancel: "取消"},
|
|
||||||
mobile.Action{Label: "重命名", OnTap: func() { a.renameSession(s) }},
|
|
||||||
mobile.Action{Label: "归档", OnTap: func() { a.setArchived(s, true) }},
|
|
||||||
mobile.Action{Label: "删除", Destructive: true, OnTap: func() { a.deleteSession(s) }},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) renameSession(s ocapi.Session) {
|
|
||||||
a.renameOpen = true
|
|
||||||
a.renameTarget = s
|
|
||||||
a.renameText = s.Title
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) renameSheet(c *ui.Context) {
|
|
||||||
if !a.renameOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.Sheet(c, &a.renameOpen, mobile.SheetOptions{Detents: []float32{0.3}}, func() {
|
|
||||||
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(10).Children(func() {
|
|
||||||
ui.Text(c, "重命名").FontSize(20).Bold()
|
|
||||||
ui.TextInput(c, &a.renameText).AutoFocus()
|
|
||||||
if ui.PrimaryButton(c, "保存").FillWidth().Clicked() {
|
|
||||||
a.renameOpen = false
|
|
||||||
a.doRename()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) doRename() {
|
|
||||||
title := a.renameText
|
|
||||||
s := a.renameTarget
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
err := a.client.UpdateSession(ctx, s.ID, a.dir(), ocapi.SessionPatch{Title: &title})
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
a.errorText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.patchSession(s.ID, func(x *ocapi.Session) { x.Title = title })
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) setArchived(s ocapi.Session, on bool) {
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
err := a.client.UpdateSession(ctx, s.ID, a.dir(), ocapi.SessionPatch{Archived: &on})
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
a.errorText = friendlyError(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) deleteSession(s ocapi.Session) {
|
|
||||||
a.sessionDeleteOpen = true
|
|
||||||
target := s
|
|
||||||
a.sessionDeleteTarget = &target
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) sessionDeleteConfirm(c *ui.Context) {
|
|
||||||
if !a.sessionDeleteOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
title := ""
|
|
||||||
if a.sessionDeleteTarget != nil {
|
|
||||||
title = a.sessionDeleteTarget.Title
|
|
||||||
}
|
|
||||||
buttons := ui.AlertDialog(c, &a.sessionDeleteOpen, "删除会话?",
|
|
||||||
"“"+title+"”及其子会话将被删除,且无法恢复。", "取消", "删除")
|
|
||||||
if buttons == 1 {
|
|
||||||
a.doDeleteSession()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) doDeleteSession() {
|
|
||||||
if a.sessionDeleteTarget == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
s := *a.sessionDeleteTarget
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
err := a.client.DeleteSession(ctx, s.ID, a.dir())
|
|
||||||
a.post(func() {
|
|
||||||
if err != nil {
|
|
||||||
a.errorText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.removeSession(s.ID)
|
|
||||||
if a.chat != nil && a.chat.id == s.ID {
|
|
||||||
a.closeChat()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
@@ -1,344 +0,0 @@
|
|||||||
package appui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
"github.com/egoist/mygo/ui"
|
|
||||||
"github.com/egoist/mygo/ui/mobile"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
|
||||||
"github.com/openchamber/openchamber-native/internal/tts"
|
|
||||||
)
|
|
||||||
|
|
||||||
// sheets draws the chat's overlays: menus, pickers and previews.
|
|
||||||
func (ch *chat) sheets(c *ui.Context) {
|
|
||||||
ch.footerSheet(c)
|
|
||||||
ch.userSheet(c)
|
|
||||||
ch.pickerSheet(c)
|
|
||||||
ch.usageSheet(c)
|
|
||||||
ch.previewSheet(c)
|
|
||||||
ch.attachSheet(c)
|
|
||||||
ch.revertConfirm(c)
|
|
||||||
ch.a.sessionActionSheet(c)
|
|
||||||
ch.a.newSessionSheet(c)
|
|
||||||
ch.a.serverActionSheet(c)
|
|
||||||
ch.a.deleteConfirmSheet(c)
|
|
||||||
ch.a.renameSheet(c)
|
|
||||||
ch.a.sessionDeleteConfirm(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// openFooter opens the actions of the turn that finished last.
|
|
||||||
func (ch *chat) openFooter() {
|
|
||||||
for i := len(ch.msgs) - 1; i >= 0; i-- {
|
|
||||||
if ch.msgs[i].Type == "assistant" && ch.msgs[i].Time.Completed > 0 {
|
|
||||||
ch.footerOpen = true
|
|
||||||
ch.footerID = ch.msgs[i].ID
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) footerSheet(c *ui.Context) {
|
|
||||||
if !ch.footerOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.ActionSheet(c, &ch.footerOpen, mobile.ActionSheetOptions{Title: "更多操作", Cancel: "取消"},
|
|
||||||
mobile.Action{Label: "朗读回答", OnTap: func() { ch.speakAnswer(ch.footerID) }},
|
|
||||||
mobile.Action{Label: "停止朗读", OnTap: func() { _ = tts.Stop() }},
|
|
||||||
mobile.Action{Label: "复制回答", OnTap: func() { ch.copyAnswer(ch.footerID) }},
|
|
||||||
mobile.Action{Label: "从这里分叉", OnTap: func() { ch.forkFrom(ch.footerID) }},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) userSheet(c *ui.Context) {
|
|
||||||
if !ch.userOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.ActionSheet(c, &ch.userOpen, mobile.ActionSheetOptions{Title: "消息操作", Cancel: "取消"},
|
|
||||||
mobile.Action{Label: "复制消息", OnTap: func() { ch.copyUserMessage(ch.userID) }},
|
|
||||||
mobile.Action{Label: "撤回此消息及之后", OnTap: func() { ch.askRevert(ch.userID) }},
|
|
||||||
mobile.Action{Label: "从这里分叉", OnTap: func() { ch.forkBefore(ch.userID) }},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) copyAnswer(id string) {
|
|
||||||
m := ch.byID[id]
|
|
||||||
parts := make([]string, 0, len(m.Content))
|
|
||||||
for _, p := range m.Content {
|
|
||||||
if p.Type == "text" && p.Text != "" {
|
|
||||||
parts = append(parts, p.Text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
text := strings.Join(parts, "\n")
|
|
||||||
if text == "" {
|
|
||||||
text = m.Text
|
|
||||||
}
|
|
||||||
if text == "" {
|
|
||||||
ch.a.chatPost(func() { ch.errText = "没有可复制的文字" })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mygo.Clipboard.WriteText(text)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) copyUserMessage(id string) {
|
|
||||||
m := ch.byID[id]
|
|
||||||
text := strings.TrimSpace(m.Text)
|
|
||||||
if text == "" {
|
|
||||||
ch.a.chatPost(func() { ch.errText = "没有可复制的文字" })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mygo.Clipboard.WriteText(text)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------ read aloud
|
|
||||||
|
|
||||||
func (ch *chat) speakAnswer(id string) {
|
|
||||||
text := ""
|
|
||||||
m := ch.byID[id]
|
|
||||||
parts := make([]string, 0, len(m.Content))
|
|
||||||
for _, p := range m.Content {
|
|
||||||
if p.Type == "text" && p.Text != "" {
|
|
||||||
parts = append(parts, p.Text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
text = strings.Join(parts, " ")
|
|
||||||
if text == "" {
|
|
||||||
text = m.Text
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(text) == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
if err := tts.Speak(ctx, text); err != nil {
|
|
||||||
ch.a.chatPost(func() { ch.errText = "朗读不可用:" + friendlyError(err) })
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------ fork / revert
|
|
||||||
|
|
||||||
func (ch *chat) forkFrom(id string) {
|
|
||||||
ch.fork(false, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) forkBefore(id string) {
|
|
||||||
ch.fork(true, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) fork(beforeMsg bool, id string) {
|
|
||||||
before := ""
|
|
||||||
if beforeMsg {
|
|
||||||
before = id
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
sess, err := ch.a.client.ForkSession(ctx, ch.id, ch.dir, before)
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.a.sessions = append([]ocapi.Session{sess}, ch.a.sessions...)
|
|
||||||
ch.a.openChat(sess)
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) askRevert(id string) {
|
|
||||||
ch.revertID = id
|
|
||||||
ch.confirmRevert = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) revertConfirm(c *ui.Context) {
|
|
||||||
if !ch.confirmRevert {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
buttons := ui.AlertDialog(c, &ch.confirmRevert, "撤回消息?",
|
|
||||||
"这条消息及其之后的内容会从会话中删除,且无法恢复。", "取消", "撤回")
|
|
||||||
if buttons == 1 {
|
|
||||||
ch.doRevert(ch.revertID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) doRevert(id string) {
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
client := ch.a.client
|
|
||||||
if client.StageRevert(ctx, ch.id, ch.dir, id) != nil {
|
|
||||||
ch.a.chatPost(func() { ch.errText = "无法撤回" })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := client.CommitRevert(ctx, ch.id, ch.dir); err != nil {
|
|
||||||
ch.a.chatPost(func() { ch.errText = friendlyError(err) })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.a.chatPost(func() { ch.reloadTail() })
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------ model / agent
|
|
||||||
|
|
||||||
func (ch *chat) openPicker(kind string) {
|
|
||||||
ch.pickerKind = kind
|
|
||||||
ch.pickerFilter = ""
|
|
||||||
ch.pickerItems = nil
|
|
||||||
ch.pickerOpen = true
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
var items []pickerItem
|
|
||||||
var err error
|
|
||||||
switch kind {
|
|
||||||
case "model":
|
|
||||||
var models []ocapi.ModelInfo
|
|
||||||
models, err = ch.a.client.Models(ctx, ch.dir)
|
|
||||||
for _, m := range models {
|
|
||||||
name := m.Name
|
|
||||||
if name == "" {
|
|
||||||
name = m.ID
|
|
||||||
}
|
|
||||||
items = append(items, pickerItem{
|
|
||||||
Key: m.ProviderID + "/" + m.ID,
|
|
||||||
Title: name,
|
|
||||||
Model: &ocapi.ModelRef{ID: m.ID, ProviderID: m.ProviderID},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
case "agent":
|
|
||||||
var agents []ocapi.AgentInfo
|
|
||||||
agents, err = ch.a.client.Agents(ctx, ch.dir)
|
|
||||||
for _, ag := range agents {
|
|
||||||
if ag.Mode != "primary" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
items = append(items, pickerItem{Key: "agent/" + ag.ID, Title: ag.Name, Agent: ag.ID})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.pickerItems = items
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) pickerSheet(c *ui.Context) {
|
|
||||||
if !ch.pickerOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.Sheet(c, &ch.pickerOpen, mobile.SheetOptions{Detents: []float32{0.85}}, func() {
|
|
||||||
ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
|
|
||||||
title := "选择模型"
|
|
||||||
if ch.pickerKind == "agent" {
|
|
||||||
title = "选择智能体"
|
|
||||||
}
|
|
||||||
ui.Text(c, title).FontSize(20).Bold()
|
|
||||||
ui.TextInput(c, &ch.pickerFilter).Placeholder("搜索").PaddingY(4)
|
|
||||||
ui.Scroll(c).Grow(1).Children(func() {
|
|
||||||
ui.Column(c).FillWidth().Gap(2).Children(func() {
|
|
||||||
filter := strings.ToLower(ch.pickerFilter)
|
|
||||||
for _, it := range ch.pickerItems {
|
|
||||||
if filter != "" && !strings.Contains(strings.ToLower(it.Title), filter) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
row := mobile.ListRow(c, mobile.RowOptions{Title: it.Title})
|
|
||||||
if row.Clicked() {
|
|
||||||
ch.pickerOpen = false
|
|
||||||
ch.selectPickerItem(it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) selectPickerItem(it pickerItem) {
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
var err error
|
|
||||||
switch ch.pickerKind {
|
|
||||||
case "model":
|
|
||||||
err = ch.a.client.SwitchModel(ctx, ch.id, ch.dir, *it.Model)
|
|
||||||
case "agent":
|
|
||||||
err = ch.a.client.SwitchAgent(ctx, ch.id, ch.dir, it.Agent)
|
|
||||||
}
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------ attachments
|
|
||||||
|
|
||||||
func (ch *chat) attachSheet(c *ui.Context) {
|
|
||||||
if !ch.attachOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mobile.ActionSheet(c, &ch.attachOpen, mobile.ActionSheetOptions{Title: "添加附件", Cancel: "取消"},
|
|
||||||
mobile.Action{Label: "照片", OnTap: func() { ch.pickFiles(true) }},
|
|
||||||
mobile.Action{Label: "文件", OnTap: func() { ch.pickFiles(false) }},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) pickFiles(imagesOnly bool) {
|
|
||||||
ch.a.post(func() { ch.attachBusy = true })
|
|
||||||
go func() {
|
|
||||||
opts := mygo.OpenDialogOptions{Multiple: true}
|
|
||||||
if imagesOnly {
|
|
||||||
opts.Filters = []mygo.FileFilter{{Name: "图片", MIMETypes: []string{"image/*"}}}
|
|
||||||
}
|
|
||||||
paths, err := mygo.Dialog.Open(opts)
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
ch.attachBusy = false
|
|
||||||
if err != nil {
|
|
||||||
ch.errText = friendlyError(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, p := range paths {
|
|
||||||
ch.addAttachment(p)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ch *chat) addAttachment(path string) {
|
|
||||||
info, err := os.Stat(path)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if info.Size() > 10<<20 {
|
|
||||||
ch.a.chatPost(func() { ch.errText = "附件不能超过 10MB" })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mime := mimeByExt(path)
|
|
||||||
url := "data:" + mime + ";base64," + base64URL(data)
|
|
||||||
kept := ""
|
|
||||||
if strings.HasPrefix(mime, "image/") {
|
|
||||||
kept = keepImage(path, info.Name())
|
|
||||||
}
|
|
||||||
ch.a.chatPost(func() {
|
|
||||||
if len(ch.attachments) >= 5 {
|
|
||||||
ch.errText = "最多 5 个附件"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch.attachments = append(ch.attachments, attachment{
|
|
||||||
Name: info.Name(), MIME: mime, DataURL: url, Size: info.Size(), LocalPath: kept,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,220 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCatalogAndPermissions(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/api/model":
|
|
||||||
if got := r.URL.Query().Get("location[directory]"); got != "/home/me/p" {
|
|
||||||
t.Errorf("model directory = %q", got)
|
|
||||||
}
|
|
||||||
fmt.Fprint(w, `{"data":[{"id":"gpt","providerID":"openai","name":"GPT"}]}`)
|
|
||||||
case "/api/agent":
|
|
||||||
fmt.Fprint(w, `{"data":[{"id":"build","name":"Build","mode":"primary"}]}`)
|
|
||||||
case "/api/permission/request":
|
|
||||||
fmt.Fprint(w, `{"data":[{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf x"]}]}`)
|
|
||||||
case "/api/session/ses_1/permission/per_1/reply":
|
|
||||||
var body map[string]any
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
||||||
if body["decision"] != "always" || body["message"] != "ok" {
|
|
||||||
t.Errorf("reply body = %v", body)
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
case "/api/session/ses_1/model":
|
|
||||||
var body struct {
|
|
||||||
Model ModelRef `json:"model"`
|
|
||||||
}
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
||||||
if body.Model.ID != "gpt" || body.Model.ProviderID != "openai" {
|
|
||||||
t.Errorf("model switch = %+v", body.Model)
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
case "/api/session/ses_1/agent":
|
|
||||||
var body map[string]any
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
||||||
if body["agent"] != "plan" {
|
|
||||||
t.Errorf("agent switch = %v", body)
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
case "/api/session/ses_1":
|
|
||||||
if r.Method != http.MethodPatch {
|
|
||||||
t.Errorf("method = %s", r.Method)
|
|
||||||
}
|
|
||||||
var body map[string]any
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
||||||
if body["title"] != "renamed" {
|
|
||||||
t.Errorf("patch = %v", body)
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected path %q", r.URL.Path)
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
|
|
||||||
models, err := c.Models(ctx, "/home/me/p")
|
|
||||||
if err != nil || len(models) != 1 || models[0].ID != "gpt" {
|
|
||||||
t.Fatalf("models: %+v %v", models, err)
|
|
||||||
}
|
|
||||||
agents, err := c.Agents(ctx, "")
|
|
||||||
if err != nil || len(agents) != 1 || agents[0].ID != "build" {
|
|
||||||
t.Fatalf("agents: %+v %v", agents, err)
|
|
||||||
}
|
|
||||||
perms, err := c.PendingPermissions(ctx, "")
|
|
||||||
if err != nil || len(perms) != 1 || perms[0].Action != "bash" {
|
|
||||||
t.Fatalf("permissions: %+v %v", perms, err)
|
|
||||||
}
|
|
||||||
if err := c.ReplyPermission(ctx, "ses_1", "per_1", PermissionAlways, "ok"); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := c.SwitchModel(ctx, "ses_1", "", ModelRef{ID: "gpt", ProviderID: "openai"}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := c.SwitchAgent(ctx, "ses_1", "", "plan"); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
title := "renamed"
|
|
||||||
if err := c.UpdateSession(ctx, "ses_1", "", SessionPatch{Title: &title}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCreateAndDeleteSession(t *testing.T) {
|
|
||||||
var createBody map[string]any
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch {
|
|
||||||
case r.URL.Path == "/api/session" && r.Method == http.MethodPost:
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&createBody)
|
|
||||||
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New","time":{"created":1,"updated":1}}}`)
|
|
||||||
case r.URL.Path == "/api/session/ses_new" && r.Method == http.MethodDelete:
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
s, err := c.CreateSession(context.Background(), CreateSessionOptions{Directory: "/p", Title: "New"})
|
|
||||||
if err != nil || s.ID != "ses_new" {
|
|
||||||
t.Fatalf("create: %+v %v", s, err)
|
|
||||||
}
|
|
||||||
if loc, _ := createBody["location"].(map[string]any); loc["directory"] != "/p" {
|
|
||||||
t.Errorf("create location: %v", createBody)
|
|
||||||
}
|
|
||||||
if err := c.DeleteSession(context.Background(), "ses_new", ""); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWaitReady(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if got := r.URL.Query().Get("wait"); got != "1500" {
|
|
||||||
t.Errorf("wait = %q", got)
|
|
||||||
}
|
|
||||||
fmt.Fprint(w, `{"healthy":true}`)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
if err := c.WaitReady(context.Background(), 1500*time.Millisecond); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCertificateFingerprint(t *testing.T) {
|
|
||||||
// A TLS server with a self-signed certificate; pinning its fingerprint
|
|
||||||
// (or skipping verification) is the only way to reach it.
|
|
||||||
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
fmt.Fprint(w, `{"status":"ok"}`)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
if _, err := New(srv.URL, Options{}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
if _, err := c.Health(context.Background()); err == nil {
|
|
||||||
t.Fatal("self-signed certificate accepted without opting in")
|
|
||||||
}
|
|
||||||
|
|
||||||
c2, _ := New(srv.URL, Options{InsecureSkipVerify: true})
|
|
||||||
if _, err := c2.Health(context.Background()); err != nil {
|
|
||||||
t.Fatalf("insecure option did not work: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPartShellsHeaderAndGetMessage(t *testing.T) {
|
|
||||||
var gotHeader string
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/api/session/ses_1/message":
|
|
||||||
gotHeader = r.Header.Get("x-openchamber-part-shells")
|
|
||||||
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[
|
|
||||||
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{},"content":[],"metadata":{"openchamberContentShell":{}}}}]}],"cursor":{}}`)
|
|
||||||
case "/api/session/ses_1/message/msg_1":
|
|
||||||
fmt.Fprint(w, `{"id":"msg_1","type":"assistant","content":[
|
|
||||||
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{},"content":[{"type":"text","text":"full output"}]}}]}`)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected path %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 10, PartShells: true})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if gotHeader != "v1" {
|
|
||||||
t.Errorf("header = %q", gotHeader)
|
|
||||||
}
|
|
||||||
if len(page.Data) != 1 || len(page.Data[0].Content[0].State.Content) != 0 {
|
|
||||||
t.Fatalf("page = %+v", page)
|
|
||||||
}
|
|
||||||
msg, err := c.GetMessage(context.Background(), "ses_1", "msg_1", "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got := msg.Content[0].State.Content[0].Text; got != "full output" {
|
|
||||||
t.Fatalf("message = %+v", msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRevertEndpoints(t *testing.T) {
|
|
||||||
var staged map[string]any
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/api/session/ses_1/revert/stage":
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&staged)
|
|
||||||
fmt.Fprint(w, `{"data":{"messageID":"msg_1"}}`)
|
|
||||||
case "/api/session/ses_1/revert/commit":
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected path %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
if err := c.StageRevert(context.Background(), "ses_1", "", "msg_1"); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if staged["messageID"] != "msg_1" {
|
|
||||||
t.Errorf("staged = %v", staged)
|
|
||||||
}
|
|
||||||
if err := c.CommitRevert(context.Background(), "ses_1", ""); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,385 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
xproxy "golang.org/x/net/proxy"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Options configures a Client.
|
|
||||||
type Options struct {
|
|
||||||
// Proxy is an optional HTTP(S) or SOCKS5 proxy URL, e.g.
|
|
||||||
// "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080". No proxy
|
|
||||||
// authentication is supported.
|
|
||||||
Proxy string
|
|
||||||
// InsecureSkipVerify disables certificate verification. Prefer
|
|
||||||
// CertFingerprint for a self-signed server.
|
|
||||||
InsecureSkipVerify bool
|
|
||||||
// CertFingerprint pins the server's leaf certificate: the SHA-256 of
|
|
||||||
// its DER bytes, as hex, with or without colons.
|
|
||||||
CertFingerprint string
|
|
||||||
// Timeout bounds normal requests. Streaming requests ignore it.
|
|
||||||
Timeout time.Duration
|
|
||||||
// UserAgent is sent on every request.
|
|
||||||
UserAgent string
|
|
||||||
// HTTPClient replaces the constructed client (tests).
|
|
||||||
HTTPClient *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client talks to one OpenChamber server.
|
|
||||||
type Client struct {
|
|
||||||
base *url.URL
|
|
||||||
token string
|
|
||||||
http *http.Client
|
|
||||||
ua string
|
|
||||||
}
|
|
||||||
|
|
||||||
// New builds a client for base. A base without a scheme gets https, except
|
|
||||||
// for loopback and private addresses, which get http.
|
|
||||||
func New(base string, opts Options) (*Client, error) {
|
|
||||||
normalized, err := NormalizeBaseURL(base)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
u, err := url.Parse(normalized)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ocapi: invalid server URL: %w", err)
|
|
||||||
}
|
|
||||||
ua := opts.UserAgent
|
|
||||||
if ua == "" {
|
|
||||||
ua = "OpenChamber-Native/0.1"
|
|
||||||
}
|
|
||||||
hc := opts.HTTPClient
|
|
||||||
if hc == nil {
|
|
||||||
tr, err := newTransport(opts)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
timeout := opts.Timeout
|
|
||||||
if timeout <= 0 {
|
|
||||||
timeout = 30 * time.Second
|
|
||||||
}
|
|
||||||
hc = &http.Client{Transport: tr, Timeout: timeout}
|
|
||||||
}
|
|
||||||
return &Client{base: u, http: hc, ua: ua}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NormalizeBaseURL trims a user-entered server address, adds a scheme when
|
|
||||||
// missing, and drops trailing slashes.
|
|
||||||
func NormalizeBaseURL(raw string) (string, error) {
|
|
||||||
s := strings.TrimSpace(raw)
|
|
||||||
if s == "" {
|
|
||||||
return "", errors.New("ocapi: server URL is empty")
|
|
||||||
}
|
|
||||||
if !strings.Contains(s, "://") {
|
|
||||||
if isPrivateHost(s) {
|
|
||||||
s = "http://" + s
|
|
||||||
} else {
|
|
||||||
s = "https://" + s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
u, err := url.Parse(s)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("ocapi: invalid server URL: %w", err)
|
|
||||||
}
|
|
||||||
if u.Scheme != "http" && u.Scheme != "https" {
|
|
||||||
return "", fmt.Errorf("ocapi: unsupported scheme %q", u.Scheme)
|
|
||||||
}
|
|
||||||
if u.Host == "" {
|
|
||||||
return "", errors.New("ocapi: server URL has no host")
|
|
||||||
}
|
|
||||||
u.Path = strings.TrimRight(u.Path, "/")
|
|
||||||
return u.String(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPrivateHost(s string) bool {
|
|
||||||
host := s
|
|
||||||
if h, _, err := net.SplitHostPort(s); err == nil {
|
|
||||||
host = h
|
|
||||||
}
|
|
||||||
host = strings.Trim(host, "[]")
|
|
||||||
if host == "localhost" || strings.HasSuffix(host, ".local") {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
ip := net.ParseIP(host)
|
|
||||||
if ip == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTransport(opts Options) (*http.Transport, error) {
|
|
||||||
tr := &http.Transport{
|
|
||||||
// No overall dial timeout for streaming; normal requests carry a
|
|
||||||
// per-request deadline through context.
|
|
||||||
DialContext: (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
|
||||||
TLSHandshakeTimeout: 15 * time.Second,
|
|
||||||
IdleConnTimeout: 90 * time.Second,
|
|
||||||
ForceAttemptHTTP2: true,
|
|
||||||
}
|
|
||||||
if raw := strings.TrimSpace(opts.Proxy); raw != "" {
|
|
||||||
pu, err := url.Parse(raw)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ocapi: invalid proxy URL: %w", err)
|
|
||||||
}
|
|
||||||
switch pu.Scheme {
|
|
||||||
case "http", "https":
|
|
||||||
tr.Proxy = http.ProxyURL(pu)
|
|
||||||
case "socks5", "socks5h":
|
|
||||||
dialer, err := xproxy.SOCKS5("tcp", pu.Host, nil, xproxy.Direct)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ocapi: socks5 proxy: %w", err)
|
|
||||||
}
|
|
||||||
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
||||||
type ctxDialer interface {
|
|
||||||
DialContext(context.Context, string, string) (net.Conn, error)
|
|
||||||
}
|
|
||||||
if cd, ok := dialer.(ctxDialer); ok {
|
|
||||||
return cd.DialContext(ctx, network, addr)
|
|
||||||
}
|
|
||||||
return dialer.Dial(network, addr)
|
|
||||||
}
|
|
||||||
tr.Proxy = nil
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("ocapi: unsupported proxy scheme %q", pu.Scheme)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if opts.InsecureSkipVerify || opts.CertFingerprint != "" {
|
|
||||||
cfg := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: opts.InsecureSkipVerify}
|
|
||||||
if fp := normalizeFingerprint(opts.CertFingerprint); fp != "" {
|
|
||||||
cfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
|
|
||||||
if len(rawCerts) == 0 {
|
|
||||||
return errors.New("ocapi: server sent no certificate")
|
|
||||||
}
|
|
||||||
sum := sha256.Sum256(rawCerts[0])
|
|
||||||
if got := hex.EncodeToString(sum[:]); got != fp {
|
|
||||||
return fmt.Errorf("ocapi: certificate fingerprint mismatch: got %s", formatFingerprint(got))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tr.TLSClientConfig = cfg
|
|
||||||
}
|
|
||||||
return tr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizeFingerprint(s string) string {
|
|
||||||
clean := strings.ToLower(strings.NewReplacer(":", "", " ", "").Replace(strings.TrimSpace(s)))
|
|
||||||
if clean == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if _, err := hex.DecodeString(clean); err != nil || len(clean) != 64 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return clean
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatFingerprint(hexString string) string {
|
|
||||||
var b strings.Builder
|
|
||||||
for i := 0; i < len(hexString); i += 2 {
|
|
||||||
if i > 0 {
|
|
||||||
b.WriteByte(':')
|
|
||||||
}
|
|
||||||
b.WriteString(strings.ToUpper(hexString[i : i+2]))
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetToken sets the bearer token used for subsequent requests.
|
|
||||||
func (c *Client) SetToken(token string) { c.token = strings.TrimSpace(token) }
|
|
||||||
|
|
||||||
// Token returns the current bearer token.
|
|
||||||
func (c *Client) Token() string { return c.token }
|
|
||||||
|
|
||||||
// BaseURL returns the client's base URL.
|
|
||||||
func (c *Client) BaseURL() string { return c.base.String() }
|
|
||||||
|
|
||||||
// APIError is a non-2xx answer.
|
|
||||||
type APIError struct {
|
|
||||||
Status int
|
|
||||||
Message string
|
|
||||||
RetryAfter time.Duration
|
|
||||||
Locked bool
|
|
||||||
Raw string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *APIError) Error() string {
|
|
||||||
if e.Message != "" {
|
|
||||||
return fmt.Sprintf("ocapi: %s (HTTP %d)", e.Message, e.Status)
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("ocapi: HTTP %d", e.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsUnauthorized reports whether err is a 401 (token expired or wrong).
|
|
||||||
func IsUnauthorized(err error) bool {
|
|
||||||
var apiErr *APIError
|
|
||||||
return errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsRateLimited reports whether err is a 429, and how long to wait.
|
|
||||||
func IsRateLimited(err error) (time.Duration, bool) {
|
|
||||||
var apiErr *APIError
|
|
||||||
if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests {
|
|
||||||
return apiErr.RetryAfter, true
|
|
||||||
}
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
|
|
||||||
type requestOptions struct {
|
|
||||||
directory string
|
|
||||||
query url.Values
|
|
||||||
rawQuery bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) buildURL(path string, ro requestOptions) string {
|
|
||||||
u := *c.base
|
|
||||||
u.Path = strings.TrimRight(u.Path, "/") + "/" + strings.TrimLeft(path, "/")
|
|
||||||
q := u.Query()
|
|
||||||
for k, vs := range ro.query {
|
|
||||||
for _, v := range vs {
|
|
||||||
q.Add(k, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
u.RawQuery = q.Encode()
|
|
||||||
return u.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) newRequest(ctx context.Context, method, path string, ro requestOptions, body any) (*http.Request, error) {
|
|
||||||
var rdr io.Reader
|
|
||||||
if body != nil {
|
|
||||||
buf, err := json.Marshal(body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
rdr = strings.NewReader(string(buf))
|
|
||||||
}
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, c.buildURL(path, ro), rdr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
req.Header.Set("Accept", "application/json")
|
|
||||||
req.Header.Set("User-Agent", c.ua)
|
|
||||||
if body != nil {
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
}
|
|
||||||
if c.token != "" {
|
|
||||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
|
||||||
}
|
|
||||||
if ro.directory != "" {
|
|
||||||
req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory))
|
|
||||||
req.Header.Set("x-opencode-directory-encoding", "uri")
|
|
||||||
}
|
|
||||||
return req, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) do(ctx context.Context, method, path string, ro requestOptions, body, out any) error {
|
|
||||||
req, err := c.newRequest(ctx, method, path, ro, body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return c.send(req, out)
|
|
||||||
}
|
|
||||||
|
|
||||||
// send performs an already-built request and decodes it.
|
|
||||||
func (c *Client) send(req *http.Request, out any) error {
|
|
||||||
res, err := c.http.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer res.Body.Close()
|
|
||||||
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
|
||||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16))
|
|
||||||
apiErr := &APIError{Status: res.StatusCode, Raw: string(raw)}
|
|
||||||
var payload struct {
|
|
||||||
Error string `json:"error"`
|
|
||||||
Locked bool `json:"locked"`
|
|
||||||
RetryAfter json.RawMessage `json:"retryAfter"`
|
|
||||||
}
|
|
||||||
if json.Unmarshal(raw, &payload) == nil {
|
|
||||||
apiErr.Message = payload.Error
|
|
||||||
apiErr.Locked = payload.Locked
|
|
||||||
apiErr.RetryAfter = parseRetryAfter(payload.RetryAfter, res.Header.Get("Retry-After"))
|
|
||||||
}
|
|
||||||
return apiErr
|
|
||||||
}
|
|
||||||
if out == nil || res.StatusCode == http.StatusNoContent {
|
|
||||||
_, _ = io.Copy(io.Discard, res.Body)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
dec := json.NewDecoder(io.LimitReader(res.Body, 64<<20))
|
|
||||||
if err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {
|
|
||||||
return fmt.Errorf("ocapi: decode response: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseRetryAfter(raw json.RawMessage, header string) time.Duration {
|
|
||||||
if len(raw) > 0 {
|
|
||||||
var secs float64
|
|
||||||
if json.Unmarshal(raw, &secs) == nil && secs > 0 {
|
|
||||||
return time.Duration(secs * float64(time.Second))
|
|
||||||
}
|
|
||||||
var text string
|
|
||||||
if json.Unmarshal(raw, &text) == nil {
|
|
||||||
if n, err := strconv.Atoi(strings.TrimSpace(text)); err == nil && n > 0 {
|
|
||||||
return time.Duration(n) * time.Second
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if n, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && n > 0 {
|
|
||||||
return time.Duration(n) * time.Second
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Health reads the server's unauthenticated health document.
|
|
||||||
func (c *Client) Health(ctx context.Context) (Health, error) {
|
|
||||||
var h Health
|
|
||||||
err := c.do(ctx, http.MethodGet, "/health", requestOptions{}, nil, &h)
|
|
||||||
return h, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionStatus probes /auth/session.
|
|
||||||
func (c *Client) SessionStatus(ctx context.Context) (AuthStatus, error) {
|
|
||||||
var s AuthStatus
|
|
||||||
err := c.do(ctx, http.MethodGet, "/auth/session", requestOptions{}, nil, &s)
|
|
||||||
return s, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login exchanges the UI password for a device client token and stores it.
|
|
||||||
func (c *Client) Login(ctx context.Context, req LoginRequest) (LoginResult, error) {
|
|
||||||
if !req.TrustDevice {
|
|
||||||
req.TrustDevice = true
|
|
||||||
}
|
|
||||||
if !req.IssueClientToken {
|
|
||||||
req.IssueClientToken = true
|
|
||||||
}
|
|
||||||
if req.ClientKind == "" {
|
|
||||||
req.ClientKind = "mobile"
|
|
||||||
}
|
|
||||||
if req.ClientLabel == "" {
|
|
||||||
req.ClientLabel = "OpenChamber Native"
|
|
||||||
}
|
|
||||||
var out LoginResult
|
|
||||||
if err := c.do(ctx, http.MethodPost, "/auth/session", requestOptions{}, req, &out); err != nil {
|
|
||||||
return LoginResult{}, err
|
|
||||||
}
|
|
||||||
if out.ClientToken != "" {
|
|
||||||
c.SetToken(out.ClientToken)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
@@ -1,309 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNormalizeBaseURL(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
in, want string
|
|
||||||
}{
|
|
||||||
{"127.0.0.1:3000", "http://127.0.0.1:3000"},
|
|
||||||
{"192.168.1.5:3000/", "http://192.168.1.5:3000"},
|
|
||||||
{"http://host:3000/", "http://host:3000"},
|
|
||||||
{"https://oc.example.com", "https://oc.example.com"},
|
|
||||||
{"oc.example.com", "https://oc.example.com"},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
got, err := NormalizeBaseURL(c.in)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NormalizeBaseURL(%q): %v", c.in, err)
|
|
||||||
}
|
|
||||||
if got != c.want {
|
|
||||||
t.Errorf("NormalizeBaseURL(%q) = %q, want %q", c.in, got, c.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, err := NormalizeBaseURL(" "); err == nil {
|
|
||||||
t.Error("empty URL accepted")
|
|
||||||
}
|
|
||||||
if _, err := NormalizeBaseURL("ftp://host"); err == nil {
|
|
||||||
t.Error("ftp scheme accepted")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHealth(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.URL.Path != "/health" {
|
|
||||||
t.Errorf("path = %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","serverId":"abc","isOpenCodeReady":true}`)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, err := New(srv.URL, Options{})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
h, err := c.Health(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if h.OpenChamberVersion != "2.7.0" || h.ServerID != "abc" || !h.IsOpenCodeReady {
|
|
||||||
t.Fatalf("unexpected health: %+v", h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSessionStatusAndLogin(t *testing.T) {
|
|
||||||
var loginBody map[string]any
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/auth/session":
|
|
||||||
if r.Method == http.MethodGet {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&loginBody); err != nil {
|
|
||||||
t.Errorf("login body: %v", err)
|
|
||||||
}
|
|
||||||
fmt.Fprint(w, `{"authenticated":true,"clientToken":"oc_client_test"}`)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected path %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
_, err := c.SessionStatus(context.Background())
|
|
||||||
if !IsUnauthorized(err) {
|
|
||||||
t.Fatalf("want 401, got %v", err)
|
|
||||||
}
|
|
||||||
res, err := c.Login(context.Background(), LoginRequest{Password: "pw", DedupeKey: "install-1"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if res.ClientToken != "oc_client_test" || c.Token() != "oc_client_test" {
|
|
||||||
t.Fatalf("token not stored: %+v, %q", res, c.Token())
|
|
||||||
}
|
|
||||||
if loginBody["trustDevice"] != true || loginBody["issueClientToken"] != true {
|
|
||||||
t.Errorf("login defaults missing: %v", loginBody)
|
|
||||||
}
|
|
||||||
if loginBody["clientKind"] != "mobile" || loginBody["password"] != "pw" {
|
|
||||||
t.Errorf("login body: %v", loginBody)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestListSessionsScoped(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.URL.Path != "/api/session" {
|
|
||||||
t.Errorf("path = %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
if got := r.URL.Query().Get("directory"); got != "/home/me/proj" {
|
|
||||||
t.Errorf("directory query = %q", got)
|
|
||||||
}
|
|
||||||
if got := r.Header.Get("x-opencode-directory"); got != "%2Fhome%2Fme%2Fproj" {
|
|
||||||
t.Errorf("directory header = %q", got)
|
|
||||||
}
|
|
||||||
if got := r.Header.Get("x-opencode-directory-encoding"); got != "uri" {
|
|
||||||
t.Errorf("directory encoding = %q", got)
|
|
||||||
}
|
|
||||||
if got := r.URL.Query().Get("limit"); got != "50" {
|
|
||||||
t.Errorf("limit = %q", got)
|
|
||||||
}
|
|
||||||
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"Hi","time":{"created":1,"updated":2},"location":{"directory":"/home/me/proj"}}],"cursor":{"next":"n1"}}`)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
page, err := c.ListSessions(context.Background(), ListSessionsOptions{Directory: "/home/me/proj", Limit: 50})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(page.Data) != 1 || page.Data[0].ID != "ses_1" || page.Cursor.Next != "n1" {
|
|
||||||
t.Fatalf("unexpected page: %+v", page)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMessagesAndTurn(t *testing.T) {
|
|
||||||
var promptBody map[string]any
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/api/session/ses_1/message":
|
|
||||||
if got := r.URL.Query().Get("order"); got != "desc" {
|
|
||||||
t.Errorf("order = %q", got)
|
|
||||||
}
|
|
||||||
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[{"type":"text","text":"hello"}]}],"cursor":{"next":"m1"}}`)
|
|
||||||
case "/api/session/ses_1/prompt":
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&promptBody)
|
|
||||||
fmt.Fprint(w, `{"data":{}}`)
|
|
||||||
case "/api/session/ses_1/interrupt":
|
|
||||||
fmt.Fprint(w, `{"interrupted":true}`)
|
|
||||||
default:
|
|
||||||
t.Errorf("unexpected path %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 20, Order: "desc"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" {
|
|
||||||
t.Fatalf("unexpected messages: %+v", page)
|
|
||||||
}
|
|
||||||
if err := c.Prompt(context.Background(), "ses_1", PromptOptions{
|
|
||||||
Text: "ping", MessageID: "msg_9",
|
|
||||||
Files: []PromptFile{{URI: "data:text/plain;base64,aGk=", Name: "note.txt"}},
|
|
||||||
}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
|
|
||||||
t.Errorf("prompt body: %v", promptBody)
|
|
||||||
}
|
|
||||||
files, _ := promptBody["files"].([]any)
|
|
||||||
if len(files) != 1 {
|
|
||||||
t.Fatalf("prompt files: %v", promptBody["files"])
|
|
||||||
}
|
|
||||||
file, _ := files[0].(map[string]any)
|
|
||||||
if file["name"] != "note.txt" || file["uri"] != "data:text/plain;base64,aGk=" {
|
|
||||||
t.Errorf("prompt file: %v", file)
|
|
||||||
}
|
|
||||||
ok, err := c.Interrupt(context.Background(), "ses_1", "")
|
|
||||||
if err != nil || !ok {
|
|
||||||
t.Fatalf("interrupt: %v %v", ok, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRateLimit(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusTooManyRequests)
|
|
||||||
fmt.Fprint(w, `{"error":"Too many login attempts, please try again later","retryAfter":12}`)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
_, err := c.Login(context.Background(), LoginRequest{Password: "x"})
|
|
||||||
wait, ok := IsRateLimited(err)
|
|
||||||
if !ok || wait != 12*time.Second {
|
|
||||||
t.Fatalf("rate limit: %v %v", wait, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStreamEvents(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if got := r.URL.Query()["types"]; len(got) != 2 {
|
|
||||||
t.Errorf("types = %v", got)
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "text/event-stream")
|
|
||||||
flusher := w.(http.Flusher)
|
|
||||||
// Split an event across writes and use two data lines, which
|
|
||||||
// SSE joins with a newline.
|
|
||||||
fmt.Fprint(w, "event: message\n")
|
|
||||||
flusher.Flush()
|
|
||||||
fmt.Fprint(w, "data: {\"id\":\"evt_1\",")
|
|
||||||
flusher.Flush()
|
|
||||||
fmt.Fprint(w, "\"type\":\"session.text.delta\",")
|
|
||||||
flusher.Flush()
|
|
||||||
fmt.Fprint(w, "\"data\":{\"delta\":\"hi\"}}\n\n")
|
|
||||||
flusher.Flush()
|
|
||||||
<-r.Context().Done()
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
defer cancel()
|
|
||||||
got := make(chan Event, 1)
|
|
||||||
go func() {
|
|
||||||
_ = c.StreamEvents(ctx, []string{"session.text.delta", "permission.asked"}, func(ev Event) error {
|
|
||||||
got <- ev
|
|
||||||
cancel()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
select {
|
|
||||||
case ev := <-got:
|
|
||||||
if ev.ID != "evt_1" || ev.Type != "session.text.delta" {
|
|
||||||
t.Fatalf("event: %+v", ev)
|
|
||||||
}
|
|
||||||
var data SessionEventData
|
|
||||||
if err := ev.UnmarshalData(&data); err != nil || data.Delta != "hi" {
|
|
||||||
t.Fatalf("data: %+v %v", data, err)
|
|
||||||
}
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("timed out waiting for an event")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProxyDialer(t *testing.T) {
|
|
||||||
// A SOCKS5 address is accepted; the connection itself is not made.
|
|
||||||
c, err := New("http://127.0.0.1:3000", Options{Proxy: "socks5://127.0.0.1:1080"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if c.http.Transport == nil {
|
|
||||||
t.Fatal("no transport")
|
|
||||||
}
|
|
||||||
if _, err := New("http://127.0.0.1:3000", Options{Proxy: "ftp://x"}); err == nil {
|
|
||||||
t.Fatal("unsupported proxy scheme accepted")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDecodeMessageContent(t *testing.T) {
|
|
||||||
body := `{"data":[{"id":"msg_1","type":"assistant","content":[
|
|
||||||
{"type":"reasoning","text":"think"},
|
|
||||||
{"type":"text","text":"answer"},
|
|
||||||
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"a.txt"}]}}]}]}`
|
|
||||||
var page MessagePage
|
|
||||||
if err := json.Unmarshal([]byte(body), &page); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
m := page.Data[0]
|
|
||||||
if len(m.Content) != 3 || m.Content[2].State == nil || m.Content[2].State.Status != "completed" {
|
|
||||||
t.Fatalf("content: %+v", m.Content)
|
|
||||||
}
|
|
||||||
if m.Content[2].State.Input["command"] != "ls" {
|
|
||||||
t.Fatalf("input: %+v", m.Content[2].State.Input)
|
|
||||||
}
|
|
||||||
if m.Content[2].State.Content[0].Text != "a.txt" {
|
|
||||||
t.Fatalf("tool content: %+v", m.Content[2].State.Content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestErrorBodyKept(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
_, _ = io.WriteString(w, `{"error":"bad thing"}`)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
err := c.DeleteSession(context.Background(), "ses_x", "")
|
|
||||||
var apiErr *APIError
|
|
||||||
if !strings.Contains(err.Error(), "bad thing") || !asAPIError(err, &apiErr) || apiErr.Status != 400 {
|
|
||||||
t.Fatalf("error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func asAPIError(err error, target **APIError) bool {
|
|
||||||
for err != nil {
|
|
||||||
if e, ok := err.(*APIError); ok {
|
|
||||||
*target = e
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
u, ok := err.(interface{ Unwrap() error })
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
err = u.Unwrap()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,180 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// StreamEvents subscribes to GET /api/event and calls fn for each event
|
|
||||||
// until ctx is done or the connection fails. types filters the event
|
|
||||||
// types; nil means every type.
|
|
||||||
func (c *Client) StreamEvents(ctx context.Context, types []string, fn func(Event) error) error {
|
|
||||||
return c.streamEvents(ctx, types, nil, fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) streamEvents(ctx context.Context, types []string, onOpen func(), fn func(Event) error) error {
|
|
||||||
q := url.Values{}
|
|
||||||
for _, t := range types {
|
|
||||||
q.Add("types", t)
|
|
||||||
}
|
|
||||||
req, err := c.newRequest(ctx, http.MethodGet, "/api/event", requestOptions{query: q}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
req.Header.Set("Accept", "text/event-stream")
|
|
||||||
req.Header.Set("Cache-Control", "no-cache")
|
|
||||||
|
|
||||||
// A streaming request must not inherit the client's overall timeout.
|
|
||||||
hc := *c.http
|
|
||||||
hc.Timeout = 0
|
|
||||||
res, err := hc.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer res.Body.Close()
|
|
||||||
if res.StatusCode != http.StatusOK {
|
|
||||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
|
|
||||||
return &APIError{Status: res.StatusCode, Raw: string(raw), Message: strings.TrimSpace(string(raw))}
|
|
||||||
}
|
|
||||||
if onOpen != nil {
|
|
||||||
onOpen()
|
|
||||||
}
|
|
||||||
|
|
||||||
reader := bufio.NewReaderSize(res.Body, 64<<10)
|
|
||||||
var data []byte
|
|
||||||
for {
|
|
||||||
line, err := reader.ReadString('\n')
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, io.EOF) || ctx.Err() != nil {
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
line = strings.TrimRight(line, "\r\n")
|
|
||||||
if line == "" {
|
|
||||||
if len(data) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var ev Event
|
|
||||||
parseErr := json.Unmarshal(data, &ev)
|
|
||||||
data = data[:0]
|
|
||||||
if parseErr != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err := fn(ev); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(line, "data:") {
|
|
||||||
chunk := strings.TrimPrefix(line, "data:")
|
|
||||||
chunk = strings.TrimPrefix(chunk, " ")
|
|
||||||
if len(data) > 0 {
|
|
||||||
data = append(data, '\n')
|
|
||||||
}
|
|
||||||
data = append(data, chunk...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SubscriptionState reports the event stream's connection state.
|
|
||||||
type SubscriptionState int
|
|
||||||
|
|
||||||
const (
|
|
||||||
Subscribing SubscriptionState = iota
|
|
||||||
Subscribed
|
|
||||||
Disconnected
|
|
||||||
)
|
|
||||||
|
|
||||||
// Subscription is a resilient event stream.
|
|
||||||
type Subscription struct {
|
|
||||||
Types []string
|
|
||||||
OnEvent func(Event)
|
|
||||||
OnState func(SubscriptionState, error)
|
|
||||||
// MinBackoff and MaxBackoff bound the reconnect delay.
|
|
||||||
MinBackoff time.Duration
|
|
||||||
MaxBackoff time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// Subscribe keeps an event stream open until ctx is done, reconnecting with
|
|
||||||
// exponential backoff. It blocks, so run it in a goroutine.
|
|
||||||
func (c *Client) Subscribe(ctx context.Context, s Subscription) {
|
|
||||||
minB, maxB := s.MinBackoff, s.MaxBackoff
|
|
||||||
if minB <= 0 {
|
|
||||||
minB = time.Second
|
|
||||||
}
|
|
||||||
if maxB <= 0 {
|
|
||||||
maxB = 30 * time.Second
|
|
||||||
}
|
|
||||||
state := func(st SubscriptionState, err error) {
|
|
||||||
if s.OnState != nil {
|
|
||||||
s.OnState(st, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
backoff := minB
|
|
||||||
for ctx.Err() == nil {
|
|
||||||
state(Subscribing, nil)
|
|
||||||
started := time.Now()
|
|
||||||
err := c.streamEvents(ctx, s.Types, func() {
|
|
||||||
state(Subscribed, nil)
|
|
||||||
}, func(ev Event) error {
|
|
||||||
if s.OnEvent != nil {
|
|
||||||
s.OnEvent(ev)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
state(Disconnected, err)
|
|
||||||
// A stream that stayed up for a while restarts at the minimum
|
|
||||||
// delay; a failing one backs off.
|
|
||||||
if time.Since(started) > 30*time.Second {
|
|
||||||
backoff = minB
|
|
||||||
}
|
|
||||||
delay := backoff/2 + time.Duration(rand.Int63n(int64(backoff/2+1)))
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-time.After(delay):
|
|
||||||
}
|
|
||||||
if backoff < maxB {
|
|
||||||
backoff *= 2
|
|
||||||
if backoff > maxB {
|
|
||||||
backoff = maxB
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WaitReady polls /api/opencode/health until OpenCode is ready or ctx ends.
|
|
||||||
func (c *Client) WaitReady(ctx context.Context, wait time.Duration) error {
|
|
||||||
if wait <= 0 {
|
|
||||||
wait = 20 * time.Second
|
|
||||||
}
|
|
||||||
q := url.Values{}
|
|
||||||
q.Set("wait", fmt.Sprint(wait.Milliseconds()))
|
|
||||||
var payload struct {
|
|
||||||
Healthy bool `json:"healthy"`
|
|
||||||
Error string `json:"error"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/opencode/health", requestOptions{query: q}, nil, &payload); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if !payload.Healthy {
|
|
||||||
if payload.Error != "" {
|
|
||||||
return fmt.Errorf("ocapi: opencode not ready: %s", payload.Error)
|
|
||||||
}
|
|
||||||
return errors.New("ocapi: opencode not ready")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RawFile reads a file the server can see, for previews. content is the
|
|
||||||
// server's Content-Type; the body is bounded to 32 MiB. Paths outside the
|
|
||||||
// session's workspace are allowed: the tool call already read the file, and
|
|
||||||
// the preview shows the same one.
|
|
||||||
func (c *Client) RawFile(ctx context.Context, path, directory string) ([]byte, string, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
q.Set("path", path)
|
|
||||||
q.Set("allowOutsideWorkspace", "true")
|
|
||||||
req, err := c.newRequest(ctx, http.MethodGet, "/api/fs/raw", requestOptions{directory: directory, query: q}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
hc := *c.http
|
|
||||||
hc.Timeout = 0
|
|
||||||
res, err := hc.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
defer res.Body.Close()
|
|
||||||
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
|
||||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
|
|
||||||
return nil, "", &APIError{Status: res.StatusCode, Raw: string(raw), Message: fmt.Sprintf("HTTP %d", res.StatusCode)}
|
|
||||||
}
|
|
||||||
data, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
|
||||||
if err != nil {
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
return data, res.Header.Get("Content-Type"), nil
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"net/url"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRawFile(t *testing.T) {
|
|
||||||
var gotPath, gotDir string
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.URL.Path != "/api/fs/raw" {
|
|
||||||
t.Errorf("path = %q", r.URL.Path)
|
|
||||||
}
|
|
||||||
if got := r.Header.Get("x-opencode-directory-encoding"); got != "uri" {
|
|
||||||
t.Errorf("directory encoding = %q", got)
|
|
||||||
}
|
|
||||||
gotPath = r.URL.Query().Get("path")
|
|
||||||
if got := r.URL.Query().Get("allowOutsideWorkspace"); got != "true" {
|
|
||||||
t.Errorf("allowOutsideWorkspace = %q", got)
|
|
||||||
}
|
|
||||||
gotDir, _ = url.PathUnescape(r.Header.Get("x-opencode-directory"))
|
|
||||||
w.Header().Set("Content-Type", "image/png")
|
|
||||||
fmt.Fprint(w, "PNGDATA")
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
c, err := New(srv.URL, Options{})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
data, mime, err := c.RawFile(context.Background(), "/work/a.png", "/work")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if string(data) != "PNGDATA" {
|
|
||||||
t.Errorf("data = %q", data)
|
|
||||||
}
|
|
||||||
if mime != "image/png" {
|
|
||||||
t.Errorf("mime = %q", mime)
|
|
||||||
}
|
|
||||||
if gotPath != "/work/a.png" {
|
|
||||||
t.Errorf("query path = %q", gotPath)
|
|
||||||
}
|
|
||||||
if gotDir != "/work" {
|
|
||||||
t.Errorf("directory = %q", gotDir)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRawFileError(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
http.Error(w, "nope", http.StatusNotFound)
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
c, _ := New(srv.URL, Options{})
|
|
||||||
if _, _, err := c.RawFile(context.Background(), "/work/missing.png", ""); err == nil {
|
|
||||||
t.Fatal("expected an error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,316 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ListSessionsOptions configures ListSessions.
|
|
||||||
type ListSessionsOptions struct {
|
|
||||||
// Directory scopes the list to one absolute path. Empty means all
|
|
||||||
// projects (each Session carries its own Location).
|
|
||||||
Directory string
|
|
||||||
Limit int
|
|
||||||
Cursor string
|
|
||||||
Order string // "asc" or "desc"
|
|
||||||
Search string
|
|
||||||
ParentID string
|
|
||||||
Archived *bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListSessions lists sessions, newest first by default.
|
|
||||||
func (c *Client) ListSessions(ctx context.Context, o ListSessionsOptions) (SessionPage, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
if o.Limit > 0 {
|
|
||||||
q.Set("limit", strconv.Itoa(o.Limit))
|
|
||||||
}
|
|
||||||
if o.Directory != "" {
|
|
||||||
q.Set("directory", o.Directory)
|
|
||||||
}
|
|
||||||
if o.Cursor != "" {
|
|
||||||
q.Set("cursor", o.Cursor)
|
|
||||||
}
|
|
||||||
if o.Order != "" {
|
|
||||||
q.Set("order", o.Order)
|
|
||||||
}
|
|
||||||
if o.Search != "" {
|
|
||||||
q.Set("search", o.Search)
|
|
||||||
}
|
|
||||||
if o.ParentID != "" {
|
|
||||||
q.Set("parentID", o.ParentID)
|
|
||||||
}
|
|
||||||
if o.Archived != nil {
|
|
||||||
q.Set("archived", strconv.FormatBool(*o.Archived))
|
|
||||||
}
|
|
||||||
var page SessionPage
|
|
||||||
err := c.do(ctx, http.MethodGet, "/api/session", requestOptions{directory: o.Directory, query: q}, nil, &page)
|
|
||||||
return page, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ActiveSessions returns the sessions running right now, keyed by id.
|
|
||||||
func (c *Client) ActiveSessions(ctx context.Context) (map[string]string, error) {
|
|
||||||
var payload struct {
|
|
||||||
Data map[string]struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/session/active", requestOptions{}, nil, &payload); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
out := make(map[string]string, len(payload.Data))
|
|
||||||
for id, v := range payload.Data {
|
|
||||||
out[id] = v.Type
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSession reads one session.
|
|
||||||
func (c *Client) GetSession(ctx context.Context, id, directory string) (Session, error) {
|
|
||||||
var payload struct {
|
|
||||||
Data Session `json:"data"`
|
|
||||||
}
|
|
||||||
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, &payload)
|
|
||||||
return payload.Data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSessionOptions configures CreateSession.
|
|
||||||
type CreateSessionOptions struct {
|
|
||||||
Directory string
|
|
||||||
Title string
|
|
||||||
Agent string
|
|
||||||
Model *ModelRef
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSession makes a new session, optionally in a directory.
|
|
||||||
func (c *Client) CreateSession(ctx context.Context, o CreateSessionOptions) (Session, error) {
|
|
||||||
body := map[string]any{}
|
|
||||||
if o.Title != "" {
|
|
||||||
body["title"] = o.Title
|
|
||||||
}
|
|
||||||
if o.Agent != "" {
|
|
||||||
body["agent"] = o.Agent
|
|
||||||
}
|
|
||||||
if o.Model != nil {
|
|
||||||
body["model"] = o.Model
|
|
||||||
}
|
|
||||||
if o.Directory != "" {
|
|
||||||
body["location"] = map[string]string{"directory": o.Directory}
|
|
||||||
}
|
|
||||||
var payload struct {
|
|
||||||
Data Session `json:"data"`
|
|
||||||
}
|
|
||||||
err := c.do(ctx, http.MethodPost, "/api/session", requestOptions{directory: o.Directory}, body, &payload)
|
|
||||||
return payload.Data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionPatch is PATCH /api/session/{id}: both fields are optional.
|
|
||||||
type SessionPatch struct {
|
|
||||||
Title *string `json:"title,omitempty"`
|
|
||||||
Archived *bool `json:"archived,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateSession renames or archives one session.
|
|
||||||
func (c *Client) UpdateSession(ctx context.Context, id, directory string, patch SessionPatch) error {
|
|
||||||
return c.do(ctx, http.MethodPatch, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, patch, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteSession removes a session and its children.
|
|
||||||
func (c *Client) DeleteSession(ctx context.Context, id, directory string) error {
|
|
||||||
return c.do(ctx, http.MethodDelete, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListMessagesOptions configures ListMessages.
|
|
||||||
type ListMessagesOptions struct {
|
|
||||||
Directory string
|
|
||||||
Limit int
|
|
||||||
Cursor string
|
|
||||||
Order string // "asc" or "desc"
|
|
||||||
// PartShells asks OpenChamber to leave finished tool results out of the
|
|
||||||
// page, which is most of a long session's bytes. Fetch the message with
|
|
||||||
// GetMessage when a row expands.
|
|
||||||
PartShells bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListMessages reads one page of a session's messages. Newest first by
|
|
||||||
// default, which is what a chat pages backwards with.
|
|
||||||
func (c *Client) ListMessages(ctx context.Context, id string, o ListMessagesOptions) (MessagePage, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
if o.Limit > 0 {
|
|
||||||
q.Set("limit", strconv.Itoa(o.Limit))
|
|
||||||
}
|
|
||||||
if o.Cursor != "" {
|
|
||||||
q.Set("cursor", o.Cursor)
|
|
||||||
}
|
|
||||||
if o.Order != "" {
|
|
||||||
q.Set("order", o.Order)
|
|
||||||
}
|
|
||||||
req, err := c.newRequest(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
|
|
||||||
requestOptions{directory: o.Directory, query: q}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return MessagePage{}, err
|
|
||||||
}
|
|
||||||
if o.PartShells {
|
|
||||||
req.Header.Set("x-openchamber-part-shells", "v1")
|
|
||||||
}
|
|
||||||
var page MessagePage
|
|
||||||
if err := c.send(req, &page); err != nil {
|
|
||||||
return MessagePage{}, err
|
|
||||||
}
|
|
||||||
return page, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMessage reads one whole message, including tool results a shelled list
|
|
||||||
// page left out.
|
|
||||||
func (c *Client) GetMessage(ctx context.Context, sessionID, messageID, directory string) (Message, error) {
|
|
||||||
var msg Message
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/message/" + url.PathEscape(messageID)
|
|
||||||
err := c.do(ctx, http.MethodGet, path, requestOptions{directory: directory}, nil, &msg)
|
|
||||||
return msg, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ModelInfo is one model the server offers.
|
|
||||||
type ModelInfo struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
ProviderID string `json:"providerID"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Variant string `json:"variant"`
|
|
||||||
Limit struct {
|
|
||||||
Context int `json:"context"`
|
|
||||||
Output int `json:"output"`
|
|
||||||
} `json:"limit"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Models lists the models the server offers for a directory.
|
|
||||||
func (c *Client) Models(ctx context.Context, directory string) ([]ModelInfo, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
if directory != "" {
|
|
||||||
q.Set("location[directory]", directory)
|
|
||||||
}
|
|
||||||
var payload struct {
|
|
||||||
Data []ModelInfo `json:"data"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/model", requestOptions{query: q}, nil, &payload); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return payload.Data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProviderInfo is one provider the server offers, with its display name.
|
|
||||||
type ProviderInfo struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Providers lists the providers available for a directory.
|
|
||||||
func (c *Client) Providers(ctx context.Context, directory string) ([]ProviderInfo, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
if directory != "" {
|
|
||||||
q.Set("location[directory]", directory)
|
|
||||||
}
|
|
||||||
var payload struct {
|
|
||||||
Data []ProviderInfo `json:"data"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/provider", requestOptions{query: q}, nil, &payload); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return payload.Data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServerLocation is the server's default working directory.
|
|
||||||
type ServerLocation struct {
|
|
||||||
Directory string `json:"directory"`
|
|
||||||
ProjectID string `json:"projectID"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Location reads the server's default location, which a new session uses
|
|
||||||
// when the user does not pick one.
|
|
||||||
func (c *Client) Location(ctx context.Context) (ServerLocation, error) {
|
|
||||||
var payload struct {
|
|
||||||
Directory string `json:"directory"`
|
|
||||||
Project struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
} `json:"project"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/location", requestOptions{}, nil, &payload); err != nil {
|
|
||||||
return ServerLocation{}, err
|
|
||||||
}
|
|
||||||
return ServerLocation{Directory: payload.Directory, ProjectID: payload.Project.ID}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AgentInfo is one entry of GET /api/agent.
|
|
||||||
type AgentInfo struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
Mode string `json:"mode"`
|
|
||||||
Hidden bool `json:"hidden"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Agents lists the agents available for a directory.
|
|
||||||
func (c *Client) Agents(ctx context.Context, directory string) ([]AgentInfo, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
if directory != "" {
|
|
||||||
q.Set("location[directory]", directory)
|
|
||||||
}
|
|
||||||
var payload struct {
|
|
||||||
Data []AgentInfo `json:"data"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/agent", requestOptions{query: q}, nil, &payload); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return payload.Data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PermissionRequest is a pending tool permission.
|
|
||||||
type PermissionRequest struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
Action string `json:"action"`
|
|
||||||
Resources []string `json:"resources"`
|
|
||||||
Message string `json:"message,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PendingPermissions lists the pending permission requests for a directory.
|
|
||||||
func (c *Client) PendingPermissions(ctx context.Context, directory string) ([]PermissionRequest, error) {
|
|
||||||
q := url.Values{}
|
|
||||||
if directory != "" {
|
|
||||||
q.Set("location[directory]", directory)
|
|
||||||
}
|
|
||||||
var payload struct {
|
|
||||||
Data []PermissionRequest `json:"data"`
|
|
||||||
}
|
|
||||||
if err := c.do(ctx, http.MethodGet, "/api/permission/request", requestOptions{query: q}, nil, &payload); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return payload.Data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PermissionDecision is how a permission request is answered.
|
|
||||||
type PermissionDecision string
|
|
||||||
|
|
||||||
const (
|
|
||||||
PermissionOnce PermissionDecision = "once"
|
|
||||||
PermissionAlways PermissionDecision = "always"
|
|
||||||
PermissionReject PermissionDecision = "reject"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ReplyPermission answers a pending permission request.
|
|
||||||
func (c *Client) ReplyPermission(ctx context.Context, sessionID, requestID string, decision PermissionDecision, message string) error {
|
|
||||||
body := map[string]any{"decision": decision}
|
|
||||||
if message != "" {
|
|
||||||
body["message"] = message
|
|
||||||
}
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/permission/" + url.PathEscape(requestID) + "/reply"
|
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{}, body, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventData unmarshals an event's payload into v.
|
|
||||||
func (e Event) UnmarshalData(v any) error {
|
|
||||||
if len(e.Data) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return json.Unmarshal(e.Data, v)
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package ocapi
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PromptOptions configures Prompt.
|
|
||||||
type PromptOptions struct {
|
|
||||||
Directory string
|
|
||||||
// MessageID is an optional client-minted id (msg_…), which makes a
|
|
||||||
// retry after a lost response a no-op instead of a duplicate.
|
|
||||||
MessageID string
|
|
||||||
Text string
|
|
||||||
// Files ride with the prompt as data URLs (or URIs the server can
|
|
||||||
// read), as the web client sends them.
|
|
||||||
Files []PromptFile
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prompt sends a user message to a session. The reply arrives through the
|
|
||||||
// event stream, not this call.
|
|
||||||
func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) error {
|
|
||||||
body := map[string]any{"text": o.Text}
|
|
||||||
if o.MessageID != "" {
|
|
||||||
body["id"] = o.MessageID
|
|
||||||
}
|
|
||||||
if len(o.Files) > 0 {
|
|
||||||
body["files"] = o.Files
|
|
||||||
}
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
|
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StageRevert marks a reversible boundary at a message: everything after it
|
|
||||||
// can be dropped with CommitRevert.
|
|
||||||
func (c *Client) StageRevert(ctx context.Context, sessionID, directory, messageID string) error {
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/revert/stage"
|
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory},
|
|
||||||
map[string]any{"messageID": messageID}, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CommitRevert drops the messages a staged revert marked.
|
|
||||||
func (c *Client) CommitRevert(ctx context.Context, sessionID, directory string) error {
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/revert/commit"
|
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ForkSession copies the session's history before a message into a new
|
|
||||||
// session. An empty before copies the whole history.
|
|
||||||
func (c *Client) ForkSession(ctx context.Context, sessionID, directory, before string) (Session, error) {
|
|
||||||
body := map[string]any{}
|
|
||||||
if before != "" {
|
|
||||||
body["before"] = before
|
|
||||||
}
|
|
||||||
var payload struct {
|
|
||||||
Data Session `json:"data"`
|
|
||||||
}
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/fork"
|
|
||||||
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, body, &payload)
|
|
||||||
return payload.Data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Interrupt stops the turn the session is running.
|
|
||||||
func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) {
|
|
||||||
var payload struct {
|
|
||||||
Interrupted bool `json:"interrupted"`
|
|
||||||
}
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/interrupt"
|
|
||||||
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, &payload)
|
|
||||||
return payload.Interrupted, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SwitchModel changes the model later turns run on.
|
|
||||||
func (c *Client) SwitchModel(ctx context.Context, sessionID, directory string, model ModelRef) error {
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/model"
|
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"model": model}, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SwitchAgent changes the agent later turns run with.
|
|
||||||
func (c *Client) SwitchAgent(ctx context.Context, sessionID, directory, agent string) error {
|
|
||||||
path := "/api/session/" + url.PathEscape(sessionID) + "/agent"
|
|
||||||
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"agent": agent}, nil)
|
|
||||||
}
|
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
// Package ocapi is a small HTTP client for the OpenChamber server API
|
|
||||||
// (which proxies OpenCode v2 under /api/*). It has no UI dependencies, so
|
|
||||||
// it can be tested with httptest and reused by the CLI probe.
|
|
||||||
package ocapi
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
// Health is GET /health.
|
|
||||||
type Health struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Timestamp string `json:"timestamp"`
|
|
||||||
OpenChamberVersion string `json:"openchamberVersion"`
|
|
||||||
Runtime string `json:"runtime"`
|
|
||||||
ServerID string `json:"serverId"`
|
|
||||||
IsOpenCodeReady bool `json:"isOpenCodeReady"`
|
|
||||||
OpenCodePort int `json:"openCodePort"`
|
|
||||||
Compatibility struct {
|
|
||||||
APIVersion int `json:"apiVersion"`
|
|
||||||
MinClientAPIVersion int `json:"minClientApiVersion"`
|
|
||||||
Capabilities []string `json:"capabilities"`
|
|
||||||
} `json:"compatibility"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuthStatus is GET /auth/session.
|
|
||||||
type AuthStatus struct {
|
|
||||||
Authenticated bool `json:"authenticated"`
|
|
||||||
Disabled bool `json:"disabled"`
|
|
||||||
Locked bool `json:"locked"`
|
|
||||||
Scope string `json:"scope"`
|
|
||||||
ClientAuthRequired bool `json:"clientAuthRequired"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoginRequest is POST /auth/session. Password is the only secret; the rest
|
|
||||||
// names this device so repeated logins collapse into one server-side record.
|
|
||||||
type LoginRequest struct {
|
|
||||||
Password string `json:"password"`
|
|
||||||
TrustDevice bool `json:"trustDevice"`
|
|
||||||
IssueClientToken bool `json:"issueClientToken"`
|
|
||||||
ClientLabel string `json:"clientLabel,omitempty"`
|
|
||||||
ClientKind string `json:"clientKind,omitempty"`
|
|
||||||
DeviceName string `json:"deviceName,omitempty"`
|
|
||||||
DevicePlatform string `json:"devicePlatform,omitempty"`
|
|
||||||
DeviceModel string `json:"deviceModel,omitempty"`
|
|
||||||
AppVersion string `json:"appVersion,omitempty"`
|
|
||||||
DedupeKey string `json:"dedupeKey,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoginResult is the answer to POST /auth/session.
|
|
||||||
type LoginResult struct {
|
|
||||||
Authenticated bool `json:"authenticated"`
|
|
||||||
ClientToken string `json:"clientToken"`
|
|
||||||
Client json.RawMessage `json:"client"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ModelRef identifies a model as OpenCode names it.
|
|
||||||
type ModelRef struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
ProviderID string `json:"providerID"`
|
|
||||||
Variant string `json:"variant,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TokenUsage is a session's or message's token counters.
|
|
||||||
type TokenUsage struct {
|
|
||||||
Total int64 `json:"total,omitempty"`
|
|
||||||
Input int64 `json:"input"`
|
|
||||||
Output int64 `json:"output"`
|
|
||||||
Reasoning int64 `json:"reasoning"`
|
|
||||||
Cache struct {
|
|
||||||
Read int64 `json:"read"`
|
|
||||||
Write int64 `json:"write"`
|
|
||||||
} `json:"cache"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Location is where a session lives.
|
|
||||||
type Location struct {
|
|
||||||
Directory string `json:"directory"`
|
|
||||||
ProjectID string `json:"projectID"`
|
|
||||||
Subpath string `json:"subpath,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionTime carries the millisecond timestamps OpenCode reports.
|
|
||||||
type SessionTime struct {
|
|
||||||
Created int64 `json:"created"`
|
|
||||||
Updated int64 `json:"updated"`
|
|
||||||
Busy int64 `json:"busy,omitempty"`
|
|
||||||
Idle int64 `json:"idle,omitempty"`
|
|
||||||
Viewed int64 `json:"viewed,omitempty"`
|
|
||||||
Archived int64 `json:"archived,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Session is one entry of GET /api/session.
|
|
||||||
type Session struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
ParentID string `json:"parentID,omitempty"`
|
|
||||||
ProjectID string `json:"projectID"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Agent string `json:"agent,omitempty"`
|
|
||||||
Model *ModelRef `json:"model,omitempty"`
|
|
||||||
Cost float64 `json:"cost"`
|
|
||||||
Tokens *TokenUsage `json:"tokens,omitempty"`
|
|
||||||
Time SessionTime `json:"time"`
|
|
||||||
Location *Location `json:"location,omitempty"`
|
|
||||||
Metadata map[string]any `json:"metadata,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PageCursor is the opaque pagination cursor of session and message lists.
|
|
||||||
type PageCursor struct {
|
|
||||||
Next string `json:"next,omitempty"`
|
|
||||||
Previous string `json:"previous,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionPage is GET /api/session.
|
|
||||||
type SessionPage struct {
|
|
||||||
Data []Session `json:"data"`
|
|
||||||
Cursor PageCursor `json:"cursor"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Message is one entry of GET /api/session/{id}/message. The server's union
|
|
||||||
// is wide; fields the client does not need stay zero.
|
|
||||||
type Message struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Time MessageTime `json:"time"`
|
|
||||||
Agent string `json:"agent,omitempty"`
|
|
||||||
Model *ModelRef `json:"model,omitempty"`
|
|
||||||
Content []ContentPart `json:"content,omitempty"`
|
|
||||||
Text string `json:"text,omitempty"`
|
|
||||||
Files []FileAttachment `json:"files,omitempty"`
|
|
||||||
Finish string `json:"finish,omitempty"`
|
|
||||||
Cost float64 `json:"cost,omitempty"`
|
|
||||||
Tokens *TokenUsage `json:"tokens,omitempty"`
|
|
||||||
Error json.RawMessage `json:"error,omitempty"`
|
|
||||||
|
|
||||||
// Shell messages
|
|
||||||
Command string `json:"command,omitempty"`
|
|
||||||
Status string `json:"status,omitempty"`
|
|
||||||
Exit *int `json:"exit,omitempty"`
|
|
||||||
Output string `json:"output,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// MessageTime carries the millisecond timestamps of a message.
|
|
||||||
type MessageTime struct {
|
|
||||||
Created int64 `json:"created"`
|
|
||||||
Streamed int64 `json:"streamed,omitempty"`
|
|
||||||
Completed int64 `json:"completed,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ContentPart is a block of an assistant message.
|
|
||||||
type ContentPart struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
Text string `json:"text,omitempty"`
|
|
||||||
ID string `json:"id,omitempty"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
State *ToolState `json:"state,omitempty"`
|
|
||||||
Time *PartTime `json:"time,omitempty"`
|
|
||||||
MIME string `json:"mime,omitempty"`
|
|
||||||
URL string `json:"url,omitempty"`
|
|
||||||
URI string `json:"uri,omitempty"`
|
|
||||||
Filename string `json:"filename,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PartTime is when a reasoning/text block was written.
|
|
||||||
type PartTime struct {
|
|
||||||
Created int64 `json:"created,omitempty"`
|
|
||||||
Completed int64 `json:"completed,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToolState is a tool call's state machine.
|
|
||||||
type ToolState struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Input map[string]any `json:"input,omitempty"`
|
|
||||||
Content []ContentPart `json:"content,omitempty"`
|
|
||||||
Attachments []ContentPart `json:"attachments,omitempty"`
|
|
||||||
Metadata map[string]any `json:"metadata,omitempty"`
|
|
||||||
Error json.RawMessage `json:"error,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PromptFile is a file riding with a prompt: a data URL or a URI the
|
|
||||||
// server can read, and its name.
|
|
||||||
type PromptFile struct {
|
|
||||||
URI string `json:"uri"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// FileAttachment is a file attached to a user prompt.
|
|
||||||
type FileAttachment struct {
|
|
||||||
URI string `json:"uri"`
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
Description string `json:"description,omitempty"`
|
|
||||||
MIME string `json:"mime,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// MessagePage is GET /api/session/{id}/message.
|
|
||||||
type MessagePage struct {
|
|
||||||
Data []Message `json:"data"`
|
|
||||||
Cursor PageCursor `json:"cursor"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Event is one server-sent event of GET /api/event.
|
|
||||||
type Event struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Created int64 `json:"created"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Location *Location `json:"location,omitempty"`
|
|
||||||
Durable *EventDurable `json:"durable,omitempty"`
|
|
||||||
Data json.RawMessage `json:"data"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// EventDurable is the durable envelope some events carry.
|
|
||||||
type EventDurable struct {
|
|
||||||
AggregateID string `json:"aggregateID"`
|
|
||||||
Seq int64 `json:"seq"`
|
|
||||||
Version int `json:"version"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SessionEventData covers the payload fields this client reads. Use
|
|
||||||
// Event.UnmarshalData into a wider struct when more is needed.
|
|
||||||
type SessionEventData struct {
|
|
||||||
SessionID string `json:"sessionID"`
|
|
||||||
AssistantMessageID string `json:"assistantMessageID"`
|
|
||||||
Ordinal int `json:"ordinal"`
|
|
||||||
Delta string `json:"delta"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
MessageID string `json:"messageID"`
|
|
||||||
PartID string `json:"partID"`
|
|
||||||
Agent string `json:"agent"`
|
|
||||||
Model *ModelRef `json:"model"`
|
|
||||||
RequestID string `json:"requestID"`
|
|
||||||
Reply string `json:"reply"`
|
|
||||||
Action string `json:"action"`
|
|
||||||
Resources []string `json:"resources"`
|
|
||||||
}
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
// Package storage keeps saved servers in the app's data directory and
|
|
||||||
// their device tokens in the platform's secure storage.
|
|
||||||
package storage
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sort"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Connection is one saved server.
|
|
||||||
type Connection struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
URL string `json:"url"`
|
|
||||||
Proxy string `json:"proxy,omitempty"`
|
|
||||||
Insecure bool `json:"insecure,omitempty"`
|
|
||||||
Fingerprint string `json:"fingerprint,omitempty"`
|
|
||||||
ServerID string `json:"serverId,omitempty"`
|
|
||||||
Passwordless bool `json:"passwordless,omitempty"`
|
|
||||||
LastUsedAt int64 `json:"lastUsedAt,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store is the persistence the UI needs. Tests use a memory store.
|
|
||||||
type Store interface {
|
|
||||||
Connections() []Connection
|
|
||||||
SaveConnections([]Connection)
|
|
||||||
InstallID() string
|
|
||||||
LoadToken(c Connection) (string, bool, error)
|
|
||||||
SaveToken(id, token string) error
|
|
||||||
ClearToken(c Connection) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Persistent is the app's store: servers in connections.json, tokens in
|
|
||||||
// the platform's secure store (the Android Keystore / iOS Keychain).
|
|
||||||
type Persistent struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
path string
|
|
||||||
conns []Connection
|
|
||||||
installID string
|
|
||||||
}
|
|
||||||
|
|
||||||
// New makes the persistent store. It reads the servers file once; call it
|
|
||||||
// on startup, before any window shows.
|
|
||||||
func New() *Persistent {
|
|
||||||
p := &Persistent{}
|
|
||||||
dir, err := mygo.App.Path(mygo.PathUserData)
|
|
||||||
if err == nil {
|
|
||||||
p.path = filepath.Join(dir, "connections.json")
|
|
||||||
}
|
|
||||||
p.load()
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) load() {
|
|
||||||
if p.path == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data, err := os.ReadFile(p.path)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var list []Connection
|
|
||||||
if json.Unmarshal(data, &list) == nil {
|
|
||||||
p.conns = list
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) save() {
|
|
||||||
if p.path == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(filepath.Dir(p.path), 0o700); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data, _ := json.Marshal(p.conns)
|
|
||||||
_ = os.WriteFile(p.path, data, 0o600)
|
|
||||||
}
|
|
||||||
|
|
||||||
// migrateLegacy is gone: the earlier Asuka builds kept their data in
|
|
||||||
// Asuka's own stores, which this app cannot read.
|
|
||||||
|
|
||||||
func (p *Persistent) Connections() []Connection {
|
|
||||||
p.mu.Lock()
|
|
||||||
defer p.mu.Unlock()
|
|
||||||
out := make([]Connection, len(p.conns))
|
|
||||||
copy(out, p.conns)
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) SaveConnections(list []Connection) {
|
|
||||||
sort.SliceStable(list, func(i, j int) bool { return list[i].LastUsedAt > list[j].LastUsedAt })
|
|
||||||
p.mu.Lock()
|
|
||||||
p.conns = list
|
|
||||||
p.mu.Unlock()
|
|
||||||
p.save()
|
|
||||||
}
|
|
||||||
|
|
||||||
// InstallID is a stable random id for this installation. It names the
|
|
||||||
// device when logging in, so repeated logins reuse one device record.
|
|
||||||
func (p *Persistent) InstallID() string {
|
|
||||||
p.mu.Lock()
|
|
||||||
defer p.mu.Unlock()
|
|
||||||
if p.installID != "" {
|
|
||||||
return p.installID
|
|
||||||
}
|
|
||||||
p.installID = NewID()
|
|
||||||
return p.installID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) tokenKey(id string) string {
|
|
||||||
sum := sha256.Sum256([]byte(id))
|
|
||||||
return "openchamber.token." + hex.EncodeToString(sum[:12])
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) LoadToken(c Connection) (string, bool, error) {
|
|
||||||
tok, err := mygo.Secrets.Get(p.tokenKey(c.ID))
|
|
||||||
if errors.Is(err, mygo.ErrSecretNotFound) {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return "", false, err
|
|
||||||
}
|
|
||||||
return string(tok), true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) SaveToken(id, token string) error {
|
|
||||||
return mygo.Secrets.Set(p.tokenKey(id), []byte(token))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Persistent) ClearToken(c Connection) error {
|
|
||||||
return mygo.Secrets.Delete(p.tokenKey(c.ID))
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewID() string {
|
|
||||||
var b [8]byte
|
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
|
||||||
return "srv_" + hex.EncodeToString(b[:4])
|
|
||||||
}
|
|
||||||
return "srv_" + hex.EncodeToString(b[:])
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"mobile": {
|
|
||||||
"id": "tts",
|
|
||||||
"android": {
|
|
||||||
"sources": ["android/*.kt"],
|
|
||||||
"class": "TTSPlugin"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
// Package tts speaks text aloud with the system's speech synthesizer, on
|
|
||||||
// phones. It is a thin Go binding over a small Android TextToSpeech plugin.
|
|
||||||
package tts
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/egoist/mygo"
|
|
||||||
)
|
|
||||||
|
|
||||||
const pluginID = "tts"
|
|
||||||
|
|
||||||
// Speak reads text aloud, stopping any speech in progress. On desktops it
|
|
||||||
// reports errors.ErrUnsupported.
|
|
||||||
func Speak(ctx context.Context, text string) error {
|
|
||||||
return mygo.Native(pluginID).Call(ctx, "speak", map[string]string{"text": text}, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop stops any speech in progress.
|
|
||||||
func Stop() error {
|
|
||||||
return mygo.Native(pluginID).Call(context.Background(), "stop", nil, nil)
|
|
||||||
}
|
|
||||||